casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
imcontsub_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_imcontsub import imcontsub
00018 class imcontsub_cli_:
00019     __name__ = "imcontsub"
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__ = (imcontsub_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'imagename':None, 'linefile':None, 'contfile':None, 'fitorder':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, linefile=None, contfile=None, fitorder=None, region=None, box=None, chans=None, stokes=None,  async=None):
00047 
00048         """Estimates and subtracts continuum emission from an image cube
00049 
00050   For each (x, y) column in imagename (or a subset selected by region and/or
00051   box), this estimates the continuum by fitting a polynomial to one or more
00052   subsets of the channels.  The continuum estimate is saved in contfile, and
00053   subtracted from imagename (or its subset) to make a spectral line estimate,
00054   which is saved in linefile.
00055 
00056   
00057   
00058 
00059   Keyword arguments:
00060   imagename -- Input image cube
00061     Default: none; Example: imagename='ngc5921_task.im'
00062   linefile -- Name of output spectral line cube
00063     Default: none; Example: outline='ngc5921_line.im'
00064   contfile -- Name of output continuum cube
00065     Default: none; Example: contfile='ngc5921_cont.im'
00066   fitorder -- Polynomial order for the continuum estimation.
00067     Default: 0; Example fitorder=2
00068   region -- ImageRegion file to select a portion of the cube for output.
00069     Default: '' (= everything)
00070     Example: region='myimage.im.rgn'
00071              region='region1'
00072     Use the viewer on the image cube to define the continuum
00073     regions.  This is more general than box but still experimental.
00074     N.B. This is NOT for selecting a subset of the input for
00075          fitting the continuum!  Only pixels that are in region
00076          will be considered, however.
00077 
00078   box --  A [blcx, blcy, trcx, trcy] region on the directional plane for
00079           selecting a subset for output.
00080           ONLY pixel values are acceptable at this time.
00081           Default: none (whole 2-D plane); Example: box='10,10,50,50'
00082           N.B. This is NOT for selecting a subset of the input for
00083                fitting the continuum!  Only pixels that are in region
00084                will be considered, however.
00085   chans -- line-free channel numbers to fit the continuum to.
00086            N.B.: This is currently the _only_ way to specify what is
00087                  continuum vs. line emission.
00088            ONLY channel numbers accepted at this time, i.e. there is no
00089            'spw:' as in the spw parameter of other tasks.  For
00090            a multi-spw image, the channelization must be the same for all.
00091            Default: '' (all)
00092            Example: chans='3~6;>40'
00093   stokes -- Stokes parameters to image, may or may not be separated
00094             by commas but best if you use commas.
00095             Default: none (all); Example: stokes='IQUV';
00096             Options: 'I','Q','U','V','RR','RL','LR','LL','XX','YX','XY','YY', ... 
00097 
00098 
00099 
00100         """
00101         if not hasattr(self, "__globals__") or self.__globals__ == None :
00102            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00103         #casac = self.__globals__['casac']
00104         casalog = self.__globals__['casalog']
00105         #casalog = casac.casac.logsink()
00106         self.__globals__['__last_task'] = 'imcontsub'
00107         self.__globals__['taskname'] = 'imcontsub'
00108         ###
00109         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00110         ###
00111         ###
00112         #Handle globals or user over-ride of arguments
00113         #
00114         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00115         useLocalDefaults = False
00116 
00117         for item in function_signature_defaults.iteritems():
00118                 key,val = item
00119                 keyVal = eval(key)
00120                 if (keyVal == None):
00121                         #user hasn't set it - use global/default
00122                         pass
00123                 else:
00124                         #user has set it - use over-ride
00125                         if (key != 'self') :
00126                            useLocalDefaults = True
00127 
00128         myparams = {}
00129         if useLocalDefaults :
00130            for item in function_signature_defaults.iteritems():
00131                key,val = item
00132                keyVal = eval(key)
00133                exec('myparams[key] = keyVal')
00134                self.parameters[key] = keyVal
00135                if (keyVal == None):
00136                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00137                    keyVal = eval(key)
00138                    if(type(keyVal) == dict) :
00139                       if len(keyVal) > 0 :
00140                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00141                       else :
00142                          exec('myparams[key] = ' + key + ' = {}')
00143 
00144         else :
00145             async = self.parameters['async']
00146             myparams['imagename'] = imagename = self.parameters['imagename']
00147             myparams['linefile'] = linefile = self.parameters['linefile']
00148             myparams['contfile'] = contfile = self.parameters['contfile']
00149             myparams['fitorder'] = fitorder = self.parameters['fitorder']
00150             myparams['region'] = region = self.parameters['region']
00151             myparams['box'] = box = self.parameters['box']
00152             myparams['chans'] = chans = self.parameters['chans']
00153             myparams['stokes'] = stokes = self.parameters['stokes']
00154 
00155 
00156         result = None
00157 
00158 #
00159 #    The following is work around to avoid a bug with current python translation
00160 #
00161         mytmp = {}
00162 
00163         mytmp['imagename'] = imagename
00164         mytmp['linefile'] = linefile
00165         mytmp['contfile'] = contfile
00166         mytmp['fitorder'] = fitorder
00167         mytmp['region'] = region
00168         mytmp['box'] = box
00169         mytmp['chans'] = chans
00170         mytmp['stokes'] = stokes
00171         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00172         trec = casac.casac.utils().torecord(pathname+'imcontsub.xml')
00173 
00174         casalog.origin('imcontsub')
00175         try :
00176           #if not trec.has_key('imcontsub') or not casac.casac.utils().verify(mytmp, trec['imcontsub']) :
00177             #return False
00178 
00179           casac.casac.utils().verify(mytmp, trec['imcontsub'], True)
00180           scriptstr=['']
00181           saveinputs = self.__globals__['saveinputs']
00182           saveinputs('imcontsub', 'imcontsub.last', myparams, self.__globals__,scriptstr=scriptstr)
00183           if async :
00184             count = 0
00185             keybase =  time.strftime("%y%m%d.%H%M%S")
00186             key = keybase + "_" + str(count)
00187             while self.__async__.has_key(key) :
00188                count += 1
00189                key = keybase + "_" + str(count)
00190             result = tm.execute('imcontsub', imagename, linefile, contfile, fitorder, region, box, chans, stokes)
00191             print "Use: "
00192             print "      tm.retrieve(return_value) # to retrieve the status"
00193             print 
00194             self.rkey = key
00195             self.__async__[key] = result
00196           else :
00197               tname = 'imcontsub'
00198               spaces = ' '*(18-len(tname))
00199               casalog.post('\n##########################################'+
00200                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00201               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00202               result = imcontsub(imagename, linefile, contfile, fitorder, region, box, chans, stokes)
00203               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00204                            '\n##########################################')
00205 
00206         except Exception, instance:
00207           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00208              raise
00209           else :
00210              #print '**** Error **** ',instance
00211              tname = 'imcontsub'
00212              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00213              pass
00214 
00215         gc.collect()
00216         return result
00217 #
00218 #
00219 #
00220     def paramgui(self, useGlobals=True, ipython_globals=None):
00221         """
00222         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00223         """
00224         import paramgui
00225         if not hasattr(self, "__globals__") or self.__globals__ == None :
00226            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00227 
00228         if useGlobals:
00229             if ipython_globals == None:
00230                 myf=self.__globals__
00231             else:
00232                 myf=ipython_globals
00233 
00234             paramgui.setGlobals(myf)
00235         else:
00236             paramgui.setGlobals({})
00237 
00238         paramgui.runTask('imcontsub', myf['_ip'])
00239         paramgui.setGlobals({})
00240 
00241 #
00242 #
00243 #
00244     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00245         if not hasattr(self, "__globals__") or self.__globals__ == None :
00246            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00247         if ipython_globals == None:
00248             myf=self.__globals__
00249         else:
00250             myf=ipython_globals
00251 
00252         a = odict()
00253         a['imagename']  = ''
00254         a['linefile']  = ''
00255         a['contfile']  = ''
00256         a['fitorder']  = 0
00257         a['region']  = ''
00258         a['box']  = ''
00259         a['chans']  = ''
00260         a['stokes']  = ''
00261 
00262         a['async']=False
00263 
00264 ### This function sets the default values but also will return the list of
00265 ### parameters or the default value of a given parameter
00266         if(param == None):
00267                 myf['__set_default_parameters'](a)
00268         elif(param == 'paramkeys'):
00269                 return a.keys()
00270         else:
00271             if(paramvalue==None and subparam==None):
00272                if(a.has_key(param)):
00273                   return a[param]
00274                else:
00275                   return self.itsdefault(param)
00276             else:
00277                retval=a[param]
00278                if(type(a[param])==dict):
00279                   for k in range(len(a[param])):
00280                      valornotval='value'
00281                      if(a[param][k].has_key('notvalue')):
00282                         valornotval='notvalue'
00283                      if((a[param][k][valornotval])==paramvalue):
00284                         retval=a[param][k].copy()
00285                         retval.pop(valornotval)
00286                         if(subparam != None):
00287                            if(retval.has_key(subparam)):
00288                               retval=retval[subparam]
00289                            else:
00290                               retval=self.itsdefault(subparam)
00291                      else:
00292                         retval=self.itsdefault(subparam)
00293                return retval
00294 
00295 
00296 #
00297 #
00298     def check_params(self, param=None, value=None, ipython_globals=None):
00299       if ipython_globals == None:
00300           myf=self.__globals__
00301       else:
00302           myf=ipython_globals
00303 #      print 'param:', param, 'value:', value
00304       try :
00305          if str(type(value)) != "<type 'instance'>" :
00306             value0 = value
00307             value = myf['cu'].expandparam(param, value)
00308             matchtype = False
00309             if(type(value) == numpy.ndarray):
00310                if(type(value) == type(value0)):
00311                   myf[param] = value.tolist()
00312                else:
00313                   #print 'value:', value, 'value0:', value0
00314                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00315                   myf[param] = value0
00316                   if type(value0) != list :
00317                      matchtype = True
00318             else :
00319                myf[param] = value
00320             value = myf['cu'].verifyparam({param:value})
00321             if matchtype:
00322                value = False
00323       except Exception, instance:
00324          #ignore the exception and just return it unchecked
00325          myf[param] = value
00326       return value
00327 #
00328 #
00329     def description(self, key='imcontsub', subkey=None):
00330         desc={'imcontsub': 'Estimates and subtracts continuum emission from an image cube',
00331                'imagename': 'Name of the input spectral line image',
00332                'linefile': 'Output continuum-subtracted image file name',
00333                'contfile': 'Output continuum image file name',
00334                'fitorder': 'Polynomial order for the continuum estimation',
00335                'region': 'Image region used for output selection',
00336                'box': '[blcx, blcy, trcx, trcy] for output selection',
00337                'chans': 'Channel range(s) for continuum fitting',
00338                'stokes': 'Stokes params to image (I,IV,IQU,IQUV)',
00339 
00340                'async': 'If true the taskname must be started using imcontsub(...)'
00341               }
00342 
00343 #
00344 # Set subfields defaults if needed
00345 #
00346 
00347         if(desc.has_key(key)) :
00348            return desc[key]
00349 
00350     def itsdefault(self, paramname) :
00351         a = {}
00352         a['imagename']  = ''
00353         a['linefile']  = ''
00354         a['contfile']  = ''
00355         a['fitorder']  = 0
00356         a['region']  = ''
00357         a['box']  = ''
00358         a['chans']  = ''
00359         a['stokes']  = ''
00360 
00361         #a = sys._getframe(len(inspect.stack())-1).f_globals
00362 
00363         if a.has_key(paramname) :
00364               return a[paramname]
00365 imcontsub_cli = imcontsub_cli_()