casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
deconvolve_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_deconvolve import deconvolve
00018 class deconvolve_cli_:
00019     __name__ = "deconvolve"
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__ = (deconvolve_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'model':None, 'psf':None, 'alg':None, 'niter':None, 'gain':None, 'threshold':None, 'mask':None, 'scales':None, 'sigma':None, 'targetflux':None, 'prior':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, model=None, psf=None, alg=None, niter=None, gain=None, threshold=None, mask=None, scales=None, sigma=None, targetflux=None, prior=None,  async=None):
00047 
00048         """Image based deconvolver
00049 
00050         Several algorithms are available to deconvolve an image with a
00051         known psf (dirty beam), or a Gaussian beam.  The algorithms
00052         available are clark and hogbom clean, a multiscale clean and a
00053         mem clean.  For more deconvolution control, use clean.
00054 
00055         Keyword arguments:
00056         imagename -- Name of input image to be deconvolved
00057         model     -- Name of output image containing the clean components
00058         psf       -- Name of psf image (dirty beam) to use
00059                      example: psf='casaxmlf.image' .
00060                      If the psf has 3 parameter, then a Gaussian
00061                      psf is assumed with the values representing
00062                      the major , minor and position angle  values
00063                      e.g  psf=['3arcsec', '2.5arcsec', '10deg']
00064         alg       -- algorithm to use: default = 'clark'
00065                        options: clark, hogbom, multiscale or mem.
00066         niter     -- Maximum number of iterations
00067         gain      -- CLEAN gain parameter; fraction to remove from peak
00068         threshold -- Halt deconvolution if the maximum residual image is
00069                      below this threshold.
00070                      default = '0.0Jy'
00071         mask      -- mask image (same shape as image and psf) to limit region
00072                      where deconvoltion is to occur
00073 
00074         ------parameters useful for multiscale only
00075         scales     -- in pixel numbers; the size of component to deconvolve.
00076                       default value [0,3,10]
00077                       recommended sizes are 0 (point), 3 (points per clean beam), and
00078                       10 (about a factor of three lower resolution)
00079         ------parameters useful for mem only
00080         sigma      -- Estimated noise for image
00081         targetflux -- Target total flux in image 
00082         prior      -- Prior image to guide mem
00083 
00084 
00085   
00086         """
00087         if not hasattr(self, "__globals__") or self.__globals__ == None :
00088            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00089         #casac = self.__globals__['casac']
00090         casalog = self.__globals__['casalog']
00091         #casalog = casac.casac.logsink()
00092         self.__globals__['__last_task'] = 'deconvolve'
00093         self.__globals__['taskname'] = 'deconvolve'
00094         ###
00095         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00096         ###
00097         ###
00098         #Handle globals or user over-ride of arguments
00099         #
00100         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00101         useLocalDefaults = False
00102 
00103         for item in function_signature_defaults.iteritems():
00104                 key,val = item
00105                 keyVal = eval(key)
00106                 if (keyVal == None):
00107                         #user hasn't set it - use global/default
00108                         pass
00109                 else:
00110                         #user has set it - use over-ride
00111                         if (key != 'self') :
00112                            useLocalDefaults = True
00113 
00114         myparams = {}
00115         if useLocalDefaults :
00116            for item in function_signature_defaults.iteritems():
00117                key,val = item
00118                keyVal = eval(key)
00119                exec('myparams[key] = keyVal')
00120                self.parameters[key] = keyVal
00121                if (keyVal == None):
00122                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00123                    keyVal = eval(key)
00124                    if(type(keyVal) == dict) :
00125                       if len(keyVal) > 0 :
00126                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00127                       else :
00128                          exec('myparams[key] = ' + key + ' = {}')
00129 
00130         else :
00131             async = self.parameters['async']
00132             myparams['imagename'] = imagename = self.parameters['imagename']
00133             myparams['model'] = model = self.parameters['model']
00134             myparams['psf'] = psf = self.parameters['psf']
00135             myparams['alg'] = alg = self.parameters['alg']
00136             myparams['niter'] = niter = self.parameters['niter']
00137             myparams['gain'] = gain = self.parameters['gain']
00138             myparams['threshold'] = threshold = self.parameters['threshold']
00139             myparams['mask'] = mask = self.parameters['mask']
00140             myparams['scales'] = scales = self.parameters['scales']
00141             myparams['sigma'] = sigma = self.parameters['sigma']
00142             myparams['targetflux'] = targetflux = self.parameters['targetflux']
00143             myparams['prior'] = prior = self.parameters['prior']
00144 
00145         if type(psf)==str: psf=[psf]
00146         if type(scales)==int: scales=[scales]
00147 
00148         result = None
00149 
00150 #
00151 #    The following is work around to avoid a bug with current python translation
00152 #
00153         mytmp = {}
00154 
00155         mytmp['imagename'] = imagename
00156         mytmp['model'] = model
00157         mytmp['psf'] = psf
00158         mytmp['alg'] = alg
00159         mytmp['niter'] = niter
00160         mytmp['gain'] = gain
00161         if type(threshold) == str :
00162            mytmp['threshold'] = casac.casac.qa.quantity(threshold)
00163         else :
00164            mytmp['threshold'] = threshold
00165         mytmp['mask'] = mask
00166         mytmp['scales'] = scales
00167         if type(sigma) == str :
00168            mytmp['sigma'] = casac.casac.qa.quantity(sigma)
00169         else :
00170            mytmp['sigma'] = sigma
00171         if type(targetflux) == str :
00172            mytmp['targetflux'] = casac.casac.qa.quantity(targetflux)
00173         else :
00174            mytmp['targetflux'] = targetflux
00175         mytmp['prior'] = prior
00176         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00177         trec = casac.casac.utils().torecord(pathname+'deconvolve.xml')
00178 
00179         casalog.origin('deconvolve')
00180         try :
00181           #if not trec.has_key('deconvolve') or not casac.casac.utils().verify(mytmp, trec['deconvolve']) :
00182             #return False
00183 
00184           casac.casac.utils().verify(mytmp, trec['deconvolve'], True)
00185           scriptstr=['']
00186           saveinputs = self.__globals__['saveinputs']
00187           saveinputs('deconvolve', 'deconvolve.last', myparams, self.__globals__,scriptstr=scriptstr)
00188           if async :
00189             count = 0
00190             keybase =  time.strftime("%y%m%d.%H%M%S")
00191             key = keybase + "_" + str(count)
00192             while self.__async__.has_key(key) :
00193                count += 1
00194                key = keybase + "_" + str(count)
00195             result = tm.execute('deconvolve', imagename, model, psf, alg, niter, gain, threshold, mask, scales, sigma, targetflux, prior)
00196             print "Use: "
00197             print "      tm.retrieve(return_value) # to retrieve the status"
00198             print 
00199             self.rkey = key
00200             self.__async__[key] = result
00201           else :
00202               tname = 'deconvolve'
00203               spaces = ' '*(18-len(tname))
00204               casalog.post('\n##########################################'+
00205                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00206               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00207               result = deconvolve(imagename, model, psf, alg, niter, gain, threshold, mask, scales, sigma, targetflux, prior)
00208               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00209                            '\n##########################################')
00210 
00211         except Exception, instance:
00212           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00213              raise
00214           else :
00215              #print '**** Error **** ',instance
00216              tname = 'deconvolve'
00217              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00218              pass
00219 
00220         gc.collect()
00221         return result
00222 #
00223 #
00224 #
00225     def paramgui(self, useGlobals=True, ipython_globals=None):
00226         """
00227         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00228         """
00229         import paramgui
00230         if not hasattr(self, "__globals__") or self.__globals__ == None :
00231            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00232 
00233         if useGlobals:
00234             if ipython_globals == None:
00235                 myf=self.__globals__
00236             else:
00237                 myf=ipython_globals
00238 
00239             paramgui.setGlobals(myf)
00240         else:
00241             paramgui.setGlobals({})
00242 
00243         paramgui.runTask('deconvolve', myf['_ip'])
00244         paramgui.setGlobals({})
00245 
00246 #
00247 #
00248 #
00249     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00250         if not hasattr(self, "__globals__") or self.__globals__ == None :
00251            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00252         if ipython_globals == None:
00253             myf=self.__globals__
00254         else:
00255             myf=ipython_globals
00256 
00257         a = odict()
00258         a['imagename']  = ''
00259         a['model']  = ''
00260         a['psf']  = ['']
00261         a['alg']  = 'clark'
00262         a['niter']  = 10
00263         a['gain']  = 0.1
00264         a['threshold']  = '0.0mJy'
00265         a['mask']  = ''
00266 
00267         a['async']=False
00268         a['alg'] = {
00269                     0:{'value':'clark'}, 
00270                     1:{'value':'hogbom'}, 
00271                     2:odict([{'value':'multiscale'}, {'scales':[0, 3, 10]}]), 
00272                     3:odict([{'value':'mem'}, {'sigma':1.0}, {'targetflux':1.0}, {'prior':''}])}
00273 
00274 ### This function sets the default values but also will return the list of
00275 ### parameters or the default value of a given parameter
00276         if(param == None):
00277                 myf['__set_default_parameters'](a)
00278         elif(param == 'paramkeys'):
00279                 return a.keys()
00280         else:
00281             if(paramvalue==None and subparam==None):
00282                if(a.has_key(param)):
00283                   return a[param]
00284                else:
00285                   return self.itsdefault(param)
00286             else:
00287                retval=a[param]
00288                if(type(a[param])==dict):
00289                   for k in range(len(a[param])):
00290                      valornotval='value'
00291                      if(a[param][k].has_key('notvalue')):
00292                         valornotval='notvalue'
00293                      if((a[param][k][valornotval])==paramvalue):
00294                         retval=a[param][k].copy()
00295                         retval.pop(valornotval)
00296                         if(subparam != None):
00297                            if(retval.has_key(subparam)):
00298                               retval=retval[subparam]
00299                            else:
00300                               retval=self.itsdefault(subparam)
00301                      else:
00302                         retval=self.itsdefault(subparam)
00303                return retval
00304 
00305 
00306 #
00307 #
00308     def check_params(self, param=None, value=None, ipython_globals=None):
00309       if ipython_globals == None:
00310           myf=self.__globals__
00311       else:
00312           myf=ipython_globals
00313 #      print 'param:', param, 'value:', value
00314       try :
00315          if str(type(value)) != "<type 'instance'>" :
00316             value0 = value
00317             value = myf['cu'].expandparam(param, value)
00318             matchtype = False
00319             if(type(value) == numpy.ndarray):
00320                if(type(value) == type(value0)):
00321                   myf[param] = value.tolist()
00322                else:
00323                   #print 'value:', value, 'value0:', value0
00324                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00325                   myf[param] = value0
00326                   if type(value0) != list :
00327                      matchtype = True
00328             else :
00329                myf[param] = value
00330             value = myf['cu'].verifyparam({param:value})
00331             if matchtype:
00332                value = False
00333       except Exception, instance:
00334          #ignore the exception and just return it unchecked
00335          myf[param] = value
00336       return value
00337 #
00338 #
00339     def description(self, key='deconvolve', subkey=None):
00340         desc={'deconvolve': 'Image based deconvolver',
00341                'imagename': 'Input image to deconvolve',
00342                'model': 'Output image containing deconvolved point model',
00343                'psf': 'Point spread function (dirty beam)',
00344                'alg': 'Algorithm to use (clark, hogbom, multiscale, mem) ',
00345                'niter': 'number of iteration in deconvolution process',
00346                'gain': 'CLEAN gain parameter',
00347                'threshold': 'level below which sources will not be deconvolved',
00348                'mask': 'image mask to limit region of deconvolution',
00349                'scales': 'scale sizes (pixels) to deconvolve',
00350                'sigma': 'mem parameter: Expected noise in image',
00351                'targetflux': 'mem parameter: Estimated total flux in image',
00352                'prior': 'mem parameter: prior image for mem search',
00353 
00354                'async': 'If true the taskname must be started using deconvolve(...)'
00355               }
00356 
00357 #
00358 # Set subfields defaults if needed
00359 #
00360 
00361         if(desc.has_key(key)) :
00362            return desc[key]
00363 
00364     def itsdefault(self, paramname) :
00365         a = {}
00366         a['imagename']  = ''
00367         a['model']  = ''
00368         a['psf']  = ['']
00369         a['alg']  = 'clark'
00370         a['niter']  = 10
00371         a['gain']  = 0.1
00372         a['threshold']  = '0.0mJy'
00373         a['mask']  = ''
00374         a['scales']  = [0, 3, 10]
00375         a['sigma']  = '0.0mJy'
00376         a['targetflux']  = '1.0Jy'
00377         a['prior']  = ''
00378 
00379         #a = sys._getframe(len(inspect.stack())-1).f_globals
00380 
00381         if self.parameters['alg']  == 'multiscale':
00382             a['scales'] = [0, 3, 10]
00383 
00384         if self.parameters['alg']  == 'mem':
00385             a['sigma'] = 1.0
00386             a['targetflux'] = 1.0
00387             a['prior'] = ''
00388 
00389         if a.has_key(paramname) :
00390               return a[paramname]
00391 deconvolve_cli = deconvolve_cli_()