casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
csvclean_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_csvclean import csvclean
00018 class csvclean_cli_:
00019     __name__ = "csvclean"
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__ = (csvclean_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'imagename':None, 'field':None, 'spw':None, 'advise':None, 'mode':None, 'nchan':None, 'width':None, 'imsize':None, 'cell':None, 'phasecenter':None, 'niter':None, 'weighting':None, 'restoringbeam':None, 'interactive':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, imagename=None, field=None, spw=None, advise=None, mode=None, nchan=None, width=None, imsize=None, cell=None, phasecenter=None, niter=None, weighting=None, restoringbeam=None, interactive=None,  async=None):
00047 
00048         """This task does an invert of the visibilities and deconvolve in the image plane.
00049 
00050         This task does not do a uvdata subtraction (aka Cotton-Schwab major cycle) 
00051         of model visibility as in clean. - For ALMA Commissioning
00052 
00053         Keyword arguments:
00054         vis -- Name of input visibility file
00055                 default: none; example: vis='ngc5921.ms' 
00056                 
00057         imagename -- Name of output CASA image. (only the prefix)
00058                    default: none; example: imagename='m2'
00059                    output images are:
00060                  m2.image; cleaned and restored image
00061                         With or without primary beam correction
00062                  m2dirty.image; dirty image
00063                  m2psf.image; point-spread function (dirty beam)
00064                  m2.model; image of clean components
00065                  m2.mask; image containing clean regions, when interative=True
00066                          
00067         field -- Select fields in mosaic.  Use field id(s) or field name(s).
00068                   ['go listobs' to obtain the list id's or names]
00069               default: ''= all fields
00070               If field string is a non-negative integer, it is assumed to
00071                   be a field index otherwise, it is assumed to be a 
00072                   field name
00073               field='0~2'; field ids 0,1,2
00074               field='0,4,5~7'; field ids 0,4,5,6,7
00075               field='3C286,3C295'; field named 3C286 and 3C295
00076               field = '3,4C*'; field id 3, all names starting with 4C
00077               
00078         spw -- Select spectral window/channels
00079            NOTE: This selects the data passed as the INPUT to mode
00080            default: ''= all spectral windows and channels
00081                 spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00082                 spw='0:5~61'; spw 0, channels 5 to 61
00083                 spw='<2';   spectral windows less than 2 (i.e. 0,1)
00084                 spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, 
00085                                    channels 3 to 45.
00086                 spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00087                 spw='0:0~10;15~60'; spectral window 0 with channels 
00088                                     0-10,15-60
00089                 spw='0:0~10,1:20~30,2:1;2;3'; spw 0, channels 0-10,
00090                       spw 1, channels 20-30, and spw 2, channels, 1,2 and 3
00091         advise -- This determines whether advice for imsize and cell is 
00092                   requested. If set to True. It won't run clean but return
00093                   values for imszise and cell estimated for the longest 
00094                   baseline in the data
00095                       
00096         imsize -- Image pixel size (x,y).  DOES NOT HAVE TO BE A POWER OF 2
00097                default = [256,256]; example: imsize=[350,350]
00098                imsize = 500 is equivalent to [500,500].
00099                Avoid odd-numbered imsize.
00100 
00101         cell -- Cell size (x,y)
00102                default= '1.0arcsec';
00103                example: cell=['0.5arcsec,'0.5arcsec'] or
00104                cell=['1arcmin', '1arcmin']
00105                cell = '1arcsec' is equivalent to ['1arcsec','1arcsec']
00106                NOTE:cell = 2.0 => ['2arcsec', '2arcsec']
00107 
00108        phasecenter -- direction measure  or fieldid for the mosaic center
00109                 default: '' => first field selected ; example: phasecenter=6
00110                 or phasecenter='J2000 19h30m00 -40d00m00'
00111 
00112         mode -- this determines what kind of image to make 
00113                 continuum or cube. In continuum all the selected data 
00114                 channels are combined in a 1 channel image using 
00115                 multifrequency synthesis.
00116                 options are 'cube' and 'continuum'
00117                 default: 'continuum'
00118   >>> mode='cube' expandable parameters
00119                nchan -- sets the number of channel in the output
00120                image. e.g nchan=10
00121                 
00122                width -- image channel width in terms of the number of
00123                         channel of the first spw of the data selected
00124                         e.g width=2  
00125               
00126                 
00127 
00128         niter -- Maximum number of iterations,
00129                if niter=0, then no CLEANing is done ("invert" only)
00130                default: 500; example: niter=5000
00131 
00132         weighting -- Weighting to apply to visibilities:
00133                default='natural'; example: weighting='uniform';
00134                Options: 'natural','uniform','briggs', 
00135                        'superuniform','briggsabs','radial'
00136 
00137         restoringbeam -- Output Gaussian restoring beam for CLEAN image
00138                [bmaj, bmin, bpa] elliptical Gaussian restoring beam.
00139                Default units are in arc-seconds for bmaj and bmin, and in degrees
00140                for bpa. Default: restoringbeam=[]; Use PSF calculated
00141                from dirty beam. 
00142                example: restoringbeam=['10arcsec'] or restorinbeam='10arcsec', circular Gaussian.
00143                         FWHM 10 arcseconds example:
00144                         restoringbeam=['10.0','5.0','45.0deg'] 10"x5" 
00145                         at 45 degrees
00146         
00147         interactive -- Create a mask interactively or not.
00148                         default=False; example: interactive=True
00149                         The viewer will open with the image displayed. Select the
00150                         region for the mask and double click in the middle of it.
00151         
00152  
00153         """
00154         if not hasattr(self, "__globals__") or self.__globals__ == None :
00155            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00156         #casac = self.__globals__['casac']
00157         casalog = self.__globals__['casalog']
00158         #casalog = casac.casac.logsink()
00159         self.__globals__['__last_task'] = 'csvclean'
00160         self.__globals__['taskname'] = 'csvclean'
00161         ###
00162         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00163         ###
00164         ###
00165         #Handle globals or user over-ride of arguments
00166         #
00167         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00168         useLocalDefaults = False
00169 
00170         for item in function_signature_defaults.iteritems():
00171                 key,val = item
00172                 keyVal = eval(key)
00173                 if (keyVal == None):
00174                         #user hasn't set it - use global/default
00175                         pass
00176                 else:
00177                         #user has set it - use over-ride
00178                         if (key != 'self') :
00179                            useLocalDefaults = True
00180 
00181         myparams = {}
00182         if useLocalDefaults :
00183            for item in function_signature_defaults.iteritems():
00184                key,val = item
00185                keyVal = eval(key)
00186                exec('myparams[key] = keyVal')
00187                self.parameters[key] = keyVal
00188                if (keyVal == None):
00189                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00190                    keyVal = eval(key)
00191                    if(type(keyVal) == dict) :
00192                       if len(keyVal) > 0 :
00193                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00194                       else :
00195                          exec('myparams[key] = ' + key + ' = {}')
00196 
00197         else :
00198             async = self.parameters['async']
00199             myparams['vis'] = vis = self.parameters['vis']
00200             myparams['imagename'] = imagename = self.parameters['imagename']
00201             myparams['field'] = field = self.parameters['field']
00202             myparams['spw'] = spw = self.parameters['spw']
00203             myparams['advise'] = advise = self.parameters['advise']
00204             myparams['mode'] = mode = self.parameters['mode']
00205             myparams['nchan'] = nchan = self.parameters['nchan']
00206             myparams['width'] = width = self.parameters['width']
00207             myparams['imsize'] = imsize = self.parameters['imsize']
00208             myparams['cell'] = cell = self.parameters['cell']
00209             myparams['phasecenter'] = phasecenter = self.parameters['phasecenter']
00210             myparams['niter'] = niter = self.parameters['niter']
00211             myparams['weighting'] = weighting = self.parameters['weighting']
00212             myparams['restoringbeam'] = restoringbeam = self.parameters['restoringbeam']
00213             myparams['interactive'] = interactive = self.parameters['interactive']
00214 
00215         if type(imsize)==int: imsize=[imsize]
00216         if type(cell)==float: cell=[cell]
00217         if type(restoringbeam)==str: restoringbeam=[restoringbeam]
00218 
00219         result = None
00220 
00221 #
00222 #    The following is work around to avoid a bug with current python translation
00223 #
00224         mytmp = {}
00225 
00226         mytmp['vis'] = vis
00227         mytmp['imagename'] = imagename
00228         mytmp['field'] = field
00229         mytmp['spw'] = spw
00230         mytmp['advise'] = advise
00231         mytmp['mode'] = mode
00232         mytmp['nchan'] = nchan
00233         mytmp['width'] = width
00234         mytmp['imsize'] = imsize
00235         if type(cell) == str :
00236            mytmp['cell'] = casac.casac.qa.quantity(cell)
00237         else :
00238            mytmp['cell'] = cell
00239         mytmp['phasecenter'] = phasecenter
00240         mytmp['niter'] = niter
00241         mytmp['weighting'] = weighting
00242         mytmp['restoringbeam'] = restoringbeam
00243         mytmp['interactive'] = interactive
00244         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00245         trec = casac.casac.utils().torecord(pathname+'csvclean.xml')
00246 
00247         casalog.origin('csvclean')
00248         try :
00249           #if not trec.has_key('csvclean') or not casac.casac.utils().verify(mytmp, trec['csvclean']) :
00250             #return False
00251 
00252           casac.casac.utils().verify(mytmp, trec['csvclean'], True)
00253           scriptstr=['']
00254           saveinputs = self.__globals__['saveinputs']
00255           saveinputs('csvclean', 'csvclean.last', myparams, self.__globals__,scriptstr=scriptstr)
00256           if async :
00257             count = 0
00258             keybase =  time.strftime("%y%m%d.%H%M%S")
00259             key = keybase + "_" + str(count)
00260             while self.__async__.has_key(key) :
00261                count += 1
00262                key = keybase + "_" + str(count)
00263             result = tm.execute('csvclean', vis, imagename, field, spw, advise, mode, nchan, width, imsize, cell, phasecenter, niter, weighting, restoringbeam, interactive)
00264             print "Use: "
00265             print "      tm.retrieve(return_value) # to retrieve the status"
00266             print 
00267             self.rkey = key
00268             self.__async__[key] = result
00269           else :
00270               tname = 'csvclean'
00271               spaces = ' '*(18-len(tname))
00272               casalog.post('\n##########################################'+
00273                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00274               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00275               result = csvclean(vis, imagename, field, spw, advise, mode, nchan, width, imsize, cell, phasecenter, niter, weighting, restoringbeam, interactive)
00276               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00277                            '\n##########################################')
00278 
00279         except Exception, instance:
00280           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00281              raise
00282           else :
00283              #print '**** Error **** ',instance
00284              tname = 'csvclean'
00285              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00286              pass
00287 
00288         gc.collect()
00289         return result
00290 #
00291 #
00292 #
00293     def paramgui(self, useGlobals=True, ipython_globals=None):
00294         """
00295         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00296         """
00297         import paramgui
00298         if not hasattr(self, "__globals__") or self.__globals__ == None :
00299            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00300 
00301         if useGlobals:
00302             if ipython_globals == None:
00303                 myf=self.__globals__
00304             else:
00305                 myf=ipython_globals
00306 
00307             paramgui.setGlobals(myf)
00308         else:
00309             paramgui.setGlobals({})
00310 
00311         paramgui.runTask('csvclean', myf['_ip'])
00312         paramgui.setGlobals({})
00313 
00314 #
00315 #
00316 #
00317     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00318         if not hasattr(self, "__globals__") or self.__globals__ == None :
00319            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00320         if ipython_globals == None:
00321             myf=self.__globals__
00322         else:
00323             myf=ipython_globals
00324 
00325         a = odict()
00326         a['vis']  = ''
00327         a['field']  = ''
00328         a['spw']  = ''
00329         a['advise']  = False
00330         a['mode']  = 'continuum'
00331 
00332         a['async']=False
00333         a['advise'] = {
00334                     0:odict([{'value':False}, {'imagename':''}, {'imsize':[256, 256]}, {'cell':[1.0, 1.0]}, {'phasecenter':''}, {'niter':500}, {'weighting':'natural'}, {'restoringbeam':[]}, {'interactive':False}]), 
00335                     1:{'value':True}}
00336         a['mode'] = {
00337                     0:{'value':'continuum'}, 
00338                     1:odict([{'value':'cube'}, {'nchan':-1}, {'width':1}])}
00339 
00340 ### This function sets the default values but also will return the list of
00341 ### parameters or the default value of a given parameter
00342         if(param == None):
00343                 myf['__set_default_parameters'](a)
00344         elif(param == 'paramkeys'):
00345                 return a.keys()
00346         else:
00347             if(paramvalue==None and subparam==None):
00348                if(a.has_key(param)):
00349                   return a[param]
00350                else:
00351                   return self.itsdefault(param)
00352             else:
00353                retval=a[param]
00354                if(type(a[param])==dict):
00355                   for k in range(len(a[param])):
00356                      valornotval='value'
00357                      if(a[param][k].has_key('notvalue')):
00358                         valornotval='notvalue'
00359                      if((a[param][k][valornotval])==paramvalue):
00360                         retval=a[param][k].copy()
00361                         retval.pop(valornotval)
00362                         if(subparam != None):
00363                            if(retval.has_key(subparam)):
00364                               retval=retval[subparam]
00365                            else:
00366                               retval=self.itsdefault(subparam)
00367                      else:
00368                         retval=self.itsdefault(subparam)
00369                return retval
00370 
00371 
00372 #
00373 #
00374     def check_params(self, param=None, value=None, ipython_globals=None):
00375       if ipython_globals == None:
00376           myf=self.__globals__
00377       else:
00378           myf=ipython_globals
00379 #      print 'param:', param, 'value:', value
00380       try :
00381          if str(type(value)) != "<type 'instance'>" :
00382             value0 = value
00383             value = myf['cu'].expandparam(param, value)
00384             matchtype = False
00385             if(type(value) == numpy.ndarray):
00386                if(type(value) == type(value0)):
00387                   myf[param] = value.tolist()
00388                else:
00389                   #print 'value:', value, 'value0:', value0
00390                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00391                   myf[param] = value0
00392                   if type(value0) != list :
00393                      matchtype = True
00394             else :
00395                myf[param] = value
00396             value = myf['cu'].verifyparam({param:value})
00397             if matchtype:
00398                value = False
00399       except Exception, instance:
00400          #ignore the exception and just return it unchecked
00401          myf[param] = value
00402       return value
00403 #
00404 #
00405     def description(self, key='csvclean', subkey=None):
00406         desc={'csvclean': 'This task does an invert of the visibilities and deconvolve in the image plane.',
00407                'vis': 'Name of input visibility file',
00408                'imagename': 'Name of image',
00409                'field': 'Select field using field id(s) or field name(s)',
00410                'spw': 'Select spectral window/channels',
00411                'advise': 'Boolean to determine if advice on image cell is requested',
00412                'mode': ' define the mode to operate csvclean: option continuum, cube ',
00413                'nchan': 'Number of channels (planes) in output image; -1 = all',
00414                'width': 'width of output spectral channels',
00415                'imsize': 'Image size in pixels (nx,ny), symmetric for single value',
00416                'cell': 'The image cell size in arcseconds [x,y]. ',
00417                'phasecenter': 'Image center: direction or field index',
00418                'niter': 'Maximum number of iterations',
00419                'weighting': 'Type of weighting',
00420                'restoringbeam': 'Output Gaussian restoring beam for CLEAN image',
00421                'interactive': 'Create a mask interactively or not.',
00422 
00423                'async': 'If true the taskname must be started using csvclean(...)'
00424               }
00425 
00426 #
00427 # Set subfields defaults if needed
00428 #
00429 
00430         if(desc.has_key(key)) :
00431            return desc[key]
00432 
00433     def itsdefault(self, paramname) :
00434         a = {}
00435         a['vis']  = ''
00436         a['imagename']  = ''
00437         a['field']  = ''
00438         a['spw']  = ''
00439         a['advise']  = False
00440         a['mode']  = 'continuum'
00441         a['nchan']  = -1
00442         a['width']  = 1
00443         a['imsize']  = [256, 256]
00444         a['cell']  = ['1.0arcsec', '1.0arcsec']
00445         a['phasecenter']  = ''
00446         a['niter']  = 500
00447         a['weighting']  = 'natural'
00448         a['restoringbeam']  = ['']
00449         a['interactive']  = False
00450 
00451         #a = sys._getframe(len(inspect.stack())-1).f_globals
00452 
00453         if self.parameters['advise']  == False:
00454             a['imagename'] = ''
00455             a['imsize'] = [256, 256]
00456             a['cell'] = [1.0, 1.0]
00457             a['phasecenter'] = ''
00458             a['niter'] = 500
00459             a['weighting'] = 'natural'
00460             a['restoringbeam'] = []
00461             a['interactive'] = False
00462 
00463         if self.parameters['mode']  == 'cube':
00464             a['nchan'] = -1
00465             a['width'] = 1
00466 
00467         if a.has_key(paramname) :
00468               return a[paramname]
00469 csvclean_cli = csvclean_cli_()