casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imcollapse_cli.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 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_imcollapse import imcollapse
00018 class imcollapse_cli_:
00019     __name__ = "imcollapse"
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__ = (imcollapse_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'function':None, 'axes':None, 'outfile':None, 'box':None, 'region':None, 'chans':None, 'stokes':None, 'mask':None, 'wantreturn':None, 'overwrite':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, function=None, axes=None, outfile=None, box=None, region=None, chans=None, stokes=None, mask=None, wantreturn=None, overwrite=None, stretch=None,  async=None):
00047 
00048         """Collapse image along one axis, aggregating pixel values along that axis.
00049 PARAMETER SUMMARY
00050 imagename        Name of the input (CASA, FITS, MIRIAD) image
00051 function         Function used to compute aggregation of pixel values along the collapsed
00052                  axis. Supported functions are max, mean, median, min, rms, stdev,
00053                  sum, variance. Minimum match is supported for the function parameter (eg,
00054                  function="r" will compute the rms of the pixel values).
00055 axis             Zero-based axis number(s) or minimal match strings to compress.
00056 outfile          Name of output CASA image. If not specified, no image is written
00057                  but an image analysis tool which references the output image is returned.
00058 overwrite        If output file is specified, controls if an already existing file by the
00059                  same name can be overwritten. If true, the user is not prompted, the file
00060                  if it exists is automatically overwritten.
00061 box              Direction plane box specification, "blcx, blcy, trcx, trcy". Only one box
00062                  may be specified. If not specified, region is used if specified. If region
00063                  is also not specified, entire directional plane unioned with any chans and
00064                  stokes specification determines the region.
00065 region           Region specification. See help par.region. Default is to not use a region.
00066 chans            Optional contiguous frequency channel number specification. Not used if
00067                  region is specified. Default is all channels.
00068 stokes           Contiguous stokes planes specification. Not used if region is specified.
00069                  Default is all stokes.
00070 mask             Mask to use. See help par.mask. Default is none.
00071 stretch          Stretch the input mask if necessary and possible. Only used if a mask is specified.
00072                  See help par.stretch.
00073 wantreturn       If true, return an image analysis tool referencing the collapsed image, if
00074                  false, return false.
00075 
00076 This task collapses an image along a specified axis or set of axes of N pixels to a single pixel on each
00077 specified axis. It computes the specified aggregate function for pixel values along the specified axes
00078 and places those values in the single remaining plane of those axes in the output image. It returns
00079 an image analysis tool containing the newly created collapsed image if wantreturn=True. Choices of
00080 aggregate functions are: max, mean, median, min, rms, stdev, sum, variance. Minimal unique match is
00081 supported for the function parameter (eg, function="r" will compute the rms of the pixel values, "med"
00082 will compute the median).
00083         
00084 Axes can be specified as a single integer or array of integers indicating the zero-based axes along
00085 which to collapse the image. Axes may also be specified as a single or array of strings which minimally
00086 and uniquely match (ignoring case) world axes names in the image (eg "dec" or ["ri, "d"] for
00087 collapsing along the declination axis or along the right ascension and declination axes, respectively).
00088         
00089 If outfile is not specified (or contains only white spaces), no image is written but, if wantreturn=True,
00090 the collapsed image is still able to be accessed via the returned image analysis tool which references
00091 the collpased image. If the returned object is not wanted it should still be captured and deleted via its
00092 done() method. If this is not done, there is no gaurantee for when the python garbage collector will delete
00093 it. If the returned object is wanted, it should be deleted as soon as possible for the same reasons, eg
00094         
00095 collapsed_image = imcollapse(..., wantreturn=T)
00096 # do things (or not) with collapsed_image and when done with object, do
00097 collapsed_image.done()
00098 
00099 The reference pixel of the collapsed axis is set to 0 and its reference value is set to the mean
00100 of the the first and last values of that axis in the specified region of the input image.
00101 
00102 # myimage.im is a 512x512x128x4 (ra,dec,freq,stokes) image
00103 imagename = "myimage.im"
00104 # collapse a subimage of it along its spectral axis avoiding the 8 edge
00105 # channels at each end of the band, computing the mean value of the pixels
00106 # resulting image is 256x256x1x4 in size.
00107 outfile="collapse_spec_mean.im"
00108 function="mean"
00109 axis=2
00110 box="127,127,383,383"
00111 chans="8~119"
00112 collapsed = imcollapse(imagename=imagename, outfile=outfile, function=function, axes=axis, box=box, chans=chans, wantreturn=True)
00113 # manipulate collapsed
00114 collapsed.done()
00115 T
00116 
00117         """
00118         if not hasattr(self, "__globals__") or self.__globals__ == None :
00119            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00120         #casac = self.__globals__['casac']
00121         casalog = self.__globals__['casalog']
00122         #casalog = casac.casac.logsink()
00123         self.__globals__['__last_task'] = 'imcollapse'
00124         self.__globals__['taskname'] = 'imcollapse'
00125         ###
00126         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00127         ###
00128         ###
00129         #Handle globals or user over-ride of arguments
00130         #
00131         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00132         useLocalDefaults = False
00133 
00134         for item in function_signature_defaults.iteritems():
00135                 key,val = item
00136                 keyVal = eval(key)
00137                 if (keyVal == None):
00138                         #user hasn't set it - use global/default
00139                         pass
00140                 else:
00141                         #user has set it - use over-ride
00142                         if (key != 'self') :
00143                            useLocalDefaults = True
00144 
00145         myparams = {}
00146         if useLocalDefaults :
00147            for item in function_signature_defaults.iteritems():
00148                key,val = item
00149                keyVal = eval(key)
00150                exec('myparams[key] = keyVal')
00151                self.parameters[key] = keyVal
00152                if (keyVal == None):
00153                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00154                    keyVal = eval(key)
00155                    if(type(keyVal) == dict) :
00156                       if len(keyVal) > 0 :
00157                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00158                       else :
00159                          exec('myparams[key] = ' + key + ' = {}')
00160 
00161         else :
00162             async = self.parameters['async']
00163             myparams['imagename'] = imagename = self.parameters['imagename']
00164             myparams['function'] = function = self.parameters['function']
00165             myparams['axes'] = axes = self.parameters['axes']
00166             myparams['outfile'] = outfile = self.parameters['outfile']
00167             myparams['box'] = box = self.parameters['box']
00168             myparams['region'] = region = self.parameters['region']
00169             myparams['chans'] = chans = self.parameters['chans']
00170             myparams['stokes'] = stokes = self.parameters['stokes']
00171             myparams['mask'] = mask = self.parameters['mask']
00172             myparams['wantreturn'] = wantreturn = self.parameters['wantreturn']
00173             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00174             myparams['stretch'] = stretch = self.parameters['stretch']
00175 
00176 
00177         result = None
00178 
00179 #
00180 #    The following is work around to avoid a bug with current python translation
00181 #
00182         mytmp = {}
00183 
00184         mytmp['imagename'] = imagename
00185         mytmp['function'] = function
00186         mytmp['axes'] = axes
00187         mytmp['outfile'] = outfile
00188         mytmp['box'] = box
00189         mytmp['region'] = region
00190         mytmp['chans'] = chans
00191         mytmp['stokes'] = stokes
00192         mytmp['mask'] = mask
00193         mytmp['wantreturn'] = wantreturn
00194         mytmp['overwrite'] = overwrite
00195         mytmp['stretch'] = stretch
00196         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00197         trec = casac.casac.utils().torecord(pathname+'imcollapse.xml')
00198 
00199         casalog.origin('imcollapse')
00200         try :
00201           #if not trec.has_key('imcollapse') or not casac.casac.utils().verify(mytmp, trec['imcollapse']) :
00202             #return False
00203 
00204           casac.casac.utils().verify(mytmp, trec['imcollapse'], True)
00205           scriptstr=['']
00206           saveinputs = self.__globals__['saveinputs']
00207           saveinputs('imcollapse', 'imcollapse.last', myparams, self.__globals__,scriptstr=scriptstr)
00208           if async :
00209             count = 0
00210             keybase =  time.strftime("%y%m%d.%H%M%S")
00211             key = keybase + "_" + str(count)
00212             while self.__async__.has_key(key) :
00213                count += 1
00214                key = keybase + "_" + str(count)
00215             result = tm.execute('imcollapse', imagename, function, axes, outfile, box, region, chans, stokes, mask, wantreturn, overwrite, stretch)
00216             print "Use: "
00217             print "      tm.retrieve(return_value) # to retrieve the status"
00218             print 
00219             self.rkey = key
00220             self.__async__[key] = result
00221           else :
00222               tname = 'imcollapse'
00223               spaces = ' '*(18-len(tname))
00224               casalog.post('\n##########################################'+
00225                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00226               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00227               result = imcollapse(imagename, function, axes, outfile, box, region, chans, stokes, mask, wantreturn, overwrite, stretch)
00228               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00229                            '\n##########################################')
00230 
00231         except Exception, instance:
00232           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00233              raise
00234           else :
00235              #print '**** Error **** ',instance
00236              tname = 'imcollapse'
00237              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00238              pass
00239 
00240         gc.collect()
00241         return result
00242 #
00243 #
00244 #
00245     def paramgui(self, useGlobals=True, ipython_globals=None):
00246         """
00247         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00248         """
00249         import paramgui
00250         if not hasattr(self, "__globals__") or self.__globals__ == None :
00251            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00252 
00253         if useGlobals:
00254             if ipython_globals == None:
00255                 myf=self.__globals__
00256             else:
00257                 myf=ipython_globals
00258 
00259             paramgui.setGlobals(myf)
00260         else:
00261             paramgui.setGlobals({})
00262 
00263         paramgui.runTask('imcollapse', myf['_ip'])
00264         paramgui.setGlobals({})
00265 
00266 #
00267 #
00268 #
00269     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00270         if not hasattr(self, "__globals__") or self.__globals__ == None :
00271            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00272         if ipython_globals == None:
00273             myf=self.__globals__
00274         else:
00275             myf=ipython_globals
00276 
00277         a = odict()
00278         a['imagename']  = ''
00279         a['function']  = ''
00280         a['axes']  = [0]
00281         a['outfile']  = ''
00282         a['box']  = ''
00283         a['chans']  = ''
00284         a['stokes']  = ''
00285         a['mask']  = ''
00286         a['wantreturn']  = False
00287         a['stretch']  = False
00288 
00289         a['async']=False
00290         a['outfile'] = {
00291                     0:odict([{'notvalue':''}, {'overwrite':False}])}
00292         a['box'] = {
00293                     0:odict([{'value':''}, {'region':""}])}
00294         a['mask'] = {
00295                     0:odict([{'notvalue':''}, {'stretch':False}])}
00296 
00297 ### This function sets the default values but also will return the list of
00298 ### parameters or the default value of a given parameter
00299         if(param == None):
00300                 myf['__set_default_parameters'](a)
00301         elif(param == 'paramkeys'):
00302                 return a.keys()
00303         else:
00304             if(paramvalue==None and subparam==None):
00305                if(a.has_key(param)):
00306                   return a[param]
00307                else:
00308                   return self.itsdefault(param)
00309             else:
00310                retval=a[param]
00311                if(type(a[param])==dict):
00312                   for k in range(len(a[param])):
00313                      valornotval='value'
00314                      if(a[param][k].has_key('notvalue')):
00315                         valornotval='notvalue'
00316                      if((a[param][k][valornotval])==paramvalue):
00317                         retval=a[param][k].copy()
00318                         retval.pop(valornotval)
00319                         if(subparam != None):
00320                            if(retval.has_key(subparam)):
00321                               retval=retval[subparam]
00322                            else:
00323                               retval=self.itsdefault(subparam)
00324                      else:
00325                         retval=self.itsdefault(subparam)
00326                return retval
00327 
00328 
00329 #
00330 #
00331     def check_params(self, param=None, value=None, ipython_globals=None):
00332       if ipython_globals == None:
00333           myf=self.__globals__
00334       else:
00335           myf=ipython_globals
00336 #      print 'param:', param, 'value:', value
00337       try :
00338          if str(type(value)) != "<type 'instance'>" :
00339             value0 = value
00340             value = myf['cu'].expandparam(param, value)
00341             matchtype = False
00342             if(type(value) == numpy.ndarray):
00343                if(type(value) == type(value0)):
00344                   myf[param] = value.tolist()
00345                else:
00346                   #print 'value:', value, 'value0:', value0
00347                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00348                   myf[param] = value0
00349                   if type(value0) != list :
00350                      matchtype = True
00351             else :
00352                myf[param] = value
00353             value = myf['cu'].verifyparam({param:value})
00354             if matchtype:
00355                value = False
00356       except Exception, instance:
00357          #ignore the exception and just return it unchecked
00358          myf[param] = value
00359       return value
00360 #
00361 #
00362     def description(self, key='imcollapse', subkey=None):
00363         desc={'imcollapse': 'Collapse image along one axis, aggregating pixel values along that axis.',
00364                'imagename': 'Name of the input image',
00365                'function': 'Function used to compute aggregation of pixel values.',
00366                'axes': 'Zero-based axis number(s) or minimal match strings to collapse.',
00367                'outfile': 'Name of output CASA image.',
00368                'box': 'Optional direction plane box ("blcx, blcy, trcx trcy").',
00369                'region': 'Region specification. See help par.region. Default is to not use a region.',
00370                'chans': 'Optional zero-based contiguous frequency channel specification.',
00371                'stokes': 'Optional contiguous stokes planes specification.',
00372                'mask': 'Mask to use. See help par.mask. Default is none.',
00373                'wantreturn': 'Should an image analysis tool referencing the collapsed image be returned?',
00374                'overwrite': 'Overwrite exisitng ouput file if it exists?',
00375                'stretch': 'Stretch the mask if necessary and possible? See help par.stretch ',
00376 
00377                'async': 'If true the taskname must be started using imcollapse(...)'
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['function']  = ''
00391         a['axes']  = [0]
00392         a['outfile']  = ''
00393         a['box']  = ''
00394         a['region']  = ''
00395         a['chans']  = ''
00396         a['stokes']  = ''
00397         a['mask']  = ''
00398         a['wantreturn']  = False
00399         a['overwrite']  = False
00400         a['stretch']  = False
00401 
00402         #a = sys._getframe(len(inspect.stack())-1).f_globals
00403 
00404         if self.parameters['outfile']  != '':
00405             a['overwrite'] = False
00406 
00407         if self.parameters['box']  == '':
00408             a['region'] = ""
00409 
00410         if self.parameters['mask']  != '':
00411             a['stretch'] = False
00412 
00413         if a.has_key(paramname) :
00414               return a[paramname]
00415 imcollapse_cli = imcollapse_cli_()