casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
widebandpbcor_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_widebandpbcor import widebandpbcor
00016 from task_widebandpbcor import casalog
00017 
00018 class widebandpbcor_pg_:
00019     __name__ = "widebandpbcor"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (widebandpbcor_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, imagename=None, nterms=None, threshold=None, action=None, reffreq=None, pbmin=None, field=None, spwlist=None, chanlist=None, weightlist=None, async=None):
00027 
00028         """Wideband PB-correction on the output of the MS-MFS algorithm
00029 
00030    Wide-band Primary-beam correction
00031 
00032     (1) Compute a set of Primary Beams at the specified frequencies
00033     (2) Calculate Taylor-coefficient images that represent the PB spectrum
00034     (3) Perform a polynomial division to PB-correct the output Taylor-coefficient
00035           images from the MS-MFS algorithm ( clean(nterms>1) )
00036     (4) Recompute spectral index (and curvature) using the corrected Taylor-coefficient images.
00037 
00038    [ Optionally, skip PB-correction, and only recalculate spectral index
00039       with a different threshold ]
00040 
00041    This is a temporary task, meant for use until projection-based gridding algorithms
00042    are available via the 'clean' task.
00043 
00044    An output directory named imagename.pbcor.workdirectory is created, and filled with
00045    an image-cube of the evaluated primary beams at all specified frequencies,
00046    Taylor-coefficients, and a 'spectral index' due to the primary beam.  
00047    Note that for the actual pb-correction, only the Taylor-coefficient images are used.
00048  
00049    Task parameters :
00050 
00051    vis -- Name of input visibility file
00052            example : vis = 'ngc5921.ms'
00053               Only one MS can be specified here, and it must contain at-least one
00054                timestep of data at all frequencies required to calculate the PB spectrum. 
00055               ( In case of multiple MSs with different spectral windows, for now, 
00056                 please split/concat a small fraction of the data to form such an MS )
00057 
00058    imagename -- Pre-name of input and output images. Same as in the clean task.           
00059            example : imagename = 'run1'
00060               Restored-images ( run1.image.tt0,etc) and residual images ( run1.residual.tt0, etc.. )
00061               must be available on disk. 
00062 
00063    nterms -- Number of Taylor terms to be used to model the frequency-dependence 
00064                  of the primary beam.
00065            example : nterms = 2
00066                 nterms must be less than or equal to the number of frequencies specified via
00067                 spwlist, chanlist and weightlist.
00068                 nterms=1 will do a standard division by the average PB computed over all
00069                 specified frequencies.
00070 
00071    threshold -- Flux level in the restored intensity map, below which to not 
00072                      recalculate spectral index. 
00073            example : threshold = '0.1Jy'
00074 
00075    action -- Choice of PB-correction with spectral-index recalculation
00076                 or only spectral-index recalculation (using the specified threshold)
00077            example : action='pbcor'  or action='calcalpha'
00078                
00079            With action='pbcor', the following output images are created/overwritten.
00080 
00081               - imagename.pbcor.workdirectory  :  This directory contains an image cube with
00082                 PBs at the list of specified frequencies, and Taylor-coefficient images that
00083                 describe the PB spectrum.
00084                    -  imagename.pb.cube : Concatenated cube of PBs 
00085                    -  imagename.pb.tt0, tt1, ... : Taylor coefficients describing the PB spectrum
00086                    -  imagename.pb.alpha : Spectral index of the PB (for information only)
00087               - imagename.image.pbcor.tt0,tt1,... : Corrected Taylor coefficients
00088               - imagename.pbcor.image.alpha : Corrected Spectral Index
00089               - imagename.pbcor.image.alpha.error : New error map.
00090 
00091             With action='calcalpha', the following output images are created/overwritten
00092               - imagename.image.alpha : Corrected Spectral Index
00093               - imagename.image.alpha.error : New error map.
00094 
00095    reffreq -- Reference frequency about which the Taylor-expansion is defined.
00096             example : reffreq = '1.5GHz'
00097                  If left unspecified, it is picked from the input restored image.
00098                  Note : If reffreq was specified during task clean to produce the images
00099                            it must be specified here. 
00100 
00101    pbmin -- PB gain level below which to not compute Taylor-coefficients or
00102                 apply PB-corrections.
00103             example : pbmin = 0.1
00104 
00105    field -- Field selection for the Primary Beam calculation. 
00106             example : field = '3C291'
00107                 This field selection must be identical to that used in 'clean'
00108 
00109    spwlist -- List of SPW ids for which to make separate Primary Beams
00110    chanlist -- List of channel ids, within the above SPW ids, at which to make PBs.
00111 
00112              example :  spwlist=[0,1,2], chanlist=[32,32,32] 
00113                           Make PBs at frequencies corresponding to channel 32 of
00114                           spws 0,1 and 2.
00115              example :  spwlist=[0,0,0], chanlist=[0,10,20]
00116                            Make PBs at frequencies corresponding to channels 0,10,20
00117                            of spw 0
00118  
00119                    Primary beams are computed at these specified frequencies and 
00120                    for pointings selected by 'field'.  Taylor-coefficients that represent
00121                    the PB spectrum are computed from these images.
00122 
00123    weightlist -- List of relative weights to apply to the PBs selected via the
00124                      spwlist,chanlist parameters. Weights should approximately represent the
00125                      sum-of-weights applicable during imaging each of these frequencies.
00126               example : weightlist=[0.5,1.0,1.0] 
00127                                  The first frequency had less usable data due to flagged RFI,
00128                                  but the other two had relatively equal weight.
00129                      These weights are applied to the PB spectrum while computing
00130                      PB Taylor-coefficients. Setting weights to anything other than 1.0
00131                      makes a difference only with very lop-sided weights. 
00132 
00133   
00134         """
00135         a=inspect.stack()
00136         stacklevel=0
00137         for k in range(len(a)):
00138           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00139                 stacklevel=k
00140                 break
00141         myf=sys._getframe(stacklevel).f_globals
00142         myf['__last_task'] = 'widebandpbcor'
00143         myf['taskname'] = 'widebandpbcor'
00144         ###
00145         myf['update_params'](func=myf['taskname'],printtext=False)
00146         ###
00147         ###
00148         #Handle globals or user over-ride of arguments
00149         #
00150         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00151         useLocalDefaults = False
00152 
00153         for item in function_signature_defaults.iteritems():
00154                 key,val = item
00155                 keyVal = eval(key)
00156                 if (keyVal == None):
00157                         #user hasn't set it - use global/default
00158                         pass
00159                 else:
00160                         #user has set it - use over-ride
00161                         if (key != 'self') :
00162                            useLocalDefaults = True
00163                         #myf[key]=keyVal
00164 
00165         myparams = {}
00166         if useLocalDefaults :
00167            for item in function_signature_defaults.iteritems():
00168                key,val = item
00169                keyVal = eval(key)
00170                exec('myparams[key] = keyVal')
00171                if (keyVal == None):
00172                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00173                    keyVal = eval(key)
00174                    if(type(keyVal) == dict) :
00175                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00176 
00177         else :
00178             uselessvariable = None 
00179             myparams['vis'] = vis = myf['vis']
00180             myparams['imagename'] = imagename = myf['imagename']
00181             myparams['nterms'] = nterms = myf['nterms']
00182             myparams['threshold'] = threshold = myf['threshold']
00183             myparams['action'] = action = myf['action']
00184             myparams['reffreq'] = reffreq = myf['reffreq']
00185             myparams['pbmin'] = pbmin = myf['pbmin']
00186             myparams['field'] = field = myf['field']
00187             myparams['spwlist'] = spwlist = myf['spwlist']
00188             myparams['chanlist'] = chanlist = myf['chanlist']
00189             myparams['weightlist'] = weightlist = myf['weightlist']
00190 
00191         if type(spwlist)==int: spwlist=[spwlist]
00192         if type(chanlist)==int: chanlist=[chanlist]
00193         if type(weightlist)==float: weightlist=[weightlist]
00194 
00195         result = None
00196 
00197 #
00198 #    The following is work around to avoid a bug with current python translation
00199 #
00200         mytmp = {}
00201 
00202         mytmp['vis'] = vis
00203         mytmp['imagename'] = imagename
00204         mytmp['nterms'] = nterms
00205         mytmp['threshold'] = threshold
00206         mytmp['action'] = action
00207         mytmp['reffreq'] = reffreq
00208         mytmp['pbmin'] = pbmin
00209         mytmp['field'] = field
00210         mytmp['spwlist'] = spwlist
00211         mytmp['chanlist'] = chanlist
00212         mytmp['weightlist'] = weightlist
00213         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00214         trec = casac.utils().torecord(pathname+'widebandpbcor.xml')
00215 
00216         casalog.origin('widebandpbcor')
00217         if not trec.has_key('widebandpbcor') or not casac.utils().verify(mytmp, trec['widebandpbcor']) :
00218             return False
00219 
00220 
00221         try :
00222           casalog.post('')
00223           casalog.post('##########################################')
00224           casalog.post('##### Begin Task: widebandpbcor           #####')
00225           casalog.post('')
00226           result = widebandpbcor(vis, imagename, nterms, threshold, action, reffreq, pbmin, field, spwlist, chanlist, weightlist)
00227           casalog.post('')
00228           casalog.post('##### End Task: widebandpbcor           #####')
00229           casalog.post('##########################################')
00230 
00231 
00232 # saveinputs for individule engine has no use
00233 # saveinputs should alos be removed from casa_in_py.py
00234 #
00235 #
00236 #          saveinputs = myf['saveinputs']
00237 #          saveinputs('widebandpbcor', 'widebandpbcor.last', myparams)
00238 #
00239 #
00240         except Exception, instance:
00241           #print '**** Error **** ',instance
00242           pass
00243 
00244         gc.collect()
00245         return result
00246 #
00247 #
00248 ##
00249 #    def paramgui(self, useGlobals=True):
00250 #        """
00251 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00252 #        """
00253 #        import paramgui
00254 #
00255 #        a=inspect.stack()
00256 #        stacklevel=0
00257 #        for k in range(len(a)):
00258 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00259 #            stacklevel=k
00260 #            break
00261 #        myf = sys._getframe(stacklevel).f_globals
00262 #
00263 #        if useGlobals:
00264 #            paramgui.setGlobals(myf)
00265 #        else:
00266 #            paramgui.setGlobals({})
00267 #
00268 #        paramgui.runTask('widebandpbcor', myf['_ip'])
00269 #        paramgui.setGlobals({})
00270 #
00271 #
00272 #
00273 #
00274     def defaults(self, param=None):
00275         a=inspect.stack()
00276         stacklevel=0
00277         for k in range(len(a)):
00278           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00279                 stacklevel=k
00280                 break
00281         myf=sys._getframe(stacklevel).f_globals
00282         a = odict()
00283         a['vis']  = ''
00284         a['imagename']  = ''
00285         a['nterms']  = 2
00286         a['threshold']  = ''
00287         a['action']  = 'pbcor'
00288 
00289         a['async']=False
00290         a['action'] = {
00291                     0:odict([{'value':'pbcor'}, {'reffreq':''}, {'pbmin':0.2}, {'field':''}, {'spwlist':[]}, {'chanlist':[]}, {'weightlist':[]}])}
00292 
00293 ### This function sets the default values but also will return the list of
00294 ### parameters or the default value of a given parameter
00295         if(param == None):
00296                 myf['__set_default_parameters'](a)
00297         elif(param == 'paramkeys'):
00298                 return a.keys()
00299         else:
00300                 if(a.has_key(param)):
00301                    #if(type(a[param]) == dict) :
00302                    #   return a[param][len(a[param])-1]['value']
00303                    #else :
00304                       return a[param]
00305 
00306 
00307 #
00308 #
00309     def check_params(self, param=None, value=None):
00310       a=inspect.stack() 
00311       stacklevel=0
00312       for k in range(len(a)):
00313         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00314             stacklevel=k
00315             break
00316       myf=sys._getframe(stacklevel).f_globals
00317 
00318 #      print 'param:', param, 'value:', value
00319       try :
00320          if str(type(value)) != "<type 'instance'>" :
00321             value0 = value
00322             value = myf['cu'].expandparam(param, value)
00323             matchtype = False
00324             if(type(value) == numpy.ndarray):
00325                if(type(value) == type(value0)):
00326                   myf[param] = value.tolist()
00327                else:
00328                   #print 'value:', value, 'value0:', value0
00329                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00330                   myf[param] = value0
00331                   if type(value0) != list :
00332                      matchtype = True
00333             else :
00334                myf[param] = value
00335             value = myf['cu'].verifyparam({param:value})
00336             if matchtype:
00337                value = False
00338       except Exception, instance:
00339          #ignore the exception and just return it unchecked
00340          myf[param] = value
00341       return value
00342 
00343 #
00344 #
00345     def description(self, key='widebandpbcor', subkey=None):
00346         desc={'widebandpbcor': 'Wideband PB-correction on the output of the MS-MFS algorithm',
00347                'vis': 'Name of measurement set. ',
00348                'imagename': 'Name-prefix of multi-termimages to operate on. ',
00349                'nterms': 'Number of taylor terms to use',
00350                'threshold': 'Intensity above which to re-calculate spectral index ',
00351                'action': 'PB-correction (pbcor) or only calc spectral-index (calcalpha)',
00352                'reffreq': 'Reference frequency (if specified in clean)',
00353                'pbmin': 'PB threshold below which to not correct',
00354                'field': 'Fields to include in the PB calculation',
00355                'spwlist': 'List of N spw ids',
00356                'chanlist': 'List of N channel ids',
00357                'weightlist': 'List of N weights (relative)',
00358 
00359                'async': 'If true the taskname must be started using widebandpbcor(...)'
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['vis']  = ''
00372         a['imagename']  = ''
00373         a['nterms']  = 2
00374         a['threshold']  = ''
00375         a['action']  = 'pbcor'
00376         a['reffreq']  = ''
00377         a['pbmin']  = 0.2
00378         a['field']  = ''
00379         a['spwlist']  = []
00380         a['chanlist']  = []
00381         a['weightlist']  = []
00382 
00383         if a.has_key(paramname) :
00384               return a[paramname]
00385 widebandpbcor_pg = widebandpbcor_pg_()