Writing Tasks in CASA

 

ALERT: This prescription for writing and incorporating tasks in CASA is for the power-user. This procedure may also change in future releases.

The Basics

It is possible to write your own task and have it appear in CASA. For example, if you want to create a task named yourtask, then must create two files, yourtask.xml and a task_yourtask.py. The .xml file is use to describe the interface to the task and the task_yourtask.py does the actual work. The argument names must be the same in both the yourtask.xml and task_yourtask.py file. The yourtask.xml file is used to generate all the interface files so yourtask will appear in the CASA system. It is easiest to start from one of the existing tasks when constructing these. You would make the name of the function in the yourtask.py be yourtask in this example.

We have provided the buildmytasks command in order to assemble your Python and XML into a loadable Python file. Thus, the steps you need to execute (again for an example task named “yourtask”):

  1. Create python code for task as task_yourtask.py
  2. Create xml for task as yourtask.xml
  3. Execute buildmytasks from the CASA prompt: !buildmytasks
  4. Initialize your new task inside CASA: execfile ’mytasks.py’


After this, you should see the help and inputs inside CASA, e.g. inp yourtask should work. Note that for the final step you invoke the file called mytasks.py, regardless of what you named the actual task. You now have a shiny new task yourtask that you can run and use in the same way as all other CASA tasks.

Note that if multiple custom tasks are stored in the same directory, they will all be built by !buildmytasks and will all be initialized by executing mytasks.py. To build and initialize only a single task, instead use !buildmytasks taskname; you are then free to rename mytasks.py (e.g. load_taskname.py) and repeat this procedure for your other tasks. Our recommendation, for those of you who are managing multiple custom tasks, is to have each task live in its own directory. The mytasks.py file need not be in the current working directory to initialize your task, since you can provide the full path upon initialization

#Example
execfile(’/full_path_to_my_task/mytasks.py’)

 

The XML file

 The key to getting your task into CASA is constructing a task interface description XML file.

Some XML basics, an xml element begins with and ends with . If an XML element contains no other XML element you may specify it via . An XML element may have zero or more attributes which are specified by attribute="attribute value". You must put the attribute value in quotes, i.e. .

All task xml files must start with this header information.

 




xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://casa.nrao.edu/schema/casa.xsd
file:///opt/casa/code/xmlcasa/xml/casa.xsd">

and the file must have the end tag


Inside a tags you will need to specify the following elements.

 


  Attributes
      type required, allowed value is "function"
      name required
  Subelements
    shortdescription
      required
    description
      required
    input
      optional
    output
      optional
    returns
      optional
    constraints
     optional

   - required by ; A short one-line description describing your task
  Attributes
     None
  Subelements
     None

   - required] by , Also used by ; A longer description describing your task with multiple lines
  Attributes
     None
  Subelements
     None

   - optional element used by ; An input block specifies which parameters are used for input
  Attributes
     None
  Subelements
      - optional
- optional
   An output element that contains a list of parameters that are "returned" by the task.
  Attributes
     None
  Subelements
      - optional
- optional
   Value returned by the task
  Attributes
     type
       optional; as specified in
  Subelements
      - optional
- optional
   A constraints element that lets you constrain params based on the values of other params.
  Attributes
     None
  Subelements
 - required.
- optional
     The input and output elements consist of param elements.
  Attributes
     type
     - required; allowed values are record, variant, string int, double, bool, intArray, doubleArray, boolArray, stringArray
  name
     - required;
  subparam
     - optional; allowed values True, False, Yes or No.
  kind
     - optional;
  mustexist
     - optional; allowed values True, False, Yes or No.
     All param elements require name and type attributes.
  Subelements
 - required;
- optional;
- optional;
- optional
     Value returned by the task
  Attributes
     type
     - required; as specified in attributes.
  Subelements
     
     - optional

     - optional; Block of allowed values
  Attributes
     enum
     - required; maybe enum or range. If specified as enum only specific values are allowed If specified as range then the value tags may have min and max attributes.
  Subelements
     
     - optional
