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.
- Solves
- Image deblurring
- Time
- Θ(K n) worst · average · best
- Space
- Θ(n) extra
- Where
- K = the number of iterations; n = the number of pixels
- Model
- Real RAM
- Properties
- deterministicgreedyiterativenot linearmonotone misfitnot nonnegative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 . 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 on a periodic grid of pixels. The formulas below use a 1D index ; an image is the same with a 2D index and the 2D DFT. The visibilities are , the DFT . The interferometer measures them only at some frequencies , with weights , and . The dirty beam and the dirty image are
The beam is real, has and is the point spread function of the array. By the convolution theorem, (periodic convolution).
The input is , , a loop gain , a threshold and a maximum number of iterations . The output is a model , which is a list of point components, and the residual . The aim is a small residual. CLEAN cannot find itself: the frequencies with 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
HOGBOM-CLEAN(D, B, g, τ, K) ▷ B is centered at index 0, B_0 > 0- 1
R ← D, M ← 0 - 2
for k ← 1 to K do - 3
p ← a pixel with the largest |R_p| - 4
if |R_p| ≤ τ then break - 5
c ← g R_p / B_0 - 6
M_p ← M_p + c ▷ a point component of flux c at p - 7
R_q ← R_q - c B_{q-p} for every pixel q ▷ indices mod n - 8
return M, R RESTORE(M, R, C) ▷ C is the clean beam- 9
return C ∗ M + R
Line L7 keeps the invariant . The loop gain is a tuned choice; values from to are common, and 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 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 and stops when it is not positive, for skies that are known to be nonnegative.
Example
Take and a 1D sky with and . The array measures the frequencies with weight , so . The dirty beam has , and , a deep negative sidelobe. The dirty image has its peak , and . With and the misfit , which starts at :
| step | pixel | flux | 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 is exactly ; for step 1 that is . After 8 steps the model is and , and after 80 steps it equals the sky to 9 digits. The number of steps to bring below depends on the gain: 81 for , 13 for , 3 for , 13 for and 81 for . With the residual grows past 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 be the misfit of the model to the measured visibilities. The residual is the negative half gradient of : . Adding at pixel changes the misfit by an exact identity,
With the drop is , which is positive for and . The value of minimizes along the coordinate , 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 , the drops have a finite sum, so . Since the DFT is invertible, at each measured frequency, and . With 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 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 . The sky is real and . The weights satisfy , and . The dirty beam and the dirty image are
is real because is symmetric, and . The model is a real image, and the misfit is
The loop is lines L1 to L8 with , no window and no positive option, unless stated. Write and for the model and the residual after steps, and , for the pixel and the flux of step .
Claim 1 (the invariant). After each step, , and
Proof. At , and . Step adds to (line L6) and subtracts from (line L7). Since , the identity is kept. For the formula, . Subtract this from .
Claim 2 (one step changes the misfit by an exact amount). For every real and pixel ,
Proof. The DFT of is . Expand with and :
By Claim 1 the middle sum is ; it is real because is real. The last term is .
So is a convex quadratic in with and with second derivative along each coordinate. The exact minimizer along the coordinate is , and line L5 takes times it. Line L3 picks the coordinate with the largest . This is coordinate descent with the greedy (Gauss-Southwell) rule and a damped step.
Claim 3 (the drop). With ,
For this is , and when . For it is , and for it is negative, so rises.
Proof. Put in Claim 2: .
Claim 4 (convergence). Let , and no window. Then and as . In particular at every frequency with .
Proof. By Claim 3 and ,
so . Line L3 picks the largest , so . By Claim 1, is the inverse DFT of . The inverse DFT is a fixed invertible linear map, so each . Each term of is when and when , so .
Claim 4 is about the data, not the sky. The set of models with is 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 itself converges).
Claim 5 (with a window). Let the window be a set of pixels, and let line L3 pick the largest over . For and , , and tends to the least value of over the models that are zero outside .
Proof. The first part is the proof of Claim 4 with the maximum over . Restricted to the models that are zero outside , is a convex quadratic , with symmetric and positive semidefinite (the restriction of as a matrix , , which is positive semidefinite because its eigenvalues on the full grid are ). Its gradient is . A convex quadratic that is bounded below has in the range of , and then , where is the smallest nonzero eigenvalue of . The right side tends to .
Claim 6 (full coverage). If for every , then and . With , CLEAN stops after as many steps as has nonzero pixels, with and (with above round-off). With each component is reached geometrically: the residual at is multiplied by at each visit, which tends to exactly when , that is .
Proof. , so and line L7 changes only , to . With each visited pixel becomes and is never visited again, and gets the full value .
Claim 6 shows that the range of Claim 4 cannot be widened: for a single point source with full coverage gives 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 , so it equals plus : the components with the dirty beam replaced by the clean beam.
Complexity
Line L3 scans the pixels and line L7 updates them, so each iteration takes time and iterations take . The extra space is for and . The number of iterations is the real cost: with , an isolated point source of flux needs about steps to get below the threshold , and an extended source needs many components, each at this cost. Forming the dirty image and beam with the FFT takes 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 . The drop at each step is .
- 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 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 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 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.
# 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
- 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)
- 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)
- 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)
- 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)
- 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.
| 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 0ZFP8H Edit this page History Report an error Markdown