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