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