casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
clearcal_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_clearcal import clearcal
00018 class clearcal_cli_:
00019     __name__ = "clearcal"
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__ = (clearcal_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'spw':None, 'intent':None, 'addmodel':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, field=None, spw=None, intent=None, addmodel=None,  async=None):
00047 
00048         """Re-initializes the calibration for a visibility data set
00049 
00050       Clearcal reinitializes the calibration columns in a measurement set.
00051       Specificially, it will set the MODEL_DATA column to unity in total intensity
00052       and zero in polarization, and it will set the  CORRECTED_DATA column to the original
00053       (observed) DATA in the DATA column.  Use the field and spw parameters to select
00054       which data to initialize.  If the dataset does not yet have the scratch
00055       columns, they will be created and initilized for the whole dataset (field and spw
00056       ill be ignored).  
00057 
00058       Keyword arguments:
00059       vis -- Name of input visibility file
00060               default: none; example: vis='ngc5921.ms'
00061 
00062       field -- Select field using field id(s) or field name(s).
00063                  [run listobs to obtain the list id's or names]
00064               default: ''=all fields
00065               If field string is a non-negative integer, it is assumed a field index
00066                 otherwise, it is assumed a field name
00067               field='0~2'; field ids 0,1,2
00068               field='0,4,5~7'; field ids 0,4,5,6,7
00069               field='3C286,3C295'; field named 3C286 adn 3C295
00070               field = '3,4C*'; field id 3, all names starting with 4C
00071       spw -- Select spectral window
00072               default: ''=all spectral windows and channels
00073               spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00074               spw='<2';  spectral windows less than 2 (i.e. 0,1)
00075               spw='0:5~61'; spw 0, channels 5 to 61
00076               spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, channels 3 to 45.
00077               spw='0~2:2:6'; spw 0,1,2 with channels 2 through 6 in each.
00078               NB: Multiple channel ranges per spw are not supported in clearcal.
00079       intent -- Select observing intent
00080                 default: ''  (no selection by intent)
00081                 intent='*BANDPASS*'  (selects data labelled with
00082                                       BANDPASS intent)
00083       addmodel -- add MODEL_DATA along with CORRECTED_DATA if True; 
00084                         otherwise it will add/reset only CORRECTED_DATA, model visibilities
00085                         will then be evaluated when needed.
00086 
00087  
00088         """
00089         if not hasattr(self, "__globals__") or self.__globals__ == None :
00090            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00091         #casac = self.__globals__['casac']
00092         casalog = self.__globals__['casalog']
00093         #casalog = casac.casac.logsink()
00094         self.__globals__['__last_task'] = 'clearcal'
00095         self.__globals__['taskname'] = 'clearcal'
00096         ###
00097         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00098         ###
00099         ###
00100         #Handle globals or user over-ride of arguments
00101         #
00102         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00103         useLocalDefaults = False
00104 
00105         for item in function_signature_defaults.iteritems():
00106                 key,val = item
00107                 keyVal = eval(key)
00108                 if (keyVal == None):
00109                         #user hasn't set it - use global/default
00110                         pass
00111                 else:
00112                         #user has set it - use over-ride
00113                         if (key != 'self') :
00114                            useLocalDefaults = True
00115 
00116         myparams = {}
00117         if useLocalDefaults :
00118            for item in function_signature_defaults.iteritems():
00119                key,val = item
00120                keyVal = eval(key)
00121                exec('myparams[key] = keyVal')
00122                self.parameters[key] = keyVal
00123                if (keyVal == None):
00124                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00125                    keyVal = eval(key)
00126                    if(type(keyVal) == dict) :
00127                       if len(keyVal) > 0 :
00128                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00129                       else :
00130                          exec('myparams[key] = ' + key + ' = {}')
00131 
00132         else :
00133             async = self.parameters['async']
00134             myparams['vis'] = vis = self.parameters['vis']
00135             myparams['field'] = field = self.parameters['field']
00136             myparams['spw'] = spw = self.parameters['spw']
00137             myparams['intent'] = intent = self.parameters['intent']
00138             myparams['addmodel'] = addmodel = self.parameters['addmodel']
00139 
00140 
00141         result = None
00142 
00143 #
00144 #    The following is work around to avoid a bug with current python translation
00145 #
00146         mytmp = {}
00147 
00148         mytmp['vis'] = vis
00149         mytmp['field'] = field
00150         mytmp['spw'] = spw
00151         mytmp['intent'] = intent
00152         mytmp['addmodel'] = addmodel
00153         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00154         trec = casac.casac.utils().torecord(pathname+'clearcal.xml')
00155 
00156         casalog.origin('clearcal')
00157         try :
00158           #if not trec.has_key('clearcal') or not casac.casac.utils().verify(mytmp, trec['clearcal']) :
00159             #return False
00160 
00161           casac.casac.utils().verify(mytmp, trec['clearcal'], True)
00162           scriptstr=['']
00163           saveinputs = self.__globals__['saveinputs']
00164           saveinputs('clearcal', 'clearcal.last', myparams, self.__globals__,scriptstr=scriptstr)
00165           if async :
00166             count = 0
00167             keybase =  time.strftime("%y%m%d.%H%M%S")
00168             key = keybase + "_" + str(count)
00169             while self.__async__.has_key(key) :
00170                count += 1
00171                key = keybase + "_" + str(count)
00172             result = tm.execute('clearcal', vis, field, spw, intent, addmodel)
00173             print "Use: "
00174             print "      tm.retrieve(return_value) # to retrieve the status"
00175             print 
00176             self.rkey = key
00177             self.__async__[key] = result
00178           else :
00179               tname = 'clearcal'
00180               spaces = ' '*(18-len(tname))
00181               casalog.post('\n##########################################'+
00182                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00183               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00184               result = clearcal(vis, field, spw, intent, addmodel)
00185               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00186                            '\n##########################################')
00187 
00188         except Exception, instance:
00189           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00190              raise
00191           else :
00192              #print '**** Error **** ',instance
00193              tname = 'clearcal'
00194              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00195              pass
00196 
00197         gc.collect()
00198         return result
00199 #
00200 #
00201 #
00202     def paramgui(self, useGlobals=True, ipython_globals=None):
00203         """
00204         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00205         """
00206         import paramgui
00207         if not hasattr(self, "__globals__") or self.__globals__ == None :
00208            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00209 
00210         if useGlobals:
00211             if ipython_globals == None:
00212                 myf=self.__globals__
00213             else:
00214                 myf=ipython_globals
00215 
00216             paramgui.setGlobals(myf)
00217         else:
00218             paramgui.setGlobals({})
00219 
00220         paramgui.runTask('clearcal', myf['_ip'])
00221         paramgui.setGlobals({})
00222 
00223 #
00224 #
00225 #
00226     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00227         if not hasattr(self, "__globals__") or self.__globals__ == None :
00228            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00229         if ipython_globals == None:
00230             myf=self.__globals__
00231         else:
00232             myf=ipython_globals
00233 
00234         a = odict()
00235         a['vis']  = ''
00236         a['field']  = ''
00237         a['spw']  = ''
00238         a['intent']  = ''
00239         a['addmodel']  = True
00240 
00241         a['async']=False
00242 
00243 ### This function sets the default values but also will return the list of
00244 ### parameters or the default value of a given parameter
00245         if(param == None):
00246                 myf['__set_default_parameters'](a)
00247         elif(param == 'paramkeys'):
00248                 return a.keys()
00249         else:
00250             if(paramvalue==None and subparam==None):
00251                if(a.has_key(param)):
00252                   return a[param]
00253                else:
00254                   return self.itsdefault(param)
00255             else:
00256                retval=a[param]
00257                if(type(a[param])==dict):
00258                   for k in range(len(a[param])):
00259                      valornotval='value'
00260                      if(a[param][k].has_key('notvalue')):
00261                         valornotval='notvalue'
00262                      if((a[param][k][valornotval])==paramvalue):
00263                         retval=a[param][k].copy()
00264                         retval.pop(valornotval)
00265                         if(subparam != None):
00266                            if(retval.has_key(subparam)):
00267                               retval=retval[subparam]
00268                            else:
00269                               retval=self.itsdefault(subparam)
00270                      else:
00271                         retval=self.itsdefault(subparam)
00272                return retval
00273 
00274 
00275 #
00276 #
00277     def check_params(self, param=None, value=None, ipython_globals=None):
00278       if ipython_globals == None:
00279           myf=self.__globals__
00280       else:
00281           myf=ipython_globals
00282 #      print 'param:', param, 'value:', value
00283       try :
00284          if str(type(value)) != "<type 'instance'>" :
00285             value0 = value
00286             value = myf['cu'].expandparam(param, value)
00287             matchtype = False
00288             if(type(value) == numpy.ndarray):
00289                if(type(value) == type(value0)):
00290                   myf[param] = value.tolist()
00291                else:
00292                   #print 'value:', value, 'value0:', value0
00293                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00294                   myf[param] = value0
00295                   if type(value0) != list :
00296                      matchtype = True
00297             else :
00298                myf[param] = value
00299             value = myf['cu'].verifyparam({param:value})
00300             if matchtype:
00301                value = False
00302       except Exception, instance:
00303          #ignore the exception and just return it unchecked
00304          myf[param] = value
00305       return value
00306 #
00307 #
00308     def description(self, key='clearcal', subkey=None):
00309         desc={'clearcal': 'Re-initializes the calibration for a visibility data set',
00310                'vis': 'Name of input visibility file (MS)',
00311                'field': 'Select field using field id(s) or field name(s)',
00312                'spw': 'Select spectral window/channel.',
00313                'intent': 'Select observing intent',
00314                'addmodel': 'Add MODEL_DATA scratch column',
00315 
00316                'async': 'If true the taskname must be started using clearcal(...)'
00317               }
00318 
00319         if(desc.has_key(key)) :
00320            return desc[key]
00321 
00322     def itsdefault(self, paramname) :
00323         a = {}
00324         a['vis']  = ''
00325         a['field']  = ''
00326         a['spw']  = ''
00327         a['intent']  = ''
00328         a['addmodel']  = True
00329 
00330         #a = sys._getframe(len(inspect.stack())-1).f_globals
00331 
00332         if a.has_key(paramname) :
00333               return a[paramname]
00334 clearcal_cli = clearcal_cli_()