Algorithmadvanced
Multiscale CLEAN
Also called MS-CLEAN, multi-scale CLEAN.
Extend CLEAN with components of several sizes: smooth the residual at each scale, pick the scale and pixel whose step lowers the misfit most, and update all smoothed residuals.
- Solves
- Image deblurring
- Time
- Θ(K s n + s² n log n) worst · average · best
- Space
- Θ(s² n) extra
- Where
- K = the number of iterations; n = the number of pixels; s = the number of scales
- Model
- Real RAM
- Properties
- deterministicgreedyiterativenot linearmonotone misfitnot nonnegative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tim J. Cornwell, 2008
Multiscale CLEAN fits a dirty image with smooth blobs of several widths in place of the single points of Hogbom CLEAN. It keeps one smoothed copy of the residual for each scale, picks the scale and pixel where a step lowers the misfit to the data the most, adds a blob of that scale to the model, and subtracts the matching cross-scale beam from every smoothed residual. Extended emission, such as a nebula or a radio lobe, then needs far fewer components, and the model avoids the mottled look of point CLEAN. Like Hogbom CLEAN it works on images with a fixed dirty beam; Cotton-Schwab CLEAN is the major-cycle frame around it that goes back to the visibilities.
In plain words
Point CLEAN explains a picture with dots. That works for stars, but a smooth cloud needs hundreds of dots, and the result looks spotty. Multiscale CLEAN has a box of stamps: a dot, a small round blob and a large round blob. At each step it tries every stamp at every place, and it keeps the one that explains the most of what is left. A large cloud is then covered by a few large blobs, and the stars still get dots. To do this fast, the method keeps one blurred copy of the leftover picture for each stamp size, and it updates all of them after each step.
The problem
The setting is that of Hogbom CLEAN. The sky lives on a periodic grid of pixels. The array measures the visibilities at the frequencies with weight , with and . The dirty beam is , so , and the dirty image is . The misfit of a model is
The input also has scale functions . Each is real, has unit sum and is symmetric, , and is the point. The code uses for , a truncated parabola of radius pixels. The output is a model and the residual .
The algorithm
Write for the residual smoothed at scale , and for the cross-scale beams. A blob of scale at pixel with flux changes by .
MULTISCALE-CLEAN(D, B, φ_0..φ_{s-1}, g, τ, K) ▷ φ_0 = δ- 1
I_t ← φ_t ∗ D for every scale t, M ← 0 - 2
B_ut ← φ_u ∗ φ_t ∗ B for every pair of scales u, t - 3
for k ← 1 to K do - 4
(u, p) ← the scale and pixel with the largest |I_u(p)| / √B_uu(0) - 5
if |I_u(p)| ≤ τ then break - 6
c ← g I_u(p) / B_uu(0) - 7
M ← M + c φ_u(· - p) ▷ a blob of scale u at p - 8
I_t(q) ← I_t(q) - c B_ut(q - p) for every scale t and pixel q - 9
return M, I_0 ▷ I_0 = R, the residual
Line L8 keeps every equal to , so the smoothed residuals never need to be computed again. Line L4 is the greedy rule: a step at lowers by , and L4 picks the largest such drop. A large blob has a small , because it is seen only by the short baselines, so dividing by lets a large scale win on extended emission even though its smoothed peak is lower. Implementations also multiply the score by a bias factor per scale, a tuned choice that usually favors small scales; the code accepts one.
Example
Take in 1D. The sky is a Gaussian of standard deviation 2 pixels and total flux 4 centered at pixel 10, plus a point of flux 1 at pixel 24. The array measures the frequencies . The scales have radii (the point), and pixels, with , and . At the start the smoothed peaks are , and , and the scores are , and . So the first step takes the radius-3 blob, although the point scale has the highest peak. With and :
| step | scale radius | pixel | flux | after | |
|---|---|---|---|---|---|
| 1 | 3 | 10 | 1.5646 | 1.0318 | 3.6530 |
| 2 | 3 | 10 | 1.0952 | 0.7223 | 2.3082 |
| 3 | 6 | 10 | 0.5838 | 0.7044 | 1.6091 |
| 4 | 0 | 24 | 0.9599 | 0.2880 | 1.1391 |
| 5 | 3 | 11 | 0.5543 | 0.3656 | 0.7946 |
| 6 | 0 | 24 | 0.6435 | 0.1930 | 0.5834 |
The blobs take the extended source and the points take the point source. To bring below 1% of the peak of the dirty image, Hogbom CLEAN with the same gain needs 65 components, and its largest error against the true sky is . Multiscale CLEAN needs 35 components (18 points, 10 blobs of radius 3 and 7 of radius 6), and its largest error is . Both fit the data equally well; the multiscale model is closer to the sky because its components look more like the sky.
Correctness
The proof is that of Hogbom CLEAN with a larger dictionary. For a blob , expanding the square gives the exact identity
because the inner product of with the residual is when is symmetric, and . With the drop is for . Because the point scale is in the dictionary, the chosen score is at least times a fixed positive constant. The drops have a finite sum, so and : the model comes to fit every measured visibility. As for Hogbom CLEAN, nothing says which of the many models that fit the data it reaches. The full proof is below.
Proof: Multiscale CLEAN keeps every smoothed residual exact, lowers the misfit at each step, and fits the data in the limitfull
Setting. As on the Hogbom CLEAN page: a periodic grid of pixels (read indices as 2D for an image), the DFT , a real sky with , weights with and , the dirty beam (real, ), and the dirty image . The misfit is . The scale functions are real and symmetric, . Write , and . The loop is lines L1 to L9 with .
From the Hogbom page (Claim 1 there), for every model ,
Claim 1 (the smoothed residuals stay exact). After every step, for every scale . In particular .
Proof. Line L1 makes it true with . A step adds to , which changes by , since periodic convolution is commutative and associative. Line L8 makes exactly this change to .
Claim 2 (the cost of a step). Let . For every real ,
Proof. , and is real because is real and symmetric. Expanding the square as on the Hogbom page,
By (1) and the convolution theorem, , which is real; take . The DFT of is , so .
, and the code requires : the scale must have some weight on the measured frequencies. For , .
Claim 3 (the drop). With (line L6),
Proof. Substitute in Claim 2.
So for every step lowers unless , and line L4 (with no bias) picks the pair with the largest drop.
Claim 4 (convergence). Let , , and let line L4 maximize with fixed weights (no bias is ). Then , , and at every measured frequency.
Proof. Let and . At the step that picks , the choice of line L4 gives, for every pixel and using the point scale,
so . By Claim 3, each step lowers by at least . Since these amounts have a finite sum, so along the iterations. By (1), is a fixed invertible linear map of the vector , so each , and as on the Hogbom page.
Claim 5 (one scale is Hogbom CLEAN). If the only scale is , then , , the score in line L4 is , and lines L6 to L8 are lines L5 to L7 of Hogbom CLEAN.
Proof. and .
What is not claimed. The set of models with is the sky plus every image whose DFT vanishes on the measured frequencies, and the iteration may approach any of them; the proof does not say that converges, nor that a larger scale set gives a model closer to the sky. The example on the page shows a closer model in one case; that is a measurement, not a theorem. If some is not symmetric, is complex and is no longer the inner product of the blob with the residual, so Claim 2 fails.
Complexity
Lines L1 and L2 take time with the FFT and space for the cross beams; by symmetry , so half of them suffice. Each iteration scans smoothed images and updates them, so it takes time, and iterations take . The number of iterations is what matters: on extended emission, is much smaller than for Hogbom CLEAN, which pays for the factor .
Properties
- The misfit never rises for , with the exact drop .
- Hogbom CLEAN is the case of one scale. With only , the algorithm is line for line Hogbom CLEAN.
- Sparse in a larger dictionary. The model is a short list of points and blobs. On a mix of compact and smooth emission it is much shorter than a list of points.
- Nonlinear and not unique. The choice in line L4 depends on the data and on the set of scales.
- Flux in large blobs depends on short baselines. is the weighted power of on the measured frequencies. If the shortest baselines are missing, a large blob is barely seen, and the step in line L6 is large and poorly constrained.
Variants and improvements
- Scale bias. A factor per scale in line L4 that favors small scales. It is a tuned choice, not a derived one.
- Other scale functions. Gaussians, tapered parabolas or wavelet atoms (see the discrete wavelet transform). The proof needs only real, symmetric functions with .
- Inside major cycles. In practice the loop is the minor cycle of Cotton-Schwab CLEAN, with the model subtracted from the visibilities between cycles.
- Multiscale multifrequency. Rau and Cornwell (2011) let each component also have a spectrum over a wide band of frequencies.
When to use it
Use multiscale CLEAN when the field has extended emission: nebulae, galaxies, radio lobes, the disk of a planet. For a field of compact sources, Hogbom or Clark CLEAN is cheaper and gives the same result. Pick the largest scale smaller than the largest structure the array can see, which is set by its shortest baseline.
Pitfalls
- Too large a scale. A blob wider than the array can see has a small , and the method puts large, poorly determined flux into it.
- No point scale. Without the residual cannot reach zero at a point source, and the proof fails.
- Scales that are not symmetric. The identity uses ; with an asymmetric function the smoothed residual is not the gradient, and the step can raise the misfit.
- The peak in place of the score. Choosing the scale by the largest alone favors the point scale, because smoothing lowers the peak. In the example the point scale has the highest peak at the start, although a blob gives the larger drop.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.
Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
(wrapped around), so a delta kernel gives the identity and no shift.
"""
import cmath
import math
# ------------------------------------------------------------------ images
def new_image(n1, n2, value=0.0):
"""An n1 x n2 image (n1 rows, n2 columns) filled with value."""
return [[value] * n2 for _ in range(n1)]
def img_add(a, b):
"""The pixelwise sum a + b."""
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def img_scale(a, c):
"""The image c a."""
return [[c * x for x in row] for row in a]
def img_dot(a, b):
"""<a, b> = sum conj(a_ij) b_ij."""
return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def img_norm(a):
"""The Euclidean (Frobenius) norm of an image."""
return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))
def flatten(img):
"""Row-major vector of an image."""
return [x for row in img for x in row]
def unflatten(v, n1, n2):
"""The n1 x n2 image of a row-major vector."""
return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]
# ------------------------------------------------------------------ DFT
def _is_pow2(n):
return n > 0 and n & (n - 1) == 0
def _fft_pow2(x):
"""Iterative radix-2 FFT, unnormalized forward transform."""
n = len(x)
a = [complex(v) for v in x]
j = 0
for i in range(1, n):
bit = n >> 1
while j & bit:
j ^= bit
bit >>= 1
j |= bit
if i < j:
a[i], a[j] = a[j], a[i]
size = 2
while size <= n:
half = size // 2
tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
for start in range(0, n, size):
for k in range(half):
u = a[start + k]
v = a[start + k + half] * tw[k]
a[start + k] = u + v
a[start + k + half] = u - v
size *= 2
return a
def dft(x):
"""X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
n = len(x)
if n == 0:
return []
if _is_pow2(n):
return _fft_pow2(x)
w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]
def idft(xf):
"""x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
n = len(xf)
if n == 0:
return []
y = dft([complex(v).conjugate() for v in xf])
return [v.conjugate() / n for v in y]
def _rows_then_cols(img, f):
rows = [f(row) for row in img]
cols = [f(list(col)) for col in zip(*rows)]
return [list(r) for r in zip(*cols)]
def dft2(img):
"""2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
return _rows_then_cols(img, dft)
def idft2(img):
"""Inverse 2D DFT, with the factor 1 / (n1 n2)."""
return _rows_then_cols(img, idft)
def _shift1(x, s):
return list(x[s:]) + list(x[:s])
def fftshift(x):
"""Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [fftshift(r) for r in x]
return _shift1(rows, (len(rows) + 1) // 2)
return _shift1(x, (len(x) + 1) // 2)
def ifftshift(x):
"""The inverse of fftshift (1D, or both axes of an image)."""
if x and isinstance(x[0], (list, tuple)):
rows = [ifftshift(r) for r in x]
return _shift1(rows, len(rows) // 2)
return _shift1(x, len(x) // 2)
def circ_conv(x, h):
"""Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
n = len(x)
nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]
def circ_conv2(img, h):
"""Periodic 2D convolution with the kernel h centered at index (0, 0)."""
n1, n2 = len(img), len(img[0])
nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
out = new_image(n1, n2)
for i in range(n1):
for j in range(n2):
out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
return out
# ------------------------------------------------------------------ phantoms
def pixel_centers(n):
"""(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
ys = [1.0 - (2 * i + 1) / n for i in range(n)]
return xs, ys
# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
(2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
(-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
(-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
(-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
(0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
(0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
(0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
(0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
(0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
(0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]
# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
(rho, a, b, x0, y0, phi)
for rho, (_, a, b, x0, y0, phi) in zip(
(1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
)
]
def ellipse_value(x, y, table):
"""The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
total = 0.0
for rho, a, b, x0, y0, phi in table:
c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
dx, dy = x - x0, y - y0
u = dx * c + dy * s
v = -dx * s + dy * c
if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
total += rho
return total
def ellipse_phantom(n, table):
"""The n x n image of an ellipse table, sampled at the pixel centers."""
xs, ys = pixel_centers(n)
return [[ellipse_value(x, y, table) for x in xs] for y in ys]
def disk_phantom(n, radius):
"""1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
xs, ys = pixel_centers(n)
r2 = radius * radius
return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]
def spikes_1d(n, positions, amplitudes):
"""A signal of length n with the given amplitudes at the given positions."""
out = [0.0] * n
for p, a in zip(positions, amplitudes):
out[p] += a
return out
# ------------------------------------------------------------------ projector
def parallel_beam_matrix(n, angles, nbins):
"""Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.
Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
value times the pixel area over the bin width is split linearly between
the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
Returns the sparse rows, each a list of (column, weight) pairs.
Pixel-driven projection has a ripple: with a bin width close to the pixel
size, a disk projection is off by up to about 10 percent in some bins. A
bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
1 percent.
"""
xs, ys = pixel_centers(n)
smax = math.sqrt(2.0)
width = 2.0 * smax / nbins
scale = (2.0 / n) ** 2 / width
rows = []
for theta in angles:
c, s = math.cos(theta), math.sin(theta)
acc = [dict() for _ in range(nbins)]
for i, y in enumerate(ys):
for j, x in enumerate(xs):
t = (x * c + y * s + smax) / width - 0.5
b0 = math.floor(t)
frac = t - b0
col = i * n + j
for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
if 0 <= b < nbins and w > 0.0:
acc[b][col] = acc[b].get(col, 0.0) + w * scale
rows.extend(sorted(d.items()) for d in acc)
return rows
def sp_matvec(rows, x):
"""y = A x for sparse rows of (column, weight) pairs."""
return [sum(w * x[c] for c, w in row) for row in rows]
def sp_rmatvec(rows, y, ncols):
"""x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
out = [0.0] * ncols
for row, yi in zip(rows, y):
if yi == 0:
continue
for c, w in row:
out[c] += w.conjugate() * yi
return out
# ------------------------------------------------------------------ noise
def gauss_noise(rng, shape, sigma):
"""Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
if isinstance(shape, int):
return [rng.gauss(0.0, sigma) for _ in range(shape)]
n1, n2 = shape
return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]
def _poisson_small(rng, lam):
"""Knuth's product method, exact for a mean lam <= 30."""
limit = math.exp(-lam)
k, p = 0, rng.random()
while p > limit:
k += 1
p *= rng.random()
return k
def poisson_sample(rng, lam):
"""An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
if lam < 0:
raise ValueError("negative mean")
total = 0
while lam > 30.0:
total += _poisson_small(rng, 30.0)
lam -= 30.0
if lam > 0.0:
total += _poisson_small(rng, lam)
return total
multiscale_clean.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiscale-clean/. The authors are listed in prov/KXJYFX.jsonl.
"""Multiscale CLEAN on a periodic grid.
Images are lists of rows, img[i][j]; a 1D signal is a 1 x n image. Kernels
(the dirty beam, the scale functions) have their center at index (0, 0),
wrapped around. Scale 0 is the delta function, so plain Hogbom CLEAN is the
case of one scale.
"""
import math
from imgkit import dft2, idft2, new_image
def scale_function(n1, n2, size):
"""A unit-sum bump of radius size: 1 - (r / size)^2 for r < size, 0 outside.
size = 0 gives the delta function at (0, 0). The bump is symmetric under
(i, j) -> (-i, -j), which the proof needs.
"""
out = new_image(n1, n2)
if size <= 0:
out[0][0] = 1.0
return out
for i in range(n1):
di = min(i, n1 - i)
for j in range(n2):
dj = min(j, n2 - j)
r2 = (di * di + dj * dj) / (size * size)
if r2 < 1.0:
out[i][j] = 1.0 - r2
total = sum(sum(row) for row in out)
return [[v / total for v in row] for row in out]
def conv_fft(*imgs):
"""The periodic convolution of several real images of the same size, by the DFT."""
prod = dft2(imgs[0])
for img in imgs[1:]:
f = dft2(img)
prod = [[a * b for a, b in zip(ra, rb)] for ra, rb in zip(prod, f)]
return [[v.real for v in row] for row in idft2(prod)]
def multiscale_clean(dirty, beam, sizes, gain=0.1, threshold=0.0, max_iter=1000, bias=None):
"""Deconvolve a dirty image with components of several sizes.
sizes lists the scale radii in pixels and must hold 0 (the delta scale).
A step at scale s and pixel p lowers the misfit by (2g - g^2) I_s(p)^2 / B_ss(0),
so the pick maximizes bias[s] |I_s(p)| / sqrt(B_ss(0)); with no bias it is the
largest drop. Returns (model, residual, components, smoothed); components is
a list of (scale index, i, j, flux), smoothed[s] = phi_s * residual.
"""
if 0 not in sizes:
raise ValueError("the scales must include the delta scale 0")
n1, n2 = len(dirty), len(dirty[0])
if bias is None:
bias = [1.0] * len(sizes)
if any(b <= 0 for b in bias):
raise ValueError("the bias must be positive")
phis = [scale_function(n1, n2, s) for s in sizes]
ns = len(sizes)
smoothed = [conv_fft(dirty, ph) for ph in phis] # @line L1
cross = [[conv_fft(phis[s], phis[t], beam) for t in range(ns)] for s in range(ns)] # @line L2
if any(cross[s][s][0][0] <= 0 for s in range(ns)):
raise ValueError("a scale is not seen by the array")
weight = [bias[s] / math.sqrt(cross[s][s][0][0]) for s in range(ns)]
model = new_image(n1, n2)
comps = []
for _ in range(max_iter): # @line L3
best, pick = -1.0, None
for s in range(ns): # @line L4
for i, row in enumerate(smoothed[s]):
for j, v in enumerate(row):
if weight[s] * abs(v) > best:
best, pick = weight[s] * abs(v), (s, i, j)
s, i0, j0 = pick
peak = smoothed[s][i0][j0]
if abs(peak) <= threshold: # @line L5
break
c = gain * peak / cross[s][s][0][0] # @line L6
ph = phis[s]
for i in range(n1): # @line L7
pi = ph[(i - i0) % n1]
mi = model[i]
for j in range(n2):
mi[j] += c * pi[(j - j0) % n2]
comps.append((s, i0, j0, c))
for t in range(ns): # @line L8
bst = cross[s][t]
img = smoothed[t]
for i in range(n1):
bi = bst[(i - i0) % n1]
ri = img[i]
for j in range(n2):
ri[j] -= c * bi[(j - j0) % n2]
residual = [list(row) for row in smoothed[sizes.index(0)]]
return model, residual, comps, smoothed # @line L9
def scale_misfit(model, sky, weights):
"""Q(M) = (1/W) sum_k w_k |V_k - M^_k|^2, the misfit to the measured visibilities."""
total = sum(sum(row) for row in weights)
vs, vm = dft2(sky), dft2(model)
acc = 0.0
for rw, ra, rb in zip(weights, vs, vm):
for w, a, b in zip(rw, ra, rb):
acc += w * abs(a - b) ** 2
return acc / total
def gaussian_blob(n1, n2, ci, cj, width, flux):
"""A periodic Gaussian of the given width (pixels) centered at (ci, cj), with the given total flux."""
out = new_image(n1, n2)
for i in range(n1):
di = min(abs(i - ci), n1 - abs(i - ci))
for j in range(n2):
dj = min(abs(j - cj), n2 - abs(j - cj))
out[i][j] = math.exp(-(di * di + dj * dj) / (2 * width * width))
total = sum(sum(row) for row in out)
return [[flux * v / total for v in row] for row in out]
test_multiscale_clean.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/multiscale-clean/. The authors are listed in prov/KXJYFX.jsonl.
import random
from imgkit import dft2, idft2, new_image
from multiscale_clean import conv_fft, gaussian_blob, multiscale_clean, scale_function, scale_misfit
def beam_and_dirty(sky, w):
n1, n2 = len(sky), len(sky[0])
s = n1 * n2 / sum(sum(r) for r in w)
beam = [[v.real * s for v in row] for row in idft2(w)]
vis = dft2(sky)
prod = [[a * b for a, b in zip(ra, rb)] for ra, rb in zip(w, vis)]
dirty = [[v.real * s for v in row] for row in idft2(prod)]
return beam, dirty
def mask_1d(n, freqs):
w = [0.0] * n
for k in freqs:
w[k % n] = 1.0
w[-k % n] = 1.0
return [w]
def mask_2d(n, fraction, rng):
w = new_image(n, n)
for k in range(-1, 2):
for l in range(-1, 2):
w[k % n][l % n] = 1.0
for k in range(n):
for l in range(n):
if rng.random() < fraction:
w[k][l] = 1.0
w[-k % n][-l % n] = 1.0
return w
def max_abs(img):
return max(abs(v) for row in img for v in row)
def page_example():
n = 32
w = mask_1d(n, (0, 1, 2, 3, 5, 7, 10))
sky = gaussian_blob(1, n, 0, 10, 2.0, 4.0)
sky[0][24] += 1.0
beam, dirty = beam_and_dirty(sky, w)
return sky, w, beam, dirty
def hogbom_reference(dirty, beam, gain, max_iter):
n1, n2 = len(dirty), len(dirty[0])
r = [list(row) for row in dirty]
comps = []
for _ in range(max_iter):
i0, j0 = max(((i, j) for i in range(n1) for j in range(n2)), key=lambda p: abs(r[p[0]][p[1]]))
c = gain * r[i0][j0] / beam[0][0]
comps.append((i0, j0, c))
for i in range(n1):
for j in range(n2):
r[i][j] -= c * beam[(i - i0) % n1][(j - j0) % n2]
return comps, r
def test_scale_functions():
d = scale_function(8, 8, 0)
assert d[0][0] == 1.0 and sum(sum(r) for r in d) == 1.0
for size in (2, 3, 5):
ph = scale_function(16, 16, size)
assert abs(sum(sum(r) for r in ph) - 1.0) < 1e-12
assert all(ph[i][j] == ph[-i % 16][-j % 16] for i in range(16) for j in range(16))
try:
multiscale_clean([[1.0, 0.0]], [[1.0, 0.0]], [2])
except ValueError:
pass
else:
raise AssertionError("the delta scale is required")
def test_one_scale_is_hogbom():
rng = random.Random(2)
w = mask_2d(16, 0.2, rng)
sky = new_image(16, 16)
for _ in range(4):
sky[rng.randrange(16)][rng.randrange(16)] += rng.uniform(0.5, 1.5)
beam, dirty = beam_and_dirty(sky, w)
_, res, comps, _ = multiscale_clean(dirty, beam, [0], gain=0.2, max_iter=25)
ref, rres = hogbom_reference(dirty, beam, 0.2, 25)
assert [(i, j) for _, i, j, _ in comps] == [(i, j) for i, j, _ in ref]
assert max(abs(a[3] - b[2]) for a, b in zip(comps, ref)) < 1e-12
assert max(abs(a - b) for ra, rb in zip(res, rres) for a, b in zip(ra, rb)) < 1e-12
def test_smoothed_residuals_stay_exact():
rng = random.Random(8)
w = mask_2d(16, 0.25, rng)
sky = gaussian_blob(16, 16, 5, 6, 1.5, 3.0)
sky[12][3] += 1.0
beam, dirty = beam_and_dirty(sky, w)
sizes = [0, 2, 4]
model, res, comps, smoothed = multiscale_clean(dirty, beam, sizes, gain=0.2, max_iter=40)
assert len({s for s, _, _, _ in comps}) >= 2
pred = conv_fft(model, beam)
true_res = [[d - p for d, p in zip(rd, rp)] for rd, rp in zip(dirty, pred)]
for size, sm in zip(sizes, smoothed):
want = conv_fft(true_res, scale_function(16, 16, size))
assert max(abs(a - b) for ra, rb in zip(sm, want) for a, b in zip(ra, rb)) < 1e-10
assert max(abs(a - b) for ra, rb in zip(res, true_res) for a, b in zip(ra, rb)) < 1e-10
def test_misfit_drops_by_the_proved_amount():
sky, w, beam, dirty = page_example()
sizes = [0, 3, 6]
phis = [scale_function(1, 32, s) for s in sizes]
bss = [conv_fft(ph, ph, beam)[0][0] for ph in phis]
for gain in (0.3, 1.0, 1.8):
q = scale_misfit(new_image(1, 32), sky, w)
for t in range(1, 9):
model, _, comps, _ = multiscale_clean(dirty, beam, sizes, gain=gain, max_iter=t)
s, _, _, c = comps[-1]
q2 = scale_misfit(model, sky, w)
assert abs((q - q2) - (2 - gain) / gain * c * c * bss[s]) < 1e-9
assert q2 < q
q = q2
def test_converges_to_the_data():
rng = random.Random(4)
w = mask_2d(16, 0.3, rng)
sky = gaussian_blob(16, 16, 8, 8, 2.0, 5.0)
beam, dirty = beam_and_dirty(sky, w)
model, res, _, _ = multiscale_clean(dirty, beam, [0, 2, 4], gain=0.5, max_iter=300)
assert max_abs(res) < 1e-2 * max_abs(dirty)
assert scale_misfit(model, sky, w) < 1e-4 * scale_misfit(new_image(16, 16), sky, w)
def test_extended_source_needs_fewer_components():
sky, w, beam, dirty = page_example()
tol = 0.01 * max_abs(dirty)
def run(sizes):
model, res, comps, _ = multiscale_clean(dirty, beam, sizes, gain=0.3, threshold=0.0, max_iter=200)
for k in range(1, len(comps) + 1):
m, r, _, _ = multiscale_clean(dirty, beam, sizes, gain=0.3, max_iter=k)
if max_abs(r) < tol:
return k, max(abs(a - b) for a, b in zip(m[0], sky[0]))
raise AssertionError("did not converge")
k_point, err_point = run([0])
k_multi, err_multi = run([0, 3, 6])
assert (k_point, k_multi) == (65, 35)
assert err_multi < 0.5 * err_point
History
CLEAN with point components had trouble with extended sources from the start. Cornwell (2008) gave the multiscale form used in radio astronomy today: smoothed residuals at a few scales, cross-scale beams that keep them exact, and a choice of scale with a bias. Rau and Cornwell (2011) combined it with a spectral model for wide-band data.
References
- T. J. Cornwell, Multiscale CLEAN deconvolution of radio synthesis images, IEEE Journal of Selected Topics in Signal Processing 2(5), 2008, pages 793 to 801 (the scale functions, the smoothed residuals, the cross-scale beams and the choice of scale)
- U. Rau and T. J. Cornwell, A multi-scale multi-frequency deconvolution algorithm for synthesis imaging in radio interferometry, Astronomy and Astrophysics 532, A71, 2011, the article (multiscale components combined with a spectral model over a wide band)
- A. Richard Thompson, James M. Moran and George W. Swenson Jr., Interferometry and Synthesis in Radio Astronomy, third edition, Springer, 2017, Chapter 11, Further Imaging Techniques (CLEAN and its variants)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag KXJYFX Edit this page History Report an error Markdown