casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
conjugatevis_cli.py
Go to the documentation of this file.
00001 #
00002 # This file was generated using xslt from its XML file
00003 #
00004 # Copyright 2008, Associated Universities Inc., Washington DC
00005 #
00006 import sys
00007 import os
00008 #from casac import *
00009 import casac
00010 import string
00011 import time
00012 import inspect
00013 import gc
00014 import numpy
00015 from odict import odict
00016 from taskmanager import tm
00017 from task_conjugatevis import conjugatevis
00018 class conjugatevis_cli_:
00019     __name__ = "conjugatevis"
00020     __async__ = {}
00021     rkey = None
00022     i_am_a_casapy_task = None
00023     # The existence of the i_am_a_casapy_task attribute allows help()
00024     # (and other) to treat casapy tasks as a special case.
00025 
00026     def __init__(self) :
00027        self.__bases__ = (conjugatevis_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'spwlist':None, 'outputvis':None, 'overwrite':None,  'async':None}
00031 
00032 
00033     def result(self, key=None):
00034             #### here we will scan the task-ids in __async__
00035             #### and add any that have completed...
00036             if key is not None and self.__async__.has_key(key) and self.__async__[key] is not None:
00037                ret = tm.retrieve(self.__async__[key])
00038                if ret['state'] == "done" :
00039                   self.__async__[key] = None
00040                elif ret['state'] == 'crashed' :
00041                   self.__async__[key] = None
00042                return ret
00043             return None
00044 
00045 
00046     def __call__(self, vis=None, spwlist=None, outputvis=None, overwrite=None,  async=None):
00047 
00048         """Change the sign of the phases in all visibility columns.
00049         Change the sign of the phases in all visibility columns
00050 
00051         Keyword arguments:
00052         vis -- Name of input visibility file
00053                 default: none; example='3C273XC1.ms'
00054         spwlist -- Select spectral window
00055                 default: [] all spws will be conjugated; example: spw=[1,2]
00056         outputvis -- name of output visibility file
00057                 default: 'conjugated_'+vis; example= 'conjugated.ms'
00058         overwrite -- Overwrite the outputvis if it exists
00059                 default=False; example: overwrite=True
00060 
00061         Example:
00062 
00063            conjugatevis(vis='NGC253.ms', spwlist=[0,1], outputvis='NGC253-conj.ms')
00064 
00065         Will conjugate all visibilities for spectral windows 0 and 1 and store the
00066         modified data in NGC253-conj.ms.
00067 
00068 
00069         """
00070         if not hasattr(self, "__globals__") or self.__globals__ == None :
00071            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00072         #casac = self.__globals__['casac']
00073         casalog = self.__globals__['casalog']
00074         #casalog = casac.casac.logsink()
00075         self.__globals__['__last_task'] = 'conjugatevis'
00076         self.__globals__['taskname'] = 'conjugatevis'
00077         ###
00078         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00079         ###
00080         ###
00081         #Handle globals or user over-ride of arguments
00082         #
00083         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00084         useLocalDefaults = False
00085 
00086         for item in function_signature_defaults.iteritems():
00087                 key,val = item
00088                 keyVal = eval(key)
00089                 if (keyVal == None):
00090                         #user hasn't set it - use global/default
00091                         pass
00092                 else:
00093                         #user has set it - use over-ride
00094                         if (key != 'self') :
00095                            useLocalDefaults = True
00096 
00097         myparams = {}
00098         if useLocalDefaults :
00099            for item in function_signature_defaults.iteritems():
00100                key,val = item
00101                keyVal = eval(key)
00102                exec('myparams[key] = keyVal')
00103                self.parameters[key] = keyVal
00104                if (keyVal == None):
00105                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00106                    keyVal = eval(key)
00107                    if(type(keyVal) == dict) :
00108                       if len(keyVal) > 0 :
00109                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00110                       else :
00111                          exec('myparams[key] = ' + key + ' = {}')
00112 
00113         else :
00114             async = self.parameters['async']
00115             myparams['vis'] = vis = self.parameters['vis']
00116             myparams['spwlist'] = spwlist = self.parameters['spwlist']
00117             myparams['outputvis'] = outputvis = self.parameters['outputvis']
00118             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00119 
00120 
00121         result = None
00122 
00123 #
00124 #    The following is work around to avoid a bug with current python translation
00125 #
00126         mytmp = {}
00127 
00128         mytmp['vis'] = vis
00129         mytmp['spwlist'] = spwlist
00130         mytmp['outputvis'] = outputvis
00131         mytmp['overwrite'] = overwrite
00132         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00133         trec = casac.casac.utils().torecord(pathname+'conjugatevis.xml')
00134 
00135         casalog.origin('conjugatevis')
00136         try :
00137           #if not trec.has_key('conjugatevis') or not casac.casac.utils().verify(mytmp, trec['conjugatevis']) :
00138             #return False
00139 
00140           casac.casac.utils().verify(mytmp, trec['conjugatevis'], True)
00141           scriptstr=['']
00142           saveinputs = self.__globals__['saveinputs']
00143           saveinputs('conjugatevis', 'conjugatevis.last', myparams, self.__globals__,scriptstr=scriptstr)
00144           if async :
00145             count = 0
00146             keybase =  time.strftime("%y%m%d.%H%M%S")
00147             key = keybase + "_" + str(count)
00148             while self.__async__.has_key(key) :
00149                count += 1
00150                key = keybase + "_" + str(count)
00151             result = tm.execute('conjugatevis', vis, spwlist, outputvis, overwrite)
00152             print "Use: "
00153             print "      tm.retrieve(return_value) # to retrieve the status"
00154             print 
00155             self.rkey = key
00156             self.__async__[key] = result
00157           else :
00158               tname = 'conjugatevis'
00159               spaces = ' '*(18-len(tname))
00160               casalog.post('\n##########################################'+
00161                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00162               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00163               result = conjugatevis(vis, spwlist, outputvis, overwrite)
00164               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00165                            '\n##########################################')
00166 
00167         except Exception, instance:
00168           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00169              raise
00170           else :
00171              #print '**** Error **** ',instance
00172              tname = 'conjugatevis'
00173              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00174              pass
00175 
00176         gc.collect()
00177         return result
00178 #
00179 #
00180 #
00181     def paramgui(self, useGlobals=True, ipython_globals=None):
00182         """
00183         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00184         """
00185         import paramgui
00186         if not hasattr(self, "__globals__") or self.__globals__ == None :
00187            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00188 
00189         if useGlobals:
00190             if ipython_globals == None:
00191                 myf=self.__globals__
00192             else:
00193                 myf=ipython_globals
00194 
00195             paramgui.setGlobals(myf)
00196         else:
00197             paramgui.setGlobals({})
00198 
00199         paramgui.runTask('conjugatevis', myf['_ip'])
00200         paramgui.setGlobals({})
00201 
00202 #
00203 #
00204 #
00205     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00206         if not hasattr(self, "__globals__") or self.__globals__ == None :
00207            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00208         if ipython_globals == None:
00209             myf=self.__globals__
00210         else:
00211             myf=ipython_globals
00212 
00213         a = odict()
00214         a['vis']  = ''
00215         a['spwlist']  = ""
00216         a['outputvis']  = ''
00217         a['overwrite']  = False
00218 
00219         a['async']=False
00220 
00221 ### This function sets the default values but also will return the list of
00222 ### parameters or the default value of a given parameter
00223         if(param == None):
00224                 myf['__set_default_parameters'](a)
00225         elif(param == 'paramkeys'):
00226                 return a.keys()
00227         else:
00228             if(paramvalue==None and subparam==None):
00229                if(a.has_key(param)):
00230                   return a[param]
00231                else:
00232                   return self.itsdefault(param)
00233             else:
00234                retval=a[param]
00235                if(type(a[param])==dict):
00236                   for k in range(len(a[param])):
00237                      valornotval='value'
00238                      if(a[param][k].has_key('notvalue')):
00239                         valornotval='notvalue'
00240                      if((a[param][k][valornotval])==paramvalue):
00241                         retval=a[param][k].copy()
00242                         retval.pop(valornotval)
00243                         if(subparam != None):
00244                            if(retval.has_key(subparam)):
00245                               retval=retval[subparam]
00246                            else:
00247                               retval=self.itsdefault(subparam)
00248                      else:
00249                         retval=self.itsdefault(subparam)
00250                return retval
00251 
00252 
00253 #
00254 #
00255     def check_params(self, param=None, value=None, ipython_globals=None):
00256       if ipython_globals == None:
00257           myf=self.__globals__
00258       else:
00259           myf=ipython_globals
00260 #      print 'param:', param, 'value:', value
00261       try :
00262          if str(type(value)) != "<type 'instance'>" :
00263             value0 = value
00264             value = myf['cu'].expandparam(param, value)
00265             matchtype = False
00266             if(type(value) == numpy.ndarray):
00267                if(type(value) == type(value0)):
00268                   myf[param] = value.tolist()
00269                else:
00270                   #print 'value:', value, 'value0:', value0
00271                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00272                   myf[param] = value0
00273                   if type(value0) != list :
00274                      matchtype = True
00275             else :
00276                myf[param] = value
00277             value = myf['cu'].verifyparam({param:value})
00278             if matchtype:
00279                value = False
00280       except Exception, instance:
00281          #ignore the exception and just return it unchecked
00282          myf[param] = value
00283       return value
00284 #
00285 #
00286     def description(self, key='conjugatevis', subkey=None):
00287         desc={'conjugatevis': 'Change the sign of the phases in all visibility columns.',
00288                'vis': 'Name of input visibility file.',
00289                'spwlist': 'Spectral window selection',
00290                'outputvis': 'Name of output visibility file',
00291                'overwrite': 'Overwrite the outputvis if it exists.',
00292 
00293                'async': 'If true the taskname must be started using conjugatevis(...)'
00294               }
00295 
00296         if(desc.has_key(key)) :
00297            return desc[key]
00298 
00299     def itsdefault(self, paramname) :
00300         a = {}
00301         a['vis']  = ''
00302         a['spwlist']  = ""
00303         a['outputvis']  = ''
00304         a['overwrite']  = False
00305 
00306         #a = sys._getframe(len(inspect.stack())-1).f_globals
00307 
00308         if a.has_key(paramname) :
00309               return a[paramname]
00310 conjugatevis_cli = conjugatevis_cli_()