casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
listvis_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_listvis import listvis
00018 class listvis_cli_:
00019     __name__ = "listvis"
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__ = (listvis_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'options':None, 'datacolumn':None, 'field':None, 'spw':None, 'selectdata':None, 'antenna':None, 'timerange':None, 'correlation':None, 'scan':None, 'feed':None, 'array':None, 'observation':None, 'uvrange':None, 'average':None, 'showflags':None, 'pagerows':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, options=None, datacolumn=None, field=None, spw=None, selectdata=None, antenna=None, timerange=None, correlation=None, scan=None, feed=None, array=None, observation=None, uvrange=None, average=None, showflags=None, pagerows=None, listfile=None,  async=None):
00047 
00048         """List measurement set visibilities.
00049 
00050 This task lists measurement set visibility data under a number of
00051 input selection conditions.  The measurement set data columns that 
00052 can be listed are: the raw data, float_data, corrected data, model data, 
00053 and residual (corrected - model) data.
00054 
00055 The output table format is dynamic.  Field, Spectral Window, and
00056 Channel columns are not displayed if the column contents are uniform.
00057 For example, if "spw = '1'" is specified, the spw column will not be
00058 displayed.  When a column is not displayed, a message is sent to the
00059 logger and terminal indicating that the column values are uniform and 
00060 listing the uniform value.
00061 
00062 Table column descriptions:
00063 
00064 COLUMN NAME       DESCRIPTION
00065 -----------       -----------
00066 Date/Time         Time stamp of data sample (YYMMDD/HH:MM:SS UT)
00067 Intrf             Interferometer baseline (antenna names)
00068 UVDist            uv-distance (units of wavelength)
00069 Fld               Field ID (if more than 1)
00070 SpW               Spectral Window ID (if more than 1)
00071 Chn               Channel number (if more than 1)
00072 (Correlated       Correlated polarizations (eg: RR, LL, XY)
00073   polarization)     Sub-columns are: Amp, Phs, Wt, F
00074 Amp               Visibility amplitude
00075 Phs               Visibility phase (deg)
00076 Wt                Weight of visibility measurement
00077 F                 Flag: 'F' = flagged datum; ' ' = unflagged
00078 UVW               UVW coordinates (meters)
00079 
00080 
00081 Input Parameters:
00082 vis         Name of input visibility file
00083             default: none; example: vis='ngc5921.ms'
00084 
00085 options     List options: default = 'ap'
00086             Not yet implemented for suboptions
00087 
00088 datacolumn  Visibility file data column:
00089             default = 'data':  options are
00090             data, float_data, corrected, model, residual (corrected-model)
00091 
00092 field       Select data based on field id(s) or name(s)
00093             default: ''==>all; example: field='1'
00094             field='0~2' field ids inclusive from 0 to 2
00095             field='3C*' all field names starting with 3C
00096 
00097 spw         Select spectral window, channel to list
00098             default: '0:0' --> spw=0, chan=0
00099             spw='2:34' spectral window 2, channel 34
00100 
00101 selectdata  Toggle the following 7 selection parameters.
00102             default: False; example: selectdata=True
00103             If false, the following parameters are reset
00104             to default values.
00105 
00106       antenna     Select calibration data based on antenna
00107                   default: ''-->all; examples: 
00108                   antenna = '5,6'; antenna index 5 and 6 solutions
00109                   antenna = '05,06'; antenna names '05' and '06 solutions
00110                  
00111       timerange   Select time range to list
00112                   default: ''-->all; examples:
00113                   timerange='10:37:50.1'; list data for this sampling interval
00114                   timerange='<10:37:25'; list data before 10:37:25
00115       
00116       correlation Select polarization correlations to list
00117                   default: ''-->all; examples: 
00118                   correlation='RR LL'; list RR and LL correlations
00119                   correlation='XX XY'; list XX and XY correlations
00120       
00121       scan        Select scans to list
00122                   default: ''-->all; examples:
00123                   scan='2'; list scan 2
00124                   scan='>2'; list scan numbers greater than 2
00125       
00126       feed        (not yet implemented)
00127       
00128       array       (not yet implemented)
00129 
00130       observation Select by observation ID(s).
00131                   default: ''-->all;
00132                   example: observation='0' (select obsID 0)
00133       
00134       uvrange     Select baseline lengths to list.
00135                   default: ''--> all; examples:
00136                   uvrange='<5kl'; less than 5 kilo-wavelengths
00137                   Caution: Input units default to meters.
00138                   Listed units are always wavelengths.
00139 
00140 average     (not yet implemented)
00141 
00142 showflags   (not yet implemented)
00143 
00144 pagerows    rows per page of listing
00145             default: 50; 0 --> do not paginate
00146 
00147 listfile    write output to disk; will not overwrite
00148             default: '' --> write to screen
00149             listfile = 'solutions.txt'
00150 
00151 async       Run asynchronously
00152             default = False; do not run asychronously
00153 
00154    
00155         """
00156         if not hasattr(self, "__globals__") or self.__globals__ == None :
00157            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00158         #casac = self.__globals__['casac']
00159         casalog = self.__globals__['casalog']
00160         #casalog = casac.casac.logsink()
00161         self.__globals__['__last_task'] = 'listvis'
00162         self.__globals__['taskname'] = 'listvis'
00163         ###
00164         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00165         ###
00166         ###
00167         #Handle globals or user over-ride of arguments
00168         #
00169         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00170         useLocalDefaults = False
00171 
00172         for item in function_signature_defaults.iteritems():
00173                 key,val = item
00174                 keyVal = eval(key)
00175                 if (keyVal == None):
00176                         #user hasn't set it - use global/default
00177                         pass
00178                 else:
00179                         #user has set it - use over-ride
00180                         if (key != 'self') :
00181                            useLocalDefaults = True
00182 
00183         myparams = {}
00184         if useLocalDefaults :
00185            for item in function_signature_defaults.iteritems():
00186                key,val = item
00187                keyVal = eval(key)
00188                exec('myparams[key] = keyVal')
00189                self.parameters[key] = keyVal
00190                if (keyVal == None):
00191                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00192                    keyVal = eval(key)
00193                    if(type(keyVal) == dict) :
00194                       if len(keyVal) > 0 :
00195                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00196                       else :
00197                          exec('myparams[key] = ' + key + ' = {}')
00198 
00199         else :
00200             async = self.parameters['async']
00201             myparams['vis'] = vis = self.parameters['vis']
00202             myparams['options'] = options = self.parameters['options']
00203             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00204             myparams['field'] = field = self.parameters['field']
00205             myparams['spw'] = spw = self.parameters['spw']
00206             myparams['selectdata'] = selectdata = self.parameters['selectdata']
00207             myparams['antenna'] = antenna = self.parameters['antenna']
00208             myparams['timerange'] = timerange = self.parameters['timerange']
00209             myparams['correlation'] = correlation = self.parameters['correlation']
00210             myparams['scan'] = scan = self.parameters['scan']
00211             myparams['feed'] = feed = self.parameters['feed']
00212             myparams['array'] = array = self.parameters['array']
00213             myparams['observation'] = observation = self.parameters['observation']
00214             myparams['uvrange'] = uvrange = self.parameters['uvrange']
00215             myparams['average'] = average = self.parameters['average']
00216             myparams['showflags'] = showflags = self.parameters['showflags']
00217             myparams['pagerows'] = pagerows = self.parameters['pagerows']
00218             myparams['listfile'] = listfile = self.parameters['listfile']
00219 
00220 
00221         result = None
00222 
00223 #
00224 #    The following is work around to avoid a bug with current python translation
00225 #
00226         mytmp = {}
00227 
00228         mytmp['vis'] = vis
00229         mytmp['options'] = options
00230         mytmp['datacolumn'] = datacolumn
00231         mytmp['field'] = field
00232         mytmp['spw'] = spw
00233         mytmp['selectdata'] = selectdata
00234         mytmp['antenna'] = antenna
00235         mytmp['timerange'] = timerange
00236         mytmp['correlation'] = correlation
00237         mytmp['scan'] = scan
00238         mytmp['feed'] = feed
00239         mytmp['array'] = array
00240         mytmp['observation'] = observation
00241         mytmp['uvrange'] = uvrange
00242         mytmp['average'] = average
00243         mytmp['showflags'] = showflags
00244         mytmp['pagerows'] = pagerows
00245         mytmp['listfile'] = listfile
00246         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00247         trec = casac.casac.utils().torecord(pathname+'listvis.xml')
00248 
00249         casalog.origin('listvis')
00250         try :
00251           #if not trec.has_key('listvis') or not casac.casac.utils().verify(mytmp, trec['listvis']) :
00252             #return False
00253 
00254           casac.casac.utils().verify(mytmp, trec['listvis'], True)
00255           scriptstr=['']
00256           saveinputs = self.__globals__['saveinputs']
00257           saveinputs('listvis', 'listvis.last', myparams, self.__globals__,scriptstr=scriptstr)
00258           if async :
00259             count = 0
00260             keybase =  time.strftime("%y%m%d.%H%M%S")
00261             key = keybase + "_" + str(count)
00262             while self.__async__.has_key(key) :
00263                count += 1
00264                key = keybase + "_" + str(count)
00265             result = tm.execute('listvis', vis, options, datacolumn, field, spw, selectdata, antenna, timerange, correlation, scan, feed, array, observation, uvrange, average, showflags, pagerows, listfile)
00266             print "Use: "
00267             print "      tm.retrieve(return_value) # to retrieve the status"
00268             print 
00269             self.rkey = key
00270             self.__async__[key] = result
00271           else :
00272               tname = 'listvis'
00273               spaces = ' '*(18-len(tname))
00274               casalog.post('\n##########################################'+
00275                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00276               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00277               result = listvis(vis, options, datacolumn, field, spw, selectdata, antenna, timerange, correlation, scan, feed, array, observation, uvrange, average, showflags, pagerows, listfile)
00278               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00279                            '\n##########################################')
00280 
00281         except Exception, instance:
00282           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00283              raise
00284           else :
00285              #print '**** Error **** ',instance
00286              tname = 'listvis'
00287              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00288              pass
00289 
00290         gc.collect()
00291         return result
00292 #
00293 #
00294 #
00295     def paramgui(self, useGlobals=True, ipython_globals=None):
00296         """
00297         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00298         """
00299         import paramgui
00300         if not hasattr(self, "__globals__") or self.__globals__ == None :
00301            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00302 
00303         if useGlobals:
00304             if ipython_globals == None:
00305                 myf=self.__globals__
00306             else:
00307                 myf=ipython_globals
00308 
00309             paramgui.setGlobals(myf)
00310         else:
00311             paramgui.setGlobals({})
00312 
00313         paramgui.runTask('listvis', myf['_ip'])
00314         paramgui.setGlobals({})
00315 
00316 #
00317 #
00318 #
00319     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00320         if not hasattr(self, "__globals__") or self.__globals__ == None :
00321            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00322         if ipython_globals == None:
00323             myf=self.__globals__
00324         else:
00325             myf=ipython_globals
00326 
00327         a = odict()
00328         a['vis']  = ''
00329         a['options']  = 'ap'
00330         a['datacolumn']  = 'data'
00331         a['field']  = ''
00332         a['spw']  = '*'
00333         a['selectdata']  = False
00334         a['observation']  = ''
00335         a['average']  = ''
00336         a['showflags']  = False
00337         a['pagerows']  = 50
00338         a['listfile']  = ''
00339 
00340         a['async']=False
00341         a['selectdata'] = {
00342                     0:{'value':False}, 
00343                     1:odict([{'value':True}, {'antenna':''}, {'timerange':''}, {'correlation':''}, {'scan':''}, {'feed':''}, {'array':''}, {'observation':''}, {'uvrange':''}])}
00344 
00345 ### This function sets the default values but also will return the list of
00346 ### parameters or the default value of a given parameter
00347         if(param == None):
00348                 myf['__set_default_parameters'](a)
00349         elif(param == 'paramkeys'):
00350                 return a.keys()
00351         else:
00352             if(paramvalue==None and subparam==None):
00353                if(a.has_key(param)):
00354                   return a[param]
00355                else:
00356                   return self.itsdefault(param)
00357             else:
00358                retval=a[param]
00359                if(type(a[param])==dict):
00360                   for k in range(len(a[param])):
00361                      valornotval='value'
00362                      if(a[param][k].has_key('notvalue')):
00363                         valornotval='notvalue'
00364                      if((a[param][k][valornotval])==paramvalue):
00365                         retval=a[param][k].copy()
00366                         retval.pop(valornotval)
00367                         if(subparam != None):
00368                            if(retval.has_key(subparam)):
00369                               retval=retval[subparam]
00370                            else:
00371                               retval=self.itsdefault(subparam)
00372                      else:
00373                         retval=self.itsdefault(subparam)
00374                return retval
00375 
00376 
00377 #
00378 #
00379     def check_params(self, param=None, value=None, ipython_globals=None):
00380       if ipython_globals == None:
00381           myf=self.__globals__
00382       else:
00383           myf=ipython_globals
00384 #      print 'param:', param, 'value:', value
00385       try :
00386          if str(type(value)) != "<type 'instance'>" :
00387             value0 = value
00388             value = myf['cu'].expandparam(param, value)
00389             matchtype = False
00390             if(type(value) == numpy.ndarray):
00391                if(type(value) == type(value0)):
00392                   myf[param] = value.tolist()
00393                else:
00394                   #print 'value:', value, 'value0:', value0
00395                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00396                   myf[param] = value0
00397                   if type(value0) != list :
00398                      matchtype = True
00399             else :
00400                myf[param] = value
00401             value = myf['cu'].verifyparam({param:value})
00402             if matchtype:
00403                value = False
00404       except Exception, instance:
00405          #ignore the exception and just return it unchecked
00406          myf[param] = value
00407       return value
00408 #
00409 #
00410     def description(self, key='listvis', subkey=None):
00411         desc={'listvis': 'List measurement set visibilities.',
00412                'vis': 'Name of input visibility file',
00413                'options': 'List options: ap only ',
00414                'datacolumn': 'Column to list: data, float_data, corrected, model, residual',
00415                'field': 'Field names or index to be listed: \'\'==>all',
00416                'spw': 'Spectral window:channels: \'\*\'==>all, spw=\'1:5~57\'',
00417                'selectdata': 'Other data selection parameters',
00418                'antenna': 'Antenna/baselines: \'\'==>all, antenna = \'3\'',
00419                'timerange': 'Time range: \'\'==>all',
00420                'correlation': 'Correlations: \'\'==>all, correlation = \'RR RL\'',
00421                'scan': 'Scan numbers',
00422                'feed': 'Multi-feed numbers (Not yet implemented)',
00423                'array': 'Array numbers (Not yet implemented)',
00424                'observation': 'Select by observation ID(s)',
00425                'uvrange': 'uv range: \'\'==>all; not yet implemented ',
00426                'average': 'Averaging mode: ''==>none (Not yet implemented)',
00427                'showflags': 'Show flagged data (Not yet implemented)',
00428                'pagerows': 'Rows per page',
00429                'listfile': 'Output file',
00430 
00431                'async': 'If true the taskname must be started using listvis(...)'
00432               }
00433 
00434 #
00435 # Set subfields defaults if needed
00436 #
00437 
00438         if(desc.has_key(key)) :
00439            return desc[key]
00440 
00441     def itsdefault(self, paramname) :
00442         a = {}
00443         a['vis']  = ''
00444         a['options']  = 'ap'
00445         a['datacolumn']  = 'data'
00446         a['field']  = ''
00447         a['spw']  = '*'
00448         a['selectdata']  = False
00449         a['antenna']  = ''
00450         a['timerange']  = ''
00451         a['correlation']  = ''
00452         a['scan']  = ''
00453         a['feed']  = ''
00454         a['array']  = ''
00455         a['observation']  = ''
00456         a['uvrange']  = ''
00457         a['average']  = ''
00458         a['showflags']  = False
00459         a['pagerows']  = 50
00460         a['listfile']  = ''
00461 
00462         #a = sys._getframe(len(inspect.stack())-1).f_globals
00463 
00464         if self.parameters['selectdata']  == True:
00465             a['antenna'] = ''
00466             a['timerange'] = ''
00467             a['correlation'] = ''
00468             a['scan'] = ''
00469             a['feed'] = ''
00470             a['array'] = ''
00471             a['observation'] = ''
00472             a['uvrange'] = ''
00473 
00474         if a.has_key(paramname) :
00475               return a[paramname]
00476 listvis_cli = listvis_cli_()