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