casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
calstat_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_calstat import calstat
00018 class calstat_cli_:
00019     __name__ = "calstat"
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__ = (calstat_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'caltable':None, 'axis':None, 'datacolumn':None, 'useflags':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, caltable=None, axis=None, datacolumn=None, useflags=None,  async=None):
00047 
00048         """Displays statistical information on a calibration table
00049         This task returns statistical information about a column in a calibration table.
00050 
00051         The following values are computed: mean value, sum of values, sum of squared values,
00052         median, median absolute deviation, quartile, minimum, maximum,
00053         variance, standard deviation, root mean square.
00054 
00055         Keyword arguments:
00056 
00057         caltable -- Name of input calibration table
00058                   default: '', example: vis='ggtau.1mm.amp.gcal'
00059 
00060         axis -- Which data to analyze. The possible values are 'amp', 'amplitude', 'phase',
00061                 'real', 'imag', 'imaginary'. Also, the name of any real valued MS column can be 
00062                 given, e.g. TIME, POLY_COEFF_AMP, REF_ANT, ANTENNA1, FLAG, ...
00063 
00064                 default: 'amplitude'
00065                 axis='gain'
00066 
00067                 The phase of a complex number is in radians in the range [-pi; pi[.
00068 
00069 
00070         datacolumn -- Which data column to use if axis is 'amp', 'amplitude',
00071                       'phase', 'real', 'imag' or 'imaginary'.
00072                 default: 'gain'
00073                 datacolumn='gain'
00074 
00075         useflags -- Take MS flags into account (not implemented, this parameter 
00076                     has no effect!)
00077                 default: False
00078                 useflag=False
00079                 useflag=True
00080         If useflags=False, flagged values are included in the statistics.
00081         If useflags=True, any flagged values are not used in the statistics.
00082 
00083         """
00084         if not hasattr(self, "__globals__") or self.__globals__ == None :
00085            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00086         #casac = self.__globals__['casac']
00087         casalog = self.__globals__['casalog']
00088         #casalog = casac.casac.logsink()
00089         self.__globals__['__last_task'] = 'calstat'
00090         self.__globals__['taskname'] = 'calstat'
00091         ###
00092         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00093         ###
00094         ###
00095         #Handle globals or user over-ride of arguments
00096         #
00097         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00098         useLocalDefaults = False
00099 
00100         for item in function_signature_defaults.iteritems():
00101                 key,val = item
00102                 keyVal = eval(key)
00103                 if (keyVal == None):
00104                         #user hasn't set it - use global/default
00105                         pass
00106                 else:
00107                         #user has set it - use over-ride
00108                         if (key != 'self') :
00109                            useLocalDefaults = True
00110 
00111         myparams = {}
00112         if useLocalDefaults :
00113            for item in function_signature_defaults.iteritems():
00114                key,val = item
00115                keyVal = eval(key)
00116                exec('myparams[key] = keyVal')
00117                self.parameters[key] = keyVal
00118                if (keyVal == None):
00119                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00120                    keyVal = eval(key)
00121                    if(type(keyVal) == dict) :
00122                       if len(keyVal) > 0 :
00123                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00124                       else :
00125                          exec('myparams[key] = ' + key + ' = {}')
00126 
00127         else :
00128             async = self.parameters['async']
00129             myparams['caltable'] = caltable = self.parameters['caltable']
00130             myparams['axis'] = axis = self.parameters['axis']
00131             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00132             myparams['useflags'] = useflags = self.parameters['useflags']
00133 
00134 
00135         result = None
00136 
00137 #
00138 #    The following is work around to avoid a bug with current python translation
00139 #
00140         mytmp = {}
00141 
00142         mytmp['caltable'] = caltable
00143         mytmp['axis'] = axis
00144         mytmp['datacolumn'] = datacolumn
00145         mytmp['useflags'] = useflags
00146         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00147         trec = casac.casac.utils().torecord(pathname+'calstat.xml')
00148 
00149         casalog.origin('calstat')
00150         try :
00151           #if not trec.has_key('calstat') or not casac.casac.utils().verify(mytmp, trec['calstat']) :
00152             #return False
00153 
00154           casac.casac.utils().verify(mytmp, trec['calstat'], True)
00155           scriptstr=['']
00156           saveinputs = self.__globals__['saveinputs']
00157           saveinputs('calstat', 'calstat.last', myparams, self.__globals__,scriptstr=scriptstr)
00158           if async :
00159             count = 0
00160             keybase =  time.strftime("%y%m%d.%H%M%S")
00161             key = keybase + "_" + str(count)
00162             while self.__async__.has_key(key) :
00163                count += 1
00164                key = keybase + "_" + str(count)
00165             result = tm.execute('calstat', caltable, axis, datacolumn, useflags)
00166             print "Use: "
00167             print "      tm.retrieve(return_value) # to retrieve the status"
00168             print 
00169             self.rkey = key
00170             self.__async__[key] = result
00171           else :
00172               tname = 'calstat'
00173               spaces = ' '*(18-len(tname))
00174               casalog.post('\n##########################################'+
00175                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00176               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00177               result = calstat(caltable, axis, datacolumn, useflags)
00178               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00179                            '\n##########################################')
00180 
00181         except Exception, instance:
00182           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00183              raise
00184           else :
00185              #print '**** Error **** ',instance
00186              tname = 'calstat'
00187              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00188              pass
00189 
00190         gc.collect()
00191         return result
00192 #
00193 #
00194 #
00195     def paramgui(self, useGlobals=True, ipython_globals=None):
00196         """
00197         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00198         """
00199         import paramgui
00200         if not hasattr(self, "__globals__") or self.__globals__ == None :
00201            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00202 
00203         if useGlobals:
00204             if ipython_globals == None:
00205                 myf=self.__globals__
00206             else:
00207                 myf=ipython_globals
00208 
00209             paramgui.setGlobals(myf)
00210         else:
00211             paramgui.setGlobals({})
00212 
00213         paramgui.runTask('calstat', myf['_ip'])
00214         paramgui.setGlobals({})
00215 
00216 #
00217 #
00218 #
00219     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00220         if not hasattr(self, "__globals__") or self.__globals__ == None :
00221            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00222         if ipython_globals == None:
00223             myf=self.__globals__
00224         else:
00225             myf=ipython_globals
00226 
00227         a = odict()
00228         a['caltable']  = ''
00229         a['axis']  = 'amplitude'
00230         a['useflags']  = True
00231 
00232         a['async']=False
00233         a['axis'] = {
00234                     0:odict([{'value':'amp'}, {'datacolumn':'gain'}]), 
00235                     1:odict([{'value':'amplitude'}, {'datacolumn':'gain'}]), 
00236                     2:odict([{'value':'phase'}, {'datacolumn':'gain'}]), 
00237                     3:odict([{'value':'real'}, {'datacolumn':'gain'}]), 
00238                     4:odict([{'value':'imag'}, {'datacolumn':'gain'}]), 
00239                     5:odict([{'value':'imaginary'}, {'datacolumn':'gain'}])}
00240 
00241 ### This function sets the default values but also will return the list of
00242 ### parameters or the default value of a given parameter
00243         if(param == None):
00244                 myf['__set_default_parameters'](a)
00245         elif(param == 'paramkeys'):
00246                 return a.keys()
00247         else:
00248             if(paramvalue==None and subparam==None):
00249                if(a.has_key(param)):
00250                   return a[param]
00251                else:
00252                   return self.itsdefault(param)
00253             else:
00254                retval=a[param]
00255                if(type(a[param])==dict):
00256                   for k in range(len(a[param])):
00257                      valornotval='value'
00258                      if(a[param][k].has_key('notvalue')):
00259                         valornotval='notvalue'
00260                      if((a[param][k][valornotval])==paramvalue):
00261                         retval=a[param][k].copy()
00262                         retval.pop(valornotval)
00263                         if(subparam != None):
00264                            if(retval.has_key(subparam)):
00265                               retval=retval[subparam]
00266                            else:
00267                               retval=self.itsdefault(subparam)
00268                      else:
00269                         retval=self.itsdefault(subparam)
00270                return retval
00271 
00272 
00273 #
00274 #
00275     def check_params(self, param=None, value=None, ipython_globals=None):
00276       if ipython_globals == None:
00277           myf=self.__globals__
00278       else:
00279           myf=ipython_globals
00280 #      print 'param:', param, 'value:', value
00281       try :
00282          if str(type(value)) != "<type 'instance'>" :
00283             value0 = value
00284             value = myf['cu'].expandparam(param, value)
00285             matchtype = False
00286             if(type(value) == numpy.ndarray):
00287                if(type(value) == type(value0)):
00288                   myf[param] = value.tolist()
00289                else:
00290                   #print 'value:', value, 'value0:', value0
00291                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00292                   myf[param] = value0
00293                   if type(value0) != list :
00294                      matchtype = True
00295             else :
00296                myf[param] = value
00297             value = myf['cu'].verifyparam({param:value})
00298             if matchtype:
00299                value = False
00300       except Exception, instance:
00301          #ignore the exception and just return it unchecked
00302          myf[param] = value
00303       return value
00304 #
00305 #
00306     def description(self, key='calstat', subkey=None):
00307         desc={'calstat': 'Displays statistical information on a calibration table',
00308                'caltable': 'Name of input calibration table',
00309                'axis': 'Which values to use',
00310                'datacolumn': 'Which data column to use',
00311                'useflags': 'Take flagging into account? (not implemented)',
00312 
00313                'async': 'If true the taskname must be started using calstat(...)'
00314               }
00315 
00316 #
00317 # Set subfields defaults if needed
00318 #
00319 
00320         if(desc.has_key(key)) :
00321            return desc[key]
00322 
00323     def itsdefault(self, paramname) :
00324         a = {}
00325         a['caltable']  = ''
00326         a['axis']  = 'amplitude'
00327         a['datacolumn']  = 'gain'
00328         a['useflags']  = True
00329 
00330         #a = sys._getframe(len(inspect.stack())-1).f_globals
00331 
00332         if self.parameters['axis']  == 'amp':
00333             a['datacolumn'] = 'gain'
00334 
00335         if self.parameters['axis']  == 'amplitude':
00336             a['datacolumn'] = 'gain'
00337 
00338         if self.parameters['axis']  == 'phase':
00339             a['datacolumn'] = 'gain'
00340 
00341         if self.parameters['axis']  == 'real':
00342             a['datacolumn'] = 'gain'
00343 
00344         if self.parameters['axis']  == 'imag':
00345             a['datacolumn'] = 'gain'
00346 
00347         if self.parameters['axis']  == 'imaginary':
00348             a['datacolumn'] = 'gain'
00349 
00350         if a.has_key(paramname) :
00351               return a[paramname]
00352 calstat_cli = calstat_cli_()