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