casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
plotants_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_plotants import plotants
00018 class plotants_cli_:
00019     __name__ = "plotants"
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__ = (plotants_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'figfile':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, vis=None, figfile=None,  async=None):
00047 
00048         """Plot the antenna distribution in the local reference frame:
00049        Plot the antenna distribution in the local reference frame:
00050 
00051        The location of the antennas in the MS will be plotted with
00052        X-toward local east; Y-toward local north.
00053 
00054        Keyword arguments:
00055        vis -- Name of input visibility file.
00056                default: none. example: vis='ngc5921.ms'
00057 
00058        figfile -- Save the plotted figure in this file.
00059                default: ''. example: figfile='myFigure.png'
00060 
00061                The name of each antenna (egs. vla=antenna number) is
00062                   shown next to its respective location.
00063 
00064                DO NOT use the buttons on the Mark Region line.  These are
00065                   not implemented yet and might abort CASA.
00066 
00067                You can zoom in by pressing the magnifier button (bottom,
00068                   third from left) and making a rectangular region with
00069                   the mouse.  Press the home button (left most button) to
00070                   remove zoom.
00071 
00072                A hard-copy of this plot can be obtained by pressing the
00073                   button on the right at the bottom of the display.  This
00074                   produces a png format file.
00075  
00076         """
00077         if not hasattr(self, "__globals__") or self.__globals__ == None :
00078            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00079         #casac = self.__globals__['casac']
00080         casalog = self.__globals__['casalog']
00081         #casalog = casac.casac.logsink()
00082         self.__globals__['__last_task'] = 'plotants'
00083         self.__globals__['taskname'] = 'plotants'
00084         ###
00085         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00086         ###
00087         ###
00088         #Handle globals or user over-ride of arguments
00089         #
00090         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00091         useLocalDefaults = False
00092 
00093         for item in function_signature_defaults.iteritems():
00094                 key,val = item
00095                 keyVal = eval(key)
00096                 if (keyVal == None):
00097                         #user hasn't set it - use global/default
00098                         pass
00099                 else:
00100                         #user has set it - use over-ride
00101                         if (key != 'self') :
00102                            useLocalDefaults = True
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                self.parameters[key] = keyVal
00111                if (keyVal == None):
00112                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00113                    keyVal = eval(key)
00114                    if(type(keyVal) == dict) :
00115                       if len(keyVal) > 0 :
00116                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00117                       else :
00118                          exec('myparams[key] = ' + key + ' = {}')
00119 
00120         else :
00121             async = self.parameters['async']
00122             myparams['vis'] = vis = self.parameters['vis']
00123             myparams['figfile'] = figfile = self.parameters['figfile']
00124 
00125 
00126         result = None
00127 
00128 #
00129 #    The following is work around to avoid a bug with current python translation
00130 #
00131         mytmp = {}
00132 
00133         mytmp['vis'] = vis
00134         mytmp['figfile'] = figfile
00135         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00136         trec = casac.casac.utils().torecord(pathname+'plotants.xml')
00137 
00138         casalog.origin('plotants')
00139         try :
00140           #if not trec.has_key('plotants') or not casac.casac.utils().verify(mytmp, trec['plotants']) :
00141             #return False
00142 
00143           casac.casac.utils().verify(mytmp, trec['plotants'], True)
00144           scriptstr=['']
00145           saveinputs = self.__globals__['saveinputs']
00146           saveinputs('plotants', 'plotants.last', myparams, self.__globals__,scriptstr=scriptstr)
00147           if async :
00148             count = 0
00149             keybase =  time.strftime("%y%m%d.%H%M%S")
00150             key = keybase + "_" + str(count)
00151             while self.__async__.has_key(key) :
00152                count += 1
00153                key = keybase + "_" + str(count)
00154             result = tm.execute('plotants', vis, figfile)
00155             print "Use: "
00156             print "      tm.retrieve(return_value) # to retrieve the status"
00157             print 
00158             self.rkey = key
00159             self.__async__[key] = result
00160           else :
00161               tname = 'plotants'
00162               spaces = ' '*(18-len(tname))
00163               casalog.post('\n##########################################'+
00164                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00165               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00166               result = plotants(vis, figfile)
00167               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00168                            '\n##########################################')
00169 
00170         except Exception, instance:
00171           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00172              raise
00173           else :
00174              #print '**** Error **** ',instance
00175              tname = 'plotants'
00176              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00177              pass
00178 
00179         gc.collect()
00180         return result
00181 #
00182 #
00183 #
00184     def paramgui(self, useGlobals=True, ipython_globals=None):
00185         """
00186         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00187         """
00188         import paramgui
00189         if not hasattr(self, "__globals__") or self.__globals__ == None :
00190            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00191 
00192         if useGlobals:
00193             if ipython_globals == None:
00194                 myf=self.__globals__
00195             else:
00196                 myf=ipython_globals
00197 
00198             paramgui.setGlobals(myf)
00199         else:
00200             paramgui.setGlobals({})
00201 
00202         paramgui.runTask('plotants', myf['_ip'])
00203         paramgui.setGlobals({})
00204 
00205 #
00206 #
00207 #
00208     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00209         if not hasattr(self, "__globals__") or self.__globals__ == None :
00210            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00211         if ipython_globals == None:
00212             myf=self.__globals__
00213         else:
00214             myf=ipython_globals
00215 
00216         a = odict()
00217         a['vis']  = ''
00218         a['figfile']  = ''
00219 
00220         a['async']=False
00221 
00222 ### This function sets the default values but also will return the list of
00223 ### parameters or the default value of a given parameter
00224         if(param == None):
00225                 myf['__set_default_parameters'](a)
00226         elif(param == 'paramkeys'):
00227                 return a.keys()
00228         else:
00229             if(paramvalue==None and subparam==None):
00230                if(a.has_key(param)):
00231                   return a[param]
00232                else:
00233                   return self.itsdefault(param)
00234             else:
00235                retval=a[param]
00236                if(type(a[param])==dict):
00237                   for k in range(len(a[param])):
00238                      valornotval='value'
00239                      if(a[param][k].has_key('notvalue')):
00240                         valornotval='notvalue'
00241                      if((a[param][k][valornotval])==paramvalue):
00242                         retval=a[param][k].copy()
00243                         retval.pop(valornotval)
00244                         if(subparam != None):
00245                            if(retval.has_key(subparam)):
00246                               retval=retval[subparam]
00247                            else:
00248                               retval=self.itsdefault(subparam)
00249                      else:
00250                         retval=self.itsdefault(subparam)
00251                return retval
00252 
00253 
00254 #
00255 #
00256     def check_params(self, param=None, value=None, ipython_globals=None):
00257       if ipython_globals == None:
00258           myf=self.__globals__
00259       else:
00260           myf=ipython_globals
00261 #      print 'param:', param, 'value:', value
00262       try :
00263          if str(type(value)) != "<type 'instance'>" :
00264             value0 = value
00265             value = myf['cu'].expandparam(param, value)
00266             matchtype = False
00267             if(type(value) == numpy.ndarray):
00268                if(type(value) == type(value0)):
00269                   myf[param] = value.tolist()
00270                else:
00271                   #print 'value:', value, 'value0:', value0
00272                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00273                   myf[param] = value0
00274                   if type(value0) != list :
00275                      matchtype = True
00276             else :
00277                myf[param] = value
00278             value = myf['cu'].verifyparam({param:value})
00279             if matchtype:
00280                value = False
00281       except Exception, instance:
00282          #ignore the exception and just return it unchecked
00283          myf[param] = value
00284       return value
00285 #
00286 #
00287     def description(self, key='plotants', subkey=None):
00288         desc={'plotants': 'Plot the antenna distribution in the local reference frame:',
00289                'vis': 'Name of input visibility file (MS)',
00290                'figfile': 'Save the plotted figure to this file',
00291 
00292                'async': 'If true the taskname must be started using plotants(...)'
00293               }
00294 
00295         if(desc.has_key(key)) :
00296            return desc[key]
00297 
00298     def itsdefault(self, paramname) :
00299         a = {}
00300         a['vis']  = ''
00301         a['figfile']  = ''
00302 
00303         #a = sys._getframe(len(inspect.stack())-1).f_globals
00304 
00305         if a.has_key(paramname) :
00306               return a[paramname]
00307 plotants_cli = plotants_cli_()