casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
uvcontsub3_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_uvcontsub3 import uvcontsub3
00018 class uvcontsub3_cli_:
00019     __name__ = "uvcontsub3"
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__ = (uvcontsub3_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'fitspw':None, 'combine':None, 'fitorder':None, 'field':None, 'spw':None, 'scan':None, 'intent':None, 'correlation':None, 'observation':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, fitspw=None, combine=None, fitorder=None, field=None, spw=None, scan=None, intent=None, correlation=None, observation=None,  async=None):
00047 
00048         """An experimental clone of uvcontsub
00049   
00050         uvcontsub3 is an experimental clone of uvcontsub with the goal of taking
00051         less time and temporary disk space.
00052 
00053         Continuum fitting and subtraction in the uv plane:
00054         
00055         This task estimates the continuum emission by fitting polynomials to
00056         the real and imaginary parts of the spectral windows and channels
00057         selected by fitspw.  This fit represents a model of the continuum in 
00058         all channels.
00059         
00060         The fitted continuum spectrum is subtracted from all channels 
00061         selected in spw, and the result (presumably only line emission)
00062         is stored in a new MS (vis + ".contsub").
00063         It will read from the CORRECTED_DATA column of vis if it is present,
00064         or DATA if it is not.  Whichever column is read is presumed to have
00065         already been calibrated.
00066 
00067         Keyword arguments:
00068         vis -- Name of input visibility file
00069                 default: none; example: vis='ngc5921.ms'
00070 
00071         fitspw -- Selection of spectral windows and channels to use in the
00072                   fit for the continuum, using general spw:chan syntax.
00073                   See the note under combine.
00074                 default: '' (all)
00075                 example: fitspw='0:5~30;40~55'
00076 
00077         combine -- Let the continuum estimation span multiple spectral windows.
00078                    default = '' (Make separate estimates for each spw.)
00079                    combine = 'spw': Necessary when one or more of the spws are
00080                                     completely blanketed by lines, so the estimate
00081                                     must be made in different spws.
00082 
00083         fitorder -- Polynomial order for the fits of the continuum w.r.t.
00084                     frequency.  fitorders > 1 are strongly discouraged
00085                     because high order polynomials have more flexibility, may
00086                     absorb line emission, and tend go wild at the edges of
00087                     fitspw, which is not what you want.
00088 
00089                 default: 0 (constant); example: fitorder=1
00090 
00091         field -- Field selection for continuum estimation and subtraction.
00092                  The estimation and subtraction is done for each selected field
00093                  in turn.  (Run listobs to get lists of the ID and names.)
00094                default: ''=all fields.  If the field string is a non-negative
00095                         integer, it is assumed to be a field index
00096                         otherwise, it is assumed to be a field name
00097                field='0~2'; field ids 0,1,2
00098                field='0,4,5~7'; field ids 0,4,5,6,7
00099                field='3C286,3C295'; fields named 3C286 and 3C295
00100                field = '3,4C*'; field id 3, all names starting with 4C
00101 
00102         spw -- Select spectral windows for the output.
00103                default: ''=all spectral windows
00104                N.B. uvcontsub3 does not yet support exclusion by channels for
00105                     the output.  Meanwhile, use split to further reduce the size
00106                     of the output MS if desired.
00107                spw='0~2,4'; spectral windows 0,1,2,4
00108                spw='<2';  spectral windows less than 2 (i.e. 0,1)
00109 
00110         scan -- Scan number range
00111             default: ''=all
00112 
00113         intent -- Select by scan intent (state).  Case sensitive.
00114             default: '' = all
00115             Examples:
00116             intent = 'CALIBRATE_ATMOSPHERE_REFERENCE'
00117             intent = 'calibrate_atmosphere_reference'.upper() # same as above
00118             # Select states that include one or both of CALIBRATE_WVR.REFERENCE
00119             # or OBSERVE_TARGET_ON_SOURCE.
00120             intent = 'CALIBRATE_WVR.REFERENCE, OBSERVE_TARGET_ON_SOURCE'
00121 
00122         correlation -- Select correlations, e.g. 'rr, ll' or ['XY', 'YX'].
00123                        default '' (all).
00124 
00125         observation -- Select by observation ID(s).
00126                        default: '' = all
00127 
00128 
00129         """
00130         if not hasattr(self, "__globals__") or self.__globals__ == None :
00131            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00132         #casac = self.__globals__['casac']
00133         casalog = self.__globals__['casalog']
00134         #casalog = casac.casac.logsink()
00135         self.__globals__['__last_task'] = 'uvcontsub3'
00136         self.__globals__['taskname'] = 'uvcontsub3'
00137         ###
00138         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00139         ###
00140         ###
00141         #Handle globals or user over-ride of arguments
00142         #
00143         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00144         useLocalDefaults = False
00145 
00146         for item in function_signature_defaults.iteritems():
00147                 key,val = item
00148                 keyVal = eval(key)
00149                 if (keyVal == None):
00150                         #user hasn't set it - use global/default
00151                         pass
00152                 else:
00153                         #user has set it - use over-ride
00154                         if (key != 'self') :
00155                            useLocalDefaults = True
00156 
00157         myparams = {}
00158         if useLocalDefaults :
00159            for item in function_signature_defaults.iteritems():
00160                key,val = item
00161                keyVal = eval(key)
00162                exec('myparams[key] = keyVal')
00163                self.parameters[key] = keyVal
00164                if (keyVal == None):
00165                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00166                    keyVal = eval(key)
00167                    if(type(keyVal) == dict) :
00168                       if len(keyVal) > 0 :
00169                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00170                       else :
00171                          exec('myparams[key] = ' + key + ' = {}')
00172 
00173         else :
00174             async = self.parameters['async']
00175             myparams['vis'] = vis = self.parameters['vis']
00176             myparams['fitspw'] = fitspw = self.parameters['fitspw']
00177             myparams['combine'] = combine = self.parameters['combine']
00178             myparams['fitorder'] = fitorder = self.parameters['fitorder']
00179             myparams['field'] = field = self.parameters['field']
00180             myparams['spw'] = spw = self.parameters['spw']
00181             myparams['scan'] = scan = self.parameters['scan']
00182             myparams['intent'] = intent = self.parameters['intent']
00183             myparams['correlation'] = correlation = self.parameters['correlation']
00184             myparams['observation'] = observation = self.parameters['observation']
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['fitspw'] = fitspw
00196         mytmp['combine'] = combine
00197         mytmp['fitorder'] = fitorder
00198         mytmp['field'] = field
00199         mytmp['spw'] = spw
00200         mytmp['scan'] = scan
00201         mytmp['intent'] = intent
00202         mytmp['correlation'] = correlation
00203         mytmp['observation'] = observation
00204         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00205         trec = casac.casac.utils().torecord(pathname+'uvcontsub3.xml')
00206 
00207         casalog.origin('uvcontsub3')
00208         try :
00209           #if not trec.has_key('uvcontsub3') or not casac.casac.utils().verify(mytmp, trec['uvcontsub3']) :
00210             #return False
00211 
00212           casac.casac.utils().verify(mytmp, trec['uvcontsub3'], True)
00213           scriptstr=['']
00214           saveinputs = self.__globals__['saveinputs']
00215           saveinputs('uvcontsub3', 'uvcontsub3.last', myparams, self.__globals__,scriptstr=scriptstr)
00216           if async :
00217             count = 0
00218             keybase =  time.strftime("%y%m%d.%H%M%S")
00219             key = keybase + "_" + str(count)
00220             while self.__async__.has_key(key) :
00221                count += 1
00222                key = keybase + "_" + str(count)
00223             result = tm.execute('uvcontsub3', vis, fitspw, combine, fitorder, field, spw, scan, intent, correlation, observation)
00224             print "Use: "
00225             print "      tm.retrieve(return_value) # to retrieve the status"
00226             print 
00227             self.rkey = key
00228             self.__async__[key] = result
00229           else :
00230               tname = 'uvcontsub3'
00231               spaces = ' '*(18-len(tname))
00232               casalog.post('\n##########################################'+
00233                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00234               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00235               result = uvcontsub3(vis, fitspw, combine, fitorder, field, spw, scan, intent, correlation, observation)
00236               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00237                            '\n##########################################')
00238 
00239         except Exception, instance:
00240           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00241              raise
00242           else :
00243              #print '**** Error **** ',instance
00244              tname = 'uvcontsub3'
00245              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00246              pass
00247 
00248         gc.collect()
00249         return result
00250 #
00251 #
00252 #
00253     def paramgui(self, useGlobals=True, ipython_globals=None):
00254         """
00255         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00256         """
00257         import paramgui
00258         if not hasattr(self, "__globals__") or self.__globals__ == None :
00259            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00260 
00261         if useGlobals:
00262             if ipython_globals == None:
00263                 myf=self.__globals__
00264             else:
00265                 myf=ipython_globals
00266 
00267             paramgui.setGlobals(myf)
00268         else:
00269             paramgui.setGlobals({})
00270 
00271         paramgui.runTask('uvcontsub3', myf['_ip'])
00272         paramgui.setGlobals({})
00273 
00274 #
00275 #
00276 #
00277     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00278         if not hasattr(self, "__globals__") or self.__globals__ == None :
00279            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00280         if ipython_globals == None:
00281             myf=self.__globals__
00282         else:
00283             myf=ipython_globals
00284 
00285         a = odict()
00286         a['vis']  = ''
00287         a['fitspw']  = ''
00288         a['combine']  = ''
00289         a['fitorder']  = 0
00290         a['field']  = ''
00291         a['spw']  = ''
00292         a['scan']  = ''
00293         a['intent']  = ''
00294         a['correlation']  = ''
00295         a['observation']  = ''
00296 
00297         a['async']=False
00298 
00299 ### This function sets the default values but also will return the list of
00300 ### parameters or the default value of a given parameter
00301         if(param == None):
00302                 myf['__set_default_parameters'](a)
00303         elif(param == 'paramkeys'):
00304                 return a.keys()
00305         else:
00306             if(paramvalue==None and subparam==None):
00307                if(a.has_key(param)):
00308                   return a[param]
00309                else:
00310                   return self.itsdefault(param)
00311             else:
00312                retval=a[param]
00313                if(type(a[param])==dict):
00314                   for k in range(len(a[param])):
00315                      valornotval='value'
00316                      if(a[param][k].has_key('notvalue')):
00317                         valornotval='notvalue'
00318                      if((a[param][k][valornotval])==paramvalue):
00319                         retval=a[param][k].copy()
00320                         retval.pop(valornotval)
00321                         if(subparam != None):
00322                            if(retval.has_key(subparam)):
00323                               retval=retval[subparam]
00324                            else:
00325                               retval=self.itsdefault(subparam)
00326                      else:
00327                         retval=self.itsdefault(subparam)
00328                return retval
00329 
00330 
00331 #
00332 #
00333     def check_params(self, param=None, value=None, ipython_globals=None):
00334       if ipython_globals == None:
00335           myf=self.__globals__
00336       else:
00337           myf=ipython_globals
00338 #      print 'param:', param, 'value:', value
00339       try :
00340          if str(type(value)) != "<type 'instance'>" :
00341             value0 = value
00342             value = myf['cu'].expandparam(param, value)
00343             matchtype = False
00344             if(type(value) == numpy.ndarray):
00345                if(type(value) == type(value0)):
00346                   myf[param] = value.tolist()
00347                else:
00348                   #print 'value:', value, 'value0:', value0
00349                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00350                   myf[param] = value0
00351                   if type(value0) != list :
00352                      matchtype = True
00353             else :
00354                myf[param] = value
00355             value = myf['cu'].verifyparam({param:value})
00356             if matchtype:
00357                value = False
00358       except Exception, instance:
00359          #ignore the exception and just return it unchecked
00360          myf[param] = value
00361       return value
00362 #
00363 #
00364     def description(self, key='uvcontsub3', subkey=None):
00365         desc={'uvcontsub3': 'An experimental clone of uvcontsub',
00366                'vis': 'Name of input MS.  Output goes to vis + ".contsub"',
00367                'fitspw': 'Spectral window:channel selection for fitting the continuum',
00368                'combine': 'Data axes to combine for the continuum estimation (none ('') or spw)',
00369                'fitorder': 'Polynomial order for the fits',
00370                'field': 'Select field(s) using id(s) or name(s)',
00371                'spw': 'Spectral window selection for output',
00372                'scan': 'Select data by scan numbers',
00373                'intent': 'Select data by scan intents',
00374                'correlation': 'Select correlations',
00375                'observation': 'Select by observation ID(s)',
00376 
00377                'async': 'If true the taskname must be started using uvcontsub3(...)'
00378               }
00379 
00380         if(desc.has_key(key)) :
00381            return desc[key]
00382 
00383     def itsdefault(self, paramname) :
00384         a = {}
00385         a['vis']  = ''
00386         a['fitspw']  = ''
00387         a['combine']  = ''
00388         a['fitorder']  = 0
00389         a['field']  = ''
00390         a['spw']  = ''
00391         a['scan']  = ''
00392         a['intent']  = ''
00393         a['correlation']  = ''
00394         a['observation']  = ''
00395 
00396         #a = sys._getframe(len(inspect.stack())-1).f_globals
00397 
00398         if a.has_key(paramname) :
00399               return a[paramname]
00400 uvcontsub3_cli = uvcontsub3_cli_()