casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
feather_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_feather import feather
00018 class feather_cli_:
00019     __name__ = "feather"
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__ = (feather_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'highres':None, 'lowres':None, 'sdfactor':None, 'effdishdiam':None, 'showplot':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, highres=None, lowres=None, sdfactor=None, effdishdiam=None, showplot=None,  async=None):
00047 
00048         """Combine two images using their Fourier transforms
00049 
00050         Feathering is a simple method for combining two images with different 
00051         spatial resolution.  The processing steps are:
00052 
00053                1. Regrid the low-resolution image to a temporary copy matching the
00054                    resolution of the high-resolution image,
00055                2. Transform each image to the spatial-frequency plane (gridded).
00056                3. Scale the low-resolution image (uv-grid) by the ratio of the
00057                    volumes of the two 'clean beams' (high-res/low-res). 
00058                4. Add to this, the uv-grid of the high-resolution image, scaled by
00059                    (1-wt) where 'wt' is the Fourier transform of the 'clean beam'
00060                    defined in the low-resolution image.
00061                5. Transform back to the image plane.
00062 
00063         Both input images must have a well-defined beam shape for this task to work. 
00064         This could be a 'clean beam' for interferometric images, and a 'primary-beam' 
00065         for a single-dish image. 
00066 
00067         The two images must also have the same flux density normalization scale.
00068 
00069         Keyword arguments:
00070         imagename -- Name of output feathered image
00071                 default: none; example: imagename='orion_combined.im'
00072         highres -- Name of high resolution (interferometer) image
00073                 default: none; example: highres='orion_vla.im'
00074              This image is often a clean image obtained from synthesis
00075                 observations.
00076         lowres -- Name of low resolution (single dish) image
00077                 default: none; example: lowres='orion_gbt.im'
00078              This image is often a image from a single-dish observations
00079                 or a clean image obtained from lower resolution synthesis
00080                 observations.
00081          sdfactor -- value by which to scale the Single Dish image. Default is 1.0
00082                          Basically modifying the flux scale of the SD image
00083          effdishdiam -- New effective SingleDish diameter to use in m. Obviously one can only reduce the dish effective dish diameter in feathering. Default -1.0 means leave as is.
00084          showplot -- If True will plot the cuts across the feathring function
00085 
00086 
00087         Comments:
00088 
00089         This task can be used as one method of combining single-dish and 
00090         interferometric images after they have been separately made.
00091         
00092         The clean task allows another method of combining single-dish and
00093         interferometric data. The single-dish image can be used as a starting 
00094         model for the interferometric image-reconstruction. If there is
00095         some overlap between the spatial-frequencies contained in the 
00096         single-dish image and the interferometer sampling function, then,
00097         such a starting model will help constrain the solutions on the 
00098         short-baselines of the interferometric data.
00099         
00100 
00101 
00102         """
00103         if not hasattr(self, "__globals__") or self.__globals__ == None :
00104            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00105         #casac = self.__globals__['casac']
00106         casalog = self.__globals__['casalog']
00107         #casalog = casac.casac.logsink()
00108         self.__globals__['__last_task'] = 'feather'
00109         self.__globals__['taskname'] = 'feather'
00110         ###
00111         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00112         ###
00113         ###
00114         #Handle globals or user over-ride of arguments
00115         #
00116         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00117         useLocalDefaults = False
00118 
00119         for item in function_signature_defaults.iteritems():
00120                 key,val = item
00121                 keyVal = eval(key)
00122                 if (keyVal == None):
00123                         #user hasn't set it - use global/default
00124                         pass
00125                 else:
00126                         #user has set it - use over-ride
00127                         if (key != 'self') :
00128                            useLocalDefaults = True
00129 
00130         myparams = {}
00131         if useLocalDefaults :
00132            for item in function_signature_defaults.iteritems():
00133                key,val = item
00134                keyVal = eval(key)
00135                exec('myparams[key] = keyVal')
00136                self.parameters[key] = keyVal
00137                if (keyVal == None):
00138                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00139                    keyVal = eval(key)
00140                    if(type(keyVal) == dict) :
00141                       if len(keyVal) > 0 :
00142                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00143                       else :
00144                          exec('myparams[key] = ' + key + ' = {}')
00145 
00146         else :
00147             async = self.parameters['async']
00148             myparams['imagename'] = imagename = self.parameters['imagename']
00149             myparams['highres'] = highres = self.parameters['highres']
00150             myparams['lowres'] = lowres = self.parameters['lowres']
00151             myparams['sdfactor'] = sdfactor = self.parameters['sdfactor']
00152             myparams['effdishdiam'] = effdishdiam = self.parameters['effdishdiam']
00153             myparams['showplot'] = showplot = self.parameters['showplot']
00154 
00155 
00156         result = None
00157 
00158 #
00159 #    The following is work around to avoid a bug with current python translation
00160 #
00161         mytmp = {}
00162 
00163         mytmp['imagename'] = imagename
00164         mytmp['highres'] = highres
00165         mytmp['lowres'] = lowres
00166         mytmp['sdfactor'] = sdfactor
00167         mytmp['effdishdiam'] = effdishdiam
00168         mytmp['showplot'] = showplot
00169         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00170         trec = casac.casac.utils().torecord(pathname+'feather.xml')
00171 
00172         casalog.origin('feather')
00173         try :
00174           #if not trec.has_key('feather') or not casac.casac.utils().verify(mytmp, trec['feather']) :
00175             #return False
00176 
00177           casac.casac.utils().verify(mytmp, trec['feather'], True)
00178           scriptstr=['']
00179           saveinputs = self.__globals__['saveinputs']
00180           saveinputs('feather', 'feather.last', myparams, self.__globals__,scriptstr=scriptstr)
00181           if async :
00182             count = 0
00183             keybase =  time.strftime("%y%m%d.%H%M%S")
00184             key = keybase + "_" + str(count)
00185             while self.__async__.has_key(key) :
00186                count += 1
00187                key = keybase + "_" + str(count)
00188             result = tm.execute('feather', imagename, highres, lowres, sdfactor, effdishdiam, showplot)
00189             print "Use: "
00190             print "      tm.retrieve(return_value) # to retrieve the status"
00191             print 
00192             self.rkey = key
00193             self.__async__[key] = result
00194           else :
00195               tname = 'feather'
00196               spaces = ' '*(18-len(tname))
00197               casalog.post('\n##########################################'+
00198                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00199               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00200               result = feather(imagename, highres, lowres, sdfactor, effdishdiam, showplot)
00201               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00202                            '\n##########################################')
00203 
00204         except Exception, instance:
00205           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00206              raise
00207           else :
00208              #print '**** Error **** ',instance
00209              tname = 'feather'
00210              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00211              pass
00212 
00213         gc.collect()
00214         return result
00215 #
00216 #
00217 #
00218     def paramgui(self, useGlobals=True, ipython_globals=None):
00219         """
00220         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00221         """
00222         import paramgui
00223         if not hasattr(self, "__globals__") or self.__globals__ == None :
00224            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00225 
00226         if useGlobals:
00227             if ipython_globals == None:
00228                 myf=self.__globals__
00229             else:
00230                 myf=ipython_globals
00231 
00232             paramgui.setGlobals(myf)
00233         else:
00234             paramgui.setGlobals({})
00235 
00236         paramgui.runTask('feather', myf['_ip'])
00237         paramgui.setGlobals({})
00238 
00239 #
00240 #
00241 #
00242     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00243         if not hasattr(self, "__globals__") or self.__globals__ == None :
00244            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00245         if ipython_globals == None:
00246             myf=self.__globals__
00247         else:
00248             myf=ipython_globals
00249 
00250         a = odict()
00251         a['imagename']  = ''
00252         a['highres']  = ''
00253         a['lowres']  = ''
00254         a['sdfactor']  = 1.0
00255         a['effdishdiam']  = -1.0
00256         a['showplot']  = False
00257 
00258         a['async']=False
00259 
00260 ### This function sets the default values but also will return the list of
00261 ### parameters or the default value of a given parameter
00262         if(param == None):
00263                 myf['__set_default_parameters'](a)
00264         elif(param == 'paramkeys'):
00265                 return a.keys()
00266         else:
00267             if(paramvalue==None and subparam==None):
00268                if(a.has_key(param)):
00269                   return a[param]
00270                else:
00271                   return self.itsdefault(param)
00272             else:
00273                retval=a[param]
00274                if(type(a[param])==dict):
00275                   for k in range(len(a[param])):
00276                      valornotval='value'
00277                      if(a[param][k].has_key('notvalue')):
00278                         valornotval='notvalue'
00279                      if((a[param][k][valornotval])==paramvalue):
00280                         retval=a[param][k].copy()
00281                         retval.pop(valornotval)
00282                         if(subparam != None):
00283                            if(retval.has_key(subparam)):
00284                               retval=retval[subparam]
00285                            else:
00286                               retval=self.itsdefault(subparam)
00287                      else:
00288                         retval=self.itsdefault(subparam)
00289                return retval
00290 
00291 
00292 #
00293 #
00294     def check_params(self, param=None, value=None, ipython_globals=None):
00295       if ipython_globals == None:
00296           myf=self.__globals__
00297       else:
00298           myf=ipython_globals
00299 #      print 'param:', param, 'value:', value
00300       try :
00301          if str(type(value)) != "<type 'instance'>" :
00302             value0 = value
00303             value = myf['cu'].expandparam(param, value)
00304             matchtype = False
00305             if(type(value) == numpy.ndarray):
00306                if(type(value) == type(value0)):
00307                   myf[param] = value.tolist()
00308                else:
00309                   #print 'value:', value, 'value0:', value0
00310                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00311                   myf[param] = value0
00312                   if type(value0) != list :
00313                      matchtype = True
00314             else :
00315                myf[param] = value
00316             value = myf['cu'].verifyparam({param:value})
00317             if matchtype:
00318                value = False
00319       except Exception, instance:
00320          #ignore the exception and just return it unchecked
00321          myf[param] = value
00322       return value
00323 #
00324 #
00325     def description(self, key='feather', subkey=None):
00326         desc={'feather': 'Combine two images using their Fourier transforms',
00327                'imagename': 'Name of output feathered image',
00328                'highres': 'Name of high resolution (interferometer) image',
00329                'lowres': 'Name of low resolution (single dish) image',
00330                'sdfactor': 'Scale factor to apply to Single Dish image',
00331                'effdishdiam': 'New effective SingleDish diameter to use in m ',
00332                'showplot': 'Show plot of feather function',
00333 
00334                'async': 'If true the taskname must be started using feather(...)'
00335               }
00336 
00337         if(desc.has_key(key)) :
00338            return desc[key]
00339 
00340     def itsdefault(self, paramname) :
00341         a = {}
00342         a['imagename']  = ''
00343         a['highres']  = ''
00344         a['lowres']  = ''
00345         a['sdfactor']  = 1.0
00346         a['effdishdiam']  = -1.0
00347         a['showplot']  = False
00348 
00349         #a = sys._getframe(len(inspect.stack())-1).f_globals
00350 
00351         if a.has_key(paramname) :
00352               return a[paramname]
00353 feather_cli = feather_cli_()