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