Examples#

Each example is a self-calibration procedure as a recipe and as the Python script that builds the same run; a test checks that they agree. The values belong to each example’s data, not to wenuray: adapt them to yours.

ALMA#

ALMA recipe#

# Phase, then amplitude-phase self-calibration of an ALMA dataset imaged with tclean: the recipe
# form of selfcal.py, which builds the same run. The values suit this example's data; adapt them
# to yours (Wenuray's own defaults come from theory or the data, not from an instrument).
#
# wenuray validate recipe.toml
# wenuray run recipe.toml --ms target.ms --output target_selfcal --plots

ms = "target.ms"  # the calibrated target data in DATA
output = "target_selfcal"

[solve]
refant = "DA51"
minblperant = 6
minsnr = 3.0
gaintype = "T"

# tclean's own parameter names. Automasking values for long baselines:
# https://casaguides.nrao.edu/index.php/Automasking_Guide
[imager]
type = "tclean"
niter = 100
threshold = "0.1mJy"
specmode = "mfs"
deconvolver = "hogbom"
gridder = "standard"
usemask = "auto-multithresh"
sidelobethreshold = 3.0
noisethreshold = 5.0
minbeamfrac = 0.3
lownoisethreshold = 1.5
negativethreshold = 0.0
interactive = false  # true to edit the masks by hand
geometry = {imsize = 1024, cell = "0.005arcsec"}
weighting = {weighting = "briggs", robust = 0.5}

# Phases combined over spectral windows, then amplitudes and phases per spectral window, cleaned
# deeper. Each spwmap is derived from combine.
[[steps]]
type = "phase"
solint = "inf"
solve = {combine = "spw"}

[[steps]]
type = "phase"
solint = "600s"
solve = {combine = "spw"}

[[steps]]
type = "ampphase"
solint = "inf"
imaging = {threshold = "0.025mJy"}

ALMA script#

"""
Phase, then amplitude-phase self-calibration of an ALMA dataset imaged with tclean.

Usage: python selfcal.py <visfile> <output_directory> [--plot]
"""
import argparse
import logging

from casatasks import split

from wenuray.config import ImageGeometry, SolveOptions, Weighting
from wenuray.imaging import Tclean
from wenuray.selfcalibration import AmpPhasecal, GainPlotObserver, LoggingObserver, Phasecal, Selfcal


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("visfile", help="Measurement set with the calibrated data in DATA")
    parser.add_argument("output", help="Directory for the images, tables and the result record")
    parser.add_argument("--plot", action="store_true", help="Plot the gain solutions")
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_arguments()
    # Wenuray logs each self-calibration round's metrics at INFO
    logging.basicConfig(level=logging.INFO)

    # tclean's own parameter names. Automasking values for long baselines:
    # https://casaguides.nrao.edu/index.php/Automasking_Guide
    imager = Tclean(
        ImageGeometry(imsize=1024, cell="0.005arcsec"),
        Weighting("briggs", robust=0.5),
        niter=100,
        threshold="0.1mJy",
        specmode="mfs",
        deconvolver="hogbom",
        gridder="standard",
        usemask="auto-multithresh",
        sidelobethreshold=3.0,
        noisethreshold=5.0,
        minbeamfrac=0.3,
        lownoisethreshold=1.5,
        negativethreshold=0.0,
        interactive=False  # True to edit the masks by hand
    )

    # Phases combined over spectral windows, then amplitudes and phases per spectral window,
    # cleaned deeper. Each spwmap is derived from combine.
    steps = [
        Phasecal("inf", solve={"combine": "spw"}),
        Phasecal("600s", solve={"combine": "spw"}),
        AmpPhasecal("inf", imaging={"threshold": "0.025mJy"}),
    ]
    selfcal = Selfcal(
        args.visfile,
        imager,
        steps,
        solve=SolveOptions(refant="DA51", minblperant=6, minsnr=3.0, gaintype="T"),
        output=args.output,
    )
    observers = [LoggingObserver()] + ([GainPlotObserver()] if args.plot else [])
    result = selfcal.run(observers)

    # The self-calibrated data, for final imaging
    split(vis=result.ms, outputvis=args.output + "/selfcal.ms", datacolumn="corrected")

VLA#

VLA recipe#

# Phase, then amplitude-phase self-calibration of a VLA dataset imaged with tclean: the recipe
# form of selfcal.py, which builds the same run. The values suit this example's data; adapt them
# to yours.
#
# wenuray run recipe.toml --ms target.ms --output target_selfcal

ms = "target.ms"
output = "target_selfcal"

[solve]
refant = "VA05"
minblperant = 4
minsnr = 3.0
gaintype = "G"

