casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
boxit_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_boxit import boxit
00016 from task_boxit import casalog
00017 
00018 class boxit_pg_:
00019     __name__ = "boxit"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (boxit_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, imagename=None, regionfile=None, threshold=None, maskname=None, chanrange=None, polrange=None, minsize=None, diag=None, boxstretch=None, overwrite=None, async=None):
00027 
00028         """Box regions in image above given threshold value.
00029 
00030        This tool finds all 2-dimensional (RA/dec) regions in the given
00031        image which are contiguous sets of pixels (islands) above the given ]
00032        threshold.  It creates a box for each island, a rectangular "cutout".
00033        The boxes are stored as regions in the output regionfile.  Works on
00034        multi-plane images, but only boxes 2-D regions in each plane.
00035        (Doesn't create cubes/3D boxes.)
00036  
00037        imagename -- Name of input images:
00038                default: none; example: imagename='myimage.image'
00039        regionfile -- Name of output region file (adds extension .rgn).
00040                default: none; if not given uses imagename+'.rgn'
00041        threshold -- value (with units) to use for island threshold.
00042                default: 0.0.
00043        maskname -- Optional output mask name.
00044                default: '' (do not write mask image)
00045        chanrange -- Range of channel ids
00046                default: '' (find boxes for all channels)
00047                example: '5~7' (find boxes for channel 5,6,7
00048        polrange -- Range of polarization ids
00049                default: '' (find boxes for all polarizations)
00050                example: '0~1' (find boxes for polarization 0,1
00051        minsize -- minimum size of island to get a box (in number of pixels)
00052                default: 2
00053        diag -- count diagonal connections as same island or not
00054                default: False
00055        boxstretch -- number of pixels to increase outward size of each box; can
00056                range from -1 to 5.
00057                default: 1
00058        overwrite -- Overwrite existing region file and/or mask?
00059                default: False.  If False, gives warning if file exists.
00060 
00061   
00062         """
00063         a=inspect.stack()
00064         stacklevel=0
00065         for k in range(len(a)):
00066           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00067                 stacklevel=k
00068                 break
00069         myf=sys._getframe(stacklevel).f_globals
00070         myf['__last_task'] = 'boxit'
00071         myf['taskname'] = 'boxit'
00072         ###
00073         myf['update_params'](func=myf['taskname'],printtext=False)
00074         ###
00075         ###
00076         #Handle globals or user over-ride of arguments
00077         #
00078         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00079         useLocalDefaults = False
00080 
00081         for item in function_signature_defaults.iteritems():
00082                 key,val = item
00083                 keyVal = eval(key)
00084                 if (keyVal == None):
00085                         #user hasn't set it - use global/default
00086                         pass
00087                 else:
00088                         #user has set it - use over-ride
00089                         if (key != 'self') :
00090                            useLocalDefaults = True
00091                         #myf[key]=keyVal
00092 
00093         myparams = {}
00094         if useLocalDefaults :
00095            for item in function_signature_defaults.iteritems():
00096                key,val = item
00097                keyVal = eval(key)
00098                exec('myparams[key] = keyVal')
00099                if (keyVal == None):
00100                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00101                    keyVal = eval(key)
00102                    if(type(keyVal) == dict) :
00103                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00104 
00105         else :
00106             uselessvariable = None 
00107             myparams['imagename'] = imagename = myf['imagename']
00108             myparams['regionfile'] = regionfile = myf['regionfile']
00109             myparams['threshold'] = threshold = myf['threshold']
00110             myparams['maskname'] = maskname = myf['maskname']
00111             myparams['chanrange'] = chanrange = myf['chanrange']
00112             myparams['polrange'] = polrange = myf['polrange']
00113             myparams['minsize'] = minsize = myf['minsize']
00114             myparams['diag'] = diag = myf['diag']
00115             myparams['boxstretch'] = boxstretch = myf['boxstretch']
00116             myparams['overwrite'] = overwrite = myf['overwrite']
00117 
00118 
00119         result = None
00120 
00121 #
00122 #    The following is work around to avoid a bug with current python translation
00123 #
00124         mytmp = {}
00125 
00126         mytmp['imagename'] = imagename
00127         mytmp['regionfile'] = regionfile
00128         if type(threshold) == str :
00129            mytmp['threshold'] = casac.quanta().quantity(threshold)
00130         else :
00131            mytmp['threshold'] = threshold
00132         mytmp['maskname'] = maskname
00133         mytmp['chanrange'] = chanrange
00134         mytmp['polrange'] = polrange
00135         mytmp['minsize'] = minsize
00136         mytmp['diag'] = diag
00137         mytmp['boxstretch'] = boxstretch
00138         mytmp['overwrite'] = overwrite
00139         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00140         trec = casac.utils().torecord(pathname+'boxit.xml')
00141 
00142         casalog.origin('boxit')
00143         if not trec.has_key('boxit') or not casac.utils().verify(mytmp, trec['boxit']) :
00144             return False
00145 
00146 
00147         try :
00148           casalog.post('')
00149           casalog.post('##########################################')
00150           casalog.post('##### Begin Task: boxit           #####')
00151           casalog.post('')
00152           result = boxit(imagename, regionfile, threshold, maskname, chanrange, polrange, minsize, diag, boxstretch, overwrite)
00153           casalog.post('')
00154           casalog.post('##### End Task: boxit           #####')
00155           casalog.post('##########################################')
00156 
00157 
00158 # saveinputs for individule engine has no use
00159 # saveinputs should alos be removed from casa_in_py.py
00160 #
00161 #
00162 #          saveinputs = myf['saveinputs']
00163 #          saveinputs('boxit', 'boxit.last', myparams)
00164 #
00165 #
00166         except Exception, instance:
00167           #print '**** Error **** ',instance
00168           pass
00169 
00170         gc.collect()
00171         return result
00172 #
00173 #
00174 ##
00175 #    def paramgui(self, useGlobals=True):
00176 #        """
00177 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00178 #        """
00179 #        import paramgui
00180 #
00181 #        a=inspect.stack()
00182 #        stacklevel=0
00183 #        for k in range(len(a)):
00184 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00185 #            stacklevel=k
00186 #            break
00187 #        myf = sys._getframe(stacklevel).f_globals
00188 #
00189 #        if useGlobals:
00190 #            paramgui.setGlobals(myf)
00191 #        else:
00192 #            paramgui.setGlobals({})
00193 #
00194 #        paramgui.runTask('boxit', myf['_ip'])
00195 #        paramgui.setGlobals({})
00196 #
00197 #
00198 #
00199 #
00200     def defaults(self, param=None):
00201         a=inspect.stack()
00202         stacklevel=0
00203         for k in range(len(a)):
00204           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00205                 stacklevel=k
00206                 break
00207         myf=sys._getframe(stacklevel).f_globals
00208         a = odict()
00209         a['imagename']  = ''
00210         a['regionfile']  = ''
00211         a['threshold']  = '0.0mJy'
00212         a['maskname']  = ''
00213         a['chanrange']  = ''
00214         a['polrange']  = ''
00215         a['minsize']  = 2
00216         a['diag']  = False
00217         a['boxstretch']  = 1
00218         a['overwrite']  = False
00219 
00220         a['async']=False
00221 
00222 ### This function sets the default values but also will return the list of
00223 ### parameters or the default value of a given parameter
00224         if(param == None):
00225                 myf['__set_default_parameters'](a)
00226         elif(param == 'paramkeys'):
00227                 return a.keys()
00228         else:
00229                 if(a.has_key(param)):
00230                    #if(type(a[param]) == dict) :
00231                    #   return a[param][len(a[param])-1]['value']
00232                    #else :
00233                       return a[param]
00234 
00235 
00236 #
00237 #
00238     def check_params(self, param=None, value=None):
00239       a=inspect.stack() 
00240       stacklevel=0
00241       for k in range(len(a)):
00242         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00243             stacklevel=k
00244             break
00245       myf=sys._getframe(stacklevel).f_globals
00246 
00247 #      print 'param:', param, 'value:', value
00248       try :
00249          if str(type(value)) != "<type 'instance'>" :
00250             value0 = value
00251             value = myf['cu'].expandparam(param, value)
00252             matchtype = False
00253             if(type(value) == numpy.ndarray):
00254                if(type(value) == type(value0)):
00255                   myf[param] = value.tolist()
00256                else:
00257                   #print 'value:', value, 'value0:', value0
00258                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00259                   myf[param] = value0
00260                   if type(value0) != list :
00261                      matchtype = True
00262             else :
00263                myf[param] = value
00264             value = myf['cu'].verifyparam({param:value})
00265             if matchtype:
00266                value = False
00267       except Exception, instance:
00268          #ignore the exception and just return it unchecked
00269          myf[param] = value
00270       return value
00271 
00272 #
00273 #
00274     def description(self, key='boxit', subkey=None):
00275         desc={'boxit': 'Box regions in image above given threshold value.',
00276                'imagename': 'Name of image to threshold',
00277                'regionfile': 'Output region file',
00278                'threshold': 'Threshold value.  Must include units.',
00279                'maskname': 'Output mask name (optional).',
00280                'chanrange': 'Range of channel ids',
00281                'polrange': 'Range of polarization ids',
00282                'minsize': 'Minimum number of pixels for a boxable island',
00283                'diag': 'Count diagonal connections?',
00284                'boxstretch': 'Increase box sizes by this many pixels beyond thresholded pixels.',
00285                'overwrite': 'Overwrite existing region file?',
00286 
00287                'async': 'If true the taskname must be started using boxit(...)'
00288               }
00289 
00290         if(desc.has_key(key)) :
00291            return desc[key]
00292 
00293     def itsdefault(self, paramname) :
00294         a = {}
00295         a['imagename']  = ''
00296         a['regionfile']  = ''
00297         a['threshold']  = '0.0mJy'
00298         a['maskname']  = ''
00299         a['chanrange']  = ''
00300         a['polrange']  = ''
00301         a['minsize']  = 2
00302         a['diag']  = False
00303         a['boxstretch']  = 1
00304         a['overwrite']  = False
00305 
00306         if a.has_key(paramname) :
00307               return a[paramname]
00308 boxit_pg = boxit_pg_()