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_immoments import immoments 00018 class immoments_cli_: 00019 __name__ = "immoments" 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__ = (immoments_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'imagename':None, 'moments':None, 'axis':None, 'region':None, 'box':None, 'chans':None, 'stokes':None, 'mask':None, 'includepix':None, 'excludepix':None, 'outfile':None, 'stretch':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, moments=None, axis=None, region=None, box=None, chans=None, stokes=None, mask=None, includepix=None, excludepix=None, outfile=None, stretch=None, async=None): 00047 00048 """Compute moments from an image 00049 The spectral moment distributions at each pixel are 00050 determined. See the cookbook and User Reference Manual for 00051 mathematical details. 00052 00053 The main control of the calculation is given by parameter 00054 moments: 00055 00056 moments=-1 - mean value of the spectrum 00057 moments=0 - integrated value of the spectrum 00058 moments=1 - intensity weighted coordinate;traditionally used to get 00059 'velocity fields' 00060 moments=2 - intensity weighted dispersion of the coordinate; traditionally 00061 used to get "velocity dispersion" 00062 moments=3 - median of I 00063 moments=4 - median coordinate 00064 moments=5 - standard deviation about the mean of the spectrum 00065 moments=6 - root mean square of the spectrum 00066 moments=7 - absolute mean deviation of the spectrum 00067 moments=8 - maximum value of the spectrum 00068 moments=9 - coordinate of the maximum value of the spectrum 00069 moments=10 - minimum value of the spectrum 00070 moments=11 - coordinate of the minimum value of the spectrum 00071 00072 Keyword arguments: 00073 imagename Name of input image 00074 default: none; example: imagename="ngc5921_task.image" 00075 moments List of moments you would like to compute 00076 default: 0 (integrated spectrum);example: moments=[0,1] 00077 see list above 00078 axis The moment axis 00079 default: (spectral axis); example: axis=spec 00080 options: ra, dec, lattitude, longitude, spectral, stokes 00081 mask Mask to use. See help par.mask. Default is none. 00082 stretch Stretch the input mask if necessary and possible. See below. 00083 region Region specification. See help par.region. Default is to not use a region. 00084 box A box region on the directional plane 00085 Only pixel values acceptable. 00086 Default: none (whole 2-D plane); 00087 Example: box="10,10,50,50" 00088 box = "10,10,30,30,35,35,50,50" (two boxes) 00089 chans channel numbers 00090 Range of channel numbers to include in statistics 00091 All spectral windows are included 00092 Default:""= all; Example: chans="3~20" 00093 stokes Stokes parameters to analyze. 00094 Default: none (all); Example: stokes="IQUV"; 00095 Example:stokes="I,Q" 00096 Options: "I","Q","U","V","RR","RL","LR","LL","XX","YX","XY","YY", ... 00097 includepix Range of pixel values to include 00098 default: [-1] (all pixels); example=[0.02,100.0] 00099 excludepix Range of pixel values to exclude 00100 default: [-1] (don"t exclude pixels); example=[100.,200.] 00101 outfile Output image file name (or root for multiple moments) 00102 default: "" (input+auto-determined suffix);example: outfile="source_moment" 00103 00104 If stretch is true and if the number of mask dimensions is less than 00105 or equal to the number of image dimensions and some axes in the 00106 mask are degenerate while the corresponding axes in the image are not, 00107 the mask will be stetched in the degenerate axis dimensions. For example, 00108 if the input image has shape [100, 200, 10] and the input 00109 mask has shape [100, 200, 1] and stretch is true, the mask will be 00110 stretched along the third dimension to shape [100, 200, 10]. However if 00111 the mask is shape [100, 200, 2], stretching is not possible and an 00112 error will result. 00113 00114 Example for finding the 1-momment, intensity-weighted 00115 coordinate, often used for finding velocity fields. 00116 immoments( axis="spec", imagename="myimage", moment=1, outfile="velocityfields" ) 00117 00118 Example finding the spectral mean, -1 moment, on a specified region 00119 of the image as defined by the box and stokes parameters 00120 taskname="immoments" 00121 default() 00122 imagename = "myimage" 00123 moment = -1 00124 00125 axis = "spec" 00126 stoke = "I" 00127 box = [55,12,97,32] 00128 go 00129 00130 Example using a mask created with a second file to select the 00131 data used to calculate the 0-moments, integrated values. In 00132 this case the mask is from the calibrated.im file and all values 00133 that have a value greater than 0.5 will be positive in the mask.. 00134 immoments( "clean.image", axis="spec", mask="calibrated.im>0.5", outfile="mom_withmask.im" ) 00135 00136 If an image has multiple (per-channel beams) and the moment axis is equal to the 00137 spectral axis, each channel will be convolved with a beam that is equal to the beam 00138 having the largest area in the beamset prior to moment determination. 00139 00140 00141 00142 """ 00143 if not hasattr(self, "__globals__") or self.__globals__ == None : 00144 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00145 #casac = self.__globals__['casac'] 00146 casalog = self.__globals__['casalog'] 00147 #casalog = casac.casac.logsink() 00148 self.__globals__['__last_task'] = 'immoments' 00149 self.__globals__['taskname'] = 'immoments' 00150 ### 00151 self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__) 00152 ### 00153 ### 00154 #Handle globals or user over-ride of arguments 00155 # 00156 function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults)) 00157 useLocalDefaults = False 00158 00159 for item in function_signature_defaults.iteritems(): 00160 key,val = item 00161 keyVal = eval(key) 00162 if (keyVal == None): 00163 #user hasn't set it - use global/default 00164 pass 00165 else: 00166 #user has set it - use over-ride 00167 if (key != 'self') : 00168 useLocalDefaults = True 00169 00170 myparams = {} 00171 if useLocalDefaults : 00172 for item in function_signature_defaults.iteritems(): 00173 key,val = item 00174 keyVal = eval(key) 00175 exec('myparams[key] = keyVal') 00176 self.parameters[key] = keyVal 00177 if (keyVal == None): 00178 exec('myparams[key] = '+ key + ' = self.itsdefault(key)') 00179 keyVal = eval(key) 00180 if(type(keyVal) == dict) : 00181 if len(keyVal) > 0 : 00182 exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']') 00183 else : 00184 exec('myparams[key] = ' + key + ' = {}') 00185 00186 else : 00187 async = self.parameters['async'] 00188 myparams['imagename'] = imagename = self.parameters['imagename'] 00189 myparams['moments'] = moments = self.parameters['moments'] 00190 myparams['axis'] = axis = self.parameters['axis'] 00191 myparams['region'] = region = self.parameters['region'] 00192 myparams['box'] = box = self.parameters['box'] 00193 myparams['chans'] = chans = self.parameters['chans'] 00194 myparams['stokes'] = stokes = self.parameters['stokes'] 00195 myparams['mask'] = mask = self.parameters['mask'] 00196 myparams['includepix'] = includepix = self.parameters['includepix'] 00197 myparams['excludepix'] = excludepix = self.parameters['excludepix'] 00198 myparams['outfile'] = outfile = self.parameters['outfile'] 00199 myparams['stretch'] = stretch = self.parameters['stretch'] 00200 00201 if type(moments)==int: moments=[moments] 00202 00203 result = None 00204 00205 # 00206 # The following is work around to avoid a bug with current python translation 00207 # 00208 mytmp = {} 00209 00210 mytmp['imagename'] = imagename 00211 mytmp['moments'] = moments 00212 mytmp['axis'] = axis 00213 mytmp['region'] = region 00214 mytmp['box'] = box 00215 mytmp['chans'] = chans 00216 mytmp['stokes'] = stokes 00217 mytmp['mask'] = mask 00218 mytmp['includepix'] = includepix 00219 mytmp['excludepix'] = excludepix 00220 mytmp['outfile'] = outfile 00221 mytmp['stretch'] = stretch 00222 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00223 trec = casac.casac.utils().torecord(pathname+'immoments.xml') 00224 00225 casalog.origin('immoments') 00226 try : 00227 #if not trec.has_key('immoments') or not casac.casac.utils().verify(mytmp, trec['immoments']) : 00228 #return False 00229 00230 casac.casac.utils().verify(mytmp, trec['immoments'], True) 00231 scriptstr=[''] 00232 saveinputs = self.__globals__['saveinputs'] 00233 saveinputs('immoments', 'immoments.last', myparams, self.__globals__,scriptstr=scriptstr) 00234 if async : 00235 count = 0 00236 keybase = time.strftime("%y%m%d.%H%M%S") 00237 key = keybase + "_" + str(count) 00238 while self.__async__.has_key(key) : 00239 count += 1 00240 key = keybase + "_" + str(count) 00241 result = tm.execute('immoments', imagename, moments, axis, region, box, chans, stokes, mask, includepix, excludepix, outfile, stretch) 00242 print "Use: " 00243 print " tm.retrieve(return_value) # to retrieve the status" 00244 print 00245 self.rkey = key 00246 self.__async__[key] = result 00247 else : 00248 tname = 'immoments' 00249 spaces = ' '*(18-len(tname)) 00250 casalog.post('\n##########################################'+ 00251 '\n##### Begin Task: ' + tname + spaces + ' #####') 00252 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00253 result = immoments(imagename, moments, axis, region, box, chans, stokes, mask, includepix, excludepix, outfile, stretch) 00254 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00255 '\n##########################################') 00256 00257 except Exception, instance: 00258 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00259 raise 00260 else : 00261 #print '**** Error **** ',instance 00262 tname = 'immoments' 00263 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00264 pass 00265 00266 gc.collect() 00267 return result 00268 # 00269 # 00270 # 00271 def paramgui(self, useGlobals=True, ipython_globals=None): 00272 """ 00273 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00274 """ 00275 import paramgui 00276 if not hasattr(self, "__globals__") or self.__globals__ == None : 00277 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00278 00279 if useGlobals: 00280 if ipython_globals == None: 00281 myf=self.__globals__ 00282 else: 00283 myf=ipython_globals 00284 00285 paramgui.setGlobals(myf) 00286 else: 00287 paramgui.setGlobals({}) 00288 00289 paramgui.runTask('immoments', myf['_ip']) 00290 paramgui.setGlobals({}) 00291 00292 # 00293 # 00294 # 00295 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00296 if not hasattr(self, "__globals__") or self.__globals__ == None : 00297 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00298 if ipython_globals == None: 00299 myf=self.__globals__ 00300 else: 00301 myf=ipython_globals 00302 00303 a = odict() 00304 a['imagename'] = '' 00305 a['moments'] = [0] 00306 a['axis'] = 'spectral' 00307 a['region'] = '' 00308 a['box'] = '' 00309 a['chans'] = '' 00310 a['stokes'] = '' 00311 a['mask'] = '' 00312 a['includepix'] = -1 00313 a['excludepix'] = -1 00314 a['outfile'] = '' 00315 00316 a['async']=False 00317 a['mask'] = { 00318 0:odict([{'notvalue':''}, {'stretch':False}])} 00319 00320 ### This function sets the default values but also will return the list of 00321 ### parameters or the default value of a given parameter 00322 if(param == None): 00323 myf['__set_default_parameters'](a) 00324 elif(param == 'paramkeys'): 00325 return a.keys() 00326 else: 00327 if(paramvalue==None and subparam==None): 00328 if(a.has_key(param)): 00329 return a[param] 00330 else: 00331 return self.itsdefault(param) 00332 else: 00333 retval=a[param] 00334 if(type(a[param])==dict): 00335 for k in range(len(a[param])): 00336 valornotval='value' 00337 if(a[param][k].has_key('notvalue')): 00338 valornotval='notvalue' 00339 if((a[param][k][valornotval])==paramvalue): 00340 retval=a[param][k].copy() 00341 retval.pop(valornotval) 00342 if(subparam != None): 00343 if(retval.has_key(subparam)): 00344 retval=retval[subparam] 00345 else: 00346 retval=self.itsdefault(subparam) 00347 else: 00348 retval=self.itsdefault(subparam) 00349 return retval 00350 00351 00352 # 00353 # 00354 def check_params(self, param=None, value=None, ipython_globals=None): 00355 if ipython_globals == None: 00356 myf=self.__globals__ 00357 else: 00358 myf=ipython_globals 00359 # print 'param:', param, 'value:', value 00360 try : 00361 if str(type(value)) != "<type 'instance'>" : 00362 value0 = value 00363 value = myf['cu'].expandparam(param, value) 00364 matchtype = False 00365 if(type(value) == numpy.ndarray): 00366 if(type(value) == type(value0)): 00367 myf[param] = value.tolist() 00368 else: 00369 #print 'value:', value, 'value0:', value0 00370 #print 'type(value):', type(value), 'type(value0):', type(value0) 00371 myf[param] = value0 00372 if type(value0) != list : 00373 matchtype = True 00374 else : 00375 myf[param] = value 00376 value = myf['cu'].verifyparam({param:value}) 00377 if matchtype: 00378 value = False 00379 except Exception, instance: 00380 #ignore the exception and just return it unchecked 00381 myf[param] = value 00382 return value 00383 # 00384 # 00385 def description(self, key='immoments', subkey=None): 00386 desc={'immoments': 'Compute moments from an image', 00387 'imagename': 'Name of the input image', 00388 'moments': 'List of moments you would like to compute', 00389 'axis': 'The momement axis: ra, dec, lat, long, spectral, or stokes', 00390 'region': 'Region specification. See help par.region. Default is to not use a region.', 00391 'box': 'Select one or more box regions', 00392 'chans': 'Select the channel(spectral) range', 00393 'stokes': 'Stokes params to image (I,IV,IQU,IQUV)', 00394 'mask': 'Mask to use. See help par.mask. Default is none.', 00395 'includepix': 'Range of pixel values to include', 00396 'excludepix': 'Range of pixel values to exclude', 00397 'outfile': 'Output image file name (or root for multiple moments) ', 00398 'stretch': 'Stretch the mask if necessary and possible? ', 00399 00400 'async': 'If true the taskname must be started using immoments(...)' 00401 } 00402 00403 # 00404 # Set subfields defaults if needed 00405 # 00406 00407 if(desc.has_key(key)) : 00408 return desc[key] 00409 00410 def itsdefault(self, paramname) : 00411 a = {} 00412 a['imagename'] = '' 00413 a['moments'] = [0] 00414 a['axis'] = 'spectral' 00415 a['region'] = '' 00416 a['box'] = '' 00417 a['chans'] = '' 00418 a['stokes'] = '' 00419 a['mask'] = '' 00420 a['includepix'] = -1 00421 a['excludepix'] = -1 00422 a['outfile'] = '' 00423 a['stretch'] = False 00424 00425 #a = sys._getframe(len(inspect.stack())-1).f_globals 00426 00427 if self.parameters['mask'] != '': 00428 a['stretch'] = False 00429 00430 if a.has_key(paramname) : 00431 return a[paramname] 00432 immoments_cli = immoments_cli_()