casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
msview_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_msview import msview
00018 class msview_cli_:
00019     __name__ = "msview"
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__ = (msview_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'infile':None, 'displaytype':None, 'channel':None, 'zoom':None, 'outfile':None, 'outscale':None, 'outdpi':None, 'outformat':None, 'outlandscape':None, 'gui':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, infile=None, displaytype=None, channel=None, zoom=None, outfile=None, outscale=None, outdpi=None, outformat=None, outlandscape=None, gui=None,  async=None):
00047 
00048         """View a visibility data set
00049 
00050         examples of usage:
00051 
00052         msview
00053         msview "mymeasurementset.ms"
00054         msview "myrestorefile.rstr"
00055         
00056         Keyword arguments:
00057         infile -- Name of file to visualize
00058                 default: ''
00059                 example: infile='my.ms'
00060                 If no infile is specified the Load Data window
00061                 will appear for selecting data.
00062         displaytype -- (optional): method of rendering data
00063                 visually (raster, contour, vector or marker).  
00064                 You can also set this parameter to 'lel' and
00065                 provide an lel expression for infile (advanced).
00066                 default: 'raster'
00067 
00068         Note: there is no longer a filetype parameter; typing of
00069         data files is now done automatically.
00070                 example:  msview infile='my.ms'
00071                 obsolete: msview infile='my.ms', filetype='ms'
00072 
00073         
00074         """
00075         if not hasattr(self, "__globals__") or self.__globals__ == None :
00076            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00077         #casac = self.__globals__['casac']
00078         casalog = self.__globals__['casalog']
00079         #casalog = casac.casac.logsink()
00080         self.__globals__['__last_task'] = 'msview'
00081         self.__globals__['taskname'] = 'msview'
00082         ###
00083         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00084         ###
00085         ###
00086         #Handle globals or user over-ride of arguments
00087         #
00088         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00089         useLocalDefaults = False
00090 
00091         for item in function_signature_defaults.iteritems():
00092                 key,val = item
00093                 keyVal = eval(key)
00094                 if (keyVal == None):
00095                         #user hasn't set it - use global/default
00096                         pass
00097                 else:
00098                         #user has set it - use over-ride
00099                         if (key != 'self') :
00100                            useLocalDefaults = True
00101 
00102         myparams = {}
00103         if useLocalDefaults :
00104            for item in function_signature_defaults.iteritems():
00105                key,val = item
00106                keyVal = eval(key)
00107                exec('myparams[key] = keyVal')
00108                self.parameters[key] = keyVal
00109                if (keyVal == None):
00110                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00111                    keyVal = eval(key)
00112                    if(type(keyVal) == dict) :
00113                       if len(keyVal) > 0 :
00114                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00115                       else :
00116                          exec('myparams[key] = ' + key + ' = {}')
00117 
00118         else :
00119             async = self.parameters['async']
00120             myparams['infile'] = infile = self.parameters['infile']
00121             myparams['displaytype'] = displaytype = self.parameters['displaytype']
00122             myparams['channel'] = channel = self.parameters['channel']
00123             myparams['zoom'] = zoom = self.parameters['zoom']
00124             myparams['outfile'] = outfile = self.parameters['outfile']
00125             myparams['outscale'] = outscale = self.parameters['outscale']
00126             myparams['outdpi'] = outdpi = self.parameters['outdpi']
00127             myparams['outformat'] = outformat = self.parameters['outformat']
00128             myparams['outlandscape'] = outlandscape = self.parameters['outlandscape']
00129             myparams['gui'] = gui = self.parameters['gui']
00130 
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['infile'] = infile
00140         mytmp['displaytype'] = displaytype
00141         mytmp['channel'] = channel
00142         mytmp['zoom'] = zoom
00143         mytmp['outfile'] = outfile
00144         mytmp['outscale'] = outscale
00145         mytmp['outdpi'] = outdpi
00146         mytmp['outformat'] = outformat
00147         mytmp['outlandscape'] = outlandscape
00148         mytmp['gui'] = gui
00149         #
00150         # This task is never suppose to use the task manager to run async
00151         #
00152         async=False
00153         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00154         trec = casac.casac.utils().torecord(pathname+'msview.xml')
00155 
00156         casalog.origin('msview')
00157         try :
00158           #if not trec.has_key('msview') or not casac.casac.utils().verify(mytmp, trec['msview']) :
00159             #return False
00160 
00161           casac.casac.utils().verify(mytmp, trec['msview'], True)
00162           scriptstr=['']
00163           saveinputs = self.__globals__['saveinputs']
00164           saveinputs('msview', 'msview.last', myparams, self.__globals__,scriptstr=scriptstr)
00165           if async :
00166             count = 0
00167             keybase =  time.strftime("%y%m%d.%H%M%S")
00168             key = keybase + "_" + str(count)
00169             while self.__async__.has_key(key) :
00170                count += 1
00171                key = keybase + "_" + str(count)
00172             result = tm.execute('msview', infile, displaytype, channel, zoom, outfile, outscale, outdpi, outformat, outlandscape, gui)
00173             print "Use: "
00174             print "      tm.retrieve(return_value) # to retrieve the status"
00175             print 
00176             self.rkey = key
00177             self.__async__[key] = result
00178           else :
00179               tname = 'msview'
00180               spaces = ' '*(18-len(tname))
00181               casalog.post('\n##########################################'+
00182                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00183               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00184               result = msview(infile, displaytype, channel, zoom, outfile, outscale, outdpi, outformat, outlandscape, gui)
00185               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00186                            '\n##########################################')
00187 
00188         except Exception, instance:
00189           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00190              raise
00191           else :
00192              #print '**** Error **** ',instance
00193              tname = 'msview'
00194              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00195              pass
00196 
00197         gc.collect()
00198         return result
00199 #
00200 #
00201 #
00202     def paramgui(self, useGlobals=True, ipython_globals=None):
00203         """
00204         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00205         """
00206         import paramgui
00207         if not hasattr(self, "__globals__") or self.__globals__ == None :
00208            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00209 
00210         if useGlobals:
00211             if ipython_globals == None:
00212                 myf=self.__globals__
00213             else:
00214                 myf=ipython_globals
00215 
00216             paramgui.setGlobals(myf)
00217         else:
00218             paramgui.setGlobals({})
00219 
00220         paramgui.runTask('msview', myf['_ip'])
00221         paramgui.setGlobals({})
00222 
00223 #
00224 #
00225 #
00226     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00227         if not hasattr(self, "__globals__") or self.__globals__ == None :
00228            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00229         if ipython_globals == None:
00230             myf=self.__globals__
00231         else:
00232             myf=ipython_globals
00233 
00234         a = odict()
00235         a['infile']  = ''
00236         a['displaytype']  = 'raster'
00237         a['channel']  = 0
00238         a['zoom']  = 1
00239         a['outfile']  = ''
00240         a['outscale']  = 1.0
00241         a['outdpi']  = 300
00242         a['outformat']  = 'jpg'
00243         a['outlandscape']  = False
00244         a['gui']  = True
00245 
00246         a['async']=False
00247 
00248 ### This function sets the default values but also will return the list of
00249 ### parameters or the default value of a given parameter
00250         if(param == None):
00251                 myf['__set_default_parameters'](a)
00252         elif(param == 'paramkeys'):
00253                 return a.keys()
00254         else:
00255             if(paramvalue==None and subparam==None):
00256                if(a.has_key(param)):
00257                   return a[param]
00258                else:
00259                   return self.itsdefault(param)
00260             else:
00261                retval=a[param]
00262                if(type(a[param])==dict):
00263                   for k in range(len(a[param])):
00264                      valornotval='value'
00265                      if(a[param][k].has_key('notvalue')):
00266                         valornotval='notvalue'
00267                      if((a[param][k][valornotval])==paramvalue):
00268                         retval=a[param][k].copy()
00269                         retval.pop(valornotval)
00270                         if(subparam != None):
00271                            if(retval.has_key(subparam)):
00272                               retval=retval[subparam]
00273                            else:
00274                               retval=self.itsdefault(subparam)
00275                      else:
00276                         retval=self.itsdefault(subparam)
00277                return retval
00278 
00279 
00280 #
00281 #
00282     def check_params(self, param=None, value=None, ipython_globals=None):
00283       if ipython_globals == None:
00284           myf=self.__globals__
00285       else:
00286           myf=ipython_globals
00287 #      print 'param:', param, 'value:', value
00288       try :
00289          if str(type(value)) != "<type 'instance'>" :
00290             value0 = value
00291             value = myf['cu'].expandparam(param, value)
00292             matchtype = False
00293             if(type(value) == numpy.ndarray):
00294                if(type(value) == type(value0)):
00295                   myf[param] = value.tolist()
00296                else:
00297                   #print 'value:', value, 'value0:', value0
00298                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00299                   myf[param] = value0
00300                   if type(value0) != list :
00301                      matchtype = True
00302             else :
00303                myf[param] = value
00304             value = myf['cu'].verifyparam({param:value})
00305             if matchtype:
00306                value = False
00307       except Exception, instance:
00308          #ignore the exception and just return it unchecked
00309          myf[param] = value
00310       return value
00311 #
00312 #
00313     def description(self, key='msview', subkey=None):
00314         desc={'msview': 'View a visibility data set',
00315                'infile': ' (Optional)  Name of file to visualize.',
00316                'displaytype': ' (Optional)  Type of visual rendering (raster, contour, vector or marker).  lel  if an lel expression is given for infile  (advanced).',
00317                'channel': ' (Optional)  access a specific channel in the image cube',
00318                'zoom': ' (Optional)  zoom in/out by increments',
00319                'outfile': ' (Optional)  name of the output file to generate',
00320                'outscale': ' (Optional)  amount to scale output bitmap formats (non-PS, non-PDF)',
00321                'outdpi': ' (Optional)  output DPI for PS/PDF',
00322                'outformat': ' (Optional)  format of the output e.g. jpg or pdf (this is overridden by the output files extension',
00323                'outlandscape': ' (Optional)  should the output mode be landscape (PS or PDF)',
00324                'gui': ' (Optional)  Display the panel in a GUI.',
00325 
00326                'async': 'If true the taskname must be started using msview(...)'
00327               }
00328 
00329 #
00330 # Set subfields defaults if needed
00331 #
00332 
00333         if(desc.has_key(key)) :
00334            return desc[key]
00335 
00336     def itsdefault(self, paramname) :
00337         a = {}
00338         a['infile']  = ''
00339         a['displaytype']  = 'raster'
00340         a['channel']  = 0
00341         a['zoom']  = 1
00342         a['outfile']  = ''
00343         a['outscale']  = 1.0
00344         a['outdpi']  = 300
00345         a['outformat']  = 'jpg'
00346         a['outlandscape']  = False
00347         a['gui']  = True
00348 
00349         #a = sys._getframe(len(inspect.stack())-1).f_globals
00350 
00351         if a.has_key(paramname) :
00352               return a[paramname]
00353 msview_cli = msview_cli_()