casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdsmooth_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_sdsmooth import sdsmooth
00018 class sdsmooth_cli_:
00019     __name__ = "sdsmooth"
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__ = (sdsmooth_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'antenna':None, 'scanaverage':None, 'scanlist':None, 'field':None, 'iflist':None, 'pollist':None, 'kernel':None, 'kwidth':None, 'chanwidth':None, 'verify':None, 'outfile':None, 'outform':None, 'overwrite':None, 'plotlevel':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, infile=None, antenna=None, scanaverage=None, scanlist=None, field=None, iflist=None, pollist=None, kernel=None, kwidth=None, chanwidth=None, verify=None, outfile=None, outform=None, overwrite=None, plotlevel=None,  async=None):
00047 
00048         """ASAP SD task: do smoothing of spectra
00049 
00050         Keyword arguments:
00051         infile -- name of input SD dataset
00052         antenna -- antenna name or id (only effective for MS input). 
00053         scanaverage -- average integrations within scans
00054                 options: (bool) True,False
00055                 default: False
00056                 example: if True, this happens in read-in
00057                          For GBT, set False!
00058         scanlist -- list of scan numbers to process
00059                 default: [] (use all scans)
00060                 example: [21,22,23,24]
00061                 this selection is in addition to field, iflist, and pollist
00062         field -- selection string for selecting scans by name
00063                 default: '' (no name selection)
00064                 example: 'FLS3a*'
00065                 this selection is in addition to scanlist, iflist,pollist
00066         iflist -- list of IF id numbers to select
00067                 default: [] (use all IFs)
00068                 example: [15]
00069                 this selection is in addition to scanlist, field, and pollist
00070         pollist -- list of polarization id numbers to select
00071                 default: [] (use all polarizations)
00072                 example: [1]
00073                 this selection is in addition to scanlist, field, and iflist
00074         kernel -- type of spectral smoothing
00075                 options: 'hanning','gaussian','boxcar','regrid'
00076                 default: 'hanning'
00077 
00078             >>>kernel expandable parameter
00079                  kwidth -- width of spectral smoothing kernel
00080                          options: (int) in channels 
00081                          default: 5
00082                          example: 5 or 10 seem to be popular for boxcar
00083                                   ignored for hanning (fixed at 5 chans)
00084                                   (0 will turn off gaussian or boxcar)
00085                  chanwidth -- channel width of regridded spectra
00086                          default: '5' (in channels)
00087                          example: '500MHz', '0.2km/s'
00088 
00089         verify -- verify the results of smoothing
00090                 options: (bool) True,False
00091                 default: False
00092                 WARNING: Currently this just asks whether you accept
00093                          the displayed smoothing and if not, continues
00094                          without smoothing.
00095                 Note: verification is not yet available for kernel='regrid'
00096         outfile -- Name of output ASAP format(scantable) file
00097                 default: '' (<infile>_sm)
00098         outform -- format of output file
00099                 options: 'ASCII','SDFITS','MS','ASAP'
00100                 default: 'ASAP'
00101                 example: the ASAP format is easiest for further sd
00102                          processing; use MS for CASA imaging.
00103                          If ASCII, then will append some stuff to
00104                          the outfile name
00105         overwrite -- overwrite the output file if already exists
00106                 options: (bool) True,False
00107                 default: False
00108                 WARNING: if outform='ASCII', this parameter is ignored
00109         plotlevel -- control for plotting of results
00110                 options: (int) 0=none, 1=some, 2=more, <0=hardcopy
00111                 default: 0 (no plotting)
00112                 example: plotlevel<0 as abs(plotlevel), e.g.
00113                          -1 => hardcopy of final plot (will be named
00114                          <outfile>_smspec.eps)
00115 
00116 
00117         DESCRIPTION:
00118 
00119         Task sdsmooth performs smoothing of the single-dish spectra.
00120         Set plotlevel >= 1 to plot spectrum before and after smoothing.
00121 
00122         WARNING for the GBT raw SDFITS format data as input:
00123         SDtasks are able to handle GBT raw SDFITS format data since the 
00124         data filler is available. However, the functionality is not well 
00125         tested yet, so that there may be unknown bugs.  
00126 
00127   
00128         """
00129         if not hasattr(self, "__globals__") or self.__globals__ == None :
00130            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00131         #casac = self.__globals__['casac']
00132         casalog = self.__globals__['casalog']
00133         #casalog = casac.casac.logsink()
00134         self.__globals__['__last_task'] = 'sdsmooth'
00135         self.__globals__['taskname'] = 'sdsmooth'
00136         ###
00137         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00138         ###
00139         ###
00140         #Handle globals or user over-ride of arguments
00141         #
00142         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00143         useLocalDefaults = False
00144 
00145         for item in function_signature_defaults.iteritems():
00146                 key,val = item
00147                 keyVal = eval(key)
00148                 if (keyVal == None):
00149                         #user hasn't set it - use global/default
00150                         pass
00151                 else:
00152                         #user has set it - use over-ride
00153                         if (key != 'self') :
00154                            useLocalDefaults = True
00155 
00156         myparams = {}
00157         if useLocalDefaults :
00158            for item in function_signature_defaults.iteritems():
00159                key,val = item
00160                keyVal = eval(key)
00161                exec('myparams[key] = keyVal')
00162                self.parameters[key] = keyVal
00163                if (keyVal == None):
00164                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00165                    keyVal = eval(key)
00166                    if(type(keyVal) == dict) :
00167                       if len(keyVal) > 0 :
00168                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00169                       else :
00170                          exec('myparams[key] = ' + key + ' = {}')
00171 
00172         else :
00173             async = self.parameters['async']
00174             myparams['infile'] = infile = self.parameters['infile']
00175             myparams['antenna'] = antenna = self.parameters['antenna']
00176             myparams['scanaverage'] = scanaverage = self.parameters['scanaverage']
00177             myparams['scanlist'] = scanlist = self.parameters['scanlist']
00178             myparams['field'] = field = self.parameters['field']
00179             myparams['iflist'] = iflist = self.parameters['iflist']
00180             myparams['pollist'] = pollist = self.parameters['pollist']
00181             myparams['kernel'] = kernel = self.parameters['kernel']
00182             myparams['kwidth'] = kwidth = self.parameters['kwidth']
00183             myparams['chanwidth'] = chanwidth = self.parameters['chanwidth']
00184             myparams['verify'] = verify = self.parameters['verify']
00185             myparams['outfile'] = outfile = self.parameters['outfile']
00186             myparams['outform'] = outform = self.parameters['outform']
00187             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00188             myparams['plotlevel'] = plotlevel = self.parameters['plotlevel']
00189 
00190         if type(scanlist)==int: scanlist=[scanlist]
00191         if type(iflist)==int: iflist=[iflist]
00192         if type(pollist)==int: pollist=[pollist]
00193 
00194         result = None
00195 
00196 #
00197 #    The following is work around to avoid a bug with current python translation
00198 #
00199         mytmp = {}
00200 
00201         mytmp['infile'] = infile
00202         mytmp['antenna'] = antenna
00203         mytmp['scanaverage'] = scanaverage
00204         mytmp['scanlist'] = scanlist
00205         mytmp['field'] = field
00206         mytmp['iflist'] = iflist
00207         mytmp['pollist'] = pollist
00208         mytmp['kernel'] = kernel
00209         mytmp['kwidth'] = kwidth
00210         mytmp['chanwidth'] = chanwidth
00211         mytmp['verify'] = verify
00212         mytmp['outfile'] = outfile
00213         mytmp['outform'] = outform
00214         mytmp['overwrite'] = overwrite
00215         mytmp['plotlevel'] = plotlevel
00216         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00217         trec = casac.casac.utils().torecord(pathname+'sdsmooth.xml')
00218 
00219         casalog.origin('sdsmooth')
00220         try :
00221           #if not trec.has_key('sdsmooth') or not casac.casac.utils().verify(mytmp, trec['sdsmooth']) :
00222             #return False
00223 
00224           casac.casac.utils().verify(mytmp, trec['sdsmooth'], True)
00225           scriptstr=['']
00226           saveinputs = self.__globals__['saveinputs']
00227           saveinputs('sdsmooth', 'sdsmooth.last', myparams, self.__globals__,scriptstr=scriptstr)
00228           if async :
00229             count = 0
00230             keybase =  time.strftime("%y%m%d.%H%M%S")
00231             key = keybase + "_" + str(count)
00232             while self.__async__.has_key(key) :
00233                count += 1
00234                key = keybase + "_" + str(count)
00235             result = tm.execute('sdsmooth', infile, antenna, scanaverage, scanlist, field, iflist, pollist, kernel, kwidth, chanwidth, verify, outfile, outform, overwrite, plotlevel)
00236             print "Use: "
00237             print "      tm.retrieve(return_value) # to retrieve the status"
00238             print 
00239             self.rkey = key
00240             self.__async__[key] = result
00241           else :
00242               tname = 'sdsmooth'
00243               spaces = ' '*(18-len(tname))
00244               casalog.post('\n##########################################'+
00245                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00246               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00247               result = sdsmooth(infile, antenna, scanaverage, scanlist, field, iflist, pollist, kernel, kwidth, chanwidth, verify, outfile, outform, overwrite, plotlevel)
00248               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00249                            '\n##########################################')
00250 
00251         except Exception, instance:
00252           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00253              raise
00254           else :
00255              #print '**** Error **** ',instance
00256              tname = 'sdsmooth'
00257              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00258              pass
00259 
00260         gc.collect()
00261         return result
00262 #
00263 #
00264 #
00265     def paramgui(self, useGlobals=True, ipython_globals=None):
00266         """
00267         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00268         """
00269         import paramgui
00270         if not hasattr(self, "__globals__") or self.__globals__ == None :
00271            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00272 
00273         if useGlobals:
00274             if ipython_globals == None:
00275                 myf=self.__globals__
00276             else:
00277                 myf=ipython_globals
00278 
00279             paramgui.setGlobals(myf)
00280         else:
00281             paramgui.setGlobals({})
00282 
00283         paramgui.runTask('sdsmooth', myf['_ip'])
00284         paramgui.setGlobals({})
00285 
00286 #
00287 #
00288 #
00289     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00290         if not hasattr(self, "__globals__") or self.__globals__ == None :
00291            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00292         if ipython_globals == None:
00293             myf=self.__globals__
00294         else:
00295             myf=ipython_globals
00296 
00297         a = odict()
00298         a['infile']  = ''
00299         a['antenna']  = 0
00300         a['scanaverage']  = False
00301         a['scanlist']  = []
00302         a['field']  = ''
00303         a['iflist']  = []
00304         a['pollist']  = []
00305         a['kernel']  = 'hanning'
00306         a['verify']  = False
00307         a['outfile']  = ''
00308         a['outform']  = 'ASAP'
00309         a['overwrite']  = False
00310         a['plotlevel']  = 0
00311 
00312         a['async']=False
00313         a['kernel'] = {
00314                     0:{'value':'hanning'}, 
00315                     1:odict([{'value':'gaussian'}, {'kwidth':5}]), 
00316                     2:odict([{'value':'boxcar'}, {'kwidth':5}]), 
00317                     3:odict([{'value':'regrid'}, {'chanwidth':'5'}])}
00318 
00319 ### This function sets the default values but also will return the list of
00320 ### parameters or the default value of a given parameter
00321         if(param == None):
00322                 myf['__set_default_parameters'](a)
00323         elif(param == 'paramkeys'):
00324                 return a.keys()
00325         else:
00326             if(paramvalue==None and subparam==None):
00327                if(a.has_key(param)):
00328                   return a[param]
00329                else:
00330                   return self.itsdefault(param)
00331             else:
00332                retval=a[param]
00333                if(type(a[param])==dict):
00334                   for k in range(len(a[param])):
00335                      valornotval='value'
00336                      if(a[param][k].has_key('notvalue')):
00337                         valornotval='notvalue'
00338                      if((a[param][k][valornotval])==paramvalue):
00339                         retval=a[param][k].copy()
00340                         retval.pop(valornotval)
00341                         if(subparam != None):
00342                            if(retval.has_key(subparam)):
00343                               retval=retval[subparam]
00344                            else:
00345                               retval=self.itsdefault(subparam)
00346                      else:
00347                         retval=self.itsdefault(subparam)
00348                return retval
00349 
00350 
00351 #
00352 #
00353     def check_params(self, param=None, value=None, ipython_globals=None):
00354       if ipython_globals == None:
00355           myf=self.__globals__
00356       else:
00357           myf=ipython_globals
00358 #      print 'param:', param, 'value:', value
00359       try :
00360          if str(type(value)) != "<type 'instance'>" :
00361             value0 = value
00362             value = myf['cu'].expandparam(param, value)
00363             matchtype = False
00364             if(type(value) == numpy.ndarray):
00365                if(type(value) == type(value0)):
00366                   myf[param] = value.tolist()
00367                else:
00368                   #print 'value:', value, 'value0:', value0
00369                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00370                   myf[param] = value0
00371                   if type(value0) != list :
00372                      matchtype = True
00373             else :
00374                myf[param] = value
00375             value = myf['cu'].verifyparam({param:value})
00376             if matchtype:
00377                value = False
00378       except Exception, instance:
00379          #ignore the exception and just return it unchecked
00380          myf[param] = value
00381       return value
00382 #
00383 #
00384     def description(self, key='sdsmooth', subkey=None):
00385         desc={'sdsmooth': 'ASAP SD task: do smoothing of spectra',
00386                'infile': 'name of input SD dataset',
00387                'antenna': 'antenna name or id (only effective for MS input)',
00388                'scanaverage': 'average integs within scans (True,False) ',
00389                'scanlist': 'list of scans to use (e.g. [1,2,3,4])',
00390                'field': 'string for selection by source name',
00391                'iflist': 'list of IF ids to select (e.g. [0,1])',
00392                'pollist': 'list of polarization ids to select (e.g. [0,1])',
00393                'kernel': 'type of spectral smoothing',
00394                'kwidth': 'width of spectral kernel in channels',
00395                'chanwidth': 'width of regridded channels',
00396                'verify': 'verify the results of smoothing [not available for kernel="regrid"]',
00397                'outfile': 'output file name',
00398                'outform': 'output file format (ASCII,MS,SDFITS,ASAP)',
00399                'overwrite': 'overwrite the output file if already exists',
00400                'plotlevel': 'plot results (0=none,1+=some,<0=hardcopy)',
00401 
00402                'async': 'If true the taskname must be started using sdsmooth(...)'
00403               }
00404 
00405 #
00406 # Set subfields defaults if needed
00407 #
00408 
00409         if(desc.has_key(key)) :
00410            return desc[key]
00411 
00412     def itsdefault(self, paramname) :
00413         a = {}
00414         a['infile']  = ''
00415         a['antenna']  = 0
00416         a['scanaverage']  = False
00417         a['scanlist']  = []
00418         a['field']  = ''
00419         a['iflist']  = []
00420         a['pollist']  = []
00421         a['kernel']  = 'hanning'
00422         a['kwidth']  = 5
00423         a['chanwidth']  = '5'
00424         a['verify']  = False
00425         a['outfile']  = ''
00426         a['outform']  = 'ASAP'
00427         a['overwrite']  = False
00428         a['plotlevel']  = 0
00429 
00430         #a = sys._getframe(len(inspect.stack())-1).f_globals
00431 
00432         if self.parameters['kernel']  == 'gaussian':
00433             a['kwidth'] = 5
00434 
00435         if self.parameters['kernel']  == 'boxcar':
00436             a['kwidth'] = 5
00437 
00438         if self.parameters['kernel']  == 'regrid':
00439             a['chanwidth'] = '5'
00440 
00441         if a.has_key(paramname) :
00442               return a[paramname]
00443 sdsmooth_cli = sdsmooth_cli_()