Algorithm Search⌘K

Algorithmcore

Hogbom CLEAN

Also called CLEAN algorithm.

Deconvolve a dirty image: find the largest residual pixel, add a point of gain times that value to the model, subtract the shifted dirty beam, and repeat.

Time
Θ(K n) worst · average · best
Space
Θ(n) extra
Where
K = the number of iterations; n = the number of pixels
Properties
deterministicgreedyiterativenot linearmonotone misfitnot nonnegative
Origin
Jan Hogbom, 1974

Hogbom CLEAN removes the sidelobes of the dirty beam from a dirty image made by a radio interferometer. It finds the largest pixel of the residual image, adds a point source with a fraction gg of that value to a model, subtracts the dirty beam shifted to that pixel and scaled by the same amount, and repeats. On the data it is greedy coordinate descent on the misfit to the measured visibilities, so the misfit goes down at every step for 0<g<20 < g < 2. It is the first and simplest member of its family: Cotton-Schwab CLEAN does the subtraction on the visibilities in major cycles, and multiscale CLEAN uses smooth blobs of several sizes in place of points.

In plain words

A radio telescope array does not take a picture directly. It gives a blurred picture in which each bright point has a pattern of rings and stripes around it. The pattern is the same for every point, and it is known. CLEAN uses this fact. It looks for the brightest spot in the picture and assumes that a point source is there. It removes a small part of the known pattern at that place, and it writes down the position and the amount it removed. Then it looks again. After many steps, the list of points explains the bright parts of the picture, and what is left is mostly noise. For the final picture, CLEAN draws each point as a small smooth spot with no rings, and adds back what is left.

The problem

The sky is an image xx on a periodic grid of nn pixels. The formulas below use a 1D index qq; an image is the same with a 2D index and the 2D DFT. The visibilities are V=FxV = \mathcal F x, the DFT Vk=∑qxqe−2πikq/nV_k = \sum_q x_q e^{-2\pi i kq/n}. The interferometer measures them only at some frequencies kk, with weights wk≥0w_k \ge 0, w−k=wkw_{-k} = w_k and W=∑kwk>0W = \sum_k w_k > 0. The dirty beam and the dirty image are

Bq=1W∑kwk e2πikq/n,Dq=1W∑kwkVk e2πikq/n.B_q = \frac{1}{W} \sum_k w_k\, e^{2\pi i kq/n}, \qquad D_q = \frac{1}{W} \sum_k w_k V_k\, e^{2\pi i kq/n}.

The beam is real, has B0=1B_0 = 1 and is the point spread function of the array. By the convolution theorem, D=B∗xD = B \ast x (periodic convolution).

The input is DD, BB, a loop gain gg, a threshold τ≥0\tau \ge 0 and a maximum number of iterations KK. The output is a model MM, which is a list of point components, and the residual R=D−B∗MR = D - B \ast M. The aim is a small residual. CLEAN cannot find xx itself: the frequencies with wk=0w_k = 0 are not measured, so many skies give the same dirty image. It finds one model, built from few points, that explains the measured data.

The algorithm

  1. HOGBOM-CLEAN(D, B, g, τ, K) ▷ B is centered at index 0, B_0 > 0
  2. 1R ← D, M ← 0
  3. 2for k ← 1 to K do
  4. 3p ← a pixel with the largest |R_p|
  5. 4if |R_p| ≤ τ then break
  6. 5c ← g R_p / B_0
  7. 6M_p ← M_p + c ▷ a point component of flux c at p
  8. 7R_q ← R_q - c B_{q-p} for every pixel q ▷ indices mod n
  9. 8return M, R
  10. RESTORE(M, R, C) ▷ C is the clean beam
  11. 9return C ∗ M + R

Line L7 keeps the invariant R=D−B∗MR = D - B \ast M. The loop gain gg is a tuned choice; values from 0.050.05 to 0.30.3 are common, and 0.10.1 is a usual default. A small gain lets a later peak take flux that a sidelobe of a near source has moved, at the cost of more iterations. The threshold is set to a few times the noise level of the image, so that CLEAN stops before it fits the noise.

RESTORE makes the image that astronomers look at. The clean beam CC is usually a Gaussian fitted to the main lobe of the dirty beam. Convolving the components with it gives a smooth image at the resolution of the array, without the sidelobes. The residual is added back so that sources that CLEAN did not reach, and the noise, stay visible.

