casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
uvcontsub_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_uvcontsub import uvcontsub
00018 class uvcontsub_cli_:
00019     __name__ = "uvcontsub"
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__ = (uvcontsub_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'fitspw':None, 'combine':None, 'solint':None, 'fitorder':None, 'spw':None, 'want_cont':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, field=None, fitspw=None, combine=None, solint=None, fitorder=None, spw=None, want_cont=None,  async=None):
00047 
00048         """Continuum fitting and subtraction in the uv plane
00049 
00050         Continuum fitting and subtraction in the uv plane:
00051         
00052         This task estimates the continuum emission by fitting polynomials to
00053         the real and imaginary parts of the spectral windows and channels
00054         selected by fitspw.  This fit represents a model of the continuum in 
00055         all channels.
00056         
00057         The fitted continuum spectrum is subtracted from all channels 
00058         selected in spw, and the result (presumably only line emission)
00059         is stored in a new MS (vis + ".contsub").
00060         It will read from the CORRECTED_DATA column of vis if it is present,
00061         or DATA if it is not.  Whichever column is read is presumed to have
00062         already been calibrated.
00063 
00064         If want_cont is True, the continuum fit is placed in a second new MS
00065         (vis + '.cont').  N.B. because the continuum model is necessarily a
00066         smoothed fit, images made with it are liable to have their field of
00067         view reduced in some strange way.  Images of the continuum should be
00068         made by simply excluding the line channels (and probably averaging the
00069         remaining ones) in clean.
00070 
00071         Keyword arguments:
00072         vis -- Name of input visibility file
00073                 default: none; example: vis='ngc5921.ms'
00074         field -- Field selection for continuum estimation and subtraction.
00075                  The estimation and subtraction is done for each selected field
00076                  in turn.  (Run listobs to get lists of the ID and names.)
00077                 default: field = '' means select all fields
00078                 field = 1 # will get field_id=1 (if you give it an 
00079                         integer, it will retrieve the source with that index.
00080                 field = '1328+307'  specifies source '1328+307'
00081                 field = '13*' will retrieve '1328+307' and any other fields
00082                    beginning with '13'
00083         fitspw -- Selection of spectral windows and channels to use in the
00084                   fit for the continuum, using general spw:chan syntax.
00085                   See the note under combine.
00086                 default: '' (all)
00087                 example: fitspw='0:5~30;40~55'
00088         combine -- Data axes to combine for the continuum estimate.
00089                 It must include 'spw' if spw contains spws that are not in
00090                 fitspw!
00091                 default: '' --> solutions will break at scan, field, and spw
00092                       boundaries according to solint
00093               Options: '', 'spw'', 'scan', or 'spw, scan'
00094               example: combine='spw' --> form spw-merged continuum estimate
00095         solint -- Timescale for per-baseline fit (units optional)
00096                 default (recommended): 'int' --> no time averaging, do a
00097                                        fit for each integration and let the
00098                                        noisy fits average out in the image.
00099 
00100                 example: solint='10s'  --> average to 10s before fitting
00101                          10 or '10' --> '10s' (unitless: assumes seconds)
00102                 options: 'int' --> per integration
00103                          'inf' --> per scan
00104 
00105                 If solint is longer than 'int', the continuum estimate can be
00106                 corrupted by time smearing!
00107 
00108         fitorder -- Polynomial order for the fits of the continuum w.r.t.
00109                     frequency.  fitorders > 1 are strongly discouraged
00110                     because high order polynomials have more flexibility, may
00111                     absorb line emission, and tend go wild at the edges of
00112                     fitspw, which is not what you want.
00113 
00114                 default: 0 (constant); example: fitorder=1
00115 
00116         spw -- Optional per spectral window selection of channels to include
00117                in the output.  See the note under combine.
00118 
00119                The spectral windows will be renumbered to start from 0, as in
00120                split.
00121         want_cont -- Create vis + '.cont' to hold the continuum estimate.
00122                 default: 'False'; example: want_cont=True
00123                 The continuum estimate will be placed in vis + '.cont'
00124         async -- Run task in a separate process (return CASA prompt)
00125                 default: False; example: async=True
00126 
00127 
00128         """
00129         if not hasattr(self, "__globals__") or self.__globals__ == None :
00130            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00131         #casac = self.__globals__['casac']
00132         casalog = self.__globals__['casalog']
00133         #casalog = casac.casac.logsink()
00134         self.__globals__['__last_task'] = 'uvcontsub'
00135         self.__globals__['taskname'] = 'uvcontsub'
00136         ###
00137         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00138         ###
00139         ###
00140         #Handle globals or user over-ride of arguments
00141         #
00142         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00143         useLocalDefaults = False
00144 
00145         for item in function_signature_defaults.iteritems():
00146                 key,val = item
00147                 keyVal = eval(key)
00148                 if (keyVal == None):
00149                         #user hasn't set it - use global/default
00150                         pass
00151                 else:
00152                         #user has set it - use over-ride
00153                         if (key != 'self') :
00154                            useLocalDefaults = True
00155 
00156         myparams = {}
00157         if useLocalDefaults :
00158            for item in function_signature_defaults.iteritems():
00159                key,val = item
00160                keyVal = eval(key)
00161                exec('myparams[key] = keyVal')
00162                self.parameters[key] = keyVal
00163                if (keyVal == None):
00164                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00165                    keyVal = eval(key)
00166                    if(type(keyVal) == dict) :
00167                       if len(keyVal) > 0 :
00168                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00169                       else :
00170                          exec('myparams[key] = ' + key + ' = {}')
00171 
00172         else :
00173             async = self.parameters['async']
00174             myparams['vis'] = vis = self.parameters['vis']
00175             myparams['field'] = field = self.parameters['field']
00176             myparams['fitspw'] = fitspw = self.parameters['fitspw']
00177             myparams['combine'] = combine = self.parameters['combine']
00178             myparams['solint'] = solint = self.parameters['solint']
00179             myparams['fitorder'] = fitorder = self.parameters['fitorder']
00180             myparams['spw'] = spw = self.parameters['spw']
00181             myparams['want_cont'] = want_cont = self.parameters['want_cont']
00182 
00183 
00184         result = None
00185 
00186 #
00187 #    The following is work around to avoid a bug with current python translation
00188 #
00189         mytmp = {}
00190 
00191         mytmp['vis'] = vis
00192         mytmp['field'] = field
00193         mytmp['fitspw'] = fitspw
00194         mytmp['combine'] = combine
00195         mytmp['solint'] = solint
00196         mytmp['fitorder'] = fitorder
00197         mytmp['spw'] = spw
00198         mytmp['want_cont'] = want_cont
00199         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00200         trec = casac.casac.utils().torecord(pathname+'uvcontsub.xml')
00201 
00202         casalog.origin('uvcontsub')
00203         try :
00204           #if not trec.has_key('uvcontsub') or not casac.casac.utils().verify(mytmp, trec['uvcontsub']) :
00205             #return False
00206 
00207           casac.casac.utils().verify(mytmp, trec['uvcontsub'], True)
00208           scriptstr=['']
00209           saveinputs = self.__globals__['saveinputs']
00210           saveinputs('uvcontsub', 'uvcontsub.last', myparams, self.__globals__,scriptstr=scriptstr)
00211           if async :
00212             count = 0
00213             keybase =  time.strftime("%y%m%d.%H%M%S")
00214             key = keybase + "_" + str(count)
00215             while self.__async__.has_key(key) :
00216                count += 1
00217                key = keybase + "_" + str(count)
00218             result = tm.execute('uvcontsub', vis, field, fitspw, combine, solint, fitorder, spw, want_cont)
00219             print "Use: "
00220             print "      tm.retrieve(return_value) # to retrieve the status"
00221             print 
00222             self.rkey = key
00223             self.__async__[key] = result
00224           else :
00225               tname = 'uvcontsub'
00226               spaces = ' '*(18-len(tname))
00227               casalog.post('\n##########################################'+
00228                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00229               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00230               result = uvcontsub(vis, field, fitspw, combine, solint, fitorder, spw, want_cont)
00231               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00232                            '\n##########################################')
00233 
00234         except Exception, instance:
00235           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00236              raise
00237           else :
00238              #print '**** Error **** ',instance
00239              tname = 'uvcontsub'
00240              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00241              pass
00242 
00243         gc.collect()
00244         return result
00245 #
00246 #
00247 #
00248     def paramgui(self, useGlobals=True, ipython_globals=None):
00249         """
00250         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00251         """
00252         import paramgui
00253         if not hasattr(self, "__globals__") or self.__globals__ == None :
00254            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00255 
00256         if useGlobals:
00257             if ipython_globals == None:
00258                 myf=self.__globals__
00259             else:
00260                 myf=ipython_globals
00261 
00262             paramgui.setGlobals(myf)
00263         else:
00264             paramgui.setGlobals({})
00265 
00266         paramgui.runTask('uvcontsub', myf['_ip'])
00267         paramgui.setGlobals({})
00268 
00269 #
00270 #
00271 #
00272     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00273         if not hasattr(self, "__globals__") or self.__globals__ == None :
00274            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00275         if ipython_globals == None:
00276             myf=self.__globals__
00277         else:
00278             myf=ipython_globals
00279 
00280         a = odict()
00281         a['vis']  = ''
00282         a['field']  = ''
00283         a['fitspw']  = ''
00284         a['combine']  = ''
00285         a['solint']  = 'int'
00286         a['fitorder']  = 0
00287         a['spw']  = ''
00288         a['want_cont']  = False
00289 
00290         a['async']=False
00291 
00292 ### This function sets the default values but also will return the list of
00293 ### parameters or the default value of a given parameter
00294         if(param == None):
00295                 myf['__set_default_parameters'](a)
00296         elif(param == 'paramkeys'):
00297                 return a.keys()
00298         else:
00299             if(paramvalue==None and subparam==None):
00300                if(a.has_key(param)):
00301                   return a[param]
00302                else:
00303                   return self.itsdefault(param)
00304             else:
00305                retval=a[param]
00306                if(type(a[param])==dict):
00307                   for k in range(len(a[param])):
00308                      valornotval='value'
00309                      if(a[param][k].has_key('notvalue')):
00310                         valornotval='notvalue'
00311                      if((a[param][k][valornotval])==paramvalue):
00312                         retval=a[param][k].copy()
00313                         retval.pop(valornotval)
00314                         if(subparam != None):
00315                            if(retval.has_key(subparam)):
00316                               retval=retval[subparam]
00317                            else:
00318                               retval=self.itsdefault(subparam)
00319                      else:
00320                         retval=self.itsdefault(subparam)
00321                return retval
00322 
00323 
00324 #
00325 #
00326     def check_params(self, param=None, value=None, ipython_globals=None):
00327       if ipython_globals == None:
00328           myf=self.__globals__
00329       else:
00330           myf=ipython_globals
00331 #      print 'param:', param, 'value:', value
00332       try :
00333          if str(type(value)) != "<type 'instance'>" :
00334             value0 = value
00335             value = myf['cu'].expandparam(param, value)
00336             matchtype = False
00337             if(type(value) == numpy.ndarray):
00338                if(type(value) == type(value0)):
00339                   myf[param] = value.tolist()
00340                else:
00341                   #print 'value:', value, 'value0:', value0
00342                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00343                   myf[param] = value0
00344                   if type(value0) != list :
00345                      matchtype = True
00346             else :
00347                myf[param] = value
00348             value = myf['cu'].verifyparam({param:value})
00349             if matchtype:
00350                value = False
00351       except Exception, instance:
00352          #ignore the exception and just return it unchecked
00353          myf[param] = value
00354       return value
00355 #
00356 #
00357     def description(self, key='uvcontsub', subkey=None):
00358         desc={'uvcontsub': 'Continuum fitting and subtraction in the uv plane',
00359                'vis': 'Name of input MS.  Output goes to vis + ".contsub"',
00360                'field': 'Select field(s) using id(s) or name(s)',
00361                'fitspw': 'Spectral window:channel selection for fitting the continuum',
00362                'combine': 'Data axes to combine for the continuum estimation (none, or spw and/or scan)',
00363                'solint': 'Continuum fit timescale (int recommended!)',
00364                'fitorder': 'Polynomial order for the fits',
00365                'spw': 'Spectral window selection for output',
00366                'want_cont': 'Create vis + ".cont" to hold the continuum estimate.',
00367 
00368                'async': 'If true the taskname must be started using uvcontsub(...)'
00369               }
00370 
00371         if(desc.has_key(key)) :
00372            return desc[key]
00373 
00374     def itsdefault(self, paramname) :
00375         a = {}
00376         a['vis']  = ''
00377         a['field']  = ''
00378         a['fitspw']  = ''
00379         a['combine']  = ''
00380         a['solint']  = 'int'
00381         a['fitorder']  = 0
00382         a['spw']  = ''
00383         a['want_cont']  = False
00384 
00385         #a = sys._getframe(len(inspect.stack())-1).f_globals
00386 
00387         if a.has_key(paramname) :
00388               return a[paramname]
00389 uvcontsub_cli = uvcontsub_cli_()