casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
fixplanets_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_fixplanets import fixplanets
00018 class fixplanets_cli_:
00019     __name__ = "fixplanets"
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__ = (fixplanets_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'fixuvw':None, 'direction':None, 'refant':None, 'reftime':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, fixuvw=None, direction=None, refant=None, reftime=None,  async=None):
00047 
00048         """Changes FIELD and SOURCE table entries based on user given direction or POINTING table, optionally fixes the UVW coordinates
00049     This task's main purpose is to correct observations which were performed
00050     with correct pointing and correlation but for which incorrect direction
00051     information was entered in the FIELD and SOURCE table of the MS.
00052     If you actually want to change the phase center of the visibilties in an MS,
00053     you should use task fixvis.
00054 
00055     Input Parameters
00056     vis        -- Name of the input visibility set
00057     
00058     field      -- field selection string
00059     
00060     fixuvw     -- recalc uvw coordinates? (default: False)
00061 
00062     direction  -- if set, don't use pointing table but set direction to this value
00063                   default= '' (use pointing table)
00064                   example: 'J2000 19h30m00 -40d00m00'
00065 
00066     refant     -- if using pointing table information, use it from this antenna
00067                   default: 0 (antenna id 0)
00068                   examples: 'DV06' (antenna with name DV06)
00069                             3 (antenna id 3)
00070     reftime    -- if using pointing table information, use it from this timestamp
00071                   default: 'first'
00072                   examples: 'median' will use the median timestamp for the given field
00073                             using only the unflagged maintable rows 
00074                             '2012/07/11/08:41:32' will use the given timestamp (must be
00075                             within the observaton time)
00076 
00077     Examples:
00078 
00079     fixplanets('uid___A002_X1c6e54_X223.ms', 'Titan', True)
00080           will look up the pointing direction from antenna 0 for field 'Titan' in 
00081           the POINTING table based on the first timestamp in the main table rows for 
00082           this field, enter this direction in the FIELD and SOURCE tables, and then 
00083           recalculate the UVW coordinates for this field.
00084 
00085     fixplanets('uid___A002_X1c6e54_X223.ms', 'Titan', False, 'J2000 12h30m15 -02d12m00')
00086           will set the directions for field 'Titan' in the FIELD and SOURCE table to the
00087           given direction and not recalculate the UVW coordinates.
00088           (This can be useful for several purposes, among them preparing a concatenation
00089           of datasets. Only fields with the same direction will be recognised as identical.
00090           fixplanets can then be run again after the concatenation using parameters as in
00091           the first example above.)
00092 
00093 
00094         """
00095         if not hasattr(self, "__globals__") or self.__globals__ == None :
00096            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00097         #casac = self.__globals__['casac']
00098         casalog = self.__globals__['casalog']
00099         #casalog = casac.casac.logsink()
00100         self.__globals__['__last_task'] = 'fixplanets'
00101         self.__globals__['taskname'] = 'fixplanets'
00102         ###
00103         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00104         ###
00105         ###
00106         #Handle globals or user over-ride of arguments
00107         #
00108         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00109         useLocalDefaults = False
00110 
00111         for item in function_signature_defaults.iteritems():
00112                 key,val = item
00113                 keyVal = eval(key)
00114                 if (keyVal == None):
00115                         #user hasn't set it - use global/default
00116                         pass
00117                 else:
00118                         #user has set it - use over-ride
00119                         if (key != 'self') :
00120                            useLocalDefaults = True
00121 
00122         myparams = {}
00123         if useLocalDefaults :
00124            for item in function_signature_defaults.iteritems():
00125                key,val = item
00126                keyVal = eval(key)
00127                exec('myparams[key] = keyVal')
00128                self.parameters[key] = keyVal
00129                if (keyVal == None):
00130                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00131                    keyVal = eval(key)
00132                    if(type(keyVal) == dict) :
00133                       if len(keyVal) > 0 :
00134                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00135                       else :
00136                          exec('myparams[key] = ' + key + ' = {}')
00137 
00138         else :
00139             async = self.parameters['async']
00140             myparams['vis'] = vis = self.parameters['vis']
00141             myparams['field'] = field = self.parameters['field']
00142             myparams['fixuvw'] = fixuvw = self.parameters['fixuvw']
00143             myparams['direction'] = direction = self.parameters['direction']
00144             myparams['refant'] = refant = self.parameters['refant']
00145             myparams['reftime'] = reftime = self.parameters['reftime']
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['field'] = field
00157         mytmp['fixuvw'] = fixuvw
00158         mytmp['direction'] = direction
00159         mytmp['refant'] = refant
00160         mytmp['reftime'] = reftime
00161         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00162         trec = casac.casac.utils().torecord(pathname+'fixplanets.xml')
00163 
00164         casalog.origin('fixplanets')
00165         try :
00166           #if not trec.has_key('fixplanets') or not casac.casac.utils().verify(mytmp, trec['fixplanets']) :
00167             #return False
00168 
00169           casac.casac.utils().verify(mytmp, trec['fixplanets'], True)
00170           scriptstr=['']
00171           saveinputs = self.__globals__['saveinputs']
00172           saveinputs('fixplanets', 'fixplanets.last', myparams, self.__globals__,scriptstr=scriptstr)
00173           if async :
00174             count = 0
00175             keybase =  time.strftime("%y%m%d.%H%M%S")
00176             key = keybase + "_" + str(count)
00177             while self.__async__.has_key(key) :
00178                count += 1
00179                key = keybase + "_" + str(count)
00180             result = tm.execute('fixplanets', vis, field, fixuvw, direction, refant, reftime)
00181             print "Use: "
00182             print "      tm.retrieve(return_value) # to retrieve the status"
00183             print 
00184             self.rkey = key
00185             self.__async__[key] = result
00186           else :
00187               tname = 'fixplanets'
00188               spaces = ' '*(18-len(tname))
00189               casalog.post('\n##########################################'+
00190                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00191               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00192               result = fixplanets(vis, field, fixuvw, direction, refant, reftime)
00193               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00194                            '\n##########################################')
00195 
00196         except Exception, instance:
00197           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00198              raise
00199           else :
00200              #print '**** Error **** ',instance
00201              tname = 'fixplanets'
00202              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00203              pass
00204 
00205         gc.collect()
00206         return result
00207 #
00208 #
00209 #
00210     def paramgui(self, useGlobals=True, ipython_globals=None):
00211         """
00212         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00213         """
00214         import paramgui
00215         if not hasattr(self, "__globals__") or self.__globals__ == None :
00216            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00217 
00218         if useGlobals:
00219             if ipython_globals == None:
00220                 myf=self.__globals__
00221             else:
00222                 myf=ipython_globals
00223 
00224             paramgui.setGlobals(myf)
00225         else:
00226             paramgui.setGlobals({})
00227 
00228         paramgui.runTask('fixplanets', myf['_ip'])
00229         paramgui.setGlobals({})
00230 
00231 #
00232 #
00233 #
00234     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00235         if not hasattr(self, "__globals__") or self.__globals__ == None :
00236            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00237         if ipython_globals == None:
00238             myf=self.__globals__
00239         else:
00240             myf=ipython_globals
00241 
00242         a = odict()
00243         a['vis']  = ''
00244         a['field']  = ""
00245         a['fixuvw']  = False
00246         a['direction']  = ''
00247         a['refant']  = 0
00248         a['reftime']  = 'first'
00249 
00250         a['async']=False
00251 
00252 ### This function sets the default values but also will return the list of
00253 ### parameters or the default value of a given parameter
00254         if(param == None):
00255                 myf['__set_default_parameters'](a)
00256         elif(param == 'paramkeys'):
00257                 return a.keys()
00258         else:
00259             if(paramvalue==None and subparam==None):
00260                if(a.has_key(param)):
00261                   return a[param]
00262                else:
00263                   return self.itsdefault(param)
00264             else:
00265                retval=a[param]
00266                if(type(a[param])==dict):
00267                   for k in range(len(a[param])):
00268                      valornotval='value'
00269                      if(a[param][k].has_key('notvalue')):
00270                         valornotval='notvalue'
00271                      if((a[param][k][valornotval])==paramvalue):
00272                         retval=a[param][k].copy()
00273                         retval.pop(valornotval)
00274                         if(subparam != None):
00275                            if(retval.has_key(subparam)):
00276                               retval=retval[subparam]
00277                            else:
00278                               retval=self.itsdefault(subparam)
00279                      else:
00280                         retval=self.itsdefault(subparam)
00281                return retval
00282 
00283 
00284 #
00285 #
00286     def check_params(self, param=None, value=None, ipython_globals=None):
00287       if ipython_globals == None:
00288           myf=self.__globals__
00289       else:
00290           myf=ipython_globals
00291 #      print 'param:', param, 'value:', value
00292       try :
00293          if str(type(value)) != "<type 'instance'>" :
00294             value0 = value
00295             value = myf['cu'].expandparam(param, value)
00296             matchtype = False
00297             if(type(value) == numpy.ndarray):
00298                if(type(value) == type(value0)):
00299                   myf[param] = value.tolist()
00300                else:
00301                   #print 'value:', value, 'value0:', value0
00302                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00303                   myf[param] = value0
00304                   if type(value0) != list :
00305                      matchtype = True
00306             else :
00307                myf[param] = value
00308             value = myf['cu'].verifyparam({param:value})
00309             if matchtype:
00310                value = False
00311       except Exception, instance:
00312          #ignore the exception and just return it unchecked
00313          myf[param] = value
00314       return value
00315 #
00316 #
00317     def description(self, key='fixplanets', subkey=None):
00318         desc={'fixplanets': 'Changes FIELD and SOURCE table entries based on user given direction or POINTING table, optionally fixes the UVW coordinates',
00319                'vis': 'Name of the input visibility set.',
00320                'field': 'Fields to operate on.  Blank = all.',
00321                'fixuvw': 'recalc uvw?',
00322                'direction': 'if set, don\'t use pointing table but set direction to this value',
00323                'refant': 'if using pointing table information, use it from this antenna',
00324                'reftime': 'if using pointing table information, use it from this timestamp (\'first\', \'median\', or YYYY/MM/DD/hh:mm:ss)',
00325 
00326                'async': 'If true the taskname must be started using fixplanets(...)'
00327               }
00328 
00329         if(desc.has_key(key)) :
00330            return desc[key]
00331 
00332     def itsdefault(self, paramname) :
00333         a = {}
00334         a['vis']  = ''
00335         a['field']  = ""
00336         a['fixuvw']  = False
00337         a['direction']  = ''
00338         a['refant']  = 0
00339         a['reftime']  = 'first'
00340 
00341         #a = sys._getframe(len(inspect.stack())-1).f_globals
00342 
00343         if a.has_key(paramname) :
00344               return a[paramname]
00345 fixplanets_cli = fixplanets_cli_()