casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
accum_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_accum import accum
00016 from task_accum import casalog
00017 
00018 class accum_pg_:
00019     __name__ = "accum"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (accum_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, tablein=None, incrtable=None, caltable=None, field=None, calfield=None, interp=None, accumtime=None, spwmap=None, async=None):
00027 
00028         """Accumulate incremental calibration solutions into a calibration table
00029 
00030        Accum will interpolate and extrapolate a temporal calibration
00031        table onto a new table that has a regularly-space time grid.
00032 
00033        The first run of accum defines the time grid and fills this
00034        table with the results from the input table.
00035 
00036        Subsequent use of accum will combine additional calibration
00037        tables onto the same grid of the initial accum table to obtain
00038        an output accum table.  See below for a concrete example.
00039 
00040 
00041      Keyword arguments:
00042 
00043      vis -- Name of input visibility file
00044              default: none.  example: vis='ngc5921.ms'
00045      tablein -- Input cumulative calibration table.
00046              default: ''  means none
00047              On first execution of accum, tablein=''
00048              and accumtime is used to generate tablein with
00049              the specified time gridding.
00050      accumtime -- The time separation when making tablein.
00051              default: 1.0  (1 second).  This time should not be
00052              less than the visibiility sampling time, but should
00053              be less than about 30% of a typical scan length.
00054      incrtable -- The calibration data to be interpolated onto the
00055              tablein file.
00056              default: ''.  Must be specified
00057      caltable -- The output cumulated calibration file.
00058              default: ''  means use tablein as the output file
00059              
00060      field -- Select field(s) from tablein to process.
00061               ['go listobs' to obtain the list id's or names]
00062             default: ''= all fields
00063             If field string is a non-negative integer, it is assumed to
00064                be a field index otherwise, it is assumed to be a field name
00065             field='0~2'; field ids 0,1,2
00066             field='0,4,5~7'; field ids 0,4,5,6,7
00067             field='3C286,3C295'; field named 3C286 and 3C295
00068             field = '3,4C*'; field id 3, all names starting with 4C
00069      calfield -- Select field(s) from incrtable to process.
00070             default: '' = all fields
00071      interp -- Interpolation type (in time[,freq]) to use for each gaintable.
00072                 When frequency interpolation is relevant (B, Df, Xf),
00073                 separate time-dependent and freq-dependent interp
00074                 types with a comma (freq _after_ the comma).                
00075                 Specifications for frequency are ignored when the
00076                 calibration table has no channel-dependence.
00077                 Time-dependent interp options ending in 'PD' enable a
00078                 "phase delay" correction per spw for non-channel-dependent
00079                 calibration types.
00080                 default: '' --> 'linear,linear' for all gaintable(s)
00081                 example: interp='nearest'   (in time, freq-dep will be
00082                                              linear, if relevant)
00083                          interp='linear,cubic'  (linear in time, cubic
00084                                                  in freq)
00085                          interp=',spline'  (spline in freq; linear in
00086                                             time by default)
00087                          interp=['nearest,spline','linear']  (for multiple gaintables)
00088                 Options: Time: 'nearest', 'linear'
00089                          Freq: 'nearest', 'linear', 'cubic', 'spline'
00090      spwmap -- Spectral windows combinations to form for gaintable(s)
00091             default: [] (apply solutions from each spw to that spw only)
00092             Example:  spwmap=[0,0,1,1] means apply the caltable solutions
00093                       from spw = 0 to the spw 0,1 and spw 1 to spw 2,3.
00094                       spwmap=[[0,0,1,1],[0,1,0,1]]  (for multiple gaintables)
00095      async -- Run task in a separate process 
00096              default: False; example: async=True
00097 
00098      Examples:
00099 
00100        Create an accum table with 10-sec sampling, filling it with the calibration
00101           in 'first_cal' with the desired interpolation.
00102 
00103            taskname = 'accum'
00104              default()
00105              vis = 'mydata.ms'
00106              tablein = ''
00107              accumtime = 10
00108              incrtable = 'first_cal'
00109              caltable = 'accum1_cal'
00110              accum()
00111 
00112        If you plot 'accum1_cal' with plotcal, you can see how the incrtable was
00113              interpolated.
00114 
00115        Continue accumulating calibrations in accum1_cal from 'second_cal'
00116 
00117            taskname = 'accum'
00118              default()
00119              vis = 'mydata.ms'
00120              tablein = 'accum1_cal'
00121              incrtable = 'second_cal'
00122              caltable = 'accum1_cal'
00123              accum()
00124 
00125        Incorporate gaincurve, opacity, parang once and for all
00126 
00127           taskname= 'gaincal'
00128              vis = 'mydata.ms'
00129              caltable = 'first_cal'
00130                etc
00131              gaincurve = T
00132              opacity = 0.11
00133              parang = T
00134              gaincal()
00135 
00136            taskname = 'accum'
00137              default()
00138              vis = 'mydata.ms'
00139              tablein = ''
00140              accumtime = 10
00141              incrtable = 'first_cal'
00142              caltable = 'accum1_cal'
00143              accum()
00144 
00145          accum1_cal with contain not only the gaincal solution, but the gaincurve,
00146              opacity and parang correction.  Hence, when applying accum1_cal
00147              on the fly for subsequent calibrations (gaincal, bandpass) or applying
00148              the calibrations, then
00149                 gaincurve=F; opacity = 0.0; parang = F  should be used
00150      
00151   
00152  
00153         """
00154         a=inspect.stack()
00155         stacklevel=0
00156         for k in range(len(a)):
00157           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00158                 stacklevel=k
00159                 break
00160         myf=sys._getframe(stacklevel).f_globals
00161         myf['__last_task'] = 'accum'
00162         myf['taskname'] = 'accum'
00163         ###
00164         myf['update_params'](func=myf['taskname'],printtext=False)
00165         ###
00166         ###
00167         #Handle globals or user over-ride of arguments
00168         #
00169         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00170         useLocalDefaults = False
00171 
00172         for item in function_signature_defaults.iteritems():
00173                 key,val = item
00174                 keyVal = eval(key)
00175                 if (keyVal == None):
00176                         #user hasn't set it - use global/default
00177                         pass
00178                 else:
00179                         #user has set it - use over-ride
00180                         if (key != 'self') :
00181                            useLocalDefaults = True
00182                         #myf[key]=keyVal
00183 
00184         myparams = {}
00185         if useLocalDefaults :
00186            for item in function_signature_defaults.iteritems():
00187                key,val = item
00188                keyVal = eval(key)
00189                exec('myparams[key] = keyVal')
00190                if (keyVal == None):
00191                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00192                    keyVal = eval(key)
00193                    if(type(keyVal) == dict) :
00194                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00195 
00196         else :
00197             uselessvariable = None 
00198             myparams['vis'] = vis = myf['vis']
00199             myparams['tablein'] = tablein = myf['tablein']
00200             myparams['incrtable'] = incrtable = myf['incrtable']
00201             myparams['caltable'] = caltable = myf['caltable']
00202             myparams['field'] = field = myf['field']
00203             myparams['calfield'] = calfield = myf['calfield']
00204             myparams['interp'] = interp = myf['interp']
00205             myparams['accumtime'] = accumtime = myf['accumtime']
00206             myparams['spwmap'] = spwmap = myf['spwmap']
00207 
00208         if type(field)==str: field=[field]
00209         if type(calfield)==str: calfield=[calfield]
00210         if type(spwmap)==int: spwmap=[spwmap]
00211 
00212         result = None
00213 
00214 #
00215 #    The following is work around to avoid a bug with current python translation
00216 #
00217         mytmp = {}
00218 
00219         mytmp['vis'] = vis
00220         mytmp['tablein'] = tablein
00221         mytmp['incrtable'] = incrtable
00222         mytmp['caltable'] = caltable
00223         mytmp['field'] = field
00224         mytmp['calfield'] = calfield
00225         mytmp['interp'] = interp
00226         mytmp['accumtime'] = accumtime
00227         mytmp['spwmap'] = spwmap
00228         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00229         trec = casac.utils().torecord(pathname+'accum.xml')
00230 
00231         casalog.origin('accum')
00232         if not trec.has_key('accum') or not casac.utils().verify(mytmp, trec['accum']) :
00233             return False
00234 
00235 
00236         try :
00237           casalog.post('')
00238           casalog.post('##########################################')
00239           casalog.post('##### Begin Task: accum           #####')
00240           casalog.post('')
00241           result = accum(vis, tablein, incrtable, caltable, field, calfield, interp, accumtime, spwmap)
00242           casalog.post('')
00243           casalog.post('##### End Task: accum           #####')
00244           casalog.post('##########################################')
00245 
00246 
00247 # saveinputs for individule engine has no use
00248 # saveinputs should alos be removed from casa_in_py.py
00249 #
00250 #
00251 #          saveinputs = myf['saveinputs']
00252 #          saveinputs('accum', 'accum.last', myparams)
00253 #
00254 #
00255         except Exception, instance:
00256           #print '**** Error **** ',instance
00257           pass
00258 
00259         gc.collect()
00260         return result
00261 #
00262 #
00263 ##
00264 #    def paramgui(self, useGlobals=True):
00265 #        """
00266 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00267 #        """
00268 #        import paramgui
00269 #
00270 #        a=inspect.stack()
00271 #        stacklevel=0
00272 #        for k in range(len(a)):
00273 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00274 #            stacklevel=k
00275 #            break
00276 #        myf = sys._getframe(stacklevel).f_globals
00277 #
00278 #        if useGlobals:
00279 #            paramgui.setGlobals(myf)
00280 #        else:
00281 #            paramgui.setGlobals({})
00282 #
00283 #        paramgui.runTask('accum', myf['_ip'])
00284 #        paramgui.setGlobals({})
00285 #
00286 #
00287 #
00288 #
00289     def defaults(self, param=None):
00290         a=inspect.stack()
00291         stacklevel=0
00292         for k in range(len(a)):
00293           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00294                 stacklevel=k
00295                 break
00296         myf=sys._getframe(stacklevel).f_globals
00297         a = odict()
00298         a['vis']  = ''
00299         a['tablein']  = ''
00300         a['incrtable']  = ''
00301         a['caltable']  = ''
00302         a['field']  = ['']
00303         a['calfield']  = ['']
00304         a['interp']  = 'linear'
00305         a['spwmap']  = [-1]
00306 
00307         a['async']=False
00308         a['tablein'] = {
00309                     0:odict([{'value':''}, {'accumtime':1.0}])}
00310 
00311 ### This function sets the default values but also will return the list of
00312 ### parameters or the default value of a given parameter
00313         if(param == None):
00314                 myf['__set_default_parameters'](a)
00315         elif(param == 'paramkeys'):
00316                 return a.keys()
00317         else:
00318                 if(a.has_key(param)):
00319                    #if(type(a[param]) == dict) :
00320                    #   return a[param][len(a[param])-1]['value']
00321                    #else :
00322                       return a[param]
00323 
00324 
00325 #
00326 #
00327     def check_params(self, param=None, value=None):
00328       a=inspect.stack() 
00329       stacklevel=0
00330       for k in range(len(a)):
00331         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00332             stacklevel=k
00333             break
00334       myf=sys._getframe(stacklevel).f_globals
00335 
00336 #      print 'param:', param, 'value:', value
00337       try :
00338          if str(type(value)) != "<type 'instance'>" :
00339             value0 = value
00340             value = myf['cu'].expandparam(param, value)
00341             matchtype = False
00342             if(type(value) == numpy.ndarray):
00343                if(type(value) == type(value0)):
00344                   myf[param] = value.tolist()
00345                else:
00346                   #print 'value:', value, 'value0:', value0
00347                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00348                   myf[param] = value0
00349                   if type(value0) != list :
00350                      matchtype = True
00351             else :
00352                myf[param] = value
00353             value = myf['cu'].verifyparam({param:value})
00354             if matchtype:
00355                value = False
00356       except Exception, instance:
00357          #ignore the exception and just return it unchecked
00358          myf[param] = value
00359       return value
00360 
00361 #
00362 #
00363     def description(self, key='accum', subkey=None):
00364         desc={'accum': 'Accumulate incremental calibration solutions into a calibration table',
00365                'vis': 'Name of input visibility file',
00366                'tablein': 'Input cumulative calibration table; use \'\' on first run',
00367                'incrtable': 'Input incremental calibration table to add',
00368                'caltable': 'Output (cumulative) calibration table',
00369                'field': 'List of field names to process from tablein',
00370                'calfield': 'List of field names to use from incrtable.',
00371                'interp': 'Interpolation mode to use for resampling incrtable solutions',
00372                'accumtime': 'Time-interval when create cumulative table',
00373                'spwmap': 'Spectral window combinations to apply',
00374 
00375                'async': 'If true the taskname must be started using accum(...)'
00376               }
00377 
00378 #
00379 # Set subfields defaults if needed
00380 #
00381 
00382         if(desc.has_key(key)) :
00383            return desc[key]
00384 
00385     def itsdefault(self, paramname) :
00386         a = {}
00387         a['vis']  = ''
00388         a['tablein']  = ''
00389         a['incrtable']  = ''
00390         a['caltable']  = ''
00391         a['field']  = ['']
00392         a['calfield']  = ['']
00393         a['interp']  = 'linear'
00394         a['accumtime']  = 1.0
00395         a['spwmap']  = [-1]
00396 
00397         if a.has_key(paramname) :
00398               return a[paramname]
00399 accum_pg = accum_pg_()