casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
fixvis_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_fixvis import fixvis
00018 class fixvis_cli_:
00019     __name__ = "fixvis"
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__ = (fixvis_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'outputvis':None, 'field':None, 'refcode':None, 'reuse':None, 'phasecenter':None, 'datacolumn':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, outputvis=None, field=None, refcode=None, reuse=None, phasecenter=None, datacolumn=None,  async=None):
00047 
00048         """Recalculates (u, v, w) and/or changes Phase Center 
00049 
00050 If the phase center is changed, the corresponding modifications are applied to the 
00051 visibility columns given by the parameter "datacolumn" which is by default set 
00052 to "all" (DATA, CORRECTED, and MODEL).
00053 
00054     Input Parameters
00055     vis        -- Name of the input visibility set
00056     
00057     outputvis  -- Name of the output visibility set, default: same as vis
00058 
00059     field      -- field selection string
00060 
00061     refcode    -- Reference frame to convert to, default: the refcode of PHASE_DIR in the 
00062                   FIELD table
00063                   example: 'B1950'
00064     
00065     reuse      -- base recalculation on existing UVW coordinates? default=True
00066                   ignored if parameter 'phasecenter' is set
00067 
00068     phasecenter  --  if set to a valid direction: change the phase center for the given 
00069                      field to this value
00070                example: 'J2000 9h25m00s -05d12m00s'
00071                If given without the equinox, e.g. '0h01m00s +00d12m00s', the parameter
00072                is interpreted as a pair of offsets in RA and DEC to the present 
00073                phasecenter. The RA offset can be given in units of time or angle. If given 
00074                as a time, it is applied as is. If given as an angle, it is corrected for 
00075                the cos(DEC) before it is applied.
00076 
00077     datacolumn -- when applying a phase center shift, modify visibilities only in 
00078                   this/these column(s)
00079                   default: 'all' (DATA, CORRECTED, and MODEL)
00080                   example: 'DATA,CORRECTED' (will not modify MODEL)
00081                
00082     Examples:
00083 
00084     fixvis('NGC3256.ms','NGC3256-fixed.ms')
00085           will recalculate the UVW coordinates for all fields based on the existing
00086           phase center information in the FIELD table.
00087 
00088     fixvis('Moon.ms','Moon-fixed.ms','Moon', '', 'J2000 9h25m00s 05d12m00s')
00089           will set the phase center for field 'Moon' to the given direction and recalculate
00090           the UVW coordinates.
00091 
00092 
00093         """
00094         if not hasattr(self, "__globals__") or self.__globals__ == None :
00095            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00096         #casac = self.__globals__['casac']
00097         casalog = self.__globals__['casalog']
00098         #casalog = casac.casac.logsink()
00099         self.__globals__['__last_task'] = 'fixvis'
00100         self.__globals__['taskname'] = 'fixvis'
00101         ###
00102         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00103         ###
00104         ###
00105         #Handle globals or user over-ride of arguments
00106         #
00107         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00108         useLocalDefaults = False
00109 
00110         for item in function_signature_defaults.iteritems():
00111                 key,val = item
00112                 keyVal = eval(key)
00113                 if (keyVal == None):
00114                         #user hasn't set it - use global/default
00115                         pass
00116                 else:
00117                         #user has set it - use over-ride
00118                         if (key != 'self') :
00119                            useLocalDefaults = True
00120 
00121         myparams = {}
00122         if useLocalDefaults :
00123            for item in function_signature_defaults.iteritems():
00124                key,val = item
00125                keyVal = eval(key)
00126                exec('myparams[key] = keyVal')
00127                self.parameters[key] = keyVal
00128                if (keyVal == None):
00129                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00130                    keyVal = eval(key)
00131                    if(type(keyVal) == dict) :
00132                       if len(keyVal) > 0 :
00133                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00134                       else :
00135                          exec('myparams[key] = ' + key + ' = {}')
00136 
00137         else :
00138             async = self.parameters['async']
00139             myparams['vis'] = vis = self.parameters['vis']
00140             myparams['outputvis'] = outputvis = self.parameters['outputvis']
00141             myparams['field'] = field = self.parameters['field']
00142             myparams['refcode'] = refcode = self.parameters['refcode']
00143             myparams['reuse'] = reuse = self.parameters['reuse']
00144             myparams['phasecenter'] = phasecenter = self.parameters['phasecenter']
00145             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00146 
00147 
00148         result = None
00149 
00150 #
00151 #    The following is work around to avoid a bug with current python translation
00152 #
00153         mytmp = {}
00154 
00155         mytmp['vis'] = vis
00156         mytmp['outputvis'] = outputvis
00157         mytmp['field'] = field
00158         mytmp['refcode'] = refcode
00159         mytmp['reuse'] = reuse
00160         mytmp['phasecenter'] = phasecenter
00161         mytmp['datacolumn'] = datacolumn
00162         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00163         trec = casac.casac.utils().torecord(pathname+'fixvis.xml')
00164 
00165         casalog.origin('fixvis')
00166         try :
00167           #if not trec.has_key('fixvis') or not casac.casac.utils().verify(mytmp, trec['fixvis']) :
00168             #return False
00169 
00170           casac.casac.utils().verify(mytmp, trec['fixvis'], True)
00171           scriptstr=['']
00172           saveinputs = self.__globals__['saveinputs']
00173           saveinputs('fixvis', 'fixvis.last', myparams, self.__globals__,scriptstr=scriptstr)
00174           if async :
00175             count = 0
00176             keybase =  time.strftime("%y%m%d.%H%M%S")
00177             key = keybase + "_" + str(count)
00178             while self.__async__.has_key(key) :
00179                count += 1
00180                key = keybase + "_" + str(count)
00181             result = tm.execute('fixvis', vis, outputvis, field, refcode, reuse, phasecenter, datacolumn)
00182             print "Use: "
00183             print "      tm.retrieve(return_value) # to retrieve the status"
00184             print 
00185             self.rkey = key
00186             self.__async__[key] = result
00187           else :
00188               tname = 'fixvis'
00189               spaces = ' '*(18-len(tname))
00190               casalog.post('\n##########################################'+
00191                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00192               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00193               result = fixvis(vis, outputvis, field, refcode, reuse, phasecenter, datacolumn)
00194               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00195                            '\n##########################################')
00196 
00197         except Exception, instance:
00198           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00199              raise
00200           else :
00201              #print '**** Error **** ',instance
00202              tname = 'fixvis'
00203              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00204              pass
00205 
00206         gc.collect()
00207         return result
00208 #
00209 #
00210 #
00211     def paramgui(self, useGlobals=True, ipython_globals=None):
00212         """
00213         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00214         """
00215         import paramgui
00216         if not hasattr(self, "__globals__") or self.__globals__ == None :
00217            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00218 
00219         if useGlobals:
00220             if ipython_globals == None:
00221                 myf=self.__globals__
00222             else:
00223                 myf=ipython_globals
00224 
00225             paramgui.setGlobals(myf)
00226         else:
00227             paramgui.setGlobals({})
00228 
00229         paramgui.runTask('fixvis', myf['_ip'])
00230         paramgui.setGlobals({})
00231 
00232 #
00233 #
00234 #
00235     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00236         if not hasattr(self, "__globals__") or self.__globals__ == None :
00237            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00238         if ipython_globals == None:
00239             myf=self.__globals__
00240         else:
00241             myf=ipython_globals
00242 
00243         a = odict()
00244         a['vis']  = ''
00245         a['outputvis']  = ''
00246         a['field']  = ""
00247         a['refcode']  = ''
00248         a['reuse']  = True
00249         a['phasecenter']  = ''
00250         a['datacolumn']  = 'all'
00251 
00252         a['async']=False
00253 
00254 ### This function sets the default values but also will return the list of
00255 ### parameters or the default value of a given parameter
00256         if(param == None):
00257                 myf['__set_default_parameters'](a)
00258         elif(param == 'paramkeys'):
00259                 return a.keys()
00260         else:
00261             if(paramvalue==None and subparam==None):
00262                if(a.has_key(param)):
00263                   return a[param]
00264                else:
00265                   return self.itsdefault(param)
00266             else:
00267                retval=a[param]
00268                if(type(a[param])==dict):
00269                   for k in range(len(a[param])):
00270                      valornotval='value'
00271                      if(a[param][k].has_key('notvalue')):
00272                         valornotval='notvalue'
00273                      if((a[param][k][valornotval])==paramvalue):
00274                         retval=a[param][k].copy()
00275                         retval.pop(valornotval)
00276                         if(subparam != None):
00277                            if(retval.has_key(subparam)):
00278                               retval=retval[subparam]
00279                            else:
00280                               retval=self.itsdefault(subparam)
00281                      else:
00282                         retval=self.itsdefault(subparam)
00283                return retval
00284 
00285 
00286 #
00287 #
00288     def check_params(self, param=None, value=None, ipython_globals=None):
00289       if ipython_globals == None:
00290           myf=self.__globals__
00291       else:
00292           myf=ipython_globals
00293 #      print 'param:', param, 'value:', value
00294       try :
00295          if str(type(value)) != "<type 'instance'>" :
00296             value0 = value
00297             value = myf['cu'].expandparam(param, value)
00298             matchtype = False
00299             if(type(value) == numpy.ndarray):
00300                if(type(value) == type(value0)):
00301                   myf[param] = value.tolist()
00302                else:
00303                   #print 'value:', value, 'value0:', value0
00304                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00305                   myf[param] = value0
00306                   if type(value0) != list :
00307                      matchtype = True
00308             else :
00309                myf[param] = value
00310             value = myf['cu'].verifyparam({param:value})
00311             if matchtype:
00312                value = False
00313       except Exception, instance:
00314          #ignore the exception and just return it unchecked
00315          myf[param] = value
00316       return value
00317 #
00318 #
00319     def description(self, key='fixvis', subkey=None):
00320         desc={'fixvis': 'Recalculates (u, v, w) and/or changes Phase Center ',
00321                'vis': 'Name of the input visibility set.',
00322                'outputvis': 'Name of the output visibility set.  (Can be the same as vis.)',
00323                'field': 'Fields to operate on.  '' = all.',
00324                'refcode': 'reference frame to convert UVW coordinates to',
00325                'reuse': 'base UVW calculation on the old values?',
00326                'phasecenter': 'use this direction as phase center',
00327                'datacolumn': 'when applying a phase center shift, modify visibilities only in this/these column(s)',
00328 
00329                'async': 'If true the taskname must be started using fixvis(...)'
00330               }
00331 
00332         if(desc.has_key(key)) :
00333            return desc[key]
00334 
00335     def itsdefault(self, paramname) :
00336         a = {}
00337         a['vis']  = ''
00338         a['outputvis']  = ''
00339         a['field']  = ""
00340         a['refcode']  = ''
00341         a['reuse']  = True
00342         a['phasecenter']  = ''
00343         a['datacolumn']  = 'all'
00344 
00345         #a = sys._getframe(len(inspect.stack())-1).f_globals
00346 
00347         if a.has_key(paramname) :
00348               return a[paramname]
00349 fixvis_cli = fixvis_cli_()