Two common options restrict line L3. A window (a "clean box") allows only pixels in a mask that the user believes hold emission. A positive option takes the largest RpR_p and stops when it is not positive, for skies that are known to be nonnegative.

Example

Take n=16n = 16 and a 1D sky with x4=1x_4 = 1 and x7=0.6x_7 = 0.6. The array measures the frequencies 0,±1,±2,±3,±50, \pm 1, \pm 2, \pm 3, \pm 5 with weight 11, so W=9W = 9. The dirty beam has B0=1B_0 = 1, B±1=0.4736B_{\pm 1} = 0.4736 and B8=−1/3B_8 = -1/3, a deep negative sidelobe. The dirty image has its peak D4=1.0234D_4 = 1.0234, and D7=0.639D_7 = 0.639. With g=0.5g = 0.5 and the misfit Q(M)=1W∑kwk∣Vk−M^k∣2Q(M) = \frac1W \sum_k w_k |V_k - \hat M_k|^2, which starts at 1.40681.4068:

step pixel pp RpR_p flux cc QQ after the step
1 4 1.0234 0.5117 0.6213
2 7 0.6191 0.3095 0.3339
3 4 0.4996 0.2498 0.1467
4 7 0.2998 0.1499 0.0793
5 4 0.2440 0.1220 0.0346
6 7 0.1451 0.0726 0.0188

Each drop of QQ is exactly (2g−g2)Rp2=0.75 Rp2(2g - g^2) R_p^2 = 0.75\, R_p^2; for step 1 that is 0.75⋅1.02342=0.7855=1.4068−0.62130.75 \cdot 1.0234^2 = 0.7855 = 1.4068 - 0.6213. After 8 steps the model is M4=0.9431M_4 = 0.9431 and M7=0.5671M_7 = 0.5671, and after 80 steps it equals the sky to 9 digits. The number of steps to bring max⁡q∣Rq∣\max_q |R_q| below 0.010.01 depends on the gain: 81 for g=0.1g = 0.1, 13 for 0.50.5, 3 for 1.01.0, 13 for 1.51.5 and 81 for 1.91.9. With g=2.1g = 2.1 the residual grows past 10810^8 in 200 steps.

Here the model also tends to the true sky. That is not guaranteed in general: the theorem below says only that the model comes to fit the measured frequencies.

Correctness

Let Q(M)=1W∑kwk∣Vk−M^k∣2Q(M) = \frac{1}{W} \sum_k w_k |V_k - \hat M_k|^2 be the misfit of the model to the measured visibilities. The residual is the negative half gradient of QQ: Rp=−12 ∂Q/∂MpR_p = -\tfrac12\, \partial Q / \partial M_p. Adding cc at pixel pp changes the misfit by an exact identity,

Q(M+c δp)=Q(M)−2cRp+c2B0.Q(M + c\,\delta_p) = Q(M) - 2c R_p + c^2 B_0 .

With c=gRp/B0c = g R_p / B_0 the drop is (2g−g2)Rp2/B0(2g - g^2) R_p^2 / B_0, which is positive for 0<g<20 < g < 2 and Rp≠0R_p \ne 0. The value c=Rp/B0c = R_p / B_0 of g=1g = 1 minimizes QQ along the coordinate pp, so CLEAN is greedy coordinate descent with a damped step, and line L3 is the rule that picks the coordinate with the largest gradient. Because Q≥0Q \ge 0, the drops have a finite sum, so max⁡q∣Rq∣→0\max_q |R_q| \to 0. Since the DFT is invertible, M^k→Vk\hat M_k \to V_k at each measured frequency, and Q→0Q \to 0. With g>2g > 2 the identity gives a rise, and the iteration can diverge. The full proof is below.

Proof: Hogbom CLEAN is greedy coordinate descent on the visibility misfit, and its residual tends to zero for 0 < g < 2full

Setting. The grid is periodic with nn pixels and a 1D index; for an image read every index as a 2D index and every DFT as the 2D DFT. The DFT is y^k=∑qyqe−2πikq/n\hat y_k = \sum_q y_q e^{-2\pi i kq/n}. The sky xx is real and V=x^V = \hat x. The weights satisfy wk≥0w_k \ge 0, w−k=wkw_{-k} = w_k and W=∑kwk>0W = \sum_k w_k > 0. The dirty beam and the dirty image are

