casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
find_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_find import find
00018 class find_cli_:
00019     __name__ = "find"
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__ = (find_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'matchstring':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, matchstring=None,  async=None):
00047 
00048         """Find string in tasks, task names, parameter names:
00049 
00050        Find string in tasks, task names, parameter names:
00051 
00052         Lists the following:
00053                 1) All of the task names that have the string
00054                 2) All of the tasks whose  contents (e.g., documentation,
00055                 parameters, etc) have the string
00056                 3) All of the parameter names that have the string
00057 
00058        Keyword arguments:
00059        matchstring -- String to match in the documentation
00060                default: ''; example: matchstring='vis'
00061  
00062         """
00063         if not hasattr(self, "__globals__") or self.__globals__ == None :
00064            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00065         #casac = self.__globals__['casac']
00066         casalog = self.__globals__['casalog']
00067         #casalog = casac.casac.logsink()
00068         self.__globals__['__last_task'] = 'find'
00069         self.__globals__['taskname'] = 'find'
00070         ###
00071         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00072         ###
00073         ###
00074         #Handle globals or user over-ride of arguments
00075         #
00076         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00077         useLocalDefaults = False
00078 
00079         for item in function_signature_defaults.iteritems():
00080                 key,val = item
00081                 keyVal = eval(key)
00082                 if (keyVal == None):
00083                         #user hasn't set it - use global/default
00084                         pass
00085                 else:
00086                         #user has set it - use over-ride
00087                         if (key != 'self') :
00088                            useLocalDefaults = True
00089 
00090         myparams = {}
00091         if useLocalDefaults :
00092            for item in function_signature_defaults.iteritems():
00093                key,val = item
00094                keyVal = eval(key)
00095                exec('myparams[key] = keyVal')
00096                self.parameters[key] = keyVal
00097                if (keyVal == None):
00098                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00099                    keyVal = eval(key)
00100                    if(type(keyVal) == dict) :
00101                       if len(keyVal) > 0 :
00102                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00103                       else :
00104                          exec('myparams[key] = ' + key + ' = {}')
00105 
00106         else :
00107             async = self.parameters['async']
00108             myparams['matchstring'] = matchstring = self.parameters['matchstring']
00109 
00110 
00111         result = None
00112 
00113 #
00114 #    The following is work around to avoid a bug with current python translation
00115 #
00116         mytmp = {}
00117 
00118         mytmp['matchstring'] = matchstring
00119         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00120         trec = casac.casac.utils().torecord(pathname+'find.xml')
00121 
00122         casalog.origin('find')
00123         try :
00124           #if not trec.has_key('find') or not casac.casac.utils().verify(mytmp, trec['find']) :
00125             #return False
00126 
00127           casac.casac.utils().verify(mytmp, trec['find'], True)
00128           scriptstr=['']
00129           saveinputs = self.__globals__['saveinputs']
00130           saveinputs('find', 'find.last', myparams, self.__globals__,scriptstr=scriptstr)
00131           if async :
00132             count = 0
00133             keybase =  time.strftime("%y%m%d.%H%M%S")
00134             key = keybase + "_" + str(count)
00135             while self.__async__.has_key(key) :
00136                count += 1
00137                key = keybase + "_" + str(count)
00138             result = tm.execute('find', matchstring)
00139             print "Use: "
00140             print "      tm.retrieve(return_value) # to retrieve the status"
00141             print 
00142             self.rkey = key
00143             self.__async__[key] = result
00144           else :
00145               tname = 'find'
00146               spaces = ' '*(18-len(tname))
00147               casalog.post('\n##########################################'+
00148                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00149               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00150               result = find(matchstring)
00151               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00152                            '\n##########################################')
00153 
00154         except Exception, instance:
00155           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00156              raise
00157           else :
00158              #print '**** Error **** ',instance
00159              tname = 'find'
00160              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00161              pass
00162 
00163         gc.collect()
00164         return result
00165 #
00166 #
00167 #
00168     def paramgui(self, useGlobals=True, ipython_globals=None):
00169         """
00170         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00171         """
00172         import paramgui
00173         if not hasattr(self, "__globals__") or self.__globals__ == None :
00174            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00175 
00176         if useGlobals:
00177             if ipython_globals == None:
00178                 myf=self.__globals__
00179             else:
00180                 myf=ipython_globals
00181 
00182             paramgui.setGlobals(myf)
00183         else:
00184             paramgui.setGlobals({})
00185 
00186         paramgui.runTask('find', myf['_ip'])
00187         paramgui.setGlobals({})
00188 
00189 #
00190 #
00191 #
00192     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00193         if not hasattr(self, "__globals__") or self.__globals__ == None :
00194            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00195         if ipython_globals == None:
00196             myf=self.__globals__
00197         else:
00198             myf=ipython_globals
00199 
00200         a = odict()
00201         a['matchstring']  = ''
00202 
00203         a['async']=False
00204 
00205 ### This function sets the default values but also will return the list of
00206 ### parameters or the default value of a given parameter
00207         if(param == None):
00208                 myf['__set_default_parameters'](a)
00209         elif(param == 'paramkeys'):
00210                 return a.keys()
00211         else:
00212             if(paramvalue==None and subparam==None):
00213                if(a.has_key(param)):
00214                   return a[param]
00215                else:
00216                   return self.itsdefault(param)
00217             else:
00218                retval=a[param]
00219                if(type(a[param])==dict):
00220                   for k in range(len(a[param])):
00221                      valornotval='value'
00222                      if(a[param][k].has_key('notvalue')):
00223                         valornotval='notvalue'
00224                      if((a[param][k][valornotval])==paramvalue):
00225                         retval=a[param][k].copy()
00226                         retval.pop(valornotval)
00227                         if(subparam != None):
00228                            if(retval.has_key(subparam)):
00229                               retval=retval[subparam]
00230                            else:
00231                               retval=self.itsdefault(subparam)
00232                      else:
00233                         retval=self.itsdefault(subparam)
00234                return retval
00235 
00236 
00237 #
00238 #
00239     def check_params(self, param=None, value=None, ipython_globals=None):
00240       if ipython_globals == None:
00241           myf=self.__globals__
00242       else:
00243           myf=ipython_globals
00244 #      print 'param:', param, 'value:', value
00245       try :
00246          if str(type(value)) != "<type 'instance'>" :
00247             value0 = value
00248             value = myf['cu'].expandparam(param, value)
00249             matchtype = False
00250             if(type(value) == numpy.ndarray):
00251                if(type(value) == type(value0)):
00252                   myf[param] = value.tolist()
00253                else:
00254                   #print 'value:', value, 'value0:', value0
00255                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00256                   myf[param] = value0
00257                   if type(value0) != list :
00258                      matchtype = True
00259             else :
00260                myf[param] = value
00261             value = myf['cu'].verifyparam({param:value})
00262             if matchtype:
00263                value = False
00264       except Exception, instance:
00265          #ignore the exception and just return it unchecked
00266          myf[param] = value
00267       return value
00268 #
00269 #
00270     def description(self, key='find', subkey=None):
00271         desc={'find': 'Find string in tasks, task names, parameter names:',
00272                'matchstring': 'String to match in the documentation',
00273 
00274                'async': 'If true the taskname must be started using find(...)'
00275               }
00276 
00277         if(desc.has_key(key)) :
00278            return desc[key]
00279 
00280     def itsdefault(self, paramname) :
00281         a = {}
00282         a['matchstring']  = ''
00283 
00284         #a = sys._getframe(len(inspect.stack())-1).f_globals
00285 
00286         if a.has_key(paramname) :
00287               return a[paramname]
00288 find_cli = find_cli_()