casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
slsearch_pg.py
Go to the documentation of this file.
00001 #
00002 # This file was generated using xslt from its XML file
00003 #
00004 # Copyright 2008, Associated Universities Inc., Washington DC
00005 #
00006 import sys
00007 import os
00008 from casac import *
00009 import string
00010 import time
00011 import inspect
00012 import gc
00013 import numpy
00014 from odict import odict
00015 from task_slsearch import slsearch
00016 from task_slsearch import casalog
00017 
00018 class slsearch_pg_:
00019     __name__ = "slsearch"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (slsearch_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     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):
00027 
00028         """Search a spectral line table.
00029 
00030 PARAMETER SUMMARY
00031 
00032 tablename      Input spectral line table name to search. If not specified, use the default table in the system.
00033 outfile        Results table name. Blank means do not write the table to disk.
00034 freqrange      Frequency range in GHz.
00035 species        Species to search for.
00036 reconly        List only NRAO recommended frequencies.
00037 chemnames      Chemical names to search for.
00038 qns            Resolved quantum numbers to search for.
00039 intensity      CDMS/JPL intensity range. -1 -> do not use an intensity range.
00040 smu2           S*mu*mu range in Debye**2. -1 -> do not use an S*mu*mu range.
00041 loga           log(A) (Einstein coefficient) range. -1 -> do not use a loga range.
00042 el             Lower energy state range in Kelvin. -1 -> do not use an el range.
00043 eu             Upper energy state range in Kelvin. -1 -> do not use an eu range.
00044 rrlinclude     Include RRLs in the result set?
00045 rrlonly        Include only RRLs in the result set?
00046 verbose        List result set to logger (and optionally logfile)?
00047 logfile        List result set to this logfile (only used if verbose=True).
00048 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.
00049 wantreturn     If true, return the spectralline tool associated with the result set.
00050 
00051     Search the specfied spectral line table. The return value (if wantreturn=true) is a spectralline tool with a new table containing the search
00052     results. This new table can be written to disk by specifying its name in the outfile parameter. If outfile is not specified
00053     (ie outfile=""), the resulting table is held in memory and deleted upon a call to close() or done() for the newly created tool
00054     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
00055     for radio recombination lines (rrls), one must specify to include rrls in the specified frequency range in the output. In this case,
00056     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 
00057     to list the search results to the logger via the verbose parameter. If verbose is False, no logger output is listed, although the results 
00058     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
00059     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
00060     it with the results.
00061     
00062     slrestool = slsearch("myspectrallines.tbl", verbose=False)
00063     # do a search postponing listing the results to the logger.
00064     slrestool = sl.search(outfile="myresults.tbl", freqrange = [200,300], species=['HOCN', 'HOCO+'])
00065     # now list the results
00066     slrestool.list()
00067     # or one could also do the following after exiting and restarting casapy
00068     sl.open("myresults.tbl")
00069     sl.list()
00070     
00071 
00072 
00073         """
00074         a=inspect.stack()
00075         stacklevel=0
00076         for k in range(len(a)):
00077           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00078                 stacklevel=k
00079                 break
00080         myf=sys._getframe(stacklevel).f_globals
00081         myf['__last_task'] = 'slsearch'
00082         myf['taskname'] = 'slsearch'
00083         ###
00084         myf['update_params'](func=myf['taskname'],printtext=False)
00085         ###
00086         ###
00087         #Handle globals or user over-ride of arguments
00088         #
00089         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00090         useLocalDefaults = False
00091 
00092         for item in function_signature_defaults.iteritems():
00093                 key,val = item
00094                 keyVal = eval(key)
00095                 if (keyVal == None):
00096                         #user hasn't set it - use global/default
00097                         pass
00098                 else:
00099                         #user has set it - use over-ride
00100                         if (key != 'self') :
00101                            useLocalDefaults = True
00102                         #myf[key]=keyVal
00103 
00104         myparams = {}
00105         if useLocalDefaults :
00106            for item in function_signature_defaults.iteritems():
00107                key,val = item
00108                keyVal = eval(key)
00109                exec('myparams[key] = keyVal')
00110                if (keyVal == None):
00111                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00112                    keyVal = eval(key)
00113                    if(type(keyVal) == dict) :
00114                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00115 
00116         else :
00117             uselessvariable = None 
00118             myparams['tablename'] = tablename = myf['tablename']
00119             myparams['outfile'] = outfile = myf['outfile']
00120             myparams['freqrange'] = freqrange = myf['freqrange']
00121             myparams['species'] = species = myf['species']
00122             myparams['reconly'] = reconly = myf['reconly']
00123             myparams['chemnames'] = chemnames = myf['chemnames']
00124             myparams['qns'] = qns = myf['qns']
00125             myparams['intensity'] = intensity = myf['intensity']
00126             myparams['smu2'] = smu2 = myf['smu2']
00127             myparams['loga'] = loga = myf['loga']
00128             myparams['el'] = el = myf['el']
00129             myparams['eu'] = eu = myf['eu']
00130             myparams['rrlinclude'] = rrlinclude = myf['rrlinclude']
00131             myparams['rrlonly'] = rrlonly = myf['rrlonly']
00132             myparams['verbose'] = verbose = myf['verbose']
00133             myparams['logfile'] = logfile = myf['logfile']
00134             myparams['append'] = append = myf['append']
00135             myparams['wantreturn'] = wantreturn = myf['wantreturn']
00136 
00137         if type(freqrange)==float: freqrange=[freqrange]
00138         if type(species)==str: species=[species]
00139         if type(chemnames)==str: chemnames=[chemnames]
00140         if type(qns)==str: qns=[qns]
00141         if type(intensity)==float: intensity=[intensity]
00142         if type(smu2)==float: smu2=[smu2]
00143         if type(loga)==float: loga=[loga]
00144         if type(el)==float: el=[el]
00145         if type(eu)==float: eu=[eu]
00146 
00147         result = None
00148 
00149 #
00150 #    The following is work around to avoid a bug with current python translation
00151 #
00152         mytmp = {}
00153 
00154         mytmp['tablename'] = tablename
00155         mytmp['outfile'] = outfile
00156         mytmp['freqrange'] = freqrange
00157         mytmp['species'] = species
00158         mytmp['reconly'] = reconly
00159         mytmp['chemnames'] = chemnames
00160         mytmp['qns'] = qns
00161         mytmp['intensity'] = intensity
00162         mytmp['smu2'] = smu2
00163         mytmp['loga'] = loga
00164         mytmp['el'] = el
00165         mytmp['eu'] = eu
00166         mytmp['rrlinclude'] = rrlinclude
00167         mytmp['rrlonly'] = rrlonly
00168         mytmp['verbose'] = verbose
00169         mytmp['logfile'] = logfile
00170         mytmp['append'] = append
00171         mytmp['wantreturn'] = wantreturn
00172         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00173         trec = casac.utils().torecord(pathname+'slsearch.xml')
00174 
00175         casalog.origin('slsearch')
00176         if not trec.has_key('slsearch') or not casac.utils().verify(mytmp, trec['slsearch']) :
00177             return False
00178 
00179 
00180         try :
00181           casalog.post('')
00182           casalog.post('##########################################')
00183           casalog.post('##### Begin Task: slsearch           #####')
00184           casalog.post('')
00185           result = slsearch(tablename, outfile, freqrange, species, reconly, chemnames, qns, intensity, smu2, loga, el, eu, rrlinclude, rrlonly, verbose, logfile, append, wantreturn)
00186           casalog.post('')
00187           casalog.post('##### End Task: slsearch           #####')
00188           casalog.post('##########################################')
00189 
00190 
00191 # saveinputs for individule engine has no use
00192 # saveinputs should alos be removed from casa_in_py.py
00193 #
00194 #
00195 #          saveinputs = myf['saveinputs']
00196 #          saveinputs('slsearch', 'slsearch.last', myparams)
00197 #
00198 #
00199         except Exception, instance:
00200           #print '**** Error **** ',instance
00201           pass
00202 
00203         gc.collect()
00204         return result
00205 #
00206 #
00207 ##
00208 #    def paramgui(self, useGlobals=True):
00209 #        """
00210 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00211 #        """
00212 #        import paramgui
00213 #
00214 #        a=inspect.stack()
00215 #        stacklevel=0
00216 #        for k in range(len(a)):
00217 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00218 #            stacklevel=k
00219 #            break
00220 #        myf = sys._getframe(stacklevel).f_globals
00221 #
00222 #        if useGlobals:
00223 #            paramgui.setGlobals(myf)
00224 #        else:
00225 #            paramgui.setGlobals({})
00226 #
00227 #        paramgui.runTask('slsearch', myf['_ip'])
00228 #        paramgui.setGlobals({})
00229 #
00230 #
00231 #
00232 #
00233     def defaults(self, param=None):
00234         a=inspect.stack()
00235         stacklevel=0
00236         for k in range(len(a)):
00237           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00238                 stacklevel=k
00239                 break
00240         myf=sys._getframe(stacklevel).f_globals
00241         a = odict()
00242         a['tablename']  = ''
00243         a['outfile']  = ''
00244         a['freqrange']  = [84,90]
00245         a['species']  = ['']
00246         a['reconly']  = False
00247         a['chemnames']  = ['']
00248         a['qns']  = ['']
00249         a['rrlinclude']  = True
00250         a['rrlonly']  = False
00251         a['verbose']  = False
00252         a['wantreturn']  = True
00253 
00254         a['async']=False
00255         a['verbose'] = {
00256                     0:odict([{'value':True}, {'logfile':""}, {'append':True}])}
00257         a['rrlonly'] = {
00258                     0:odict([{'value':False}, {'intensity':-1}, {'smu2':-1}, {'loga':-1}, {'eu':-1}, {'el':-1}])}
00259 
00260 ### This function sets the default values but also will return the list of
00261 ### parameters or the default value of a given parameter
00262         if(param == None):
00263                 myf['__set_default_parameters'](a)
00264         elif(param == 'paramkeys'):
00265                 return a.keys()
00266         else:
00267                 if(a.has_key(param)):
00268                    #if(type(a[param]) == dict) :
00269                    #   return a[param][len(a[param])-1]['value']
00270                    #else :
00271                       return a[param]
00272 
00273 
00274 #
00275 #
00276     def check_params(self, param=None, value=None):
00277       a=inspect.stack() 
00278       stacklevel=0
00279       for k in range(len(a)):
00280         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00281             stacklevel=k
00282             break
00283       myf=sys._getframe(stacklevel).f_globals
00284 
00285 #      print 'param:', param, 'value:', value
00286       try :
00287          if str(type(value)) != "<type 'instance'>" :
00288             value0 = value
00289             value = myf['cu'].expandparam(param, value)
00290             matchtype = False
00291             if(type(value) == numpy.ndarray):
00292                if(type(value) == type(value0)):
00293                   myf[param] = value.tolist()
00294                else:
00295                   #print 'value:', value, 'value0:', value0
00296                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00297                   myf[param] = value0
00298                   if type(value0) != list :
00299                      matchtype = True
00300             else :
00301                myf[param] = value
00302             value = myf['cu'].verifyparam({param:value})
00303             if matchtype:
00304                value = False
00305       except Exception, instance:
00306          #ignore the exception and just return it unchecked
00307          myf[param] = value
00308       return value
00309 
00310 #
00311 #
00312     def description(self, key='slsearch', subkey=None):
00313         desc={'slsearch': 'Search a spectral line table.',
00314                'tablename': 'Input spectral line table name to search. If not specified, use the default table in the system.',
00315                'outfile': 'Results table name. Blank means do not write the table to disk.',
00316                'freqrange': 'Frequency range in GHz.',
00317                'species': 'Species to search for.',
00318                'reconly': 'List only NRAO recommended frequencies.',
00319                'chemnames': 'Chemical names to search for.',
00320                'qns': 'Resolved quantum numbers to search for.',
00321                'intensity': 'CDMS/JPL intensity range. -1 -> do not use an intensity range.',
00322                'smu2': 'S*mu*mu range in Debye**2. -1 -> do not use an S*mu*mu range.',
00323                'loga': 'log(A) (Einstein coefficient) range. -1 -> do not use a loga range.',
00324                'el': 'Lower energy state range in Kelvin. -1 -> do not use an el range.',
00325                'eu': 'Upper energy state range in Kelvin. -1 -> do not use an eu range.',
00326                'rrlinclude': 'Include RRLs in the result set?',
00327                'rrlonly': 'Include only RRLs in the result set?',
00328                'verbose': 'List result set to logger (and optionally logfile)?',
00329                'logfile': 'List result set to this logfile (only used if verbose=True).',
00330                '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.',
00331                'wantreturn': 'If true, return the spectralline tool associated with the result set.',
00332 
00333                'async': 'If true the taskname must be started using slsearch(...)'
00334               }
00335 
00336 #
00337 # Set subfields defaults if needed
00338 #
00339 
00340         if(desc.has_key(key)) :
00341            return desc[key]
00342 
00343     def itsdefault(self, paramname) :
00344         a = {}
00345         a['tablename']  = ''
00346         a['outfile']  = ''
00347         a['freqrange']  = [84,90]
00348         a['species']  = ['']
00349         a['reconly']  = False
00350         a['chemnames']  = ['']
00351         a['qns']  = ['']
00352         a['intensity']  = [-1]
00353         a['smu2']  = [-1]
00354         a['loga']  = [-1]
00355         a['el']  = [-1]
00356         a['eu']  = [-1]
00357         a['rrlinclude']  = True
00358         a['rrlonly']  = False
00359         a['verbose']  = False
00360         a['logfile']  = '""'
00361         a['append']  = False
00362         a['wantreturn']  = True
00363 
00364         if a.has_key(paramname) :
00365               return a[paramname]
00366 slsearch_pg = slsearch_pg_()