Bq=1W∑kwke2πikq/n,Dq=1W∑kwkVke2πikq/n.B_q = \frac1W \sum_k w_k e^{2\pi i kq/n}, \qquad D_q = \frac1W \sum_k w_k V_k e^{2\pi i kq/n}.

BB is real because ww is symmetric, and B0=1W∑kwk=1B_0 = \frac1W \sum_k w_k = 1. The model MM is a real image, and the misfit is

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

The loop is lines L1 to L8 with τ=0\tau = 0, no window and no positive option, unless stated. Write M(t)M^{(t)} and R(t)R^{(t)} for the model and the residual after tt steps, and ptp_t, ctc_t for the pixel and the flux of step tt.

Claim 1 (the invariant). After each step, R(t)=D−B∗M(t)R^{(t)} = D - B \ast M^{(t)}, and

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

Proof. At t=0t = 0, R=DR = D and M=0M = 0. Step tt adds ctδptc_t \delta_{p_t} to MM (line L6) and subtracts ctBq−ptc_t B_{q - p_t} from RqR_q (line L7). Since (B∗δp)q=Bq−p(B \ast \delta_p)_q = B_{q-p}, the identity R=D−B∗MR = D - B \ast M is kept. For the formula, (B∗M)q=∑rBq−rMr=1W∑kwk(∑rMre−2πikr/n)e2πikq/n=1W∑kwkM^ke2πikq/n(B \ast M)_q = \sum_r B_{q-r} M_r = \frac1W \sum_k w_k \big(\sum_r M_r e^{-2\pi i kr/n}\big) e^{2\pi i kq/n} = \frac1W \sum_k w_k \hat M_k e^{2\pi i kq/n}. Subtract this from DqD_q. □\square

Claim 2 (one step changes the misfit by an exact amount). For every real cc and pixel pp,

Q(M+c δp)=Q(M)−2c Rp+c2B0,R=D−B∗M.Q(M + c\,\delta_p) = Q(M) - 2c\,R_p + c^2 B_0, \qquad R = D - B \ast M .

Proof. The DFT of c δpc\,\delta_p is c e−2πikp/nc\, e^{-2\pi i kp/n}. Expand ∣a−b∣2=∣a∣2−2 Re(abˉ)+∣b∣2|a - b|^2 = |a|^2 - 2\,\mathrm{Re}(a \bar b) + |b|^2 with a=Vk−M^ka = V_k - \hat M_k and b=c e−2πikp/nb = c\,e^{-2\pi i kp/n}:

Q(M+cδp)=Q(M)−2cW Re∑kwk(Vk−M^k)e2πikp/n+c2W∑kwk.Q(M + c\delta_p) = Q(M) - \frac{2c}{W}\, \mathrm{Re} \sum_k w_k (V_k - \hat M_k) e^{2\pi i kp/n} + \frac{c^2}{W} \sum_k w_k .

By Claim 1 the middle sum is WRpW R_p; it is real because RR is real. The last term is c2B0c^2 B_0. □\square

So QQ is a convex quadratic in MM with ∂Q/∂Mp=−2Rp\partial Q / \partial M_p = -2 R_p and with second derivative 2B02B_0 along each coordinate. The exact minimizer along the coordinate pp is c=Rp/B0c = R_p / B_0, and line L5 takes gg times it. Line L3 picks the coordinate with the largest ∣∂Q/∂Mp∣|\partial Q / \partial M_p|. This is coordinate descent with the greedy (Gauss-Southwell) rule and a damped step.

Claim 3 (the drop). With c=gRp/B0c = g R_p / B_0,

Q(M)−Q(M+c δp)=(2g−g2) Rp2B0.Q(M) - Q(M + c\,\delta_p) = (2g - g^2)\, \frac{R_p^2}{B_0} .

For 0<g<20 < g < 2 this is ≥0\ge 0, and >0> 0 when Rp≠0R_p \ne 0. For g=2g = 2 it is 00, and for g>2g > 2 it is negative, so QQ rises.