# tclean's own parameter names. Automasking values for the VLA:
# https://casaguides.nrao.edu/index.php/Automasking_Guide
[imager]
type = "tclean"
niter = 100
specmode = "mfs"
deconvolver = "hogbom"
gridder = "standard"
pbcor = true
usemask = "auto-multithresh"
sidelobethreshold = 1.25
noisethreshold = 5.0
minbeamfrac = 0.1
lownoisethreshold = 2.0
negativethreshold = 0.0
interactive = false
geometry = {imsize = 1024, cell = "0.3arcsec"}
weighting = {weighting = "briggs", robust = 0.5}

[[steps]]
type = "phase"
solint = "inf"
solve = {combine = "spw"}

[[steps]]
type = "ampphase"
solint = "inf"

VLA script#

"""
Phase, then amplitude-phase self-calibration of a VLA dataset imaged with tclean.

Usage: python selfcal.py <visfile> <output_directory> [--plot]
"""
import argparse
import logging

from casatasks import split

from wenuray.config import ImageGeometry, SolveOptions, Weighting
from wenuray.imaging import Tclean
from wenuray.selfcalibration import AmpPhasecal, GainPlotObserver, LoggingObserver, Phasecal, Selfcal


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("visfile", help="Measurement set with the calibrated data in DATA")
    parser.add_argument("output", help="Directory for the images, tables and the result record")
    parser.add_argument("--plot", action="store_true", help="Plot the gain solutions")
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_arguments()
    # Wenuray logs each self-calibration round's metrics at INFO
    logging.basicConfig(level=logging.INFO)

    # tclean's own parameter names. Automasking values for the VLA:
    # https://casaguides.nrao.edu/index.php/Automasking_Guide
    imager = Tclean(
        ImageGeometry(imsize=1024, cell="0.3arcsec"),
        Weighting("briggs", robust=0.5),
        niter=100,
        specmode="mfs",
        deconvolver="hogbom",
        gridder="standard",
        pbcor=True,
        usemask="auto-multithresh",
        sidelobethreshold=1.25,
        noisethreshold=5.0,
        minbeamfrac=0.1,
        lownoisethreshold=2.0,
        negativethreshold=0.0,
        interactive=False  # True to edit the masks by hand
    )

    selfcal = Selfcal(
        args.visfile,
        imager,
        [Phasecal("inf", solve={"combine": "spw"}),
         AmpPhasecal("inf")],
        solve=SolveOptions(refant="VA05", minblperant=4, minsnr=3.0, gaintype="G"),
        output=args.output,
    )
    observers = [LoggingObserver()] + ([GainPlotObserver()] if args.plot else [])
    result = selfcal.run(observers)

    # The self-calibrated data, for final imaging
    split(vis=result.ms, outputvis=args.output + "/selfcal.ms", datacolumn="corrected")

e-MERLIN#

e-MERLIN recipe#

# Amplitude-phase self-calibration of an e-MERLIN target, on top of an existing phase table,
# imaged with multiscale tclean: the recipe form of selfcal.py with its default options.
#
# A recipe describes the self-calibration only. selfcal.py also prepares the data first: it
# splits the calibrated target into DATA (target.flagged.ms) and can flag residual RFI. Do that,
# then:
#
# wenuray run recipe.toml --output target_selfcal

ms = "target.flagged.ms"
output = "target_selfcal"

[apply]
applymode = "calonly"  # leave data with failed solutions unflagged

[solve]
refant = "Kn,Cm,Mk2,Pi,De,Da"  # in order of preference
minblperant = 2
minsnr = 3.0
gaintype = "G"
combine = "spw"

# tclean's own parameter names. Cell size and scales suit e-MERLIN at L-band; adjust them to your
# band and target. With a mask of your own: usemask = "user", mask = "mask.im"
[imager]
type = "tclean"
niter = 10000
scales = [0, 3, 5, 10, 15, 20, 30, 40, 50, 80, 100]
specmode = "mfs"
deconvolver = "multiscale"
gridder = "standard"
pbcor = false
interactive = false
cycleniter = 100
usemask = "auto-multithresh"
mask = ""
geometry = {imsize = 1024, cell = "0.02arcsec"}
weighting = {weighting = "briggs", robust = 2.0}

# The existing phase table, applied before every solve. Solutions combined over the 8 spws are
# stored under spw 0
[[initial_stack.tables]]
path = "pcal"
calmode = "p"
spwmap = [0, 0, 0, 0, 0, 0, 0, 0]

# Amplitude-phase solution intervals, from long to short, cleaning deeper as calibration improves.
# Each round flags residual RFI (CORRECTED_DATA - MODEL_DATA) before imaging, with flagdata's
# names; a rejected round's flags are rolled back
[[steps]]
type = "ampphase"
solint = "14min"
imaging = {nsigma = 3.0}
flagging = {type = "residual", mode = "rflag", timedevscale = 3.0, freqdevscale = 3.0, spectralmax = 500, extendflags = false, ntime = "scan"}

