casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
uvcontsub2_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_uvcontsub2 import uvcontsub2
00018 class uvcontsub2_cli_:
00019     __name__ = "uvcontsub2"
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__ = (uvcontsub2_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         """Temporarily a clone of uvcontsub
00049   
00050         uvcontsub2 has been renamed to uvcontsub.  For now uvcontsub2 is an
00051         alias for uvcontsub, but that may change.
00052         
00053         For parameter descriptions, please see the help of uvcontsub.
00054 
00055 
00056         """
00057         if not hasattr(self, "__globals__") or self.__globals__ == None :
00058            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00059         #casac = self.__globals__['casac']
00060         casalog = self.__globals__['casalog']
00061         #casalog = casac.casac.logsink()
00062         self.__globals__['__last_task'] = 'uvcontsub2'
00063         self.__globals__['taskname'] = 'uvcontsub2'
00064         ###
00065         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00066         ###
00067         ###
00068         #Handle globals or user over-ride of arguments
00069         #
00070         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00071         useLocalDefaults = False
00072 
00073         for item in function_signature_defaults.iteritems():
00074                 key,val = item
00075                 keyVal = eval(key)
00076                 if (keyVal == None):
00077                         #user hasn't set it - use global/default
00078                         pass
00079                 else:
00080                         #user has set it - use over-ride
00081                         if (key != 'self') :
00082                            useLocalDefaults = True
00083 
00084         myparams = {}
00085         if useLocalDefaults :
00086            for item in function_signature_defaults.iteritems():
00087                key,val = item
00088                keyVal = eval(key)
00089                exec('myparams[key] = keyVal')
00090                self.parameters[key] = keyVal
00091                if (keyVal == None):
00092                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00093                    keyVal = eval(key)
00094                    if(type(keyVal) == dict) :
00095                       if len(keyVal) > 0 :
00096                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00097                       else :
00098                          exec('myparams[key] = ' + key + ' = {}')
00099 
00100         else :
00101             async = self.parameters['async']
00102             myparams['vis'] = vis = self.parameters['vis']
00103             myparams['field'] = field = self.parameters['field']
00104             myparams['fitspw'] = fitspw = self.parameters['fitspw']
00105             myparams['combine'] = combine = self.parameters['combine']
00106             myparams['solint'] = solint = self.parameters['solint']
00107             myparams['fitorder'] = fitorder = self.parameters['fitorder']
00108             myparams['spw'] = spw = self.parameters['spw']
00109             myparams['want_cont'] = want_cont = self.parameters['want_cont']
00110 
00111 
00112         result = None
00113 
00114 #
00115 #    The following is work around to avoid a bug with current python translation
00116 #
00117         mytmp = {}
00118 
00119         mytmp['vis'] = vis
00120         mytmp['field'] = field
00121         mytmp['fitspw'] = fitspw
00122         mytmp['combine'] = combine
00123         mytmp['solint'] = solint
00124         mytmp['fitorder'] = fitorder
00125         mytmp['spw'] = spw
00126         mytmp['want_cont'] = want_cont
00127         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00128         trec = casac.casac.utils().torecord(pathname+'uvcontsub2.xml')
00129 
00130         casalog.origin('uvcontsub2')
00131         try :
00132           #if not trec.has_key('uvcontsub2') or not casac.casac.utils().verify(mytmp, trec['uvcontsub2']) :
00133             #return False
00134 
00135           casac.casac.utils().verify(mytmp, trec['uvcontsub2'], True)
00136           scriptstr=['']
00137           saveinputs = self.__globals__['saveinputs']
00138           saveinputs('uvcontsub2', 'uvcontsub2.last', myparams, self.__globals__,scriptstr=scriptstr)
00139           if async :
00140             count = 0
00141             keybase =  time.strftime("%y%m%d.%H%M%S")
00142             key = keybase + "_" + str(count)
00143             while self.__async__.has_key(key) :
00144                count += 1
00145                key = keybase + "_" + str(count)
00146             result = tm.execute('uvcontsub2', vis, field, fitspw, combine, solint, fitorder, spw, want_cont)
00147             print "Use: "
00148             print "      tm.retrieve(return_value) # to retrieve the status"
00149             print 
00150             self.rkey = key
00151             self.__async__[key] = result
00152           else :
00153               tname = 'uvcontsub2'
00154               spaces = ' '*(18-len(tname))
00155               casalog.post('\n##########################################'+
00156                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00157               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00158               result = uvcontsub2(vis, field, fitspw, combine, solint, fitorder, spw, want_cont)
00159               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00160                            '\n##########################################')
00161 
00162         except Exception, instance:
00163           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00164              raise
00165           else :
00166              #print '**** Error **** ',instance
00167              tname = 'uvcontsub2'
00168              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00169              pass
00170 
00171         gc.collect()
00172         return result
00173 #
00174 #
00175 #
00176     def paramgui(self, useGlobals=True, ipython_globals=None):
00177         """
00178         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00179         """
00180         import paramgui
00181         if not hasattr(self, "__globals__") or self.__globals__ == None :
00182            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00183 
00184         if useGlobals:
00185             if ipython_globals == None:
00186                 myf=self.__globals__
00187             else:
00188                 myf=ipython_globals
00189 
00190             paramgui.setGlobals(myf)
00191         else:
00192             paramgui.setGlobals({})
00193 
00194         paramgui.runTask('uvcontsub2', myf['_ip'])
00195         paramgui.setGlobals({})
00196 
00197 #
00198 #
00199 #
00200     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00201         if not hasattr(self, "__globals__") or self.__globals__ == None :
00202            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00203         if ipython_globals == None:
00204             myf=self.__globals__
00205         else:
00206             myf=ipython_globals
00207 
00208         a = odict()
00209         a['vis']  = ''
00210         a['field']  = ''
00211         a['fitspw']  = ''
00212         a['combine']  = ''
00213         a['solint']  = 'int'
00214         a['fitorder']  = 0
00215         a['spw']  = ''
00216         a['want_cont']  = False
00217 
00218         a['async']=False
00219 
00220 ### This function sets the default values but also will return the list of
00221 ### parameters or the default value of a given parameter
00222         if(param == None):
00223                 myf['__set_default_parameters'](a)
00224         elif(param == 'paramkeys'):
00225                 return a.keys()
00226         else:
00227             if(paramvalue==None and subparam==None):
00228                if(a.has_key(param)):
00229                   return a[param]
00230                else:
00231                   return self.itsdefault(param)
00232             else:
00233                retval=a[param]
00234                if(type(a[param])==dict):
00235                   for k in range(len(a[param])):
00236                      valornotval='value'
00237                      if(a[param][k].has_key('notvalue')):
00238                         valornotval='notvalue'
00239                      if((a[param][k][valornotval])==paramvalue):
00240                         retval=a[param][k].copy()
00241                         retval.pop(valornotval)
00242                         if(subparam != None):
00243                            if(retval.has_key(subparam)):
00244                               retval=retval[subparam]
00245                            else:
00246                               retval=self.itsdefault(subparam)
00247                      else:
00248                         retval=self.itsdefault(subparam)
00249                return retval
00250 
00251 
00252 #
00253 #
00254     def check_params(self, param=None, value=None, ipython_globals=None):
00255       if ipython_globals == None:
00256           myf=self.__globals__
00257       else:
00258           myf=ipython_globals
00259 #      print 'param:', param, 'value:', value
00260       try :
00261          if str(type(value)) != "<type 'instance'>" :
00262             value0 = value
00263             value = myf['cu'].expandparam(param, value)
00264             matchtype = False
00265             if(type(value) == numpy.ndarray):
00266                if(type(value) == type(value0)):
00267                   myf[param] = value.tolist()
00268                else:
00269                   #print 'value:', value, 'value0:', value0
00270                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00271                   myf[param] = value0
00272                   if type(value0) != list :
00273                      matchtype = True
00274             else :
00275                myf[param] = value
00276             value = myf['cu'].verifyparam({param:value})
00277             if matchtype:
00278                value = False
00279       except Exception, instance:
00280          #ignore the exception and just return it unchecked
00281          myf[param] = value
00282       return value
00283 #
00284 #
00285     def description(self, key='uvcontsub2', subkey=None):
00286         desc={'uvcontsub2': 'Temporarily a clone of uvcontsub',
00287                'vis': 'Name of input MS.  Output goes to vis + ".contsub"',
00288                'field': 'Select field(s) using id(s) or name(s)',
00289                'fitspw': 'Spectral window:channel selection for fitting the continuum',
00290                'combine': 'Data axes to combine for the continuum estimation (none or spw and/or scan)',
00291                'solint': 'Continuum fit timescale (stick to int!)',
00292                'fitorder': 'Polynomial order for the fits',
00293                'spw': 'Spectral window selection for output',
00294                'want_cont': 'Create vis + ".cont" to hold the continuum estimate.',
00295 
00296                'async': 'If true the taskname must be started using uvcontsub2(...)'
00297               }
00298 
00299         if(desc.has_key(key)) :
00300            return desc[key]
00301 
00302     def itsdefault(self, paramname) :
00303         a = {}
00304         a['vis']  = ''
00305         a['field']  = ''
00306         a['fitspw']  = ''
00307         a['combine']  = ''
00308         a['solint']  = 'int'
00309         a['fitorder']  = 0
00310         a['spw']  = ''
00311         a['want_cont']  = False
00312 
00313         #a = sys._getframe(len(inspect.stack())-1).f_globals
00314 
00315         if a.has_key(paramname) :
00316               return a[paramname]
00317 uvcontsub2_cli = uvcontsub2_cli_()