Proof. Put c=gRp/B0c = g R_p / B_0 in Claim 2: −2cRp+c2B0=(−2g+g2)Rp2/B0-2cR_p + c^2 B_0 = (-2g + g^2) R_p^2 / B_0. □\square

Claim 4 (convergence). Let 0<g<20 < g < 2, τ=0\tau = 0 and no window. Then max⁡q∣Rq(t)∣→0\max_q |R^{(t)}_q| \to 0 and Q(M(t))→0Q(M^{(t)}) \to 0 as t→∞t \to \infty. In particular M^k(t)→Vk\hat M^{(t)}_k \to V_k at every frequency with wk>0w_k > 0.

Proof. By Claim 3 and Q≥0Q \ge 0,

(2g−g2)∑t≥0(Rpt+1(t))2B0≤Q(0)<∞,(2g - g^2) \sum_{t \ge 0} \frac{\big(R^{(t)}_{p_{t+1}}\big)^2}{B_0} \le Q(0) < \infty,

so Rpt+1(t)→0R^{(t)}_{p_{t+1}} \to 0. Line L3 picks the largest ∣Rq∣|R_q|, so max⁡q∣Rq(t)∣=∣Rpt+1(t)∣→0\max_q |R^{(t)}_q| = |R^{(t)}_{p_{t+1}}| \to 0. By Claim 1, R(t)R^{(t)} is the inverse DFT of nWwk(Vk−M^k(t))\frac{n}{W} w_k (V_k - \hat M^{(t)}_k). The inverse DFT is a fixed invertible linear map, so each wk(Vk−M^k(t))→0w_k (V_k - \hat M^{(t)}_k) \to 0. Each term of QQ is 1Wwk∣Vk−M^k∣2=1Wwk∣wk(Vk−M^k)∣2\frac1W w_k |V_k - \hat M_k|^2 = \frac{1}{W w_k} |w_k(V_k - \hat M_k)|^2 when wk>0w_k > 0 and 00 when wk=0w_k = 0, so Q(M(t))→0Q(M^{(t)}) \to 0. □\square

Claim 4 is about the data, not the sky. The set of models with Q=0Q = 0 is xx plus every image whose DFT is zero on the measured frequencies, and CLEAN may approach any point of it, or no single point (the theorem does not say that M(t)M^{(t)} itself converges).

Claim 5 (with a window). Let the window be a set SS of pixels, and let line L3 pick the largest ∣Rq∣|R_q| over q∈Sq \in S. For 0<g<20 < g < 2 and τ=0\tau = 0, max⁡q∈S∣Rq(t)∣→0\max_{q \in S} |R^{(t)}_q| \to 0, and Q(M(t))Q(M^{(t)}) tends to the least value of QQ over the models that are zero outside SS.

Proof. The first part is the proof of Claim 4 with the maximum over SS. Restricted to the models mm that are zero outside SS, QQ is a convex quadratic f(m)=Q(0)−2⟨d,m⟩+⟨m,Hm⟩f(m) = Q(0) - 2\langle d, m\rangle + \langle m, Hm\rangle, with HH symmetric and positive semidefinite (the restriction of BB as a matrix Bq−rB_{q-r}, q,r∈Sq, r \in S, which is positive semidefinite because its eigenvalues on the full grid are nwk/W≥0n w_k / W \ge 0). Its gradient is −2R∣S-2 R|_S. A convex quadratic that is bounded below has dd in the range of HH, and then f(m)−min⁡f=⟨Hm−d,H+(Hm−d)⟩≤∥R∣S∥2/λf(m) - \min f = \langle Hm - d, H^{+}(Hm - d)\rangle \le \|R|_S\|^2 / \lambda, where λ\lambda is the smallest nonzero eigenvalue of HH. The right side tends to 00. □\square

Claim 6 (full coverage). If wk=1w_k = 1 for every kk, then B=δ0B = \delta_0 and D=xD = x. With g=1g = 1, CLEAN stops after as many steps as xx has nonzero pixels, with M=xM = x and R=0R = 0 (with τ\tau above round-off). With g≠1g \ne 1 each component is reached geometrically: the residual at pp is multiplied by 1−g1 - g at each visit, which tends to 00 exactly when ∣1−g∣<1|1 - g| < 1, that is 0<g<20 < g < 2.

