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