casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
deconvolve_pg.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 string
00010 import time
00011 import inspect
00012 import gc
00013 import numpy
00014 from odict import odict
00015 from task_deconvolve import deconvolve
00016 from task_deconvolve import casalog
00017 
00018 class deconvolve_pg_:
00019     __name__ = "deconvolve"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (deconvolve_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     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):
00027 
00028         """Image based deconvolver
00029 
00030         Several algorithms are available to deconvolve an image with a
00031         known psf (dirty beam), or a Gaussian beam.  The algorithms
00032         available are clark and hogbom clean, a multiscale clean and a
00033         mem clean.  For more deconvolution control, use clean.
00034 
00035         Keyword arguments:
00036         imagename -- Name of input image to be deconvolved
00037         model     -- Name of output image containing the clean components
00038         psf       -- Name of psf image (dirty beam) to use
00039                      example: psf='casaxmlf.image' .
00040                      If the psf has 3 parameter, then a Gaussian
00041                      psf is assumed with the values representing
00042                      the major , minor and position angle  values
00043                      e.g  psf=['3arcsec', '2.5arcsec', '10deg']
00044         alg       -- algorithm to use: default = 'clark'
00045                        options: clark, hogbom, multiscale or mem.
00046         niter     -- Maximum number of iterations
00047         gain      -- CLEAN gain parameter; fraction to remove from peak
00048         threshold -- Halt deconvolution if the maximum residual image is
00049                      below this threshold.
00050                      default = '0.0Jy'
00051         mask      -- mask image (same shape as image and psf) to limit region
00052                      where deconvoltion is to occur
00053 
00054         ------parameters useful for multiscale only
00055         scales     -- in pixel numbers; the size of component to deconvolve.
00056                       default value [0,3,10]
00057                       recommended sizes are 0 (point), 3 (points per clean beam), and
00058                       10 (about a factor of three lower resolution)
00059         ------parameters useful for mem only
00060         sigma      -- Estimated noise for image
00061         targetflux -- Target total flux in image 
00062         prior      -- Prior image to guide mem
00063 
00064 
00065   
00066         """
00067         a=inspect.stack()
00068         stacklevel=0
00069         for k in range(len(a)):
00070           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00071                 stacklevel=k
00072                 break
00073         myf=sys._getframe(stacklevel).f_globals
00074         myf['__last_task'] = 'deconvolve'
00075         myf['taskname'] = 'deconvolve'
00076         ###
00077         myf['update_params'](func=myf['taskname'],printtext=False)
00078         ###
00079         ###
00080         #Handle globals or user over-ride of arguments
00081         #
00082         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00083         useLocalDefaults = False
00084 
00085         for item in function_signature_defaults.iteritems():
00086                 key,val = item
00087                 keyVal = eval(key)
00088                 if (keyVal == None):
00089                         #user hasn't set it - use global/default
00090                         pass
00091                 else:
00092                         #user has set it - use over-ride
00093                         if (key != 'self') :
00094                            useLocalDefaults = True
00095                         #myf[key]=keyVal
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                if (keyVal == None):
00104                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00105                    keyVal = eval(key)
00106                    if(type(keyVal) == dict) :
00107                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00108 
00109         else :
00110             uselessvariable = None 
00111             myparams['imagename'] = imagename = myf['imagename']
00112             myparams['model'] = model = myf['model']
00113             myparams['psf'] = psf = myf['psf']
00114             myparams['alg'] = alg = myf['alg']
00115             myparams['niter'] = niter = myf['niter']
00116             myparams['gain'] = gain = myf['gain']
00117             myparams['threshold'] = threshold = myf['threshold']
00118             myparams['mask'] = mask = myf['mask']
00119             myparams['scales'] = scales = myf['scales']
00120             myparams['sigma'] = sigma = myf['sigma']
00121             myparams['targetflux'] = targetflux = myf['targetflux']
00122             myparams['prior'] = prior = myf['prior']
00123 
00124         if type(psf)==str: psf=[psf]
00125         if type(scales)==int: scales=[scales]
00126 
00127         result = None
00128 
00129 #
00130 #    The following is work around to avoid a bug with current python translation
00131 #
00132         mytmp = {}
00133 
00134         mytmp['imagename'] = imagename
00135         mytmp['model'] = model
00136         mytmp['psf'] = psf
00137         mytmp['alg'] = alg
00138         mytmp['niter'] = niter
00139         mytmp['gain'] = gain
00140         if type(threshold) == str :
00141            mytmp['threshold'] = casac.quanta().quantity(threshold)
00142         else :
00143            mytmp['threshold'] = threshold
00144         mytmp['mask'] = mask
00145         mytmp['scales'] = scales
00146         if type(sigma) == str :
00147            mytmp['sigma'] = casac.quanta().quantity(sigma)
00148         else :
00149            mytmp['sigma'] = sigma
00150         if type(targetflux) == str :
00151            mytmp['targetflux'] = casac.quanta().quantity(targetflux)
00152         else :
00153            mytmp['targetflux'] = targetflux
00154         mytmp['prior'] = prior
00155         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00156         trec = casac.utils().torecord(pathname+'deconvolve.xml')
00157 
00158         casalog.origin('deconvolve')
00159         if not trec.has_key('deconvolve') or not casac.utils().verify(mytmp, trec['deconvolve']) :
00160             return False
00161 
00162 
00163         try :
00164           casalog.post('')
00165           casalog.post('##########################################')
00166           casalog.post('##### Begin Task: deconvolve           #####')
00167           casalog.post('')
00168           result = deconvolve(imagename, model, psf, alg, niter, gain, threshold, mask, scales, sigma, targetflux, prior)
00169           casalog.post('')
00170           casalog.post('##### End Task: deconvolve           #####')
00171           casalog.post('##########################################')
00172 
00173 
00174 # saveinputs for individule engine has no use
00175 # saveinputs should alos be removed from casa_in_py.py
00176 #
00177 #
00178 #          saveinputs = myf['saveinputs']
00179 #          saveinputs('deconvolve', 'deconvolve.last', myparams)
00180 #
00181 #
00182         except Exception, instance:
00183           #print '**** Error **** ',instance
00184           pass
00185 
00186         gc.collect()
00187         return result
00188 #
00189 #
00190 ##
00191 #    def paramgui(self, useGlobals=True):
00192 #        """
00193 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00194 #        """
00195 #        import paramgui
00196 #
00197 #        a=inspect.stack()
00198 #        stacklevel=0
00199 #        for k in range(len(a)):
00200 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00201 #            stacklevel=k
00202 #            break
00203 #        myf = sys._getframe(stacklevel).f_globals
00204 #
00205 #        if useGlobals:
00206 #            paramgui.setGlobals(myf)
00207 #        else:
00208 #            paramgui.setGlobals({})
00209 #
00210 #        paramgui.runTask('deconvolve', myf['_ip'])
00211 #        paramgui.setGlobals({})
00212 #
00213 #
00214 #
00215 #
00216     def defaults(self, param=None):
00217         a=inspect.stack()
00218         stacklevel=0
00219         for k in range(len(a)):
00220           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00221                 stacklevel=k
00222                 break
00223         myf=sys._getframe(stacklevel).f_globals
00224         a = odict()
00225         a['imagename']  = ''
00226         a['model']  = ''
00227         a['psf']  = ['']
00228         a['alg']  = 'clark'
00229         a['niter']  = 10
00230         a['gain']  = 0.1
00231         a['threshold']  = '0.0mJy'
00232         a['mask']  = ''
00233 
00234         a['async']=False
00235         a['alg'] = {
00236                     0:{'value':'clark'}, 
00237                     1:{'value':'hogbom'}, 
00238                     2:odict([{'value':'multiscale'}, {'scales':[0, 3, 10]}]), 
00239                     3:odict([{'value':'mem'}, {'sigma':1.0}, {'targetflux':1.0}, {'prior':''}])}
00240 
00241 ### This function sets the default values but also will return the list of
00242 ### parameters or the default value of a given parameter
00243         if(param == None):
00244                 myf['__set_default_parameters'](a)
00245         elif(param == 'paramkeys'):
00246                 return a.keys()
00247         else:
00248                 if(a.has_key(param)):
00249                    #if(type(a[param]) == dict) :
00250                    #   return a[param][len(a[param])-1]['value']
00251                    #else :
00252                       return a[param]
00253 
00254 
00255 #
00256 #
00257     def check_params(self, param=None, value=None):
00258       a=inspect.stack() 
00259       stacklevel=0
00260       for k in range(len(a)):
00261         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00262             stacklevel=k
00263             break
00264       myf=sys._getframe(stacklevel).f_globals
00265 
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 #
00293     def description(self, key='deconvolve', subkey=None):
00294         desc={'deconvolve': 'Image based deconvolver',
00295                'imagename': 'Input image to deconvolve',
00296                'model': 'Output image containing deconvolved point model',
00297                'psf': 'Point spread function (dirty beam)',
00298                'alg': 'Algorithm to use (clark, hogbom, multiscale, mem) ',
00299                'niter': 'number of iteration in deconvolution process',
00300                'gain': 'CLEAN gain parameter',
00301                'threshold': 'level below which sources will not be deconvolved',
00302                'mask': 'image mask to limit region of deconvolution',
00303                'scales': 'scale sizes (pixels) to deconvolve',
00304                'sigma': 'mem parameter: Expected noise in image',
00305                'targetflux': 'mem parameter: Estimated total flux in image',
00306                'prior': 'mem parameter: prior image for mem search',
00307 
00308                'async': 'If true the taskname must be started using deconvolve(...)'
00309               }
00310 
00311 #
00312 # Set subfields defaults if needed
00313 #
00314 
00315         if(desc.has_key(key)) :
00316            return desc[key]
00317 
00318     def itsdefault(self, paramname) :
00319         a = {}
00320         a['imagename']  = ''
00321         a['model']  = ''
00322         a['psf']  = ['']
00323         a['alg']  = 'clark'
00324         a['niter']  = 10
00325         a['gain']  = 0.1
00326         a['threshold']  = '0.0mJy'
00327         a['mask']  = ''
00328         a['scales']  = [0, 3, 10]
00329         a['sigma']  = '0.0mJy'
00330         a['targetflux']  = '1.0Jy'
00331         a['prior']  = ''
00332 
00333         if a.has_key(paramname) :
00334               return a[paramname]
00335 deconvolve_pg = deconvolve_pg_()