[[steps]]
type = "ampphase"
solint = "7min"
imaging = {nsigma = 2.5}
flagging = {type = "residual", mode = "rflag", timedevscale = 3.0, freqdevscale = 3.0, spectralmax = 500, extendflags = false, ntime = "scan"}

[[steps]]
type = "ampphase"
solint = "3.5min"
imaging = {nsigma = 2.0}
flagging = {type = "residual", mode = "rflag", timedevscale = 3.0, freqdevscale = 3.0, spectralmax = 500, extendflags = false, ntime = "scan"}

e-MERLIN script#

"""
Amplitude-phase self-calibration of an e-MERLIN target, on top of existing phase solutions, imaged
with multiscale tclean. Optionally flags residual RFI before self-calibrating.

Usage: python selfcal.py <visfile> <output_directory> <field> [--phase-caltable pcal]
       [--phase-caltable-per-spw] [--mask MASK] [--uvrange UVRANGE] [--refant REFANT]
       [--flag [--rflag-spw SPW ...]] [--plot]
"""
import argparse
import logging
import os
from pathlib import Path

from casatasks import flagdata, flagmanager, mstransform, split

from wenuray.config import ApplyOptions, ImageGeometry, Selection, SolveOptions, Weighting
from wenuray.imaging import Tclean
from wenuray.selfcalibration import (
    AmpPhasecal, CalStack, CalTable, GainPlotObserver, LoggingObserver, ResidualFlagging, Selfcal
)
from wenuray.selfcalibration.caltable import derive_spwmap
from wenuray.utils import count_spectral_windows, get_spw_ids

# Amplitude-phase solution intervals, from long to short, cleaning deeper as calibration improves
SOLINTS = ["14min", "7min", "3.5min"]
NSIGMAS = [3.0, 2.5, 2.0]


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("visfile", help="Calibrated measurement set (CORRECTED_DATA is used)")
    parser.add_argument("output", help="Directory for the images, tables and the result record")
    parser.add_argument("field", help="Target field to self-calibrate")
    parser.add_argument(
        "--phase-caltable", default="pcal", help="Existing phase calibration table to pre-apply"
    )
    parser.add_argument(
        "--phase-caltable-per-spw",
        action="store_true",
        help="The phase table has one solution per spw (default: combined over spws)"
    )
    parser.add_argument("--mask", help="CASA mask image; automasking is used if omitted")
    parser.add_argument(
        "--uvrange", default="", help="uv-range to solve, apply and image, e.g. '>60klambda'"
    )
    parser.add_argument(
        "--refant", default="Kn,Cm,Mk2,Pi,De,Da", help="Reference antennas, in order of preference"
    )
    parser.add_argument(
        "--flag", action="store_true", help="Flag residual RFI with rflag before self-calibrating"
    )
    parser.add_argument(
        "--rflag-spw",
        action="append",
        default=None,
        help="Spectral window selection flagged together; repeat for several groups "
        "(default: all spws in one pass)"
    )
    parser.add_argument("--plot", action="store_true", help="Plot the gain solutions")
    return parser.parse_args()


def flag_residual_rfi(vis: str, spw_groups: list) -> None:
    flagmanager(vis=vis, mode='save', versionname='before_selfcal_flagging')
    for spw in spw_groups:
        flagdata(
            vis=vis,
            datacolumn="data",
            spw=spw,
            correlation="LL,RR",
            mode="rflag",
            action="apply",
            flagbackup=False
        )
        flagdata(
            vis=vis,
            datacolumn="data",
            spw=spw,
            mode="extend",
            extendflags=False,
            action="apply",
            flagbackup=False
        )
    flagmanager(vis=vis, mode='save', versionname='after_selfcal_flagging')


