Writing Tasks in CASA

How to create your own CASA tasks


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



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 <element> and ends with </element>. If an XML element contains no other XML element you may specify it via <element/>. 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. <element myattribute="attribute value">.

All task xml files must start with this header information.


<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" ?>
<casaxml xmlns="http://casa.nrao.edu/schema/psetTypes.html"

and the file must have the end tag


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


      type required, allowed value is "function"
      name required
   - required by <task>; A short one-line description describing your task
   - required] by <task>, Also used by <param>; A longer description describing your task with multiple lines
   - optional element used by <task>; An input block specifies which parameters are used for input
     <param> - optional
<output> - optional
   An output element that contains a list of parameters that are "returned" by the task.
     <param> - optional
<returns> - optional
   Value returned by the task
       optional; as specified in <param>
     <description> - optional
<constraints> - optional
   A constraints element that lets you constrain params based on the values of other params.
<when> - required.
<param> - optional
     The input and output elements consist of param elements.
     - required; allowed values are record, variant, string int, double, bool, intArray, doubleArray, boolArray, stringArray
     - required;
     - optional; allowed values True, False, Yes or No.
     - optional;
     - optional; allowed values True, False, Yes or No.
     All param elements require name and type attributes.
<description> - required;
<value> - optional;
<allowed> - optional;
<value> - optional
     Value returned by the task
     - required; as specified in <param> attributes.
     - optional
     - optional; Block of allowed values
     - 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.
     - optional
<when> - optional
     When blocks allow value specific handling for parameters
     - required; Specifies special handling for a <param>
     - optional
<notequals> - optional
<equals> - optional
     Reset parameters if equal to the specified value
     - required; the value of the parameter
     - required
<notequals> - optional
    Reset specified parameters if not equal to the specified value
     - required; The value of the parameter
<default> - optional
<default> - optional
     Resets default values for specified parameters
     - required; Name of the <param> to be reset.
     - required, the revised value of the <param>.
     <example> - optional
     An example block, typically in python
    lang optional; specifies the language of the example, defaults to python.



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.


<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" ?>
<casaxml xmlns="http://casa.nrao.edu/schema/psetTypes.html"

<!-- This is the param set for clean -->
<!-- This does the equivalent of -->
<!-- imgr:=imager('anyfile.ms'); -->
<!-- imgr.setdata(mode='channel',nchan=100,start=1,step=1,fieldid=1) -->
<!-- imgr.setimage(nx=512,ny=,cellx='1arcsec',celly='1arcsec',stokes='I',-->
<!--               mode='channel',start=35,step=1,nchan=40, -->
<!--               fieldid=[1]) -->
<!-- imgr.weight('natural'); -->
<!-- imgr.clean(algorithm='csclean',niter=500,model='field1') -->

<task type="function" name="clean">

  <shortdescription>Deconvolve an image with selected algorithm</shortdescription>

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


    <param type="string" name="vis" kind="ms" mustexist="true">
    <description>name of input visibility file</description>

    <param type="string" name="imagename">
            <description>Pre-name of output images</description>

    <param type="string" name="field">
      <description>Field Name</description>

    <param type="any" name="spw">
            <description>Spectral windows:channels: \'\' is all </description>
            <any type="variant"/>
            <value type="string"></value>
    <param type="bool" name="selectdata">
            <description>Other data selection parameters</description>
    <param type="string" name="timerange" subparam="true">
            <description>Range of time to select from data</description>
    <param type="string" name="uvrange" subparam="true">
            <description>Select data within uvrange </description>
    <param type="string" name="antenna" subparam="true">
            <description>Select data based on antenna/baseline</description>
    <param type="string" name="scan" subparam="true">
            <description>scan number range</description>

    <param type="string" name="mode">
               Type of selection (mfs, channel, velocity, frequency)
            <allowed kind="enum">


    <param type="int" name="niter">
    <description>Maximum number of iterations</description>

    <param type="double" name="gain">
            <description>Loop gain for cleaning</description>

    <param type="double" name="threshold" units="mJy">
            <description>Flux level to stop cleaning.  Must include units</description>

