Algorithm Search⌘K

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.

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
Properties
deterministicgreedyiterativenot linearmonotone misfitnot nonnegative
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 xx lives on a periodic grid of nn pixels. The array measures the visibilities V=x^V = \hat x at the frequencies with weight wk>0w_k > 0, with w−k=wkw_{-k} = w_k and W=∑kwkW = \sum_k w_k. The dirty beam is B=1WF−1(n w)B = \frac1W \mathcal F^{-1}(n\,w), so B0=1B_0 = 1, and the dirty image is D=B∗xD = B \ast x. The misfit of a model MM is

Q(M)=1W∑kwk ∣Vk−M^k∣2.Q(M) = \frac1W \sum_k w_k\, |V_k - \hat M_k|^2 .

The input also has ss scale functions ϕ0,…,ϕs−1\phi_0, \ldots, \phi_{s-1}. Each is real, has unit sum and is symmetric, ϕ(−q)=ϕ(q)\phi(-q) = \phi(q), and ϕ0=δ\phi_0 = \delta is the point. The code uses ϕ(q)∝1−∣q∣2/a2\phi(q) \propto 1 - |q|^2/a^2 for ∣q∣<a|q| < a, a truncated parabola of radius aa pixels. The output is a model M=∑jcj ϕsj(⋅−pj)M = \sum_j c_j\, \phi_{s_j}(\cdot - p_j) and the residual R=D−B∗MR = D - B \ast M.

The algorithm

Write It=ϕt∗RI_t = \phi_t \ast R for the residual smoothed at scale tt, and But=ϕu∗ϕt∗BB_{ut} = \phi_u \ast \phi_t \ast B for the cross-scale beams. A blob of scale uu at pixel pp with flux cc changes ItI_t by −c But(⋅−p)-c\,B_{ut}(\cdot - p).

  1. MULTISCALE-CLEAN(D, B, φ_0..φ_{s-1}, g, τ, K) ▷ φ_0 = δ
  2. 1I_t ← φ_t ∗ D for every scale t, M ← 0
  3. 2B_ut ← φ_u ∗ φ_t ∗ B for every pair of scales u, t
  4. 3for k ← 1 to K do
  5. 4(u, p) ← the scale and pixel with the largest |I_u(p)| / √B_uu(0)
  6. 5if |I_u(p)| ≤ τ then break
  7. 6c ← g I_u(p) / B_uu(0)
  8. 7M ← M + c φ_u(· - p) ▷ a blob of scale u at p
  9. 8I_t(q) ← I_t(q) - c B_ut(q - p) for every scale t and pixel q
  10. 9return M, I_0 ▷ I_0 = R, the residual

Line L8 keeps every ItI_t equal to ϕt∗(D−B∗M)\phi_t \ast (D - B \ast M), so the smoothed residuals never need to be computed again. Line L4 is the greedy rule: a step at (u,p)(u, p) lowers QQ by (2g−g2) Iu(p)2/Buu(0)(2g - g^2)\, I_u(p)^2 / B_{uu}(0), and L4 picks the largest such drop. A large blob has a small Buu(0)B_{uu}(0), because it is seen only by the short baselines, so dividing by Buu(0)\sqrt{B_{uu}(0)} 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 n=32n = 32 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 0,±1,±2,±3,±5,±7,±100, \pm1, \pm2, \pm3, \pm5, \pm7, \pm10. The scales have radii 00 (the point), 33 and 66 pixels, with Buu(0)=1B_{uu}(0) = 1, 0.45490.4549 and 0.24870.2487. At the start the smoothed peaks are 2.00852.0085, 1.56461.5646 and 1.11061.1106, and the scores ∣Iu(p)∣/Buu(0)|I_u(p)| / \sqrt{B_{uu}(0)} are 2.00852.0085, 2.31982.3198 and 2.22712.2271. So the first step takes the radius-3 blob, although the point scale has the highest peak. With g=0.3g = 0.3 and Q(0)=6.3975Q(0) = 6.3975:

step scale radius pixel Iu(p)I_u(p) flux cc QQ 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 max⁡q∣Rq∣\max_q |R_q| 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 0.4820.482. Multiscale CLEAN needs 35 components (18 points, 10 blobs of radius 3 and 7 of radius 6), and its largest error is 0.1460.146. 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 ψ=ϕu(⋅−p)\psi = \phi_u(\cdot - p), expanding the square gives the exact identity

Q(M+c ψ)=Q(M)−2c Iu(p)+c2Buu(0),Q(M + c\,\psi) = Q(M) - 2c\, I_u(p) + c^2 B_{uu}(0),

