casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
listobs_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_listobs import listobs
00018 class listobs_cli_:
00019     __name__ = "listobs"
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__ = (listobs_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'selectdata':None, 'spw':None, 'field':None, 'antenna':None, 'uvrange':None, 'timerange':None, 'correlation':None, 'scan':None, 'intent':None, 'feed':None, 'array':None, 'observation':None, 'verbose':None, 'listfile':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, selectdata=None, spw=None, field=None, antenna=None, uvrange=None, timerange=None, correlation=None, scan=None, intent=None, feed=None, array=None, observation=None, verbose=None, listfile=None,  async=None):
00047 
00048         """List the summary of a data set in the logger or in a file
00049 
00050        List the summary information of a data set in the logger or in a file, based on
00051        a data selection. Only rows can be selected and printed. No in-row selection is
00052        possible (channel or correlation). Refer to the task listvis to list visibilites.
00053 
00054        Lists the following properties of a measurement set:
00055        scan list, field list, spectral window list with
00056        correlators, antenna locations, ms table information.
00057 
00058        Keyword arguments:
00059        vis -- Name of input visibility file
00060                default: none. example: vis='ngc5921.ms'
00061        
00062        selectdata -- Select a subset of data for flagging
00063                     default: False
00064                     options: True,False
00065                     The summary listing will only apply to the specified selection.
00066 
00067               antenna -- Select data based on baseline
00068                     default: '' (all); example: antenna='5&6' baseline 5-6
00069                     antenna='5&6;7&8' #baseline 5-6 and 7-8
00070                     antenna='5' # all cross-correlation baselines between antenna 5 and all other available
00071                                   antennas
00072                     antenna='5,6' # all baselines with antennas 5 and 6
00073                     antenna='1&&1' # only the auto-correlation baselines for antenna 1
00074                     antenna='1&&*' # cross and auto-correlation baselines between antenna 1
00075                                              and all other available antennas
00076                     antenna='1~7&&&' # only the auto-correlation baselines for antennas in range 1~7
00077               spw -- Select data based on spectral window and channels
00078                     default: '' (all); example: spw='1'
00079                     spw='<2' #spectral windows less than 2
00080                     spw='>1' #spectral windows greater than 1
00081               correlation -- Correlation types
00082                     default: '' (all);
00083                     example: correlation='RR LL'
00084               field -- Select data based on field id(s) or name(s)
00085                     default: '' (all); example: field='1'
00086                     field='0~2' # field ids inclusive from 0 to 2
00087                     field='3C*' # all field names starting with 3C
00088               uvrange -- Select data within uvrange (default units meters)
00089                     default: '' (all); example:
00090                     uvrange='0~1000klambda'; uvrange from 0-1000 kilo-lamgda
00091                     uvrange='>4klamda';uvranges greater than 4 kilo-lambda
00092                     uvrange='0~1000km'; uvrange in kilometers
00093               timerange  -- Select data based on time range:
00094                     default = '' (all); example,
00095                     timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00096                     Note: YYYY/MM/DD can be dropped as needed:
00097                     timerange='09:14:0~09:54:0' # this time range
00098                     timerange='09:44:00' # data within one integration of time
00099                     timerange='>10:24:00' # data after this time
00100                     timerange='09:44:00+00:13:00' #data 13 minutes after time
00101               scan -- Select data based on scan number
00102                     default: '' (all); example: scan='>3'
00103               intent -- Select data based on observation intent
00104                     default: '' (all); example: intent='*CAL*,*BAND*'
00105               feed -- Selection based on the feed - NOT IMPLEMENTED YET
00106               array -- Selection based on the antenna array
00107               observation -- Selection based on the observation ID
00108                     default: '' (all); example: observation='1' or observation=1
00109 
00110 
00111        verbose -- level of detail
00112              verbose=True: (default); scan and antenna lists
00113              verbose=False: less information
00114              
00115        listfile -- name of disk file to write output.
00116                default: None. Example: listfile='list.txt'
00117 
00118 
00119       The 'Int (s)' column is the average of the MS's INTERVAL column
00120       for each scan, so in a time-averaged MS 'Int' = 9.83s more likely
00121       means 5 10s integrations and 1 9s integration (timebin) than 6
00122       9.83s integrations. 
00123  
00124         """
00125         if not hasattr(self, "__globals__") or self.__globals__ == None :
00126            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00127         #casac = self.__globals__['casac']
00128         casalog = self.__globals__['casalog']
00129         #casalog = casac.casac.logsink()
00130         self.__globals__['__last_task'] = 'listobs'
00131         self.__globals__['taskname'] = 'listobs'
00132         ###
00133         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00134         ###
00135         ###
00136         #Handle globals or user over-ride of arguments
00137         #
00138         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00139         useLocalDefaults = False
00140 
00141         for item in function_signature_defaults.iteritems():
00142                 key,val = item
00143                 keyVal = eval(key)
00144                 if (keyVal == None):
00145                         #user hasn't set it - use global/default
00146                         pass
00147                 else:
00148                         #user has set it - use over-ride
00149                         if (key != 'self') :
00150                            useLocalDefaults = True
00151 
00152         myparams = {}
00153         if useLocalDefaults :
00154            for item in function_signature_defaults.iteritems():
00155                key,val = item
00156                keyVal = eval(key)
00157                exec('myparams[key] = keyVal')
00158                self.parameters[key] = keyVal
00159                if (keyVal == None):
00160                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00161                    keyVal = eval(key)
00162                    if(type(keyVal) == dict) :
00163                       if len(keyVal) > 0 :
00164                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00165                       else :
00166                          exec('myparams[key] = ' + key + ' = {}')
00167 
00168         else :
00169             async = self.parameters['async']
00170             myparams['vis'] = vis = self.parameters['vis']
00171             myparams['selectdata'] = selectdata = self.parameters['selectdata']
00172             myparams['spw'] = spw = self.parameters['spw']
00173             myparams['field'] = field = self.parameters['field']
00174             myparams['antenna'] = antenna = self.parameters['antenna']
00175             myparams['uvrange'] = uvrange = self.parameters['uvrange']
00176             myparams['timerange'] = timerange = self.parameters['timerange']
00177             myparams['correlation'] = correlation = self.parameters['correlation']
00178             myparams['scan'] = scan = self.parameters['scan']
00179             myparams['intent'] = intent = self.parameters['intent']
00180             myparams['feed'] = feed = self.parameters['feed']
00181             myparams['array'] = array = self.parameters['array']
00182             myparams['observation'] = observation = self.parameters['observation']
00183             myparams['verbose'] = verbose = self.parameters['verbose']
00184             myparams['listfile'] = listfile = self.parameters['listfile']
00185 
00186 
00187         result = None
00188 
00189 #
00190 #    The following is work around to avoid a bug with current python translation
00191 #
00192         mytmp = {}
00193 
00194         mytmp['vis'] = vis
00195         mytmp['selectdata'] = selectdata
00196         mytmp['spw'] = spw
00197         mytmp['field'] = field
00198         mytmp['antenna'] = antenna
00199         mytmp['uvrange'] = uvrange
00200         mytmp['timerange'] = timerange
00201         mytmp['correlation'] = correlation
00202         mytmp['scan'] = scan
00203         mytmp['intent'] = intent
00204         mytmp['feed'] = feed
00205         mytmp['array'] = array
00206         mytmp['observation'] = observation
00207         mytmp['verbose'] = verbose
00208         mytmp['listfile'] = listfile
00209         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00210         trec = casac.casac.utils().torecord(pathname+'listobs.xml')
00211 
00212         casalog.origin('listobs')
00213         try :
00214           #if not trec.has_key('listobs') or not casac.casac.utils().verify(mytmp, trec['listobs']) :
00215             #return False
00216 
00217           casac.casac.utils().verify(mytmp, trec['listobs'], True)
00218           scriptstr=['']
00219           saveinputs = self.__globals__['saveinputs']
00220           saveinputs('listobs', 'listobs.last', myparams, self.__globals__,scriptstr=scriptstr)
00221           if async :
00222             count = 0
00223             keybase =  time.strftime("%y%m%d.%H%M%S")
00224             key = keybase + "_" + str(count)
00225             while self.__async__.has_key(key) :
00226                count += 1
00227                key = keybase + "_" + str(count)
00228             result = tm.execute('listobs', vis, selectdata, spw, field, antenna, uvrange, timerange, correlation, scan, intent, feed, array, observation, verbose, listfile)
00229             print "Use: "
00230             print "      tm.retrieve(return_value) # to retrieve the status"
00231             print 
00232             self.rkey = key
00233             self.__async__[key] = result
00234           else :
00235               tname = 'listobs'
00236               spaces = ' '*(18-len(tname))
00237               casalog.post('\n##########################################'+
00238                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00239               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00240               result = listobs(vis, selectdata, spw, field, antenna, uvrange, timerange, correlation, scan, intent, feed, array, observation, verbose, listfile)
00241               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00242                            '\n##########################################')
00243 
00244         except Exception, instance:
00245           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00246              raise
00247           else :
00248              #print '**** Error **** ',instance
00249              tname = 'listobs'
00250              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00251              pass
00252 
00253         gc.collect()
00254         return result
00255 #
00256 #
00257 #
00258     def paramgui(self, useGlobals=True, ipython_globals=None):
00259         """
00260         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00261         """
00262         import paramgui
00263         if not hasattr(self, "__globals__") or self.__globals__ == None :
00264            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00265 
00266         if useGlobals:
00267             if ipython_globals == None:
00268                 myf=self.__globals__
00269             else:
00270                 myf=ipython_globals
00271 
00272             paramgui.setGlobals(myf)
00273         else:
00274             paramgui.setGlobals({})
00275 
00276         paramgui.runTask('listobs', myf['_ip'])
00277         paramgui.setGlobals({})
00278 
00279 #
00280 #
00281 #
00282     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00283         if not hasattr(self, "__globals__") or self.__globals__ == None :
00284            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00285         if ipython_globals == None:
00286             myf=self.__globals__
00287         else:
00288             myf=ipython_globals
00289 
00290         a = odict()
00291         a['vis']  = ''
00292         a['selectdata']  = True
00293         a['verbose']  = True
00294         a['listfile']  = ''
00295 
00296         a['async']=False
00297         a['selectdata'] = {
00298                     0:odict([{'value':True}, {'field':''}, {'spw':''}, {'antenna':''}, {'timerange':''}, {'correlation':''}, {'scan':''}, {'intent':''}, {'feed':''}, {'array':''}, {'uvrange':''}, {'observation':''}]), 
00299                     1:{'value':False}}
00300 
00301 ### This function sets the default values but also will return the list of
00302 ### parameters or the default value of a given parameter
00303         if(param == None):
00304                 myf['__set_default_parameters'](a)
00305         elif(param == 'paramkeys'):
00306                 return a.keys()
00307         else:
00308             if(paramvalue==None and subparam==None):
00309                if(a.has_key(param)):
00310                   return a[param]
00311                else:
00312                   return self.itsdefault(param)
00313             else:
00314                retval=a[param]
00315                if(type(a[param])==dict):
00316                   for k in range(len(a[param])):
00317                      valornotval='value'
00318                      if(a[param][k].has_key('notvalue')):
00319                         valornotval='notvalue'
00320                      if((a[param][k][valornotval])==paramvalue):
00321                         retval=a[param][k].copy()
00322                         retval.pop(valornotval)
00323                         if(subparam != None):
00324                            if(retval.has_key(subparam)):
00325                               retval=retval[subparam]
00326                            else:
00327                               retval=self.itsdefault(subparam)
00328                      else:
00329                         retval=self.itsdefault(subparam)
00330                return retval
00331 
00332 
00333 #
00334 #
00335     def check_params(self, param=None, value=None, ipython_globals=None):
00336       if ipython_globals == None:
00337           myf=self.__globals__
00338       else:
00339           myf=ipython_globals
00340 #      print 'param:', param, 'value:', value
00341       try :
00342          if str(type(value)) != "<type 'instance'>" :
00343             value0 = value
00344             value = myf['cu'].expandparam(param, value)
00345             matchtype = False
00346             if(type(value) == numpy.ndarray):
00347                if(type(value) == type(value0)):
00348                   myf[param] = value.tolist()
00349                else:
00350                   #print 'value:', value, 'value0:', value0
00351                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00352                   myf[param] = value0
00353                   if type(value0) != list :
00354                      matchtype = True
00355             else :
00356                myf[param] = value
00357             value = myf['cu'].verifyparam({param:value})
00358             if matchtype:
00359                value = False
00360       except Exception, instance:
00361          #ignore the exception and just return it unchecked
00362          myf[param] = value
00363       return value
00364 #
00365 #
00366     def description(self, key='listobs', subkey=None):
00367         desc={'listobs': 'List the summary of a data set in the logger or in a file',
00368                'vis': 'Name of input visibility file (MS)',
00369                'selectdata': 'Data selection parameters',
00370                'spw': 'spectral-window/frequency/channel',
00371                'field': 'Field names or field index numbers: \'\'==>all, field=\'0~2,3C286\'',
00372                'antenna': 'antenna/baselines: \'\'==>all, antenna =\'3,VA04\'',
00373                'uvrange': 'uv range: \'\'==>all; uvrange =\'0~100klambda\', default units=meters',
00374                'timerange': 'time range: \'\'==>all,timerange=\'09:14:0~09:54:0\'',
00375                'correlation': 'Select data based on correlation',
00376                'scan': 'scan numbers: \'\'==>all',
00377                'intent': 'Select data based on observation intent: \'\'==>all',
00378                'feed': 'multi-feed numbers: Not yet implemented',
00379                'array': '(sub)array numbers: \'\'==>all',
00380                'observation': 'Select data based on observation ID: \'\'==>all',
00381                'verbose': '',
00382                'listfile': 'Name of disk file to write output: \'\'==>to terminal',
00383 
00384                'async': 'If true the taskname must be started using listobs(...)'
00385               }
00386 
00387 #
00388 # Set subfields defaults if needed
00389 #
00390 
00391         if(desc.has_key(key)) :
00392            return desc[key]
00393 
00394     def itsdefault(self, paramname) :
00395         a = {}
00396         a['vis']  = ''
00397         a['selectdata']  = True
00398         a['spw']  = ''
00399         a['field']  = ''
00400         a['antenna']  = ''
00401         a['uvrange']  = ''
00402         a['timerange']  = ''
00403         a['correlation']  = ''
00404         a['scan']  = ''
00405         a['intent']  = ''
00406         a['feed']  = ''
00407         a['array']  = ''
00408         a['observation']  = ''
00409         a['verbose']  = True
00410         a['listfile']  = ''
00411 
00412         #a = sys._getframe(len(inspect.stack())-1).f_globals
00413 
00414         if self.parameters['selectdata']  == True:
00415             a['field'] = ''
00416             a['spw'] = ''
00417             a['antenna'] = ''
00418             a['timerange'] = ''
00419             a['correlation'] = ''
00420             a['scan'] = ''
00421             a['intent'] = ''
00422             a['feed'] = ''
00423             a['array'] = ''
00424             a['uvrange'] = ''
00425             a['observation'] = ''
00426 
00427         if a.has_key(paramname) :
00428               return a[paramname]
00429 listobs_cli = listobs_cli_()