casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
fluxscale_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_fluxscale import fluxscale
00016 from task_fluxscale import casalog
00017 
00018 class fluxscale_pg_:
00019     __name__ = "fluxscale"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (fluxscale_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, caltable=None, fluxtable=None, reference=None, transfer=None, listfile=None, append=None, refspwmap=None, incremental=None, async=None):
00027 
00028         """Bootstrap the flux density scale from standard calibrators
00029 
00030        After running gaincal on standard flux density calibrators (with or
00031        without an image model), and other calibrators with unknown flux
00032        densities (assumed 1 Jy), fluxscale applies the constraint that
00033        net system gain was, in fact, independent of field, on average,
00034        and that field-dependent gains in the input caltable are solely
00035        a result of the unknown flux densities for the calibrators.
00036        Using time-averaged gain amplitudes, the ratio between 
00037        each ordinary calibrator and the flux density calibrator(s) is 
00038        formed for each antenna and polarization (that they have in
00039        common).  For incremetal=False(default), the median of 
00040        this ratio over antennas and polarizations yields a correction 
00041        factor that is applied to the ordinary calibrators' gains. For 
00042        incremental=True, only the correction factors are written out 
00043        to the output fluxtable.
00044 
00045        The square of the gain correction factor for each calibrator
00046        and spw is the presumed flux density of that calibrator, and is
00047        reported in the logger.  The errors reported with this value
00048        reflect the scatter in gain ratio over antennas and
00049        polarizations, divided by the square root of the number of 
00050        antennas and polarizations available.  If the flux densities 
00051        for multiple spws exist, fitted spectral index and (for nspw>2)
00052        curvature are also reported. The MODEL_DATA column
00053        is currently _not_ revised to reflect the flux densities
00054        derived by fluxscale.  Use setjy to set the MODEL_DATA column,
00055        if necessary.
00056 
00057        The constant gain constraint is usually a reasonable assumption
00058        for the electronic systems on typical antennas.  It is
00059        important that external time- and/or elevation-dependent
00060        effects are separately accounted for when solving for the gain
00061        solution supplied to fluxscale, e.g., gain curves, 
00062        opacity, etc.  The fluxscale results can also be degraded
00063        by poor pointing during the observation.
00064 
00065 
00066        Keyword arguments:
00067        vis -- Name of input visibility file
00068                default: none; example: vis='ngc5921.ms'
00069        caltable -- Name of input calibration table
00070                default: none; example: caltable='ngc5921.gcal'
00071                This cal table was obtained from task gaincal.
00072        fluxtable -- Name of output, flux-scaled calibration table
00073                default: none; example: fluxtable='ngc5921.gcal2'
00074                The gains in this table have been adjusted by the
00075                derived flux density each calibrator.  The MODEL_DATA
00076                column has NOT been updated for the flux density of the
00077                calibrator.  Use setjy to do this if it is a point source.
00078        reference -- Reference field name(s)
00079                The names of the fields with a known flux densities or
00080                   visibilties that have been placed in the MODEL column
00081                   by setjy or ft for a model not in the CASA system.
00082                The syntax is similar to field.  Hence field index or
00083                   names can be used.
00084                default: none; example: reference='1328+307'
00085        transfer -- Transfer field name(s)
00086                The names of the fields with unknown flux densities.
00087                   These should be point-like calibrator sources
00088                The syntax is similar to field.  Hence source index or
00089                  names can be used.
00090                default: '' = all sources in caltable that are not specified
00091                   as reference sources.  Do not include unknown target sources
00092                example: transfer='1445+099, 3C84'; transfer = '0,4'
00093 
00094                NOTE: All fields in reference and transfer must have solutions
00095                in the caltable.
00096 
00097        listfile -- Fit listfile name
00098                The list file contains the flux density, flux density error,
00099                  S/N, and number of solutions (all antennas and feeds) for each
00100                  spectral window.  NOTE: The nominal spectral window frequencies
00101                  will be included in the future.
00102                default: '' = no fit listfile will be created.
00103 
00104        append -- Append fluxscaled solutions to the fluxtable.
00105                default: False; (will overwrite if already existing)
00106                example: append=True
00107        refspwmap -- Vector of spectral windows enablings scaling across
00108                spectral windows
00109                default: [-1]==> none.
00110                Example with 4 spectral windows:
00111                if the reference fields were observed only in spw=1 & 3,
00112                and the transfer fields were observed in all 4 spws (0,1,2,3),
00113                specify refspwmap=[1,1,3,3].
00114                This will ensure that transfer fields observed in spws 0,1,2,3
00115                will be referenced to reference field solutions only in
00116                spw 1 or 3.
00117       
00118        incremental -- Create an incremental caltable containing only gain correction 
00119                factors ( flux density= 1/(gain correction factor)**2)
00120                default: False; (older behavior = create flux-scaled gain table)
00121                example: incremental=True (output a caltable containing flux scale factors.)
00122               
00123                NOTE: If you use the incremental option, note that BOTH this incremental 
00124                fluxscale table AND an amplitude vs. time table should be supplied in applycal.
00125 
00126  
00127         """
00128         a=inspect.stack()
00129         stacklevel=0
00130         for k in range(len(a)):
00131           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00132                 stacklevel=k
00133                 break
00134         myf=sys._getframe(stacklevel).f_globals
00135         myf['__last_task'] = 'fluxscale'
00136         myf['taskname'] = 'fluxscale'
00137         ###
00138         myf['update_params'](func=myf['taskname'],printtext=False)
00139         ###
00140         ###
00141         #Handle globals or user over-ride of arguments
00142         #
00143         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00144         useLocalDefaults = False
00145 
00146         for item in function_signature_defaults.iteritems():
00147                 key,val = item
00148                 keyVal = eval(key)
00149                 if (keyVal == None):
00150                         #user hasn't set it - use global/default
00151                         pass
00152                 else:
00153                         #user has set it - use over-ride
00154                         if (key != 'self') :
00155                            useLocalDefaults = True
00156                         #myf[key]=keyVal
00157 
00158         myparams = {}
00159         if useLocalDefaults :
00160            for item in function_signature_defaults.iteritems():
00161                key,val = item
00162                keyVal = eval(key)
00163                exec('myparams[key] = keyVal')
00164                if (keyVal == None):
00165                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00166                    keyVal = eval(key)
00167                    if(type(keyVal) == dict) :
00168                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00169 
00170         else :
00171             uselessvariable = None 
00172             myparams['vis'] = vis = myf['vis']
00173             myparams['caltable'] = caltable = myf['caltable']
00174             myparams['fluxtable'] = fluxtable = myf['fluxtable']
00175             myparams['reference'] = reference = myf['reference']
00176             myparams['transfer'] = transfer = myf['transfer']
00177             myparams['listfile'] = listfile = myf['listfile']
00178             myparams['append'] = append = myf['append']
00179             myparams['refspwmap'] = refspwmap = myf['refspwmap']
00180             myparams['incremental'] = incremental = myf['incremental']
00181 
00182         if type(reference)==str: reference=[reference]
00183         if type(transfer)==str: transfer=[transfer]
00184         if type(refspwmap)==int: refspwmap=[refspwmap]
00185 
00186         result = None
00187 
00188 #
00189 #    The following is work around to avoid a bug with current python translation
00190 #
00191         mytmp = {}
00192 
00193         mytmp['vis'] = vis
00194         mytmp['caltable'] = caltable
00195         mytmp['fluxtable'] = fluxtable
00196         mytmp['reference'] = reference
00197         mytmp['transfer'] = transfer
00198         mytmp['listfile'] = listfile
00199         mytmp['append'] = append
00200         mytmp['refspwmap'] = refspwmap
00201         mytmp['incremental'] = incremental
00202         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00203         trec = casac.utils().torecord(pathname+'fluxscale.xml')
00204 
00205         casalog.origin('fluxscale')
00206         if not trec.has_key('fluxscale') or not casac.utils().verify(mytmp, trec['fluxscale']) :
00207             return False
00208 
00209 
00210         try :
00211           casalog.post('')
00212           casalog.post('##########################################')
00213           casalog.post('##### Begin Task: fluxscale           #####')
00214           casalog.post('')
00215           result = fluxscale(vis, caltable, fluxtable, reference, transfer, listfile, append, refspwmap, incremental)
00216           casalog.post('')
00217           casalog.post('##### End Task: fluxscale           #####')
00218           casalog.post('##########################################')
00219 
00220 
00221 # saveinputs for individule engine has no use
00222 # saveinputs should alos be removed from casa_in_py.py
00223 #
00224 #
00225 #          saveinputs = myf['saveinputs']
00226 #          saveinputs('fluxscale', 'fluxscale.last', myparams)
00227 #
00228 #
00229         except Exception, instance:
00230           #print '**** Error **** ',instance
00231           pass
00232 
00233         gc.collect()
00234         return result
00235 #
00236 #
00237 ##
00238 #    def paramgui(self, useGlobals=True):
00239 #        """
00240 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00241 #        """
00242 #        import paramgui
00243 #
00244 #        a=inspect.stack()
00245 #        stacklevel=0
00246 #        for k in range(len(a)):
00247 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00248 #            stacklevel=k
00249 #            break
00250 #        myf = sys._getframe(stacklevel).f_globals
00251 #
00252 #        if useGlobals:
00253 #            paramgui.setGlobals(myf)
00254 #        else:
00255 #            paramgui.setGlobals({})
00256 #
00257 #        paramgui.runTask('fluxscale', myf['_ip'])
00258 #        paramgui.setGlobals({})
00259 #
00260 #
00261 #
00262 #
00263     def defaults(self, param=None):
00264         a=inspect.stack()
00265         stacklevel=0
00266         for k in range(len(a)):
00267           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00268                 stacklevel=k
00269                 break
00270         myf=sys._getframe(stacklevel).f_globals
00271         a = odict()
00272         a['vis']  = ''
00273         a['caltable']  = ''
00274         a['fluxtable']  = ''
00275         a['reference']  = ['']
00276         a['transfer']  = ['']
00277         a['listfile']  = ''
00278         a['append']  = False
00279         a['refspwmap']  = [-1]
00280         a['incremental']  = False
00281 
00282         a['async']=False
00283 
00284 ### This function sets the default values but also will return the list of
00285 ### parameters or the default value of a given parameter
00286         if(param == None):
00287                 myf['__set_default_parameters'](a)
00288         elif(param == 'paramkeys'):
00289                 return a.keys()
00290         else:
00291                 if(a.has_key(param)):
00292                    #if(type(a[param]) == dict) :
00293                    #   return a[param][len(a[param])-1]['value']
00294                    #else :
00295                       return a[param]
00296 
00297 
00298 #
00299 #
00300     def check_params(self, param=None, value=None):
00301       a=inspect.stack() 
00302       stacklevel=0
00303       for k in range(len(a)):
00304         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00305             stacklevel=k
00306             break
00307       myf=sys._getframe(stacklevel).f_globals
00308 
00309 #      print 'param:', param, 'value:', value
00310       try :
00311          if str(type(value)) != "<type 'instance'>" :
00312             value0 = value
00313             value = myf['cu'].expandparam(param, value)
00314             matchtype = False
00315             if(type(value) == numpy.ndarray):
00316                if(type(value) == type(value0)):
00317                   myf[param] = value.tolist()
00318                else:
00319                   #print 'value:', value, 'value0:', value0
00320                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00321                   myf[param] = value0
00322                   if type(value0) != list :
00323                      matchtype = True
00324             else :
00325                myf[param] = value
00326             value = myf['cu'].verifyparam({param:value})
00327             if matchtype:
00328                value = False
00329       except Exception, instance:
00330          #ignore the exception and just return it unchecked
00331          myf[param] = value
00332       return value
00333 
00334 #
00335 #
00336     def description(self, key='fluxscale', subkey=None):
00337         desc={'fluxscale': 'Bootstrap the flux density scale from standard calibrators',
00338                'vis': 'Name of input visibility file (MS)',
00339                'caltable': 'Name of input calibration table',
00340                'fluxtable': 'Name of output, flux-scaled calibration table',
00341                'reference': 'Reference field name(s) (transfer flux scale FROM)',
00342                'transfer': 'Transfer field name(s) (transfer flux scale TO), \'\' -> all',
00343                'listfile': 'Name of listfile that contains the fit information.  Default is '' (no file).',
00344                'append': 'Append solutions?',
00345                'refspwmap': 'Scale across spectral window boundaries.  See help fluxscale',
00346                'incremental': 'incremental caltable',
00347 
00348                'async': 'If true the taskname must be started using fluxscale(...)'
00349               }
00350 
00351         if(desc.has_key(key)) :
00352            return desc[key]
00353 
00354     def itsdefault(self, paramname) :
00355         a = {}
00356         a['vis']  = ''
00357         a['caltable']  = ''
00358         a['fluxtable']  = ''
00359         a['reference']  = ['']
00360         a['transfer']  = ['']
00361         a['listfile']  = ''
00362         a['append']  = False
00363         a['refspwmap']  = [-1]
00364         a['incremental']  = False
00365 
00366         if a.has_key(paramname) :
00367               return a[paramname]
00368 fluxscale_pg = fluxscale_pg_()