<!-- Getting rid of this
    <param type="bool" name="csclean">
      <description>Use Cotton-Schwab style reconciliation with UV-data</description>

    <param type="string" name="psfmode">
            <description>method of PSF calculation to use during minor cycles</description>
            <allowed kind="enum">

    <param type="string" name="imagermode">
      <description> Use csclean or mosaic.  If \'\', use psfmode</description>
      <allowed kind="enum">

    <param type="string" name="ftmachine" subparam="true">
            <description>Gridding method for the image</description>
            <allowed kind="enum">
    <param type="bool" name="mosweight" subparam="true">
      <description>Individually weight the fields of the mosaic</description>
    <param type="string" name="scaletype" subparam="true">
      <description>Controls scaling of pixels in the image plane. 
          example: scaletype=\'PBCOR\' Options: \'PBCOR\',\'SAULT\'</description>
      <allowed kind="enum">

    <param type="intArray" name="multiscale">
      <description>set deconvolution scales (pixels), 
        default: multiscale=[] (standard CLEAN)</description>
      <value type="vector">

    <param type="int" name="negcomponent" subparam="true">
         Stop cleaning if the largest scale finds this number of neg components

    <param type="bool" name="interactive">
            <description>use interactive clean (with GUI viewer)</description>

    <param type="any" name="mask">
            <description>cleanbox(es), mask image(s), and/or region(s)  used in cleaning
            <any type="variant"/>
            <value type="stringArray"></value>

    <param type="int" name="nchan" subparam="true">
            <description>Number of channels (planes) in output image</description>

    <param type="any" name="start" subparam="true">
            <description>First channel in input to use</description>
            <any type="variant"/>
            <value type="int">0</value>

    <param type="any" name="width" subparam="true">
            <description>Number of input channels to average</description>
            <any type="variant"/>
            <value type="int">1</value>

    <param type="intArray" name="imsize">
            <description>x and y image size in pixels, symmetric for single value
            <value type="vector">

    <param type="doubleArray" name="cell" units="arcsec">
    <description>x and y cell size. default unit arcsec</description>
    <value type="vector"><value>1.0</value><value>1.0</value></value>

    <param type="any" name="phasecenter">
            <description>Image phase center: position or field index</description>
            <any type="variant"/>
            <value type="string"></value>

    <param type="string" name="restfreq">
            <description>rest frequency to assign to image (see help)</description>

    <param type="string" name="stokes">
            <description>Stokes params to image (eg I,IV, QU,IQUV)</description>
    <allowed kind="enum">



    <param type="string" name="weighting">
    <description>Weighting to apply to visibilities</description>
    <allowed kind="enum">

    <param type="double" name="robust" subparam='true'>
            <description>Briggs robustness parameter</description>
            <allowed kind="range">
            <value range="min">-2.0</value>
            <value range="max">2.0</value>

    <param type="bool" name="uvtaper">
            <description>Apply additional uv tapering of  visibilities.</description>

    <param type="stringArray" name="outertaper" subparam="true">
            <description>uv-taper on outer baselines in uv-plane</description>
            <value type="vector">

    <param type="stringArray" name="innertaper" subparam="true">
            <description>uv-taper in center of uv-plane</description>

    <param type="string" name="modelimage">
            <description>Name of model image(s) to initialize cleaning</description>
    <param type="stringArray" name="restoringbeam">
      <description>Output Gaussian restoring beam for CLEAN image</description>
    <param type="bool" name="pbcor">
            <description>Output primary beam-corrected image</description>

    <param type="double" name="minpb">
            <description>Minimum PB level to use</description>

    <param type="any" name="noise"  subparam='true'>
            <description>noise parameter for briggs abs mode weighting</description>
            <any type="variant"/>
            <value type="string">1.0Jy</value>      

    <param type="int" name="npixels" subparam='true'>
            <description>number of pixels for superuniform or briggs weighting

    <param type="int" name="npercycle" subparam='true'>
            <description>Number of iterations before interactive prompt</description>
    <param type="double" name="cyclefactor" subparam='true'>
      <description>change depth in between of  csclean cycle</description>
    <param type="int" name="cyclespeedup" subparam='true'>
            <description>Cycle threshold doubles in this number of iteration</description>


            <when param="selectdata">
                  <equals type="bool" value="False"/>
                  <equals type="bool" value="True">
                    <default param="timerange"><value type="string"></value>
                    <default param="uvrange"><value type="string"></value>
                    <default param="antenna"><value type="string"></value>
                    <default param="scan"><value type="string"></value>
            <when param="multiscale">
                  <notequals type="vector" value="[]" > 
                    <default param="negcomponent"><value>-1</value>
            <when param="mode">
                <equals value="mfs"/>
                <equals value="channel">
                        <default param="nchan"><value>1</value></default>
                        <default param="start"><value>0</value>
                            <description>first input channel to use</description>
                        <default param="width"><value>1</value></default>
                <equals value="velocity">
                        <default param="nchan"><value>1</value></default>
                        <default param="start"><value type="string">0.0km/s</value>
                            <description>Velocity of first image channel: e.g. \'0.0km/s\'
                    <default param="width"><value type="string">1km/s</value>
                            <description>image channel width in velocity units: 
                               e.g. \'-1.0km/s\'</description>
                <equals value="frequency">
                        <default param="nchan"><value>1</value></default>
                        <default param="start"><value type="string">1.4GHz</value>
                            <description>Frequency of first image channel: e.q. \'1.4GHz\'
                    <default param="width"><value type="string">10kHz</value>
                            <description>Image channel width in frequency units:
                                e.g. \'1.0kHz\'</description>
            <when param="weighting">
                <equals value="natural"/>
                <equals value="uniform"/>
                <equals value="briggs">
                        <default param="robust"><value>0.0</value></default>
                        <default param="npixels"><value>0</value>
                            <description>number of pixels to determine uv-cell size
                                 0=&gt; field of view</description>
                <equals value="briggsabs">
                        <default param="robust"><value>0.0</value></default>
                        <default param="noise"><value type="string">1.0Jy</value></default>
                        <default param="npixels"><value>0</value>
                            <description>number of pixels to determine uv-cell size
                                 0=&gt; field of view</description>
                <equals value="superuniform">
                        <default param="npixels"><value>0</value>
                            <description>number of pixels to determine uv-cell size
                                 0=&gt; +/-3pixels</description>
            <when param="uvtaper">
                <equals type="bool" value="False"/>
                <equals type="bool" value="True">
                        <default param="outertaper"><value type="vector"></value></default>
                        <default param="innertaper"><value type="vector"></value></default>
            <when param="interactive">
                <equals type="bool" value="False"/>
                <equals type="bool" value="True">
                      <default param="npercycle"><value>100</value></default>
            <when param="imagermode">
                <equals value=""/>
                <equals value="csclean">
                        <default param="cyclefactor"><value>1.5</value></default>
                        <default param="cyclespeedup"><value>-1</value></default>
                <equals value="mosaic">
                        <default param="mosweight"><value>False</value></default>
                        <default param="ftmachine"><value type="string">mosaic</value>
                        <default param="scaletype"><value type="string">SAULT</value>
                        <default param="cyclefactor"><value>1.5</value></default>
                        <default param="cyclespeedup"><value>-1</value></default>