because the inner product of ψ\psi with the residual is (ϕu∗R)(p)(\phi_u \ast R)(p) when ϕu\phi_u is symmetric, and 1W∑kwk∣ϕ^u(k)∣2=Buu(0)\frac1W \sum_k w_k |\hat\phi_u(k)|^2 = B_{uu}(0). With c=g Iu(p)/Buu(0)c = g\, I_u(p) / B_{uu}(0) the drop is (2g−g2)Iu(p)2/Buu(0)>0(2g - g^2) I_u(p)^2 / B_{uu}(0) > 0 for 0<g<20 < g < 2. Because the point scale is in the dictionary, the chosen score is at least max⁡q∣Rq∣\max_q |R_q| times a fixed positive constant. The drops have a finite sum, so max⁡q∣Rq∣→0\max_q |R_q| \to 0 and Q→0Q \to 0: 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 nn pixels (read indices as 2D for an image), the DFT y^k=∑qyqe−2πikq/n\hat y_k = \sum_q y_q e^{-2\pi i kq/n}, a real sky xx with V=x^V = \hat x, weights wk≥0w_k \ge 0 with w−k=wkw_{-k} = w_k and W=∑kwk>0W = \sum_k w_k > 0, the dirty beam Bq=1W∑kwke2πikq/nB_q = \frac1W \sum_k w_k e^{2\pi i kq/n} (real, B0=1B_0 = 1), and the dirty image D=B∗xD = B \ast x. The misfit is Q(M)=1W∑kwk∣Vk−M^k∣2Q(M) = \frac1W \sum_k w_k |V_k - \hat M_k|^2. The scale functions ϕ0=δ,ϕ1,…,ϕs−1\phi_0 = \delta, \phi_1, \ldots, \phi_{s-1} are real and symmetric, ϕu(−q)=ϕu(q)\phi_u(-q) = \phi_u(q). Write R=D−B∗MR = D - B \ast M, It=ϕt∗RI_t = \phi_t \ast R and But=ϕu∗ϕt∗BB_{ut} = \phi_u \ast \phi_t \ast B. The loop is lines L1 to L9 with τ=0\tau = 0.

From the Hogbom page (Claim 1 there), for every model MM,

Rq=1W∑kwk(Vk−M^k)e2πikq/n.(1)R_q = \frac1W \sum_k w_k (V_k - \hat M_k) e^{2\pi i kq/n}. \tag{1}

Claim 1 (the smoothed residuals stay exact). After every step, It=ϕt∗(D−B∗M)I_t = \phi_t \ast (D - B \ast M) for every scale tt. In particular I0=RI_0 = R.

Proof. Line L1 makes it true with M=0M = 0. A step adds c ϕu(⋅−p)=c ϕu∗δpc\,\phi_u(\cdot - p) = c\,\phi_u \ast \delta_p to MM, which changes ϕt∗(D−B∗M)\phi_t \ast (D - B \ast M) by −c ϕt∗B∗ϕu∗δp=−c But(⋅−p)-c\,\phi_t \ast B \ast \phi_u \ast \delta_p = -c\,B_{ut}(\cdot - p), since periodic convolution is commutative and associative. Line L8 makes exactly this change to ItI_t. □\square

Claim 2 (the cost of a step). Let ψ=ϕu(⋅−p)\psi = \phi_u(\cdot - p). For every real cc,

Q(M+c ψ)=Q(M)−2c Iu(p)+c2Buu(0).Q(M + c\,\psi) = Q(M) - 2c\, I_u(p) + c^2 B_{uu}(0).

Proof. ψ^k=ϕ^u(k)e−2πikp/n\hat\psi_k = \hat\phi_u(k) e^{-2\pi i kp/n}, and ϕ^u(k)\hat\phi_u(k) is real because ϕu\phi_u is real and symmetric. Expanding the square as on the Hogbom page,

Q(M+cψ)=Q(M)−2cWRe∑kwk(Vk−M^k) ϕ^u(k) e2πikp/n+c2W∑kwk ϕ^u(k)2.Q(M + c\psi) = Q(M) - \frac{2c}{W} \mathrm{Re} \sum_k w_k (V_k - \hat M_k)\, \hat\phi_u(k)\, e^{2\pi i kp/n} + \frac{c^2}{W} \sum_k w_k\, \hat\phi_u(k)^2 .

By (1) and the convolution theorem, 1W∑kwk(Vk−M^k)ϕ^u(k)e2πikq/n=(ϕu∗R)q=Iu(q)\frac1W \sum_k w_k (V_k - \hat M_k) \hat\phi_u(k) e^{2\pi i kq/n} = (\phi_u \ast R)_q = I_u(q), which is real; take q=pq = p. The DFT of BB is B^k=nwk/W\hat B_k = n w_k / W, so Buu(0)=1n∑kϕ^u(k)2B^k=1W∑kwkϕ^u(k)2B_{uu}(0) = \frac1n \sum_k \hat\phi_u(k)^2 \hat B_k = \frac1W \sum_k w_k \hat\phi_u(k)^2. □\square

Buu(0)≥0B_{uu}(0) \ge 0, and the code requires Buu(0)>0B_{uu}(0) > 0: the scale must have some weight on the measured frequencies. For u=0u = 0, B00(0)=B0=1B_{00}(0) = B_0 = 1.

