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