Proof. Bq=1n∑ke2πikq/n=δq,0B_q = \frac1n \sum_k e^{2\pi i kq/n} = \delta_{q,0}, so D=xD = x and line L7 changes only RpR_p, to Rp−gRp=(1−g)RpR_p - g R_p = (1 - g)R_p. With g=1g = 1 each visited pixel becomes 00 and is never visited again, and MpM_p gets the full value xpx_p. □\square

Claim 6 shows that the range 0<g<20 < g < 2 of Claim 4 cannot be widened: for g≥2g \ge 2 a single point source with full coverage gives ∣Rp∣≥∣xp∣|R_p| \ge |x_p| at every step.

Restoring. RESTORE (line L9) is a convolution and an addition, and makes no claim of optimality. With the invariant of Claim 1 the restored image is C∗M+D−B∗MC \ast M + D - B \ast M, so it equals DD plus (C−B)∗M(C - B) \ast M: the components with the dirty beam replaced by the clean beam.

Complexity

Line L3 scans the nn pixels and line L7 updates them, so each iteration takes Θ(n)\Theta(n) time and KK iterations take Θ(Kn)\Theta(Kn). The extra space is Θ(n)\Theta(n) for RR and MM. The number of iterations is the real cost: with 0<g≤10 < g \le 1, an isolated point source of flux FF needs about log⁡(F/τ)/log⁡(1/(1−g))\log(F/\tau) / \log(1/(1-g)) steps to get below the threshold τ\tau, and an extended source needs many components, each at this cost. Forming the dirty image and beam with the FFT takes Θ(nlog⁡n)\Theta(n \log n) once, and RESTORE is one more convolution.

Clark (1980) cut the cost of line L7 by subtracting only a small patch of the beam in fast minor cycles, and then recomputing the exact residual with the FFT in a major cycle.

Properties

  • Nonlinear. The choice of pixel in line L3 depends on the data, so CLEAN of a sum of two skies is not the sum of the two results.
  • Greedy and sparse. The model holds only pixels that were the peak at some step. For a few point sources, it is a few points.
  • The misfit never rises for 0<g<20 < g < 2. The drop at each step is (2g−g2)Rp2/B0(2g - g^2) R_p^2 / B_0.
  • Not unique. The model fits the measured frequencies, and the unmeasured frequencies are whatever the greedy path left there. Another gain or another tie break gives another model.
  • No noise model. CLEAN fits the data as it is. Only the threshold keeps it from fitting the noise.

Variants and improvements

  • Clark CLEAN. Minor cycles with a beam patch and the brightest pixels only, then a major cycle with the FFT. See the complexity section.
  • Cotton-Schwab CLEAN. Each major cycle subtracts the model from the visibilities themselves, so gridding errors and wide-field effects such as the ww term (see W-projection) do not build up.
  • Multiscale CLEAN. Components are smooth blobs of several widths, which fit extended emission with far fewer components than points.
  • Positive CLEAN and clean boxes. Only positive components, or only pixels inside a mask. These add prior knowledge and reduce spurious components.
  • Other priors. The maximum entropy method fits the same data with a smooth positive image in place of a few points.

When to use it

Use Hogbom CLEAN on a dirty image of a field that holds mostly compact sources, when the dirty beam is known and the same over the field. It is simple, fast for a small image, and its result is easy to inspect: a list of components. For large images use the Clark or Cotton-Schwab form, which give the same kind of result with cheaper iterations. For smooth extended emission, use multiscale CLEAN or a regularized method, because point components fit it badly.

Pitfalls

  • A gain of 2 or more. The misfit does not go down, and for g>2g > 2 the residual grows without bound. Even a gain near 1 can put flux on a sidelobe of a near source, and later steps must then correct it.
  • Cleaning into the noise. With τ=0\tau = 0 CLEAN puts components on noise peaks. Set the threshold to a few times the noise level.
  • A beam that is too small. To subtract a source at any pixel from every pixel of the image, the beam must cover twice the image size in each direction. A beam of the image size, as on the periodic grid here, wraps the sidelobes around the edges.
  • Extended emission. Point components on a smooth source give a mottled model, and at times regular stripes. Multiscale CLEAN or a smaller gain help.
  • Mixed units in the restored image. The model is convolved with the clean beam, but the residual still has the dirty beam. When the two beams have very different areas, the flux of faint emission in the restored image is wrong.

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.

