casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
slsearch_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_slsearch import slsearch
00018 class slsearch_cli_:
00019     __name__ = "slsearch"
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__ = (slsearch_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'tablename':None, 'outfile':None, 'freqrange':None, 'species':None, 'reconly':None, 'chemnames':None, 'qns':None, 'intensity':None, 'smu2':None, 'loga':None, 'el':None, 'eu':None, 'rrlinclude':None, 'rrlonly':None, 'verbose':None, 'logfile':None, 'append':None, 'wantreturn':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, tablename=None, outfile=None, freqrange=None, species=None, reconly=None, chemnames=None, qns=None, intensity=None, smu2=None, loga=None, el=None, eu=None, rrlinclude=None, rrlonly=None, verbose=None, logfile=None, append=None, wantreturn=None,  async=None):
00047 
00048         """Search a spectral line table.
00049 
00050 PARAMETER SUMMARY
00051 
00052 tablename      Input spectral line table name to search. If not specified, use the default table in the system.
00053 outfile        Results table name. Blank means do not write the table to disk.
00054 freqrange      Frequency range in GHz.
00055 species        Species to search for.
00056 reconly        List only NRAO recommended frequencies.
00057 chemnames      Chemical names to search for.
00058 qns            Resolved quantum numbers to search for.
00059 intensity      CDMS/JPL intensity range. -1 -> do not use an intensity range.
00060 smu2           S*mu*mu range in Debye**2. -1 -> do not use an S*mu*mu range.
00061 loga           log(A) (Einstein coefficient) range. -1 -> do not use a loga range.
00062 el             Lower energy state range in Kelvin. -1 -> do not use an el range.
00063 eu             Upper energy state range in Kelvin. -1 -> do not use an eu range.
00064 rrlinclude     Include RRLs in the result set?
00065 rrlonly        Include only RRLs in the result set?
00066 verbose        List result set to logger (and optionally logfile)?
00067 logfile        List result set to this logfile (only used if verbose=True).
00068 append         If true, append to logfile if it already exists, if false overwrite logfile it it exists. Only used if verbose=True and logfile not blank.
00069 wantreturn     If true, return the spectralline tool associated with the result set.
00070 
00071     Search the specfied spectral line table. The return value (if wantreturn=true) is a spectralline tool with a new table containing the search
00072     results. This new table can be written to disk by specifying its name in the outfile parameter. If outfile is not specified
00073     (ie outfile=""), the resulting table is held in memory and deleted upon a call to close() or done() for the newly created tool
00074     or upon exiting casapy if wantreturn=True or immediately upon completion of task execution if wantreturn=False. Because Splatalogue does not have values for intensity, smu2, loga, eu, and el
00075     for radio recombination lines (rrls), one must specify to include rrls in the specified frequency range in the output. In this case,
00076     RRLs will be included ignoring any filters on intensity, smu2, loga, eu, and el. One can also specify to list only RRLs. One can specify 
00077     to list the search results to the logger via the verbose parameter. If verbose is False, no logger output is listed, although the results 
00078     can be listed later by running the sl.list() method on the newly created spectral line tool if wantreturn=True. If verbose=True, one can also specify that
00079     the results be listed to a logfile and if this file already exists, one can specify that the results be appended to it or to overwrite
00080     it with the results.
00081     
00082     slrestool = slsearch("myspectrallines.tbl", verbose=False)
00083     # do a search postponing listing the results to the logger.
00084     slrestool = sl.search(outfile="myresults.tbl", freqrange = [200,300], species=['HOCN', 'HOCO+'])
00085     # now list the results
00086     slrestool.list()
00087     # or one could also do the following after exiting and restarting casapy
00088     sl.open("myresults.tbl")
00089     sl.list()
00090     
00091 
00092 
00093         """
00094         if not hasattr(self, "__globals__") or self.__globals__ == None :
00095            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00096         #casac = self.__globals__['casac']
00097         casalog = self.__globals__['casalog']
00098         #casalog = casac.casac.logsink()
00099         self.__globals__['__last_task'] = 'slsearch'
00100         self.__globals__['taskname'] = 'slsearch'
00101         ###
00102         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00103         ###
00104         ###
00105         #Handle globals or user over-ride of arguments
00106         #
00107         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00108         useLocalDefaults = False
00109 
00110         for item in function_signature_defaults.iteritems():
00111                 key,val = item
00112                 keyVal = eval(key)
00113                 if (keyVal == None):
00114                         #user hasn't set it - use global/default
00115                         pass
00116                 else:
00117                         #user has set it - use over-ride
00118                         if (key != 'self') :
00119                            useLocalDefaults = True
00120 
00121         myparams = {}
00122         if useLocalDefaults :
00123            for item in function_signature_defaults.iteritems():
00124                key,val = item
00125                keyVal = eval(key)
00126                exec('myparams[key] = keyVal')
00127                self.parameters[key] = keyVal
00128                if (keyVal == None):
00129                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00130                    keyVal = eval(key)
00131                    if(type(keyVal) == dict) :
00132                       if len(keyVal) > 0 :
00133                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00134                       else :
00135                          exec('myparams[key] = ' + key + ' = {}')
00136 
00137         else :
00138             async = self.parameters['async']
00139             myparams['tablename'] = tablename = self.parameters['tablename']
00140             myparams['outfile'] = outfile = self.parameters['outfile']
00141             myparams['freqrange'] = freqrange = self.parameters['freqrange']
00142             myparams['species'] = species = self.parameters['species']
00143             myparams['reconly'] = reconly = self.parameters['reconly']
00144             myparams['chemnames'] = chemnames = self.parameters['chemnames']
00145             myparams['qns'] = qns = self.parameters['qns']
00146             myparams['intensity'] = intensity = self.parameters['intensity']
00147             myparams['smu2'] = smu2 = self.parameters['smu2']
00148             myparams['loga'] = loga = self.parameters['loga']
00149             myparams['el'] = el = self.parameters['el']
00150             myparams['eu'] = eu = self.parameters['eu']
00151             myparams['rrlinclude'] = rrlinclude = self.parameters['rrlinclude']
00152             myparams['rrlonly'] = rrlonly = self.parameters['rrlonly']
00153             myparams['verbose'] = verbose = self.parameters['verbose']
00154             myparams['logfile'] = logfile = self.parameters['logfile']
00155             myparams['append'] = append = self.parameters['append']
00156             myparams['wantreturn'] = wantreturn = self.parameters['wantreturn']
00157 
00158         if type(freqrange)==float: freqrange=[freqrange]
00159         if type(species)==str: species=[species]
00160         if type(chemnames)==str: chemnames=[chemnames]
00161         if type(qns)==str: qns=[qns]
00162         if type(intensity)==float: intensity=[intensity]
00163         if type(smu2)==float: smu2=[smu2]
00164         if type(loga)==float: loga=[loga]
00165         if type(el)==float: el=[el]
00166         if type(eu)==float: eu=[eu]
00167 
00168         result = None
00169 
00170 #
00171 #    The following is work around to avoid a bug with current python translation
00172 #
00173         mytmp = {}
00174 
00175         mytmp['tablename'] = tablename
00176         mytmp['outfile'] = outfile
00177         mytmp['freqrange'] = freqrange
00178         mytmp['species'] = species
00179         mytmp['reconly'] = reconly
00180         mytmp['chemnames'] = chemnames
00181         mytmp['qns'] = qns
00182         mytmp['intensity'] = intensity
00183         mytmp['smu2'] = smu2
00184         mytmp['loga'] = loga
00185         mytmp['el'] = el
00186         mytmp['eu'] = eu
00187         mytmp['rrlinclude'] = rrlinclude
00188         mytmp['rrlonly'] = rrlonly
00189         mytmp['verbose'] = verbose
00190         mytmp['logfile'] = logfile
00191         mytmp['append'] = append
00192         mytmp['wantreturn'] = wantreturn
00193         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00194         trec = casac.casac.utils().torecord(pathname+'slsearch.xml')
00195 
00196         casalog.origin('slsearch')
00197         try :
00198           #if not trec.has_key('slsearch') or not casac.casac.utils().verify(mytmp, trec['slsearch']) :
00199             #return False
00200 
00201           casac.casac.utils().verify(mytmp, trec['slsearch'], True)
00202           scriptstr=['']
00203           saveinputs = self.__globals__['saveinputs']
00204           saveinputs('slsearch', 'slsearch.last', myparams, self.__globals__,scriptstr=scriptstr)
00205           if async :
00206             count = 0
00207             keybase =  time.strftime("%y%m%d.%H%M%S")
00208             key = keybase + "_" + str(count)
00209             while self.__async__.has_key(key) :
00210                count += 1
00211                key = keybase + "_" + str(count)
00212             result = tm.execute('slsearch', tablename, outfile, freqrange, species, reconly, chemnames, qns, intensity, smu2, loga, el, eu, rrlinclude, rrlonly, verbose, logfile, append, wantreturn)
00213             print "Use: "
00214             print "      tm.retrieve(return_value) # to retrieve the status"
00215             print 
00216             self.rkey = key
00217             self.__async__[key] = result
00218           else :
00219               tname = 'slsearch'
00220               spaces = ' '*(18-len(tname))
00221               casalog.post('\n##########################################'+
00222                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00223               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00224               result = slsearch(tablename, outfile, freqrange, species, reconly, chemnames, qns, intensity, smu2, loga, el, eu, rrlinclude, rrlonly, verbose, logfile, append, wantreturn)
00225               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00226                            '\n##########################################')
00227 
00228         except Exception, instance:
00229           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00230              raise
00231           else :
00232              #print '**** Error **** ',instance
00233              tname = 'slsearch'
00234              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00235              pass
00236 
00237         gc.collect()
00238         return result
00239 #
00240 #
00241 #
00242     def paramgui(self, useGlobals=True, ipython_globals=None):
00243         """
00244         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00245         """
00246         import paramgui
00247         if not hasattr(self, "__globals__") or self.__globals__ == None :
00248            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00249 
00250         if useGlobals:
00251             if ipython_globals == None:
00252                 myf=self.__globals__
00253             else:
00254                 myf=ipython_globals
00255 
00256             paramgui.setGlobals(myf)
00257         else:
00258             paramgui.setGlobals({})
00259 
00260         paramgui.runTask('slsearch', myf['_ip'])
00261         paramgui.setGlobals({})
00262 
00263 #
00264 #
00265 #
00266     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00267         if not hasattr(self, "__globals__") or self.__globals__ == None :
00268            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00269         if ipython_globals == None:
00270             myf=self.__globals__
00271         else:
00272             myf=ipython_globals
00273 
00274         a = odict()
00275         a['tablename']  = ''
00276         a['outfile']  = ''
00277         a['freqrange']  = [84,90]
00278         a['species']  = ['']
00279         a['reconly']  = False
00280         a['chemnames']  = ['']
00281         a['qns']  = ['']
00282         a['rrlinclude']  = True
00283         a['rrlonly']  = False
00284         a['verbose']  = False
00285         a['wantreturn']  = True
00286 
00287         a['async']=False
00288         a['verbose'] = {
00289                     0:odict([{'value':True}, {'logfile':""}, {'append':True}])}
00290         a['rrlonly'] = {
00291                     0:odict([{'value':False}, {'intensity':-1}, {'smu2':-1}, {'loga':-1}, {'eu':-1}, {'el':-1}])}
00292 
00293 ### This function sets the default values but also will return the list of
00294 ### parameters or the default value of a given parameter
00295         if(param == None):
00296                 myf['__set_default_parameters'](a)
00297         elif(param == 'paramkeys'):
00298                 return a.keys()
00299         else:
00300             if(paramvalue==None and subparam==None):
00301                if(a.has_key(param)):
00302                   return a[param]
00303                else:
00304                   return self.itsdefault(param)
00305             else:
00306                retval=a[param]
00307                if(type(a[param])==dict):
00308                   for k in range(len(a[param])):
00309                      valornotval='value'
00310                      if(a[param][k].has_key('notvalue')):
00311                         valornotval='notvalue'
00312                      if((a[param][k][valornotval])==paramvalue):
00313                         retval=a[param][k].copy()
00314                         retval.pop(valornotval)
00315                         if(subparam != None):
00316                            if(retval.has_key(subparam)):
00317                               retval=retval[subparam]
00318                            else:
00319                               retval=self.itsdefault(subparam)
00320                      else:
00321                         retval=self.itsdefault(subparam)
00322                return retval
00323 
00324 
00325 #
00326 #
00327     def check_params(self, param=None, value=None, ipython_globals=None):
00328       if ipython_globals == None:
00329           myf=self.__globals__
00330       else:
00331           myf=ipython_globals
00332 #      print 'param:', param, 'value:', value
00333       try :
00334          if str(type(value)) != "<type 'instance'>" :
00335             value0 = value
00336             value = myf['cu'].expandparam(param, value)
00337             matchtype = False
00338             if(type(value) == numpy.ndarray):
00339                if(type(value) == type(value0)):
00340                   myf[param] = value.tolist()
00341                else:
00342                   #print 'value:', value, 'value0:', value0
00343                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00344                   myf[param] = value0
00345                   if type(value0) != list :
00346                      matchtype = True
00347             else :
00348                myf[param] = value
00349             value = myf['cu'].verifyparam({param:value})
00350             if matchtype:
00351                value = False
00352       except Exception, instance:
00353          #ignore the exception and just return it unchecked
00354          myf[param] = value
00355       return value
00356 #
00357 #
00358     def description(self, key='slsearch', subkey=None):
00359         desc={'slsearch': 'Search a spectral line table.',
00360                'tablename': 'Input spectral line table name to search. If not specified, use the default table in the system.',
00361                'outfile': 'Results table name. Blank means do not write the table to disk.',
00362                'freqrange': 'Frequency range in GHz.',
00363                'species': 'Species to search for.',
00364                'reconly': 'List only NRAO recommended frequencies.',
00365                'chemnames': 'Chemical names to search for.',
00366                'qns': 'Resolved quantum numbers to search for.',
00367                'intensity': 'CDMS/JPL intensity range. -1 -> do not use an intensity range.',
00368                'smu2': 'S*mu*mu range in Debye**2. -1 -> do not use an S*mu*mu range.',
00369                'loga': 'log(A) (Einstein coefficient) range. -1 -> do not use a loga range.',
00370                'el': 'Lower energy state range in Kelvin. -1 -> do not use an el range.',
00371                'eu': 'Upper energy state range in Kelvin. -1 -> do not use an eu range.',
00372                'rrlinclude': 'Include RRLs in the result set?',
00373                'rrlonly': 'Include only RRLs in the result set?',
00374                'verbose': 'List result set to logger (and optionally logfile)?',
00375                'logfile': 'List result set to this logfile (only used if verbose=True).',
00376                'append': 'If true, append to logfile if it already exists, if false overwrite logfile it it exists. Only used if verbose=True and logfile not blank.',
00377                'wantreturn': 'If true, return the spectralline tool associated with the result set.',
00378 
00379                'async': 'If true the taskname must be started using slsearch(...)'
00380               }
00381 
00382 #
00383 # Set subfields defaults if needed
00384 #
00385 
00386         if(desc.has_key(key)) :
00387            return desc[key]
00388 
00389     def itsdefault(self, paramname) :
00390         a = {}
00391         a['tablename']  = ''
00392         a['outfile']  = ''
00393         a['freqrange']  = [84,90]
00394         a['species']  = ['']
00395         a['reconly']  = False
00396         a['chemnames']  = ['']
00397         a['qns']  = ['']
00398         a['intensity']  = [-1]
00399         a['smu2']  = [-1]
00400         a['loga']  = [-1]
00401         a['el']  = [-1]
00402         a['eu']  = [-1]
00403         a['rrlinclude']  = True
00404         a['rrlonly']  = False
00405         a['verbose']  = False
00406         a['logfile']  = '""'
00407         a['append']  = False
00408         a['wantreturn']  = True
00409 
00410         #a = sys._getframe(len(inspect.stack())-1).f_globals
00411 
00412         if self.parameters['verbose']  == True:
00413             a['logfile'] = ""
00414             a['append'] = True
00415 
00416         if self.parameters['rrlonly']  == False:
00417             a['intensity'] = -1
00418             a['smu2'] = -1
00419             a['loga'] = -1
00420             a['eu'] = -1
00421             a['el'] = -1
00422 
00423         if a.has_key(paramname) :
00424               return a[paramname]
00425 slsearch_cli = slsearch_cli_()