casa  $Rev:20696$
 All Classes Namespaces Files Functions Variables
mosaic_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_mosaic import mosaic
00018 class mosaic_cli_:
00019     __name__ = "mosaic"
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__ = (mosaic_cli_,)
00028        self.__doc__ = self.__call__.__doc__
00029 
00030        self.parameters={'vis':None, 'imagename':None, 'mode':None, 'alg':None, 'imsize':None, 'cell':None, 'phasecenter':None, 'stokes':None, 'niter':None, 'gain':None, 'threshold':None, 'mask':None, 'cleanbox':None, 'nchan':None, 'start':None, 'width':None, 'field':None, 'spw':None, 'timerange':None, 'restfreq':None, 'sdimage':None, 'modelimage':None, 'weighting':None, 'mosweight':None, 'rmode':None, 'robust':None, 'ftmachine':None, 'cyclefactor':None, 'cyclespeedup':None, 'scaletype':None, 'minpb':None, 'sigma':None, 'targetflux':None, 'constrainflux':None, 'prior':None, 'negcomponent':None, 'scales':None, 'npercycle':None, 'npixels':None, 'noise':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, mode=None, alg=None, imsize=None, cell=None, phasecenter=None, stokes=None, niter=None, gain=None, threshold=None, mask=None, cleanbox=None, nchan=None, start=None, width=None, field=None, spw=None, timerange=None, restfreq=None, sdimage=None, modelimage=None, weighting=None, mosweight=None, rmode=None, robust=None, ftmachine=None, cyclefactor=None, cyclespeedup=None, scaletype=None, minpb=None, sigma=None, targetflux=None, constrainflux=None, prior=None, negcomponent=None, scales=None, npercycle=None, npixels=None, noise=None,  async=None):
00047 
00048         """Create a multi-field deconvolved image with selected algorithm
00049 
00050 
00051     Two types of point-source deconvolution, as well as multi-scale
00052     deconvolution, are available.  A continuum image (mfs) is produced
00053     by gridding together all spectral data.   Individual channels or
00054     groups of channels can also be images and then placed in an output
00055     image cube.
00056 
00057     The cleaning regions can be specified by an input mask image, from a
00058     file containing rectangular regions, or interactively as the
00059     deconvolution progresses.
00060 
00061     The mosaic task only uses the "corrected" datacolumn which is made
00062     from the "data" data column using applycal with the appropriate
00063     calibration tables.  Many Stokes combinations are available.
00064 
00065 
00066     Keyword arguments:
00067     vis -- Name of input visibility file
00068             default: none; example: vis='ngc5921.ms'
00069     imagename -- Pre-name of output images:
00070             default: none; example: imagename='m2'
00071             output images are:
00072               m2.image; cleaned and restored image
00073               m2.flux;  relative sky sensitivity over field
00074               m2.model; image of clean components
00075               m2.residual; image of residuals
00076               m2.interactive.mask; image containing clean regions
00077     mode -- Frequency Specification:
00078             NOTE: See examples below:
00079             default: 'mfs'
00080               mode = 'mfs' means produce one image from all specified data.
00081               mode = 'channel'; Use with nchan, start, width to specify
00082                       output image cube.  See examples below
00083               mode = 'velocity', means channels are specified in velocity.
00084               mode = 'frequency', means channels are specified in frequency.
00085        >>> mode expandable parameters (for modes other than 'mfs')
00086             Start, width are given in units of channels, frequency or velocity
00087                as indicated by mode, but only channel is complete.
00088             nchan -- Number of channels (planes) in output image
00089               default: 1; example: nchan=3
00090             start -- Start input channel (relative-0)
00091               default=0; example: start=5
00092             width -- Output channel width (>1 indicates channel averaging)
00093               default=1; example: width=4
00094         examples:
00095             spw = '0,1'; mode = 'mfs'
00096                will produce one image made from all channels in spw 0 and 1
00097             spw='0:5~28^2'; mode = 'mfs' 
00098                will produce one image made with channels (5,7,9,...,25,27)
00099             spw = '0'; mode = 'channel': nchan=3; start=5; width=4
00100                will produce an image with 3 output planes
00101                plane 1 contains data from channels (5+6+7+8)
00102                plane 2 contains data from channels (9+10+11+12)
00103                plane 3 contains data from channels (13+14+15+16)
00104             spw = '0:0~63^3'; mode=chann; nchan=21; start = 0; width = 1
00105                will produce an image with 20 output planes
00106                Plane 1 contains data from channel 0
00107                Plane 2 contains date from channel 2
00108                Plane 21 contains data from channel 61
00109             spw = '0:0~40^2'; mode = 'channel'; nchan = 3; start = 5; width = 4
00110                will produce an image with three output planes
00111                plane 1 contains channels (5,7)
00112                plane 2 contains channels (13,15)
00113                plane 3 contains channels (21,23)
00114     alg -- Algorithm to use (expandable):
00115             default: 'clark': Options: 'clark','hogbom','multiscale','entropy'
00116             'hogbom' Cleans from the images only.  Only inner quarter
00117                      of image is cleaned
00118             'clark' Cleans from gridded us data.  Only inner quarter of
00119                     image is cleaned
00120             'multiscale' cleans with several resolutions using hobgom clean
00121                   Currently much slower than single resolution. For extended 
00122                   sources, try single resolution with interactive and
00123             'entropy' Maximum entropy algorithm is still experimental
00124                   and not recommended for general use
00125       >>> multiscale expandable parameter
00126             scales  -- in pixel numbers; the size of component to deconvolve
00127                   default = [0,3,10]
00128                    recommended sizes are 0 (point), 3 (points per clean beam), and
00129                     10 (about a factor of three lower resolution)
00130             negcomponent' -- Stop component search when the largest
00131                   scale has found this number of negative components; -1 means
00132                   continue component search even if the largest component is 
00133                   negative.
00134                   default: 2; example: negcomponent=-1
00135       >>> entropy (MEM) expandable parameters (experimental)
00136             sigma -- Target image sigma
00137                   default: '0.001Jy'; example: sigma='0.1Jy'
00138             targetflux -- Target flux for final image
00139                   default: '1.0Jy'; example: targetflux='200Jy'
00140             constrainflux -- Constrain image to match target flux;
00141                   otherwise, targetflux is used to initialize model only.   
00142                        default: False; example: constrainflux=True
00143             prior -- Name of MEM prior images
00144                   default: ['']; example: prior='source_mem.image'
00145     imsize -- Image pixel size (x,y)
00146             default = [256,256]; example: imsize=[350,350]
00147             imsize = 500 is equivalent to [500,500]
00148     cell -- Cell size (x,y)
00149             default= none;
00150             example: cell=['0.5arcsec,'0.5arcsec'] or
00151             cell=['1arcmin', '1arcmin']
00152             cell = '1arcsec' is equivalent to ['1arcsec','1arcsec']
00153             NOTE:cell = '2' makes default cell size of 2 radians! 
00154     phasecenter -- direction measure  or fieldid for the mosaic center
00155             default: 0 (imply field=0 as center); example: phasecenter=6
00156             or phasecenter='J2000 19h30m00 -40d00m00'
00157     stokes -- Stokes parameters to image
00158             default='I'; example: stokes='IQUV';
00159             Options: 'I','IV''QU','IQUV','RR','LL','XX','YY','RRLL','XXYY'
00160     niter -- Maximum number iterations, set to zero for no CLEANing
00161             default: 500; example: niter=500
00162     gain -- Loop gain for CLEANing
00163             default: 0.1; example: gain=0.5
00164     threshold -- Flux level at which to stop CLEANing (units=mJy)
00165             default: 0.0; example: threshold=0.0  
00166     mask -- Name of mask image used for CLEANing
00167             default '' means no mask;
00168               example: mask='orion.mask'.  
00169             It is useful to use a mask from a previous interactive mosaic 
00170             session for a new execution.  The mask image shape
00171             must be the same as the new mosaic.
00172     cleanbox -- Cleaning region:
00173             default: [] defaults to inner quarter of image
00174             Three specification types:
00175             (a) 'interactive' allows the user to build the cleaning
00176                  mask interactively using the viewer.  The viewer will 
00177                  appear every npercycle interation, but modify as needed
00178                  The final interactive maks is saved in the file
00179                  imagename_interactive.mask.
00180             (b) Explicit pixel ranges
00181                 example: cleanbox=[110,110,150,145]
00182                 clean region with blc=110,100; trc=150,145 (pixel values)
00183                 Only one clean region can be given this way.
00184             (c) Filename with pixel values with ascii format:
00185                 <fieldindex blc-x blc-y trc-x trc-y> on each line
00186                 1  45  66  123 124
00187                 2  23 100  300 340
00188       >>> 'interactive' expandable parameter 
00189             npercycle -- this is the number of iterations between each clean 
00190             to update mask interactively. Set to about niter/5, can also
00191             be changed interactively.               
00192     field -- Select fields in mosaic.  Use field id(s) or field name(s).
00193                ['go listobs' to obtain the list id's or names]
00194            default: ''=all fields
00195            If field string is a non-negative integer, it is assumed to
00196                be a field index otherwise, it is assumed to be a field name
00197            field='0~2'; field ids 0,1,2
00198            field='0,4,5~7'; field ids 0,4,5,6,7
00199            field='3C286,3C295'; field named 3C286 and 3C295
00200            field = '3,4C*'; field id 3, all names starting with 4C
00201     spw -- Select spectral window/channels
00202            NOTE: This selects the data passed as the INPUT to mode
00203            default: ''=all spectral windows and channels
00204              spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
00205              spw='<2';  spectral windows less than 2 (i.e. 0,1)
00206              spw='0:5~61'; spw 0, channels 5 to 61
00207              spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, channels 3 to 45.
00208              spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
00209              spw='0:0~10;15~60'; spectral window 0 with channels 0-10,15-60
00210              spw='0:0~10,1:20~30,2:1;2;3'; spw 0, channels 0-10,
00211                    spw 1, channels 20-30, and spw 2, channels, 1,2 and 3
00212     timerange  -- Time range:
00213             default = '' (all); examples,
00214             selectime = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
00215             Note: if YYYY/MM/DD is missing date defaults to first day
00216               in data set
00217             timerange='09:14:0~09:54:0' picks 40 min on first day
00218             timerange= '25:00:00~27:30:00' picks 1 hr to 3 hr 30min on next day
00219             timerange='09:44:00' data within one integration of time
00220             timerange='>10:24:00' data after this time
00221     restfreq -- Specify rest frequency to use for image
00222             default=''
00223             Occasionally it is necessary to set this (for example some VLA
00224             spectral line data).  For example for
00225             NH_3 (1,1) put restfreq='23.694496GHz'
00226     sdimage -- Input Single Dish image to use for model
00227             default='' (no image); example: sdimage='n4826_12mchan.im'
00228     modelimage -- Name of output(/input) model image
00229             default='' (none=imagename.model); modelimage='orion.model'
00230             Note: This specifies the output model if a single dish
00231             image is input or the output model name from the imaging
00232     weighting -- Weighting to apply to visibilities:
00233             default='natural'; example: weighting='uniform';
00234             Options: 'natural','uniform','briggs','radial', 'superuniform'
00235        >>> Weighting expandable parameters
00236             For weighting='briggs'
00237               rmode -- Robustness mode (see help mosaic)
00238                 default='norm'; example='abs';
00239                 Options: 'norm','abs','none'
00240               robust -- Brigg's robustness parameter
00241                 default=0.0; example: robust=0.5;
00242                 Options: -2.0 to 2.0; -2 (uniform)/+2 (natural)
00243               noise   -- noise parameter to use for rmode='abs' in
00244                 briggs weighting
00245                 example noise='1.0mJy'
00246             For superuniform/briggs weighting
00247                 npixels -- number of pixels to determine uv-cell size
00248                 for weight calculation
00249                 example npixels=7
00250     mosweight -- Individually weight the fields of the mosaic
00251             default: False; example: mosweight=True
00252             This can be useful if some of your fields are more
00253             sensitive than others (i.e. due to time spent on-source);
00254             this parameter will give more weight to higher sensitivity
00255             fields in the overlap regions.
00256     ftmachine -- Gridding method for the image;
00257             Options: ft (standard interferometric gridding), sd
00258             (standard single dish) both (ft and sd as appropriate),
00259             mosaic (gridding use PB as convolution function)
00260             default: 'mosaic'; example: ftmachine='ft'
00261     cyclefactor -- Change the threshold at which the deconvolution cycle will
00262             stop, degrid and subtract from the visibilities. For poor PSFs,
00263             reconcile often (cyclefactor=4 or 5); For good PSFs, use
00264             cyclefactor 1.5 to 2.0.
00265             default: 1.5; example: cyclefactor=4
00266             cycle threshold = cyclefactor * max sidelobe * max residual
00267     cyclespeedup -- Cycle threshold doubles in this number of iterations
00268             default: -1; example: cyclespeedup=500
00269     scaletype -- Controls scaling of pixels in the image plane. 
00270             default='SAULT'; example: scaletype='PBCOR'
00271             Options: 'PBCOR','SAULT'
00272             'SAULT' scale makes an output image where the noise is constant
00273              across the whole mosaic. However, the image is NOT
00274              corrected for the PB pattern, and therefore is not "flux
00275              correct". Division of the SAULT image_name.image image
00276              by the image_name.flux image will produce a "flux correct image".
00277              The 'PBCOR' option uses the SAULT scaling scheme for
00278              deconvolution, but when interactively cleaning shows the
00279              primary beam corrected image; the final PBCOR image is "flux
00280              correct"
00281     minpb -- Minimum PB level to use
00282             default=0.1; example: minpb=0.01
00283     async --  Run asynchronously
00284             default = False; do not run asychronously
00285   
00286         """
00287         if not hasattr(self, "__globals__") or self.__globals__ == None :
00288            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00289         #casac = self.__globals__['casac']
00290         casalog = self.__globals__['casalog']
00291         #casalog = casac.casac.logsink()
00292         self.__globals__['__last_task'] = 'mosaic'
00293         self.__globals__['taskname'] = 'mosaic'
00294         ###
00295         self.__globals__['update_params'](func=self.__globals__['taskname'],printtext=False,ipython_globals=self.__globals__)
00296         ###
00297         ###
00298         #Handle globals or user over-ride of arguments
00299         #
00300         function_signature_defaults=dict(zip(self.__call__.func_code.co_varnames,self.__call__.func_defaults))
00301         useLocalDefaults = False
00302 
00303         for item in function_signature_defaults.iteritems():
00304                 key,val = item
00305                 keyVal = eval(key)
00306                 if (keyVal == None):
00307                         #user hasn't set it - use global/default
00308                         pass
00309                 else:
00310                         #user has set it - use over-ride
00311                         if (key != 'self') :
00312                            useLocalDefaults = True
00313 
00314         myparams = {}
00315         if useLocalDefaults :
00316            for item in function_signature_defaults.iteritems():
00317                key,val = item
00318                keyVal = eval(key)
00319                exec('myparams[key] = keyVal')
00320                self.parameters[key] = keyVal
00321                if (keyVal == None):
00322                    exec('myparams[key] = '+ key + ' = self.itsdefault(key)')
00323                    keyVal = eval(key)
00324                    if(type(keyVal) == dict) :
00325                       if len(keyVal) > 0 :
00326                          exec('myparams[key] = ' + key + ' = keyVal[len(keyVal)-1][\'value\']')
00327                       else :
00328                          exec('myparams[key] = ' + key + ' = {}')
00329 
00330         else :
00331             async = self.parameters['async']
00332             myparams['vis'] = vis = self.parameters['vis']
00333             myparams['imagename'] = imagename = self.parameters['imagename']
00334             myparams['mode'] = mode = self.parameters['mode']
00335             myparams['alg'] = alg = self.parameters['alg']
00336             myparams['imsize'] = imsize = self.parameters['imsize']
00337             myparams['cell'] = cell = self.parameters['cell']
00338             myparams['phasecenter'] = phasecenter = self.parameters['phasecenter']
00339             myparams['stokes'] = stokes = self.parameters['stokes']
00340             myparams['niter'] = niter = self.parameters['niter']
00341             myparams['gain'] = gain = self.parameters['gain']
00342             myparams['threshold'] = threshold = self.parameters['threshold']
00343             myparams['mask'] = mask = self.parameters['mask']
00344             myparams['cleanbox'] = cleanbox = self.parameters['cleanbox']
00345             myparams['nchan'] = nchan = self.parameters['nchan']
00346             myparams['start'] = start = self.parameters['start']
00347             myparams['width'] = width = self.parameters['width']
00348             myparams['field'] = field = self.parameters['field']
00349             myparams['spw'] = spw = self.parameters['spw']
00350             myparams['timerange'] = timerange = self.parameters['timerange']
00351             myparams['restfreq'] = restfreq = self.parameters['restfreq']
00352             myparams['sdimage'] = sdimage = self.parameters['sdimage']
00353             myparams['modelimage'] = modelimage = self.parameters['modelimage']
00354             myparams['weighting'] = weighting = self.parameters['weighting']
00355             myparams['mosweight'] = mosweight = self.parameters['mosweight']
00356             myparams['rmode'] = rmode = self.parameters['rmode']
00357             myparams['robust'] = robust = self.parameters['robust']
00358             myparams['ftmachine'] = ftmachine = self.parameters['ftmachine']
00359             myparams['cyclefactor'] = cyclefactor = self.parameters['cyclefactor']
00360             myparams['cyclespeedup'] = cyclespeedup = self.parameters['cyclespeedup']
00361             myparams['scaletype'] = scaletype = self.parameters['scaletype']
00362             myparams['minpb'] = minpb = self.parameters['minpb']
00363             myparams['sigma'] = sigma = self.parameters['sigma']
00364             myparams['targetflux'] = targetflux = self.parameters['targetflux']
00365             myparams['constrainflux'] = constrainflux = self.parameters['constrainflux']
00366             myparams['prior'] = prior = self.parameters['prior']
00367             myparams['negcomponent'] = negcomponent = self.parameters['negcomponent']
00368             myparams['scales'] = scales = self.parameters['scales']
00369             myparams['npercycle'] = npercycle = self.parameters['npercycle']
00370             myparams['npixels'] = npixels = self.parameters['npixels']
00371             myparams['noise'] = noise = self.parameters['noise']
00372 
00373         if type(imsize)==int: imsize=[imsize]
00374         if type(cell)==float: cell=[cell]
00375         if type(mask)==str: mask=[mask]
00376         if type(prior)==str: prior=[prior]
00377         if type(scales)==int: scales=[scales]
00378 
00379         result = None
00380 
00381 #
00382 #    The following is work around to avoid a bug with current python translation
00383 #
00384         mytmp = {}
00385 
00386         mytmp['vis'] = vis
00387         mytmp['imagename'] = imagename
00388         mytmp['mode'] = mode
00389         mytmp['alg'] = alg
00390         mytmp['imsize'] = imsize
00391         if type(cell) == str :
00392            mytmp['cell'] = casac.casac.qa.quantity(cell)
00393         else :
00394            mytmp['cell'] = cell
00395         mytmp['phasecenter'] = phasecenter
00396         mytmp['stokes'] = stokes
00397         mytmp['niter'] = niter
00398         mytmp['gain'] = gain
00399         mytmp['threshold'] = threshold
00400         mytmp['mask'] = mask
00401         mytmp['cleanbox'] = cleanbox
00402         mytmp['nchan'] = nchan
00403         mytmp['start'] = start
00404         mytmp['width'] = width
00405         mytmp['field'] = field
00406         mytmp['spw'] = spw
00407         mytmp['timerange'] = timerange
00408         mytmp['restfreq'] = restfreq
00409         mytmp['sdimage'] = sdimage
00410         mytmp['modelimage'] = modelimage
00411         mytmp['weighting'] = weighting
00412         mytmp['mosweight'] = mosweight
00413         mytmp['rmode'] = rmode
00414         mytmp['robust'] = robust
00415         mytmp['ftmachine'] = ftmachine
00416         mytmp['cyclefactor'] = cyclefactor
00417         mytmp['cyclespeedup'] = cyclespeedup
00418         mytmp['scaletype'] = scaletype
00419         mytmp['minpb'] = minpb
00420         if type(sigma) == str :
00421            mytmp['sigma'] = casac.casac.qa.quantity(sigma)
00422         else :
00423            mytmp['sigma'] = sigma
00424         if type(targetflux) == str :
00425            mytmp['targetflux'] = casac.casac.qa.quantity(targetflux)
00426         else :
00427            mytmp['targetflux'] = targetflux
00428         mytmp['constrainflux'] = constrainflux
00429         mytmp['prior'] = prior
00430         mytmp['negcomponent'] = negcomponent
00431         mytmp['scales'] = scales
00432         mytmp['npercycle'] = npercycle
00433         mytmp['npixels'] = npixels
00434         if type(noise) == str :
00435            mytmp['noise'] = casac.casac.qa.quantity(noise)
00436         else :
00437            mytmp['noise'] = noise
00438         pathname='file:///'+os.environ.get('CASAPATH').split()[0]+'/share/xml/'
00439         trec = casac.casac.utils().torecord(pathname+'mosaic.xml')
00440 
00441         casalog.origin('mosaic')
00442         try :
00443           #if not trec.has_key('mosaic') or not casac.casac.utils().verify(mytmp, trec['mosaic']) :
00444             #return False
00445 
00446           casac.casac.utils().verify(mytmp, trec['mosaic'], True)
00447           scriptstr=['']
00448           saveinputs = self.__globals__['saveinputs']
00449           saveinputs('mosaic', 'mosaic.last', myparams, self.__globals__,scriptstr=scriptstr)
00450           if async :
00451             count = 0
00452             keybase =  time.strftime("%y%m%d.%H%M%S")
00453             key = keybase + "_" + str(count)
00454             while self.__async__.has_key(key) :
00455                count += 1
00456                key = keybase + "_" + str(count)
00457             result = tm.execute('mosaic', vis, imagename, mode, alg, imsize, cell, phasecenter, stokes, niter, gain, threshold, mask, cleanbox, nchan, start, width, field, spw, timerange, restfreq, sdimage, modelimage, weighting, mosweight, rmode, robust, ftmachine, cyclefactor, cyclespeedup, scaletype, minpb, sigma, targetflux, constrainflux, prior, negcomponent, scales, npercycle, npixels, noise)
00458             print "Use: "
00459             print "      tm.retrieve(return_value) # to retrieve the status"
00460             print 
00461             self.rkey = key
00462             self.__async__[key] = result
00463           else :
00464               tname = 'mosaic'
00465               spaces = ' '*(18-len(tname))
00466               casalog.post('\n##########################################'+
00467                            '\n##### Begin Task: ' + tname + spaces + ' #####')
00468               casalog.post(scriptstr[1][1:]+'\n', 'INFO')
00469               result = mosaic(vis, imagename, mode, alg, imsize, cell, phasecenter, stokes, niter, gain, threshold, mask, cleanbox, nchan, start, width, field, spw, timerange, restfreq, sdimage, modelimage, weighting, mosweight, rmode, robust, ftmachine, cyclefactor, cyclespeedup, scaletype, minpb, sigma, targetflux, constrainflux, prior, negcomponent, scales, npercycle, npixels, noise)
00470               casalog.post('##### End Task: ' + tname + '  ' + spaces + ' #####'+
00471                            '\n##########################################')
00472 
00473         except Exception, instance:
00474           if(self.__globals__.has_key('__rethrow_casa_exceptions') and self.__globals__['__rethrow_casa_exceptions']) :
00475              raise
00476           else :
00477              #print '**** Error **** ',instance
00478              tname = 'mosaic'
00479              casalog.post('An error occurred running task '+tname+'.', 'ERROR')
00480              pass
00481 
00482         gc.collect()
00483         return result
00484 #
00485 #
00486 #
00487     def paramgui(self, useGlobals=True, ipython_globals=None):
00488         """
00489         Opens a parameter GUI for this task.  If useGlobals is true, then any relevant global parameter settings are used.
00490         """
00491         import paramgui
00492         if not hasattr(self, "__globals__") or self.__globals__ == None :
00493            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00494 
00495         if useGlobals:
00496             if ipython_globals == None:
00497                 myf=self.__globals__
00498             else:
00499                 myf=ipython_globals
00500 
00501             paramgui.setGlobals(myf)
00502         else:
00503             paramgui.setGlobals({})
00504 
00505         paramgui.runTask('mosaic', myf['_ip'])
00506         paramgui.setGlobals({})
00507 
00508 #
00509 #
00510 #
00511     def defaults(self, param=None, ipython_globals=None, paramvalue=None, subparam=None):
00512         if not hasattr(self, "__globals__") or self.__globals__ == None :
00513            self.__globals__=sys._getframe(len(inspect.stack())-1).f_globals
00514         if ipython_globals == None:
00515             myf=self.__globals__
00516         else:
00517             myf=ipython_globals
00518 
00519         a = odict()
00520         a['vis']  = ''
00521         a['imagename']  = ''
00522         a['mode']  = 'mfs'
00523         a['alg']  = 'clark'
00524         a['imsize']  = [256, 256]
00525         a['cell']  = ['1.0arcsec', '1.0arcsec']
00526         a['phasecenter']  = ''
00527         a['stokes']  = 'I'
00528         a['niter']  = 500
00529         a['gain']  = 0.1
00530         a['threshold']  = 0.0
00531         a['mask']  = ['']
00532         a['cleanbox']  = {}
00533         a['field']  = ''
00534         a['spw']  = ''
00535         a['timerange']  = ''
00536         a['restfreq']  = ''
00537         a['sdimage']  = ''
00538         a['modelimage']  = ''
00539         a['weighting']  = 'natural'
00540         a['mosweight']  = False
00541         a['ftmachine']  = 'mosaic'
00542         a['cyclefactor']  = 1.5
00543         a['cyclespeedup']  = -1
00544         a['scaletype']  = 'SAULT'
00545         a['minpb']  = 0.1
00546 
00547         a['async']=False
00548         a['mode'] = {
00549                     0:{'value':'mfs'}, 
00550                     1:odict([{'value':'channel'}, {'nchan':1}, {'start':0}, {'width':1}]), 
00551                     2:odict([{'value':'velocity'}, {'nchan':1}, {'start':'0.0km/s'}, {'width':'1km/s'}]), 
00552                     3:odict([{'value':'frequency'}, {'nchan':1}, {'start':'1.4GHz'}, {'width':'10kHz'}])}
00553         a['alg'] = {
00554                     0:{'value':'clark'}, 
00555                     1:{'value':'hogbom'}, 
00556                     2:odict([{'value':'multiscale'}, {'scales':[0, 3, 10]}, {'negcomponent':2}]), 
00557                     3:odict([{'value':'entropy'}, {'sigma':0.01}, {'targetflux':1.0}, {'constrainflux':False}, {'prior':['']}]), 
00558                     4:{'value':'emptiness'}}
00559         a['weighting'] = {
00560                     0:{'value':'natural'}, 
00561                     1:{'value':'uniform'}, 
00562                     2:odict([{'value':'briggs'}, {'rmode':'none'}, {'robust':0.0}, {'noise':0.0}, {'npixels':0}]), 
00563                     3:odict([{'value':'superuniform'}, {'npixels':0}])}
00564         a['cleanbox'] = {
00565                     0:{'value':[]}, 
00566                     1:odict([{'value':'interactive'}, {'npercycle':100}])}
00567 
00568 ### This function sets the default values but also will return the list of
00569 ### parameters or the default value of a given parameter
00570         if(param == None):
00571                 myf['__set_default_parameters'](a)
00572         elif(param == 'paramkeys'):
00573                 return a.keys()
00574         else:
00575             if(paramvalue==None and subparam==None):
00576                if(a.has_key(param)):
00577                   return a[param]
00578                else:
00579                   return self.itsdefault(param)
00580             else:
00581                retval=a[param]
00582                if(type(a[param])==dict):
00583                   for k in range(len(a[param])):
00584                      valornotval='value'
00585                      if(a[param][k].has_key('notvalue')):
00586                         valornotval='notvalue'
00587                      if((a[param][k][valornotval])==paramvalue):
00588                         retval=a[param][k].copy()
00589                         retval.pop(valornotval)
00590                         if(subparam != None):
00591                            if(retval.has_key(subparam)):
00592                               retval=retval[subparam]
00593                            else:
00594                               retval=self.itsdefault(subparam)
00595                      else:
00596                         retval=self.itsdefault(subparam)
00597                return retval
00598 
00599 
00600 #
00601 #
00602     def check_params(self, param=None, value=None, ipython_globals=None):
00603       if ipython_globals == None:
00604           myf=self.__globals__
00605       else:
00606           myf=ipython_globals
00607 #      print 'param:', param, 'value:', value
00608       try :
00609          if str(type(value)) != "<type 'instance'>" :
00610             value0 = value
00611             value = myf['cu'].expandparam(param, value)
00612             matchtype = False
00613             if(type(value) == numpy.ndarray):
00614                if(type(value) == type(value0)):
00615                   myf[param] = value.tolist()
00616                else:
00617                   #print 'value:', value, 'value0:', value0
00618                   #print 'type(value):', type(value), 'type(value0):', type(value0)
00619                   myf[param] = value0
00620                   if type(value0) != list :
00621                      matchtype = True
00622             else :
00623                myf[param] = value
00624             value = myf['cu'].verifyparam({param:value})
00625             if matchtype:
00626                value = False
00627       except Exception, instance:
00628          #ignore the exception and just return it unchecked
00629          myf[param] = value
00630       return value
00631 #
00632 #
00633     def description(self, key='mosaic', subkey=None):
00634         desc={'mosaic': 'Create a multi-field deconvolved image with selected algorithm',
00635                'vis': 'name of input visibility file',
00636                'imagename': 'Pre-name of output images',
00637                'mode': 'Type of selection (mfs, channel, velocity, frequency)',
00638                'alg': 'Algorithm to use (clark, hogbom, multiscale) ',
00639                'imsize': 'Image size in pixels (nx,ny), symmetric for single value',
00640                'cell': 'The image cell size in arcseconds [x,y]. ',
00641                'phasecenter': 'Field Identififier or direction of the image phase center',
00642                'stokes': 'Stokes params to image (I,IV,QU,IQUV,RR,LL,XX,YY,RRLL,XXYY)',
00643                'niter': 'Maximum number of iterations',
00644                'gain': 'Loop gain for cleaning',
00645                'threshold': 'Flux level to stop cleaning (unit mJy assumed)',
00646                'mask': 'Set of mask images used in cleaning',
00647                'cleanbox': 'clean box regions or file name or \'interactive\'',
00648                'nchan': 'Number of channels in output image',
00649                'start': 'Start channel',
00650                'width': 'Channel width (value > 1 indicates channel averaging)',
00651                'field': 'Field Name',
00652                'spw': 'Spectral windows:channels: \'\' is all ',
00653                'timerange': 'Range of time to select from data',
00654                'restfreq': 'rest frequency to use in image',
00655                'sdimage': 'Input single dish image to use for model',
00656                'modelimage': 'Name of output(/input) model image',
00657                'weighting': 'Weighting to apply to visibilities',
00658                'mosweight': 'Individually weight the fields of the mosaic',
00659                'rmode': 'Robustness mode (for Briggs weightting)',
00660                'robust': 'Briggs robustness parameter',
00661                'ftmachine': 'Gridding method for the image',
00662                'cyclefactor': 'Threshold for minor/major cycles (see pdoc)',
00663                'cyclespeedup': 'Cycle threshold doubles in this number of iterations',
00664                'scaletype': 'Controls scaling of pixels in the image plane',
00665                'minpb': 'Minimum PB level to use',
00666                'sigma': 'Target image sigma',
00667                'targetflux': 'Target flux for final image',
00668                'constrainflux': 'Constrain image to match target flux ',
00669                'prior': 'Name of MEM prior images',
00670                'negcomponent': 'Stop the component search when the largest scale has found this number of negative components',
00671                'scales': 'resolutions in pixel units',
00672                'npercycle': 'Number of iterations before interactive masking prompt',
00673                'npixels': 'number of pixels to determine cell size for superuniform or briggs weighting',
00674                'noise': 'noise parameter for briggs weighting when rmode=\'abs\'',
00675 
00676                'async': 'If true the taskname must be started using mosaic(...)'
00677               }
00678 
00679 #
00680 # Set subfields defaults if needed
00681 #
00682         if(subkey == 'channel'):
00683           desc['start'] = 'first channel in image relative to data channels'
00684         if(subkey == 'velocity'):
00685           desc['start'] = 'Velocity of first image channel: e.g \'0.0km/s\''
00686         if(subkey == 'velocity'):
00687           desc['width'] = 'image channel width in velocity units: e.g \'-1.0km/s\''
00688         if(subkey == 'frequency'):
00689           desc['start'] = 'Frequency of first image channel: e.q. \'1.4GHz\''
00690         if(subkey == 'frequency'):
00691           desc['width'] = 'Image channel width in frequency units: e.g \'1.0kHz\''
00692         if(subkey == 'briggs'):
00693           desc['npixels'] = 'number of pixels to determine uv-cell size 0=> field of view'
00694         if(subkey == 'superuniform'):
00695           desc['npixels'] = 'number of pixels to determine uv-cell size 0=> +/-3pixels'
00696 
00697         if(desc.has_key(key)) :
00698            return desc[key]
00699 
00700     def itsdefault(self, paramname) :
00701         a = {}
00702         a['vis']  = ''
00703         a['imagename']  = ''
00704         a['mode']  = 'mfs'
00705         a['alg']  = 'clark'
00706         a['imsize']  = [256, 256]
00707         a['cell']  = ['1.0arcsec', '1.0arcsec']
00708         a['phasecenter']  = ''
00709         a['stokes']  = 'I'
00710         a['niter']  = 500
00711         a['gain']  = 0.1
00712         a['threshold']  = 0.0
00713         a['mask']  = ['']
00714         a['cleanbox']  = {}
00715         a['nchan']  = 1
00716         a['start']  = 0
00717         a['width']  = 1
00718         a['field']  = ''
00719         a['spw']  = ''
00720         a['timerange']  = ''
00721         a['restfreq']  = ''
00722         a['sdimage']  = ''
00723         a['modelimage']  = ''
00724         a['weighting']  = 'natural'
00725         a['mosweight']  = False
00726         a['rmode']  = 'norm'
00727         a['robust']  = 0.0
00728         a['ftmachine']  = 'mosaic'
00729         a['cyclefactor']  = 1.5
00730         a['cyclespeedup']  = -1
00731         a['scaletype']  = 'SAULT'
00732         a['minpb']  = 0.1
00733         a['sigma']  = '0.001Jy'
00734         a['targetflux']  = '1.0Jy'
00735         a['constrainflux']  = False
00736         a['prior']  = ['']
00737         a['negcomponent']  = 2
00738         a['scales']  = [0, 3, 10]
00739         a['npercycle']  = 100
00740         a['npixels']  = 0
00741         a['noise']  = '0.0Jy'
00742 
00743         #a = sys._getframe(len(inspect.stack())-1).f_globals
00744 
00745         if self.parameters['mode']  == 'channel':
00746             a['nchan'] = 1
00747             a['start'] = 0
00748             a['width'] = 1
00749 
00750         if self.parameters['mode']  == 'velocity':
00751             a['nchan'] = 1
00752             a['start'] = '0.0km/s'
00753             a['width'] = '1km/s'
00754 
00755         if self.parameters['mode']  == 'frequency':
00756             a['nchan'] = 1
00757             a['start'] = '1.4GHz'
00758             a['width'] = '10kHz'
00759 
00760         if self.parameters['alg']  == 'multiscale':
00761             a['scales'] = [0, 3, 10]
00762             a['negcomponent'] = 2
00763 
00764         if self.parameters['alg']  == 'entropy':
00765             a['sigma'] = 0.01
00766             a['targetflux'] = 1.0
00767             a['constrainflux'] = False
00768             a['prior'] = ['']
00769 
00770         if self.parameters['weighting']  == 'briggs':
00771             a['rmode'] = 'none'
00772             a['robust'] = 0.0
00773             a['noise'] = 0.0
00774             a['npixels'] = 0
00775 
00776         if self.parameters['weighting']  == 'superuniform':
00777             a['npixels'] = 0
00778 
00779         if self.parameters['cleanbox']  == 'interactive':
00780             a['npercycle'] = 100
00781 
00782         if a.has_key(paramname) :
00783               return a[paramname]
00784 mosaic_cli = mosaic_cli_()