casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
vishead_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_vishead import vishead
00018 class vishead_cli_:
00019     __name__ = "vishead"
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__ = (vishead_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'mode':None, 'listitems':None, 'hdkey':None, 'hdindex':None, 'hdvalue':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, mode=None, listitems=None, hdkey=None, hdindex=None, hdvalue=None,  async=None):
00047 
00048         """List, summary, get, and put metadata in a measurement set
00049 
00050         This task allows the user to manipulate some meta-data parameters in a
00051         measurement set.  The mode='list' shows those keywords that are
00052         presently implemented, with their values.  The contents associated
00053         with the keywords can be obtained (get) and changed (put).
00054 
00055         The modes that are available are:
00056 
00057            list    --- List all keywords that are recognized, and list the
00058                        value(s) for each.  Only these keywords can be obtained
00059                        (get) or changed (put) 
00060            summary --- Equivalent to running taskname='listobs'; verbose=F
00061            get     --- Get the specified keyword value(s) from the ms
00062            put     --- Put the specified keyword value(s) into the ms
00063 
00064         Parameters currently implemented are (June 1, 2009):
00065 
00066            cal_grp              
00067            field                 Field names
00068            fld_code              Field Observing codes
00069            freq_group_name       
00070            log                   
00071            observer              Observer name
00072            project               Project name
00073            ptcs                  Phase tracking centers for each field
00074            release_date          
00075            schedule
00076            schedule_type
00077            spw_name              Spectral parameters?
00078            source_name           Source Names (=Field Names?)
00079            telescope             Telescope Name
00080 
00081         Keyword arguments:
00082 
00083         vis  --- Name of input visibility file
00084                   default: none, example: vis='my.ms'
00085 
00086         mode --- Mode of operation for vishead
00087                   default = 'list'; example: mode='get'
00088 
00089         hdkey--- keyword to get or put from the ms (used in get/put mode only)
00090                   ex: hdkey='telescope'
00091 
00092         hdindex--- index (counting from 0) if keyword is an array (used in get/put
00093                   mode only)
00094                   ex: hdindex='2'; hdindex=''->put/get full array; 
00095 
00096         hdvalue   --- value to be put in the MS (used in put mode only)
00097                   ex: hdvalue=array(['MyTelescope'])
00098 
00099 
00100 
00101 
00102         Examples:
00103 
00104            To transfer the parameters to useful python items requires some care.
00105 
00106            taskname = 'vishead'
00107            default() 
00108            vis = '3C84C.ms'
00109            mode = 'get'
00110                       
00111            to get a field name (string),
00112               hdkey = 'field'; hdindex = '2'; hdvalue=vishead(); 
00113                        print hdvalue[0] = the name for field='2'                    
00114                 
00115            to get an phase center (number)
00116               hdkey = 'ptcs'; hdindex = '1'; hdvalue = vishead();
00117                        hdvalue[0][0] gives the ra, hdvalue[0][1] gives the dec in field '1'
00118 
00119 
00120            taskname = 'vishead'
00121            default() 
00122            vis = '3C84C.ms'
00123            mode = 'put'
00124 
00125           To change a string,
00126 
00127               hdkey = 'field'; hdindex = '2'; hdvalue = 'junk'; vishead()
00128                    field='2' is renamed 'junk'
00129 
00130           To change a number, (egs. ra of field=1 to 0.5 radian)
00131               is too complicated to figure out!
00132              
00133 
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'] = 'vishead'
00142         self.__globals__['taskname'] = 'vishead'
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['mode'] = mode = self.parameters['mode']
00183             myparams['listitems'] = listitems = self.parameters['listitems']
00184             myparams['hdkey'] = hdkey = self.parameters['hdkey']
00185             myparams['hdindex'] = hdindex = self.parameters['hdindex']
00186             myparams['hdvalue'] = hdvalue = self.parameters['hdvalue']
00187 
00188         if type(listitems)==str: listitems=[listitems]
00189 
00190         result = None
00191 
00192 #
00193 #    The following is work around to avoid a bug with current python translation
00194 #
00195         mytmp = {}
00196 
00197         mytmp['vis'] = vis
00198         mytmp['mode'] = mode
00199         mytmp['listitems'] = listitems
00200         mytmp['hdkey'] = hdkey
00201         mytmp['hdindex'] = hdindex
00202         mytmp['hdvalue'] = hdvalue
00203         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00204         trec = casac.casac.utils().torecord(pathname+'vishead.xml')
00205 
00206         casalog.origin('vishead')
00207         try :
00208           #if not trec.has_key('vishead') or not casac.casac.utils().verify(mytmp, trec['vishead']) :
00209             #return False
00210 
00211           casac.casac.utils().verify(mytmp, trec['vishead'], True)
00212           scriptstr=['']
00213           saveinputs = self.__globals__['saveinputs']
00214           saveinputs('vishead', 'vishead.last', myparams, self.__globals__,scriptstr=scriptstr)
00215           if async :
00216             count = 0
00217             keybase =  time.strftime("%y%m%d.%H%M%S")
00218             key = keybase + "_" + str(count)
00219             while self.__async__.has_key(key) :
00220                count += 1
00221                key = keybase + "_" + str(count)
00222             result = tm.execute('vishead', vis, mode, listitems, hdkey, hdindex, hdvalue)
00223             print "Use: "
00224             print "      tm.retrieve(return_value) # to retrieve the status"
00225             print 
00226             self.rkey = key
00227             self.__async__[key] = result
00228           else :
00229               tname = 'vishead'
00230               spaces = ' '*(18-len(tname))
00231               casalog.post('\n##########################################'+
00232                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00233               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00234               result = vishead(vis, mode, listitems, hdkey, hdindex, hdvalue)
00235               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00236                            '\n##########################################')
00237 
00238         except Exception, instance:
00239           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00240              raise
00241           else :
00242              #print '**** Error **** ',instance
00243              tname = 'vishead'
00244              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00245              pass
00246 
00247         gc.collect()
00248         return result
00249 #
00250 #
00251 #
00252     def paramgui(self, useGlobals=True, ipython_globals=None):
00253         """
00254         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00255         """
00256         import paramgui
00257         if not hasattr(self, "__globals__") or self.__globals__ == None :
00258            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00259 
00260         if useGlobals:
00261             if ipython_globals == None:
00262                 myf=self.__globals__
00263             else:
00264                 myf=ipython_globals
00265 
00266             paramgui.setGlobals(myf)
00267         else:
00268             paramgui.setGlobals({})
00269 
00270         paramgui.runTask('vishead', myf['_ip'])
00271         paramgui.setGlobals({})
00272 
00273 #
00274 #
00275 #
00276     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00277         if not hasattr(self, "__globals__") or self.__globals__ == None :
00278            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00279         if ipython_globals == None:
00280             myf=self.__globals__
00281         else:
00282             myf=ipython_globals
00283 
00284         a = odict()
00285         a['vis']  = ''
00286         a['mode']  = 'summary'
00287 
00288         a['async']=False
00289         a['mode'] = {
00290                     0:odict([{'value':'list'}, {'listitems':['telescope', 'observer', 'project', 'field', 'freq_group_name', 'spw_name', 'schedule', 'schedule_type', 'release_date']}]), 
00291                     1:{'value':'summary'}, 
00292                     2:odict([{'value':'get'}, {'hdkey':''}, {'hdindex':''}]), 
00293                     3:odict([{'value':'put'}, {'hdkey':''}, {'hdindex':''}, {'hdvalue':''}])}
00294 
00295 ### This function sets the default values but also will return the list of
00296 ### parameters or the default value of a given parameter
00297         if(param == None):
00298                 myf['__set_default_parameters'](a)
00299         elif(param == 'paramkeys'):
00300                 return a.keys()
00301         else:
00302             if(paramvalue==None and subparam==None):
00303                if(a.has_key(param)):
00304                   return a[param]
00305                else:
00306                   return self.itsdefault(param)
00307             else:
00308                retval=a[param]
00309                if(type(a[param])==dict):
00310                   for k in range(len(a[param])):
00311                      valornotval='value'
00312                      if(a[param][k].has_key('notvalue')):
00313                         valornotval='notvalue'
00314                      if((a[param][k][valornotval])==paramvalue):
00315                         retval=a[param][k].copy()
00316                         retval.pop(valornotval)
00317                         if(subparam != None):
00318                            if(retval.has_key(subparam)):
00319                               retval=retval[subparam]
00320                            else:
00321                               retval=self.itsdefault(subparam)
00322                      else:
00323                         retval=self.itsdefault(subparam)
00324                return retval
00325 
00326 
00327 #
00328 #
00329     def check_params(self, param=None, value=None, ipython_globals=None):
00330       if ipython_globals == None:
00331           myf=self.__globals__
00332       else:
00333           myf=ipython_globals
00334 #      print 'param:', param, 'value:', value
00335       try :
00336          if str(type(value)) != "<type 'instance'>" :
00337             value0 = value
00338             value = myf['cu'].expandparam(param, value)
00339             matchtype = False
00340             if(type(value) == numpy.ndarray):
00341                if(type(value) == type(value0)):
00342                   myf[param] = value.tolist()
00343                else:
00344                   #print 'value:', value, 'value0:', value0
00345                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00346                   myf[param] = value0
00347                   if type(value0) != list :
00348                      matchtype = True
00349             else :
00350                myf[param] = value
00351             value = myf['cu'].verifyparam({param:value})
00352             if matchtype:
00353                value = False
00354       except Exception, instance:
00355          #ignore the exception and just return it unchecked
00356          myf[param] = value
00357       return value
00358 #
00359 #
00360     def description(self, key='vishead', subkey=None):
00361         desc={'vishead': 'List, summary, get, and put metadata in a measurement set',
00362                'vis': 'Name of input visibility file',
00363                'mode': 'options: list, summary, get, put',
00364                'listitems': 'items to list ([] for all)',
00365                'hdkey': 'keyword to get/put',
00366                'hdindex': 'keyword index to get/put, counting from zero. ''==>all',
00367                'hdvalue': 'value of hdkey',
00368 
00369                'async': 'If true the taskname must be started using vishead(...)'
00370               }
00371 
00372 #
00373 # Set subfields defaults if needed
00374 #
00375 
00376         if(desc.has_key(key)) :
00377            return desc[key]
00378 
00379     def itsdefault(self, paramname) :
00380         a = {}
00381         a['vis']  = ''
00382         a['mode']  = 'summary'
00383         a['listitems']  = ['telescope', 'observer', 'project', 'field', 'freq_group_name', 'spw_name', 'schedule', 'schedule_type', 'release_date']
00384         a['hdkey']  = ''
00385         a['hdindex']  = ''
00386         a['hdvalue']  = ''
00387 
00388         #a = sys._getframe(len(inspect.stack())-1).f_globals
00389 
00390         if self.parameters['mode']  == 'list':
00391             a['listitems'] = ['telescope', 'observer', 'project', 'field', 'freq_group_name', 'spw_name', 'schedule', 'schedule_type', 'release_date']
00392 
00393         if self.parameters['mode']  == 'get':
00394             a['hdkey'] = ''
00395             a['hdindex'] = ''
00396 
00397         if self.parameters['mode']  == 'put':
00398             a['hdkey'] = ''
00399             a['hdindex'] = ''
00400             a['hdvalue'] = ''
00401 
00402         if a.has_key(paramname) :
00403               return a[paramname]
00404 vishead_cli = vishead_cli_()