- optional
     When blocks allow value specific handling for parameters
  Attributes
     param
     - required; Specifies special handling for a
  Subelements
     
     - optional
- optional
- optional
     Reset parameters if equal to the specified value
  Attributes
     value
     - required; the value of the parameter
  Subelements
     
     - required
- optional
    Reset specified parameters if not equal to the specified value
  Attributes
     value
     - required; The value of the parameter
  Subelements
- optional
- optional
     Resets default values for specified parameters
  Attributes
     param
     - required; Name of the to be reset.
  Subelements
     
     - required, the revised value of the .
      - optional
     An example block, typically in python
  Attributes
    lang optional; specifies the language of the example, defaults to python.
  Subelements
    None
 

 

 

The task yourtask.py file

You must write the python code that does the actual work. The task_*.py file function call sequence must be the same as specified in the XML file. We may relax the requirement that the function call sequence exactly match the sequence in the XML file in a future release.

The task_*.py file should contain the following preamble

import os
from taskinit import *


plus any other global function imports you will need such as

import time


followed by the task function def. See below for an example.

 

Example: The clean task

 Note that the following is for illustration only and does not reflect the current implementation of clean – a task that is always developing further on a quick pace.

File clean.xml

Clean.xml gives a fairly comprehensive example of how to construct the XML file.

 


















  Deconvolve an image with selected algorithm

  
  Form images from visibilities. Handles continuum and spectral line cubes.
  

  

    
    name of input visibility file
    
    

    
            Pre-name of output images
            
    

    
      Field Name
      
    

    
            Spectral windows:channels: \'\' is all 
            
            
    
    
            Other data selection parameters
            False
    
    
    
            Range of time to select from data
            
    
    
            Select data within uvrange 
            
    
    
            Select data based on antenna/baseline
            
    
    
            scan number range
            
    
    

    
            
               Type of selection (mfs, channel, velocity, frequency)
            
            mfs
            
            mfs
            channel
            velocity
            frequency
    
    

    

    
    Maximum number of iterations
    500
    

    
            Loop gain for cleaning
            0.1
    

    
            Flux level to stop cleaning.  Must include units
            0.0
    



    
            method of PSF calculation to use during minor cycles
            clark
            
              clark
              hogbom
            
    

    
       Use csclean or mosaic.  If \'\', use psfmode
      
      
              
              csclean
              mosaic
      


    
    
            Gridding method for the image
            mosaic
            
              mosaic
              ft
              sd
              both
            
            
    
    
      Individually weight the fields of the mosaic
      False
    
    
      Controls scaling of pixels in the image plane. 
          default=\'SAULT\'; 
          example: scaletype=\'PBCOR\' Options: \'PBCOR\',\'SAULT\'
      SAULT
      
        SAULT
        PBCOR
      
    
    

    
      set deconvolution scales (pixels), 
        default: multiscale=[] (standard CLEAN)
      
        
      

    
    
      
         Stop cleaning if the largest scale finds this number of neg components
      
      0
    


    
            use interactive clean (with GUI viewer)
            False
    

    
            cleanbox(es), mask image(s), and/or region(s)  used in cleaning
            
            
            
    


    
            Number of channels (planes) in output image
            1
    

    
            First channel in input to use
            
            0
    

    
            Number of input channels to average
            
            1
    


    
            x and y image size in pixels, symmetric for single value
            
            
    256256
            
    

    
    x and y cell size. default unit arcsec
    1.01.0
    

    
            Image phase center: position or field index
            
            
    

    
            rest frequency to assign to image (see help)
            
    

    
            Stokes params to image (eg I,IV, QU,IQUV)
            I
    
            I
            IV
            QU
            IQUV
            RR
            LL
            RRLL
            XX
            YY
            XXYY
    
    

    

    

    
    Weighting to apply to visibilities
    natural
    
            natural
            uniform
            briggs
            briggsabs
            radial
            superuniform
    
    


    
            Briggs robustness parameter
            0.0
            
            -2.0
            2.0
    
    

    
            Apply additional uv tapering of  visibilities.
            False
    

    
            uv-taper on outer baselines in uv-plane
            
              
            
    

    
            uv-taper in center of uv-plane
            1.0
    

    
            Name of model image(s) to initialize cleaning
            
    
    
      Output Gaussian restoring beam for CLEAN image
      
    
    
            Output primary beam-corrected image
            False
    

    
            Minimum PB level to use
            0.1
    


    
            noise parameter for briggs abs mode weighting
            
            1.0Jy      
    

    
            number of pixels for superuniform or briggs weighting
            
            0
    



    
            Number of iterations before interactive prompt
            100
    
    
      change depth in between of  csclean cycle
      1.5
    
    
            Cycle threshold doubles in this number of iteration
            -1
    
    

    

    
            
                  
                  
                    
                    
                    
                    
                    
                    
                    
                    
                
            
            
                   
                    -1
                    
                
            
            
                
                
                        1
                        0
                            first input channel to use
                        
                        1
                
                
                        1
                        0.0km/s
                            Velocity of first image channel: e.g. \'0.0km/s\'
                            
                    
                    1km/s
                            image channel width in velocity units: 
                               e.g. \'-1.0km/s\'
                    
                
                
                        1
                        1.4GHz
                            Frequency of first image channel: e.q. \'1.4GHz\'
                            
                    
                    10kHz
                            Image channel width in frequency units:
                                e.g. \'1.0kHz\'
                    
                
            
            
            
                
                
                
                        0.0
                        0
                            number of pixels to determine uv-cell size
                                 0=> field of view
                    
                
                
                        0.0
                        1.0Jy
                        0
                            number of pixels to determine uv-cell size
                                 0=> field of view
                    
                
                
                        0
                            number of pixels to determine uv-cell size
                                 0=> +/-3pixels
                    
                
            
            
                
                
                        
                        
                
            
            
                
                
                      100
                
            
            
                
                
                        1.5
                        -1
                
                
                        False
                        mosaic
                                
                        SAULT
                                
                        1.5
                        -1
                
            

    

    

  

  

       The main clean deconvolution task.  It contains many functions
 
        1)  Make 'dirty' image and 'dirty' beam (psf)
        2)  Multi-frequency-continuum images or spectral channel imaging
        3)  Full Stokes imaging
        4)  Mosaicking of several pointings
        5)  Multi-scale cleaning
        6)  Interactive clean boxing
        7)  Initial starting model
 
 
       vis -- Name of input visibility file
               default: none; example: vis='ngc5921.ms'
       imagename -- Pre-name of output images:
               default: none; example: imagename='m2'
               output images are:
                 m2.image; cleaned and restored image
                        With or without primary beam correction
                 m2.psf; point-spread function (dirty beam)
                 m2.flux;  relative sky sensitivity over field
                 m2.model; image of clean components
                 m2.residual; image of residuals
                 m2.interactive.mask; image containing clean regions
       field -- Select fields in mosaic.  Use field id(s) or field name(s).
                  ['go listobs' to obtain the list id's or names]
              default: ''=all fields
              If field string is a non-negative integer, it is assumed to
                  be a field index otherwise, it is assumed to be a 
                  field name
              field='0~2'; field ids 0,1,2
              field='0,4,5~7'; field ids 0,4,5,6,7
              field='3C286,3C295'; field named 3C286 and 3C295
              field = '3,4C*'; field id 3, all names starting with 4C
       spw -- Select spectral window/channels
              NOTE: This selects the data passed as the INPUT to mode
              default: ''=all spectral windows and channels
                spw='0~2,4'; spectral windows 0,1,2,4 (all channels)
                spw='0:5~61'; spw 0, channels 5 to 61
                spw='<2';   spectral windows less than 2 (i.e. 0,1)
                spw='0,10,3:3~45'; spw 0,10 all channels, spw 3, 
                                   channels 3 to 45.
                spw='0~2:2~6'; spw 0,1,2 with channels 2 through 6 in each.
                spw='0:0~10;15~60'; spectral window 0 with channels 
                                    0-10,15-60
                spw='0:0~10,1:20~30,2:1;2;3'; spw 0, channels 0-10,
                      spw 1, channels 20-30, and spw 2, channels, 1,2 and 3
       selectdata -- Other data selection parameters
              default: True
  >>> selectdata=True expandable parameters
              timerange  -- Select data based on time range:
                 default = '' (all); examples,
                  timerange = 'YYYY/MM/DD/hh:mm:ss~YYYY/MM/DD/hh:mm:ss'
                  Note: if YYYY/MM/DD is missing date defaults to first 
                        day in data set
                  timerange='09:14:0~09:54:0' picks 40 min on first day
                  timerange= '25:00:00~27:30:00' picks 1 hr to 3 hr 
                             30min on NEXT day
                  timerange='09:44:00' pick data within one integration 
                             of time
                  timerange='>10:24:00' data after this time
              uvrange -- Select data within uvrange (default units meters)
                  default: '' (all); example:
                  uvrange='0~1000klambda'; uvrange from 0-1000 kilo-lambda
                  uvrange='>4klambda';uvranges greater than 4 kilo lambda
              antenna -- Select data based on antenna/baseline
                  default: '' (all)
                  If antenna string is a non-negative integer, it is 
                    assumed to be an antenna index, otherwise, it is
                    considered an antenna name.
                  antenna='5&6'; baseline between antenna index 5 and 
                                 index 6.
                  antenna='VA05&VA06'; baseline between VLA antenna 5 
                                       and 6.
                  antenna='5&6;7&8'; baselines 5-6 and 7-8
                  antenna='5'; all baselines with antenna index 5
                  antenna='05'; all baselines with antenna number 05 
                                (VLA old name)
                  antenna='5,6,9'; all baselines with antennas 5,6,9 
                                   index numbers
              scan -- Scan number range.
                  default: '' (all)
                  example: scan='1~5'
                  Check 'go listobs' to insure the scan numbers are in 
                        order.
       mode -- Frequency Specification:
               NOTE: See examples below:
               default: 'mfs'
                 mode = 'mfs' means produce one image from all 
                      specified data.
                 mode = 'channel'; Use with nchan, start, width to specify
                         output image cube.  See examples below
                 mode = 'velocity', means channels are specified in 
                      velocity.
                 mode = 'frequency', means channels are specified in 
                      frequency.
  >>> mode expandable parameters (for modes other than 'mfs')
               Start, width are given in units of channels, frequency 
                  or velocity as indicated by mode, but only channel
                  is complete.
               nchan -- Number of channels (planes) in output image
                 default: 1; example: nchan=3
               start -- Start input channel (relative-0)
                 default=0; example: start=5
               width -- Output channel width in units of the input
                     channel width (>1 indicates channel averaging)
                 default=1; example: width=4
           examples:
               spw = '0,1'; mode = 'mfs'
                  will produce one image made from all channels in spw 
                       0 and 1
               spw='0:5~28^2'; mode = 'mfs'
                  will produce one image made with channels 
                       (5,7,9,...,25,27)
               spw = '0'; mode = 'channel': nchan=3; start=5; width=4
                  will produce an image with 3 output planes
                  plane 1 contains data from channels (5+6+7+8)
                  plane 2 contains data from channels (9+10+11+12)
                  plane 3 contains data from channels (13+14+15+16)
               spw = '0:0~63^3'; mode='channel'; nchan=21; start = 0; 
                   width = 1
                  will produce an image with 20 output planes
                  Plane 1 contains data from channel 0
                  Plane 2 contains date from channel 2
                  Plane 21 contains data from channel 61
               spw = '0:0~40^2'; mode = 'channel'; nchan = 3; start = 
                   5; width = 4
                  will produce an image with three output planes
                  plane 1 contains channels (5,7)
                  plane 2 contains channels (13,15)
                  plane 3 contains channels (21,23)
       psfmode -- method of PSF calculation to use during minor cycles:
               default: 'clark': Options: 'clark','hogbom'
               'clark'  use smaller beam (faster, usually good enough)
               'hogbom' full-width of image (slower, better for poor 
               uv-coverage)
               Note:  psfmode will be used to clean is imagermode = ''
       imagermode -- Advanced imaging e.g. mosaic or Cotton-Schwab clean
               default: imagermode='': Options: '', 'csclean', 'mosaic'
               default ''  => psfmode cleaning algorithm used
  >>> imagermode='mosaic' expandable parameter(s):
         Image as a mosaic of the different pointings (uses csclean 
         style too)
               mosweight -- Individually weight the fields of the mosaic
                       default: False; example: mosweight=True
                       This can be useful if some of your fields are more
                       sensitive than others (i.e. due to time spent 
                       on-source); this parameter will give more weight to 
                       higher sensitivity fields in the overlap regions.
               ftmachine -- Gridding method for the image;
                       Options: ft (standard interferometric gridding), sd
                       (standard single dish) both (ft and sd as appropriate),
                       mosaic (gridding use PB as convolution function)
                       default: 'mosaic'; example: ftmachine='ft'
               scaletype -- Controls scaling of pixels in the image plane.
                       (Not fully implemented...for now only controls 
                       what is seen if interactive=True...but in the future will 
                       control the image on which clean components are searched)
                       default='SAULT'; example: scaletype='PBCOR'
                       Options: 'PBCOR','SAULT'
                       'SAULT' when interactive=True shows the residual
                              with constant noise across the mosaic. If
                              pbcor=False, the final output image is NOT
                              corrected for the PB pattern, and therefore is
                              not "flux correct". Division of SAULT
                              <imagename>.image by the <imagename>.flux image
                              will produce a "flux correct image", can also
                              be achieved by setting pbcor=True.
                       'PBCOR' uses the SAULT scaling scheme for
                              deconvolution, but if interactive=True shows the
                              primary beam corrected image; the final PBCOR
                              image is "flux correct" if pbcor=True.
  >>> imagermode='csclean' expandable parameter(s): Image using the
            Cotton-Schwab algorithm in between major cycles
            cyclefactor -- Change the threshold at which
                          the deconvolution cycle will stop, degrid
                          and subtract from the visibilities.  For
                          poor PSFs, reconcile often (cyclefactor=4 or
                          5); For good PSFs, use cyclefactor 1.5 to
                          2.0. Note: threshold = cyclefactor * max
                          sidelobe * max residual.
                          default: 1.5; example: cyclefactor=4
            cyclespeedup -- Cycle threshold doubles in this
                          number of iterations default: -1;
                          example: cyclespeedup=3
                          try cyclespeedup = 50 to speed up cleaning 
       multiscale -- set of scales to use in deconvolution.  If set,
               cleans with several resolutions using hobgom clean. The
               scale sizes are in units of cellsize.  So if
               cell='2arcsec', a multiscale scale=10 = 20arcsec.  First
               scale should always be 0 (point), we suggest second on
               the order of synthesized beam, third 3-5 times
               synthesized beam, etc. For example if synthesized beam
               is 10" and cell=2", try multscale = [0,5,15]. Note,
               multiscale is currently a bit slow.
              default: multiscale=[] (standard CLEAN using psfmode algorithm,
               no multi-scale). Example:  multscale = [0,5,15] 
  >>> multiscale expandable parameter(s): negcomponent -- Stop
               component search when the largest scale has found this
               number of negative components; -1 means continue
               component search even if the largest component is
               negative.  default: -1; example: negcomponent=50
       imsize -- Image pixel size (x,y)
               default = [256,256]; example: imsize=[350,350]
               imsize = 500 is equivalent to [500,500]
       cell -- Cell size (x,y)
               default= '1.0arcsec';
               example: cell=['0.5arcsec,'0.5arcsec'] or
               cell=['1arcmin', '1arcmin']
               cell = '1arcsec' is equivalent to ['1arcsec','1arcsec']
               NOTE:cell = 2.0 => ['2arcsec', '2arcsec']
       phasecenter -- direction measure  or fieldid for the mosaic center
               default: '' => first field selected ; example: phasecenter=6
               or phasecenter='J2000 19h30m00 -40d00m00'
       restfreq -- Specify rest frequency to use for output image
               default='' Occasionally it is necessary to set this (for
               example some VLA spectral line data).  For example for
               NH_3 (1,1) put restfreq='23.694496GHz'
       stokes -- Stokes parameters to image
               default='I'; example: stokes='IQUV';
               Options: 'I','IV''QU','IQUV','RR','LL','XX','YY','RRLL','XXYY'
       niter -- Maximum number iterations,
               if niter=0, then no CLEANing is done ("invert" only)
               default: 500; example: niter=5000
       gain -- Loop gain for CLEANing
               default: 0.1; example: gain=0.5
       threshold -- Flux level at which to stop CLEANing
               default: '0.0mJy'; 
               example: threshold='2.3mJy'  (always include units)
                        threshold = '0.0023Jy'
                        threshold = '0.0023Jy/beam' (okay also)
       interactive -- use interactive clean (with GUI viewer)
               default: interactive=False
               example: interactive=True
               interactive clean allows the user to build the cleaning
                    mask interactively using the viewer.  The viewer will
                    appear every npercycle iteration, but modify as needed
                    The final interactive mask is saved in the file
                    imagename_interactive.mask.  The initial masks use the
                    union of mask and cleanbox (see below)
  >>> interactive=True expandable parameter npercycle -- this is the
               number of iterations between each clean to update mask
               interactively. Set to about niter/5, but can also be
               changed interactively.
       mask -- Specification of cleanbox(es), mask image(s), and/or
           region(s) to be used for CLEANing. As long as the image has
           the same shape (size), mask images from a previous
           interactive session can be used for a new execution. NOTE:
           the initial clean mask actually used is the union of what
           is specified in mask and <imagename>.mask default: [] (no
           masking); Possible specification types: (a) Explicit
           cleanbox pixel ranges example: mask=[110,110,150,145] clean
           region with blc=110,100; trc=150,145 (pixel values) (b)
           Filename with cleanbox pixel values with ascii format:
           example: mask='mycleanbox.txt' <fieldid blc-x blc-y
           trc-x trc-y> on each line 
           1 45 66 123 124 
           2 23 100 300 340
           (c) Filename for image mask example: mask='myimage.mask'
           (d) Filename for region specification (e.g. from viewer)
           example: mask='myregion.rgn' (e) Combinations of any of the
           above example: mask=[[110,110,150,145],'mycleanbox.txt',
           'myimage.mask','myregion.rgn']
       uvtaper -- Apply additional uv tapering of the visibilities.
               default: uvtaper=False; example: uvtaper=True
  >>> uvtaper=True expandable parameters
               outertaper -- uv-taper on outer baselines in uv-plane
                 [bmaj, bmin, bpa] taper Gaussian scale in uv or 
                 angular units. NOTE: uv taper in (klambda) is roughly on-sky 
                 FWHM(arcsec/200)
                 default: outertaper=[]; no outer taper applied
                 example: outertaper=['5klambda']  circular taper 
                                FWHM=5 kilo-lambda
                         outertaper=['5klambda','3klambda','45.0deg']
                         outertaper=['10arcsec'] on-sky FWHM 10"
                         outertaper=['300.0'] default units are meters 
                                in aperture plane
               innertaper -- uv-taper in center of uv-plane
                 [bmaj,bmin,bpa] Gaussian scale at which taper falls to 
                 zero at uv=0
                 default: innertaper=[]; no inner taper applied
                 NOT YET IMPLEMENTED                
       modelimage -- Name of model image(s) to initialize cleaning. If
               multiple images, then these will be added together to
               form initial staring model NOTE: these are in addition
               to any initial model in the <imagename>.model image file
               default: '' (none); example: modelimage='orion.model'
               modelimage=['orion.model','sdorion.image'] Note: if the
               units in the image are Jy/beam as in a single-dish
               image, then it will be converted to Jy/pixel as in a
               model image, using the restoring beam in the image
               header
       weighting -- Weighting to apply to visibilities:
               default='natural'; example: weighting='uniform';
              Options: 'natural','uniform','briggs', 
                       'superuniform','briggsabs','radial'
  >>> Weighting expandable parameters
               For weighting='briggs' and 'briggsabs'
                 robust -- Brigg's robustness parameter
                   default=0.0; example: robust=0.5;
                   Options: -2.0 to 2.0; -2 (uniform)/+2 (natural)
              For weighting='briggsabs'
                 noise   -- noise parameter to use for Briggs "abs" 
                weighting
                   example noise='1.0mJy'
               For superuniform/briggs/briggsabs weighting
                 npixels -- number of pixels to determine uv-cell size
                   for weight calculation
                   example npixels=7
       restoringbeam -- Output Gaussian restoring beam for CLEAN image
               [bmaj, bmin, bpa] elliptical Gaussian restoring beam
               default units are in arc-seconds for bmaj,bmin, degrees
               for bpa default: restoringbeam=[]; Use PSF calculated
               from dirty beam. 
              example: restoringbeam=['10arcsec'] circular Gaussian 
                       FWHM 10" example:
                       restoringbeam=['10.0','5.0','45.0deg'] 10"x5" 
                       at 45 degrees
       pbcor -- Output primary beam-corrected image 
              default: pbcor=False; output un-corrected image 
              example: pbcor=True; output pb-corrected image (masked outside
               minpb) Note: if you set pbcor=False, you can later
               recover the pbcor image by dividing by the .flux image
               (e.g. using immath)
       minpb -- Minimum PB level to use default=0.1; example:
               minpb=0.01 Note: this minpb is always in effect
               (regardless of pbcor=True/False) 

  




 


File task_clean.py

 

Task clean implementation file.


import os
from taskinit import *
from cleanhelper import *


def clean(vis,imagename,field, spw, selectdata, timerange, uvrange, antenna, 
          scan, mode,niter, gain,threshold, psfmode, imagermode, ftmachine,
          mosweight, scaletype, multiscale, negcomponent,interactive,mask,
          nchan,start,width,imsize,cell, phasecenter, restfreq, stokes,
          weighting,robust, uvtaper,outertaper,innertaper, modelimage,
          restoringbeam,pbcor, minpb,  noise, npixels, npercycle, cyclefactor,
          cyclespeedup):

        #Python script

        casalog.origin('clean')

        maskimage=''
        if((mask==[]) or (mask=='')):
                mask=['']
        if (interactive):
                if( (mask=='') or (mask==['']) or (mask==[])):
        #try:
        if(1):
                imCln=imtool.create()
                imset=cleanhelper(imCln, vis)
                
                if((len(imagename)==0) or (imagename.isspace())):
                        raise Exception, 'Cannot proceed with blank imagename'
                casalog.origin('clean')
                
                imset.defineimages(imsize=imsize, cell=cell, stokes=stokes,
                                   mode=mode, spw=spw, nchan=nchan,
                                   start=start,  width=width,
                                   restfreq=restfreq, field=field,
                                   phasecenter=phasecenter)
                
                imset.datselweightfilter(field=field, spw=spw,
                                         timerange=timerange,
                                         uvrange=uvrange,
                                         antenna=antenna, scan=scan,
                                         wgttype=weighting,
                                         robust=robust,
                                         noise=noise, npixels=npixels,
                                         mosweight=mosweight,
                                         innertaper=innertaper,
                                         outertaper=outertaper)
                                         
                if(maskimage==''):
                        maskimage=imagename+'.mask'
                imset.makemaskimage(outputmask=maskimage,imagename=imagename,
                                    maskobject=mask)


                
                
                ###define clean alg
                alg=psfmode
                if(multiscale==[0]):
                        multiscale=[]
                if((type(multiscale)==list) and (len(multiscale)>0)):
                        alg='multiscale' 
                        imCln.setscales(scalemethod='uservector',
                                        uservector=multiscale)
                if(imagermode=='csclean'):
                        alg='mf'+alg
                if(imagermode=='mosaic'):
                        if(alg.count('mf') <1):
                                alg='mf'+alg
                        imCln.setoptions(ftmachine=ftmachine, padding=1.0)
                        imCln.setvp(dovp=True)
                ###PBCOR or not
                sclt='SAULT'
                if((scaletype=='PBCOR') or (scaletype=='pbcor')):
                        sclt='NONE'
                        imCln.setvp(dovp=True)
                else:
                        if(imagermode != 'mosaic'):
                                ##make a pb for flux scale
                                imCln.setvp(dovp=True)
                                imCln.makeimage(type='pb', image=imagename+'.flux')
                                imCln.setvp(dovp=False)
                ##restoring
                imset.setrestoringbeam(restoringbeam)
                ###model image
                imset.convertmodelimage(modelimages=modelimage,
                                        outputmodel=imagename+'.model')

                ####after all the mask shenanigans...make sure to use the
                ####last mask
                maskimage=imset.outputmask
                if((imagermode=='mosaic')):
                        imCln.setmfcontrol(stoplargenegatives=negcomponent,scaletype=sclt,
                                           minpb=minpb,cyclefactor=cyclefactor,
                                           cyclespeedup=cyclespeedup,
                                           fluxscale=[imagename+'.flux'])
                else:
                        imCln.setmfcontrol(stoplargenegatives=negcomponent,
                             cyclefactor=cyclefactor, cyclespeedup=cyclespeedup)
                        
                imCln.clean(algorithm=alg,niter=niter,gain=gain,
                            threshold=qa.quantity(threshold,'mJy'),
                            model=[imagename+'.model'],
                            residual=[imagename+'.residual'],
                            image=[imagename+'.image'], 
                            psfimage=[imagename+'.psf'], 
                            mask=maskimage, interactive=interactive, 
                            npercycle=npercycle)
                imCln.close()
                presdir=os.path.realpath('.')
                newimage=imagename
                if(imagename.count('/') > 0):
                        newimage=os.path.basename(imagename)
                        os.chdir(os.path.dirname(imagename))
                result          = '\'' + newimage + '.image' + '\'';
                fluxscale_image = '\'' + newimage + '.flux'  + '\'';
                if (pbcor):
                        if(sclt != 'NONE'):
                                ##otherwise its already divided
                                ia.open(newimage+'.image')
                                
                                pixmask = fluxscale_image+'>'+str(minpb);
                                ia.calcmask(pixmask,asdefault=True);

                                pixels='iif('+ fluxscale_image+'>'+str(minpb)+','
                                        + result+'/'+fluxscale_image+', 0)'
                                ia.calc(pixels=pixels)
                                ia.close()
                else:
                        ##  people has imaged the fluxed corrected image
                        ## but want the
                        ## final image to be non-fluxed corrected
                        if(sclt=='NONE'):
                                ia.open(newimage+'.image')
                                result=newimage+'.image'
                                fluxscale_image=newimage+'.flux'
                                pixels=result+'*'+fluxscale_image
                                ia.calc(pixels=pixels)
                                ia.close()
                os.chdir(presdir)

                
                del imCln

#       except Exception, instance:
#               print '*** Error *** ',instance
#               raise Exception, instance