casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
importgmrt_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_importgmrt import importgmrt
00018 class importgmrt_cli_:
00019     __name__ = "importgmrt"
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__ = (importgmrt_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'fitsfile':None, 'flagfile':None, 'vis':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, fitsfile=None, flagfile=None, vis=None,  async=None):
00047 
00048         """Convert a UVFITS file to a CASA visibility data set
00049         Convert a GMRT FITS file to a CASA visibility data set:
00050 
00051         Keyword arguments:
00052         fitsfile -- Name of input UV FITS file
00053                     default: none; example='3C273XC1.fits'
00054         flagfile -- List of files containing flagging information.
00055                     default: none; example='3c273XC1.flag'
00056                                    example=['3c273Cc1_1.flag','3c273Cc2_1.flag',']
00057         vis      -- Name of output visibility file (MS)
00058                     default: none; example: vis='3C273XC1.ms'
00059         async    -- Run asynchronously
00060                     default = false; do not run asychronously
00061 
00062         Note: Don't forget to flag autocorrections using
00063            taskname flagdata, autocorr = true
00064 
00065  
00066         """
00067         if not hasattr(self, "__globals__") or self.__globals__ == None :
00068            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00069         #casac = self.__globals__['casac']
00070         casalog = self.__globals__['casalog']
00071         #casalog = casac.casac.logsink()
00072         self.__globals__['__last_task'] = 'importgmrt'
00073         self.__globals__['taskname'] = 'importgmrt'
00074         ###
00075         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00076         ###
00077         ###
00078         #Handle globals or user over-ride of arguments
00079         #
00080         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00081         useLocalDefaults = False
00082 
00083         for item in function_signature_defaults.iteritems():
00084                 key,val = item
00085                 keyVal = eval(key)
00086                 if (keyVal == None):
00087                         #user hasn't set it - use global/default
00088                         pass
00089                 else:
00090                         #user has set it - use over-ride
00091                         if (key != 'self') :
00092                            useLocalDefaults = True
00093 
00094         myparams = {}
00095         if useLocalDefaults :
00096            for item in function_signature_defaults.iteritems():
00097                key,val = item
00098                keyVal = eval(key)
00099                exec('myparams[key] = keyVal')
00100                self.parameters[key] = keyVal
00101                if (keyVal == None):
00102                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00103                    keyVal = eval(key)
00104                    if(type(keyVal) == dict) :
00105                       if len(keyVal) > 0 :
00106                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00107                       else :
00108                          exec('myparams[key] = ' + key + ' = {}')
00109 
00110         else :
00111             async = self.parameters['async']
00112             myparams['fitsfile'] = fitsfile = self.parameters['fitsfile']
00113             myparams['flagfile'] = flagfile = self.parameters['flagfile']
00114             myparams['vis'] = vis = self.parameters['vis']
00115 
00116 
00117         result = None
00118 
00119 #
00120 #    The following is work around to avoid a bug with current python translation
00121 #
00122         mytmp = {}
00123 
00124         mytmp['fitsfile'] = fitsfile
00125         mytmp['flagfile'] = flagfile
00126         mytmp['vis'] = vis
00127         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00128         trec = casac.casac.utils().torecord(pathname+'importgmrt.xml')
00129 
00130         casalog.origin('importgmrt')
00131         try :
00132           #if not trec.has_key('importgmrt') or not casac.casac.utils().verify(mytmp, trec['importgmrt']) :
00133             #return False
00134 
00135           casac.casac.utils().verify(mytmp, trec['importgmrt'], True)
00136           scriptstr=['']
00137           saveinputs = self.__globals__['saveinputs']
00138           saveinputs('importgmrt', 'importgmrt.last', myparams, self.__globals__,scriptstr=scriptstr)
00139           if async :
00140             count = 0
00141             keybase =  time.strftime("%y%m%d.%H%M%S")
00142             key = keybase + "_" + str(count)
00143             while self.__async__.has_key(key) :
00144                count += 1
00145                key = keybase + "_" + str(count)
00146             result = tm.execute('importgmrt', fitsfile, flagfile, vis)
00147             print "Use: "
00148             print "      tm.retrieve(return_value) # to retrieve the status"
00149             print 
00150             self.rkey = key
00151             self.__async__[key] = result
00152           else :
00153               tname = 'importgmrt'
00154               spaces = ' '*(18-len(tname))
00155               casalog.post('\n##########################################'+
00156                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00157               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00158               result = importgmrt(fitsfile, flagfile, vis)
00159               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00160                            '\n##########################################')
00161 
00162         except Exception, instance:
00163           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00164              raise
00165           else :
00166              #print '**** Error **** ',instance
00167              tname = 'importgmrt'
00168              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00169              pass
00170 
00171         gc.collect()
00172         return result
00173 #
00174 #
00175 #
00176     def paramgui(self, useGlobals=True, ipython_globals=None):
00177         """
00178         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00179         """
00180         import paramgui
00181         if not hasattr(self, "__globals__") or self.__globals__ == None :
00182            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00183 
00184         if useGlobals:
00185             if ipython_globals == None:
00186                 myf=self.__globals__
00187             else:
00188                 myf=ipython_globals
00189 
00190             paramgui.setGlobals(myf)
00191         else:
00192             paramgui.setGlobals({})
00193 
00194         paramgui.runTask('importgmrt', myf['_ip'])
00195         paramgui.setGlobals({})
00196 
00197 #
00198 #
00199 #
00200     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00201         if not hasattr(self, "__globals__") or self.__globals__ == None :
00202            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00203         if ipython_globals == None:
00204             myf=self.__globals__
00205         else:
00206             myf=ipython_globals
00207 
00208         a = odict()
00209         a['fitsfile']  = ''
00210         a['flagfile']  = ''
00211         a['vis']  = ''
00212 
00213         a['async']=False
00214 
00215 ### This function sets the default values but also will return the list of
00216 ### parameters or the default value of a given parameter
00217         if(param == None):
00218                 myf['__set_default_parameters'](a)
00219         elif(param == 'paramkeys'):
00220                 return a.keys()
00221         else:
00222             if(paramvalue==None and subparam==None):
00223                if(a.has_key(param)):
00224                   return a[param]
00225                else:
00226                   return self.itsdefault(param)
00227             else:
00228                retval=a[param]
00229                if(type(a[param])==dict):
00230                   for k in range(len(a[param])):
00231                      valornotval='value'
00232                      if(a[param][k].has_key('notvalue')):
00233                         valornotval='notvalue'
00234                      if((a[param][k][valornotval])==paramvalue):
00235                         retval=a[param][k].copy()
00236                         retval.pop(valornotval)
00237                         if(subparam != None):
00238                            if(retval.has_key(subparam)):
00239                               retval=retval[subparam]
00240                            else:
00241                               retval=self.itsdefault(subparam)
00242                      else:
00243                         retval=self.itsdefault(subparam)
00244                return retval
00245 
00246 
00247 #
00248 #
00249     def check_params(self, param=None, value=None, ipython_globals=None):
00250       if ipython_globals == None:
00251           myf=self.__globals__
00252       else:
00253           myf=ipython_globals
00254 #      print 'param:', param, 'value:', value
00255       try :
00256          if str(type(value)) != "<type 'instance'>" :
00257             value0 = value
00258             value = myf['cu'].expandparam(param, value)
00259             matchtype = False
00260             if(type(value) == numpy.ndarray):
00261                if(type(value) == type(value0)):
00262                   myf[param] = value.tolist()
00263                else:
00264                   #print 'value:', value, 'value0:', value0
00265                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00266                   myf[param] = value0
00267                   if type(value0) != list :
00268                      matchtype = True
00269             else :
00270                myf[param] = value
00271             value = myf['cu'].verifyparam({param:value})
00272             if matchtype:
00273                value = False
00274       except Exception, instance:
00275          #ignore the exception and just return it unchecked
00276          myf[param] = value
00277       return value
00278 #
00279 #
00280     def description(self, key='importgmrt', subkey=None):
00281         desc={'importgmrt': 'Convert a UVFITS file to a CASA visibility data set',
00282                'fitsfile': 'Name of input UV FITS file',
00283                'flagfile': 'Name of output visibility file (MS)',
00284                'vis': 'Name of output visibility file (MS)',
00285 
00286                'async': 'If true the taskname must be started using importgmrt(...)'
00287               }
00288 
00289         if(desc.has_key(key)) :
00290            return desc[key]
00291 
00292     def itsdefault(self, paramname) :
00293         a = {}
00294         a['fitsfile']  = ''
00295         a['flagfile']  = ''
00296         a['vis']  = ''
00297 
00298         #a = sys._getframe(len(inspect.stack())-1).f_globals
00299 
00300         if a.has_key(paramname) :
00301               return a[paramname]
00302 importgmrt_cli = importgmrt_cli_()