casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
tclean_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_tclean import tclean
00018 class tclean_cli_:
00019     __name__ = "tclean"
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__ = (tclean_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'field':None, 'spw':None, 'imagename':None, 'nchan':None, 'startmodel':None, 'niter':None, 'threshold':None, 'loopgain':None, 'maxcycleniter':None, 'cyclefactor':None, 'minpsffraction':None, 'maxpsffraction':None, 'usescratch':None, 'clusterdef':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, vis=None, field=None, spw=None, imagename=None, nchan=None, startmodel=None, niter=None, threshold=None, loopgain=None, maxcycleniter=None, cyclefactor=None, minpsffraction=None, maxpsffraction=None, usescratch=None, clusterdef=None,  async=None):
00047 
00048         """Construct and deconvolve images
00049 
00050        This is an empty task. 
00051        It is meant only to build/test/maintain the interface for the refactored imaging code. 
00052        When ready, it will be offered to users for testing.
00053 
00054   
00055         """
00056         if not hasattr(self, "__globals__") or self.__globals__ == None :
00057            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00058         #casac = self.__globals__['casac']
00059         casalog = self.__globals__['casalog']
00060         #casalog = casac.casac.logsink()
00061         self.__globals__['__last_task'] = 'tclean'
00062         self.__globals__['taskname'] = 'tclean'
00063         ###
00064         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00065         ###
00066         ###
00067         #Handle globals or user over-ride of arguments
00068         #
00069         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00070         useLocalDefaults = False
00071 
00072         for item in function_signature_defaults.iteritems():
00073                 key,val = item
00074                 keyVal = eval(key)
00075                 if (keyVal == None):
00076                         #user hasn't set it - use global/default
00077                         pass
00078                 else:
00079                         #user has set it - use over-ride
00080                         if (key != 'self') :
00081                            useLocalDefaults = True
00082 
00083         myparams = {}
00084         if useLocalDefaults :
00085            for item in function_signature_defaults.iteritems():
00086                key,val = item
00087                keyVal = eval(key)
00088                exec('myparams[key] = keyVal')
00089                self.parameters[key] = keyVal
00090                if (keyVal == None):
00091                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00092                    keyVal = eval(key)
00093                    if(type(keyVal) == dict) :
00094                       if len(keyVal) > 0 :
00095                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00096                       else :
00097                          exec('myparams[key] = ' + key + ' = {}')
00098 
00099         else :
00100             async = self.parameters['async']
00101             myparams['vis'] = vis = self.parameters['vis']
00102             myparams['field'] = field = self.parameters['field']
00103             myparams['spw'] = spw = self.parameters['spw']
00104             myparams['imagename'] = imagename = self.parameters['imagename']
00105             myparams['nchan'] = nchan = self.parameters['nchan']
00106             myparams['startmodel'] = startmodel = self.parameters['startmodel']
00107             myparams['niter'] = niter = self.parameters['niter']
00108             myparams['threshold'] = threshold = self.parameters['threshold']
00109             myparams['loopgain'] = loopgain = self.parameters['loopgain']
00110             myparams['maxcycleniter'] = maxcycleniter = self.parameters['maxcycleniter']
00111             myparams['cyclefactor'] = cyclefactor = self.parameters['cyclefactor']
00112             myparams['minpsffraction'] = minpsffraction = self.parameters['minpsffraction']
00113             myparams['maxpsffraction'] = maxpsffraction = self.parameters['maxpsffraction']
00114             myparams['usescratch'] = usescratch = self.parameters['usescratch']
00115             myparams['clusterdef'] = clusterdef = self.parameters['clusterdef']
00116 
00117 
00118         result = None
00119 
00120 #
00121 #    The following is work around to avoid a bug with current python translation
00122 #
00123         mytmp = {}
00124 
00125         mytmp['vis'] = vis
00126         mytmp['field'] = field
00127         mytmp['spw'] = spw
00128         mytmp['imagename'] = imagename
00129         mytmp['nchan'] = nchan
00130         mytmp['startmodel'] = startmodel
00131         mytmp['niter'] = niter
00132         mytmp['threshold'] = threshold
00133         mytmp['loopgain'] = loopgain
00134         mytmp['maxcycleniter'] = maxcycleniter
00135         mytmp['cyclefactor'] = cyclefactor
00136         mytmp['minpsffraction'] = minpsffraction
00137         mytmp['maxpsffraction'] = maxpsffraction
00138         mytmp['usescratch'] = usescratch
00139         mytmp['clusterdef'] = clusterdef
00140         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00141         trec = casac.casac.utils().torecord(pathname+'tclean.xml')
00142 
00143         casalog.origin('tclean')
00144         try :
00145           #if not trec.has_key('tclean') or not casac.casac.utils().verify(mytmp, trec['tclean']) :
00146             #return False
00147 
00148           casac.casac.utils().verify(mytmp, trec['tclean'], True)
00149           scriptstr=['']
00150           saveinputs = self.__globals__['saveinputs']
00151           saveinputs('tclean', 'tclean.last', myparams, self.__globals__,scriptstr=scriptstr)
00152           if async :
00153             count = 0
00154             keybase =  time.strftime("%y%m%d.%H%M%S")
00155             key = keybase + "_" + str(count)
00156             while self.__async__.has_key(key) :
00157                count += 1
00158                key = keybase + "_" + str(count)
00159             result = tm.execute('tclean', vis, field, spw, imagename, nchan, startmodel, niter, threshold, loopgain, maxcycleniter, cyclefactor, minpsffraction, maxpsffraction, usescratch, clusterdef)
00160             print "Use: "
00161             print "      tm.retrieve(return_value) # to retrieve the status"
00162             print 
00163             self.rkey = key
00164             self.__async__[key] = result
00165           else :
00166               tname = 'tclean'
00167               spaces = ' '*(18-len(tname))
00168               casalog.post('\n##########################################'+
00169                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00170               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00171               result = tclean(vis, field, spw, imagename, nchan, startmodel, niter, threshold, loopgain, maxcycleniter, cyclefactor, minpsffraction, maxpsffraction, usescratch, clusterdef)
00172               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00173                            '\n##########################################')
00174 
00175         except Exception, instance:
00176           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00177              raise
00178           else :
00179              #print '**** Error **** ',instance
00180              tname = 'tclean'
00181              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00182              pass
00183 
00184         gc.collect()
00185         return result
00186 #
00187 #
00188 #
00189     def paramgui(self, useGlobals=True, ipython_globals=None):
00190         """
00191         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00192         """
00193         import paramgui
00194         if not hasattr(self, "__globals__") or self.__globals__ == None :
00195            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00196 
00197         if useGlobals:
00198             if ipython_globals == None:
00199                 myf=self.__globals__
00200             else:
00201                 myf=ipython_globals
00202 
00203             paramgui.setGlobals(myf)
00204         else:
00205             paramgui.setGlobals({})
00206 
00207         paramgui.runTask('tclean', myf['_ip'])
00208         paramgui.setGlobals({})
00209 
00210 #
00211 #
00212 #
00213     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00214         if not hasattr(self, "__globals__") or self.__globals__ == None :
00215            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00216         if ipython_globals == None:
00217             myf=self.__globals__
00218         else:
00219             myf=ipython_globals
00220 
00221         a = odict()
00222         a['vis']  = ''
00223         a['field']  = ''
00224         a['spw']  = ''
00225         a['imagename']  = ''
00226         a['nchan']  = 1
00227         a['startmodel']  = ''
00228         a['niter']  = 500
00229         a['threshold']  = 0.0
00230         a['loopgain']  = 0.1
00231         a['maxcycleniter']  = -1
00232         a['usescratch']  = False
00233         a['clusterdef']  = ''
00234 
00235         a['async']=False
00236         a['maxcycleniter'] = {
00237                     0:odict([{'notvalue':-1}, {'cyclefactor':1.0}, {'minpsffraction':0.05}, {'maxpsffraction':0.8}])}
00238 
00239 ### This function sets the default values but also will return the list of
00240 ### parameters or the default value of a given parameter
00241         if(param == None):
00242                 myf['__set_default_parameters'](a)
00243         elif(param == 'paramkeys'):
00244                 return a.keys()
00245         else:
00246             if(paramvalue==None and subparam==None):
00247                if(a.has_key(param)):
00248                   return a[param]
00249                else:
00250                   return self.itsdefault(param)
00251             else:
00252                retval=a[param]
00253                if(type(a[param])==dict):
00254                   for k in range(len(a[param])):
00255                      valornotval='value'
00256                      if(a[param][k].has_key('notvalue')):
00257                         valornotval='notvalue'
00258                      if((a[param][k][valornotval])==paramvalue):
00259                         retval=a[param][k].copy()
00260                         retval.pop(valornotval)
00261                         if(subparam != None):
00262                            if(retval.has_key(subparam)):
00263                               retval=retval[subparam]
00264                            else:
00265                               retval=self.itsdefault(subparam)
00266                      else:
00267                         retval=self.itsdefault(subparam)
00268                return retval
00269 
00270 
00271 #
00272 #
00273     def check_params(self, param=None, value=None, ipython_globals=None):
00274       if ipython_globals == None:
00275           myf=self.__globals__
00276       else:
00277           myf=ipython_globals
00278 #      print 'param:', param, 'value:', value
00279       try :
00280          if str(type(value)) != "<type 'instance'>" :
00281             value0 = value
00282             value = myf['cu'].expandparam(param, value)
00283             matchtype = False
00284             if(type(value) == numpy.ndarray):
00285                if(type(value) == type(value0)):
00286                   myf[param] = value.tolist()
00287                else:
00288                   #print 'value:', value, 'value0:', value0
00289                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00290                   myf[param] = value0
00291                   if type(value0) != list :
00292                      matchtype = True
00293             else :
00294                myf[param] = value
00295             value = myf['cu'].verifyparam({param:value})
00296             if matchtype:
00297                value = False
00298       except Exception, instance:
00299          #ignore the exception and just return it unchecked
00300          myf[param] = value
00301       return value
00302 #
00303 #
00304     def description(self, key='tclean', subkey=None):
00305         desc={'tclean': 'Construct and deconvolve images',
00306                'vis': 'Name of input visibility file(s)',
00307                'field': 'field(s) to select',
00308                'spw': 'spw(s) to select',
00309                'imagename': 'Pre-name of output images',
00310                'nchan': 'Number of channels in the output image',
00311                'startmodel': 'Name of starting model image',
00312                'niter': 'Maximum number of iterations',
00313                'threshold': 'Stopping threshold (number, in units of Jy)',
00314                'loopgain': 'Loop gain',
00315                'maxcycleniter': 'Maximum number of minor-cycle iterations before triggering a major cycle',
00316                'cyclefactor': 'Scaling on PSF sidelobe level to compute the minor-cycle stopping threshold.',
00317                'minpsffraction': 'PSF fraction that marks the max depth of cleaning in the minor cycle ',
00318                'maxpsffraction': 'PSF fraction that marks the minimum depth of cleaning in the minor cycle ',
00319                'usescratch': 'True if to save model visibilities in MODEL_DATA column',
00320                'clusterdef': 'Name of a file that contains the cluster definition',
00321 
00322                'async': 'If true the taskname must be started using tclean(...)'
00323               }
00324 
00325 #
00326 # Set subfields defaults if needed
00327 #
00328 
00329         if(desc.has_key(key)) :
00330            return desc[key]
00331 
00332     def itsdefault(self, paramname) :
00333         a = {}
00334         a['vis']  = ''
00335         a['field']  = ''
00336         a['spw']  = ''
00337         a['imagename']  = ''
00338         a['nchan']  = 1
00339         a['startmodel']  = ''
00340         a['niter']  = 500
00341         a['threshold']  = 0.0
00342         a['loopgain']  = 0.1
00343         a['maxcycleniter']  = -1
00344         a['cyclefactor']  = 1.0
00345         a['minpsffraction']  = 0.05
00346         a['maxpsffraction']  = 0.8
00347         a['usescratch']  = False
00348         a['clusterdef']  = ''
00349 
00350         #a = sys._getframe(len(inspect.stack())-1).f_globals
00351 
00352         if self.parameters['maxcycleniter']  != -1:
00353             a['cyclefactor'] = 1.0
00354             a['minpsffraction'] = 0.05
00355             a['maxpsffraction'] = 0.8
00356 
00357         if a.has_key(paramname) :
00358               return a[paramname]
00359 tclean_cli = tclean_cli_()