casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imsmooth_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_imsmooth import imsmooth
00018 class imsmooth_cli_:
00019     __name__ = "imsmooth"
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__ = (imsmooth_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'kernel':None, 'major':None, 'minor':None, 'pa':None, 'targetres':None, 'region':None, 'box':None, 'chans':None, 'stokes':None, 'mask':None, 'outfile':None, 'stretch':None, 'overwrite':None, 'beam':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, kernel=None, major=None, minor=None, pa=None, targetres=None, region=None, box=None, chans=None, stokes=None, mask=None, outfile=None, stretch=None, overwrite=None, beam=None,  async=None):
00047 
00048         """Smooth an image or portion of an image
00049 This task performs a Fourier-based convolution to 'smooth' the
00050 image. Smoothing is typically performed in order to reduce the noise in
00051 an image.
00052 
00053         Keyword arguments:
00054         imagename -- Input image name
00055                 Default: none; Example: imagename='ngc5921_task.im'
00056         outfile -- Output smoothed image file name
00057                 default: 'imsmooth_results.im'; 
00058                 example: outfile='my.image.smooth';
00059     kernel -- Type of kernel to use when smoothing (gaussian or boxcar).
00060                 default: 'gauss'; example: kernel='gauss'
00061                 options: 'gauss' or 'boxcar' 
00062     major -- Depends on the kernel type, see explanation below.
00063     minor -- Depends on the kernel type, see explanation below.       
00064     pa    -- position angle to use for gaussian kernel, unused for boxcar.
00065     beam  -- When kernel="gauss", this parameter can be used instead of major,
00066              minor, and pa to specify the gaussian parameters. See details below.
00067     targetres -- Used only for gaussian kernels. If True, major, minor, and
00068              pa, or beam, are the resolution of the output image. If false, a gaussian
00069              with these parameters is convolved with the input image to produce
00070              the output image.
00071     mask --  Mask to use. See help par.mask. Default is none.
00072     region -- region file or name.
00073               Use the viewer, then region manager to select regions of
00074               the image to process.  Similar to box, but graphical
00075               Or the name of a region stored with the image, 
00076               use rg.namesintable()
00077               to retrieve the list of names.
00078               Default: none
00079               Example: region='myimage.im.rgn'
00080                          region='region1'
00081         box --  A box region on the directional plane
00082                 ONLY pixel values acceptable at this time.
00083                 Default: none (whole 2-D plane); Example: box='10,10,50,50'
00084         chans -- channel numbers to select for the continuum,
00085                 ONLY channel numbers accepted at this time.
00086                 Default: none (all); 
00087                   Example: chans='3~6;>40'
00088         stokes -- Stokes parameters to image
00089                 Example: 'I'
00090                 Default: none (all);
00091                 Options: 'I','Q','U','V','RR','RL','LR','LL','XX','YX','XY','YY', ... 
00092 
00093 Kernel Parameters
00094 -----------------
00095 Finally, and most importantly the kernel is specified via the
00096 major and minor parameters. 
00097 
00098 Gaussian kernel: major and minor are the full width at half maximum 
00099                  (FWHM) of the Gaussian. pa is the position angle
00100                  of the gaussian. In addition, the targetres parameter
00101                  indicates if the specified gaussian is to be the
00102                  resolution of the final image (True) or if it is to
00103                  be used to convolve the input image to create the
00104                  output image. If True, the input image must have
00105                  a restoring beam in its header.
00106                  If the image has multiple beams and targetres=True,
00107                  all planes in the image will be convolved so that the
00108                  resulting resolution is that specified by the beam parameter.
00109                  If the image has multiple beams and targetres=False, each plane
00110                  will be convolved with a Gaussian specified by beam (and hence, in
00111                  general, the output image will also have multiple beams that vary
00112                  with spectral channel and/or polarization).
00113 Boxcar kernel:   major, length of the box along the y-axis and
00114                  minor, length of the box along the x-axis
00115 
00116 The major, minor, and pa parameters can be specified in one of three ways
00117    Quantity -- for example major=qa.quantity(1, 'arcsec')
00118                Note that you can use pixel units, such as 
00119                major=qa.quantity(1, 'pix')
00120    String -- for example minor='1pix' or major='0.5km'
00121              (i.e. a string that the Quanta quantity function accepts).
00122    Numeric -- for example major=10.
00123               In this case, the units of major and minor are assumed to 
00124               be in arcsec and units of pa are assumed to be degrees. 
00125 
00126 In the case of a Gaussian, the beam parameter offers an alternate way of
00127 describing the convolving Gaussian. If used, neither major, minor,
00128 nor pa can be specified. The beam parameter must have exactly three
00129 fields: "major", "minor", and "pa" (or "positionangle"). This is, not coincidentally,
00130 the record format for the output of ia.restoringbeam(). For example
00131 
00132 beam = {"major": "5arcsec", "minor": "2arcsec", "pa": "20deg"}
00133 
00134 If both beam and any of major, minor, and/or pa is specified for a Gaussian kernel,
00135 an exception will be thrown.
00136 
00137 Note: Using pixel units allows you to convolve axes with different units.
00138 
00139 # EXAMPLE 1
00140 # smoothing with a gaussian kernel 20arseconds by 10 arseconds
00141 imsmooth( imagename='my.image', kernel='gauss', major='10arcsec', minor='10arcsec')
00142 
00143 # EXAMPLE 2
00144 # Smoothing using pixel coordinates and a boxcar kernel.
00145 imsmooth( imagename='new.image', major='20pix', minor='10pix', kernel='boxcar')
00146 
00147 
00148         """
00149         if not hasattr(self, "__globals__") or self.__globals__ == None :
00150            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00151         #casac = self.__globals__['casac']
00152         casalog = self.__globals__['casalog']
00153         #casalog = casac.casac.logsink()
00154         self.__globals__['__last_task'] = 'imsmooth'
00155         self.__globals__['taskname'] = 'imsmooth'
00156         ###
00157         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00158         ###
00159         ###
00160         #Handle globals or user over-ride of arguments
00161         #
00162         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00163         useLocalDefaults = False
00164 
00165         for item in function_signature_defaults.iteritems():
00166                 key,val = item
00167                 keyVal = eval(key)
00168                 if (keyVal == None):
00169                         #user hasn't set it - use global/default
00170                         pass
00171                 else:
00172                         #user has set it - use over-ride
00173                         if (key != 'self') :
00174                            useLocalDefaults = True
00175 
00176         myparams = {}
00177         if useLocalDefaults :
00178            for item in function_signature_defaults.iteritems():
00179                key,val = item
00180                keyVal = eval(key)
00181                exec('myparams[key] = keyVal')
00182                self.parameters[key] = keyVal
00183                if (keyVal == None):
00184                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00185                    keyVal = eval(key)
00186                    if(type(keyVal) == dict) :
00187                       if len(keyVal) > 0 :
00188                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00189                       else :
00190                          exec('myparams[key] = ' + key + ' = {}')
00191 
00192         else :
00193             async = self.parameters['async']
00194             myparams['imagename'] = imagename = self.parameters['imagename']
00195             myparams['kernel'] = kernel = self.parameters['kernel']
00196             myparams['major'] = major = self.parameters['major']
00197             myparams['minor'] = minor = self.parameters['minor']
00198             myparams['pa'] = pa = self.parameters['pa']
00199             myparams['targetres'] = targetres = self.parameters['targetres']
00200             myparams['region'] = region = self.parameters['region']
00201             myparams['box'] = box = self.parameters['box']
00202             myparams['chans'] = chans = self.parameters['chans']
00203             myparams['stokes'] = stokes = self.parameters['stokes']
00204             myparams['mask'] = mask = self.parameters['mask']
00205             myparams['outfile'] = outfile = self.parameters['outfile']
00206             myparams['stretch'] = stretch = self.parameters['stretch']
00207             myparams['overwrite'] = overwrite = self.parameters['overwrite']
00208             myparams['beam'] = beam = self.parameters['beam']
00209 
00210 
00211         result = None
00212 
00213 #
00214 #    The following is work around to avoid a bug with current python translation
00215 #
00216         mytmp = {}
00217 
00218         mytmp['imagename'] = imagename
00219         mytmp['kernel'] = kernel
00220         mytmp['major'] = major
00221         mytmp['minor'] = minor
00222         mytmp['pa'] = pa
00223         mytmp['targetres'] = targetres
00224         mytmp['region'] = region
00225         mytmp['box'] = box
00226         mytmp['chans'] = chans
00227         mytmp['stokes'] = stokes
00228         mytmp['mask'] = mask
00229         mytmp['outfile'] = outfile
00230         mytmp['stretch'] = stretch
00231         mytmp['overwrite'] = overwrite
00232         mytmp['beam'] = beam
00233         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00234         trec = casac.casac.utils().torecord(pathname+'imsmooth.xml')
00235 
00236         casalog.origin('imsmooth')
00237         try :
00238           #if not trec.has_key('imsmooth') or not casac.casac.utils().verify(mytmp, trec['imsmooth']) :
00239             #return False
00240 
00241           casac.casac.utils().verify(mytmp, trec['imsmooth'], True)
00242           scriptstr=['']
00243           saveinputs = self.__globals__['saveinputs']
00244           saveinputs('imsmooth', 'imsmooth.last', myparams, self.__globals__,scriptstr=scriptstr)
00245           if async :
00246             count = 0
00247             keybase =  time.strftime("%y%m%d.%H%M%S")
00248             key = keybase + "_" + str(count)
00249             while self.__async__.has_key(key) :
00250                count += 1
00251                key = keybase + "_" + str(count)
00252             result = tm.execute('imsmooth', imagename, kernel, major, minor, pa, targetres, region, box, chans, stokes, mask, outfile, stretch, overwrite, beam)
00253             print "Use: "
00254             print "      tm.retrieve(return_value) # to retrieve the status"
00255             print 
00256             self.rkey = key
00257             self.__async__[key] = result
00258           else :
00259               tname = 'imsmooth'
00260               spaces = ' '*(18-len(tname))
00261               casalog.post('\n##########################################'+
00262                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00263               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00264               result = imsmooth(imagename, kernel, major, minor, pa, targetres, region, box, chans, stokes, mask, outfile, stretch, overwrite, beam)
00265               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00266                            '\n##########################################')
00267 
00268         except Exception, instance:
00269           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00270              raise
00271           else :
00272              #print '**** Error **** ',instance
00273              tname = 'imsmooth'
00274              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00275              pass
00276 
00277         gc.collect()
00278         return result
00279 #
00280 #
00281 #
00282     def paramgui(self, useGlobals=True, ipython_globals=None):
00283         """
00284         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00285         """
00286         import paramgui
00287         if not hasattr(self, "__globals__") or self.__globals__ == None :
00288            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00289 
00290         if useGlobals:
00291             if ipython_globals == None:
00292                 myf=self.__globals__
00293             else:
00294                 myf=ipython_globals
00295 
00296             paramgui.setGlobals(myf)
00297         else:
00298             paramgui.setGlobals({})
00299 
00300         paramgui.runTask('imsmooth', myf['_ip'])
00301         paramgui.setGlobals({})
00302 
00303 #
00304 #
00305 #
00306     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00307         if not hasattr(self, "__globals__") or self.__globals__ == None :
00308            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00309         if ipython_globals == None:
00310             myf=self.__globals__
00311         else:
00312             myf=ipython_globals
00313 
00314         a = odict()
00315         a['imagename']  = ''
00316         a['kernel']  = 'gauss'
00317         a['region']  = ''
00318         a['box']  = ''
00319         a['chans']  = ''
00320         a['stokes']  = ''
00321         a['mask']  = ''
00322         a['outfile']  = ''
00323         a['overwrite']  = False
00324 
00325         a['async']=False
00326         a['kernel'] = {
00327                     0:odict([{'value':'gauss'}, {'major':'2.5arcsec'}, {'minor':'2.0arcsec'}, {'pa':'0deg'}, {'beam':''}, {'targetres':False}]), 
00328                     1:odict([{'value':'gaussian'}, {'major':'2.5arcsec'}, {'minor':'2.0arcsec'}, {'pa':'0deg'}, {'beam':''}, {'targetres':False}]), 
00329                     2:odict([{'value':'box'}, {'major':'2.0arcsec'}, {'minor':'2.0arcsec'}]), 
00330                     3:odict([{'value':'boxcar'}, {'major':'2.0arcsec'}, {'minor':'2.0arcsec'}])}
00331         a['mask'] = {
00332                     0:odict([{'notvalue':''}, {'stretch':False}])}
00333 
00334 ### This function sets the default values but also will return the list of
00335 ### parameters or the default value of a given parameter
00336         if(param == None):
00337                 myf['__set_default_parameters'](a)
00338         elif(param == 'paramkeys'):
00339                 return a.keys()
00340         else:
00341             if(paramvalue==None and subparam==None):
00342                if(a.has_key(param)):
00343                   return a[param]
00344                else:
00345                   return self.itsdefault(param)
00346             else:
00347                retval=a[param]
00348                if(type(a[param])==dict):
00349                   for k in range(len(a[param])):
00350                      valornotval='value'
00351                      if(a[param][k].has_key('notvalue')):
00352                         valornotval='notvalue'
00353                      if((a[param][k][valornotval])==paramvalue):
00354                         retval=a[param][k].copy()
00355                         retval.pop(valornotval)
00356                         if(subparam != None):
00357                            if(retval.has_key(subparam)):
00358                               retval=retval[subparam]
00359                            else:
00360                               retval=self.itsdefault(subparam)
00361                      else:
00362                         retval=self.itsdefault(subparam)
00363                return retval
00364 
00365 
00366 #
00367 #
00368     def check_params(self, param=None, value=None, ipython_globals=None):
00369       if ipython_globals == None:
00370           myf=self.__globals__
00371       else:
00372           myf=ipython_globals
00373 #      print 'param:', param, 'value:', value
00374       try :
00375          if str(type(value)) != "<type 'instance'>" :
00376             value0 = value
00377             value = myf['cu'].expandparam(param, value)
00378             matchtype = False
00379             if(type(value) == numpy.ndarray):
00380                if(type(value) == type(value0)):
00381                   myf[param] = value.tolist()
00382                else:
00383                   #print 'value:', value, 'value0:', value0
00384                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00385                   myf[param] = value0
00386                   if type(value0) != list :
00387                      matchtype = True
00388             else :
00389                myf[param] = value
00390             value = myf['cu'].verifyparam({param:value})
00391             if matchtype:
00392                value = False
00393       except Exception, instance:
00394          #ignore the exception and just return it unchecked
00395          myf[param] = value
00396       return value
00397 #
00398 #
00399     def description(self, key='imsmooth', subkey=None):
00400         desc={'imsmooth': 'Smooth an image or portion of an image',
00401                'imagename': 'Name of the input image',
00402                'kernel': 'Type of kernel to use: gaussian or boxcar.',
00403                'major': 'Major axis for the kernels, default direction is along y-axis.',
00404                'minor': 'Minor axis in gaussian and boxcar kernels',
00405                'pa': 'Position angle for gaussian kernel',
00406                'targetres': 'If gaussian kernel, specified parameters are to be resolution of output image (True) or parameters of gaussian to convolve with input image (False).',
00407                'region': 'Image Region or name.  Use viewer',
00408                'box': 'Select one or more box regions',
00409                'chans': 'Select the spectral channel range',
00410                'stokes': 'Stokes parameters to image (I,IV,IQU,IQUV)',
00411                'mask': 'Mask to use. See help par.mask. Default is none.',
00412                'outfile': 'Output, smoothed, image file name ',
00413                'stretch': 'Stretch the mask if necessary and possible? See help par.stretch ',
00414                'overwrite': 'Overwrite (unprompted) pre-existing output file?',
00415                'beam': 'Alternate way of describing a Gaussian. If specified, must be a dictionary with keys "major", "minor", and "pa" (or "positionangle")',
00416 
00417                'async': 'If true the taskname must be started using imsmooth(...)'
00418               }
00419 
00420 #
00421 # Set subfields defaults if needed
00422 #
00423 
00424         if(desc.has_key(key)) :
00425            return desc[key]
00426 
00427     def itsdefault(self, paramname) :
00428         a = {}
00429         a['imagename']  = ''
00430         a['kernel']  = 'gauss'
00431         a['major']  = '2.0arcsec'
00432         a['minor']  = '2.0arcsec'
00433         a['pa']  = '0deg'
00434         a['targetres']  = False
00435         a['region']  = ''
00436         a['box']  = ''
00437         a['chans']  = ''
00438         a['stokes']  = ''
00439         a['mask']  = ''
00440         a['outfile']  = ''
00441         a['stretch']  = False
00442         a['overwrite']  = False
00443         a['beam']  = ''
00444 
00445         #a = sys._getframe(len(inspect.stack())-1).f_globals
00446 
00447         if self.parameters['kernel']  == 'gauss':
00448             a['major'] = '2.5arcsec'
00449             a['minor'] = '2.0arcsec'
00450             a['pa'] = '0deg'
00451             a['beam'] = ''
00452             a['targetres'] = False
00453 
00454         if self.parameters['kernel']  == 'gaussian':
00455             a['major'] = '2.5arcsec'
00456             a['minor'] = '2.0arcsec'
00457             a['pa'] = '0deg'
00458             a['beam'] = ''
00459             a['targetres'] = False
00460 
00461         if self.parameters['kernel']  == 'box':
00462             a['major'] = '2.0arcsec'
00463             a['minor'] = '2.0arcsec'
00464 
00465         if self.parameters['kernel']  == 'boxcar':
00466             a['major'] = '2.0arcsec'
00467             a['minor'] = '2.0arcsec'
00468 
00469         if self.parameters['mask']  != '':
00470             a['stretch'] = False
00471 
00472         if a.has_key(paramname) :
00473               return a[paramname]
00474 imsmooth_cli = imsmooth_cli_()