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_imstat import imstat 00018 class imstat_cli_: 00019 __name__ = "imstat" 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__ = (imstat_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'imagename':None, 'axes':None, 'region':None, 'box':None, 'chans':None, 'stokes':None, 'listit':None, 'verbose':None, 'mask':None, 'stretch':None, 'logfile':None, 'append':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, axes=None, region=None, box=None, chans=None, stokes=None, listit=None, verbose=None, mask=None, stretch=None, logfile=None, append=None, async=None): 00047 00048 """Displays statistical information from an image or image region 00049 00050 Many parameters are determined from the specified region of an image. 00051 For this version, the region can be specified by a set of rectangular 00052 pixel coordinates, the channel ranges and the Stokes. 00053 00054 For directed output, run as 00055 myoutput = imstat() 00056 00057 00058 Keyword arguments: 00059 imagename Name of input image 00060 Default: none; Example: imagename='ngc5921_task.im' 00061 axes axes to compute statistics over. -1 => all axes. 00062 region Region of interest. See help par.region. 00063 box A box region specified in pixels on the directional plane 00064 Default: none (whole 2-D plane); 00065 Example: box='10,10,50,50' 00066 box = '10,10,30,30,35,35,50,50' (two boxes) 00067 chans Zero based channel numbers 00068 Range of channel numbers to include in statistics 00069 All spectral windows are included 00070 Default:''= all; Example: chans='3~20' 00071 stokes Stokes parameters to analyze. 00072 Default: all; Example: stokes='IQUV'; 00073 Example:stokes='I,Q' 00074 Options: 'I','Q','U','V','RR','RL','LR','LL','XX','YX','XY','YY', ... 00075 listit Print stats and bounding box to logger? 00076 verbose Print additional messages to logger? 00077 mask Mask to use. See help par.mask. Default is none. 00078 stretch Stretch the mask if necessary and possible? See help par.stretch 00079 logfile Name of file to write fit results. 00080 append If logfile exists, append to it (True) or overwrite it (False). 00081 00082 00083 General procedure: 00084 00085 1. Specify inputs, then 00086 00087 2. myoutput = imstat() 00088 or specify inputs directly in calling sequence to task 00089 myoutput = imstat(imagename='image.im', etc) 00090 00091 3. myoutput['KEYS'] will contain the result associated with any 00092 of the keys given below 00093 00094 KEYS CURRENTLY AVAILABLE 00095 blc - absolute PIXEL coordinate of the bottom left corner of 00096 the bounding box surrounding the selected region 00097 blcf - Same as blc, but uses WORLD coordinates instead of pixels 00098 trc - the absolute PIXEL coordinate of the top right corner 00099 of the bounding box surrounding the selected region 00100 trcf - Same as trc, but uses WORLD coordinates instead of pixels 00101 flux - the integrated flux density if the beam is defined and 00102 the if brightness units are $Jy/beam$ 00103 npts - the number of unmasked points used 00104 max - the maximum pixel value 00105 min - minimum pixel value 00106 maxpos - absolute PIXEL coordinate of maximum pixel value 00107 maxposf - Same as maxpos, but uses WORLD coordinates instead of pixels 00108 minpos - absolute pixel coordinate of minimum pixel value 00109 minposf - Same as minpos, but uses WORLD coordinates instead of pixels 00110 sum - the sum of the pixel values: $\sum I_i$ 00111 sumsq - the sum of the squares of the pixel values: $\sum I_i^2$ 00112 mean - the mean of pixel values: 00113 $\bar{I} = \sum I_i / n$ 00114 sigma - the standard deviation about the mean: 00115 $\sigma^2 = (\sum I_i - \bar{I})^2 / (n-1)$ 00116 rms - the root mean square: 00117 $\sqrt {\sum I_i^2 / n}$ 00118 median - the median pixel value 00119 medabsdevmed - the median of the absolute deviations from the 00120 median 00121 quartile - the inter-quartile range. Find the points 00122 which are 25% largest and 75% largest (the median is 00123 50% largest), find their difference and divide that 00124 difference by 2. 00125 00126 Additional Examples 00127 # Selected two box region 00128 # box 1, bottom-left coord is 2,3 and top-right coord is 14,15 00129 # box 2, bottom-left coord is 30,31 and top-right coord is 42,43 00130 imstat( 'myImage', box='2,3,14,15;30,31,42,43' ) 00131 00132 # Select the same two box regions but only channels 4 and 5 00133 imstat( 'myImage', box='2,3,14,15;30,31,42,43', chan='4~5' ) 00134 00135 # Select all channels greater the 20 as well as channel 0. 00136 # Then the mean and standard deviation are printed 00137 results = imstat( 'myImage', chans='>20;0' ) 00138 print "Mean is: ", results['mean'], " s.d. ", results['sigma'] 00139 00140 # Find statistical information for the Q stokes value only 00141 # then the I stokes values only, and printing out the statistical 00142 # values that we are interested in. 00143 s1 = imstat( 'myimage', stokes='Q' ) 00144 s2 = imstat( 'myimage', stokes='I' ) 00145 print " | MIN | MAX | MEAN" 00146 print " Q | ",s1['min'][0]," | ",s1['max'][0]," | ",," | ",s1['mean'][0] 00147 print " I | ",s2['min'][0]," | ",s2['max'][0]," | ",," | ",s2['mean'][0] 00148 00149 # evaluate statistics for each spectral plane in an ra x dec x frequency image 00150 ia.fromshape("", [20,30,40]) 00151 # give pixels non-zero values 00152 ia.addnoise() 00153 # These are the display axes, the calculation of statistics occurs 00154 # for each (hyper)plane along axes not listed in the axes parameter, 00155 # in this case axis 2 (the frequency axis) 00156 # display the rms for each frequency plane (your mileage will vary with 00157 # the values). 00158 stats = ia.statistics(axes=[0,1]) 00159 stats["rms"] 00160 Out[10]: 00161 array([ 0.99576014, 1.03813124, 0.97749186, 0.97587883, 1.04189885, 00162 1.03784776, 1.03371549, 1.03153074, 1.00841606, 0.947155 , 00163 0.97335404, 0.94389403, 1.0010221 , 0.97151822, 1.03942156, 00164 1.01158476, 0.96957082, 1.04212773, 1.00589049, 0.98696715, 00165 1.00451481, 1.02307892, 1.03102005, 0.97334671, 0.95209879, 00166 1.02088714, 0.96999902, 0.98661619, 1.01039267, 0.96842754, 00167 0.99464947, 1.01536798, 1.02466023, 0.96956468, 0.98090756, 00168 0.9835844 , 0.95698935, 1.05487967, 0.99846411, 0.99634868]) 00169 00170 00171 00172 """ 00173 if not hasattr(self, "__globals__") or self.__globals__ == None : 00174 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00175 #casac = self.__globals__['casac'] 00176 casalog = self.__globals__['casalog'] 00177 #casalog = casac.casac.logsink() 00178 self.__globals__['__last_task'] = 'imstat' 00179 self.__globals__['taskname'] = 'imstat' 00180 ### 00181 self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__) 00182 ### 00183 ### 00184 #Handle globals or user over-ride of arguments 00185 # 00186 function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults)) 00187 useLocalDefaults = False 00188 00189 for item in function_signature_defaults.iteritems(): 00190 key,val = item 00191 keyVal = eval(key) 00192 if (keyVal == None): 00193 #user hasn't set it - use global/default 00194 pass 00195 else: 00196 #user has set it - use over-ride 00197 if (key != 'self') : 00198 useLocalDefaults = True 00199 00200 myparams = {} 00201 if useLocalDefaults : 00202 for item in function_signature_defaults.iteritems(): 00203 key,val = item 00204 keyVal = eval(key) 00205 exec('myparams[key] = keyVal') 00206 self.parameters[key] = keyVal 00207 if (keyVal == None): 00208 exec('myparams[key] = '+ key + ' = self.itsdefault(key)') 00209 keyVal = eval(key) 00210 if(type(keyVal) == dict) : 00211 if len(keyVal) > 0 : 00212 exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']') 00213 else : 00214 exec('myparams[key] = ' + key + ' = {}') 00215 00216 else : 00217 async = self.parameters['async'] 00218 myparams['imagename'] = imagename = self.parameters['imagename'] 00219 myparams['axes'] = axes = self.parameters['axes'] 00220 myparams['region'] = region = self.parameters['region'] 00221 myparams['box'] = box = self.parameters['box'] 00222 myparams['chans'] = chans = self.parameters['chans'] 00223 myparams['stokes'] = stokes = self.parameters['stokes'] 00224 myparams['listit'] = listit = self.parameters['listit'] 00225 myparams['verbose'] = verbose = self.parameters['verbose'] 00226 myparams['mask'] = mask = self.parameters['mask'] 00227 myparams['stretch'] = stretch = self.parameters['stretch'] 00228 myparams['logfile'] = logfile = self.parameters['logfile'] 00229 myparams['append'] = append = self.parameters['append'] 00230 00231 00232 result = None 00233 00234 # 00235 # The following is work around to avoid a bug with current python translation 00236 # 00237 mytmp = {} 00238 00239 mytmp['imagename'] = imagename 00240 mytmp['axes'] = axes 00241 mytmp['region'] = region 00242 mytmp['box'] = box 00243 mytmp['chans'] = chans 00244 mytmp['stokes'] = stokes 00245 mytmp['listit'] = listit 00246 mytmp['verbose'] = verbose 00247 mytmp['mask'] = mask 00248 mytmp['stretch'] = stretch 00249 mytmp['logfile'] = logfile 00250 mytmp['append'] = append 00251 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00252 trec = casac.casac.utils().torecord(pathname+'imstat.xml') 00253 00254 casalog.origin('imstat') 00255 try : 00256 #if not trec.has_key('imstat') or not casac.casac.utils().verify(mytmp, trec['imstat']) : 00257 #return False 00258 00259 casac.casac.utils().verify(mytmp, trec['imstat'], True) 00260 scriptstr=[''] 00261 saveinputs = self.__globals__['saveinputs'] 00262 saveinputs('imstat', 'imstat.last', myparams, self.__globals__,scriptstr=scriptstr) 00263 if async : 00264 count = 0 00265 keybase = time.strftime("%y%m%d.%H%M%S") 00266 key = keybase + "_" + str(count) 00267 while self.__async__.has_key(key) : 00268 count += 1 00269 key = keybase + "_" + str(count) 00270 result = tm.execute('imstat', imagename, axes, region, box, chans, stokes, listit, verbose, mask, stretch, logfile, append) 00271 print "Use: " 00272 print " tm.retrieve(return_value) # to retrieve the status" 00273 print 00274 self.rkey = key 00275 self.__async__[key] = result 00276 else : 00277 tname = 'imstat' 00278 spaces = ' '*(18-len(tname)) 00279 casalog.post('\n##########################################'+ 00280 '\n##### Begin Task: ' + tname + spaces + ' #####') 00281 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00282 result = imstat(imagename, axes, region, box, chans, stokes, listit, verbose, mask, stretch, logfile, append) 00283 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00284 '\n##########################################') 00285 00286 except Exception, instance: 00287 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00288 raise 00289 else : 00290 #print '**** Error **** ',instance 00291 tname = 'imstat' 00292 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00293 pass 00294 00295 gc.collect() 00296 return result 00297 # 00298 # 00299 # 00300 def paramgui(self, useGlobals=True, ipython_globals=None): 00301 """ 00302 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00303 """ 00304 import paramgui 00305 if not hasattr(self, "__globals__") or self.__globals__ == None : 00306 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00307 00308 if useGlobals: 00309 if ipython_globals == None: 00310 myf=self.__globals__ 00311 else: 00312 myf=ipython_globals 00313 00314 paramgui.setGlobals(myf) 00315 else: 00316 paramgui.setGlobals({}) 00317 00318 paramgui.runTask('imstat', myf['_ip']) 00319 paramgui.setGlobals({}) 00320 00321 # 00322 # 00323 # 00324 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00325 if not hasattr(self, "__globals__") or self.__globals__ == None : 00326 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00327 if ipython_globals == None: 00328 myf=self.__globals__ 00329 else: 00330 myf=ipython_globals 00331 00332 a = odict() 00333 a['imagename'] = '' 00334 a['axes'] = -1 00335 a['region'] = '' 00336 a['box'] = '' 00337 a['chans'] = '' 00338 a['stokes'] = '' 00339 a['listit'] = True 00340 a['verbose'] = True 00341 a['mask'] = '' 00342 a['logfile'] = '' 00343 00344 a['async']=False 00345 a['mask'] = { 00346 0:odict([{'notvalue':''}, {'stretch':False}])} 00347 a['logfile'] = { 00348 0:odict([{'notvalue':''}, {'append':True}])} 00349 00350 ### This function sets the default values but also will return the list of 00351 ### parameters or the default value of a given parameter 00352 if(param == None): 00353 myf['__set_default_parameters'](a) 00354 elif(param == 'paramkeys'): 00355 return a.keys() 00356 else: 00357 if(paramvalue==None and subparam==None): 00358 if(a.has_key(param)): 00359 return a[param] 00360 else: 00361 return self.itsdefault(param) 00362 else: 00363 retval=a[param] 00364 if(type(a[param])==dict): 00365 for k in range(len(a[param])): 00366 valornotval='value' 00367 if(a[param][k].has_key('notvalue')): 00368 valornotval='notvalue' 00369 if((a[param][k][valornotval])==paramvalue): 00370 retval=a[param][k].copy() 00371 retval.pop(valornotval) 00372 if(subparam != None): 00373 if(retval.has_key(subparam)): 00374 retval=retval[subparam] 00375 else: 00376 retval=self.itsdefault(subparam) 00377 else: 00378 retval=self.itsdefault(subparam) 00379 return retval 00380 00381 00382 # 00383 # 00384 def check_params(self, param=None, value=None, ipython_globals=None): 00385 if ipython_globals == None: 00386 myf=self.__globals__ 00387 else: 00388 myf=ipython_globals 00389 # print 'param:', param, 'value:', value 00390 try : 00391 if str(type(value)) != "<type 'instance'>" : 00392 value0 = value 00393 value = myf['cu'].expandparam(param, value) 00394 matchtype = False 00395 if(type(value) == numpy.ndarray): 00396 if(type(value) == type(value0)): 00397 myf[param] = value.tolist() 00398 else: 00399 #print 'value:', value, 'value0:', value0 00400 #print 'type(value):', type(value), 'type(value0):', type(value0) 00401 myf[param] = value0 00402 if type(value0) != list : 00403 matchtype = True 00404 else : 00405 myf[param] = value 00406 value = myf['cu'].verifyparam({param:value}) 00407 if matchtype: 00408 value = False 00409 except Exception, instance: 00410 #ignore the exception and just return it unchecked 00411 myf[param] = value 00412 return value 00413 # 00414 # 00415 def description(self, key='imstat', subkey=None): 00416 desc={'imstat': 'Displays statistical information from an image or image region', 00417 'imagename': 'Name of the input image', 00418 'axes': 'List of axes to evaluate statistics over. Default is all axes.', 00419 'region': 'Image Region or name. Use Viewer', 00420 'box': 'Select one or more box regions', 00421 'chans': 'Select the channel(spectral) range', 00422 'stokes': 'Stokes params to image (I,IV,IQU,IQUV). Default "" => include all', 00423 'listit': 'Print stats and bounding box to logger?', 00424 'verbose': 'Print additional messages to logger?', 00425 'mask': 'Mask to use. See help par.mask. Default is none.', 00426 'stretch': 'Stretch the mask if necessary and possible? See help par.stretch ', 00427 'logfile': 'Name of file to write fit results.', 00428 'append': 'If logfile exists, append to it if True or overwrite it if False', 00429 00430 'async': 'If true the taskname must be started using imstat(...)' 00431 } 00432 00433 # 00434 # Set subfields defaults if needed 00435 # 00436 00437 if(desc.has_key(key)) : 00438 return desc[key] 00439 00440 def itsdefault(self, paramname) : 00441 a = {} 00442 a['imagename'] = '' 00443 a['axes'] = -1 00444 a['region'] = '' 00445 a['box'] = '' 00446 a['chans'] = '' 00447 a['stokes'] = '' 00448 a['listit'] = True 00449 a['verbose'] = True 00450 a['mask'] = '' 00451 a['stretch'] = False 00452 a['logfile'] = '' 00453 a['append'] = True 00454 00455 #a = sys._getframe(len(inspect.stack())-1).f_globals 00456 00457 if self.parameters['mask'] != '': 00458 a['stretch'] = False 00459 00460 if self.parameters['logfile'] != '': 00461 a['append'] = True 00462 00463 if a.has_key(paramname) : 00464 return a[paramname] 00465 imstat_cli = imstat_cli_()