casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
listsdm_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_listsdm import listsdm
00018 class listsdm_cli_:
00019     __name__ = "listsdm"
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__ = (listsdm_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'sdm':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, sdm=None,  async=None):
00047 
00048         """Lists observation information present in an SDM directory.
00049 
00050         The listsdm task reads SDM XML tables, processes the
00051         observation information contained therein, and prints this
00052         information to the CASA log.  It will also return a dictionary
00053         keyed on scan number.  The dictionary contains the following
00054         information:
00055 
00056         'baseband'   list of baseband name(s)
00057         'chanwidth'  list of channel widths (Hz)
00058         'end'        observation end time (UTC)
00059         'field'      field ID
00060         'intent'     scan intent(s)
00061         'nchan'      list of number of channels
00062         'nsubs'      number of subscans
00063         'reffreq'    list of reference frequencies (Hz)
00064         'source'     source name
00065         'spws'       list of spectral windows
00066         'start'      observation start time (UTC)
00067         'timerange'  start time - end time range (UTC)
00068         
00069         Example:
00070 
00071         myscans = listsdm(sdm='AS1039_sb1382796_2_000.55368.51883247685')
00072 
00073         Prints information about the requested SDM to the CASA logger
00074         and returns a dictionary with scan information in 'myscans'.
00075 
00076         Keyword argument:
00077 
00078         sdm -- Name of input SDM directory.  
00079                example: sdm='AG836_sb1377811_1.55345.300883159725'
00080                 
00081   
00082         """
00083         if not hasattr(self, "__globals__") or self.__globals__ == None :
00084            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00085         #casac = self.__globals__['casac']
00086         casalog = self.__globals__['casalog']
00087         #casalog = casac.casac.logsink()
00088         self.__globals__['__last_task'] = 'listsdm'
00089         self.__globals__['taskname'] = 'listsdm'
00090         ###
00091         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00092         ###
00093         ###
00094         #Handle globals or user over-ride of arguments
00095         #
00096         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00097         useLocalDefaults = False
00098 
00099         for item in function_signature_defaults.iteritems():
00100                 key,val = item
00101                 keyVal = eval(key)
00102                 if (keyVal == None):
00103                         #user hasn't set it - use global/default
00104                         pass
00105                 else:
00106                         #user has set it - use over-ride
00107                         if (key != 'self') :
00108                            useLocalDefaults = True
00109 
00110         myparams = {}
00111         if useLocalDefaults :
00112            for item in function_signature_defaults.iteritems():
00113                key,val = item
00114                keyVal = eval(key)
00115                exec('myparams[key] = keyVal')
00116                self.parameters[key] = keyVal
00117                if (keyVal == None):
00118                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00119                    keyVal = eval(key)
00120                    if(type(keyVal) == dict) :
00121                       if len(keyVal) > 0 :
00122                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00123                       else :
00124                          exec('myparams[key] = ' + key + ' = {}')
00125 
00126         else :
00127             async = self.parameters['async']
00128             myparams['sdm'] = sdm = self.parameters['sdm']
00129 
00130 
00131         result = None
00132 
00133 #
00134 #    The following is work around to avoid a bug with current python translation
00135 #
00136         mytmp = {}
00137 
00138         mytmp['sdm'] = sdm
00139         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00140         trec = casac.casac.utils().torecord(pathname+'listsdm.xml')
00141 
00142         casalog.origin('listsdm')
00143         try :
00144           #if not trec.has_key('listsdm') or not casac.casac.utils().verify(mytmp, trec['listsdm']) :
00145             #return False
00146 
00147           casac.casac.utils().verify(mytmp, trec['listsdm'], True)
00148           scriptstr=['']
00149           saveinputs = self.__globals__['saveinputs']
00150           saveinputs('listsdm', 'listsdm.last', myparams, self.__globals__,scriptstr=scriptstr)
00151           if async :
00152             count = 0
00153             keybase =  time.strftime("%y%m%d.%H%M%S")
00154             key = keybase + "_" + str(count)
00155             while self.__async__.has_key(key) :
00156                count += 1
00157                key = keybase + "_" + str(count)
00158             result = tm.execute('listsdm', sdm)
00159             print "Use: "
00160             print "      tm.retrieve(return_value) # to retrieve the status"
00161             print 
00162             self.rkey = key
00163             self.__async__[key] = result
00164           else :
00165               tname = 'listsdm'
00166               spaces = ' '*(18-len(tname))
00167               casalog.post('\n##########################################'+
00168                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00169               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00170               result = listsdm(sdm)
00171               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00172                            '\n##########################################')
00173 
00174         except Exception, instance:
00175           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00176              raise
00177           else :
00178              #print '**** Error **** ',instance
00179              tname = 'listsdm'
00180              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00181              pass
00182 
00183         gc.collect()
00184         return result
00185 #
00186 #
00187 #
00188     def paramgui(self, useGlobals=True, ipython_globals=None):
00189         """
00190         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00191         """
00192         import paramgui
00193         if not hasattr(self, "__globals__") or self.__globals__ == None :
00194            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00195 
00196         if useGlobals:
00197             if ipython_globals == None:
00198                 myf=self.__globals__
00199             else:
00200                 myf=ipython_globals
00201 
00202             paramgui.setGlobals(myf)
00203         else:
00204             paramgui.setGlobals({})
00205 
00206         paramgui.runTask('listsdm', myf['_ip'])
00207         paramgui.setGlobals({})
00208 
00209 #
00210 #
00211 #
00212     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00213         if not hasattr(self, "__globals__") or self.__globals__ == None :
00214            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00215         if ipython_globals == None:
00216             myf=self.__globals__
00217         else:
00218             myf=ipython_globals
00219 
00220         a = odict()
00221         a['sdm']  = ''
00222 
00223         a['async']=False
00224 
00225 ### This function sets the default values but also will return the list of
00226 ### parameters or the default value of a given parameter
00227         if(param == None):
00228                 myf['__set_default_parameters'](a)
00229         elif(param == 'paramkeys'):
00230                 return a.keys()
00231         else:
00232             if(paramvalue==None and subparam==None):
00233                if(a.has_key(param)):
00234                   return a[param]
00235                else:
00236                   return self.itsdefault(param)
00237             else:
00238                retval=a[param]
00239                if(type(a[param])==dict):
00240                   for k in range(len(a[param])):
00241                      valornotval='value'
00242                      if(a[param][k].has_key('notvalue')):
00243                         valornotval='notvalue'
00244                      if((a[param][k][valornotval])==paramvalue):
00245                         retval=a[param][k].copy()
00246                         retval.pop(valornotval)
00247                         if(subparam != None):
00248                            if(retval.has_key(subparam)):
00249                               retval=retval[subparam]
00250                            else:
00251                               retval=self.itsdefault(subparam)
00252                      else:
00253                         retval=self.itsdefault(subparam)
00254                return retval
00255 
00256 
00257 #
00258 #
00259     def check_params(self, param=None, value=None, ipython_globals=None):
00260       if ipython_globals == None:
00261           myf=self.__globals__
00262       else:
00263           myf=ipython_globals
00264 #      print 'param:', param, 'value:', value
00265       try :
00266          if str(type(value)) != "<type 'instance'>" :
00267             value0 = value
00268             value = myf['cu'].expandparam(param, value)
00269             matchtype = False
00270             if(type(value) == numpy.ndarray):
00271                if(type(value) == type(value0)):
00272                   myf[param] = value.tolist()
00273                else:
00274                   #print 'value:', value, 'value0:', value0
00275                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00276                   myf[param] = value0
00277                   if type(value0) != list :
00278                      matchtype = True
00279             else :
00280                myf[param] = value
00281             value = myf['cu'].verifyparam({param:value})
00282             if matchtype:
00283                value = False
00284       except Exception, instance:
00285          #ignore the exception and just return it unchecked
00286          myf[param] = value
00287       return value
00288 #
00289 #
00290     def description(self, key='listsdm', subkey=None):
00291         desc={'listsdm': 'Lists observation information present in an SDM directory.',
00292                'sdm': 'Name of input SDM directory',
00293 
00294                'async': 'If true the taskname must be started using listsdm(...)'
00295               }
00296 
00297         if(desc.has_key(key)) :
00298            return desc[key]
00299 
00300     def itsdefault(self, paramname) :
00301         a = {}
00302         a['sdm']  = ''
00303 
00304         #a = sys._getframe(len(inspect.stack())-1).f_globals
00305 
00306         if a.has_key(paramname) :
00307               return a[paramname]
00308 listsdm_cli = listsdm_cli_()