casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
ssoflux_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_ssoflux import ssoflux
00018 class ssoflux_cli_:
00019     __name__ = "ssoflux"
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__ = (ssoflux_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'spw':None, 'modimage':None, 'fluxdensity':None, 'standard':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, modimage=None, fluxdensity=None, standard=None,  async=None):
00047 
00048         """Fills the model column with the visibilities of a calibrator
00049        *This is an experimental clone of setjy while flux calibration with
00050         Solar System objects is being tested.  It will eventually be merged
00051         back into setjy.*
00052 
00053        This task sets the model visibility amp and phase of a
00054        specified source (generally a calibrator).  The simplest way is
00055        to enter the flux density (I,Q,U,V) explicitly, but this is
00056        valid only for a point source.
00057 
00058        For an extended source, the clean model (image.model) can be
00059        specified and the model visibilities associated with this clean
00060        model is placed in the visibility model column.
00061 
00062        Models are available for 3C48, 3C138, 3C286 between
00063        1.4 and 43 GHz.  3C147 is available above 13 GHz.  These models
00064        are scaled to the precise frequency of the data.  Only I source 
00065        model can be inserted at a time.
00066 
00067        The location of the models are system dependent:  At the AOC and CV,
00068        the models are in the directory::/usr/lib/casapy/data/nrao/VLA/CalModels
00069        or /usr/lib64/casapy/data/nrao/VLA/CalModel.
00070 
00071        ssoflux need only be run on the calibrator sources with a known flux
00072        density and/or model.
00073 
00074        Keyword arguments:
00075        vis -- Name of input visibility file
00076                default: none.  example: vis='ngc5921.ms'
00077        field -- Select field using field id(s) or field name(s).
00078               default: ''=all fields, but run ssoflux one field at a time.
00079                  [run listobs to obtain the list id's or names of calibrators]
00080               If field is a non-negative integer, it is assumed to be a field
00081               index.  Otherwise, it is taken to be a field name.
00082               field='0~2'; field ids 0,1,2
00083               field='0,4,5~7'; field ids 0,4,5,6,7
00084               field='3C286,3C295'; field named 3C286 and 3C295
00085               field = '3,4C*'; field id 3, all names starting with 4C
00086        spw -- Select spectral window/channels
00087               default: ''=all spectral windows and channels
00088               spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00089               spw='<2';  spectral windows less than 2 (i.e. 0,1)
00090               spw='0:5~61'; spw 0, channels 5 to 61
00091               spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, channels 3 to 45.
00092               spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00093               spw='0:0~10;15~60'; spectral window 0 with channels 0-10,15-60
00094               spw='0:0~10,1:20~30,2:1;2;4'; spw 0, channels 0-10,
00095                        spw 1, channels 20-30, and spw 2, channels, 1,2 and 4
00096 
00097        Use one of the two methods below:  modimage or fluxdensity
00098 
00099        modimage -- Model image (I only) for setting the model visibilities.
00100               default: '' means use fluxdensity instead of modimage. 
00101               Each field must be done separately.  The image clean model
00102               will be scaled from the frequency in the model to that actually used,
00103               unless fluxdensity = 0 (or fluxdensity[0] = 0).
00104               Both the amplitude and phase are calculated.
00105               At the AOC or CV, the models are located in
00106               /usr/lib/casapy/data/nrao/VLA/CalModels/3C286_L.im (egs)
00107                    lib64
00108 
00109        fluxdensity -- Specified flux density [I,Q,U,V] in Jy
00110                default: -1, uses [1,0,0,0] flux density for all sources,
00111                   except for 3C286, 3C48 and 3C147, which use standard flux
00112                   densities.  It is recommended to use modimage for
00113                   these sources if they are resolved by the observation.
00114                Only one flux density can be specified at a time.  The phases are
00115                   set to zero.
00116                example   fluxdensity=-1  will insert 1.0 for all calibrators
00117                          except 3C286, 3C147 and 3C48.
00118                example   field = '1'; fluxdensity=[3.2,0,0,0] wil put in 
00119                          a flux density of I=3.2 for field='1'
00120 
00121                At present (June 2000), this is the only method to insert a
00122                polarized flux density model.
00123                example:  fluxdensity=[2.63,0.21,-0.33,0.02]
00124                          will put in I,Q,U,V flux densities of 2.63,0.21,-0.33,
00125                          and 0.02, respectively, in the model column.
00126 
00127        standard -- Flux density standard, used if fluxdensity<0
00128                default: 'Perley-Taylor 99'; example: standard='Baars'
00129                Options: 'Baars','Perley 90','Perley-Taylor 95',
00130                   'Perley-Taylor 99', 'Perley-Butler 2010',
00131                   and 'Butler-JPL-Horizons 2010'.
00132                All but the last one are for extragalactic calibrators,
00133                and the final one is for Solar System objects.
00134  
00135         """
00136         if not hasattr(self, "__globals__") or self.__globals__ == None :
00137            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00138         #casac = self.__globals__['casac']
00139         casalog = self.__globals__['casalog']
00140         #casalog = casac.casac.logsink()
00141         self.__globals__['__last_task'] = 'ssoflux'
00142         self.__globals__['taskname'] = 'ssoflux'
00143         ###
00144         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00145         ###
00146         ###
00147         #Handle globals or user over-ride of arguments
00148         #
00149         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00150         useLocalDefaults = False
00151 
00152         for item in function_signature_defaults.iteritems():
00153                 key,val = item
00154                 keyVal = eval(key)
00155                 if (keyVal == None):
00156                         #user hasn't set it - use global/default
00157                         pass
00158                 else:
00159                         #user has set it - use over-ride
00160                         if (key != 'self') :
00161                            useLocalDefaults = True
00162 
00163         myparams = {}
00164         if useLocalDefaults :
00165            for item in function_signature_defaults.iteritems():
00166                key,val = item
00167                keyVal = eval(key)
00168                exec('myparams[key] = keyVal')
00169                self.parameters[key] = keyVal
00170                if (keyVal == None):
00171                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00172                    keyVal = eval(key)
00173                    if(type(keyVal) == dict) :
00174                       if len(keyVal) > 0 :
00175                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00176                       else :
00177                          exec('myparams[key] = ' + key + ' = {}')
00178 
00179         else :
00180             async = self.parameters['async']
00181             myparams['vis'] = vis = self.parameters['vis']
00182             myparams['field'] = field = self.parameters['field']
00183             myparams['spw'] = spw = self.parameters['spw']
00184             myparams['modimage'] = modimage = self.parameters['modimage']
00185             myparams['fluxdensity'] = fluxdensity = self.parameters['fluxdensity']
00186             myparams['standard'] = standard = self.parameters['standard']
00187 
00188 
00189         result = None
00190 
00191 #
00192 #    The following is work around to avoid a bug with current python translation
00193 #
00194         mytmp = {}
00195 
00196         mytmp['vis'] = vis
00197         mytmp['field'] = field
00198         mytmp['spw'] = spw
00199         mytmp['modimage'] = modimage
00200         mytmp['fluxdensity'] = fluxdensity
00201         mytmp['standard'] = standard
00202         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00203         trec = casac.casac.utils().torecord(pathname+'ssoflux.xml')
00204 
00205         casalog.origin('ssoflux')
00206         try :
00207           #if not trec.has_key('ssoflux') or not casac.casac.utils().verify(mytmp, trec['ssoflux']) :
00208             #return False
00209 
00210           casac.casac.utils().verify(mytmp, trec['ssoflux'], True)
00211           scriptstr=['']
00212           saveinputs = self.__globals__['saveinputs']
00213           saveinputs('ssoflux', 'ssoflux.last', myparams, self.__globals__,scriptstr=scriptstr)
00214           if async :
00215             count = 0
00216             keybase =  time.strftime("%y%m%d.%H%M%S")
00217             key = keybase + "_" + str(count)
00218             while self.__async__.has_key(key) :
00219                count += 1
00220                key = keybase + "_" + str(count)
00221             result = tm.execute('ssoflux', vis, field, spw, modimage, fluxdensity, standard)
00222             print "Use: "
00223             print "      tm.retrieve(return_value) # to retrieve the status"
00224             print 
00225             self.rkey = key
00226             self.__async__[key] = result
00227           else :
00228               tname = 'ssoflux'
00229               spaces = ' '*(18-len(tname))
00230               casalog.post('\n##########################################'+
00231                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00232               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00233               result = ssoflux(vis, field, spw, modimage, fluxdensity, standard)
00234               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00235                            '\n##########################################')
00236 
00237         except Exception, instance:
00238           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00239              raise
00240           else :
00241              #print '**** Error **** ',instance
00242              tname = 'ssoflux'
00243              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00244              pass
00245 
00246         gc.collect()
00247         return result
00248 #
00249 #
00250 #
00251     def paramgui(self, useGlobals=True, ipython_globals=None):
00252         """
00253         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00254         """
00255         import paramgui
00256         if not hasattr(self, "__globals__") or self.__globals__ == None :
00257            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00258 
00259         if useGlobals:
00260             if ipython_globals == None:
00261                 myf=self.__globals__
00262             else:
00263                 myf=ipython_globals
00264 
00265             paramgui.setGlobals(myf)
00266         else:
00267             paramgui.setGlobals({})
00268 
00269         paramgui.runTask('ssoflux', myf['_ip'])
00270         paramgui.setGlobals({})
00271 
00272 #
00273 #
00274 #
00275     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00276         if not hasattr(self, "__globals__") or self.__globals__ == None :
00277            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00278         if ipython_globals == None:
00279             myf=self.__globals__
00280         else:
00281             myf=ipython_globals
00282 
00283         a = odict()
00284         a['vis']  = ''
00285         a['field']  = ''
00286         a['spw']  = ''
00287         a['modimage']  = ''
00288         a['fluxdensity']  = -1
00289         a['standard']  = 'Perley-Taylor 99'
00290 
00291         a['async']=False
00292 
00293 ### This function sets the default values but also will return the list of
00294 ### parameters or the default value of a given parameter
00295         if(param == None):
00296                 myf['__set_default_parameters'](a)
00297         elif(param == 'paramkeys'):
00298                 return a.keys()
00299         else:
00300             if(paramvalue==None and subparam==None):
00301                if(a.has_key(param)):
00302                   return a[param]
00303                else:
00304                   return self.itsdefault(param)
00305             else:
00306                retval=a[param]
00307                if(type(a[param])==dict):
00308                   for k in range(len(a[param])):
00309                      valornotval='value'
00310                      if(a[param][k].has_key('notvalue')):
00311                         valornotval='notvalue'
00312                      if((a[param][k][valornotval])==paramvalue):
00313                         retval=a[param][k].copy()
00314                         retval.pop(valornotval)
00315                         if(subparam != None):
00316                            if(retval.has_key(subparam)):
00317                               retval=retval[subparam]
00318                            else:
00319                               retval=self.itsdefault(subparam)
00320                      else:
00321                         retval=self.itsdefault(subparam)
00322                return retval
00323 
00324 
00325 #
00326 #
00327     def check_params(self, param=None, value=None, ipython_globals=None):
00328       if ipython_globals == None:
00329           myf=self.__globals__
00330       else:
00331           myf=ipython_globals
00332 #      print 'param:', param, 'value:', value
00333       try :
00334          if str(type(value)) != "<type 'instance'>" :
00335             value0 = value
00336             value = myf['cu'].expandparam(param, value)
00337             matchtype = False
00338             if(type(value) == numpy.ndarray):
00339                if(type(value) == type(value0)):
00340                   myf[param] = value.tolist()
00341                else:
00342                   #print 'value:', value, 'value0:', value0
00343                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00344                   myf[param] = value0
00345                   if type(value0) != list :
00346                      matchtype = True
00347             else :
00348                myf[param] = value
00349             value = myf['cu'].verifyparam({param:value})
00350             if matchtype:
00351                value = False
00352       except Exception, instance:
00353          #ignore the exception and just return it unchecked
00354          myf[param] = value
00355       return value
00356 #
00357 #
00358     def description(self, key='ssoflux', subkey=None):
00359         desc={'ssoflux': 'Fills the model column with the visibilities of a calibrator',
00360                'vis': 'Name of input visibility file',
00361                'field': 'Field name(s)',
00362                'spw': 'Spectral window identifier (list)',
00363                'modimage': 'File location for field model',
00364                'fluxdensity': 'Specified flux density [I,Q,U,V]; -1 will lookup values',
00365                'standard': 'Flux density standard',
00366 
00367                'async': 'If true the taskname must be started using ssoflux(...)'
00368               }
00369 
00370         if(desc.has_key(key)) :
00371            return desc[key]
00372 
00373     def itsdefault(self, paramname) :
00374         a = {}
00375         a['vis']  = ''
00376         a['field']  = ''
00377         a['spw']  = ''
00378         a['modimage']  = ''
00379         a['fluxdensity']  = -1
00380         a['standard']  = 'Perley-Taylor 99'
00381 
00382         #a = sys._getframe(len(inspect.stack())-1).f_globals
00383 
00384         if a.has_key(paramname) :
00385               return a[paramname]
00386 ssoflux_cli = ssoflux_cli_()