casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
hanningsmooth_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_hanningsmooth import hanningsmooth
00018 class hanningsmooth_cli_:
00019     __name__ = "hanningsmooth"
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__ = (hanningsmooth_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'datacolumn':None, 'outputvis':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, vis=None, datacolumn=None, outputvis=None,  async=None):
00047 
00048         """Hanning smooth frequency channel data to remove Gibbs ringing
00049 
00050     This function Hanning smoothes the frequency channels with
00051     a weighted running average. The weights are 0.5 for the central 
00052     channel and 0.25 for each of the two adjacent channels. The first 
00053     and last channels are flagged.
00054     Inclusion of a flagged value in an average causes that data value
00055     to be flagged. 
00056     If an 'outputvis' filename is given, the task will copy the input file to the 
00057     output file name first, including all columns that are present in the input MS. 
00058     After that step it will smooth the column(s) as requested in the 'datacolumn' parameter. 
00059     Alternatively, if no 'outputvis' is specified, hanningsmooth will work directly on the 
00060     input visibility file. 
00061     If the 'CORRECTED' data column is requested for an MS that does not contain this column, 
00062     it will be filled from the 'DATA' column and then smoothed.
00063     
00064     WARNING: by default, all visibility columns will be smoothed. This will 
00065              modify the DATA column of the output MS in order to make sure that
00066              later gaincal will work on the smoothed data, e.g. as part of self-cal.
00067 
00068     Keyword arguments:
00069     vis -- Name of input visibility file (MS)
00070            default: none; example: vis='ngc5921.ms'
00071     datacolumn -- the name of the MS column to be Hanning smoothed
00072                   default='all'; example: datacolumn='corrected'
00073                   options: 'corrected', 'data', 'all'
00074     outputvis -- name of the output visibility file (MS)
00075                  default=none (write to the input MS); example: outputvis='ngc5921_src.ms'
00076 
00077     hanningsmooth(vis='ngc4852.ms', datacolumn='data', outputvis='ngc4852-hs.ms')                
00078 
00079 
00080  
00081         """
00082         if not hasattr(self, "__globals__") or self.__globals__ == None :
00083            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00084         #casac = self.__globals__['casac']
00085         casalog = self.__globals__['casalog']
00086         #casalog = casac.casac.logsink()
00087         self.__globals__['__last_task'] = 'hanningsmooth'
00088         self.__globals__['taskname'] = 'hanningsmooth'
00089         ###
00090         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00091         ###
00092         ###
00093         #Handle globals or user over-ride of arguments
00094         #
00095         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00096         useLocalDefaults = False
00097 
00098         for item in function_signature_defaults.iteritems():
00099                 key,val = item
00100                 keyVal = eval(key)
00101                 if (keyVal == None):
00102                         #user hasn't set it - use global/default
00103                         pass
00104                 else:
00105                         #user has set it - use over-ride
00106                         if (key != 'self') :
00107                            useLocalDefaults = True
00108 
00109         myparams = {}
00110         if useLocalDefaults :
00111            for item in function_signature_defaults.iteritems():
00112                key,val = item
00113                keyVal = eval(key)
00114                exec('myparams[key] = keyVal')
00115                self.parameters[key] = keyVal
00116                if (keyVal == None):
00117                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00118                    keyVal = eval(key)
00119                    if(type(keyVal) == dict) :
00120                       if len(keyVal) > 0 :
00121                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00122                       else :
00123                          exec('myparams[key] = ' + key + ' = {}')
00124 
00125         else :
00126             async = self.parameters['async']
00127             myparams['vis'] = vis = self.parameters['vis']
00128             myparams['datacolumn'] = datacolumn = self.parameters['datacolumn']
00129             myparams['outputvis'] = outputvis = self.parameters['outputvis']
00130 
00131 
00132         result = None
00133 
00134 #
00135 #    The following is work around to avoid a bug with current python translation
00136 #
00137         mytmp = {}
00138 
00139         mytmp['vis'] = vis
00140         mytmp['datacolumn'] = datacolumn
00141         mytmp['outputvis'] = outputvis
00142         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00143         trec = casac.casac.utils().torecord(pathname+'hanningsmooth.xml')
00144 
00145         casalog.origin('hanningsmooth')
00146         try :
00147           #if not trec.has_key('hanningsmooth') or not casac.casac.utils().verify(mytmp, trec['hanningsmooth']) :
00148             #return False
00149 
00150           casac.casac.utils().verify(mytmp, trec['hanningsmooth'], True)
00151           scriptstr=['']
00152           saveinputs = self.__globals__['saveinputs']
00153           saveinputs('hanningsmooth', 'hanningsmooth.last', myparams, self.__globals__,scriptstr=scriptstr)
00154           if async :
00155             count = 0
00156             keybase =  time.strftime("%y%m%d.%H%M%S")
00157             key = keybase + "_" + str(count)
00158             while self.__async__.has_key(key) :
00159                count += 1
00160                key = keybase + "_" + str(count)
00161             result = tm.execute('hanningsmooth', vis, datacolumn, outputvis)
00162             print "Use: "
00163             print "      tm.retrieve(return_value) # to retrieve the status"
00164             print 
00165             self.rkey = key
00166             self.__async__[key] = result
00167           else :
00168               tname = 'hanningsmooth'
00169               spaces = ' '*(18-len(tname))
00170               casalog.post('\n##########################################'+
00171                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00172               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00173               result = hanningsmooth(vis, datacolumn, outputvis)
00174               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00175                            '\n##########################################')
00176 
00177         except Exception, instance:
00178           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00179              raise
00180           else :
00181              #print '**** Error **** ',instance
00182              tname = 'hanningsmooth'
00183              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00184              pass
00185 
00186         gc.collect()
00187         return result
00188 #
00189 #
00190 #
00191     def paramgui(self, useGlobals=True, ipython_globals=None):
00192         """
00193         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00194         """
00195         import paramgui
00196         if not hasattr(self, "__globals__") or self.__globals__ == None :
00197            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00198 
00199         if useGlobals:
00200             if ipython_globals == None:
00201                 myf=self.__globals__
00202             else:
00203                 myf=ipython_globals
00204 
00205             paramgui.setGlobals(myf)
00206         else:
00207             paramgui.setGlobals({})
00208 
00209         paramgui.runTask('hanningsmooth', myf['_ip'])
00210         paramgui.setGlobals({})
00211 
00212 #
00213 #
00214 #
00215     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00216         if not hasattr(self, "__globals__") or self.__globals__ == None :
00217            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00218         if ipython_globals == None:
00219             myf=self.__globals__
00220         else:
00221             myf=ipython_globals
00222 
00223         a = odict()
00224         a['vis']  = ''
00225         a['datacolumn']  = 'all'
00226         a['outputvis']  = ''
00227 
00228         a['async']=False
00229 
00230 ### This function sets the default values but also will return the list of
00231 ### parameters or the default value of a given parameter
00232         if(param == None):
00233                 myf['__set_default_parameters'](a)
00234         elif(param == 'paramkeys'):
00235                 return a.keys()
00236         else:
00237             if(paramvalue==None and subparam==None):
00238                if(a.has_key(param)):
00239                   return a[param]
00240                else:
00241                   return self.itsdefault(param)
00242             else:
00243                retval=a[param]
00244                if(type(a[param])==dict):
00245                   for k in range(len(a[param])):
00246                      valornotval='value'
00247                      if(a[param][k].has_key('notvalue')):
00248                         valornotval='notvalue'
00249                      if((a[param][k][valornotval])==paramvalue):
00250                         retval=a[param][k].copy()
00251                         retval.pop(valornotval)
00252                         if(subparam != None):
00253                            if(retval.has_key(subparam)):
00254                               retval=retval[subparam]
00255                            else:
00256                               retval=self.itsdefault(subparam)
00257                      else:
00258                         retval=self.itsdefault(subparam)
00259                return retval
00260 
00261 
00262 #
00263 #
00264     def check_params(self, param=None, value=None, ipython_globals=None):
00265       if ipython_globals == None:
00266           myf=self.__globals__
00267       else:
00268           myf=ipython_globals
00269 #      print 'param:', param, 'value:', value
00270       try :
00271          if str(type(value)) != "<type 'instance'>" :
00272             value0 = value
00273             value = myf['cu'].expandparam(param, value)
00274             matchtype = False
00275             if(type(value) == numpy.ndarray):
00276                if(type(value) == type(value0)):
00277                   myf[param] = value.tolist()
00278                else:
00279                   #print 'value:', value, 'value0:', value0
00280                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00281                   myf[param] = value0
00282                   if type(value0) != list :
00283                      matchtype = True
00284             else :
00285                myf[param] = value
00286             value = myf['cu'].verifyparam({param:value})
00287             if matchtype:
00288                value = False
00289       except Exception, instance:
00290          #ignore the exception and just return it unchecked
00291          myf[param] = value
00292       return value
00293 #
00294 #
00295     def description(self, key='hanningsmooth', subkey=None):
00296         desc={'hanningsmooth': 'Hanning smooth frequency channel data to remove Gibbs ringing',
00297                'vis': 'Name of input visibility file (MS)',
00298                'datacolumn': 'the name of the MS column into which to write the smoothed data',
00299                'outputvis': 'name of the output visibility file (MS)',
00300 
00301                'async': 'If true the taskname must be started using hanningsmooth(...)'
00302               }
00303 
00304         if(desc.has_key(key)) :
00305            return desc[key]
00306 
00307     def itsdefault(self, paramname) :
00308         a = {}
00309         a['vis']  = ''
00310         a['datacolumn']  = 'all'
00311         a['outputvis']  = ''
00312 
00313         #a = sys._getframe(len(inspect.stack())-1).f_globals
00314 
00315         if a.has_key(paramname) :
00316               return a[paramname]
00317 hanningsmooth_cli = hanningsmooth_cli_()