casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imsubimage_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_imsubimage import imsubimage
00018 class imsubimage_cli_:
00019     __name__ = "imsubimage"
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__ = (imsubimage_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'outfile':None, 'region':None, 'mask':None, 'dropdeg':None, 'overwrite':None, 'verbose':None, 'stretch':None, 'wantreturn':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, imagename=None, outfile=None, region=None, mask=None, dropdeg=None, overwrite=None, verbose=None, stretch=None, wantreturn=None,  async=None):
00047 
00048         """Create a (sub)image from a region of the image
00049 PARAMETER SUMMARY
00050 imagename        Name of the input image
00051 outfile          Name of output file. Empty means create a temporary image and return it.
00052 region           Region of interest. See help par.region for specification options. Default ("") is entire image.
00053 mask             Mask to use. See help par.mask. Default ("") is none.
00054 dropdeg          If True, all degenerate axes in the input image will be excluded in the output image.
00055 overwrite        If True, a pre-existing file of the same name as outfile will be overwritten.
00056 verbose          Post additional informative messages to the logger.
00057 stretch          Stretch the input mask if necessary and possible. Only used if a mask is specified.
00058                  See help par.stretch.
00059 
00060 OVERVIEW
00061 
00062 This task copies all or part of the image to another on-the-fly Image tool.
00063 If {\stfaf outfile} is given, the subimage is written to the specified
00064 disk file.  If {\stfaf outfile} is unset, the returned Image \tool\ actually
00065 references the input image file (i.e.  that associated with the Image
00066 \tool\ to which you are applying this function).  So if you deleted the
00067 input image disk file, it would render this \tool\ useless.  When you destroy this
00068 \tool\ (with the done function)
00069 the reference connection is broken. 
00070 
00071 Sometimes it is useful to drop axes of length one (degenerate axes).
00072 Set {\stfaf dropdeg} equal to True if you want to do this.
00073 
00074 The output mask is the combination (logical OR) of the default input
00075 \pixelmask\ (if any) and the OTF mask.  Any other input \pixelmasks\
00076 will not be copied.  Use function maskhandler if you
00077 need to copy other masks too.
00078 
00079 If the mask has fewer dimensions than the image and if the shape
00080 of the dimensions the mask and image have in common are the same,
00081 the mask will automatically have the missing dimensions added so
00082 it conforms to the image.
00083 
00084 If stretch is true and if the number of mask dimensions is less than
00085 or equal to the number of image dimensions and some axes in the
00086 mask are degenerate while the corresponding axes in the image are not,
00087 the mask will be stetched in the degenerate dimensions. For example,
00088 if the input image has shape [100, 200, 10] and the input
00089 mask has shape [100, 200, 1] and stretch is true, the mask will be
00090 stretched along the third dimension to shape [100, 200, 10]. However if
00091 the mask is shape [100, 200, 2], stretching is not possible and an
00092 error will result.
00093 
00094 
00095         """
00096         if not hasattr(self, "__globals__") or self.__globals__ == None :
00097            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00098         #casac = self.__globals__['casac']
00099         casalog = self.__globals__['casalog']
00100         #casalog = casac.casac.logsink()
00101         self.__globals__['__last_task'] = 'imsubimage'
00102         self.__globals__['taskname'] = 'imsubimage'
00103         ###
00104         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00105         ###
00106         ###
00107         #Handle globals or user over-ride of arguments
00108         #
00109         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00110         useLocalDefaults = False
00111 
00112         for item in function_signature_defaults.iteritems():
00113                 key,val = item
00114                 keyVal = eval(key)
00115                 if (keyVal == None):
00116                         #user hasn't set it - use global/default
00117                         pass
00118                 else:
00119                         #user has set it - use over-ride
00120                         if (key != 'self') :
00121                            useLocalDefaults = True
00122 
00123         myparams = {}
00124         if useLocalDefaults :
00125            for item in function_signature_defaults.iteritems():
00126                key,val = item
00127                keyVal = eval(key)
00128                exec('myparams[key] = keyVal')
00129                self.parameters[key] = keyVal
00130                if (keyVal == None):
00131                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00132                    keyVal = eval(key)
00133                    if(type(keyVal) == dict) :
00134                       if len(keyVal) > 0 :
00135                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00136                       else :
00137                          exec('myparams[key] = ' + key + ' = {}')
00138 
00139         else :
00140             async = self.parameters['async']
00141             myparams['imagename'] = imagename = self.parameters['imagename']
00142             myparams['outfile'] = outfile = self.parameters['outfile']
00143             myparams['region'] = region = self.parameters['region']
00144             myparams['mask'] = mask = self.parameters['mask']
00145             myparams['dropdeg'] = dropdeg = self.parameters['dropdeg']
00146             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00147             myparams['verbose'] = verbose = self.parameters['verbose']
00148             myparams['stretch'] = stretch = self.parameters['stretch']
00149             myparams['wantreturn'] = wantreturn = self.parameters['wantreturn']
00150 
00151 
00152         result = None
00153 
00154 #
00155 #    The following is work around to avoid a bug with current python translation
00156 #
00157         mytmp = {}
00158 
00159         mytmp['imagename'] = imagename
00160         mytmp['outfile'] = outfile
00161         mytmp['region'] = region
00162         mytmp['mask'] = mask
00163         mytmp['dropdeg'] = dropdeg
00164         mytmp['overwrite'] = overwrite
00165         mytmp['verbose'] = verbose
00166         mytmp['stretch'] = stretch
00167         mytmp['wantreturn'] = wantreturn
00168         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00169         trec = casac.casac.utils().torecord(pathname+'imsubimage.xml')
00170 
00171         casalog.origin('imsubimage')
00172         try :
00173           #if not trec.has_key('imsubimage') or not casac.casac.utils().verify(mytmp, trec['imsubimage']) :
00174             #return False
00175 
00176           casac.casac.utils().verify(mytmp, trec['imsubimage'], True)
00177           scriptstr=['']
00178           saveinputs = self.__globals__['saveinputs']
00179           saveinputs('imsubimage', 'imsubimage.last', myparams, self.__globals__,scriptstr=scriptstr)
00180           if async :
00181             count = 0
00182             keybase =  time.strftime("%y%m%d.%H%M%S")
00183             key = keybase + "_" + str(count)
00184             while self.__async__.has_key(key) :
00185                count += 1
00186                key = keybase + "_" + str(count)
00187             result = tm.execute('imsubimage', imagename, outfile, region, mask, dropdeg, overwrite, verbose, stretch, wantreturn)
00188             print "Use: "
00189             print "      tm.retrieve(return_value) # to retrieve the status"
00190             print 
00191             self.rkey = key
00192             self.__async__[key] = result
00193           else :
00194               tname = 'imsubimage'
00195               spaces = ' '*(18-len(tname))
00196               casalog.post('\n##########################################'+
00197                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00198               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00199               result = imsubimage(imagename, outfile, region, mask, dropdeg, overwrite, verbose, stretch, wantreturn)
00200               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00201                            '\n##########################################')
00202 
00203         except Exception, instance:
00204           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00205              raise
00206           else :
00207              #print '**** Error **** ',instance
00208              tname = 'imsubimage'
00209              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00210              pass
00211 
00212         gc.collect()
00213         return result
00214 #
00215 #
00216 #
00217     def paramgui(self, useGlobals=True, ipython_globals=None):
00218         """
00219         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00220         """
00221         import paramgui
00222         if not hasattr(self, "__globals__") or self.__globals__ == None :
00223            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00224 
00225         if useGlobals:
00226             if ipython_globals == None:
00227                 myf=self.__globals__
00228             else:
00229                 myf=ipython_globals
00230 
00231             paramgui.setGlobals(myf)
00232         else:
00233             paramgui.setGlobals({})
00234 
00235         paramgui.runTask('imsubimage', myf['_ip'])
00236         paramgui.setGlobals({})
00237 
00238 #
00239 #
00240 #
00241     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00242         if not hasattr(self, "__globals__") or self.__globals__ == None :
00243            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00244         if ipython_globals == None:
00245             myf=self.__globals__
00246         else:
00247             myf=ipython_globals
00248 
00249         a = odict()
00250         a['imagename']  = ''
00251         a['outfile']  = ''
00252         a['region']  = ''
00253         a['mask']  = ''
00254         a['dropdeg']  = False
00255         a['overwrite']  = False
00256         a['verbose']  = True
00257         a['stretch']  = False
00258         a['wantreturn']  = True
00259 
00260         a['async']=False
00261 
00262 ### This function sets the default values but also will return the list of
00263 ### parameters or the default value of a given parameter
00264         if(param == None):
00265                 myf['__set_default_parameters'](a)
00266         elif(param == 'paramkeys'):
00267                 return a.keys()
00268         else:
00269             if(paramvalue==None and subparam==None):
00270                if(a.has_key(param)):
00271                   return a[param]
00272                else:
00273                   return self.itsdefault(param)
00274             else:
00275                retval=a[param]
00276                if(type(a[param])==dict):
00277                   for k in range(len(a[param])):
00278                      valornotval='value'
00279                      if(a[param][k].has_key('notvalue')):
00280                         valornotval='notvalue'
00281                      if((a[param][k][valornotval])==paramvalue):
00282                         retval=a[param][k].copy()
00283                         retval.pop(valornotval)
00284                         if(subparam != None):
00285                            if(retval.has_key(subparam)):
00286                               retval=retval[subparam]
00287                            else:
00288                               retval=self.itsdefault(subparam)
00289                      else:
00290                         retval=self.itsdefault(subparam)
00291                return retval
00292 
00293 
00294 #
00295 #
00296     def check_params(self, param=None, value=None, ipython_globals=None):
00297       if ipython_globals == None:
00298           myf=self.__globals__
00299       else:
00300           myf=ipython_globals
00301 #      print 'param:', param, 'value:', value
00302       try :
00303          if str(type(value)) != "<type 'instance'>" :
00304             value0 = value
00305             value = myf['cu'].expandparam(param, value)
00306             matchtype = False
00307             if(type(value) == numpy.ndarray):
00308                if(type(value) == type(value0)):
00309                   myf[param] = value.tolist()
00310                else:
00311                   #print 'value:', value, 'value0:', value0
00312                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00313                   myf[param] = value0
00314                   if type(value0) != list :
00315                      matchtype = True
00316             else :
00317                myf[param] = value
00318             value = myf['cu'].verifyparam({param:value})
00319             if matchtype:
00320                value = False
00321       except Exception, instance:
00322          #ignore the exception and just return it unchecked
00323          myf[param] = value
00324       return value
00325 #
00326 #
00327     def description(self, key='imsubimage', subkey=None):
00328         desc={'imsubimage': 'Create a (sub)image from a region of the image',
00329                'imagename': 'Input image name.  Default is unset.',
00330                'outfile': 'Output image name.  Default is unset.',
00331                'region': 'Region of interest.  Default is whole image.',
00332                'mask': 'Mask to use. See help par.mask. Default is none.',
00333                'dropdeg': 'Drop degenerate axes',
00334                'overwrite': 'Overwrite (unprompted) pre-existing output file?',
00335                'verbose': 'Post additional informative messages to the logger',
00336                'stretch': 'Stretch the mask if necessary and possible? ',
00337                'wantreturn': 'If True, return an image analysis tool associated with the subimage. If False, return nothing. ',
00338 
00339                'async': 'If true the taskname must be started using imsubimage(...)'
00340               }
00341 
00342         if(desc.has_key(key)) :
00343            return desc[key]
00344 
00345     def itsdefault(self, paramname) :
00346         a = {}
00347         a['imagename']  = ''
00348         a['outfile']  = ''
00349         a['region']  = ''
00350         a['mask']  = ''
00351         a['dropdeg']  = False
00352         a['overwrite']  = False
00353         a['verbose']  = True
00354         a['stretch']  = False
00355         a['wantreturn']  = True
00356 
00357         #a = sys._getframe(len(inspect.stack())-1).f_globals
00358 
00359         if a.has_key(paramname) :
00360               return a[paramname]
00361 imsubimage_cli = imsubimage_cli_()