casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
sdbaseline_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_sdbaseline import sdbaseline
00018 class sdbaseline_cli_:
00019     __name__ = "sdbaseline"
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__ = (sdbaseline_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'antenna':None, 'fluxunit':None, 'telescopeparm':None, 'specunit':None, 'restfreq':None, 'frame':None, 'doppler':None, 'scanlist':None, 'field':None, 'iflist':None, 'pollist':None, 'tau':None, 'masklist':None, 'maskmode':None, 'thresh':None, 'avg_limit':None, 'edge':None, 'blfunc':None, 'order':None, 'npiece':None, 'applyfft':None, 'fftmethod':None, 'fftthresh':None, 'addwn':None, 'rejwn':None, 'clipthresh':None, 'clipniter':None, 'verify':None, 'verbose':None, 'bloutput':None, 'blformat':None, 'showprogress':None, 'minnrow':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, fluxunit=None, telescopeparm=None, specunit=None, restfreq=None, frame=None, doppler=None, scanlist=None, field=None, iflist=None, pollist=None, tau=None, masklist=None, maskmode=None, thresh=None, avg_limit=None, edge=None, blfunc=None, order=None, npiece=None, applyfft=None, fftmethod=None, fftthresh=None, addwn=None, rejwn=None, clipthresh=None, clipniter=None, verify=None, verbose=None, bloutput=None, blformat=None, showprogress=None, minnrow=None, outfile=None, outform=None, overwrite=None, plotlevel=None,  async=None):
00047 
00048         """ASAP SD task: fit/subtract a spectral baseline 
00049         Keyword arguments:
00050         infile -- name of input SD dataset
00051         antenna -- antenna name or id (only effective for MS input). 
00052         fluxunit -- units for line flux
00053                 options: 'K','Jy',''
00054                 default: '' (keep current fluxunit)
00055                 WARNING: For GBT data, see description below.
00056             >>> fluxunit expandable parameter
00057                  telescopeparm -- the telescope characteristics
00058                         options: (str) name or (list) list of gain info
00059                         default: '' (none set)
00060                         example: if telescopeparm='', it tries to get the telescope
00061                                  name from the data.
00062                                  Full antenna parameters (diameter,ap.eff.) known
00063                                  to ASAP are
00064                                  'ATPKSMB', 'ATPKSHOH', 'ATMOPRA', 'DSS-43',
00065                                  'CEDUNA','HOBART'. For GBT, it fixes default fluxunit
00066                                  to 'K' first then convert to a new fluxunit.
00067                                  telescopeparm=[104.9,0.43] diameter(m), ap.eff.
00068                                  telescopeparm=[0.743] gain in Jy/K
00069                                  telescopeparm='FIX' to change default fluxunit
00070                                  see description below
00071         specunit -- units for spectral axis
00072                 options: (str) 'channel','km/s','GHz','MHz','kHz','Hz',''
00073                 default: '' (=current)
00074                 example: this will be the units for masklist
00075             >>> specunit expandable parameters
00076                  restfreq -- rest frequency
00077                          available type includes float, int, string, list of float, 
00078                          list of int, list of string, and list of dictionary. the 
00079                          default unit of restfreq in case of float, int, or string 
00080                          without unit is Hz. string input can be a value only 
00081                          (treated as Hz) or a value followed by unit for which 'GHz',
00082                          'MHz','kHz',and 'Hz' are available. 
00083                          a list can be used to set different rest frequencies for 
00084                          each IF. the length of list input must be nIF. dictionary 
00085                          input should be a pair of molecule name and frequency with 
00086                          keys of 'name' and 'value', respectively. values in the 
00087                          dictionary input follows the same manner as for single 
00088                          float or string input. 
00089                          example: 345.796
00090                                   '1420MHz'
00091                                   [345.8, 347.0, 356.7]
00092                                   ['345.8MHz', '347.0MHz', '356.7MHz']
00093                                   [{'name':'CO','value':345}]
00094         frame -- frequency frame for spectral axis
00095                 options: (str) 'LSRK','REST','TOPO','LSRD','BARY',
00096                          'GEO','GALACTO','LGROUP','CMB'
00097                 default: currently set frame in scantable
00098                 WARNING: frame='REST' not yet implemented
00099         doppler -- doppler mode
00100                 options: (str) 'RADIO','OPTICAL','Z','BETA','GAMMA'
00101                 default: currently set doppler in scantable
00102         scanlist -- list of scan numbers to process
00103                 default: [] (use all scans)
00104                 example: [21,22,23,24]
00105                 this selection is in addition to field, iflist, and pollist
00106         field -- selection string for selecting scans by name
00107                 default: '' (no name selection)
00108                 example: 'FLS3a*'
00109                 this selection is in addition to scanlist, iflist, and pollist
00110         iflist -- list of IF id numbers to select
00111                 default: [] (use all IFs)
00112                 example: [15]
00113                 this selection is in addition to scanlist, field, and pollist
00114         pollist -- list of polarization id numbers to select
00115                 default: [] (use all polarizations)
00116                 example: [1]
00117                 this selection is in addition to scanlist, field, and iflist
00118         tau -- atmospheric optical depth
00119                 default: 0.0 (no correction)
00120         masklist -- list or string of mask regions to INCLUDE in BASELINE fit
00121                     a string masklist allows per IF selection of channels.
00122                 default: [] (entire spectrum)
00123                 example: [[1000,3000],[5000,7000]]
00124                          '0:1000~3000;5000~7000, 1:200~350;450~600'
00125                          when maskmode is 'auto' or 'interact', this mask 
00126                          will be applied first before fitting as base mask
00127         maskmode -- mode of setting additional channel masks
00128                 options: (str) 'auto','list','interact'
00129                 default: 'auto'
00130                 example: maskmode='auto' runs linefinder to detect line regions 
00131                          to be excluded from fitting. this mode requires three 
00132                          expandable parameters: thresh, avg_limit, and edge.
00133                          USE WITH CARE! May need to tweak the expandable parameters.
00134                          maskmode='list' uses the given masklist only: no additional 
00135                          masks applied.
00136                          maskmode='interact' allows users to manually modify the 
00137                          mask regions by dragging mouse on the spectrum plotter GUI.
00138                          use LEFT or RIGHT button to add or delete regions, 
00139                          respectively.
00140                
00141             >>> maskmode expandable parameters
00142                  thresh -- S/N threshold for linefinder
00143                          default: 5
00144                          example: a single channel S/N ratio above which the channel is
00145                                   considered to be a detection
00146                  avg_limit -- channel averaging for broad lines
00147                          default: 4
00148                          example: a number of consecutive channels not greater than
00149                                   this parameter can be averaged to search for broad lines
00150                  edge -- channels to drop at beginning and end of spectrum
00151                          default: 0
00152                          example: [1000] drops 1000 channels at beginning AND end
00153                                   [1000,500] drops 1000 from beginning and 500 from end
00154                  Note: For bad baselines threshold should be increased,
00155                  and avg_limit decreased (or even switched off completely by
00156                  setting this parameter to 1) to avoid detecting baseline
00157                  undulations instead of real lines.
00158         blfunc -- baseline model function
00159                 options: (str) 'poly','chebyshev','cspline','sinusoid'
00160                 default: 'poly'
00161                 example: blfunc='poly' uses a single polynomial line of 
00162                          any order which should be given as an expandable 
00163                          parameter 'order' to fit baseline. 
00164                          blfunc='chebyshev' uses Chebyshev polynomials. 
00165                          blfunc='cspline' uses a cubic spline function, a piecewise 
00166                          cubic polynomial having C2-continuity (i.e., the second 
00167                          derivative is continuous at the joining points). 
00168                          blfunc='sinusoid' uses a combination of sinusoidal curves. 
00169             >>> blfunc expandable parameters
00170                  order -- order of baseline polynomial
00171                          options: (int) (<0 turns off baseline fitting)
00172                          default: 5
00173                          example: typically in range 2-9 (higher values
00174                                   seem to be needed for GBT)
00175                  npiece -- number of the element polynomials of cubic spline curve
00176                          options: (int) (<0 turns off baseline fitting)
00177                          default: 2
00178                  applyfft -- automatically set wave numbers of sinusoidal functions 
00179                          for fitting by applying some method like FFT.
00180                          options: (bool) True, False
00181                          default: True
00182                  fftmethod -- method to be used when applyfft=True. Now only 
00183                          'fft' is available and it is the default.
00184                  fftthresh -- threshold to select wave numbers to be used for 
00185                          sinusoidal fitting. both (float) and (str) accepted.
00186                          given a float value, the unit is set to sigma.
00187                          for string values, allowed formats include:
00188                            'xsigma' or 'x' (= x-sigma level. e.g., '3sigma'), or
00189                            'topx' (= the x strongest ones, e.g. 'top5').
00190                          default is 3.0 (unit: sigma).
00191                  addwn -- additional wave number(s) of sinusoids to be used 
00192                          for fitting. 
00193                          (list) and (int) are accepted to specify every
00194                          wave numbers. also (str) can be used in case
00195                          you need to specify wave numbers in a certain range,
00196                          e.g., 'a-b' (= a, a+1, a+2, ..., b-1, b),
00197                                '<a'  (= 0,1,...,a-2,a-1),
00198                                '>=a' (= a, a+1, ... up to the maximum wave
00199                                       number corresponding to the Nyquist
00200                                       frequency for the case of FFT).
00201                          default: [0] (i.e., constant is subtracted at least)
00202                  rejwn -- wave number(s) of sinusoid NOT to be used for fitting.
00203                          can be set just as addwn but has higher priority:
00204                          wave numbers which are specified both in addwn
00205                          and rejwn will NOT be used. 
00206                          default: []
00207                  clipthresh -- clipping threshold for iterative fitting
00208                          default: 3
00209                  clipniter -- maximum iteration number
00210                          default: 0 (no iteration, i.e., no clipping)
00211         verify -- verify the results of baseline fitting
00212                 options: (bool) True,False
00213                 default: False
00214                 NOTE: Currently available only when blfunc='poly'
00215                 WARNING: Currently this just asks whether you accept
00216                          the displayed fit and if not, continues
00217                          without doing any baseline fit.
00218         verbose -- output fitting results to logger
00219                 default: True
00220                 example: If False, the fitting results including coefficients, 
00221                          residual rms, etc., are not output to the CASA logger, 
00222                          while the processing speed gets faster
00223         bloutput -- output fitting results to a text file
00224                 default: True
00225                 example: If False, the fitting results including coefficients, 
00226                          residual rms, etc., are not output to a text file 
00227                          (<outfile>_blparam.txt), while the processing 
00228                          speed gets faster
00229         blformat -- format of the logger output and text file specified with bloutput
00230                 options: '', 'csv'
00231                 default: '' (same as in the past, easy to read but huge)
00232         showprogress -- show progress status for large data
00233                 default: True
00234         minnrow -- minimum number of input spectra to show progress status
00235                 default: 1000
00236         outfile -- Name of output file
00237                 default: '' (<infile>_bs)
00238         outform -- format of output file
00239                 options: 'ASCII','SDFITS','MS','ASAP'
00240                 default: 'ASAP'
00241                 example: the ASAP format is easiest for further sd
00242                          processing; use MS for CASA imaging.
00243                          If ASCII, then will append some stuff to
00244                          the outfile name
00245         overwrite -- overwrite the output file if already exists
00246                 options: (bool) True,False
00247                 default: False
00248                 WARNING: if outform='ASCII', this parameter is ignored
00249         plotlevel -- control for plotting of results
00250                 options: (int) 0=none, 1=some, 2=more, <0=hardcopy
00251                 default: 0 (no plotting)
00252                 example: plotlevel<0 as abs(plotlevel), e.g.
00253                          -1 => hardcopy of final plot (will be named
00254                         <outfile>_bspec.eps)
00255                 WARNING: be careful plotting in fsotf mode!
00256 
00257 
00258 
00259         DESCRIPTION:
00260 
00261         Task sdbaseline performs baseline fitting/removal for single-dish spectra.
00262         The fit parameters, terms and rms of base-line are saved to an ascii 
00263         file, '<outfile>_blparam.txt'. 
00264 
00265         ASAP recognizes the data of the "AT" telescopes, but currently
00266         does not know about the GBT or any other telescope. This task
00267         does know about GBT. Telescope name is obtained from the data.
00268         If you wish to change the fluxunit (see below), and telescopeparm='',
00269         for the AT telescopes it will use internal telescope parameters for
00270         flux conversion. For GBT, it will use an approximate aperture
00271         efficiency conversion.  If you give telescopeparm a list , 
00272         then if the list has a single float it is assumed to
00273         be the gain in Jy/K, if two or more elements they are assumed
00274         to be telescope diameter (m) and aperture efficiency
00275         respectively.
00276 
00277         Note that sdbaseline assumes that the fluxunit is set correctly in
00278         the data already.  If not, then set telescopeparm='FIX' and it
00279         will set the default units to fluxunit without conversion.
00280         NOTE: If the data in infile is an ms from GBT and the default flux
00281         unit is missing and this task automatically fixes the default fluxunit
00282         to 'K' before the conversion.
00283 
00284         WARNING for the GBT raw SDFITS format data as input:
00285         SDtasks are able to handle GBT raw SDFITS format data since the 
00286         data filler is available. However, the functionality is not well 
00287         tested yet, so that there may be unknown bugs.         
00288 
00289   
00290         """
00291         if not hasattr(self, "__globals__") or self.__globals__ == None :
00292            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00293         #casac = self.__globals__['casac']
00294         casalog = self.__globals__['casalog']
00295         #casalog = casac.casac.logsink()
00296         self.__globals__['__last_task'] = 'sdbaseline'
00297         self.__globals__['taskname'] = 'sdbaseline'
00298         ###
00299         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00300         ###
00301         ###
00302         #Handle globals or user over-ride of arguments
00303         #
00304         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00305         useLocalDefaults = False
00306 
00307         for item in function_signature_defaults.iteritems():
00308                 key,val = item
00309                 keyVal = eval(key)
00310                 if (keyVal == None):
00311                         #user hasn't set it - use global/default
00312                         pass
00313                 else:
00314                         #user has set it - use over-ride
00315                         if (key != 'self') :
00316                            useLocalDefaults = True
00317 
00318         myparams = {}
00319         if useLocalDefaults :
00320            for item in function_signature_defaults.iteritems():
00321                key,val = item
00322                keyVal = eval(key)
00323                exec('myparams[key] = keyVal')
00324                self.parameters[key] = keyVal
00325                if (keyVal == None):
00326                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00327                    keyVal = eval(key)
00328                    if(type(keyVal) == dict) :
00329                       if len(keyVal) > 0 :
00330                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00331                       else :
00332                          exec('myparams[key] = ' + key + ' = {}')
00333 
00334         else :
00335             async = self.parameters['async']
00336             myparams['infile'] = infile = self.parameters['infile']
00337             myparams['antenna'] = antenna = self.parameters['antenna']
00338             myparams['fluxunit'] = fluxunit = self.parameters['fluxunit']
00339             myparams['telescopeparm'] = telescopeparm = self.parameters['telescopeparm']
00340             myparams['specunit'] = specunit = self.parameters['specunit']
00341             myparams['restfreq'] = restfreq = self.parameters['restfreq']
00342             myparams['frame'] = frame = self.parameters['frame']
00343             myparams['doppler'] = doppler = self.parameters['doppler']
00344             myparams['scanlist'] = scanlist = self.parameters['scanlist']
00345             myparams['field'] = field = self.parameters['field']
00346             myparams['iflist'] = iflist = self.parameters['iflist']
00347             myparams['pollist'] = pollist = self.parameters['pollist']
00348             myparams['tau'] = tau = self.parameters['tau']
00349             myparams['masklist'] = masklist = self.parameters['masklist']
00350             myparams['maskmode'] = maskmode = self.parameters['maskmode']
00351             myparams['thresh'] = thresh = self.parameters['thresh']
00352             myparams['avg_limit'] = avg_limit = self.parameters['avg_limit']
00353             myparams['edge'] = edge = self.parameters['edge']
00354             myparams['blfunc'] = blfunc = self.parameters['blfunc']
00355             myparams['order'] = order = self.parameters['order']
00356             myparams['npiece'] = npiece = self.parameters['npiece']
00357             myparams['applyfft'] = applyfft = self.parameters['applyfft']
00358             myparams['fftmethod'] = fftmethod = self.parameters['fftmethod']
00359             myparams['fftthresh'] = fftthresh = self.parameters['fftthresh']
00360             myparams['addwn'] = addwn = self.parameters['addwn']
00361             myparams['rejwn'] = rejwn = self.parameters['rejwn']
00362             myparams['clipthresh'] = clipthresh = self.parameters['clipthresh']
00363             myparams['clipniter'] = clipniter = self.parameters['clipniter']
00364             myparams['verify'] = verify = self.parameters['verify']
00365             myparams['verbose'] = verbose = self.parameters['verbose']
00366             myparams['bloutput'] = bloutput = self.parameters['bloutput']
00367             myparams['blformat'] = blformat = self.parameters['blformat']
00368             myparams['showprogress'] = showprogress = self.parameters['showprogress']
00369             myparams['minnrow'] = minnrow = self.parameters['minnrow']
00370             myparams['outfile'] = outfile = self.parameters['outfile']
00371             myparams['outform'] = outform = self.parameters['outform']
00372             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00373             myparams['plotlevel'] = plotlevel = self.parameters['plotlevel']
00374 
00375         if type(scanlist)==int: scanlist=[scanlist]
00376         if type(iflist)==int: iflist=[iflist]
00377         if type(pollist)==int: pollist=[pollist]
00378         if type(edge)==int: edge=[edge]
00379 
00380         result = None
00381 
00382 #
00383 #    The following is work around to avoid a bug with current python translation
00384 #
00385         mytmp = {}
00386 
00387         mytmp['infile'] = infile
00388         mytmp['antenna'] = antenna
00389         mytmp['fluxunit'] = fluxunit
00390         mytmp['telescopeparm'] = telescopeparm
00391         mytmp['specunit'] = specunit
00392         mytmp['restfreq'] = restfreq
00393         mytmp['frame'] = frame
00394         mytmp['doppler'] = doppler
00395         mytmp['scanlist'] = scanlist
00396         mytmp['field'] = field
00397         mytmp['iflist'] = iflist
00398         mytmp['pollist'] = pollist
00399         mytmp['tau'] = tau
00400         mytmp['masklist'] = masklist
00401         mytmp['maskmode'] = maskmode
00402         mytmp['thresh'] = thresh
00403         mytmp['avg_limit'] = avg_limit
00404         mytmp['edge'] = edge
00405         mytmp['blfunc'] = blfunc
00406         mytmp['order'] = order
00407         mytmp['npiece'] = npiece
00408         mytmp['applyfft'] = applyfft
00409         mytmp['fftmethod'] = fftmethod
00410         mytmp['fftthresh'] = fftthresh
00411         mytmp['addwn'] = addwn
00412         mytmp['rejwn'] = rejwn
00413         mytmp['clipthresh'] = clipthresh
00414         mytmp['clipniter'] = clipniter
00415         mytmp['verify'] = verify
00416         mytmp['verbose'] = verbose
00417         mytmp['bloutput'] = bloutput
00418         mytmp['blformat'] = blformat
00419         mytmp['showprogress'] = showprogress
00420         mytmp['minnrow'] = minnrow
00421         mytmp['outfile'] = outfile
00422         mytmp['outform'] = outform
00423         mytmp['overwrite'] = overwrite
00424         mytmp['plotlevel'] = plotlevel
00425         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00426         trec = casac.casac.utils().torecord(pathname+'sdbaseline.xml')
00427 
00428         casalog.origin('sdbaseline')
00429         try :
00430           #if not trec.has_key('sdbaseline') or not casac.casac.utils().verify(mytmp, trec['sdbaseline']) :
00431             #return False
00432 
00433           casac.casac.utils().verify(mytmp, trec['sdbaseline'], True)
00434           scriptstr=['']
00435           saveinputs = self.__globals__['saveinputs']
00436           saveinputs('sdbaseline', 'sdbaseline.last', myparams, self.__globals__,scriptstr=scriptstr)
00437           if async :
00438             count = 0
00439             keybase =  time.strftime("%y%m%d.%H%M%S")
00440             key = keybase + "_" + str(count)
00441             while self.__async__.has_key(key) :
00442                count += 1
00443                key = keybase + "_" + str(count)
00444             result = tm.execute('sdbaseline', infile, antenna, fluxunit, telescopeparm, specunit, restfreq, frame, doppler, scanlist, field, iflist, pollist, tau, masklist, maskmode, thresh, avg_limit, edge, blfunc, order, npiece, applyfft, fftmethod, fftthresh, addwn, rejwn, clipthresh, clipniter, verify, verbose, bloutput, blformat, showprogress, minnrow, outfile, outform, overwrite, plotlevel)
00445             print "Use: "
00446             print "      tm.retrieve(return_value) # to retrieve the status"
00447             print 
00448             self.rkey = key
00449             self.__async__[key] = result
00450           else :
00451               tname = 'sdbaseline'
00452               spaces = ' '*(18-len(tname))
00453               casalog.post('\n##########################################'+
00454                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00455               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00456               result = sdbaseline(infile, antenna, fluxunit, telescopeparm, specunit, restfreq, frame, doppler, scanlist, field, iflist, pollist, tau, masklist, maskmode, thresh, avg_limit, edge, blfunc, order, npiece, applyfft, fftmethod, fftthresh, addwn, rejwn, clipthresh, clipniter, verify, verbose, bloutput, blformat, showprogress, minnrow, outfile, outform, overwrite, plotlevel)
00457               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00458                            '\n##########################################')
00459 
00460         except Exception, instance:
00461           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00462              raise
00463           else :
00464              #print '**** Error **** ',instance
00465              tname = 'sdbaseline'
00466              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00467              pass
00468 
00469         gc.collect()
00470         return result
00471 #
00472 #
00473 #
00474     def paramgui(self, useGlobals=True, ipython_globals=None):
00475         """
00476         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00477         """
00478         import paramgui
00479         if not hasattr(self, "__globals__") or self.__globals__ == None :
00480            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00481 
00482         if useGlobals:
00483             if ipython_globals == None:
00484                 myf=self.__globals__
00485             else:
00486                 myf=ipython_globals
00487 
00488             paramgui.setGlobals(myf)
00489         else:
00490             paramgui.setGlobals({})
00491 
00492         paramgui.runTask('sdbaseline', myf['_ip'])
00493         paramgui.setGlobals({})
00494 
00495 #
00496 #
00497 #
00498     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00499         if not hasattr(self, "__globals__") or self.__globals__ == None :
00500            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00501         if ipython_globals == None:
00502             myf=self.__globals__
00503         else:
00504             myf=ipython_globals
00505 
00506         a = odict()
00507         a['infile']  = ''
00508         a['antenna']  = 0
00509         a['fluxunit']  = ''
00510         a['specunit']  = ''
00511         a['frame']  = ''
00512         a['doppler']  = ''
00513         a['scanlist']  = []
00514         a['field']  = ''
00515         a['iflist']  = []
00516         a['pollist']  = []
00517         a['tau']  = 0.0
00518         a['masklist']  = []
00519         a['maskmode']  = ''
00520         a['blfunc']  = 'poly'
00521         a['verify']  = False
00522         a['verbose']  = True
00523         a['bloutput']  = True
00524         a['blformat']  = ''
00525         a['showprogress']  = True
00526         a['outfile']  = ''
00527         a['outform']  = 'ASAP'
00528         a['overwrite']  = False
00529         a['plotlevel']  = 0
00530 
00531         a['async']=False
00532         a['fluxunit'] = {
00533                     0:{'value':''}, 
00534                     1:odict([{'value':'K'}, {'telescopeparm':''}]), 
00535                     2:odict([{'value':'k'}, {'telescopeparm':''}]), 
00536                     3:odict([{'value':'Jy'}, {'telescopeparm':''}]), 
00537                     4:odict([{'value':'jy'}, {'telescopeparm':''}])}
00538         a['specunit'] = {
00539                     0:{'value':''}, 
00540                     1:{'value':'channel'}, 
00541                     2:{'value':'GHz'}, 
00542                     3:{'value':'MHz'}, 
00543                     4:{'value':'kHz'}, 
00544                     5:{'value':'Hz'}, 
00545                     6:odict([{'value':'km/s'}, {'restfreq':''}])}
00546         a['maskmode'] = {
00547                     0:odict([{'value':'auto'}, {'thresh':5.0}, {'avg_limit':4}, {'edge':[0]}]), 
00548                     1:{'value':'list'}, 
00549                     2:{'value':'interact'}}
00550         a['blfunc'] = {
00551                     0:odict([{'value':'poly'}, {'order':5}]), 
00552                     1:odict([{'value':'chebyshev'}, {'order':5}, {'clipthresh':3.0}, {'clipniter':0}]), 
00553                     2:odict([{'value':'cspline'}, {'npiece':2}, {'clipthresh':3.0}, {'clipniter':0}]), 
00554                     3:odict([{'value':'sinusoid'}, {'applyfft':True}, {'fftmethod':'fft'}, {'fftthresh':3.0}, {'addwn':[0]}, {'rejwn':[]}, {'clipthresh':3.0}, {'clipniter':0}])}
00555         a['showprogress'] = {
00556                     0:odict([{'value':True}, {'minnrow':1000}])}
00557 
00558 ### This function sets the default values but also will return the list of
00559 ### parameters or the default value of a given parameter
00560         if(param == None):
00561                 myf['__set_default_parameters'](a)
00562         elif(param == 'paramkeys'):
00563                 return a.keys()
00564         else:
00565             if(paramvalue==None and subparam==None):
00566                if(a.has_key(param)):
00567                   return a[param]
00568                else:
00569                   return self.itsdefault(param)
00570             else:
00571                retval=a[param]
00572                if(type(a[param])==dict):
00573                   for k in range(len(a[param])):
00574                      valornotval='value'
00575                      if(a[param][k].has_key('notvalue')):
00576                         valornotval='notvalue'
00577                      if((a[param][k][valornotval])==paramvalue):
00578                         retval=a[param][k].copy()
00579                         retval.pop(valornotval)
00580                         if(subparam != None):
00581                            if(retval.has_key(subparam)):
00582                               retval=retval[subparam]
00583                            else:
00584                               retval=self.itsdefault(subparam)
00585                      else:
00586                         retval=self.itsdefault(subparam)
00587                return retval
00588 
00589 
00590 #
00591 #
00592     def check_params(self, param=None, value=None, ipython_globals=None):
00593       if ipython_globals == None:
00594           myf=self.__globals__
00595       else:
00596           myf=ipython_globals
00597 #      print 'param:', param, 'value:', value
00598       try :
00599          if str(type(value)) != "<type 'instance'>" :
00600             value0 = value
00601             value = myf['cu'].expandparam(param, value)
00602             matchtype = False
00603             if(type(value) == numpy.ndarray):
00604                if(type(value) == type(value0)):
00605                   myf[param] = value.tolist()
00606                else:
00607                   #print 'value:', value, 'value0:', value0
00608                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00609                   myf[param] = value0
00610                   if type(value0) != list :
00611                      matchtype = True
00612             else :
00613                myf[param] = value
00614             value = myf['cu'].verifyparam({param:value})
00615             if matchtype:
00616                value = False
00617       except Exception, instance:
00618          #ignore the exception and just return it unchecked
00619          myf[param] = value
00620       return value
00621 #
00622 #
00623     def description(self, key='sdbaseline', subkey=None):
00624         desc={'sdbaseline': 'ASAP SD task: fit/subtract a spectral baseline ',
00625                'infile': 'name of input SD dataset',
00626                'antenna': 'antenna name or id (only effective for MS input)',
00627                'fluxunit': 'units for line flux (K,Jy) (''=current)',
00628                'telescopeparm': 'param of telescope for flux conversion',
00629                'specunit': 'units for spectral axis (channel,km/s,GHz)',
00630                'restfreq': 'rest frequency (default unit: Hz)',
00631                'frame': 'frequency reference frame, e.g. LSRK (''=current)',
00632                'doppler': 'doppler convention, e.g. RADIO (''=current)',
00633                'scanlist': 'list of scans to use (e.g. [1,2,3,4])',
00634                'field': 'string for selection by source name',
00635                'iflist': 'list of IF ids to select (e.g. [0,1])',
00636                'pollist': 'list of polarization ids to select (e.g. [0,1])',
00637                'tau': 'atmospheric optical depth for correction',
00638                'masklist': 'list or string of mask regions to INCLUDE in BASELINE fit',
00639                'maskmode': 'mode of setting additional channel masks',
00640                'thresh': 'S/N threshold for linefinder',
00641                'avg_limit': 'channel averaging for broad lines',
00642                'edge': 'channels to drop at beginning and end of spectrum',
00643                'blfunc': 'baseline model function',
00644                'order': 'order of baseline polynomial',
00645                'npiece': 'number of element polynomials of spline',
00646                'applyfft': 'automatically set wave numbers of sinusoids',
00647                'fftmethod': 'method for automatically set wave numbers of sinusoids',
00648                'fftthresh': 'threshold to select wave numbers of sinusoids',
00649                'addwn': 'additional wave numbers to use',
00650                'rejwn': 'wave numbers NOT to use',
00651                'clipthresh': 'clipping threshold for iterative fitting',
00652                'clipniter': 'maximum iteration number',
00653                'verify': 'verify the results of baseline fitting (only for blfunc="poly")',
00654                'verbose': 'output fitting results to logger',
00655                'bloutput': 'output fitting results to a text file',
00656                'blformat': 'format of the text file specified with bloutput',
00657                'showprogress': 'show progress status for large data',
00658                'minnrow': 'minimum number of input spectra to show progress status',
00659                'outfile': 'output file name',
00660                'outform': 'output file format (ASCII,MS,SDFITS,ASAP)',
00661                'overwrite': 'overwrite the output file if already exists',
00662                'plotlevel': 'plot results (0=none,1+=some,<0=hardcopy)',
00663 
00664                'async': 'If true the taskname must be started using sdbaseline(...)'
00665               }
00666 
00667 #
00668 # Set subfields defaults if needed
00669 #
00670 
00671         if(desc.has_key(key)) :
00672            return desc[key]
00673 
00674     def itsdefault(self, paramname) :
00675         a = {}
00676         a['infile']  = ''
00677         a['antenna']  = 0
00678         a['fluxunit']  = ''
00679         a['telescopeparm']  = ''
00680         a['specunit']  = ''
00681         a['restfreq']  = ''
00682         a['frame']  = ''
00683         a['doppler']  = ''
00684         a['scanlist']  = []
00685         a['field']  = ''
00686         a['iflist']  = []
00687         a['pollist']  = []
00688         a['tau']  = 0.0
00689         a['masklist']  = []
00690         a['maskmode']  = ''
00691         a['thresh']  = 5.0
00692         a['avg_limit']  = 4
00693         a['edge']  = [0]
00694         a['blfunc']  = 'poly'
00695         a['order']  = 5
00696         a['npiece']  = 2
00697         a['applyfft']  = True
00698         a['fftmethod']  = 'fft'
00699         a['fftthresh']  = 3.0
00700         a['addwn']  = [0]
00701         a['rejwn']  = []
00702         a['clipthresh']  = 3.0
00703         a['clipniter']  = 0
00704         a['verify']  = False
00705         a['verbose']  = True
00706         a['bloutput']  = True
00707         a['blformat']  = ''
00708         a['showprogress']  = True
00709         a['minnrow']  = 1000
00710         a['outfile']  = ''
00711         a['outform']  = 'ASAP'
00712         a['overwrite']  = False
00713         a['plotlevel']  = 0
00714 
00715         #a = sys._getframe(len(inspect.stack())-1).f_globals
00716 
00717         if self.parameters['fluxunit']  == 'K':
00718             a['telescopeparm'] = ''
00719 
00720         if self.parameters['fluxunit']  == 'k':
00721             a['telescopeparm'] = ''
00722 
00723         if self.parameters['fluxunit']  == 'Jy':
00724             a['telescopeparm'] = ''
00725 
00726         if self.parameters['fluxunit']  == 'jy':
00727             a['telescopeparm'] = ''
00728 
00729         if self.parameters['specunit']  == 'km/s':
00730             a['restfreq'] = ''
00731 
00732         if self.parameters['maskmode']  == 'auto':
00733             a['thresh'] = 5.0
00734             a['avg_limit'] = 4
00735             a['edge'] = [0]
00736 
00737         if self.parameters['blfunc']  == 'poly':
00738             a['order'] = 5
00739 
00740         if self.parameters['blfunc']  == 'chebyshev':
00741             a['order'] = 5
00742             a['clipthresh'] = 3.0
00743             a['clipniter'] = 0
00744 
00745         if self.parameters['blfunc']  == 'cspline':
00746             a['npiece'] = 2
00747             a['clipthresh'] = 3.0
00748             a['clipniter'] = 0
00749 
00750         if self.parameters['blfunc']  == 'sinusoid':
00751             a['applyfft'] = True
00752             a['fftmethod'] = 'fft'
00753             a['fftthresh'] = 3.0
00754             a['addwn'] = [0]
00755             a['rejwn'] = []
00756             a['clipthresh'] = 3.0
00757             a['clipniter'] = 0
00758 
00759         if self.parameters['showprogress']  == True:
00760             a['minnrow'] = 1000
00761 
00762         if a.has_key(paramname) :
00763               return a[paramname]
00764 sdbaseline_cli = sdbaseline_cli_()