casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
impbcor_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_impbcor import impbcor
00016 from task_impbcor import casalog
00017 
00018 class impbcor_pg_:
00019     __name__ = "impbcor"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (impbcor_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, imagename=None, pbimage=None, outfile=None, overwrite=None, box=None, region=None, chans=None, stokes=None, mask=None, mode=None, cutoff=None, wantreturn=None, stretch=None, async=None):
00027 
00028         """Construct a primary beam corrected image from an image and a primary beam pattern.
00029 PARAMETER SUMMARY
00030 imagename        Name of the input (CASA, FITS, MIRIAD) image
00031 pbimage          Name of the image (CASA, FITS, MIRIAD) of the primary beam pattern or an array of pixel values.
00032 outfile          Name of output CASA image. If not specified, no image is written
00033                  but an image analysis tool which references the output image is returned.
00034 overwrite        If output file is specified, controls if an already existing file by the
00035                  same name can be overwritten. If true, the user is not prompted, the file
00036                  if it exists is automatically overwritten.
00037 box              Direction plane box specification, "blcx, blcy, trcx, trcy". Only one box
00038                  may be specified. If not specified, region is used if specified. If region
00039                  is also not specified, entire directional plane unioned with any chans and
00040                  stokes specification determines the region.
00041 region           Optional region file to use.
00042 chans            Optional contiguous frequency channel number specification. Not used if
00043                  region is specified. Default is all channels.
00044 stokes           Contiguous stokes planes specification. Not used if region is specified.
00045                  Default is all stokes.
00046 mask             Mask to use. See help par.mask. Default is none.
00047 stretch          Stretch the input mask if necessary and possible. See help par.mask.
00048 mode             Divide or multiply the image by the primary beam image. Minimal match supported. Default "divide"
00049 cutoff           PB cutoff. If mode is "d", all values less than this will be masked. If "m", all values greater will be masked. Less than 0, no cutoff. Default no cutoff
00050 wantreturn       If true, return an image analysis tool referencing the collapsed image, if
00051                  false, return false.
00052         
00053 
00054 DESCRIPTION
00055 Correct an image for primary beam attenuation using an image of the primary beam pattern.
00056 The primary beam pattern can be provided as an image, in which case 1. it must have the same
00057 shape as the input image and its coordinate system must be the same, or 2. it must
00058 be a 2-D image in which case its coordinate system must consist of a (2-D) direction
00059 coordinate which is the same as the direction coordinate in the input image and
00060 its direction plane must be the same shape as that of the input image. Alternatively,
00061 pbimage can be an array of pixel values in which case the same dimensionality and
00062 shape constraints apply.
00063 An image tool referencing the corrected image is returned if wantreturn=True. The corrected image will also
00064 be written to disk if outfile is not empty (and overwrite=True if outfile already exists).
00065 One can choose between dividing the image by the primary beam pattern (mode="divide") or
00066 multiplying the image by the primary beam pattern (mode="multiply"). One can also choose
00067 to specify a cutoff limit for the primary beam pattern. For mode="divide", for all pixels
00068 below this cutoff in the primary beam pattern, the output image will be masked. In the
00069 case of mode="multiply", all pixels in the output will be masked corresponding to pixels
00070 with values greater than the cutoff in the primary beam pattern. A negative value for
00071 cutoff means that no cutoff will be applied, which is the default.
00072 
00073 EXAMPLE 
00074 impbcor(imagename="attunuated.im", pbimage="mypb.im", outname="pbcorred.im", mode="divide", cutoff=0.1)
00075     
00076         """
00077         a=inspect.stack()
00078         stacklevel=0
00079         for k in range(len(a)):
00080           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00081                 stacklevel=k
00082                 break
00083         myf=sys._getframe(stacklevel).f_globals
00084         myf['__last_task'] = 'impbcor'
00085         myf['taskname'] = 'impbcor'
00086         ###
00087         myf['update_params'](func=myf['taskname'],printtext=False)
00088         ###
00089         ###
00090         #Handle globals or user over-ride of arguments
00091         #
00092         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00093         useLocalDefaults = False
00094 
00095         for item in function_signature_defaults.iteritems():
00096                 key,val = item
00097                 keyVal = eval(key)
00098                 if (keyVal == None):
00099                         #user hasn't set it - use global/default
00100                         pass
00101                 else:
00102                         #user has set it - use over-ride
00103                         if (key != 'self') :
00104                            useLocalDefaults = True
00105                         #myf[key]=keyVal
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                if (keyVal == None):
00114                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00115                    keyVal = eval(key)
00116                    if(type(keyVal) == dict) :
00117                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00118 
00119         else :
00120             uselessvariable = None 
00121             myparams['imagename'] = imagename = myf['imagename']
00122             myparams['pbimage'] = pbimage = myf['pbimage']
00123             myparams['outfile'] = outfile = myf['outfile']
00124             myparams['overwrite'] = overwrite = myf['overwrite']
00125             myparams['box'] = box = myf['box']
00126             myparams['region'] = region = myf['region']
00127             myparams['chans'] = chans = myf['chans']
00128             myparams['stokes'] = stokes = myf['stokes']
00129             myparams['mask'] = mask = myf['mask']
00130             myparams['mode'] = mode = myf['mode']
00131             myparams['cutoff'] = cutoff = myf['cutoff']
00132             myparams['wantreturn'] = wantreturn = myf['wantreturn']
00133             myparams['stretch'] = stretch = myf['stretch']
00134 
00135 
00136         result = None
00137 
00138 #
00139 #    The following is work around to avoid a bug with current python translation
00140 #
00141         mytmp = {}
00142 
00143         mytmp['imagename'] = imagename
00144         mytmp['pbimage'] = pbimage
00145         mytmp['outfile'] = outfile
00146         mytmp['overwrite'] = overwrite
00147         mytmp['box'] = box
00148         mytmp['region'] = region
00149         mytmp['chans'] = chans
00150         mytmp['stokes'] = stokes
00151         mytmp['mask'] = mask
00152         mytmp['mode'] = mode
00153         mytmp['cutoff'] = cutoff
00154         mytmp['wantreturn'] = wantreturn
00155         mytmp['stretch'] = stretch
00156         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00157         trec = casac.utils().torecord(pathname+'impbcor.xml')
00158 
00159         casalog.origin('impbcor')
00160         if not trec.has_key('impbcor') or not casac.utils().verify(mytmp, trec['impbcor']) :
00161             return False
00162 
00163 
00164         try :
00165           casalog.post('')
00166           casalog.post('##########################################')
00167           casalog.post('##### Begin Task: impbcor           #####')
00168           casalog.post('')
00169           result = impbcor(imagename, pbimage, outfile, overwrite, box, region, chans, stokes, mask, mode, cutoff, wantreturn, stretch)
00170           casalog.post('')
00171           casalog.post('##### End Task: impbcor           #####')
00172           casalog.post('##########################################')
00173 
00174 
00175 # saveinputs for individule engine has no use
00176 # saveinputs should alos be removed from casa_in_py.py
00177 #
00178 #
00179 #          saveinputs = myf['saveinputs']
00180 #          saveinputs('impbcor', 'impbcor.last', myparams)
00181 #
00182 #
00183         except Exception, instance:
00184           #print '**** Error **** ',instance
00185           pass
00186 
00187         gc.collect()
00188         return result
00189 #
00190 #
00191 ##
00192 #    def paramgui(self, useGlobals=True):
00193 #        """
00194 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00195 #        """
00196 #        import paramgui
00197 #
00198 #        a=inspect.stack()
00199 #        stacklevel=0
00200 #        for k in range(len(a)):
00201 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00202 #            stacklevel=k
00203 #            break
00204 #        myf = sys._getframe(stacklevel).f_globals
00205 #
00206 #        if useGlobals:
00207 #            paramgui.setGlobals(myf)
00208 #        else:
00209 #            paramgui.setGlobals({})
00210 #
00211 #        paramgui.runTask('impbcor', myf['_ip'])
00212 #        paramgui.setGlobals({})
00213 #
00214 #
00215 #
00216 #
00217     def defaults(self, param=None):
00218         a=inspect.stack()
00219         stacklevel=0
00220         for k in range(len(a)):
00221           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00222                 stacklevel=k
00223                 break
00224         myf=sys._getframe(stacklevel).f_globals
00225         a = odict()
00226         a['imagename']  = ''
00227         a['pbimage']  = ""
00228         a['outfile']  = ''
00229         a['box']  = ''
00230         a['chans']  = ''
00231         a['stokes']  = ''
00232         a['mask']  = ''
00233         a['mode']  = 'divide'
00234         a['cutoff']  = -1.0
00235         a['wantreturn']  = False
00236 
00237         a['async']=False
00238         a['outfile'] = {
00239                     0:odict([{'notvalue':''}, {'overwrite':False}])}
00240         a['box'] = {
00241                     0:odict([{'value':''}, {'region':""}])}
00242         a['mask'] = {
00243                     0:odict([{'notvalue':''}, {'stretch':False}])}
00244 
00245 ### This function sets the default values but also will return the list of
00246 ### parameters or the default value of a given parameter
00247         if(param == None):
00248                 myf['__set_default_parameters'](a)
00249         elif(param == 'paramkeys'):
00250                 return a.keys()
00251         else:
00252                 if(a.has_key(param)):
00253                    #if(type(a[param]) == dict) :
00254                    #   return a[param][len(a[param])-1]['value']
00255                    #else :
00256                       return a[param]
00257 
00258 
00259 #
00260 #
00261     def check_params(self, param=None, value=None):
00262       a=inspect.stack() 
00263       stacklevel=0
00264       for k in range(len(a)):
00265         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00266             stacklevel=k
00267             break
00268       myf=sys._getframe(stacklevel).f_globals
00269 
00270 #      print 'param:', param, 'value:', value
00271       try :
00272          if str(type(value)) != "<type 'instance'>" :
00273             value0 = value
00274             value = myf['cu'].expandparam(param, value)
00275             matchtype = False
00276             if(type(value) == numpy.ndarray):
00277                if(type(value) == type(value0)):
00278                   myf[param] = value.tolist()
00279                else:
00280                   #print 'value:', value, 'value0:', value0
00281                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00282                   myf[param] = value0
00283                   if type(value0) != list :
00284                      matchtype = True
00285             else :
00286                myf[param] = value
00287             value = myf['cu'].verifyparam({param:value})
00288             if matchtype:
00289                value = False
00290       except Exception, instance:
00291          #ignore the exception and just return it unchecked
00292          myf[param] = value
00293       return value
00294 
00295 #
00296 #
00297     def description(self, key='impbcor', subkey=None):
00298         desc={'impbcor': 'Construct a primary beam corrected image from an image and a primary beam pattern.',
00299                'imagename': 'Name of the input image',
00300                'pbimage': 'Name of the primary beam image which must exist or array of values for the pb response. Default ""',
00301                'outfile': 'Output image name. If empty, no image is written. Default ""',
00302                'overwrite': 'Overwrite the output if it exists? Default False',
00303                'box': 'One or more boxes to use for fit region(s). Default is to use the entire directional plane.',
00304                'region': 'The region to correct. Default is entire image. If both box and region are specified, box is used and region is not.',
00305                'chans': 'The frequency planes to correct. Default is all frequencies.',
00306                'stokes': 'The correlations to correct. Default is all.',
00307                'mask': 'Mask to use. See help par.mask. Default is none.',
00308                'mode': 'Divide or multiply the image by the primary beam image. Minimal match supported. Default "divide"',
00309                'cutoff': 'PB cutoff. If mode is "d", all values less than this will be masked. If "m", all values greater will be masked. Less than 0, no cutoff. Default no cutoff',
00310                'wantreturn': 'Return an image tool referencing the corrected image?',
00311                'stretch': 'Stretch the mask if necessary and possible? See help par.stretch ',
00312 
00313                'async': 'If true the taskname must be started using impbcor(...)'
00314               }
00315 
00316 #
00317 # Set subfields defaults if needed
00318 #
00319 
00320         if(desc.has_key(key)) :
00321            return desc[key]
00322 
00323     def itsdefault(self, paramname) :
00324         a = {}
00325         a['imagename']  = ''
00326         a['pbimage']  = ""
00327         a['outfile']  = ''
00328         a['overwrite']  = False
00329         a['box']  = ''
00330         a['region']  = ""
00331         a['chans']  = ''
00332         a['stokes']  = ''
00333         a['mask']  = ''
00334         a['mode']  = 'divide'
00335         a['cutoff']  = -1.0
00336         a['wantreturn']  = False
00337         a['stretch']  = False
00338 
00339         if a.has_key(paramname) :
00340               return a[paramname]
00341 impbcor_pg = impbcor_pg_()