Tutorial: self-calibrating a simulated ALMA observation#
This tutorial makes an observation whose answer we know, breaks it the way the atmosphere does, and lets Wenuray repair it. You’ll see what each self-calibration round does to the image, and check that the gains Wenuray solves for are the gains that were put in.
Everything runs on a laptop in about ten minutes, in Wenuray’s Docker image, which holds Wenuray
and Pyralysis side by side (see
Installation). The files are in
examples/simulated/:
git clone https://github.com/miguelcarcamov/wenuray && cd wenuray
docker run --rm -it -v "$PWD":/work -w /work ghcr.io/miguelcarcamov/wenuray:latest bash
1. Simulate the observation#
simulate.py
uses Pyralysis’s simulation framework. The sky is a protoplanetary disk: a ring, 0.45″ in radius
with a 0.3″ hole, inclined by 30°, and a compact source at its centre, 0.18 Jy in all. ALMA observes
it in configuration C-10.6 at 345 GHz (Band 7) for two hours, in 30 s integrations.
# ALMA in configuration C-10.6 at 345 GHz (Band 7): one 2 GHz channel, 30 s integrations over 2 h.
# The gains: 40 degrees of phase and 5% of amplitude per integration; the noise: a 150 K system.
OBSERVATION = Observation(
configuration="alma.cycle10.6.cfg",
frequency=345e9,
bandwidth=2e9,
system_temperature=150.0,
phase_error=40.0,
amplitude_error=0.05,
declination="-37d09m16s",
seed=2026,
)
The sky and the simulation itself come from
pyralysis_simulation.py,
which other examples can share:
def observe(observation: Observation, sources: list):
"""
The noiseless observation: Pyralysis's simulation pipeline, from an hour before transit for
the observation's duration
"""
from astropy.time import Time
from pyralysis.pipelines.simulation import SimulationContext, SimulationPipeline
context = SimulationContext(
config={
"antenna_config_path": observation.path,
"sources": sources,
"observation_config": {
"center_frequency": observation.frequency * u.Hz,
"channel_width": observation.bandwidth * u.Hz,
"n_channels": 1,
"pointing_position": target(observation),
"hour_angle": "-{0:g}h".format(observation.duration / 7200),
"integration_time": observation.integration * u.s,
"observation_time": "{0:g}s".format(observation.duration),
"reference_time": Time(REFERENCE_TIME, scale="utc"),
},
}
)
SimulationPipeline().run(context)
return context.dataset
Then the observation is corrupted with Pyralysis’s noise injectors, as its documentation recommends: the multiplicative errors first, then the additive ones, as in a receiver chain.
Antenna gain errors: 40° of phase and 5% of amplitude per antenna, drawn anew for every integration, like fast atmospheric phase fluctuations.
Thermal noise from the radiometer equation for a 150 K system. Pyralysis also writes the
SIGMAandWEIGHTcolumns to match it.
def gain_errors(observation: Observation):
"""
Antenna-based gains. With a coherence time, they drift smoothly (DriftingGainInjector);
without, Pyralysis's AntennaGainInjector draws them anew for every integration (and channel;
there is one), so only solutions at every integration can follow them
"""
from pyralysis.injectors import AntennaGainInjector
options = dict(
amp_sigma=observation.amplitude_error,
phase_sigma=np.radians(observation.phase_error),
seed=observation.seed
)
if observation.coherence_time is None:
return AntennaGainInjector(**options)
return drifting_gain_injector()(coherence_time=observation.coherence_time, **options)
def thermal_noise(observation: Observation):
"""
Radiometer-equation noise; Pyralysis also writes SIGMA and WEIGHT for it
"""
from pyralysis.injectors import ThermalNoiseInjector
return ThermalNoiseInjector(
system_temperature=observation.system_temperature,
integration_time=observation.integration,
channel_bandwidth=observation.bandwidth,
aperture_efficiency=APERTURE_EFFICIENCY,
seed=observation.seed + 1,
)
The script writes three things: tutorial.ms, the corrupted observation; tutorial.ms.ideal, the
same observation and the same thermal noise without gain errors, which is what a perfect
calibration would give; and tutorial.ms.gains.npz, the injected gains:
python examples/simulated/simulate.py tutorial.ms
2. Describe the self-calibration#
The procedure is a short recipe,
recipe.toml:
# 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"
A few choices, and why:
The reference antenna is the one nearest the array’s centre: it sees every other antenna on short, well-measured baselines.
cell = "auto"takes the cell from the data: the Nyquist cell of the longest baseline, divided by 2.5, so about five pixels cover the beam. Here that’s 0.0153″. 256 pixels hold the disk and some sky around it.Three rounds. A phase solution over the whole observation (
inf) first: it can only remove the part of the errors that’s constant, and here there’s little. Then phases every integration (int), as fast as the errors change. Last, amplitudes and phases every integration, once the model is good.
Or let Wenuray suggest one#
wenuray suggest writes a recipe from the data alone, each value with the reason for it, before
anything is imaged (A recipe from the data):
wenuray suggest tutorial.ms -o suggested.toml
wenuray validate suggested.toml
On the tutorial’s data it writes
suggested.toml:
# A Wenuray self-calibration recipe suggested from tutorial.ms by `wenuray suggest` (Wenuray
# 1.2.2.dev3). Each value derived from the data says why. Check it with `wenuray validate`, then
# `wenuray run` it. Paths are relative to this file.
ms = "tutorial.ms" # the calibrated target data in DATA
[selection] # one selection for the solve, the apply and the imager
field = "unnamed" # the field self-calibrated
spw = "" # every spectral window with data: 0
[solve] # gaincal options shared by every step
# 39 m from the array centre, 0.0% of its sampled data flagged: the best of 43 antennas by distance
# and flagging
refant = "A042"
# closure amplitudes need 4 antennas, so each antenna's solution needs baselines to 3 others
minblperant = 3
minsnr = 3.0 # gaincal's default; solint "auto" aims at twice it
gaintype = "T" # one solution for both polarizations, with the S/N of both
[imager]
type = "tclean" # or "pyralysis"
niter = 1000
# each round cleans to 3 x its residual rms, which approaches the thermal noise from the data,
# 22.7 uJy/beam, as the gains improve
nsigma = 3.0
# the cell: the Nyquist cell over 2.5; the size: 2.5 primary-beam FWHMs (#67)
geometry = { imsize = [2500, 2500], cell = "0.0153arcsec" }
weighting = { weighting = "natural" } # the most sensitive: self-calibration needs the signal
# A first phase solution per scan, against the initial model.
[[steps]]
type = "phase"
solint = "inf"
# The phases again, round by round, each at the shortest solint the S/N supports against the last
# round's model, until the gains are at their noise (#66).
[[steps]]
type = "repeat"
step = { type = "phase", solint = "auto" }
# Amplitudes last: if the S/N can't support an amplitude solution, "auto" finds no solint and the
# run ends there, with the phases kept.
[[steps]]
type = "ampphase"
solint = "auto"
It takes the same reference antenna as the recipe above, A042, 39 m from the array’s centre, and
the same 0.0153″ cell. It differs where the recipe uses what we know about the source:
The image size. It covers 2.5 primary-beam FWHMs, 2500 pixels, since it can’t know where the emission is. This disk fits in 256 pixels, which images faster and leaves less noise to clean.
The solints. The suggestion leaves them
"auto", resolved round by round against each model: the S/N decides how short they get. The recipe above setsintbecause we know the simulated gains change every integration.
wenuray suggest tutorial.ms --image adds one quick image, in 50 s here, and decides the amplitude
step from the S/N it predicts
(suggested-image.toml).
This disk is bright enough. The amplitude solutions’ predicted S/N over a scan is 120, well above
the 6 they need, so the step stays:
# Amplitudes last: the amplitude solutions' predicted S/N over a scan, 120.0 (CASA's, the antenna's
# over sqrt(2)), reaches 6 (2 x minsnr). If the run's models can't support an amplitude solution,
# "auto" finds no solint and the run ends there, with the phases kept.
[[steps]]
type = "ampphase"
solint = "auto"
Start from the suggestion for data of your own, and change what you know better.
The same run in Python is
selfcal.py;
a test checks that the two build the same run.
3. Run it#
wenuray run examples/simulated/recipe.toml --ms tutorial.ms --output tutorial_selfcal
Each round images the data, solves the gains against that image’s model, applies them and keeps the round only if the image improves. The log tells the story:
Round |
Solution interval |
Peak S/N |
Image noise |
Model flux |
Gain corrections / their noise |
|---|---|---|---|---|---|
initial |
310 |
59.2 µJy/beam |
0.106 Jy |
||
phase |
|
380 |
48.4 µJy/beam |
0.107 Jy |
6.3 |
phase |
|
1215 |
24.7 µJy/beam |
0.179 Jy |
14.5 |
amplitude and phase |
|
1241 |
24.3 µJy/beam |
0.179 Jy |
phase 0.3, amplitude 1.5 |
ideal: no gain errors |
1245 |
24.1 µJy/beam |
0.179 Jy |
Before calibration, the phase errors scatter the visibilities so much that they partly cancel out: the image holds only 0.106 of the 0.18 Jy. The solution over the whole observation helps a little. The solutions every integration recover the flux and bring the noise to within 1% of the ideal image’s. The last round’s corrections are at the level of their own noise (0.3 and 1.5): there was nothing left to correct, which is what convergence looks like.
4. Look at the results#
Make the figures with
make_figures.py:
python examples/simulated/make_figures.py tutorial.ms tutorial_selfcal figures
Top: the image before self-calibration, after it, and of the data without gain errors. Bottom: their residuals. Before, the residual is dominated by the source and by stripes the gain errors spread across the image; after, it matches the ideal one. The faint disk left in both is extended flux the deconvolution hasn’t cleaned yet, not a calibration error.#
Each round’s peak S/N, its noise against the ideal image’s (the floor any calibration can reach), and its gain corrections against their own noise. A ratio near 1 in the last panel means a round found nothing more to correct.#
The phases Wenuray found against those injected, relative to the reference antenna. Left: one antenna over the two hours, integration by integration. Right: every antenna at every integration. They agree to 3.0° rms. The errors were 40° per antenna, so 56° rms between an antenna and the reference.#
What the warnings mean#
Wenuray warns twice during this run, and here both are false alarms:
The data’s noise is 1.51 times the noise their weights state.
The residual inside the source mask is below the thermal noise (rounds 2 and 3).
Wenuray measured the noise from the difference between consecutive integrations, which cancels
the source as long as the gains change slowly. In this simulation they change completely every
integration, so the differences kept part of the source, and the noise measured came out about
twice too high. The weights are right (SIGMA matches the noise of the ideal data exactly), and the
residual isn’t below the real thermal noise. Since 1.2.1 Wenuray also measures the noise from the
difference of the two parallel hands, which the gains, the same in both, don’t touch, and uses it
when it is the lower (#153): neither
warning is given then. The figures and numbers here were made before.
What Pyralysis’s simulation needs for CASA#
A measurement set from Pyralysis 3.3’s simulation doesn’t open in CASA as it comes. simulate.py’s
write() patches three things, filed upstream:
The pipeline’s export writes only the main table, so every subtable is empty (pyralysis#405). Write with
DaskMS(...).write(dataset, tables="ALL").The spectral windows record REST frequencies, which tclean can’t convert (pyralysis#406). Observatories record TOPO.
The
FEEDtable is empty, so tclean finds no receptors (pyralysis#407). Each antenna gets a row with ALMA’s linear feeds, X and Y.
Two more don’t stop CASA here: STATE_ID and PROCESSOR_ID point to empty tables
(pyralysis#408), and the antenna gains are drawn
independently for every integration and channel
(pyralysis#409). The latter is why this
tutorial uses one channel per spectral window, and why its gains change faster than real ones do.
Try it yourself#
Slower or stronger errors: change
phase_sigmaandamp_sigmaingain_errors().A longer ladder: once gains can be correlated in time (pyralysis#409), add
Phasecal("120s")betweeninfandint, and watch the corrections fall round by round. Or let the data choose:Repeat(Phasecal("auto"))shortens the solint round by round until the corrections are at the noise (Solints from the data). Here, with gains that change every integration, it goes straight toint.Pyralysis as the imager: set
type = "pyralysis"in[imager], with a mask (see Imagers).