hogbom_clean.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hogbom-clean/. The authors are listed in prov/0ZFP8H.jsonl.
"""Hogbom CLEAN on a periodic grid.

Images are lists of rows, img[i][j]. A 1D signal is a 1 x n image. The dirty
beam has the same size as the image and its center at index (0, 0), wrapped
around, so a beam that is a delta at (0, 0) gives the identity. On this grid
the dirty image is exactly the periodic convolution of the sky with the
dirty beam, when both come from the same gridded uv weights.
"""

import math

from imgkit import circ_conv2, dft2, idft2, new_image


def dirty_beam(weights):
    """The dirty beam of gridded uv weights w[k][l] >= 0, scaled to peak 1.

    The weights must be symmetric, w[-k][-l] = w[k][l], so that the beam is real.
    """
    total = sum(sum(row) for row in weights)
    b = idft2(weights)
    n1, n2 = len(weights), len(weights[0])
    s = n1 * n2 / total
    return [[(v * s).real for v in row] for row in b]


def dirty_image(sky, weights):
    """The dirty image of a sky: the inverse DFT of the weighted visibilities, scaled like the beam."""
    total = sum(sum(row) for row in weights)
    vis = dft2(sky)
    n1, n2 = len(sky), len(sky[0])
    s = n1 * n2 / total
    prod = [[w * v for w, v in zip(rw, rv)] for rw, rv in zip(weights, vis)]
    return [[(v * s).real for v in row] for row in idft2(prod)]


def data_misfit(model, sky, weights):
    """Q(M) = (1/W) sum_k w_k |V_k - M^_k|^2 with V = DFT(sky); CLEAN does not increase it for 0 < gain < 2."""
    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 find_peak(r, positive_only=False, window=None):
    """The position (i, j) of the largest |r| (or largest r), inside the window mask if one is given."""
    best, pos = -math.inf, None
    for i, row in enumerate(r):
        for j, v in enumerate(row):
            if window is not None and not window[i][j]:
                continue
            key = v if positive_only else abs(v)
            if key > best:
                best, pos = key, (i, j)
    return pos


def hogbom_clean(dirty, beam, gain=0.1, threshold=0.0, max_iter=1000, positive_only=False, window=None):
    """Deconvolve a dirty image with Hogbom CLEAN.

    Returns (model, residual, components); components is the list of
    (i, j, flux) in the order they were found. The invariant
    residual = dirty - beam * model (periodic convolution) holds after each step.
    """
    n1, n2 = len(dirty), len(dirty[0])
    b0 = beam[0][0]
    if b0 <= 0:
        raise ValueError("the beam peak must be positive")
    r = [list(row) for row in dirty]  # @line L1
    model = new_image(n1, n2)
    comps = []
    for _ in range(max_iter):  # @line L2
        p = find_peak(r, positive_only, window)  # @line L3
        if p is None:
            break
        i0, j0 = p
        peak = r[i0][j0]
        if abs(peak) <= threshold or (positive_only and peak <= 0):  # @line L4
            break
        c = gain * peak / b0  # @line L5
        model[i0][j0] += c  # @line L6
        comps.append((i0, j0, c))
        for i in range(n1):  # @line L7
            bi = beam[(i - i0) % n1]
            ri = r[i]
            for j in range(n2):
                ri[j] -= c * bi[(j - j0) % n2]
    return model, r, comps  # @line L8


def fit_clean_beam(beam):
    """An axis-aligned Gaussian clean beam, peak 1 at (0, 0), matched to the main lobe of the dirty beam.

    The widths come from the beam values next to the peak: b(1, 0) / b(0, 0) = exp(-1 / (2 s1^2))
    and the same for the other axis.
    """
    n1, n2 = len(beam), len(beam[0])
    b0 = beam[0][0]

    def width(nb):
        ratio = nb / b0
        if not 0.0 < ratio < 1.0:
            raise ValueError("the main lobe is not resolved by the grid")
        return math.sqrt(-1.0 / (2.0 * math.log(ratio)))

    s1 = width(0.5 * (beam[1 % n1][0] + beam[-1 % n1][0])) if n1 > 1 else None
    s2 = width(0.5 * (beam[0][1 % n2] + beam[0][-1 % n2])) if n2 > 1 else None
    out = new_image(n1, n2)
    for i in range(n1):
        di = min(i, n1 - i)
        for j in range(n2):
            dj = min(j, n2 - j)
            e = 0.0
            if s1:
                e += di * di / (2 * s1 * s1)
            elif di:
                continue
            if s2:
                e += dj * dj / (2 * s2 * s2)
            elif dj:
                continue
            out[i][j] = math.exp(-e)
    return out


