casa
$Rev:20696$
|
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_boxit import boxit 00018 class boxit_cli_: 00019 __name__ = "boxit" 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__ = (boxit_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'imagename':None, 'regionfile':None, 'threshold':None, 'maskname':None, 'chanrange':None, 'polrange':None, 'minsize':None, 'diag':None, 'boxstretch':None, 'overwrite':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, regionfile=None, threshold=None, maskname=None, chanrange=None, polrange=None, minsize=None, diag=None, boxstretch=None, overwrite=None, async=None): 00047 00048 """Box regions in image above given threshold value. 00049 00050 This tool finds all 2-dimensional (RA/dec) regions in the given 00051 image which are contiguous sets of pixels (islands) above the given ] 00052 threshold. It creates a box for each island, a rectangular "cutout". 00053 The boxes are stored as regions in the output regionfile. Works on 00054 multi-plane images, but only boxes 2-D regions in each plane. 00055 (Doesn't create cubes/3D boxes.) 00056 00057 imagename -- Name of input images: 00058 default: none; example: imagename='myimage.image' 00059 regionfile -- Name of output region file (adds extension .rgn). 00060 default: none; if not given uses imagename+'.rgn' 00061 threshold -- value (with units) to use for island threshold. 00062 default: 0.0. 00063 maskname -- Optional output mask name. 00064 default: '' (do not write mask image) 00065 chanrange -- Range of channel ids 00066 default: '' (find boxes for all channels) 00067 example: '5~7' (find boxes for channel 5,6,7 00068 polrange -- Range of polarization ids 00069 default: '' (find boxes for all polarizations) 00070 example: '0~1' (find boxes for polarization 0,1 00071 minsize -- minimum size of island to get a box (in number of pixels) 00072 default: 2 00073 diag -- count diagonal connections as same island or not 00074 default: False 00075 boxstretch -- number of pixels to increase outward size of each box; can 00076 range from -1 to 5. 00077 default: 1 00078 overwrite -- Overwrite existing region file and/or mask? 00079 default: False. If False, gives warning if file exists. 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'] = 'boxit' 00089 self.__globals__['taskname'] = 'boxit' 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['imagename'] = imagename = self.parameters['imagename'] 00129 myparams['regionfile'] = regionfile = self.parameters['regionfile'] 00130 myparams['threshold'] = threshold = self.parameters['threshold'] 00131 myparams['maskname'] = maskname = self.parameters['maskname'] 00132 myparams['chanrange'] = chanrange = self.parameters['chanrange'] 00133 myparams['polrange'] = polrange = self.parameters['polrange'] 00134 myparams['minsize'] = minsize = self.parameters['minsize'] 00135 myparams['diag'] = diag = self.parameters['diag'] 00136 myparams['boxstretch'] = boxstretch = self.parameters['boxstretch'] 00137 myparams['overwrite'] = overwrite = self.parameters['overwrite'] 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['imagename'] = imagename 00148 mytmp['regionfile'] = regionfile 00149 if type(threshold) == str : 00150 mytmp['threshold'] = casac.casac.qa.quantity(threshold) 00151 else : 00152 mytmp['threshold'] = threshold 00153 mytmp['maskname'] = maskname 00154 mytmp['chanrange'] = chanrange 00155 mytmp['polrange'] = polrange 00156 mytmp['minsize'] = minsize 00157 mytmp['diag'] = diag 00158 mytmp['boxstretch'] = boxstretch 00159 mytmp['overwrite'] = overwrite 00160 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00161 trec = casac.casac.utils().torecord(pathname+'boxit.xml') 00162 00163 casalog.origin('boxit') 00164 try : 00165 #if not trec.has_key('boxit') or not casac.casac.utils().verify(mytmp, trec['boxit']) : 00166 #return False 00167 00168 casac.casac.utils().verify(mytmp, trec['boxit'], True) 00169 scriptstr=[''] 00170 saveinputs = self.__globals__['saveinputs'] 00171 saveinputs('boxit', 'boxit.last', myparams, self.__globals__,scriptstr=scriptstr) 00172 if async : 00173 count = 0 00174 keybase = time.strftime("%y%m%d.%H%M%S") 00175 key = keybase + "_" + str(count) 00176 while self.__async__.has_key(key) : 00177 count += 1 00178 key = keybase + "_" + str(count) 00179 result = tm.execute('boxit', imagename, regionfile, threshold, maskname, chanrange, polrange, minsize, diag, boxstretch, overwrite) 00180 print "Use: " 00181 print " tm.retrieve(return_value) # to retrieve the status" 00182 print 00183 self.rkey = key 00184 self.__async__[key] = result 00185 else : 00186 tname = 'boxit' 00187 spaces = ' '*(18-len(tname)) 00188 casalog.post('\n##########################################'+ 00189 '\n##### Begin Task: ' + tname + spaces + ' #####') 00190 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00191 result = boxit(imagename, regionfile, threshold, maskname, chanrange, polrange, minsize, diag, boxstretch, overwrite) 00192 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00193 '\n##########################################') 00194 00195 except Exception, instance: 00196 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00197 raise 00198 else : 00199 #print '**** Error **** ',instance 00200 tname = 'boxit' 00201 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00202 pass 00203 00204 gc.collect() 00205 return result 00206 # 00207 # 00208 # 00209 def paramgui(self, useGlobals=True, ipython_globals=None): 00210 """ 00211 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00212 """ 00213 import paramgui 00214 if not hasattr(self, "__globals__") or self.__globals__ == None : 00215 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00216 00217 if useGlobals: 00218 if ipython_globals == None: 00219 myf=self.__globals__ 00220 else: 00221 myf=ipython_globals 00222 00223 paramgui.setGlobals(myf) 00224 else: 00225 paramgui.setGlobals({}) 00226 00227 paramgui.runTask('boxit', myf['_ip']) 00228 paramgui.setGlobals({}) 00229 00230 # 00231 # 00232 # 00233 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00234 if not hasattr(self, "__globals__") or self.__globals__ == None : 00235 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00236 if ipython_globals == None: 00237 myf=self.__globals__ 00238 else: 00239 myf=ipython_globals 00240 00241 a = odict() 00242 a['imagename'] = '' 00243 a['regionfile'] = '' 00244 a['threshold'] = '0.0mJy' 00245 a['maskname'] = '' 00246 a['chanrange'] = '' 00247 a['polrange'] = '' 00248 a['minsize'] = 2 00249 a['diag'] = False 00250 a['boxstretch'] = 1 00251 a['overwrite'] = False 00252 00253 a['async']=False 00254 00255 ### This function sets the default values but also will return the list of 00256 ### parameters or the default value of a given parameter 00257 if(param == None): 00258 myf['__set_default_parameters'](a) 00259 elif(param == 'paramkeys'): 00260 return a.keys() 00261 else: 00262 if(paramvalue==None and subparam==None): 00263 if(a.has_key(param)): 00264 return a[param] 00265 else: 00266 return self.itsdefault(param) 00267 else: 00268 retval=a[param] 00269 if(type(a[param])==dict): 00270 for k in range(len(a[param])): 00271 valornotval='value' 00272 if(a[param][k].has_key('notvalue')): 00273 valornotval='notvalue' 00274 if((a[param][k][valornotval])==paramvalue): 00275 retval=a[param][k].copy() 00276 retval.pop(valornotval) 00277 if(subparam != None): 00278 if(retval.has_key(subparam)): 00279 retval=retval[subparam] 00280 else: 00281 retval=self.itsdefault(subparam) 00282 else: 00283 retval=self.itsdefault(subparam) 00284 return retval 00285 00286 00287 # 00288 # 00289 def check_params(self, param=None, value=None, ipython_globals=None): 00290 if ipython_globals == None: 00291 myf=self.__globals__ 00292 else: 00293 myf=ipython_globals 00294 # print 'param:', param, 'value:', value 00295 try : 00296 if str(type(value)) != "<type 'instance'>" : 00297 value0 = value 00298 value = myf['cu'].expandparam(param, value) 00299 matchtype = False 00300 if(type(value) == numpy.ndarray): 00301 if(type(value) == type(value0)): 00302 myf[param] = value.tolist() 00303 else: 00304 #print 'value:', value, 'value0:', value0 00305 #print 'type(value):', type(value), 'type(value0):', type(value0) 00306 myf[param] = value0 00307 if type(value0) != list : 00308 matchtype = True 00309 else : 00310 myf[param] = value 00311 value = myf['cu'].verifyparam({param:value}) 00312 if matchtype: 00313 value = False 00314 except Exception, instance: 00315 #ignore the exception and just return it unchecked 00316 myf[param] = value 00317 return value 00318 # 00319 # 00320 def description(self, key='boxit', subkey=None): 00321 desc={'boxit': 'Box regions in image above given threshold value.', 00322 'imagename': 'Name of image to threshold', 00323 'regionfile': 'Output region file', 00324 'threshold': 'Threshold value. Must include units.', 00325 'maskname': 'Output mask name (optional).', 00326 'chanrange': 'Range of channel ids', 00327 'polrange': 'Range of polarization ids', 00328 'minsize': 'Minimum number of pixels for a boxable island', 00329 'diag': 'Count diagonal connections?', 00330 'boxstretch': 'Increase box sizes by this many pixels beyond thresholded pixels.', 00331 'overwrite': 'Overwrite existing region file?', 00332 00333 'async': 'If true the taskname must be started using boxit(...)' 00334 } 00335 00336 if(desc.has_key(key)) : 00337 return desc[key] 00338 00339 def itsdefault(self, paramname) : 00340 a = {} 00341 a['imagename'] = '' 00342 a['regionfile'] = '' 00343 a['threshold'] = '0.0mJy' 00344 a['maskname'] = '' 00345 a['chanrange'] = '' 00346 a['polrange'] = '' 00347 a['minsize'] = 2 00348 a['diag'] = False 00349 a['boxstretch'] = 1 00350 a['overwrite'] = False 00351 00352 #a = sys._getframe(len(inspect.stack())-1).f_globals 00353 00354 if a.has_key(paramname) : 00355 return a[paramname] 00356 boxit_cli = boxit_cli_()