casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imview_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_imview import imview
00018 class imview_cli_:
00019     __name__ = "imview"
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__ = (imview_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'raster':None, 'contour':None, 'zoom':None, 'axes':None, 'out':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, raster=None, contour=None, zoom=None, axes=None, out=None,  async=None):
00047 
00048         """View an image
00049         The imview task provides access to a subset of all of the configuration
00050         options for loading and configuring the display of images in the casaviewer.
00051         This interface will evolve and eventually provide access to nearly all of 
00052         the image options available in the casaviewer.
00053 
00054         To simply create a casaviewer to set up interactively, you can use:
00055 
00056             imview
00057 
00058         To open a particular image:
00059 
00060             imview "ngc5921.clean.image"
00061 
00062         to open an image and overlay a contour:
00063 
00064             imview "ngc5921.clean.image", "ngc5921.clean.image"
00065 
00066         or equivalently:
00067 
00068             imview( raster="ngc5921.clean.image", contour="ngc5921.clean.image" )
00069 
00070         to output an image:
00071 
00072             imview( raster="ngc5921.clean.image", out="ngc5921-01.png" )    
00073             
00074 
00075         There are five optional parameters for imview -- raster, contour, zoom,
00076         axes, and out. Each of these parameters can take a few different forms and 
00077         are treated as python dictionaries:
00078 
00079         raster  -- (string) image file to open
00080                    (dict)   file (string)     => image file to open
00081                             scaling (float)   => scaling power cycles
00082                             range (float*2)   => data range
00083                             colormap (string) => name of colormap
00084                             colorwedge (bool) => show color wedge?
00085         contour -- (string) file to load as a contour
00086                    (dict)   file (string)     => file to load
00087                             levels (float*N)  => relative levels
00088                             base (numeric)    => zero in relative levels
00089                             unit (numeric)    => one in the relative levels
00090         zoom    -- (int)    integral zoom level
00091                    (string) region file to load as the zoom region
00092                    (dict)   blc (numeric*2)   => bottom left corner
00093                             trc (numeric*2)   => top right corner
00094                             coord (string)    => pixel or world
00095                             channel (int)     => chanel to display
00096                    (dict)   <region record>   => record loaded
00097                                                  e.g. rg.fromfiletorecord( )
00098         axes    -- (string*3) demension to display on the x, y, and z axes
00099                    (dict)     x               => dimension for x-axes
00100                               y               => dimension for y-axes
00101                               z               => dimension for z-axes
00102         out     -- (string) file with a supported extension
00103                             [jpg, pdf, eps, ps, png, xbm, xpm, ppm]
00104                     (dict)    file (string)   => filename
00105                               format (string) => valid ext (filename ext overrides)
00106                               scale (numeric) => scale for non-eps, non-ps output
00107                               dpi (numeric)   => dpi for eps or ps output
00108                               orient (string) => portrait or landscape
00109 
00110         Examples: 
00111 
00112         1)  A subset (zoom) of a raster image. Note the notation of curly brackets:
00113 
00114             imview(raster="ngc5921.clean.image", out="ngc5921-02.png",
00115                    zoom={'channel': 10, 'blc': [113,109], 'trc': [141,136]} )
00116 
00117 
00118         2) An overlay of a raster image, ngc5921.clean.image, with a
00119         contour map of the same image ngc5921.clean.image. Data ranges
00120         are selected, as well as the colormap and the scaling cycles
00121         of the raster image. Contours are autogenerated and The x-axis
00122         will be Declination. The image is written out to a file named 
00123         myout.png in the png format.
00124 
00125         imview(raster={'file': 'ngc5921.clean.image',
00126                        'range': [-0.01,0.03],
00127                        'colormap': 'Hot Metal 2',
00128                        'scaling': -1},
00129                contour={'file': 'ngc5921.clean.image'},
00130                axes={'x':'Declination'} ,
00131                zoom={'channel': 7, 'blc': [75,75], 'trc': [175,175],
00132                      'coord': 'pixel'},
00133                out='myout.png')
00134 
00135         3) As example (2) but with an integral zoom level and no output to a file
00136 
00137         imview(raster={'file': 'ngc5921.clean.image', 
00138                        'range': [-0.01,0.03], 
00139                        'colormap': 'Hot Metal 2'}, 
00140                contour={'file': 'ngc5921.clean.image'}, 
00141                axes={'x':'Declination'} , 
00142                zoom=2)
00143 
00144         4) Now, the contour levels are explicitely given, a region file is used
00145         to define the zoom area
00146 
00147         imview(raster={'file': 'ngc5921.clean.image',
00148                        'range': [-0.01,0.03],
00149                        'colormap': 'Hot Metal 2'},
00150                contour={'file': 'ngc5921.clean.image',
00151                         'levels': [-0.2, 0.2, 0.25, 0.3, 0.35, 0.4, 0.6, 0.8] },
00152                zoom='myregion.rgn')
00153 
00154         specifying "zoom={'file': 'myregion.rgn', 'channel': 10}" would result
00155         in the same level of zoom and would display channel number 10 from
00156         the cube.
00157 
00158 
00159         
00160         """
00161         if not hasattr(self, "__globals__") or self.__globals__ == None :
00162            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00163         #casac = self.__globals__['casac']
00164         casalog = self.__globals__['casalog']
00165         #casalog = casac.casac.logsink()
00166         self.__globals__['__last_task'] = 'imview'
00167         self.__globals__['taskname'] = 'imview'
00168         ###
00169         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00170         ###
00171         ###
00172         #Handle globals or user over-ride of arguments
00173         #
00174         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00175         useLocalDefaults = False
00176 
00177         for item in function_signature_defaults.iteritems():
00178                 key,val = item
00179                 keyVal = eval(key)
00180                 if (keyVal == None):
00181                         #user hasn't set it - use global/default
00182                         pass
00183                 else:
00184                         #user has set it - use over-ride
00185                         if (key != 'self') :
00186                            useLocalDefaults = True
00187 
00188         myparams = {}
00189         if useLocalDefaults :
00190            for item in function_signature_defaults.iteritems():
00191                key,val = item
00192                keyVal = eval(key)
00193                exec('myparams[key] = keyVal')
00194                self.parameters[key] = keyVal
00195                if (keyVal == None):
00196                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00197                    keyVal = eval(key)
00198                    if(type(keyVal) == dict) :
00199                       if len(keyVal) > 0 :
00200                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00201                       else :
00202                          exec('myparams[key] = ' + key + ' = {}')
00203 
00204         else :
00205             async = self.parameters['async']
00206             myparams['raster'] = raster = self.parameters['raster']
00207             myparams['contour'] = contour = self.parameters['contour']
00208             myparams['zoom'] = zoom = self.parameters['zoom']
00209             myparams['axes'] = axes = self.parameters['axes']
00210             myparams['out'] = out = self.parameters['out']
00211 
00212 
00213         result = None
00214 
00215 #
00216 #    The following is work around to avoid a bug with current python translation
00217 #
00218         mytmp = {}
00219 
00220         mytmp['raster'] = raster
00221         mytmp['contour'] = contour
00222         mytmp['zoom'] = zoom
00223         mytmp['axes'] = axes
00224         mytmp['out'] = out
00225         #
00226         # This task is never suppose to use the task manager to run async
00227         #
00228         async=False
00229         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00230         trec = casac.casac.utils().torecord(pathname+'imview.xml')
00231 
00232         casalog.origin('imview')
00233         try :
00234           #if not trec.has_key('imview') or not casac.casac.utils().verify(mytmp, trec['imview']) :
00235             #return False
00236 
00237           casac.casac.utils().verify(mytmp, trec['imview'], True)
00238           scriptstr=['']
00239           saveinputs = self.__globals__['saveinputs']
00240           saveinputs('imview', 'imview.last', myparams, self.__globals__,scriptstr=scriptstr)
00241           if async :
00242             count = 0
00243             keybase =  time.strftime("%y%m%d.%H%M%S")
00244             key = keybase + "_" + str(count)
00245             while self.__async__.has_key(key) :
00246                count += 1
00247                key = keybase + "_" + str(count)
00248             result = tm.execute('imview', raster, contour, zoom, axes, out)
00249             print "Use: "
00250             print "      tm.retrieve(return_value) # to retrieve the status"
00251             print 
00252             self.rkey = key
00253             self.__async__[key] = result
00254           else :
00255               tname = 'imview'
00256               spaces = ' '*(18-len(tname))
00257               casalog.post('\n##########################################'+
00258                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00259               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00260               result = imview(raster, contour, zoom, axes, out)
00261               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00262                            '\n##########################################')
00263 
00264         except Exception, instance:
00265           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00266              raise
00267           else :
00268              #print '**** Error **** ',instance
00269              tname = 'imview'
00270              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00271              pass
00272 
00273         gc.collect()
00274         return result
00275 #
00276 #
00277 #
00278     def paramgui(self, useGlobals=True, ipython_globals=None):
00279         """
00280         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00281         """
00282         import paramgui
00283         if not hasattr(self, "__globals__") or self.__globals__ == None :
00284            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00285 
00286         if useGlobals:
00287             if ipython_globals == None:
00288                 myf=self.__globals__
00289             else:
00290                 myf=ipython_globals
00291 
00292             paramgui.setGlobals(myf)
00293         else:
00294             paramgui.setGlobals({})
00295 
00296         paramgui.runTask('imview', myf['_ip'])
00297         paramgui.setGlobals({})
00298 
00299 #
00300 #
00301 #
00302     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00303         if not hasattr(self, "__globals__") or self.__globals__ == None :
00304            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00305         if ipython_globals == None:
00306             myf=self.__globals__
00307         else:
00308             myf=ipython_globals
00309 
00310         a = odict()
00311         a['raster']  = {}
00312         a['contour']  = {}
00313         a['zoom']  = 1
00314         a['axes']  = {}
00315         a['out']  = ''
00316 
00317         a['async']=False
00318 
00319 ### This function sets the default values but also will return the list of
00320 ### parameters or the default value of a given parameter
00321         if(param == None):
00322                 myf['__set_default_parameters'](a)
00323         elif(param == 'paramkeys'):
00324                 return a.keys()
00325         else:
00326             if(paramvalue==None and subparam==None):
00327                if(a.has_key(param)):
00328                   return a[param]
00329                else:
00330                   return self.itsdefault(param)
00331             else:
00332                retval=a[param]
00333                if(type(a[param])==dict):
00334                   for k in range(len(a[param])):
00335                      valornotval='value'
00336                      if(a[param][k].has_key('notvalue')):
00337                         valornotval='notvalue'
00338                      if((a[param][k][valornotval])==paramvalue):
00339                         retval=a[param][k].copy()
00340                         retval.pop(valornotval)
00341                         if(subparam != None):
00342                            if(retval.has_key(subparam)):
00343                               retval=retval[subparam]
00344                            else:
00345                               retval=self.itsdefault(subparam)
00346                      else:
00347                         retval=self.itsdefault(subparam)
00348                return retval
00349 
00350 
00351 #
00352 #
00353     def check_params(self, param=None, value=None, ipython_globals=None):
00354       if ipython_globals == None:
00355           myf=self.__globals__
00356       else:
00357           myf=ipython_globals
00358 #      print 'param:', param, 'value:', value
00359       try :
00360          if str(type(value)) != "<type 'instance'>" :
00361             value0 = value
00362             value = myf['cu'].expandparam(param, value)
00363             matchtype = False
00364             if(type(value) == numpy.ndarray):
00365                if(type(value) == type(value0)):
00366                   myf[param] = value.tolist()
00367                else:
00368                   #print 'value:', value, 'value0:', value0
00369                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00370                   myf[param] = value0
00371                   if type(value0) != list :
00372                      matchtype = True
00373             else :
00374                myf[param] = value
00375             value = myf['cu'].verifyparam({param:value})
00376             if matchtype:
00377                value = False
00378       except Exception, instance:
00379          #ignore the exception and just return it unchecked
00380          myf[param] = value
00381       return value
00382 #
00383 #
00384     def description(self, key='imview', subkey=None):
00385         desc={'imview': 'View an image',
00386                'raster': '(Optional)  Raster filename (string) or complete raster config dictionary. The allowed dictionary keys are file (string), scaling (numeric), range (2 element numeric vector), colormap (string), and colorwedge (bool).',
00387                'contour': '(Optional)  Contour filename (string) or complete contour config dictionary. The allowed dictionary keys are file (string), levels (numeric vector), unit (float), and base (float).',
00388                'zoom': '(Optional)  zoom can specify intermental zoom (integer), zoom region read from a file (string) or dictionary specifying the zoom region. The dictionary can have two forms. It can be either a simple region specified with blc (2 element vector) and trc (2 element vector) [along with an optional coord key ("pixel" or "world"; pixel is the default) or a complete region rectangle e.g. loaded with "rg.fromfiletorecord( )". The dictionary can also contain a channel (integer) field which indicates which channel should be displayed.',
00389                'axes': '(Optional)  this can either be a three element vector (string) where each element describes what should be found on each of the x, y, and z axes or a dictionary containing fields "x", "y" and "z" (string).',
00390                'out': '(Optional)  Output filename or complete output config dictionary. If a string is passed, the file extension is used to determine the output type (jpg, pdf, eps, ps, png, xbm, xpm, or ppm). If a dictionary is passed, it can contain the fields, file (string), scale (float), dpi (int), or orient (landscape or portrait). The scale field is used for the bitmap formats (i.e. not ps or pdf) and the dpi parameter is used for scalable formats (pdf or ps).',
00391 
00392                'async': 'If true the taskname must be started using imview(...)'
00393               }
00394 
00395 #
00396 # Set subfields defaults if needed
00397 #
00398 
00399         if(desc.has_key(key)) :
00400            return desc[key]
00401 
00402     def itsdefault(self, paramname) :
00403         a = {}
00404         a['raster']  = {}
00405         a['contour']  = {}
00406         a['zoom']  = 1
00407         a['axes']  = {}
00408         a['out']  = ''
00409 
00410         #a = sys._getframe(len(inspect.stack())-1).f_globals
00411 
00412         if a.has_key(paramname) :
00413               return a[paramname]
00414 imview_cli = imview_cli_()