casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
ft_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_ft import ft
00018 class ft_cli_:
00019     __name__ = "ft"
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__ = (ft_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'spw':None, 'model':None, 'nterms':None, 'reffreq':None, 'complist':None, 'incremental':None, 'usescratch':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, spw=None, model=None, nterms=None, reffreq=None, complist=None, incremental=None, usescratch=None,  async=None):
00047 
00048         """Insert a source model  a visibility set:
00049 
00050        A source model (souce.model image) or components list is converted into a
00051        model visibility that is inserted into the MODEL_DATA column.  This is
00052        needed to use resolved source in gaincal and in fluxscale.  
00053 
00054        Setjy will automatically make this ft step on the
00055        sources currently available are 3C48, 3C138, 3C147, 3C286
00056        at 1.4, 5.0, 8.4, 15, 22, 43 GHz.  Their location is site
00057        dependent.  In Charlottesville and at the AOC, the models are
00058        in /usr/lib(lib64)/casapy/data/nrao/VLA/CalModels.
00059                
00060 
00061        Keyword arguments:
00062        vis -- Name of input visibility file
00063               default: none; example: vis='ngc5921.ms'
00064        field -- Field name list
00065                default: '' ==> all
00066                NOTE: BUT, only one source can be specified in a multi-source vis.
00067                field = '1328+307'  specifies source '1328+307'
00068                field = '4' specified field with index 4
00069        spw -- Spw selection
00070                default: spw = '' (all spw)
00071        model -- Name of input model image
00072                default: '' ==> None;
00073                example: model='/usr/lib/casapy/data/nrao/VLA/CalModels/3C286_X.im'
00074                Note: The model visibilities are scaled from the model frequency
00075                      to the observed frequency of the data.
00076        nterms -- Number of terms used to model the sky frequency dependence
00077                  default: 1  ==> one model image is required
00078                  example : nterms=3  represents a 2nd order Taylor-polynomial in frequency
00079                            and should be used in conjuction with coefficient model images as 
00080                            model=['xxx.model.tt0','xxx.model.tt1', 'xxx.model.tt2']
00081              reffreq -- Reference-frequency about which this Taylor-expansion is defined.
00082                         default: '' ==> reads the reference frequency from the model image
00083                         example : reffreq = '1.5GHz'
00084        complist -- Name of component list
00085                default: None; ; example: complist='test.cl'
00086                component lists are difficult to make.
00087        incremental -- Add model visibility to the existing model visibilties stored in the MS
00088                default: False; example: incremental=True
00089        usescratch  -- if True model visibilities will be stored in the scratch column 
00090                             MODEL_DATA; when false the model visibilities will be generated 
00091                             on the fly (this mode may save some disk space equivalent to 
00092                             the volume of the observed data). 
00093                             default: False; example usescratch=True
00094 
00095 
00096      
00097 
00098 
00099 
00100  
00101         """
00102         if not hasattr(self, "__globals__") or self.__globals__ == None :
00103            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00104         #casac = self.__globals__['casac']
00105         casalog = self.__globals__['casalog']
00106         #casalog = casac.casac.logsink()
00107         self.__globals__['__last_task'] = 'ft'
00108         self.__globals__['taskname'] = 'ft'
00109         ###
00110         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00111         ###
00112         ###
00113         #Handle globals or user over-ride of arguments
00114         #
00115         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00116         useLocalDefaults = False
00117 
00118         for item in function_signature_defaults.iteritems():
00119                 key,val = item
00120                 keyVal = eval(key)
00121                 if (keyVal == None):
00122                         #user hasn't set it - use global/default
00123                         pass
00124                 else:
00125                         #user has set it - use over-ride
00126                         if (key != 'self') :
00127                            useLocalDefaults = True
00128 
00129         myparams = {}
00130         if useLocalDefaults :
00131            for item in function_signature_defaults.iteritems():
00132                key,val = item
00133                keyVal = eval(key)
00134                exec('myparams[key] = keyVal')
00135                self.parameters[key] = keyVal
00136                if (keyVal == None):
00137                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00138                    keyVal = eval(key)
00139                    if(type(keyVal) == dict) :
00140                       if len(keyVal) > 0 :
00141                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00142                       else :
00143                          exec('myparams[key] = ' + key + ' = {}')
00144 
00145         else :
00146             async = self.parameters['async']
00147             myparams['vis'] = vis = self.parameters['vis']
00148             myparams['field'] = field = self.parameters['field']
00149             myparams['spw'] = spw = self.parameters['spw']
00150             myparams['model'] = model = self.parameters['model']
00151             myparams['nterms'] = nterms = self.parameters['nterms']
00152             myparams['reffreq'] = reffreq = self.parameters['reffreq']
00153             myparams['complist'] = complist = self.parameters['complist']
00154             myparams['incremental'] = incremental = self.parameters['incremental']
00155             myparams['usescratch'] = usescratch = self.parameters['usescratch']
00156 
00157 
00158         result = None
00159 
00160 #
00161 #    The following is work around to avoid a bug with current python translation
00162 #
00163         mytmp = {}
00164 
00165         mytmp['vis'] = vis
00166         mytmp['field'] = field
00167         mytmp['spw'] = spw
00168         mytmp['model'] = model
00169         mytmp['nterms'] = nterms
00170         mytmp['reffreq'] = reffreq
00171         mytmp['complist'] = complist
00172         mytmp['incremental'] = incremental
00173         mytmp['usescratch'] = usescratch
00174         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00175         trec = casac.casac.utils().torecord(pathname+'ft.xml')
00176 
00177         casalog.origin('ft')
00178         try :
00179           #if not trec.has_key('ft') or not casac.casac.utils().verify(mytmp, trec['ft']) :
00180             #return False
00181 
00182           casac.casac.utils().verify(mytmp, trec['ft'], True)
00183           scriptstr=['']
00184           saveinputs = self.__globals__['saveinputs']
00185           saveinputs('ft', 'ft.last', myparams, self.__globals__,scriptstr=scriptstr)
00186           if async :
00187             count = 0
00188             keybase =  time.strftime("%y%m%d.%H%M%S")
00189             key = keybase + "_" + str(count)
00190             while self.__async__.has_key(key) :
00191                count += 1
00192                key = keybase + "_" + str(count)
00193             result = tm.execute('ft', vis, field, spw, model, nterms, reffreq, complist, incremental, usescratch)
00194             print "Use: "
00195             print "      tm.retrieve(return_value) # to retrieve the status"
00196             print 
00197             self.rkey = key
00198             self.__async__[key] = result
00199           else :
00200               tname = 'ft'
00201               spaces = ' '*(18-len(tname))
00202               casalog.post('\n##########################################'+
00203                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00204               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00205               result = ft(vis, field, spw, model, nterms, reffreq, complist, incremental, usescratch)
00206               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00207                            '\n##########################################')
00208 
00209         except Exception, instance:
00210           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00211              raise
00212           else :
00213              #print '**** Error **** ',instance
00214              tname = 'ft'
00215              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00216              pass
00217 
00218         gc.collect()
00219         return result
00220 #
00221 #
00222 #
00223     def paramgui(self, useGlobals=True, ipython_globals=None):
00224         """
00225         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00226         """
00227         import paramgui
00228         if not hasattr(self, "__globals__") or self.__globals__ == None :
00229            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00230 
00231         if useGlobals:
00232             if ipython_globals == None:
00233                 myf=self.__globals__
00234             else:
00235                 myf=ipython_globals
00236 
00237             paramgui.setGlobals(myf)
00238         else:
00239             paramgui.setGlobals({})
00240 
00241         paramgui.runTask('ft', myf['_ip'])
00242         paramgui.setGlobals({})
00243 
00244 #
00245 #
00246 #
00247     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00248         if not hasattr(self, "__globals__") or self.__globals__ == None :
00249            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00250         if ipython_globals == None:
00251             myf=self.__globals__
00252         else:
00253             myf=ipython_globals
00254 
00255         a = odict()
00256         a['vis']  = ''
00257         a['field']  = ''
00258         a['spw']  = ''
00259         a['model']  = ''
00260         a['nterms']  = 1
00261         a['complist']  = ''
00262         a['incremental']  = False
00263         a['usescratch']  = False
00264 
00265         a['async']=False
00266         a['nterms'] = {
00267                     0:odict([{'notvalue':1}, {'reffreq':''}])}
00268 
00269 ### This function sets the default values but also will return the list of
00270 ### parameters or the default value of a given parameter
00271         if(param == None):
00272                 myf['__set_default_parameters'](a)
00273         elif(param == 'paramkeys'):
00274                 return a.keys()
00275         else:
00276             if(paramvalue==None and subparam==None):
00277                if(a.has_key(param)):
00278                   return a[param]
00279                else:
00280                   return self.itsdefault(param)
00281             else:
00282                retval=a[param]
00283                if(type(a[param])==dict):
00284                   for k in range(len(a[param])):
00285                      valornotval='value'
00286                      if(a[param][k].has_key('notvalue')):
00287                         valornotval='notvalue'
00288                      if((a[param][k][valornotval])==paramvalue):
00289                         retval=a[param][k].copy()
00290                         retval.pop(valornotval)
00291                         if(subparam != None):
00292                            if(retval.has_key(subparam)):
00293                               retval=retval[subparam]
00294                            else:
00295                               retval=self.itsdefault(subparam)
00296                      else:
00297                         retval=self.itsdefault(subparam)
00298                return retval
00299 
00300 
00301 #
00302 #
00303     def check_params(self, param=None, value=None, ipython_globals=None):
00304       if ipython_globals == None:
00305           myf=self.__globals__
00306       else:
00307           myf=ipython_globals
00308 #      print 'param:', param, 'value:', value
00309       try :
00310          if str(type(value)) != "<type 'instance'>" :
00311             value0 = value
00312             value = myf['cu'].expandparam(param, value)
00313             matchtype = False
00314             if(type(value) == numpy.ndarray):
00315                if(type(value) == type(value0)):
00316                   myf[param] = value.tolist()
00317                else:
00318                   #print 'value:', value, 'value0:', value0
00319                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00320                   myf[param] = value0
00321                   if type(value0) != list :
00322                      matchtype = True
00323             else :
00324                myf[param] = value
00325             value = myf['cu'].verifyparam({param:value})
00326             if matchtype:
00327                value = False
00328       except Exception, instance:
00329          #ignore the exception and just return it unchecked
00330          myf[param] = value
00331       return value
00332 #
00333 #
00334     def description(self, key='ft', subkey=None):
00335         desc={'ft': 'Insert a source model  a visibility set:',
00336                'vis': 'Name of input visibility file (MS)',
00337                'field': 'Field selection',
00338                'spw': 'Spw selection',
00339                'model': 'Name of input model image(s)',
00340                'nterms': 'Number of terms used to model the sky frequency dependence',
00341                'reffreq': 'Reference frequency (e.g. \'1.5e+9\' or \'1.5GHz\')',
00342                'complist': 'Name of component list',
00343                'incremental': 'Add to the existing model visibility?',
00344                'usescratch': 'If True predicted  visibility  is stored in MODEL_DATA column',
00345 
00346                'async': 'If true the taskname must be started using ft(...)'
00347               }
00348 
00349 #
00350 # Set subfields defaults if needed
00351 #
00352 
00353         if(desc.has_key(key)) :
00354            return desc[key]
00355 
00356     def itsdefault(self, paramname) :
00357         a = {}
00358         a['vis']  = ''
00359         a['field']  = ''
00360         a['spw']  = ''
00361         a['model']  = ''
00362         a['nterms']  = 1
00363         a['reffreq']  = ''
00364         a['complist']  = ''
00365         a['incremental']  = False
00366         a['usescratch']  = False
00367 
00368         #a = sys._getframe(len(inspect.stack())-1).f_globals
00369 
00370         if self.parameters['nterms']  != 1:
00371             a['reffreq'] = ''
00372 
00373         if a.has_key(paramname) :
00374               return a[paramname]
00375 ft_cli = ft_cli_()