casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdlist_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_sdlist import sdlist
00018 class sdlist_cli_:
00019     __name__ = "sdlist"
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__ = (sdlist_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'antenna':None, 'scanaverage':None, 'outfile':None, 'overwrite':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, infile=None, antenna=None, scanaverage=None, outfile=None, overwrite=None,  async=None):
00047 
00048         """ASAP SD task: list summary of single dish data
00049         Keyword arguments:
00050         infile -- name of input SD dataset
00051         antenna -- antenna name or id (only effective for MS input). 
00052         scanaverage -- average integrations within scans
00053                 options: (bool) True,False
00054                 default: False
00055                 example: if True, this happens in read-in
00056                 For GBT, set False!
00057         outfile -- Name of output file for summary list
00058                 default: '' (no output file)
00059                 example: 'mysd_summary.txt'
00060         overwrite -- overwrite the output file if already exists
00061                 options: (bool) True,False
00062                 default: False
00063 
00064 
00065         DESCRIPTION:
00066 
00067         Task sdlist lists the scan summary of the dataset after importing
00068         as a scantable into ASAP.  It will optionally output this summary
00069         as file.
00070 
00071         Note that if your PAGER environment variable is set to 'less' and
00072         you have set the 'verbose' ASAP environment variable to True
00073         (the default), then the screen version of the summary will page.
00074         You can disable this for sdlist by setting
00075         sd.rcParams['verbose']=False
00076         before running sdlist.  Set it back afterwards if you want lots
00077         of information.
00078 
00079         WARNING for the GBT raw SDFITS format data as input:
00080         SDtasks are able to handle GBT raw SDFITS format data since the 
00081         data filler is available. However, the functionality is not well 
00082         tested yet, so that there may be unknown bugs.  
00083 
00084   
00085         """
00086         if not hasattr(self, "__globals__") or self.__globals__ == None :
00087            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00088         #casac = self.__globals__['casac']
00089         casalog = self.__globals__['casalog']
00090         #casalog = casac.casac.logsink()
00091         self.__globals__['__last_task'] = 'sdlist'
00092         self.__globals__['taskname'] = 'sdlist'
00093         ###
00094         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00095         ###
00096         ###
00097         #Handle globals or user over-ride of arguments
00098         #
00099         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00100         useLocalDefaults = False
00101 
00102         for item in function_signature_defaults.iteritems():
00103                 key,val = item
00104                 keyVal = eval(key)
00105                 if (keyVal == None):
00106                         #user hasn't set it - use global/default
00107                         pass
00108                 else:
00109                         #user has set it - use over-ride
00110                         if (key != 'self') :
00111                            useLocalDefaults = True
00112 
00113         myparams = {}
00114         if useLocalDefaults :
00115            for item in function_signature_defaults.iteritems():
00116                key,val = item
00117                keyVal = eval(key)
00118                exec('myparams[key] = keyVal')
00119                self.parameters[key] = keyVal
00120                if (keyVal == None):
00121                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00122                    keyVal = eval(key)
00123                    if(type(keyVal) == dict) :
00124                       if len(keyVal) > 0 :
00125                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00126                       else :
00127                          exec('myparams[key] = ' + key + ' = {}')
00128 
00129         else :
00130             async = self.parameters['async']
00131             myparams['infile'] = infile = self.parameters['infile']
00132             myparams['antenna'] = antenna = self.parameters['antenna']
00133             myparams['scanaverage'] = scanaverage = self.parameters['scanaverage']
00134             myparams['outfile'] = outfile = self.parameters['outfile']
00135             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00136 
00137 
00138         result = None
00139 
00140 #
00141 #    The following is work around to avoid a bug with current python translation
00142 #
00143         mytmp = {}
00144 
00145         mytmp['infile'] = infile
00146         mytmp['antenna'] = antenna
00147         mytmp['scanaverage'] = scanaverage
00148         mytmp['outfile'] = outfile
00149         mytmp['overwrite'] = overwrite
00150         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00151         trec = casac.casac.utils().torecord(pathname+'sdlist.xml')
00152 
00153         casalog.origin('sdlist')
00154         try :
00155           #if not trec.has_key('sdlist') or not casac.casac.utils().verify(mytmp, trec['sdlist']) :
00156             #return False
00157 
00158           casac.casac.utils().verify(mytmp, trec['sdlist'], True)
00159           scriptstr=['']
00160           saveinputs = self.__globals__['saveinputs']
00161           saveinputs('sdlist', 'sdlist.last', myparams, self.__globals__,scriptstr=scriptstr)
00162           if async :
00163             count = 0
00164             keybase =  time.strftime("%y%m%d.%H%M%S")
00165             key = keybase + "_" + str(count)
00166             while self.__async__.has_key(key) :
00167                count += 1
00168                key = keybase + "_" + str(count)
00169             result = tm.execute('sdlist', infile, antenna, scanaverage, outfile, overwrite)
00170             print "Use: "
00171             print "      tm.retrieve(return_value) # to retrieve the status"
00172             print 
00173             self.rkey = key
00174             self.__async__[key] = result
00175           else :
00176               tname = 'sdlist'
00177               spaces = ' '*(18-len(tname))
00178               casalog.post('\n##########################################'+
00179                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00180               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00181               result = sdlist(infile, antenna, scanaverage, outfile, overwrite)
00182               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00183                            '\n##########################################')
00184 
00185         except Exception, instance:
00186           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00187              raise
00188           else :
00189              #print '**** Error **** ',instance
00190              tname = 'sdlist'
00191              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00192              pass
00193 
00194         gc.collect()
00195         return result
00196 #
00197 #
00198 #
00199     def paramgui(self, useGlobals=True, ipython_globals=None):
00200         """
00201         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00202         """
00203         import paramgui
00204         if not hasattr(self, "__globals__") or self.__globals__ == None :
00205            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00206 
00207         if useGlobals:
00208             if ipython_globals == None:
00209                 myf=self.__globals__
00210             else:
00211                 myf=ipython_globals
00212 
00213             paramgui.setGlobals(myf)
00214         else:
00215             paramgui.setGlobals({})
00216 
00217         paramgui.runTask('sdlist', myf['_ip'])
00218         paramgui.setGlobals({})
00219 
00220 #
00221 #
00222 #
00223     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00224         if not hasattr(self, "__globals__") or self.__globals__ == None :
00225            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00226         if ipython_globals == None:
00227             myf=self.__globals__
00228         else:
00229             myf=ipython_globals
00230 
00231         a = odict()
00232         a['infile']  = ''
00233         a['antenna']  = 0
00234         a['scanaverage']  = False
00235         a['outfile']  = ''
00236         a['overwrite']  = False
00237 
00238         a['async']=False
00239 
00240 ### This function sets the default values but also will return the list of
00241 ### parameters or the default value of a given parameter
00242         if(param == None):
00243                 myf['__set_default_parameters'](a)
00244         elif(param == 'paramkeys'):
00245                 return a.keys()
00246         else:
00247             if(paramvalue==None and subparam==None):
00248                if(a.has_key(param)):
00249                   return a[param]
00250                else:
00251                   return self.itsdefault(param)
00252             else:
00253                retval=a[param]
00254                if(type(a[param])==dict):
00255                   for k in range(len(a[param])):
00256                      valornotval='value'
00257                      if(a[param][k].has_key('notvalue')):
00258                         valornotval='notvalue'
00259                      if((a[param][k][valornotval])==paramvalue):
00260                         retval=a[param][k].copy()
00261                         retval.pop(valornotval)
00262                         if(subparam != None):
00263                            if(retval.has_key(subparam)):
00264                               retval=retval[subparam]
00265                            else:
00266                               retval=self.itsdefault(subparam)
00267                      else:
00268                         retval=self.itsdefault(subparam)
00269                return retval
00270 
00271 
00272 #
00273 #
00274     def check_params(self, param=None, value=None, ipython_globals=None):
00275       if ipython_globals == None:
00276           myf=self.__globals__
00277       else:
00278           myf=ipython_globals
00279 #      print 'param:', param, 'value:', value
00280       try :
00281          if str(type(value)) != "<type 'instance'>" :
00282             value0 = value
00283             value = myf['cu'].expandparam(param, value)
00284             matchtype = False
00285             if(type(value) == numpy.ndarray):
00286                if(type(value) == type(value0)):
00287                   myf[param] = value.tolist()
00288                else:
00289                   #print 'value:', value, 'value0:', value0
00290                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00291                   myf[param] = value0
00292                   if type(value0) != list :
00293                      matchtype = True
00294             else :
00295                myf[param] = value
00296             value = myf['cu'].verifyparam({param:value})
00297             if matchtype:
00298                value = False
00299       except Exception, instance:
00300          #ignore the exception and just return it unchecked
00301          myf[param] = value
00302       return value
00303 #
00304 #
00305     def description(self, key='sdlist', subkey=None):
00306         desc={'sdlist': 'ASAP SD task: list summary of single dish data',
00307                'infile': 'name of input SD dataset',
00308                'antenna': 'antenna name or id (only effective for MS input)',
00309                'scanaverage': 'average integs within scans (True,False) ',
00310                'outfile': 'Name of output file for summary list',
00311                'overwrite': 'overwrite the output file if already exists',
00312 
00313                'async': 'If true the taskname must be started using sdlist(...)'
00314               }
00315 
00316         if(desc.has_key(key)) :
00317            return desc[key]
00318 
00319     def itsdefault(self, paramname) :
00320         a = {}
00321         a['infile']  = ''
00322         a['antenna']  = 0
00323         a['scanaverage']  = False
00324         a['outfile']  = ''
00325         a['overwrite']  = False
00326 
00327         #a = sys._getframe(len(inspect.stack())-1).f_globals
00328 
00329         if a.has_key(paramname) :
00330               return a[paramname]
00331 sdlist_cli = sdlist_cli_()