if __name__ == '__main__':
    args = parse_arguments()
    # Wenuray logs each self-calibration round's metrics at INFO
    logging.basicConfig(level=logging.INFO)

    # Self-calibration solves against DATA, so the calibrated target is split into DATA first
    selfcal_vis = Path(args.visfile).stem + ".flagged.ms"
    if not os.path.exists(selfcal_vis):
        mstransform(
            vis=args.visfile, outputvis=selfcal_vis, datacolumn="corrected", field=args.field
        )

    if args.flag:
        flag_residual_rfi(selfcal_vis, args.rflag_spw or [""])

    # tclean's own parameter names. Cell size and scales suit e-MERLIN at L-band; adjust them to
    # your band and target
    imager = Tclean(
        ImageGeometry(imsize=1024, cell="0.02arcsec"),
        Weighting("briggs", robust=2.0),
        niter=10000,
        scales=[0, 3, 5, 10, 15, 20, 30, 40, 50, 80, 100],
        specmode="mfs",
        deconvolver="multiscale",
        gridder="standard",
        pbcor=False,
        interactive=False,
        cycleniter=100,
        usemask="user" if args.mask else "auto-multithresh",
        mask=args.mask or ""
    )

    # The existing phase table is applied before every solve. Its spwmap: solutions combined over
    # spws are stored under the lowest one
    phase_spwmap = derive_spwmap(
        "" if args.phase_caltable_per_spw else "spw", get_spw_ids(selfcal_vis),
        count_spectral_windows(selfcal_vis)
    )
    phase_table = CalTable(args.phase_caltable, "p", tuple(phase_spwmap))

    # Each round flags residual RFI (CORRECTED_DATA - MODEL_DATA) before imaging, with flagdata's
    # names; a rejected round's flags are rolled back
    rflag = ResidualFlagging(
        "rflag",
        timedevscale=3.0,
        freqdevscale=3.0,
        spectralmax=500,
        extendflags=False,
        ntime="scan"
    )
    steps = [
        AmpPhasecal(solint, imaging={"nsigma": nsigma}, flagging=rflag)
        for solint, nsigma in zip(SOLINTS, NSIGMAS)
    ]
    selfcal = Selfcal(
        selfcal_vis,
        imager,
        steps,
        selection=Selection(uvrange=args.uvrange),
        solve=SolveOptions(
            refant=args.refant, minblperant=2, minsnr=3.0, gaintype="G", combine="spw"
        ),
        apply=ApplyOptions(applymode="calonly"),
        output=args.output,
        initial_stack=CalStack([phase_table]),
    )
    observers = [LoggingObserver()] + ([GainPlotObserver()] if args.plot else [])
    result = selfcal.run(observers)

    # The self-calibrated data, for final imaging
    split(vis=result.ms, outputvis=args.output + "/selfcal.ms", datacolumn="corrected")

Simulated ALMA observation#

The tutorial’s example: simulate.py makes the data with Pyralysis, and make_figures.py draws the results.

Simulated recipe#

# Self-calibration of the tutorial's simulated ALMA observation (docs/tutorial.md): a disk whose
# antenna gains change every integration. Make the data first with simulate.py. The values (the
# reference antenna, the image size, the solution intervals) are this example's.

ms = "tutorial.ms"
output = "tutorial_selfcal"

[solve]
refant = "A042"  # the antenna nearest the array's centre

[imager]
type = "tclean"
niter = 2000
nsigma = 3.0
usemask = "auto-multithresh"
# The cell comes from the data's Nyquist cell; 256 pixels hold the disk and some sky around it
geometry = {imsize = 256, cell = "auto"}

[[steps]]  # phases over the whole observation: the gains change too fast for it
type = "phase"
solint = "inf"

[[steps]]  # phases every integration, as fast as the gains change
type = "phase"
solint = "int"

[[steps]]  # amplitudes and phases every integration, now that the model is good
type = "ampphase"
solint = "int"

Simulated script#

"""
Self-calibration of the tutorial's simulated ALMA observation (docs/tutorial.md), imaged with
tclean: the same run as recipe.toml. Make the data first with simulate.py.

Usage: python selfcal.py <visfile> <output_directory> [--plot]
"""
import argparse
import logging

from wenuray.config import ImageGeometry, SolveOptions
from wenuray.imaging import Tclean
from wenuray.selfcalibration import AmpPhasecal, GainPlotObserver, LoggingObserver, Phasecal, Selfcal


def parse_arguments():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("visfile", help="Measurement set with the simulated data in DATA")
    parser.add_argument("output", help="Directory for the images, tables and the result record")
    parser.add_argument("--plot", action="store_true", help="Plot the gain solutions")
    return parser.parse_args()


if __name__ == '__main__':
    args = parse_arguments()
    # Wenuray logs each self-calibration round's metrics at INFO
    logging.basicConfig(level=logging.INFO)

    # The cell comes from the data's Nyquist cell; 256 pixels hold the disk and some sky around it
    imager = Tclean(
        ImageGeometry(imsize=256, cell="auto"), niter=2000, nsigma=3.0, usemask="auto-multithresh"
    )
    # The simulated gains change every integration: a solution over the whole observation can't
    # follow them, solutions every integration can
    steps = [Phasecal("inf"), Phasecal("int"), AmpPhasecal("int")]
    selfcal = Selfcal(
        args.visfile,
        imager,
        steps,
        solve=SolveOptions(refant="A042"),  # the antenna nearest the array's centre
        output=args.output,
    )
    observers = [LoggingObserver()] + ([GainPlotObserver()] if args.plot else [])
    selfcal.run(observers)