def restore(model, residual, clean_beam):
    """The restored image: the model convolved with the clean beam, plus the residual."""
    smooth = circ_conv2(model, clean_beam)  # @line L9
    return [[a + b for a, b in zip(ra, rb)] for ra, rb in zip(smooth, residual)]
imgkit.py 322 lines
# 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
test_hogbom_clean.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hogbom-clean/. The authors are listed in prov/0ZFP8H.jsonl.

import random

from hogbom_clean import (
    data_misfit,
    dirty_beam,
    dirty_image,
    fit_clean_beam,
    hogbom_clean,
    restore,
)
from imgkit import circ_conv2, new_image


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):
    """Random gridded uv weights, symmetric under (k, l) -> (-k, -l), with the zero spacing measured."""
    w = new_image(n, n)
    w[0][0] = 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 test_page_example_1d():
    w = mask_1d(16, (0, 1, 2, 3, 5))
    sky = [[0.0] * 16]
    sky[0][4], sky[0][7] = 1.0, 0.6
    beam = dirty_beam(w)
    dirty = dirty_image(sky, w)
    assert abs(beam[0][0] - 1.0) < 1e-12
    assert abs(beam[0][8] + 1.0 / 3.0) < 1e-12
    assert abs(dirty[0][4] - 1.0234) < 1e-4
    model, res, comps = hogbom_clean(dirty, beam, gain=0.5, max_iter=4)
    assert [(j, round(c, 4)) for _, j, c in comps] == [(4, 0.5117), (7, 0.3095), (4, 0.2498), (7, 0.1499)]
    model, res, comps = hogbom_clean(dirty, beam, gain=0.5, max_iter=80)
    assert max(abs(a - b) for a, b in zip(model[0], sky[0])) < 1e-9
    assert max_abs(res) < 1e-9


def test_dirty_image_is_beam_convolution():
    rng = random.Random(11)
    w = mask_2d(16, 0.25, rng)
    sky = [[rng.random() if rng.random() < 0.1 else 0.0 for _ in range(16)] for _ in range(16)]
    a = dirty_image(sky, w)
    b = circ_conv2(sky, dirty_beam(w))
    assert max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb)) < 1e-12


def test_residual_invariant_2d():
    rng = random.Random(5)
    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, 2.0)
    beam = dirty_beam(w)
    dirty = dirty_image(sky, w)
    model, res, comps = hogbom_clean(dirty, beam, gain=0.2, max_iter=60)
    pred = circ_conv2(model, beam)
    gap = max(abs(d - p - r) for rd, rp, rr in zip(dirty, pred, res) for d, p, r in zip(rd, rp, rr))
    assert gap < 1e-10
    assert abs(sum(c for _, _, c in comps) - sum(sum(r) for r in model)) < 1e-10


def test_misfit_drops_by_the_proved_amount():
    rng = random.Random(7)
    w = mask_2d(16, 0.2, rng)
    sky = new_image(16, 16)
    for _ in range(5):
        sky[rng.randrange(16)][rng.randrange(16)] += rng.uniform(0.2, 1.0)
    beam = dirty_beam(w)
    dirty = dirty_image(sky, w)
    for gain in (0.1, 1.0, 1.9):
        model, res = new_image(16, 16), dirty
        q = data_misfit(model, sky, w)
        for _ in range(8):
            m2, r2, comps = hogbom_clean(res, beam, gain=gain, max_iter=1)
            i, j, c = comps[0]
            peak = res[i][j]
            model[i][j] += c
            q2 = data_misfit(model, sky, w)
            assert abs((q - q2) - (2 * gain - gain * gain) * peak * peak) < 1e-9
            assert q2 <= q + 1e-12
            q, res = q2, r2