<!--Get rid of that soon
            <when param="mosaicmode">
                <equals type="bool" value="False"/>
                <equals type="bool" value="True">
                        <default param="mosweight"><value>False</value></default>
                        <default param="ftmachine"><value type="string">mosaic</value></default>
                        <default param="scaletype"><value type="string">SAULT</value></default>


  <returns type="void"/>


       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='&lt;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 
                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
  &gt;&gt;&gt; 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='&gt;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='&gt;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&amp;6'; baseline between antenna index 5 and 
                                 index 6.
                  antenna='VA05&amp;VA06'; baseline between VLA antenna 5 
                                       and 6.
                  antenna='5&amp;6;7&amp;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 
       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 
                 mode = 'frequency', means channels are specified in 
  &gt;&gt;&gt; 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 (&gt;1 indicates channel averaging)
                 default=1; example: width=4
               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 
               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 
               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 ''  =&gt; psfmode cleaning algorithm used
  &gt;&gt;&gt; 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
                              &lt;imagename&gt;.image by the &lt;imagename&gt;.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.
  &gt;&gt;&gt; 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] 
  &gt;&gt;&gt; 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 =&gt; ['2arcsec', '2arcsec']
       phasecenter -- direction measure  or fieldid for the mosaic center
               default: '' =&gt; 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)
  &gt;&gt;&gt; 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 &lt;imagename&gt;.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' &lt;fieldid blc-x blc-y
           trc-x trc-y&gt; 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',
       uvtaper -- Apply additional uv tapering of the visibilities.
               default: uvtaper=False; example: uvtaper=True
  &gt;&gt;&gt; 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 
                 default: outertaper=[]; no outer taper applied
                 example: outertaper=['5klambda']  circular taper 
                                FWHM=5 kilo-lambda
                         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 &lt;imagename&gt;.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
       weighting -- Weighting to apply to visibilities:
               default='natural'; example: weighting='uniform';
              Options: 'natural','uniform','briggs', 
  &gt;&gt;&gt; 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" 
                   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,

        #Python script


        if((mask==[]) or (mask=='')):
        if (interactive):
                if( (mask=='') or (mask==['']) or (mask==[])):
                imset=cleanhelper(imCln, vis)
                if((len(imagename)==0) or (imagename.isspace())):
                        raise Exception, 'Cannot proceed with blank imagename'
                imset.defineimages(imsize=imsize, cell=cell, stokes=stokes,
                                   mode=mode, spw=spw, nchan=nchan,
                                   start=start,  width=width,
                                   restfreq=restfreq, field=field,
                imset.datselweightfilter(field=field, spw=spw,
                                         antenna=antenna, scan=scan,
                                         noise=noise, npixels=npixels,

                ###define clean alg
                if((type(multiscale)==list) and (len(multiscale)>0)):
                        if(alg.count('mf') <1):
                        imCln.setoptions(ftmachine=ftmachine, padding=1.0)
                ###PBCOR or not
                if((scaletype=='PBCOR') or (scaletype=='pbcor')):
                        if(imagermode != 'mosaic'):
                                ##make a pb for flux scale
                                imCln.makeimage(type='pb', image=imagename+'.flux')
                ###model image

                ####after all the mask shenanigans...make sure to use the
                ####last mask
                             cyclefactor=cyclefactor, cyclespeedup=cyclespeedup)
                            mask=maskimage, interactive=interactive, 
                if(imagename.count('/') > 0):
                result          = '\'' + newimage + '.image' + '\'';
                fluxscale_image = '\'' + newimage + '.flux'  + '\'';
                if (pbcor):
                        if(sclt != 'NONE'):
                                ##otherwise its already divided
                                pixmask = fluxscale_image+'>'+str(minpb);

                                pixels='iif('+ fluxscale_image+'>'+str(minpb)+','
                                        + result+'/'+fluxscale_image+', 0)'
                        ##  people has imaged the fluxed corrected image
                        ## but want the
                        ## final image to be non-fluxed corrected

                del imCln

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