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