Claim 3 (the drop). With c=g Iu(p)/Buu(0)c = g\, I_u(p) / B_{uu}(0) (line L6),

Q(M)−Q(M+cψ)=(2g−g2) Iu(p)2Buu(0)=2−gg c2Buu(0).Q(M) - Q(M + c\psi) = (2g - g^2)\, \frac{I_u(p)^2}{B_{uu}(0)} = \frac{2 - g}{g}\, c^2 B_{uu}(0).

Proof. Substitute cc in Claim 2. □\square

So for 0<g<20 < g < 2 every step lowers QQ unless Iu(p)=0I_u(p) = 0, and line L4 (with no bias) picks the pair (u,p)(u, p) with the largest drop.

Claim 4 (convergence). Let 0<g<20 < g < 2, τ=0\tau = 0, and let line L4 maximize βu∣Iu(p)∣/Buu(0)\beta_u |I_u(p)| / \sqrt{B_{uu}(0)} with fixed weights βu>0\beta_u > 0 (no bias is βu=1\beta_u = 1). Then max⁡q∣Rq∣→0\max_q |R_q| \to 0, Q(M)→0Q(M) \to 0, and M^k→Vk\hat M_k \to V_k at every measured frequency.

Proof. Let βmax⁡=max⁡uβu\beta_{\max} = \max_u \beta_u and b=max⁡uBuu(0)b = \max_u B_{uu}(0). At the step that picks (u,p)(u, p), the choice of line L4 gives, for every pixel qq and using the point scale,

βu∣Iu(p)∣Buu(0)≥β0∣I0(q)∣B00(0)=β0∣Rq∣,\beta_u \frac{|I_u(p)|}{\sqrt{B_{uu}(0)}} \ge \beta_0 \frac{|I_0(q)|}{\sqrt{B_{00}(0)}} = \beta_0 |R_q|,

so Iu(p)2/Buu(0)≥(β0/βmax⁡)2max⁡qRq2I_u(p)^2 / B_{uu}(0) \ge (\beta_0 / \beta_{\max})^2 \max_q R_q^2. By Claim 3, each step lowers QQ by at least (2g−g2)(β0/βmax⁡)2max⁡qRq2(2g - g^2)(\beta_0 / \beta_{\max})^2 \max_q R_q^2. Since Q≥0Q \ge 0 these amounts have a finite sum, so max⁡q∣Rq∣→0\max_q |R_q| \to 0 along the iterations. By (1), RR is a fixed invertible linear map of the vector (wk(Vk−M^k))k(w_k (V_k - \hat M_k))_k, so each wk(Vk−M^k)→0w_k (V_k - \hat M_k) \to 0, and Q→0Q \to 0 as on the Hogbom page. □\square

Claim 5 (one scale is Hogbom CLEAN). If the only scale is ϕ0=δ\phi_0 = \delta, then I0=RI_0 = R, B00=BB_{00} = B, the score in line L4 is ∣Rp∣|R_p|, and lines L6 to L8 are lines L5 to L7 of Hogbom CLEAN.

Proof. δ∗δ∗B=B\delta \ast \delta \ast B = B and δ∗R=R\delta \ast R = R. □\square

What is not claimed. The set of models with Q=0Q = 0 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 MM 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 ϕu\phi_u is not symmetric, ϕ^u(k)\hat\phi_u(k) is complex and Iu(p)I_u(p) is no longer the inner product of the blob with the residual, so Claim 2 fails.

Complexity

Lines L1 and L2 take Θ(s2nlog⁡n)\Theta(s^2 n \log n) time with the FFT and Θ(s2n)\Theta(s^2 n) space for the cross beams; by symmetry But=BtuB_{ut} = B_{tu}, so half of them suffice. Each iteration scans ss smoothed images and updates them, so it takes Θ(sn)\Theta(sn) time, and KK iterations take Θ(Ksn)\Theta(Ksn). The number of iterations is what matters: on extended emission, KK is much smaller than for Hogbom CLEAN, which pays for the factor ss.

Properties

  • The misfit never rises for 0<g<20 < g < 2, with the exact drop (2g−g2)Iu(p)2/Buu(0)(2g - g^2) I_u(p)^2 / B_{uu}(0).
  • Hogbom CLEAN is the case of one scale. With only ϕ0=δ\phi_0 = \delta, 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. Buu(0)B_{uu}(0) is the weighted power of ϕ^u\hat\phi_u on the measured frequencies. If the shortest baselines are missing, a large blob is barely seen, and the step cc 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 Buu(0)>0B_{uu}(0) > 0.
  • 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 Buu(0)B_{uu}(0), and the method puts large, poorly determined flux into it.
  • No point scale. Without ϕ0=δ\phi_0 = \delta the residual cannot reach zero at a point source, and the proof fails.
  • Scales that are not symmetric. The identity uses ϕ(−q)=ϕ(q)\phi(-q) = \phi(q); 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 ∣Iu(p)∣|I_u(p)| 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.

imgkit.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example