casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
caltabconvert_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_caltabconvert import caltabconvert
00018 class caltabconvert_cli_:
00019     __name__ = "caltabconvert"
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__ = (caltabconvert_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'caltabold':None, 'vis':None, 'ptype':None, 'caltabnew':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, caltabold=None, vis=None, ptype=None, caltabnew=None,  async=None):
00047 
00048         """Convert old-style caltables into new-style caltables.\n
00049     This task converts old-style (up to CASA 3.3.0) caltables into new-style 
00050     (CASA 3.4.0 and later) caltables. It is provided as a convenience and 
00051     is strictly temporary. The information transferred should be enough 
00052     for most calibration purposes. BPOLY and GSPLINE versions are not 
00053     supported. Only simple bugs will be fixed. If there are other issues, 
00054     it is suggested that a new-style caltable be created directly.
00055 
00056     Arguments:
00057 
00058     caltabold -- Name of the old-style caltable.
00059     default: none
00060     example: caltabold='gronk.g0'
00061 
00062     vis -- Name of the visibility file (MS) associated with the old-style
00063         caltable.
00064     default: none
00065     example: vis='blurp.ms'
00066 
00067     ptype -- Type of data in the new-format caltable.
00068     default: "complex"; allowed values: "complex" or "float"
00069     example: ptype="complex"
00070 
00071     NB: The old-style caltables do not have this information, so it is
00072     imperative that users get it correct.  "complex" refers to caltables that
00073     have complex gains (e.g., produced by gaincal, bpcal, etc.).  "float" refers
00074     to caltables that real numbers such as delays (e.g., produced by gencal).
00075 
00076     caltabnew -- Name of the new-style caltable.
00077     default: "" --> the suffix ".new" is appended to the name of the old-style
00078         caltable
00079     example: caltabold='gronk_new.g0'
00080   
00081         """
00082         if not hasattr(self, "__globals__") or self.__globals__ == None :
00083            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00084         #casac = self.__globals__['casac']
00085         casalog = self.__globals__['casalog']
00086         #casalog = casac.casac.logsink()
00087         self.__globals__['__last_task'] = 'caltabconvert'
00088         self.__globals__['taskname'] = 'caltabconvert'
00089         ###
00090         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00091         ###
00092         ###
00093         #Handle globals or user over-ride of arguments
00094         #
00095         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00096         useLocalDefaults = False
00097 
00098         for item in function_signature_defaults.iteritems():
00099                 key,val = item
00100                 keyVal = eval(key)
00101                 if (keyVal == None):
00102                         #user hasn't set it - use global/default
00103                         pass
00104                 else:
00105                         #user has set it - use over-ride
00106                         if (key != 'self') :
00107                            useLocalDefaults = True
00108 
00109         myparams = {}
00110         if useLocalDefaults :
00111            for item in function_signature_defaults.iteritems():
00112                key,val = item
00113                keyVal = eval(key)
00114                exec('myparams[key] = keyVal')
00115                self.parameters[key] = keyVal
00116                if (keyVal == None):
00117                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00118                    keyVal = eval(key)
00119                    if(type(keyVal) == dict) :
00120                       if len(keyVal) > 0 :
00121                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00122                       else :
00123                          exec('myparams[key] = ' + key + ' = {}')
00124 
00125         else :
00126             async = self.parameters['async']
00127             myparams['caltabold'] = caltabold = self.parameters['caltabold']
00128             myparams['vis'] = vis = self.parameters['vis']
00129             myparams['ptype'] = ptype = self.parameters['ptype']
00130             myparams['caltabnew'] = caltabnew = self.parameters['caltabnew']
00131 
00132 
00133         result = None
00134 
00135 #
00136 #    The following is work around to avoid a bug with current python translation
00137 #
00138         mytmp = {}
00139 
00140         mytmp['caltabold'] = caltabold
00141         mytmp['vis'] = vis
00142         mytmp['ptype'] = ptype
00143         mytmp['caltabnew'] = caltabnew
00144         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00145         trec = casac.casac.utils().torecord(pathname+'caltabconvert.xml')
00146 
00147         casalog.origin('caltabconvert')
00148         try :
00149           #if not trec.has_key('caltabconvert') or not casac.casac.utils().verify(mytmp, trec['caltabconvert']) :
00150             #return False
00151 
00152           casac.casac.utils().verify(mytmp, trec['caltabconvert'], True)
00153           scriptstr=['']
00154           saveinputs = self.__globals__['saveinputs']
00155           saveinputs('caltabconvert', 'caltabconvert.last', myparams, self.__globals__,scriptstr=scriptstr)
00156           if async :
00157             count = 0
00158             keybase =  time.strftime("%y%m%d.%H%M%S")
00159             key = keybase + "_" + str(count)
00160             while self.__async__.has_key(key) :
00161                count += 1
00162                key = keybase + "_" + str(count)
00163             result = tm.execute('caltabconvert', caltabold, vis, ptype, caltabnew)
00164             print "Use: "
00165             print "      tm.retrieve(return_value) # to retrieve the status"
00166             print 
00167             self.rkey = key
00168             self.__async__[key] = result
00169           else :
00170               tname = 'caltabconvert'
00171               spaces = ' '*(18-len(tname))
00172               casalog.post('\n##########################################'+
00173                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00174               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00175               result = caltabconvert(caltabold, vis, ptype, caltabnew)
00176               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00177                            '\n##########################################')
00178 
00179         except Exception, instance:
00180           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00181              raise
00182           else :
00183              #print '**** Error **** ',instance
00184              tname = 'caltabconvert'
00185              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00186              pass
00187 
00188         gc.collect()
00189         return result
00190 #
00191 #
00192 #
00193     def paramgui(self, useGlobals=True, ipython_globals=None):
00194         """
00195         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00196         """
00197         import paramgui
00198         if not hasattr(self, "__globals__") or self.__globals__ == None :
00199            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00200 
00201         if useGlobals:
00202             if ipython_globals == None:
00203                 myf=self.__globals__
00204             else:
00205                 myf=ipython_globals
00206 
00207             paramgui.setGlobals(myf)
00208         else:
00209             paramgui.setGlobals({})
00210 
00211         paramgui.runTask('caltabconvert', myf['_ip'])
00212         paramgui.setGlobals({})
00213 
00214 #
00215 #
00216 #
00217     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00218         if not hasattr(self, "__globals__") or self.__globals__ == None :
00219            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00220         if ipython_globals == None:
00221             myf=self.__globals__
00222         else:
00223             myf=ipython_globals
00224 
00225         a = odict()
00226         a['caltabold']  = ''
00227         a['vis']  = ''
00228         a['ptype']  = 'complex'
00229         a['caltabnew']  = ''
00230 
00231         a['async']=False
00232 
00233 ### This function sets the default values but also will return the list of
00234 ### parameters or the default value of a given parameter
00235         if(param == None):
00236                 myf['__set_default_parameters'](a)
00237         elif(param == 'paramkeys'):
00238                 return a.keys()
00239         else:
00240             if(paramvalue==None and subparam==None):
00241                if(a.has_key(param)):
00242                   return a[param]
00243                else:
00244                   return self.itsdefault(param)
00245             else:
00246                retval=a[param]
00247                if(type(a[param])==dict):
00248                   for k in range(len(a[param])):
00249                      valornotval='value'
00250                      if(a[param][k].has_key('notvalue')):
00251                         valornotval='notvalue'
00252                      if((a[param][k][valornotval])==paramvalue):
00253                         retval=a[param][k].copy()
00254                         retval.pop(valornotval)
00255                         if(subparam != None):
00256                            if(retval.has_key(subparam)):
00257                               retval=retval[subparam]
00258                            else:
00259                               retval=self.itsdefault(subparam)
00260                      else:
00261                         retval=self.itsdefault(subparam)
00262                return retval
00263 
00264 
00265 #
00266 #
00267     def check_params(self, param=None, value=None, ipython_globals=None):
00268       if ipython_globals == None:
00269           myf=self.__globals__
00270       else:
00271           myf=ipython_globals
00272 #      print 'param:', param, 'value:', value
00273       try :
00274          if str(type(value)) != "<type 'instance'>" :
00275             value0 = value
00276             value = myf['cu'].expandparam(param, value)
00277             matchtype = False
00278             if(type(value) == numpy.ndarray):
00279                if(type(value) == type(value0)):
00280                   myf[param] = value.tolist()
00281                else:
00282                   #print 'value:', value, 'value0:', value0
00283                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00284                   myf[param] = value0
00285                   if type(value0) != list :
00286                      matchtype = True
00287             else :
00288                myf[param] = value
00289             value = myf['cu'].verifyparam({param:value})
00290             if matchtype:
00291                value = False
00292       except Exception, instance:
00293          #ignore the exception and just return it unchecked
00294          myf[param] = value
00295       return value
00296 #
00297 #
00298     def description(self, key='caltabconvert', subkey=None):
00299         desc={'caltabconvert': 'Convert old-style caltables into new-style caltables.\n',
00300                'caltabold': 'Name of the old-style caltable.',
00301                'vis': 'Name of the visibility file (MS) associated with the old-style caltable.',
00302                'ptype': 'Type of data in the new-format caltable ("complex" or "float"; default is "complex").',
00303                'caltabnew': 'Name of the new-style caltable.  If not specified, the suffix ".new" is appended to the name of old-style caltable.',
00304 
00305                'async': 'If true the taskname must be started using caltabconvert(...)'
00306               }
00307 
00308         if(desc.has_key(key)) :
00309            return desc[key]
00310 
00311     def itsdefault(self, paramname) :
00312         a = {}
00313         a['caltabold']  = ''
00314         a['vis']  = ''
00315         a['ptype']  = 'complex'
00316         a['caltabnew']  = ''
00317 
00318         #a = sys._getframe(len(inspect.stack())-1).f_globals
00319 
00320         if a.has_key(paramname) :
00321               return a[paramname]
00322 caltabconvert_cli = caltabconvert_cli_()