casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
splattotable_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_splattotable import splattotable
00018 class splattotable_cli_:
00019     __name__ = "splattotable"
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__ = (splattotable_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'filenames':None, 'table':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, filenames=None, table=None, wantreturn=None,  async=None):
00047 
00048         """Convert a downloaded Splatalogue spectral line list to a casa table.
00049 PARAMETER SUMMARY
00050 filenames   Files containing Splatalogue lists.
00051 table       Output table name.
00052 wantreturn  Do you want the task to return a spectralline tool attached to the results table? If not false is returned.
00053 
00054 This task reads a spectral line list(s) downloaded from Splatalogue (www.splatalogue.net) and loads it into a CASA table which
00055 can be queried via eg the slsearch task.
00056     
00057 REQUIRMENTS OF THE DOWNLOADED FILES
00058     
00059 The downloaded files must be in a specific format for this task to succeed. The columns are the
00060 important things; one can filter the results as one desires using Splatalogue, but the particular columns must be present as described
00061 below. The columns which must be present in the downloaded file in this exact order are: "Species", "NRAO Recommended", "Chemical Name",
00062 "Freq in GHz", "Resolved QNs", "CDMS/JPL Intensity", "Sijmu2 (D2)",
00063 "Log10 (Aij)", "EL (K)", "EU (K)", "Linelist". In order to get these columns in this order, one should
00064 select exactly the following items on the Splatalogue search interface. Under "Specify Ranges" one should select "GHz" for the frequency unit.
00065 Under "Line Strength Display" select exactly "CDMS/JPL Intensity",
00066 "Sij mu2", and "Aij". Under "Energy Levels", one should select exactly "Elower (K)" and "Eupper (K)". Under "Miscellaneous", one should
00067 select exactly "Display Ordered Frequency ONLY" and "Display NRAO Recommended Frequencies". One should then initiate the search and on
00068 the resulting page, one should select the Tab Field Separator and then export the list. The resulting list should be in the proper
00069 format for importing into CASA.
00070     
00071 RETURN VALUE
00072 This task returns an open spectralline tool which references the new table if wantarray=true. The new table can also be opened by 
00073 a spectralline tool using the open method (eg sl.open(tablename)). False is returned if wantarray=false.
00074 
00075 
00076 newsl = splattotable("mysplatlist.txt", "mynewsl.tbl", true)
00077 
00078 
00079 
00080         """
00081         if not hasattr(self, "__globals__") or self.__globals__ == None :
00082            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00083         #casac = self.__globals__['casac']
00084         casalog = self.__globals__['casalog']
00085         #casalog = casac.casac.logsink()
00086         self.__globals__['__last_task'] = 'splattotable'
00087         self.__globals__['taskname'] = 'splattotable'
00088         ###
00089         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00090         ###
00091         ###
00092         #Handle globals or user over-ride of arguments
00093         #
00094         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00095         useLocalDefaults = False
00096 
00097         for item in function_signature_defaults.iteritems():
00098                 key,val = item
00099                 keyVal = eval(key)
00100                 if (keyVal == None):
00101                         #user hasn't set it - use global/default
00102                         pass
00103                 else:
00104                         #user has set it - use over-ride
00105                         if (key != 'self') :
00106                            useLocalDefaults = True
00107 
00108         myparams = {}
00109         if useLocalDefaults :
00110            for item in function_signature_defaults.iteritems():
00111                key,val = item
00112                keyVal = eval(key)
00113                exec('myparams[key] = keyVal')
00114                self.parameters[key] = keyVal
00115                if (keyVal == None):
00116                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00117                    keyVal = eval(key)
00118                    if(type(keyVal) == dict) :
00119                       if len(keyVal) > 0 :
00120                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00121                       else :
00122                          exec('myparams[key] = ' + key + ' = {}')
00123 
00124         else :
00125             async = self.parameters['async']
00126             myparams['filenames'] = filenames = self.parameters['filenames']
00127             myparams['table'] = table = self.parameters['table']
00128             myparams['wantreturn'] = wantreturn = self.parameters['wantreturn']
00129 
00130         if type(filenames)==str: filenames=[filenames]
00131 
00132         result = None
00133 
00134 #
00135 #    The following is work around to avoid a bug with current python translation
00136 #
00137         mytmp = {}
00138 
00139         mytmp['filenames'] = filenames
00140         mytmp['table'] = table
00141         mytmp['wantreturn'] = wantreturn
00142         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00143         trec = casac.casac.utils().torecord(pathname+'splattotable.xml')
00144 
00145         casalog.origin('splattotable')
00146         try :
00147           #if not trec.has_key('splattotable') or not casac.casac.utils().verify(mytmp, trec['splattotable']) :
00148             #return False
00149 
00150           casac.casac.utils().verify(mytmp, trec['splattotable'], True)
00151           scriptstr=['']
00152           saveinputs = self.__globals__['saveinputs']
00153           saveinputs('splattotable', 'splattotable.last', myparams, self.__globals__,scriptstr=scriptstr)
00154           if async :
00155             count = 0
00156             keybase =  time.strftime("%y%m%d.%H%M%S")
00157             key = keybase + "_" + str(count)
00158             while self.__async__.has_key(key) :
00159                count += 1
00160                key = keybase + "_" + str(count)
00161             result = tm.execute('splattotable', filenames, table, wantreturn)
00162             print "Use: "
00163             print "      tm.retrieve(return_value) # to retrieve the status"
00164             print 
00165             self.rkey = key
00166             self.__async__[key] = result
00167           else :
00168               tname = 'splattotable'
00169               spaces = ' '*(18-len(tname))
00170               casalog.post('\n##########################################'+
00171                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00172               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00173               result = splattotable(filenames, table, wantreturn)
00174               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00175                            '\n##########################################')
00176 
00177         except Exception, instance:
00178           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00179              raise
00180           else :
00181              #print '**** Error **** ',instance
00182              tname = 'splattotable'
00183              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00184              pass
00185 
00186         gc.collect()
00187         return result
00188 #
00189 #
00190 #
00191     def paramgui(self, useGlobals=True, ipython_globals=None):
00192         """
00193         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00194         """
00195         import paramgui
00196         if not hasattr(self, "__globals__") or self.__globals__ == None :
00197            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00198 
00199         if useGlobals:
00200             if ipython_globals == None:
00201                 myf=self.__globals__
00202             else:
00203                 myf=ipython_globals
00204 
00205             paramgui.setGlobals(myf)
00206         else:
00207             paramgui.setGlobals({})
00208 
00209         paramgui.runTask('splattotable', myf['_ip'])
00210         paramgui.setGlobals({})
00211 
00212 #
00213 #
00214 #
00215     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00216         if not hasattr(self, "__globals__") or self.__globals__ == None :
00217            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00218         if ipython_globals == None:
00219             myf=self.__globals__
00220         else:
00221             myf=ipython_globals
00222 
00223         a = odict()
00224         a['filenames']  = ['']
00225         a['table']  = ''
00226         a['wantreturn']  = True
00227 
00228         a['async']=False
00229 
00230 ### This function sets the default values but also will return the list of
00231 ### parameters or the default value of a given parameter
00232         if(param == None):
00233                 myf['__set_default_parameters'](a)
00234         elif(param == 'paramkeys'):
00235                 return a.keys()
00236         else:
00237             if(paramvalue==None and subparam==None):
00238                if(a.has_key(param)):
00239                   return a[param]
00240                else:
00241                   return self.itsdefault(param)
00242             else:
00243                retval=a[param]
00244                if(type(a[param])==dict):
00245                   for k in range(len(a[param])):
00246                      valornotval='value'
00247                      if(a[param][k].has_key('notvalue')):
00248                         valornotval='notvalue'
00249                      if((a[param][k][valornotval])==paramvalue):
00250                         retval=a[param][k].copy()
00251                         retval.pop(valornotval)
00252                         if(subparam != None):
00253                            if(retval.has_key(subparam)):
00254                               retval=retval[subparam]
00255                            else:
00256                               retval=self.itsdefault(subparam)
00257                      else:
00258                         retval=self.itsdefault(subparam)
00259                return retval
00260 
00261 
00262 #
00263 #
00264     def check_params(self, param=None, value=None, ipython_globals=None):
00265       if ipython_globals == None:
00266           myf=self.__globals__
00267       else:
00268           myf=ipython_globals
00269 #      print 'param:', param, 'value:', value
00270       try :
00271          if str(type(value)) != "<type 'instance'>" :
00272             value0 = value
00273             value = myf['cu'].expandparam(param, value)
00274             matchtype = False
00275             if(type(value) == numpy.ndarray):
00276                if(type(value) == type(value0)):
00277                   myf[param] = value.tolist()
00278                else:
00279                   #print 'value:', value, 'value0:', value0
00280                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00281                   myf[param] = value0
00282                   if type(value0) != list :
00283                      matchtype = True
00284             else :
00285                myf[param] = value
00286             value = myf['cu'].verifyparam({param:value})
00287             if matchtype:
00288                value = False
00289       except Exception, instance:
00290          #ignore the exception and just return it unchecked
00291          myf[param] = value
00292       return value
00293 #
00294 #
00295     def description(self, key='splattotable', subkey=None):
00296         desc={'splattotable': 'Convert a downloaded Splatalogue spectral line list to a casa table.',
00297                'filenames': 'Files containing Splatalogue lists.',
00298                'table': 'Output table name.',
00299                'wantreturn': 'Do you want the task to return a spectralline tool attached to the results table?',
00300 
00301                'async': 'If true the taskname must be started using splattotable(...)'
00302               }
00303 
00304         if(desc.has_key(key)) :
00305            return desc[key]
00306 
00307     def itsdefault(self, paramname) :
00308         a = {}
00309         a['filenames']  = ['']
00310         a['table']  = ''
00311         a['wantreturn']  = True
00312 
00313         #a = sys._getframe(len(inspect.stack())-1).f_globals
00314 
00315         if a.has_key(paramname) :
00316               return a[paramname]
00317 splattotable_cli = splattotable_cli_()