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_imhead import imhead 00018 class imhead_cli_: 00019 __name__ = "imhead" 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__ = (imhead_cli_,) 00028 self.__doc__ = self.__call__.__doc__ 00029 00030 self.parameters={'imagename':None, 'mode':None, 'hdkey':None, 'hdvalue':None, 'hdtype':None, 'hdcomment':None, 'verbose':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, mode=None, hdkey=None, hdvalue=None, hdtype=None, hdcomment=None, verbose=None, async=None): 00047 00048 """List, get and put image header parameters 00049 00050 This task allows the user to manipulate some meta-data parameters in an 00051 image. The mode='list' shows those keywords that are 00052 presently implemented, with their values. The contents associated 00053 with the keywords can be obtained (get) and changed (put). 00054 00055 Additional image parameter listings are available. 00056 00057 [For visibility files, the taskname='vishead' should be used.] 00058 00059 The modes that are available are: 00060 00061 list --- Lists the image header keywords and values. 00062 Use this if 'get' and 'put' are executed. 00063 get --- Get the specified keyword value(s) from the image 00064 put --- Put the specified keyword value(s) into the image 00065 00066 history --- Display the history information in hte CASA logger. 00067 summary --- Information summarizing the CASA image file. 00068 fits --- Lists the header information in a FITS style (not available) 00069 add --- Adds a new header key. Use with caution 00070 del --- Delete a header key, hdkey. Use with caution 00071 00072 Parameters currently implemented are listed using mode = 'list' 00073 00074 beammaj Major axis of the clean beam 00075 beammin Minor axis of the clean beam 00076 beampa Position angle of the clean beam 00077 NOTE: If the image contains multiple beams, use mode="summary" to get 00078 a listing. 00079 bunit Brightness unit (K, Jy/beam, etc) 00080 cdeltn Pixel size, nth axis (max n is 4) 00081 crpixn Pixel coordinate of reference point, nth axis 00082 crvaln Pixel location of reference point, nth axis 00083 ctypen Axis name, nth axis 00084 cunitn Pixel units, nth axis 00085 datamax Maximum pixel value in image 00086 datamin Minimum pixel value in image 00087 date-obs Date of the observation 00088 equinox Reference frame for directional coordinates 00089 imtype Image type: intensity, 00090 minpos 00091 minpixpos 00092 maxpos 00093 maxpixpos 00094 object Source name 00095 observer Observer name 00096 projection Image projection ('SIN','TAN', or 'ZEA') 00097 reffreqtype Reference frame for the spectral coordinates 00098 restfreq Rest Frequency 00099 shape Number of pixels along each axis 00100 telescope Telescope name 00101 00102 Keyword arguments: 00103 00104 imagename --- Name of input image 00105 default: none; example: imagename='ngc5921_task.image' 00106 mode --- Mode: options: 00107 default: none; 'list', 'summary', 'fits', 'history', 00108 'get', 'put', 'add', and 'del' 00109 00110 NOTE: 'add' and 'del' should be used with caution 00111 00112 hdkey --- keyword to use with get, put, add, or del 00113 default: none; example: hdkey='telescope' 00114 hdvalue --- keyword value that is 'got', or to be 'put' or 00115 to be 'added' 00116 default: ''; example: hdvalue='VLA' 00117 hdcomment --- comment to be stored with the keyword for mode='put' or mode='add' 00118 Examples: 00119 hdkey='date-obs';hdvalue='2007/06/20/00:00:00' 00120 hdkey='beammajor';hdvalue='55arcsec' 00121 hdkey='beampa'';hdvalue='0deg' 00122 hdkey='restfrequency';hdvalue='1.421GHz' 00123 hdkey='restfrequency';hdvalue='1.421GHz, 115.272GHz' 00124 hdkey='projection';hdvalue='TAN' 00125 hdkey='cdelt4';hdvalue=24415.05 00126 hdkey='cdelt1';hdvalue='7.75e-5deg' 00127 hdkey='crval1';hdvalue=qa.quantity( '763180', 'arsec') 00128 hdkey='crval1';hdvalue='14:07:58' 00129 hdkey='crval4';hdvalue='6250000Hz' 00130 00131 hdtype --- Used only with 'add' mode. It is the data type that 00132 is used to store the hdkey. It can not be used to 00133 change the data type of an exiting keyword. 00134 options: bool, int, string, doubple, complex 00135 default: none; example hdtype='double' 00136 00137 00138 Note that hdvalue will contain numbers, strings as well as units. 00139 00140 If mode="summary", verbose=True and the image contains multiple beams, the output, 00141 will contain information on every beam in the dataset. If mode="summary", 00142 verbose=False and the image has multiple beams, only a brief summary of 00143 beams for each polarization is listed. In this 00144 case, the beams with the maximum area, the minimum area, and the median area for 00145 each polarization are listed. If mode is not "summary" and/or the image does not 00146 have multiple beams, verbose is not used. 00147 00148 Examples: 00149 00150 1) get the clean beam from one image and put it in a second image 00151 00152 Get the clean beam from image1 into hdvalue 00153 imagename = 'image1.im'; mode = 'get'; hdkey = 'beam' 00154 hdvalue = imhead() 00155 print hdvalue # to see values 00156 00157 To then put the clean beam into image2 00158 imagename = 'image2.im', mode = 'put'; imhead() 00159 00160 2) Most output values are dictionaries: 00161 00162 00163 mode = 'get'; hdkey = 'maxpos'; aa = imhead() 00164 00165 would give for the command print aa 00166 {'value': '03:19:48.160, +41.30.42.103, I, 4.88163e+09Hz', 'unit': ''} 00167 print aa['value'] gives 00168 03:19:48.160, +41.30.42.103, I, 4.88163e+09Hz 00169 print aa['value'[1][0:12] gives 03:19:48.160 00170 00171 00172 mode = 'get'; hdkey = 'crpix1'; aa = imhead() 00173 00174 would give for the command print aa 00175 {'value': '128.0', 'unit': ''} 00176 print aa['value'] gives 00177 128.0 (a string) 00178 00179 3) The use of put is a bit more straight-forward 00180 00181 mode = 'put'; hdkey = 'crpix1'; hdvalue = '200'; imhead() 00182 then 00183 mode = 'get'; hdkey = 'crpix1'; aa = imhead() would give 00184 {'value': '200.0', 'unit': ''} 00185 00186 00187 00188 """ 00189 if not hasattr(self, "__globals__") or self.__globals__ == None : 00190 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00191 #casac = self.__globals__['casac'] 00192 casalog = self.__globals__['casalog'] 00193 #casalog = casac.casac.logsink() 00194 self.__globals__['__last_task'] = 'imhead' 00195 self.__globals__['taskname'] = 'imhead' 00196 ### 00197 self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__) 00198 ### 00199 ### 00200 #Handle globals or user over-ride of arguments 00201 # 00202 function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults)) 00203 useLocalDefaults = False 00204 00205 for item in function_signature_defaults.iteritems(): 00206 key,val = item 00207 keyVal = eval(key) 00208 if (keyVal == None): 00209 #user hasn't set it - use global/default 00210 pass 00211 else: 00212 #user has set it - use over-ride 00213 if (key != 'self') : 00214 useLocalDefaults = True 00215 00216 myparams = {} 00217 if useLocalDefaults : 00218 for item in function_signature_defaults.iteritems(): 00219 key,val = item 00220 keyVal = eval(key) 00221 exec('myparams[key] = keyVal') 00222 self.parameters[key] = keyVal 00223 if (keyVal == None): 00224 exec('myparams[key] = '+ key + ' = self.itsdefault(key)') 00225 keyVal = eval(key) 00226 if(type(keyVal) == dict) : 00227 if len(keyVal) > 0 : 00228 exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']') 00229 else : 00230 exec('myparams[key] = ' + key + ' = {}') 00231 00232 else : 00233 async = self.parameters['async'] 00234 myparams['imagename'] = imagename = self.parameters['imagename'] 00235 myparams['mode'] = mode = self.parameters['mode'] 00236 myparams['hdkey'] = hdkey = self.parameters['hdkey'] 00237 myparams['hdvalue'] = hdvalue = self.parameters['hdvalue'] 00238 myparams['hdtype'] = hdtype = self.parameters['hdtype'] 00239 myparams['hdcomment'] = hdcomment = self.parameters['hdcomment'] 00240 myparams['verbose'] = verbose = self.parameters['verbose'] 00241 00242 00243 result = None 00244 00245 # 00246 # The following is work around to avoid a bug with current python translation 00247 # 00248 mytmp = {} 00249 00250 mytmp['imagename'] = imagename 00251 mytmp['mode'] = mode 00252 mytmp['hdkey'] = hdkey 00253 mytmp['hdvalue'] = hdvalue 00254 mytmp['hdtype'] = hdtype 00255 mytmp['hdcomment'] = hdcomment 00256 mytmp['verbose'] = verbose 00257 pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/' 00258 trec = casac.casac.utils().torecord(pathname+'imhead.xml') 00259 00260 casalog.origin('imhead') 00261 try : 00262 #if not trec.has_key('imhead') or not casac.casac.utils().verify(mytmp, trec['imhead']) : 00263 #return False 00264 00265 casac.casac.utils().verify(mytmp, trec['imhead'], True) 00266 scriptstr=[''] 00267 saveinputs = self.__globals__['saveinputs'] 00268 saveinputs('imhead', 'imhead.last', myparams, self.__globals__,scriptstr=scriptstr) 00269 if async : 00270 count = 0 00271 keybase = time.strftime("%y%m%d.%H%M%S") 00272 key = keybase + "_" + str(count) 00273 while self.__async__.has_key(key) : 00274 count += 1 00275 key = keybase + "_" + str(count) 00276 result = tm.execute('imhead', imagename, mode, hdkey, hdvalue, hdtype, hdcomment, verbose) 00277 print "Use: " 00278 print " tm.retrieve(return_value) # to retrieve the status" 00279 print 00280 self.rkey = key 00281 self.__async__[key] = result 00282 else : 00283 tname = 'imhead' 00284 spaces = ' '*(18-len(tname)) 00285 casalog.post('\n##########################################'+ 00286 '\n##### Begin Task: ' + tname + spaces + ' #####') 00287 casalog.post(scriptstr[1][1:]+'\n', 'INFO') 00288 result = imhead(imagename, mode, hdkey, hdvalue, hdtype, hdcomment, verbose) 00289 casalog.post('##### End Task: ' + tname + ' ' + spaces + ' #####'+ 00290 '\n##########################################') 00291 00292 except Exception, instance: 00293 if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) : 00294 raise 00295 else : 00296 #print '**** Error **** ',instance 00297 tname = 'imhead' 00298 casalog.post('An error occurred running task '+tname+'.', 'ERROR') 00299 pass 00300 00301 gc.collect() 00302 return result 00303 # 00304 # 00305 # 00306 def paramgui(self, useGlobals=True, ipython_globals=None): 00307 """ 00308 Opens a parameter GUI for this task. If useGlobals is true, then any relevant global parameter settings are used. 00309 """ 00310 import paramgui 00311 if not hasattr(self, "__globals__") or self.__globals__ == None : 00312 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00313 00314 if useGlobals: 00315 if ipython_globals == None: 00316 myf=self.__globals__ 00317 else: 00318 myf=ipython_globals 00319 00320 paramgui.setGlobals(myf) 00321 else: 00322 paramgui.setGlobals({}) 00323 00324 paramgui.runTask('imhead', myf['_ip']) 00325 paramgui.setGlobals({}) 00326 00327 # 00328 # 00329 # 00330 def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None): 00331 if not hasattr(self, "__globals__") or self.__globals__ == None : 00332 self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals 00333 if ipython_globals == None: 00334 myf=self.__globals__ 00335 else: 00336 myf=ipython_globals 00337 00338 a = odict() 00339 a['imagename'] = '' 00340 a['mode'] = 'summary' 00341 00342 a['async']=False 00343 a['mode'] = { 00344 0:odict([{'value':'summary'}, {'verbose':False}]), 00345 1:{'value':'list'}, 00346 2:{'value':'history'}, 00347 3:{'value':'fits'}, 00348 4:odict([{'value':'put'}, {'hdkey':''}, {'hdvalue':''}, {'hdtype':''}, {'hdcomment':''}]), 00349 5:odict([{'value':'add'}, {'hdkey':''}, {'hdvalue':''}, {'hdtype':''}, {'hdcomment':''}]), 00350 6:odict([{'value':'get'}, {'hdkey':''}]), 00351 7:odict([{'value':'del'}, {'hdkey':''}])} 00352 00353 ### This function sets the default values but also will return the list of 00354 ### parameters or the default value of a given parameter 00355 if(param == None): 00356 myf['__set_default_parameters'](a) 00357 elif(param == 'paramkeys'): 00358 return a.keys() 00359 else: 00360 if(paramvalue==None and subparam==None): 00361 if(a.has_key(param)): 00362 return a[param] 00363 else: 00364 return self.itsdefault(param) 00365 else: 00366 retval=a[param] 00367 if(type(a[param])==dict): 00368 for k in range(len(a[param])): 00369 valornotval='value' 00370 if(a[param][k].has_key('notvalue')): 00371 valornotval='notvalue' 00372 if((a[param][k][valornotval])==paramvalue): 00373 retval=a[param][k].copy() 00374 retval.pop(valornotval) 00375 if(subparam != None): 00376 if(retval.has_key(subparam)): 00377 retval=retval[subparam] 00378 else: 00379 retval=self.itsdefault(subparam) 00380 else: 00381 retval=self.itsdefault(subparam) 00382 return retval 00383 00384 00385 # 00386 # 00387 def check_params(self, param=None, value=None, ipython_globals=None): 00388 if ipython_globals == None: 00389 myf=self.__globals__ 00390 else: 00391 myf=ipython_globals 00392 # print 'param:', param, 'value:', value 00393 try : 00394 if str(type(value)) != "<type 'instance'>" : 00395 value0 = value 00396 value = myf['cu'].expandparam(param, value) 00397 matchtype = False 00398 if(type(value) == numpy.ndarray): 00399 if(type(value) == type(value0)): 00400 myf[param] = value.tolist() 00401 else: 00402 #print 'value:', value, 'value0:', value0 00403 #print 'type(value):', type(value), 'type(value0):', type(value0) 00404 myf[param] = value0 00405 if type(value0) != list : 00406 matchtype = True 00407 else : 00408 myf[param] = value 00409 value = myf['cu'].verifyparam({param:value}) 00410 if matchtype: 00411 value = False 00412 except Exception, instance: 00413 #ignore the exception and just return it unchecked 00414 myf[param] = value 00415 return value 00416 # 00417 # 00418 def description(self, key='imhead', subkey=None): 00419 desc={'imhead': 'List, get and put image header parameters', 00420 'imagename': 'Name of the input image', 00421 'mode': 'imhead options: add, del, get, history, list, put, summary ', 00422 'hdkey': 'The FITS keyword', 00423 'hdvalue': 'Value of hdkey)', 00424 'hdtype': 'Data type of the header keyword.', 00425 'hdcomment': 'Comment associated with the header keyword', 00426 'verbose': 'Give a full listing of beams or just a short summary? Only used when the image has multiple beams and mode="summary".', 00427 00428 'async': 'If true the taskname must be started using imhead(...)' 00429 } 00430 00431 # 00432 # Set subfields defaults if needed 00433 # 00434 00435 if(desc.has_key(key)) : 00436 return desc[key] 00437 00438 def itsdefault(self, paramname) : 00439 a = {} 00440 a['imagename'] = '' 00441 a['mode'] = 'summary' 00442 a['hdkey'] = '' 00443 a['hdvalue'] = '' 00444 a['hdtype'] = '' 00445 a['hdcomment'] = '' 00446 a['verbose'] = False 00447 00448 #a = sys._getframe(len(inspect.stack())-1).f_globals 00449 00450 if self.parameters['mode'] == 'summary': 00451 a['verbose'] = False 00452 00453 if self.parameters['mode'] == 'put': 00454 a['hdkey'] = '' 00455 a['hdvalue'] = '' 00456 a['hdtype'] = '' 00457 a['hdcomment'] = '' 00458 00459 if self.parameters['mode'] == 'add': 00460 a['hdkey'] = '' 00461 a['hdvalue'] = '' 00462 a['hdtype'] = '' 00463 a['hdcomment'] = '' 00464 00465 if self.parameters['mode'] == 'get': 00466 a['hdkey'] = '' 00467 00468 if self.parameters['mode'] == 'del': 00469 a['hdkey'] = '' 00470 00471 if a.has_key(paramname) : 00472 return a[paramname] 00473 imhead_cli = imhead_cli_()