casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
autoclean_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_autoclean import autoclean
00016 from task_autoclean import casalog
00017 
00018 class autoclean_pg_:
00019     __name__ = "autoclean"
00020 
00021     def __init__(self) :
00022        self.__bases__ = (autoclean_pg_,)
00023        self.__doc__ = self.__call__.__doc__
00024 
00025 
00026     def __call__(self, vis=None, imagename=None, field=None, spw=None, selectdata=None, timerange=None, uvrange=None, antenna=None, scan=None, mode=None, nchan=None, start=None, width=None, interpolation=None, doconcat=None, psfmode=None, imagermode=None, cyclefactor=None, cyclespeedup=None, imsize=None, cell=None, phasecenter=None, restfreq=None, stokes=None, weighting=None, robust=None, noise=None, npixels=None, interactive=None, mask=None, modelimage=None, uvtaper=None, outertaper=None, innertaper=None, niter=None, npercycle=None, npercycle_speedup=None, gain=None, pbcor=None, minpb=None, clean_threshold=None, Nrms=None, eps_maxres=None, useabsresid=None, allow_maxres_inc=None, island_rms=None, diag=None, peak_rms=None, gain_threshold=None, Npeak=None, shape=None, boxstretch=None, irregsize=None, async=None):
00027 
00028         """CLEAN an image with automatically-chosen clean regions.
00029        This is a wrapper for clean which includes automatic clean boxing.
00030        Current capabilities include:
00031  
00032         1)  Multi-frequency-continuum images or spectral channel imaging
00033         2)  Stokes I imaging only
00034         3)  Use starting mask
00035  
00036  
00037        vis -- Name of input visibility file
00038                default: none; example: vis='ngc5921.ms'
00039        imagename -- Pre-name of output images:
00040                default: none; example: imagename='m2'
00041                output images are:
00042                  m2.image; cleaned and restored image
00043                         With or without primary beam correction
00044                  m2.psf; point-spread function (dirty beam)
00045                  m2.flux;  relative sky sensitivity over field
00046                  m2.mask;  total clean regions
00047                  m2.model; image of clean components
00048                  m2.residual; image of residuals
00049        field -- Select fields in mosaic.  Use field id(s) or field name(s).
00050                   ['go listobs' to obtain the list id's or names]
00051               default: ''= all fields
00052               If field string is a non-negative integer, it is assumed to
00053                   be a field index otherwise, it is assumed to be a 
00054                   field name
00055               field='0~2'; field ids 0,1,2
00056               field='0,4,5~7'; field ids 0,4,5,6,7
00057               field='3C286,3C295'; field named 3C286 and 3C295
00058               field = '3,4C*'; field id 3, all names starting with 4C
00059        spw -- Select spectral window/channels
00060               NOTE: This selects the data passed as the INPUT to mode
00061               default: ''=all spectral windows and channels
00062                 spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00063                 spw='0:5~61'; spw 0, channels 5 to 61
00064                 spw='<2';   spectral windows less than 2 (i.e. 0,1)
00065                 spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, 
00066                                    channels 3 to 45.
00067                  spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00068                  spw='0:0~10;15~60'; spectral window 0 with channels 
00069                                     0-10,15-60
00070                  spw='0:0~10,1:20~30,2:1;2;3'; spw 0, channels 0-10,
00071                       spw 1, channels 20-30, and spw 2, channels, 1,2 and 3
00072        selectdata -- Other data selection parameters
00073                default: True
00074 
00075   >>> selectdata=True expandable parameters
00076                See help par.selectdata for more on these
00077 
00078                timerange  -- Select data based on time range:
00079                    default: '' (all); examples,
00080                    timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00081                    Note: if YYYY/MM/DD is missing date defaults to first 
00082                          day in data set
00083                    timerange='09:14:0~09:54:0' picks 40 min on first day
00084                    timerange='25:00:00~27:30:00' picks 1 hr to 3 hr 
00085                              30min on NEXT day
00086                    timerange='09:44:00' pick data within one integration 
00087                              of time
00088                    timerange='>10:24:00' data after this time
00089                uvrange -- Select data within uvrange (default units meters)
00090                    default: '' (all); example:
00091                    uvrange='0~1000klambda'; uvrange from 0-1000 kilo-lambda
00092                    uvrange='>4klambda';uvranges greater than 4 kilo lambda
00093                antenna -- Select data based on antenna/baseline
00094                    default: '' (all)
00095                    If antenna string is a non-negative integer, it is 
00096                    assumed to be an antenna index, otherwise, it is
00097                    considered an antenna name.
00098                    antenna='5&6'; baseline between antenna index 5 and 
00099                                  index 6.
00100                    antenna='VA05&VA06'; baseline between VLA antenna 5 
00101                                        and 6.
00102                    antenna='5&6;7&8'; baselines 5-6 and 7-8
00103                    antenna='5'; all baselines with antenna index 5
00104                    antenna='05'; all baselines with antenna number 05 
00105                                 (VLA old name)
00106                    antenna='5,6,9'; all baselines with antennas 5,6,9 
00107                                    index numbers
00108               scan -- Scan number range.
00109                   default: '' (all)
00110                   example: scan='1~5'
00111                   Check 'go listobs' to insure the scan numbers are in 
00112                         order.
00113        mode -- Frequency Specification:
00114                NOTE: Channels deselected with spw parameter will contain all
00115                      zeros. 
00116                See examples below.
00117                default: 'mfs'
00118                  mode = 'mfs' means produce one image from all 
00119                       specified data.
00120                  mode = 'channel'; Use with nchan, start, width to specify
00121                          output image cube.  See examples below
00122                  mode = 'velocity', means channels are specified in 
00123                       velocity.
00124                  mode = 'frequency', means channels are specified in 
00125                       frequency.
00126 
00127   >>> mode expandable parameters (for modes other than 'mfs')
00128                Start, width are given in units of channels, frequency 
00129                   or velocity as indicated by mode (note: only nearest neighbour 
00130                   interpolation is available at this time).
00131                nchan -- Number of channels (planes) in output image
00132                  default: 1; example: nchan=3
00133                start -- Start input channel (relative-0)
00134                  default=0; example: start=5
00135                width -- Output channel width in units of the input
00136                      channel width (>1 indicates channel averaging)
00137                  default=1; example: width=4
00138                interpolation -- Interpolation type of spectral data when gridded on
00139                      the uv-plane
00140                  default = 'linear'
00141                doconcat -- Tells autoclean to concatenate multiple channel images into
00142                      single image at the end of its run.  (Autoclean makes an image
00143                      for each channel, and cleans/boxes them one at a time.)
00144                  default = 'True'
00145            examples:
00146                spw = '0,1'; mode = 'mfs'
00147                   will produce one image made from all channels in spw 
00148                        0 and 1
00149                spw='0:5~28^2'; mode = 'mfs'
00150                   will produce one image made with channels 
00151                        (5,7,9,...,25,27)
00152                spw = '0'; mode = 'channel': nchan=3; start=5; width=4
00153                   will produce an image with 3 output planes
00154                   plane 1 contains data from channels (5+6+7+8)
00155                   plane 2 contains data from channels (9+10+11+12)
00156                   plane 3 contains data from channels (13+14+15+16)
00157                spw = '0:0~63^3'; mode='channel'; nchan=21; start = 0; 
00158                    width = 1
00159                   will produce an image with 20 output planes
00160                   Plane 1 contains data from channel 0
00161                   Plane 2 contains date from channel 2
00162                   Plane 21 contains data from channel 61
00163                spw = '0:0~40^2'; mode = 'channel'; nchan = 3; start = 
00164                    5; width = 4
00165                   will produce an image with three output planes
00166                   plane 1 contains channels (5,7)
00167                   plane 2 contains channels (13,15)
00168                   plane 3 contains channels (21,23)
00169 
00170        psfmode -- method of PSF calculation to use during minor cycles:
00171                default: 'clark': Options: 'clark','clarkstokes', 'hogbom'
00172                'clark'  use smaller beam (faster, usually good enough);
00173                 for stokes images clean components peaks are searched in the I^2+Q^2+U^2+V^2 domain 
00174                'clarkstokes' locate clean components independently in each stokes image
00175                'hogbom' full-width of image (slower, better for poor 
00176                uv-coverage)
00177                Note:  psfmode will be used to clean is imagermode = ''
00178        imagermode -- Advanced imaging e.g mosaic or Cotton-Schwab clean
00179                default: imagermode='': Options: '', 'csclean'
00180                default ''  => psfmode cleaning algorithm used
00181 
00182   >>> imagermode='csclean' expandable parameter(s): 
00183             Image using the Cotton-Schwab algorithm in between major cycles
00184             cyclefactor -- Change the threshold at which
00185                           the deconvolution cycle will stop, degrid
00186                           and subtract from the visibilities.  For
00187                           poor PSFs, reconcile often (cyclefactor=4 or
00188                           5); For good PSFs, use cyclefactor 1.5 to
00189                           2.0. Note: threshold = cyclefactor * max
00190                           sidelobe * max residual.
00191                           default: 1.5; example: cyclefactor=4
00192             cyclespeedup -- Cycle threshold doubles in this
00193                           number of iterations default: -1;
00194                           example: cyclespeedup=3
00195                           try cyclespeedup = 50 to speed up cleaning 
00196              
00197        imsize -- Image pixel size (x,y).  DOES NOT HAVE TO BE A POWER OF 2
00198                default = [256,256]; example: imsize=[350,350]
00199                imsize = 500 is equivalent to [500,500]
00200                Avoid odd-numbered imsize.
00201        cell -- Cell size (x,y)
00202                default= '1.0arcsec';
00203                example: cell=['0.5arcsec,'0.5arcsec'] or
00204                cell=['1arcmin', '1arcmin']
00205                cell = '1arcsec' is equivalent to ['1arcsec','1arcsec']
00206                NOTE:cell = 2.0 => ['2arcsec', '2arcsec']
00207        phasecenter -- direction measure  or fieldid for the mosaic center
00208                default: '' => first field selected ; example: phasecenter=6
00209                or phasecenter='J2000 19h30m00 -40d00m00'
00210        restfreq -- Specify rest frequency to use for output image
00211                default='' Occasionally it is necessary to set this (for
00212                example some VLA spectral line data).  For example for
00213                NH_3 (1,1) put restfreq='23.694496GHz'
00214        stokes -- Stokes parameters to image
00215                default='I'; example: stokes='IQUV';
00216                Options: 'I','IV''QU','IQUV','RR','LL','XX','YY','RRLL','XXYY'
00217 
00218        weighting -- Weighting to apply to visibilities:
00219                default='natural'; example: weighting='uniform';
00220                Options: 'natural','uniform','briggs', 
00221                        'superuniform','briggsabs','radial'
00222 
00223   >>> Weighting expandable parameters
00224                For weighting='briggs' and 'briggsabs'
00225                    robust -- Brigg's robustness parameter
00226                    default=0.0; example: robust=0.5;
00227                    Options: -2.0 to 2.0; -2 (uniform)/+2 (natural)
00228                For weighting='briggsabs'
00229                    noise   -- noise parameter to use for Briggs "abs" 
00230                    weighting
00231                    example noise='1.0mJy'
00232                npixels -- uv-cell area used for weight calculation
00233                    example npixels=1
00234                    Default = 0
00235                    superuniform:  0 Means 3x3 cells for weighting
00236                      the cell weight is proportional to the weight of
00237                      the 3x3 cells centered on it.
00238                    superuniform = F means 1x1 cell for averaging weights.
00239                    briggs/briggsabs: 0 is similar to 1x1 cell weight.
00240                      1 may? be similar to 3X3 cells.
00241                    Only npixels 0 or 1 recommended
00242                    
00243        mask -- Initial specification of cleanbox(es), mask image(s), and/or
00244            region(s) to be used for CLEANing.  For channel data (image cubes),
00245            any initial mask will be applied to every channel. mask default: 
00246            [] (no masking); Possible specification types: (a) Explicit
00247            cleanbox pixel ranges example: mask=[110,110,150,145] clean
00248            region with blc=110,100; trc=150,145 (pixel values) (b)
00249            Filename with cleanbox pixel values with ascii format:
00250            example: mask='mycleanbox.txt' <fieldid blc-x blc-y
00251            trc-x trc-y> on each line 
00252            1 45 66 123 124 
00253            2 23 100 300 340
00254            (c) Filename for image mask example: mask='myimage.mask'
00255            (d) Filename for region specification (e.g. from viewer)
00256            example: mask='myregion.rgn' (e) Combinations of any of the
00257            above example: mask=[[110,110,150,145],'mycleanbox.txt',
00258            'myimage.mask','myregion.rgn']
00259            If include outlier fields, then mask need to be spefied in
00260            nested lists: e.g. mask=[[[110,110,150,145],'myimage.mask'],[],[20,20,40,40]]
00261            (A clean box with [110,110,150,145] and a image mask for main field, 
00262             no mask for 1st outlier field, 1 clean box for second outlier field.)
00263        modelimage -- Name of model image(s) to initialize cleaning. If
00264                multiple images, then these will be added together to
00265                form initial starting model NOTE: these are in addition
00266                to any initial model in the <imagename>.model image file
00267                default: '' (none); example: modelimage='orion.model'
00268                modelimage=['orion.model','sdorion.image'] Note: if the
00269                units in the image are Jy/beam as in a single-dish
00270                image, then it will be converted to Jy/pixel as in a
00271                model image, using the restoring beam in the image
00272                header
00273   >>> uvtaper=True expandable parameters
00274                outertaper -- uv-taper on outer baselines in uv-plane
00275                  [bmaj, bmin, bpa] taper Gaussian scale in uv or 
00276                  angular units. NOTE: uv taper in (klambda) is roughly on-sky 
00277                  FWHM(arcsec/200)
00278                  default: outertaper=[]; no outer taper applied
00279                  example: outertaper=['5klambda']  circular taper 
00280                                 FWHM=5 kilo-lambda
00281                          outertaper=['5klambda','3klambda','45.0deg']
00282                          outertaper=['10arcsec'] on-sky FWHM 10"
00283                          outertaper=['300.0'] default units are meters 
00284                                 in aperture plane
00285                innertaper -- uv-taper in center of uv-plane
00286                  [bmaj,bmin,bpa] Gaussian scale at which taper falls to 
00287                  zero at uv=0
00288                  default: innertaper=[]; no inner taper applied
00289                  NOT YET IMPLEMENTED                
00290        niter -- Maximum number iterations over all clean iterations.
00291                default: 500;  example: niter=5000
00292        npercycle -- Number of clean minor cycles before making new clean region
00293            selection. 
00294            default: 100;  example: npercycle = 100
00295        npercycle_speedup: If no new clean regions found during an iteration of
00296            clean region selections, increase npercycle by this factor.
00297            (Npercycle returns to initial value if new clean regions are later
00298             found.)
00299            default: 1.5;  example: npercycle_speedup = 2
00300        gain -- Loop gain for CLEANing
00301                default: 0.1; example: gain=0.5
00302        pbcor -- Output primary beam-corrected image 
00303               default: pbcor=False; output un-corrected image 
00304               example: pbcor=True; output pb-corrected image (masked outside
00305                minpb) Note: if you set pbcor=False, you can later
00306                recover the pbcor image by dividing by the .flux image
00307                (e.g. using immath)
00308        minpb -- Minimum PB level to use default=0.1;
00309                The flux image is used to determine this
00310                except for the case of mosaic with ft='mosaic'
00311                where the flux.pbcoverage image is used.
00312                example:
00313                minpb=0.01 Note: this minpb is always in effect
00314                (regardless of pbcor=True/False) 
00315        clean_threshold -- Flux level at which to stop CLEANing
00316                default: '0.0mJy'; 
00317                example: threshold='2.3mJy'  (always include units)
00318                         threshold = '0.0023Jy'
00319                         threshold = '0.0023Jy/beam' (okay also)
00320        Nrms -- Stop cleaning when maximum residual is below this value times
00321            the current rms (outside the current clean regions).
00322            default: 6
00323            example: Nrms=4
00324        eps_maxres -- Convergence parameter to stop cleaning: stop if maximum
00325            residual has changed by less than a factor of eps_maxres.
00326            default: 0.01  (one per cent change)
00327            example: eps_maxres = 0.05
00328        allow_maxres_inc -- Parameter to stop cleaning: stop if maximum residual
00329            has increased between clean iterations this number of times.
00330            default: 3
00331            example: allow_maxres_inc = 2
00332        island_rms: threshold (this value times current rms) at which to box the
00333            residual image when searching for new clean regions
00334            default: 4
00335            example:  island_rms = 3
00336        diag: T/F switch to declare if pixels connected on the diagonal belong
00337            to the same island, when selecting pixels for clean boxing
00338            default: False
00339            example: diag = True
00340        peak_rms: threshold (this value times current rms) for peak pixel flux
00341            to qualify an island for clean boxing
00342            default: 6
00343            example: peak_rms = 5
00344        gain_threshold: threshold (this value times current maximum residual) of
00345            peak pixel in island to qualify island for clean boxing. 
00346            default: 0.1
00347            example: gain_threshold = 0.5
00348        Npeak: maximum number of new clean regions to add each iteration
00349            default: 3
00350            example: Npeak = 5
00351        shape: parameter to determine shape of clean regions. 
00352            0: all circles
00353            1: all boxes
00354            2: choose according to island shape (circles if island has similar
00355            dimension in x and y direction, box otherwise)
00356            default: 1  
00357            example: shape=2
00358        boxstretch: number of pixels to increase outward size of clean region,
00359            can range from -1 to 5. 
00360            default: 1
00361            example: boxstretch = 3
00362        irregsize: for islands this large (dimension in pixels) or larger, fill
00363            in mask with island's actual shape rather than using a box or
00364            circle.  Set to 0 to ignore this parameter.
00365            default: 100
00366            example: irregsize = 50
00367 
00368   
00369         """
00370         a=inspect.stack()
00371         stacklevel=0
00372         for k in range(len(a)):
00373           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00374                 stacklevel=k
00375                 break
00376         myf=sys._getframe(stacklevel).f_globals
00377         myf['__last_task'] = 'autoclean'
00378         myf['taskname'] = 'autoclean'
00379         ###
00380         myf['update_params'](func=myf['taskname'],printtext=False)
00381         ###
00382         ###
00383         #Handle globals or user over-ride of arguments
00384         #
00385         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00386         useLocalDefaults = False
00387 
00388         for item in function_signature_defaults.iteritems():
00389                 key,val = item
00390                 keyVal = eval(key)
00391                 if (keyVal == None):
00392                         #user hasn't set it - use global/default
00393                         pass
00394                 else:
00395                         #user has set it - use over-ride
00396                         if (key != 'self') :
00397                            useLocalDefaults = True
00398                         #myf[key]=keyVal
00399 
00400         myparams = {}
00401         if useLocalDefaults :
00402            for item in function_signature_defaults.iteritems():
00403                key,val = item
00404                keyVal = eval(key)
00405                exec('myparams[key] = keyVal')
00406                if (keyVal == None):
00407                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00408                    keyVal = eval(key)
00409                    if(type(keyVal) == dict) :
00410                       exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00411 
00412         else :
00413             uselessvariable = None 
00414             myparams['vis'] = vis = myf['vis']
00415             myparams['imagename'] = imagename = myf['imagename']
00416             myparams['field'] = field = myf['field']
00417             myparams['spw'] = spw = myf['spw']
00418             myparams['selectdata'] = selectdata = myf['selectdata']
00419             myparams['timerange'] = timerange = myf['timerange']
00420             myparams['uvrange'] = uvrange = myf['uvrange']
00421             myparams['antenna'] = antenna = myf['antenna']
00422             myparams['scan'] = scan = myf['scan']
00423             myparams['mode'] = mode = myf['mode']
00424             myparams['nchan'] = nchan = myf['nchan']
00425             myparams['start'] = start = myf['start']
00426             myparams['width'] = width = myf['width']
00427             myparams['interpolation'] = interpolation = myf['interpolation']
00428             myparams['doconcat'] = doconcat = myf['doconcat']
00429             myparams['psfmode'] = psfmode = myf['psfmode']
00430             myparams['imagermode'] = imagermode = myf['imagermode']
00431             myparams['cyclefactor'] = cyclefactor = myf['cyclefactor']
00432             myparams['cyclespeedup'] = cyclespeedup = myf['cyclespeedup']
00433             myparams['imsize'] = imsize = myf['imsize']
00434             myparams['cell'] = cell = myf['cell']
00435             myparams['phasecenter'] = phasecenter = myf['phasecenter']
00436             myparams['restfreq'] = restfreq = myf['restfreq']
00437             myparams['stokes'] = stokes = myf['stokes']
00438             myparams['weighting'] = weighting = myf['weighting']
00439             myparams['robust'] = robust = myf['robust']
00440             myparams['noise'] = noise = myf['noise']
00441             myparams['npixels'] = npixels = myf['npixels']
00442             myparams['interactive'] = interactive = myf['interactive']
00443             myparams['mask'] = mask = myf['mask']
00444             myparams['modelimage'] = modelimage = myf['modelimage']
00445             myparams['uvtaper'] = uvtaper = myf['uvtaper']
00446             myparams['outertaper'] = outertaper = myf['outertaper']
00447             myparams['innertaper'] = innertaper = myf['innertaper']
00448             myparams['niter'] = niter = myf['niter']
00449             myparams['npercycle'] = npercycle = myf['npercycle']
00450             myparams['npercycle_speedup'] = npercycle_speedup = myf['npercycle_speedup']
00451             myparams['gain'] = gain = myf['gain']
00452             myparams['pbcor'] = pbcor = myf['pbcor']
00453             myparams['minpb'] = minpb = myf['minpb']
00454             myparams['clean_threshold'] = clean_threshold = myf['clean_threshold']
00455             myparams['Nrms'] = Nrms = myf['Nrms']
00456             myparams['eps_maxres'] = eps_maxres = myf['eps_maxres']
00457             myparams['useabsresid'] = useabsresid = myf['useabsresid']
00458             myparams['allow_maxres_inc'] = allow_maxres_inc = myf['allow_maxres_inc']
00459             myparams['island_rms'] = island_rms = myf['island_rms']
00460             myparams['diag'] = diag = myf['diag']
00461             myparams['peak_rms'] = peak_rms = myf['peak_rms']
00462             myparams['gain_threshold'] = gain_threshold = myf['gain_threshold']
00463             myparams['Npeak'] = Npeak = myf['Npeak']
00464             myparams['shape'] = shape = myf['shape']
00465             myparams['boxstretch'] = boxstretch = myf['boxstretch']
00466             myparams['irregsize'] = irregsize = myf['irregsize']
00467 
00468         if type(imsize)==int: imsize=[imsize]
00469         if type(cell)==float: cell=[cell]
00470         if type(outertaper)==str: outertaper=[outertaper]
00471         if type(innertaper)==str: innertaper=[innertaper]
00472 
00473         result = None
00474 
00475 #
00476 #    The following is work around to avoid a bug with current python translation
00477 #
00478         mytmp = {}
00479 
00480         mytmp['vis'] = vis
00481         mytmp['imagename'] = imagename
00482         mytmp['field'] = field
00483         mytmp['spw'] = spw
00484         mytmp['selectdata'] = selectdata
00485         mytmp['timerange'] = timerange
00486         mytmp['uvrange'] = uvrange
00487         mytmp['antenna'] = antenna
00488         mytmp['scan'] = scan
00489         mytmp['mode'] = mode
00490         mytmp['nchan'] = nchan
00491         mytmp['start'] = start
00492         mytmp['width'] = width
00493         mytmp['interpolation'] = interpolation
00494         mytmp['doconcat'] = doconcat
00495         mytmp['psfmode'] = psfmode
00496         mytmp['imagermode'] = imagermode
00497         mytmp['cyclefactor'] = cyclefactor
00498         mytmp['cyclespeedup'] = cyclespeedup
00499         mytmp['imsize'] = imsize
00500         if type(cell) == str :
00501            mytmp['cell'] = casac.quanta().quantity(cell)
00502         else :
00503            mytmp['cell'] = cell
00504         mytmp['phasecenter'] = phasecenter
00505         mytmp['restfreq'] = restfreq
00506         mytmp['stokes'] = stokes
00507         mytmp['weighting'] = weighting
00508         mytmp['robust'] = robust
00509         mytmp['noise'] = noise
00510         mytmp['npixels'] = npixels
00511         mytmp['interactive'] = interactive
00512         mytmp['mask'] = mask
00513         mytmp['modelimage'] = modelimage
00514         mytmp['uvtaper'] = uvtaper
00515         mytmp['outertaper'] = outertaper
00516         mytmp['innertaper'] = innertaper
00517         mytmp['niter'] = niter
00518         mytmp['npercycle'] = npercycle
00519         mytmp['npercycle_speedup'] = npercycle_speedup
00520         mytmp['gain'] = gain
00521         mytmp['pbcor'] = pbcor
00522         mytmp['minpb'] = minpb
00523         if type(clean_threshold) == str :
00524            mytmp['clean_threshold'] = casac.quanta().quantity(clean_threshold)
00525         else :
00526            mytmp['clean_threshold'] = clean_threshold
00527         mytmp['Nrms'] = Nrms
00528         mytmp['eps_maxres'] = eps_maxres
00529         mytmp['useabsresid'] = useabsresid
00530         mytmp['allow_maxres_inc'] = allow_maxres_inc
00531         mytmp['island_rms'] = island_rms
00532         mytmp['diag'] = diag
00533         mytmp['peak_rms'] = peak_rms
00534         mytmp['gain_threshold'] = gain_threshold
00535         mytmp['Npeak'] = Npeak
00536         mytmp['shape'] = shape
00537         mytmp['boxstretch'] = boxstretch
00538         mytmp['irregsize'] = irregsize
00539         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00540         trec = casac.utils().torecord(pathname+'autoclean.xml')
00541 
00542         casalog.origin('autoclean')
00543         if not trec.has_key('autoclean') or not casac.utils().verify(mytmp, trec['autoclean']) :
00544             return False
00545 
00546 
00547         try :
00548           casalog.post('')
00549           casalog.post('##########################################')
00550           casalog.post('##### Begin Task: autoclean           #####')
00551           casalog.post('')
00552           result = autoclean(vis, imagename, field, spw, selectdata, timerange, uvrange, antenna, scan, mode, nchan, start, width, interpolation, doconcat, psfmode, imagermode, cyclefactor, cyclespeedup, imsize, cell, phasecenter, restfreq, stokes, weighting, robust, noise, npixels, interactive, mask, modelimage, uvtaper, outertaper, innertaper, niter, npercycle, npercycle_speedup, gain, pbcor, minpb, clean_threshold, Nrms, eps_maxres, useabsresid, allow_maxres_inc, island_rms, diag, peak_rms, gain_threshold, Npeak, shape, boxstretch, irregsize)
00553           casalog.post('')
00554           casalog.post('##### End Task: autoclean           #####')
00555           casalog.post('##########################################')
00556 
00557 
00558 # saveinputs for individule engine has no use
00559 # saveinputs should alos be removed from casa_in_py.py
00560 #
00561 #
00562 #          saveinputs = myf['saveinputs']
00563 #          saveinputs('autoclean', 'autoclean.last', myparams)
00564 #
00565 #
00566         except Exception, instance:
00567           #print '**** Error **** ',instance
00568           pass
00569 
00570         gc.collect()
00571         return result
00572 #
00573 #
00574 ##
00575 #    def paramgui(self, useGlobals=True):
00576 #        """
00577 #        Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00578 #        """
00579 #        import paramgui
00580 #
00581 #        a=inspect.stack()
00582 #        stacklevel=0
00583 #        for k in range(len(a)):
00584 #          if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00585 #            stacklevel=k
00586 #            break
00587 #        myf = sys._getframe(stacklevel).f_globals
00588 #
00589 #        if useGlobals:
00590 #            paramgui.setGlobals(myf)
00591 #        else:
00592 #            paramgui.setGlobals({})
00593 #
00594 #        paramgui.runTask('autoclean', myf['_ip'])
00595 #        paramgui.setGlobals({})
00596 #
00597 #
00598 #
00599 #
00600     def defaults(self, param=None):
00601         a=inspect.stack()
00602         stacklevel=0
00603         for k in range(len(a)):
00604           if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00605                 stacklevel=k
00606                 break
00607         myf=sys._getframe(stacklevel).f_globals
00608         a = odict()
00609         a['vis']  = ''
00610         a['imagename']  = ''
00611         a['field']  = ''
00612         a['spw']  = ''
00613         a['selectdata']  = True
00614         a['mode']  = 'mfs'
00615         a['psfmode']  = 'clark'
00616         a['imagermode']  = ''
00617         a['imsize']  = [256, 256]
00618         a['cell']  = ['1.0arcsec']
00619         a['phasecenter']  = ''
00620         a['restfreq']  = ''
00621         a['stokes']  = 'I'
00622         a['weighting']  = 'natural'
00623         a['interactive']  = False
00624         a['mask']  = []
00625         a['modelimage']  = ''
00626         a['uvtaper']  = False
00627         a['niter']  = 500
00628         a['npercycle']  = 100
00629         a['npercycle_speedup']  = 1.5
00630         a['gain']  = 0.1
00631         a['pbcor']  = False
00632         a['minpb']  = 0.1
00633         a['clean_threshold']  = '0.0mJy'
00634         a['Nrms']  = 6
00635         a['eps_maxres']  = 0.01
00636         a['useabsresid']  = False
00637         a['allow_maxres_inc']  = 3
00638         a['island_rms']  = 4
00639         a['diag']  = False
00640         a['peak_rms']  = 6
00641         a['gain_threshold']  = 0.1
00642         a['Npeak']  = 3
00643         a['shape']  = 1
00644         a['boxstretch']  = 1
00645         a['irregsize']  = 100
00646 
00647         a['async']=False
00648         a['selectdata'] = {
00649                     0:{'value':False}, 
00650                     1:odict([{'value':True}, {'timerange':''}, {'uvrange':''}, {'antenna':''}, {'scan':''}])}
00651         a['mode'] = {
00652                     0:odict([{'value':'mfs'}, {'nterms':1}, {'reffreq':''}]), 
00653                     1:odict([{'value':'channel'}, {'nchan':1}, {'start':0}, {'width':1}, {'interpolation':'linear'}, {'doconcat':True}]), 
00654                     2:odict([{'value':'velocity'}, {'nchan':1}, {'start':'0.0km/s'}, {'width':'1km/s'}, {'interpolation':'linear'}, {'doconcat':True}]), 
00655                     3:odict([{'value':'frequency'}, {'nchan':1}, {'start':'1.4GHz'}, {'width':'10kHz'}, {'interpolation':'linear'}, {'doconcat':True}])}
00656         a['weighting'] = {
00657                     0:{'value':'natural'}, 
00658                     1:{'value':'uniform'}, 
00659                     2:odict([{'value':'briggs'}, {'robust':0.0}, {'npixels':0}]), 
00660                     3:odict([{'value':'briggsabs'}, {'robust':0.0}, {'noise':'1.0Jy'}, {'npixels':0}]), 
00661                     4:odict([{'value':'superuniform'}, {'npixels':0}])}
00662         a['uvtaper'] = {
00663                     0:{'value':False}, 
00664                     1:odict([{'value':True}, {'outertaper':[]}, {'innertaper':[]}])}
00665         a['imagermode'] = {
00666                     0:{'value':''}, 
00667                     1:odict([{'value':'csclean'}, {'cyclefactor':1.5}, {'cyclespeedup':-1}])}
00668 
00669 ### This function sets the default values but also will return the list of
00670 ### parameters or the default value of a given parameter
00671         if(param == None):
00672                 myf['__set_default_parameters'](a)
00673         elif(param == 'paramkeys'):
00674                 return a.keys()
00675         else:
00676                 if(a.has_key(param)):
00677                    #if(type(a[param]) == dict) :
00678                    #   return a[param][len(a[param])-1]['value']
00679                    #else :
00680                       return a[param]
00681 
00682 
00683 #
00684 #
00685     def check_params(self, param=None, value=None):
00686       a=inspect.stack() 
00687       stacklevel=0
00688       for k in range(len(a)):
00689         if (string.find(a[k][1], 'ipython console') > 0) or (string.find(a[k][1], '<string>') >= 0):
00690             stacklevel=k
00691             break
00692       myf=sys._getframe(stacklevel).f_globals
00693 
00694 #      print 'param:', param, 'value:', value
00695       try :
00696          if str(type(value)) != "<type 'instance'>" :
00697             value0 = value
00698             value = myf['cu'].expandparam(param, value)
00699             matchtype = False
00700             if(type(value) == numpy.ndarray):
00701                if(type(value) == type(value0)):
00702                   myf[param] = value.tolist()
00703                else:
00704                   #print 'value:', value, 'value0:', value0
00705                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00706                   myf[param] = value0
00707                   if type(value0) != list :
00708                      matchtype = True
00709             else :
00710                myf[param] = value
00711             value = myf['cu'].verifyparam({param:value})
00712             if matchtype:
00713                value = False
00714       except Exception, instance:
00715          #ignore the exception and just return it unchecked
00716          myf[param] = value
00717       return value
00718 
00719 #
00720 #
00721     def description(self, key='autoclean', subkey=None):
00722         desc={'autoclean': 'CLEAN an image with automatically-chosen clean regions.',
00723                'vis': 'Name of input visibility file',
00724                'imagename': 'Pre-name of output images',
00725                'field': 'Field Name or id',
00726                'spw': 'Spectral windows:channels e.g. \'0~3:3~100\', \'\' is all',
00727                'selectdata': 'Other data selection parameters',
00728                'timerange': 'Range of time to select from data',
00729                'uvrange': 'Select data within uvrange ',
00730                'antenna': 'Select data based on antenna/baseline',
00731                'scan': 'Scan number range',
00732                'mode': 'Spectral gridding type (mfs, channel, velocity, frequency)',
00733                'nchan': 'Number of channels (planes) in output image',
00734                'start': 'First channel in input to use',
00735                'width': 'Number of input channels to average',
00736                'interpolation': 'Spectral interpolation(nearest, linear, cubic)',
00737                'doconcat': 'Concatenate multiple channels into single final image',
00738                'psfmode': 'Method of PSF calculation to use during minor cycles',
00739                'imagermode': 'Options: \'csclean\' or \'mosaic\', \' \', uses psfmode',
00740                'cyclefactor': 'change depth in between of csclean cycle',
00741                'cyclespeedup': 'Cycle threshold doubles in this number of iteration',
00742                'imsize': 'x and y image size in pixels. Single value: same for both',
00743                'cell': 'x and y cell size(s). Default unit arcsec.',
00744                'phasecenter': 'Image center: direction or field index',
00745                'restfreq': 'Rest frequency to assign to image (see help)',
00746                'stokes': 'Stokes params to image (eg I,IV, QU,IQUV); Current autoclean implementation requires Stokes="I".',
00747                'weighting': 'Weighting of uv (natural, uniform, briggs, ...)',
00748                'robust': 'Briggs robustness parameter',
00749                'noise': 'noise parameter for briggs abs mode weighting',
00750                'npixels': 'number of pixels for superuniform or briggs weighting',
00751                'interactive': 'use interactive clean (with GUI viewer)',
00752                'mask': 'Initial cleanbox(es), mask image(s), and/or region(s)  used in cleaning',
00753                'modelimage': 'Name of model image(s) to initialize cleaning',
00754                'uvtaper': 'Apply additional uv tapering of visibilities',
00755                'outertaper': 'uv-taper on outer baselines in uv-plane',
00756                'innertaper': 'uv-taper in center of uv-plane (not implemented)',
00757                'niter': 'Max number of total clean cycles per channel',
00758                'npercycle': 'Clean iterations before adding new clean boxes',
00759                'npercycle_speedup': 'Increase npercycle by this factor if no new regions found.',
00760                'gain': 'Loop gain for cleaning',
00761                'pbcor': 'Output primary beam-corrected image',
00762                'minpb': 'Minimum PB level to use',
00763                'clean_threshold': 'Flux level to stop cleaning.  Must include units.',
00764                'Nrms': 'Threshold to stop cleaning: current rms * Nrms',
00765                'eps_maxres': 'Stop cleaning if max abs(residual) changes by less than this factor',
00766                'useabsresid': 'If True, use absolute value of residual to test for clean convergence.',
00767                'allow_maxres_inc': 'Stop cleaning if max abs(residual) increases this many times (set to -1 to ignore)',
00768                'island_rms': 'Threshold for islands when finding clean regions: current rms * island_rms',
00769                'diag': 'Count diagonal connection as same island?',
00770                'peak_rms': 'Threshold to add new clean box: peak in island must be at least current rms * peak_rms',
00771                'gain_threshold': 'Threshold to add new clean box: peak in island must be at least current max residual * gain_threshold',
00772                'Npeak': 'Max number of new clean regions to add in each iteration.',
00773                'shape': 'Shape of clean regions: 0 for circles, 1 for boxes, 2 for both.',
00774                'boxstretch': 'Increase clean region size by this many pixels beyond island size.',
00775                'irregsize': 'For regions this large (in pixels), use irregular clean region.',
00776 
00777                'async': 'If true the taskname must be started using autoclean(...)'
00778               }
00779 
00780 #
00781 # Set subfields defaults if needed
00782 #
00783         if(subkey == 'channel'):
00784           desc['start'] = 'First channel to use (0=first channel specified in spw)'
00785         if(subkey == 'velocity'):
00786           desc['start'] = 'Velocity of first image channel: e.g \'0.0km/s\''
00787         if(subkey == 'velocity'):
00788           desc['width'] = 'image channel width in velocity units: e.g \'1.0km/s\''
00789         if(subkey == 'frequency'):
00790           desc['start'] = 'Frequency of first image channel: e.q. \'1.4GHz\''
00791         if(subkey == 'frequency'):
00792           desc['width'] = 'Image channel width in frequency units: e.g \'1.0kHz\''
00793         if(subkey == 'briggs'):
00794           desc['npixels'] = 'number of pixels to determine uv-cell size 0=> field of view'
00795         if(subkey == 'briggsabs'):
00796           desc['npixels'] = 'number of pixels to determine uv-cell size 0=> field of view'
00797         if(subkey == 'superuniform'):
00798           desc['npixels'] = 'number of pixels to determine uv-cell size 0=> +/-3pixels'
00799 
00800         if(desc.has_key(key)) :
00801            return desc[key]
00802 
00803     def itsdefault(self, paramname) :
00804         a = {}
00805         a['vis']  = ''
00806         a['imagename']  = ''
00807         a['field']  = ''
00808         a['spw']  = ''
00809         a['selectdata']  = True
00810         a['timerange']  = ''
00811         a['uvrange']  = ''
00812         a['antenna']  = ''
00813         a['scan']  = ''
00814         a['mode']  = 'mfs'
00815         a['nchan']  = 1
00816         a['start']  = 0
00817         a['width']  = 1
00818         a['interpolation']  = 'linear'
00819         a['doconcat']  = True
00820         a['psfmode']  = 'clark'
00821         a['imagermode']  = ''
00822         a['cyclefactor']  = 1.5
00823         a['cyclespeedup']  = -1
00824         a['imsize']  = [256, 256]
00825         a['cell']  = ['1.0arcsec']
00826         a['phasecenter']  = ''
00827         a['restfreq']  = ''
00828         a['stokes']  = 'I'
00829         a['weighting']  = 'natural'
00830         a['robust']  = 0.0
00831         a['noise']  = '1.0Jy'
00832         a['npixels']  = 0
00833         a['interactive']  = False
00834         a['mask']  = []
00835         a['modelimage']  = ''
00836         a['uvtaper']  = False
00837         a['outertaper']  = ['']
00838         a['innertaper']  = ['1.0']
00839         a['niter']  = 500
00840         a['npercycle']  = 100
00841         a['npercycle_speedup']  = 1.5
00842         a['gain']  = 0.1
00843         a['pbcor']  = False
00844         a['minpb']  = 0.1
00845         a['clean_threshold']  = '0.0mJy'
00846         a['Nrms']  = 6
00847         a['eps_maxres']  = 0.01
00848         a['useabsresid']  = False
00849         a['allow_maxres_inc']  = 3
00850         a['island_rms']  = 4
00851         a['diag']  = False
00852         a['peak_rms']  = 6
00853         a['gain_threshold']  = 0.1
00854         a['Npeak']  = 3
00855         a['shape']  = 1
00856         a['boxstretch']  = 1
00857         a['irregsize']  = 100
00858 
00859         if a.has_key(paramname) :
00860               return a[paramname]
00861 autoclean_pg = autoclean_pg_()