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