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