def test_gain_range():
    rng = random.Random(3)
    w = mask_2d(16, 0.3, rng)
    sky = new_image(16, 16)
    for _ in range(3):
        sky[rng.randrange(16)][rng.randrange(16)] += 1.0
    beam = dirty_beam(w)
    dirty = dirty_image(sky, w)
    start = max_abs(dirty)
    _, res, _ = hogbom_clean(dirty, beam, gain=0.5, max_iter=300)
    assert max_abs(res) < 1e-3 * start
    _, res, _ = hogbom_clean(dirty, beam, gain=2.2, max_iter=60)
    assert max_abs(res) > 10 * start


def test_full_coverage_gives_the_sky():
    n = 8
    w = new_image(n, n, 1.0)
    beam = dirty_beam(w)
    assert abs(beam[0][0] - 1.0) < 1e-12 and abs(beam[3][5]) < 1e-12
    sky = new_image(n, n)
    sky[1][2], sky[5][6], sky[7][0] = 3.0, -1.0, 2.0
    model, res, comps = hogbom_clean(dirty_image(sky, w), beam, gain=1.0, threshold=1e-9, max_iter=10)
    assert len(comps) == 3
    assert max(abs(a - b) for ra, rb in zip(model, sky) for a, b in zip(ra, rb)) < 1e-12


def test_threshold_positive_and_window():
    rng = random.Random(9)
    w = mask_2d(16, 0.3, rng)
    sky = new_image(16, 16)
    sky[4][4], sky[10][12] = 1.0, 0.5
    beam = dirty_beam(w)
    dirty = dirty_image(sky, w)
    _, res, comps = hogbom_clean(dirty, beam, gain=0.1, threshold=0.05, max_iter=5000)
    assert max_abs(res) <= 0.05 + 1e-12
    _, _, comps = hogbom_clean(dirty, beam, gain=0.1, positive_only=True, max_iter=200)
    assert all(c > 0 for _, _, c in comps)
    win = [[abs(i - 4) <= 1 and abs(j - 4) <= 1 for j in range(16)] for i in range(16)]
    _, _, comps = hogbom_clean(dirty, beam, gain=0.1, window=win, max_iter=50)
    assert all(abs(i - 4) <= 1 and abs(j - 4) <= 1 for i, j, _ in comps)


def test_restore_point_source():
    rng = random.Random(4)
    w = mask_2d(16, 0.35, rng)
    for k in range(-2, 3):
        for l in range(-2, 3):
            w[k % 16][l % 16] = 1.0
    sky = new_image(16, 16)
    sky[8][8] = 2.0
    beam = dirty_beam(w)
    model, res, _ = hogbom_clean(dirty_image(sky, w), beam, gain=0.2, max_iter=200)
    cb = fit_clean_beam(beam)
    assert cb[0][0] == 1.0 and 0.0 < cb[0][1] < 1.0
    img = restore(model, res, cb)
    assert abs(img[8][8] - 2.0) < 1e-6
    assert abs(sum(sum(r) for r in model) - 2.0) < 1e-6

History

Jan Hogbom described CLEAN in 1974, as a way to make maps from interferometers whose baselines did not fill a regular grid. The dirty beam of such an array has strong sidelobes, and CLEAN removed them by fitting the map with point sources. Schwarz (1978) described CLEAN as a least squares fit of the model to the measured visibilities, which is the view used in the proof here. Clark (1980) split the work into minor and major cycles, and Schwab (1984) moved the major cycle to the visibilities, which gave Cotton-Schwab CLEAN. Cornwell (2008) added several scales in multiscale CLEAN.

References

  1. Hogbom, Aperture synthesis with a non-regular distribution of interferometer baselines, 1974, the whole article (the CLEAN procedure, the clean beam and examples on synthesis maps)
  2. Schwarz, Mathematical-statistical description of the iterative beam removing technique (method CLEAN), 1978, the article (CLEAN as a least squares fit of the model to the measured visibilities)
  3. Clark, An efficient implementation of the algorithm CLEAN, 1980, the article (minor cycles with a small patch of the beam, major cycles with the FFT)
  4. 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 (the section on CLEAN)
  5. Jean-Luc Starck and Fionn Murtagh, Astronomical Image and Data Analysis, second edition, Springer, 2006, the chapter on deconvolution (CLEAN among the iterative methods)

Where this leads

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