casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
smoothcal_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_smoothcal import smoothcal
00018 class smoothcal_cli_:
00019     __name__ = "smoothcal"
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__ = (smoothcal_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'tablein':None, 'caltable':None, 'field':None, 'smoothtype':None, 'smoothtime':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, tablein=None, caltable=None, field=None, smoothtype=None, smoothtime=None,  async=None):
00047 
00048         """Smooth calibration solution(s) derived from one or more sources:
00049 
00050 
00051         A G- or T-type gain calibration can be smoothed.  The amplitude and
00052         phase smoothing times are currently the same.  Calibration values
00053         will be smoothed over all fields designed.
00054 
00055         Keyword arguments:
00056         vis -- Name of input visibility file
00057                 default: none; example: vis='ngc5921.ms'
00058         tablein -- Input calibration table (G or T)
00059                 default: none; example: tablein='ngc5921.gcal'
00060         caltable -- Output calibration table (smoothed)
00061                 default: none; example: caltable='ngc5921_smooth.gcal'
00062         field -- subset of fields to select and smooth
00063                 default: '' means all; example: field='0319_415_1,3C286'
00064         smoothtype -- The smoothing filter to be used for both amp and phase
00065                 default: 'median'; example: smoothtype='mean'
00066                 Options: 'median','mean'
00067         smoothtime -- Smoothing filter time (sec)
00068                 default: 300.0; example: smoothtime=60.
00069  
00070         """
00071         if not hasattr(self, "__globals__") or self.__globals__ == None :
00072            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00073         #casac = self.__globals__['casac']
00074         casalog = self.__globals__['casalog']
00075         #casalog = casac.casac.logsink()
00076         self.__globals__['__last_task'] = 'smoothcal'
00077         self.__globals__['taskname'] = 'smoothcal'
00078         ###
00079         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00080         ###
00081         ###
00082         #Handle globals or user over-ride of arguments
00083         #
00084         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00085         useLocalDefaults = False
00086 
00087         for item in function_signature_defaults.iteritems():
00088                 key,val = item
00089                 keyVal = eval(key)
00090                 if (keyVal == None):
00091                         #user hasn't set it - use global/default
00092                         pass
00093                 else:
00094                         #user has set it - use over-ride
00095                         if (key != 'self') :
00096                            useLocalDefaults = True
00097 
00098         myparams = {}
00099         if useLocalDefaults :
00100            for item in function_signature_defaults.iteritems():
00101                key,val = item
00102                keyVal = eval(key)
00103                exec('myparams[key] = keyVal')
00104                self.parameters[key] = keyVal
00105                if (keyVal == None):
00106                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00107                    keyVal = eval(key)
00108                    if(type(keyVal) == dict) :
00109                       if len(keyVal) > 0 :
00110                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00111                       else :
00112                          exec('myparams[key] = ' + key + ' = {}')
00113 
00114         else :
00115             async = self.parameters['async']
00116             myparams['vis'] = vis = self.parameters['vis']
00117             myparams['tablein'] = tablein = self.parameters['tablein']
00118             myparams['caltable'] = caltable = self.parameters['caltable']
00119             myparams['field'] = field = self.parameters['field']
00120             myparams['smoothtype'] = smoothtype = self.parameters['smoothtype']
00121             myparams['smoothtime'] = smoothtime = self.parameters['smoothtime']
00122 
00123         if type(field)==str: field=[field]
00124 
00125         result = None
00126 
00127 #
00128 #    The following is work around to avoid a bug with current python translation
00129 #
00130         mytmp = {}
00131 
00132         mytmp['vis'] = vis
00133         mytmp['tablein'] = tablein
00134         mytmp['caltable'] = caltable
00135         mytmp['field'] = field
00136         mytmp['smoothtype'] = smoothtype
00137         mytmp['smoothtime'] = smoothtime
00138         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00139         trec = casac.casac.utils().torecord(pathname+'smoothcal.xml')
00140 
00141         casalog.origin('smoothcal')
00142         try :
00143           #if not trec.has_key('smoothcal') or not casac.casac.utils().verify(mytmp, trec['smoothcal']) :
00144             #return False
00145 
00146           casac.casac.utils().verify(mytmp, trec['smoothcal'], True)
00147           scriptstr=['']
00148           saveinputs = self.__globals__['saveinputs']
00149           saveinputs('smoothcal', 'smoothcal.last', myparams, self.__globals__,scriptstr=scriptstr)
00150           if async :
00151             count = 0
00152             keybase =  time.strftime("%y%m%d.%H%M%S")
00153             key = keybase + "_" + str(count)
00154             while self.__async__.has_key(key) :
00155                count += 1
00156                key = keybase + "_" + str(count)
00157             result = tm.execute('smoothcal', vis, tablein, caltable, field, smoothtype, smoothtime)
00158             print "Use: "
00159             print "      tm.retrieve(return_value) # to retrieve the status"
00160             print 
00161             self.rkey = key
00162             self.__async__[key] = result
00163           else :
00164               tname = 'smoothcal'
00165               spaces = ' '*(18-len(tname))
00166               casalog.post('\n##########################################'+
00167                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00168               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00169               result = smoothcal(vis, tablein, caltable, field, smoothtype, smoothtime)
00170               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00171                            '\n##########################################')
00172 
00173         except Exception, instance:
00174           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00175              raise
00176           else :
00177              #print '**** Error **** ',instance
00178              tname = 'smoothcal'
00179              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00180              pass
00181 
00182         gc.collect()
00183         return result
00184 #
00185 #
00186 #
00187     def paramgui(self, useGlobals=True, ipython_globals=None):
00188         """
00189         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00190         """
00191         import paramgui
00192         if not hasattr(self, "__globals__") or self.__globals__ == None :
00193            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00194 
00195         if useGlobals:
00196             if ipython_globals == None:
00197                 myf=self.__globals__
00198             else:
00199                 myf=ipython_globals
00200 
00201             paramgui.setGlobals(myf)
00202         else:
00203             paramgui.setGlobals({})
00204 
00205         paramgui.runTask('smoothcal', myf['_ip'])
00206         paramgui.setGlobals({})
00207 
00208 #
00209 #
00210 #
00211     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00212         if not hasattr(self, "__globals__") or self.__globals__ == None :
00213            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00214         if ipython_globals == None:
00215             myf=self.__globals__
00216         else:
00217             myf=ipython_globals
00218 
00219         a = odict()
00220         a['vis']  = ''
00221         a['tablein']  = ''
00222         a['caltable']  = ''
00223         a['field']  = ['']
00224         a['smoothtype']  = 'median'
00225         a['smoothtime']  = 60.0
00226 
00227         a['async']=False
00228 
00229 ### This function sets the default values but also will return the list of
00230 ### parameters or the default value of a given parameter
00231         if(param == None):
00232                 myf['__set_default_parameters'](a)
00233         elif(param == 'paramkeys'):
00234                 return a.keys()
00235         else:
00236             if(paramvalue==None and subparam==None):
00237                if(a.has_key(param)):
00238                   return a[param]
00239                else:
00240                   return self.itsdefault(param)
00241             else:
00242                retval=a[param]
00243                if(type(a[param])==dict):
00244                   for k in range(len(a[param])):
00245                      valornotval='value'
00246                      if(a[param][k].has_key('notvalue')):
00247                         valornotval='notvalue'
00248                      if((a[param][k][valornotval])==paramvalue):
00249                         retval=a[param][k].copy()
00250                         retval.pop(valornotval)
00251                         if(subparam != None):
00252                            if(retval.has_key(subparam)):
00253                               retval=retval[subparam]
00254                            else:
00255                               retval=self.itsdefault(subparam)
00256                      else:
00257                         retval=self.itsdefault(subparam)
00258                return retval
00259 
00260 
00261 #
00262 #
00263     def check_params(self, param=None, value=None, ipython_globals=None):
00264       if ipython_globals == None:
00265           myf=self.__globals__
00266       else:
00267           myf=ipython_globals
00268 #      print 'param:', param, 'value:', value
00269       try :
00270          if str(type(value)) != "<type 'instance'>" :
00271             value0 = value
00272             value = myf['cu'].expandparam(param, value)
00273             matchtype = False
00274             if(type(value) == numpy.ndarray):
00275                if(type(value) == type(value0)):
00276                   myf[param] = value.tolist()
00277                else:
00278                   #print 'value:', value, 'value0:', value0
00279                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00280                   myf[param] = value0
00281                   if type(value0) != list :
00282                      matchtype = True
00283             else :
00284                myf[param] = value
00285             value = myf['cu'].verifyparam({param:value})
00286             if matchtype:
00287                value = False
00288       except Exception, instance:
00289          #ignore the exception and just return it unchecked
00290          myf[param] = value
00291       return value
00292 #
00293 #
00294     def description(self, key='smoothcal', subkey=None):
00295         desc={'smoothcal': 'Smooth calibration solution(s) derived from one or more sources:',
00296                'vis': 'Name of input visibility file (MS)',
00297                'tablein': 'Input calibration table',
00298                'caltable': 'Output calibration table',
00299                'field': 'Field name list',
00300                'smoothtype': 'Smoothing filter to use',
00301                'smoothtime': 'Smoothing time (sec)',
00302 
00303                'async': 'If true the taskname must be started using smoothcal(...)'
00304               }
00305 
00306         if(desc.has_key(key)) :
00307            return desc[key]
00308 
00309     def itsdefault(self, paramname) :
00310         a = {}
00311         a['vis']  = ''
00312         a['tablein']  = ''
00313         a['caltable']  = ''
00314         a['field']  = ['']
00315         a['smoothtype']  = 'median'
00316         a['smoothtime']  = 60.0
00317 
00318         #a = sys._getframe(len(inspect.stack())-1).f_globals
00319 
00320         if a.has_key(paramname) :
00321               return a[paramname]
00322 smoothcal_cli = smoothcal_cli_()