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_makemask import makemask 00018 class makemask_cli_: 00019 __name__ = "makemask" 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__ = (makemask_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'mode':None, 'inpimage':None, 'inpmask':None, 'output':None, 'overwrite':None, 'inpfreqs':None, 'outfreqs':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, mode=None, inpimage=None, inpmask=None, output=None, overwrite=None, inpfreqs=None, outfreqs=None, async=None): 00047 00048 """Makes and manipulates image masks 00049 00050 Modes : 00051 ------------- 00052 00053 copy : Copy/merge masks and regrid if necessary to a new or existing mask 00054 expand : Expand a mask from one range of freqs to another range 00055 list : list internal masks in inpimage to the log 00056 delete : delete an internal mask from an image (if the deleted mask was a default mask, 00057 the task chooses the first one in the remaining internal mask list (as appears 00058 in the log when do listing with mode='list') 00059 setdefaultmask : set a specified internal mask as a defult internal mask 00060 00061 00062 00063 00064 In all cases (for output mask is expected), if the output image has a different coordinate system from the 00065 result of input and processing, the mask will be regridded to the output 00066 coordinate system. 00067 00068 00069 Parameter Descriptions and rules: 00070 ------------------------------ 00071 inpimage : Name of input image to use as a reference for the output coordinates (if output does not exist). 00072 Also used as a reference image when regions are specified in inpmask for copy mode 00073 default: none (must specify for list, copy, expand modes) 00074 00075 Expandable parameters for mode='copy','expand','delete' and 'setdefaultmask': 00076 inpmask : Name(s) of input mask(s) 00077 default: none 00078 To specify an image (zero/non-zero) mask, just give a image name (e.g. myimage1.im) 00079 To specify an internal (T/F) mask, you must give a parent image name and the internal mask name 00080 seperated by a colon. (e.g. myimage1.im:mask0). The internal mask names can be found by running 00081 the makemask task in mode='list'. 00082 00083 (expand mode) 00084 'myimage:mask0' : use(true/false) internal mask 00085 'myimage' : use the inpimage values to make a mask (zero/non-zero). 00086 Non-zero values are normalized to one in the process. 00087 (merge mode) 00088 Specify the image mask(s), T/F mask(s), and region(s) to be merged in a list of strings. 00089 The regions can be specified directly in the CASA region format or in the text file(s) contains 00090 the regions. 00091 00092 (delete and setdefaultmask mode) 00093 Specify the internal mask with the format, image:mask 00094 00095 00096 output : Name of output image. 00097 default: none 00098 *The resultant mask is written as an image (zero/one) mask if the output is a plain image name 00099 *The resultant mask is written as an internal (T/F) mask if the output name is the form of 'imagename:maskname' 00100 The created mask is set as a default internal mask. 00101 *To re-grid a mask to a different coordinate system, 00102 give an image with the target coordinate system in inpimage. Or make a copy an imge 00103 with the target coordinate system and specified the name of the copy in output. 00104 00105 00106 - If output is specifield as a plain image, if it exists, it will regrid the mask to 00107 the new coordinate system and modify output (if overwrite=True). 00108 - If output is specifield as an image with an internal mask, if the internal mask exists, 00109 it will regrid the mask to the new coordinate system and modify the internal mask only (if overwrite=True). 00110 - If output does not exist, it will only copy inpimage 00111 - If output == inpimage, do not regrid. Only modify in-place. 00112 00113 overwrite : overwrite the mask specified in output? (see also the output rules above) 00114 default: False 00115 00116 Additional expandable parameters for mode='expand': 00117 inpfreqs : input channel/frequency/velocity range 00118 Specify channels in a list of integers. for frequency/velocity, 00119 a range is specified in a string with '~', e.g. '1.5MHz~1.6MHz' 00120 default: [] - all channels 00121 outfreqs : output channel/frequency/velocity range 00122 Specify same way as inpfreqs 00123 default: [] - all channels 00124 00125 00126 Usage examples : 00127 --------------------------- 00128 (1) (list mode): 00129 makemask(mode='list', inpimage='mymask.im') 00130 it prints out a list of the internal mask(s) exist in mymask.im to the log 00131 00132 (2) (copy mode): 00133 Regrid a boolean mask from one coordinate system to another and save as boolean mask 00134 in the output image. 00135 00136 makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='newmask.im:mask0') 00137 00138 (3) (copy mode): 00139 Same as (1), but save as integer mask in the output image. 00140 00141 makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='newmask.im') 00142 00143 00144 (4) (copy mode): 00145 Convert a boolean(true/false) mask to integer(one/zero) mask in the same image 00146 00147 makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im:mask0', output='', overwrite=True) 00148 00149 00150 (5) (copy mode): 00151 Convert an integer (one/zero) mask to boolean(true/false) mask in the same image 00152 00153 makemask(mode='copy', inpimage='oldmask.im', inpmask='oldmask.im', output='oldmask.im:mask0') 00154 00155 00156 (6) (copy mode): 00157 00158 Merge a one/zero mask and T/F masks, using the input coordinate-sys of inpimage and 00159 saving in a new output file. Remember, if the image specified in output already exist and 00160 has a different coordinate system from inpimage, the mask will be regridded to it. 00161 All masks to be merged are specified in a list in inpmask. 00162 The name of internal masks must be given in the format, 'parent_image_name:internal_mask_name', 00163 as shown the example below. 00164 00165 In the example below, image1.im (the 1/0 mask), the internal masks, mask0 from image1.im 00166 and mask1 from image2.im, and a region (on image1.im as defined in inpimage) are combined. 00167 The output, newmask.im is a new mask name which has not 00168 yet exist so image specified in inpimage, image1.im's coordinates are used as a target 00169 image coordinates. If image1.im and image2.im has different coordinates, image2.im:mask1 is 00170 regridded before it is combined to the other two masks. 00171 00172 makemask(mode='copy', 00173 inpimage='image1.im', 00174 inpmask=['image1.im', image1.im:mask0','image2.mask:mask1', 'circle[[15pix , 15pix] ,8pix ]'], 00175 output='newmask.im); 00176 00177 (7) (expand mode): 00178 Expand a (one/zero) mask from continuum imaging to use as an input mask image for 00179 spectral line imaging. Use an existing spectral line clean image as a template by 00180 sepecified in inpimage. 00181 The inpfreqs is left out as it uses a default (=[], means all channels). 00182 00183 makemask(mode='expand', inpimage='spec.clean.image', inpmask='cont.clean.mask' 00184 outfreqs=[4,5,6,7], output='spec.clean.mask') 00185 00186 (8) (expand mode): 00187 Expand a boolean mask from one range of channels to another range 00188 in the same image. 00189 00190 makemask(mode='expand', inpimage='oldmask.im', inpmask='oldmask.im:mask0', inpfreqs=[5,6], outfreqs=[4,5,6,7], 00191 output='oldmask.im:mask0', overwrite=True) 00192 00193 00194 (9) (expand mode): 00195 Expand a boolean mask from a range of channels in the input image to another range 00196 of channels in a different image with a different spectral-coordinate system. 00197 Save the mask as ones/zeros so that it can be used as an input mask in the clean task. 00198 00199 makemask(mode='expand', inpimage='bigmask.im', inpmask='smallmask.im:mask0', 00200 inpfreqs='1.5MHz~1.6MHz', outfreqs='1.2MHz~1.8MHz', output='bigmask.im', overwrite=True) 00201 00202 (10) (delete mode) 00203 Delete an internal mask from an image. 00204 00205 makemask(mode='delete', inpmask='newmask.im:mask0') 00206 00207 (11) (setdefaultmask mode) 00208 Set an internal mask as a default internal mask. 00209 00210 makemask(mode='setdefaultmask', inpmask='newmask.im:mask1') 00211 00212 00213 00214 00215 00216 00217 """ 00218 if not hasattr(self, "__globals__") or self.__globals__ == None : 00219 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00220 #casac = self.__globals__['casac'] 00221 casalog = self.__globals__['casalog'] 00222 #casalog = casac.casac.logsink() 00223 self.__globals__['__last_task'] = 'makemask' 00224 self.__globals__['taskname'] = 'makemask' 00225 ### 00226 self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__) 00227 ### 00228 ### 00229 #Handle globals or user over-ride of arguments 00230 # 00231 function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults)) 00232 useLocalDefaults = False 00233 00234 for item in function_signature_defaults.iteritems(): 00235 key,val = item 00236 keyVal = eval(key) 00237 if (keyVal == None): 00238 #user hasn't set it - use global/default 00239 pass 00240 else: 00241 #user has set it - use over-ride 00242 if (key != 'self') : 00243 useLocalDefaults = True 00244 00245 myparams = {} 00246 if useLocalDefaults : 00247 for item in function_signature_defaults.iteritems(): 00248 key,val = item 00249 keyVal = eval(key) 00250 exec('myparams[key] = keyVal') 00251 self.parameters[key] = keyVal 00252 if (keyVal == None): 00253 exec('myparams[key] = '+ key + ' = self.itsdefault(key)') 00254 keyVal = eval(key) 00255 if(type(keyVal) == dict) : 00256 if len(keyVal) > 0 : 00257 exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']') 00258 else : 00259 exec('myparams[key] = ' + key + ' = {}') 00260 00261 else : 00262 async = self.parameters['async'] 00263 myparams['mode'] = mode = self.parameters['mode'] 00264 myparams['inpimage'] = inpimage = self.parameters['inpimage'] 00265 myparams['inpmask'] = inpmask = self.parameters['inpmask'] 00266 myparams['output'] = output = self.parameters['output'] 00267 myparams['overwrite'] = overwrite = self.parameters['overwrite'] 00268 myparams['inpfreqs'] = inpfreqs = self.parameters['inpfreqs'] 00269 myparams['outfreqs'] = outfreqs = self.parameters['outfreqs'] 00270 00271 00272 result = None 00273 00274 # 00275 # The following is work around to avoid a bug with current python translation 00276 # 00277 mytmp = {} 00278 00279 mytmp['mode'] = mode 00280 mytmp['inpimage'] = inpimage 00281 mytmp['inpmask'] = inpmask 00282 mytmp['output'] = output 00283 mytmp['overwrite'] = overwrite 00284 mytmp['inpfreqs'] = inpfreqs 00285 mytmp['outfreqs'] = outfreqs 00286 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00287 trec = casac.casac.utils().torecord(pathname+'makemask.xml') 00288 00289 casalog.origin('makemask') 00290 try : 00291 #if not trec.has_key('makemask') or not casac.casac.utils().verify(mytmp, trec['makemask']) : 00292 #return False 00293 00294 casac.casac.utils().verify(mytmp, trec['makemask'], True) 00295 scriptstr=[''] 00296 saveinputs = self.__globals__['saveinputs'] 00297 saveinputs('makemask', 'makemask.last', myparams, self.__globals__,scriptstr=scriptstr) 00298 if async : 00299 count = 0 00300 keybase = time.strftime("%y%m%d.%H%M%S") 00301 key = keybase + "_" + str(count) 00302 while self.__async__.has_key(key) : 00303 count += 1 00304 key = keybase + "_" + str(count) 00305 result = tm.execute('makemask', mode, inpimage, inpmask, output, overwrite, inpfreqs, outfreqs) 00306 print "Use: " 00307 print " tm.retrieve(return_value) # to retrieve the status" 00308 print 00309 self.rkey = key 00310 self.__async__[key] = result 00311 else : 00312 tname = 'makemask' 00313 spaces = ' '*(18-len(tname)) 00314 casalog.post('\n##########################################'+ 00315 '\n##### Begin Task: ' + tname + spaces + ' #####') 00316 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00317 result = makemask(mode, inpimage, inpmask, output, overwrite, inpfreqs, outfreqs) 00318 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00319 '\n##########################################') 00320 00321 except Exception, instance: 00322 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00323 raise 00324 else : 00325 #print '**** Error **** ',instance 00326 tname = 'makemask' 00327 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00328 pass 00329 00330 gc.collect() 00331 return result 00332 # 00333 # 00334 # 00335 def paramgui(self, useGlobals=True, ipython_globals=None): 00336 """ 00337 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00338 """ 00339 import paramgui 00340 if not hasattr(self, "__globals__") or self.__globals__ == None : 00341 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00342 00343 if useGlobals: 00344 if ipython_globals == None: 00345 myf=self.__globals__ 00346 else: 00347 myf=ipython_globals 00348 00349 paramgui.setGlobals(myf) 00350 else: 00351 paramgui.setGlobals({}) 00352 00353 paramgui.runTask('makemask', myf['_ip']) 00354 paramgui.setGlobals({}) 00355 00356 # 00357 # 00358 # 00359 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00360 if not hasattr(self, "__globals__") or self.__globals__ == None : 00361 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00362 if ipython_globals == None: 00363 myf=self.__globals__ 00364 else: 00365 myf=ipython_globals 00366 00367 a = odict() 00368 a['mode'] = 'list' 00369 00370 a['async']=False 00371 a['mode'] = { 00372 0:odict([{'value':'list'}, {'inpimage':''}]), 00373 1:odict([{'value':'copy'}, {'inpimage':''}, {'inpmask':''}, {'output':''}, {'overwrite':False}]), 00374 2:odict([{'value':'expand'}, {'inpimage':''}, {'inpmask':''}, {'inpfreqs':[]}, {'outfreqs':[]}, {'output':''}, {'overwrite':False}]), 00375 3:odict([{'value':'delete'}, {'inpmask':''}]), 00376 4:odict([{'value':'setdefaultmask'}, {'inpmask':''}])} 00377 00378 ### This function sets the default values but also will return the list of 00379 ### parameters or the default value of a given parameter 00380 if(param == None): 00381 myf['__set_default_parameters'](a) 00382 elif(param == 'paramkeys'): 00383 return a.keys() 00384 else: 00385 if(paramvalue==None and subparam==None): 00386 if(a.has_key(param)): 00387 return a[param] 00388 else: 00389 return self.itsdefault(param) 00390 else: 00391 retval=a[param] 00392 if(type(a[param])==dict): 00393 for k in range(len(a[param])): 00394 valornotval='value' 00395 if(a[param][k].has_key('notvalue')): 00396 valornotval='notvalue' 00397 if((a[param][k][valornotval])==paramvalue): 00398 retval=a[param][k].copy() 00399 retval.pop(valornotval) 00400 if(subparam != None): 00401 if(retval.has_key(subparam)): 00402 retval=retval[subparam] 00403 else: 00404 retval=self.itsdefault(subparam) 00405 else: 00406 retval=self.itsdefault(subparam) 00407 return retval 00408 00409 00410 # 00411 # 00412 def check_params(self, param=None, value=None, ipython_globals=None): 00413 if ipython_globals == None: 00414 myf=self.__globals__ 00415 else: 00416 myf=ipython_globals 00417 # print 'param:', param, 'value:', value 00418 try : 00419 if str(type(value)) != "<type 'instance'>" : 00420 value0 = value 00421 value = myf['cu'].expandparam(param, value) 00422 matchtype = False 00423 if(type(value) == numpy.ndarray): 00424 if(type(value) == type(value0)): 00425 myf[param] = value.tolist() 00426 else: 00427 #print 'value:', value, 'value0:', value0 00428 #print 'type(value):', type(value), 'type(value0):', type(value0) 00429 myf[param] = value0 00430 if type(value0) != list : 00431 matchtype = True 00432 else : 00433 myf[param] = value 00434 value = myf['cu'].verifyparam({param:value}) 00435 if matchtype: 00436 value = False 00437 except Exception, instance: 00438 #ignore the exception and just return it unchecked 00439 myf[param] = value 00440 return value 00441 # 00442 # 00443 def description(self, key='makemask', subkey=None): 00444 desc={'makemask': 'Makes and manipulates image masks', 00445 'mode': 'Mask method (copy,expand,merge,delete,setdefaultmask)', 00446 'inpimage': 'Name of input image.', 00447 'inpmask': 'mask(s) to be processed: image masks,T/F internal masks(Need to include parent image names)', 00448 'output': 'Name of output mask (imagename or imagename:internal_maskname)', 00449 'overwrite': 'overwrite output if exists?', 00450 'inpfreqs': 'List of chans/freqs (in inpmask) to read masks from ', 00451 'outfreqs': 'List of chans/freqs (in output) on which to expand the mask', 00452 00453 'async': 'If true the taskname must be started using makemask(...)' 00454 } 00455 00456 # 00457 # Set subfields defaults if needed 00458 # 00459 00460 if(desc.has_key(key)) : 00461 return desc[key] 00462 00463 def itsdefault(self, paramname) : 00464 a = {} 00465 a['mode'] = 'list' 00466 a['inpimage'] = '' 00467 a['inpmask'] = '' 00468 a['output'] = '' 00469 a['overwrite'] = False 00470 a['inpfreqs'] = [] 00471 a['outfreqs'] = [] 00472 00473 #a = sys._getframe(len(inspect.stack())-1).f_globals 00474 00475 if self.parameters['mode'] == 'list': 00476 a['inpimage'] = '' 00477 00478 if self.parameters['mode'] == 'copy': 00479 a['inpimage'] = '' 00480 a['inpmask'] = '' 00481 a['output'] = '' 00482 a['overwrite'] = False 00483 00484 if self.parameters['mode'] == 'expand': 00485 a['inpimage'] = '' 00486 a['inpmask'] = '' 00487 a['inpfreqs'] = [] 00488 a['outfreqs'] = [] 00489 a['output'] = '' 00490 a['overwrite'] = False 00491 00492 if self.parameters['mode'] == 'delete': 00493 a['inpmask'] = '' 00494 00495 if self.parameters['mode'] == 'setdefaultmask': 00496 a['inpmask'] = '' 00497 00498 if a.has_key(paramname) : 00499 return a[paramname] 00500 makemask_cli = makemask_cli_()