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_imval import imval 00018 class imval_cli_: 00019 __name__ = "imval" 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__ = (imval_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'imagename':None, 'region':None, 'box':None, 'chans':None, 'stokes':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, region=None, box=None, chans=None, stokes=None, async=None): 00047 00048 """Get the data value(s) and/or mask value in an image. 00049 The data point(s) to be retrieved are those found in the specified 00050 region, which may be: 00051 1. A region file from the viewer (region parameter) 00052 2. A region specified by a set of rectangular 00053 pixel coordinates, the channel ranges and/or the Stokes. 00054 00055 For directed output, run as 00056 myoutput = imval() 00057 00058 00059 Keyword arguments: 00060 imagename -- Name of input image 00061 Default: none; Example: imagename='ngc5921_task.im' 00062 region -- region file or name. 00063 Use the viewer, then region manager to select regions of 00064 the image to process. Similar to box, but graphical 00065 Or the name of a region stored with the image, 00066 use rg.namesintable() 00067 to retrieve the list of names. 00068 Default: none 00069 Example: region='myimage.im.rgn' 00070 region='region1' 00071 box -- A box region on the directional plane 00072 Only pixel values acceptable at this time. 00073 Default: '' (referencepixel values for the Directional coord); 00074 Example: box='10,10,50,50' 00075 box = '10,10,30,30,35,35,50,50' (two boxes) 00076 box = '-1,-1' (all points) 00077 chans -- channel numbers 00078 Range of channel numbers to include in statistics 00079 All spectral windows are included 00080 Default:''= all; Example: chans='3~20'; 00081 chans='-1' (all channels) 00082 stokes -- Stokes parameters to analyze. 00083 Default: none (all); Example: stokes='IQUV'; 00084 stokes='I,Q' 00085 stokes='-1' (all stokes values) 00086 Options: 'I','Q','U','V','RR','RL','LR','LL','XX','YX','XY','YY', ... 00087 00088 General procedure: 00089 00090 1. Specify inputs, then 00091 00092 2. myoutput = imval() 00093 or specify inputs directly in calling sequence to task 00094 myoutput = imsval(imagename='image.im', etc) 00095 00096 3. myoutput['KEYS'] will contain the result associated with any 00097 of the keys given below 00098 00099 KEYS CURRENTLY AVAILABLE 00100 blc - absolute PIXEL coordinate of the bottom left corner of 00101 the bounding box surrounding the selected region 00102 trc - the absolute PIXEL coordinate of the top right corner 00103 of the bounding box surrOunding the selected region 00104 axes - List the data stored in each axis of the data block. 00105 unit - unit of the returned data values. 00106 data - data value(s) found in the given region 00107 mask - mask value(s) found in the given region 00108 00109 NOTE: The data returned is in the same order as it is internally 00110 stored, typically RA, DEC, spectral, stokes. Also both the data 00111 and mask values are returned as Python Numpy arrays, for more 00112 information on how to manipulate them see 00113 http://numpy.scipy.org/#array_interface 00114 00115 00116 Additional Examples 00117 # The value and mask value at a single point (5,17,2,Q) 00118 imval( 'myImage', box='5,5,17,17', chans=2, stokes='Q' ) 00119 00120 # Select and report on two box regions 00121 # box 1, bottom-left coord is 2,3 and top-right coord is 14,15 00122 # box 2, bottom-left coord is 30,31 and top-right coord is 42,43 00123 # Note that only the boxes for the 00124 imval( 'myImage', box='2,3,14,15;30,31,42,43' ) 00125 00126 # Select the same two box regions but only channels 4 and 5 00127 imval( 'myImage', box='2,3,14,15;30,31,42,43', chan='4~5' ) 00128 00129 # Select all channels greater the 20 as well as channel 0. 00130 # Then the mean and standard deviation are printed 00131 # Note that the data returned is a Python numpy array which 00132 # has built in operations such as min, max, and means as 00133 # demonstrated here. 00134 results = imval( 'myImage', chans='>20;0' ) 00135 imval_data=results['data'] 00136 mask=results['mask'] 00137 # holds the absolute coordinates of the associated pixels in imval_data 00138 coords = results['coords'] 00139 print "Data max: ", imval_data.max(), " mean is ", imval_data.mean() 00140 swapped_data=imval_data.swapaxes(0,2) 00141 swapped_mask=mask.swapaxes(0,2) 00142 print "Data values for 21st channel: \n", swapped_data[0] 00143 print "Mask values for 21st channel: \n", swapped_mask[0] 00144 00145 """ 00146 if not hasattr(self, "__globals__") or self.__globals__ == None : 00147 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00148 #casac = self.__globals__['casac'] 00149 casalog = self.__globals__['casalog'] 00150 #casalog = casac.casac.logsink() 00151 self.__globals__['__last_task'] = 'imval' 00152 self.__globals__['taskname'] = 'imval' 00153 ### 00154 self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__) 00155 ### 00156 ### 00157 #Handle globals or user over-ride of arguments 00158 # 00159 function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults)) 00160 useLocalDefaults = False 00161 00162 for item in function_signature_defaults.iteritems(): 00163 key,val = item 00164 keyVal = eval(key) 00165 if (keyVal == None): 00166 #user hasn't set it - use global/default 00167 pass 00168 else: 00169 #user has set it - use over-ride 00170 if (key != 'self') : 00171 useLocalDefaults = True 00172 00173 myparams = {} 00174 if useLocalDefaults : 00175 for item in function_signature_defaults.iteritems(): 00176 key,val = item 00177 keyVal = eval(key) 00178 exec('myparams[key] = keyVal') 00179 self.parameters[key] = keyVal 00180 if (keyVal == None): 00181 exec('myparams[key] = '+ key + ' = self.itsdefault(key)') 00182 keyVal = eval(key) 00183 if(type(keyVal) == dict) : 00184 if len(keyVal) > 0 : 00185 exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']') 00186 else : 00187 exec('myparams[key] = ' + key + ' = {}') 00188 00189 else : 00190 async = self.parameters['async'] 00191 myparams['imagename'] = imagename = self.parameters['imagename'] 00192 myparams['region'] = region = self.parameters['region'] 00193 myparams['box'] = box = self.parameters['box'] 00194 myparams['chans'] = chans = self.parameters['chans'] 00195 myparams['stokes'] = stokes = self.parameters['stokes'] 00196 00197 00198 result = None 00199 00200 # 00201 # The following is work around to avoid a bug with current python translation 00202 # 00203 mytmp = {} 00204 00205 mytmp['imagename'] = imagename 00206 mytmp['region'] = region 00207 mytmp['box'] = box 00208 mytmp['chans'] = chans 00209 mytmp['stokes'] = stokes 00210 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00211 trec = casac.casac.utils().torecord(pathname+'imval.xml') 00212 00213 casalog.origin('imval') 00214 try : 00215 #if not trec.has_key('imval') or not casac.casac.utils().verify(mytmp, trec['imval']) : 00216 #return False 00217 00218 casac.casac.utils().verify(mytmp, trec['imval'], True) 00219 scriptstr=[''] 00220 saveinputs = self.__globals__['saveinputs'] 00221 saveinputs('imval', 'imval.last', myparams, self.__globals__,scriptstr=scriptstr) 00222 if async : 00223 count = 0 00224 keybase = time.strftime("%y%m%d.%H%M%S") 00225 key = keybase + "_" + str(count) 00226 while self.__async__.has_key(key) : 00227 count += 1 00228 key = keybase + "_" + str(count) 00229 result = tm.execute('imval', imagename, region, box, chans, stokes) 00230 print "Use: " 00231 print " tm.retrieve(return_value) # to retrieve the status" 00232 print 00233 self.rkey = key 00234 self.__async__[key] = result 00235 else : 00236 tname = 'imval' 00237 spaces = ' '*(18-len(tname)) 00238 casalog.post('\n##########################################'+ 00239 '\n##### Begin Task: ' + tname + spaces + ' #####') 00240 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00241 result = imval(imagename, region, box, chans, stokes) 00242 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00243 '\n##########################################') 00244 00245 except Exception, instance: 00246 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00247 raise 00248 else : 00249 #print '**** Error **** ',instance 00250 tname = 'imval' 00251 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00252 pass 00253 00254 for arg in result : 00255 if not async and not result.has_key(arg) : 00256 throw('Missing output value '+arg) 00257 00258 gc.collect() 00259 return result 00260 # 00261 # 00262 # 00263 def paramgui(self, useGlobals=True, ipython_globals=None): 00264 """ 00265 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00266 """ 00267 import paramgui 00268 if not hasattr(self, "__globals__") or self.__globals__ == None : 00269 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00270 00271 if useGlobals: 00272 if ipython_globals == None: 00273 myf=self.__globals__ 00274 else: 00275 myf=ipython_globals 00276 00277 paramgui.setGlobals(myf) 00278 else: 00279 paramgui.setGlobals({}) 00280 00281 paramgui.runTask('imval', myf['_ip']) 00282 paramgui.setGlobals({}) 00283 00284 # 00285 # 00286 # 00287 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00288 if not hasattr(self, "__globals__") or self.__globals__ == None : 00289 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00290 if ipython_globals == None: 00291 myf=self.__globals__ 00292 else: 00293 myf=ipython_globals 00294 00295 a = odict() 00296 a['imagename'] = '' 00297 a['region'] = '' 00298 a['box'] = '' 00299 a['chans'] = '' 00300 a['stokes'] = '' 00301 00302 a['async']=False 00303 00304 ### This function sets the default values but also will return the list of 00305 ### parameters or the default value of a given parameter 00306 if(param == None): 00307 myf['__set_default_parameters'](a) 00308 elif(param == 'paramkeys'): 00309 return a.keys() 00310 else: 00311 if(paramvalue==None and subparam==None): 00312 if(a.has_key(param)): 00313 return a[param] 00314 else: 00315 return self.itsdefault(param) 00316 else: 00317 retval=a[param] 00318 if(type(a[param])==dict): 00319 for k in range(len(a[param])): 00320 valornotval='value' 00321 if(a[param][k].has_key('notvalue')): 00322 valornotval='notvalue' 00323 if((a[param][k][valornotval])==paramvalue): 00324 retval=a[param][k].copy() 00325 retval.pop(valornotval) 00326 if(subparam != None): 00327 if(retval.has_key(subparam)): 00328 retval=retval[subparam] 00329 else: 00330 retval=self.itsdefault(subparam) 00331 else: 00332 retval=self.itsdefault(subparam) 00333 return retval 00334 00335 00336 # 00337 # 00338 def check_params(self, param=None, value=None, ipython_globals=None): 00339 if ipython_globals == None: 00340 myf=self.__globals__ 00341 else: 00342 myf=ipython_globals 00343 # print 'param:', param, 'value:', value 00344 try : 00345 if str(type(value)) != "<type 'instance'>" : 00346 value0 = value 00347 value = myf['cu'].expandparam(param, value) 00348 matchtype = False 00349 if(type(value) == numpy.ndarray): 00350 if(type(value) == type(value0)): 00351 myf[param] = value.tolist() 00352 else: 00353 #print 'value:', value, 'value0:', value0 00354 #print 'type(value):', type(value), 'type(value0):', type(value0) 00355 myf[param] = value0 00356 if type(value0) != list : 00357 matchtype = True 00358 else : 00359 myf[param] = value 00360 value = myf['cu'].verifyparam({param:value}) 00361 if matchtype: 00362 value = False 00363 except Exception, instance: 00364 #ignore the exception and just return it unchecked 00365 myf[param] = value 00366 return value 00367 # 00368 # 00369 def description(self, key='imval', subkey=None): 00370 desc={'imval': 'Get the data value(s) and/or mask value in an image.', 00371 'imagename': 'Name of the input image', 00372 'region': 'Image Region or name. Use viewer', 00373 'box': 'Select one or more box regions', 00374 'chans': 'Select the channel(spectral) range', 00375 'stokes': 'Stokes params to image (I,IV,IQU,IQUV)', 00376 00377 'async': 'If true the taskname must be started using imval(...)' 00378 } 00379 00380 # 00381 # Set subfields defaults if needed 00382 # 00383 00384 if(desc.has_key(key)) : 00385 return desc[key] 00386 00387 def itsdefault(self, paramname) : 00388 a = {} 00389 a['imagename'] = '' 00390 a['region'] = '' 00391 a['box'] = '' 00392 a['chans'] = '' 00393 a['stokes'] = '' 00394 00395 #a = sys._getframe(len(inspect.stack())-1).f_globals 00396 00397 if a.has_key(paramname) : 00398 return a[paramname] 00399 imval_cli = imval_cli_()