Algorithm Search⌘K

Algorithmresearch

W-projection

Also called w-term correction.

Correct the non-coplanar baseline term in wide field radio imaging by convolving each visibility with a w-dependent Fresnel kernel during gridding.

Time
Θ(m S^2 + P N log N) worst · average · best
Space
Θ(N + P S^2) extra
Where
N = the number of pixels; P = the number of distinct w values; S = the half-width of the kernel in cells; m = the number of visibilities
Properties
deterministicexact with full kernelgridding is adjoint of degriddingnot iterativelinear
Origin
Tim J. Cornwell, Kumar Golap, Sanjay Bhatnagar, 2008

W-projection makes the dirty image of a wide field from an array whose baselines do not lie in one plane, so that each visibility depends on its height ww as well as on (u,v)(u, v). It writes the ww term of the measurement equation as a convolution in the uvuv plane by a kernel that depends only on ww, applies that kernel while it puts the visibilities on the grid, and then images the whole field with one 2D FFT. The plain dirty image of aperture synthesis drops the ww term and is correct only for a small field. W-projection is not a deconvolution method: Cotton-Schwab CLEAN calls it, and its adjoint, in each major cycle.

In plain words

A radio array measures the sky through pairs of antennas. When the antennas do not lie in one plane, each measurement also carries a focus error that depends on the height difference of the pair, its w value. The error is zero at the center of the image and grows toward the edges, so a plain image blurs and weakens sources far from the center. W-projection removes the error before the image is made. It spreads each measurement over a small patch of grid cells, with a pattern that undoes the focus error for that w. Measurements with the same w use the same pattern, so each pattern is computed once. Then one Fourier transform makes the whole image. A larger patch gives a more accurate image and costs more time. The same patterns, used the other way, turn a sky model into predicted measurements.

The problem

For an incoherent sky with brightness I(l,m)I(l, m) in the direction cosines (l,m)(l, m), a baseline (u,v,w)(u, v, w) in wavelengths measures the visibility

V(u,v,w)=∬I(l,m)ν(l,m) e−2πi (ul+vm+w(ν−1)) dl dm,ν=1−l2−m2.V(u, v, w) = \iint \frac{I(l, m)}{\nu(l, m)}\, e^{-2\pi i\,(ul + vm + w(\nu - 1))}\, dl\, dm, \qquad \nu = \sqrt{1 - l^2 - m^2}.

With w=0w = 0, or with l2+m2l^2 + m^2 small, the last phase vanishes and VV is the 2D Fourier transform of I/νI / \nu, which is the Van Cittert-Zernike theorem. The dropped phase is 2πw(ν−1)≈−πw(l2+m2)2\pi w(\nu - 1) \approx -\pi w (l^2 + m^2). It is small only when ∣w∣ (l2+m2)≪1|w|\,(l^2 + m^2) \ll 1 over the field, which fails for long baselines, low frequencies and wide fields.

The discrete form used on this page has n×nn \times n pixels with signed offsets p=(a,b)p = (a, b), −n/2≤a,b<n/2-n/2 \le a, b < n/2, and l=b Δll = b\,\Delta l, m=a Δlm = a\,\Delta l. The grid cell in the uvuv plane is Δu=1/(n Δl)\Delta u = 1/(n\,\Delta l), and a visibility sits on the grid point k=(kv,ku)k = (k_v, k_u) with any real ww. With N=n2N = n^2, the real sky xx and yp=xp/νpy_p = x_p / \nu_p, the model is

V(k,w)=∑pyp Gw(p) e−2πi k⋅p/n,Gw(p)=e−2πiw(νp−1).V(k, w) = \sum_p y_p\, G_w(p)\, e^{-2\pi i\, k \cdot p / n}, \qquad G_w(p) = e^{-2\pi i w (\nu_p - 1)} .

Measured visibilities VjV_j at (kj,wj)(k_j, w_j) come with weights ωj>0\omega_j > 0, and Ω=∑jωj\Omega = \sum_j \omega_j. The exact dirty image is the adjoint of this model, Dp=1Ω∑jωj Re(Vj ajp‾)D_p = \frac1\Omega \sum_j \omega_j\, \mathrm{Re}\big(V_j\, \overline{a_{jp}}\big) with ajp=Gwj(p) e−2πi kj⋅p/n/νpa_{jp} = G_{w_j}(p)\, e^{-2\pi i\, k_j \cdot p/n} / \nu_p. The direct sum costs Θ(mN)\Theta(mN) for mm visibilities. The task is to compute DD, and the model visibilities of a given sky, with FFTs.

Real visibilities do not sit on grid points; a gridding kernel spreads each one onto the grid, as in the nonuniform FFT. Grid points here keep the ww step apart from that interpolation.

The algorithm

On the grid, V(⋅,w)V(\cdot, w) is the DFT of the product y⋅Gwy \cdot G_w. By the convolution theorem, the DFT of a product is the circular convolution of the DFTs divided by NN, so

V(k,w)=∑qKw(q) V(k−q,0),Kw=1N DFT(Gw).V(k, w) = \sum_q K_w(q)\, V(k - q, 0), \qquad K_w = \frac1N\, \mathrm{DFT}(G_w).

The visibility at height ww is the visibility at w=0w = 0 convolved with the kernel KwK_w. The kernel is a Fresnel pattern: GwG_w is a pure phase, and KwK_w spreads over a few cells for small ∣w∣|w| and over more cells for large ∣w∣|w|. Gridding with the conjugate kernel is the adjoint operation, and it gives the dirty image.

  1. W-PROJECTION-IMAGE(vis, n, Δl, S) ▷ vis: tuples (k, w, V, ω), offsets mod n
  2. 1F ← n × n grid of zeros
  3. 2for each visibility (k, w, V, ω) in vis do
  4. 3K ← W-KERNEL(n, Δl, w, S) ▷ cached for each distinct w
  5. 4F[k - q] ← F[k - q] + ω · conj(K_q) · V for every offset q of K
  6. 5E ← N · IDFT2(F)
  7. 6return D_p ← Re(E_p) / (Ω · ν_p) for every pixel p
  8. W-KERNEL(n, Δl, w, S)
  9. 7G_p ← exp(-2πi w (ν_p - 1)) for every pixel p
  10. 8Ĝ ← DFT2(G)
  11. 9return K_q ← Ĝ_q / N for the offsets q with |q_v|, |q_u| ≤ S

The prediction of model visibilities is the same steps in the other order: V0=DFT2(x/ν)V_0 = \mathrm{DFT2}(x/\nu) with one FFT, then Vj=∑qKwj(q) V0[kj−q]V_j = \sum_q K_{w_j}(q)\, V_0[k_j - q] for each visibility. This degridding step is the adjoint of lines L1 to L4, for every support SS.

The support SS is the only accuracy setting. With S≥n/2S \ge n/2 the kernel is complete and both outputs are exact. In practice SS is a few cells, and it grows with ∣w∣|w|: the phase of GwG_w has the local frequency w l/νw\, l / \nu in uu, so the kernel reaches about ∣w∣ lmax⁡/Δu|w|\, l_{\max} / \Delta u cells from its center. Production codes compute the kernels on an oversampled grid for a list of ww values, and take the kernel of the nearest listed ww for each visibility.

Example

Take n=16n = 16 and Δl=0.05\Delta l = 0.05, so ∣l∣,∣m∣≤0.4|l|, |m| \le 0.4 and Δu=1.25\Delta u = 1.25 wavelengths. The sky has a point of flux 1 at the center pixel and one at the offset (a,b)=(−7,6)(a, b) = (-7, 6), where l=0.3l = 0.3, m=−0.35m = -0.35 and ν=0.8874\nu = 0.8874. There are 40 visibilities with ku,kvk_u, k_v drawn from {−5,…,5}\{-5, \dots, 5\} and ww drawn from {−6,−3,0,3,6}\{-6, -3, 0, 3, 6\}, with seed 1 and unit weights. At the corner source and w=6w = 6, the dropped phase is 2π⋅6⋅(1−0.8874)=4.252\pi \cdot 6 \cdot (1 - 0.8874) = 4.25 radians, far from small.

The kernel for w=6w = 6 has ∣K(0,0)∣=0.380|K(0,0)| = 0.380 and ∣K(q)∣=0.294|K(q)| = 0.294 at the four nearest offsets. Its total energy ∑q∣K(q)∣2\sum_q |K(q)|^2 is 1. The part of the energy with ∣qv∣,∣qu∣≤S|q_v|, |q_u| \le S is 0.145 for S=0S = 0, 0.717 for S=1S = 1, 0.916 for S=2S = 2, 0.983 for S=4S = 4 and 0.995 for S=6S = 6.

The table gives the largest error of the predicted visibilities, divided by the largest ∣Vj∣|V_j|, and the dirty image at the two sources. The exact dirty image has 1.1541 at the center and 1.4240 at the corner source.

method prediction error image at center image at corner source
no ww term 0.925 1.1541 -0.3269
S=0S = 0 1.235 0.2715 0.1634
S=1S = 1 0.545 1.6268 1.1433
S=2S = 2 0.321 1.0297 1.1408
S=4S = 4 0.134 1.1331 1.3394
S=6S = 6 0.060 1.1439 1.4378
full kernel (16×1616 \times 16) 0 to rounding 1.1541 1.4240

Without the ww term, the center source is exact, because ν=1\nu = 1 there, but the corner source comes out negative. A kernel of one cell is worse than no correction: it scales every visibility by K(0,0)K(0, 0) and drops the rest of the kernel. From S=1S = 1 on, the prediction error falls as the support grows, and the image values at the sources come close to the exact ones from S=4S = 4 on.

Correctness

On the grid the identity V(k,w)=∑qKw(q) V(k−q,0)V(k, w) = \sum_q K_w(q)\, V(k - q, 0) is exact, by the convolution theorem for the DFT. So degridding with the full kernel gives the exact model visibilities. Line L4 adds ωjKw(q)‾ Vj\omega_j \overline{K_w(q)}\, V_j at kj−qk_j - q, and the inverse DFT turns this into ωjVjνpajp‾\omega_j V_j \nu_p \overline{a_{jp}} at pixel pp, because Gw(p)‾=∑qKw(q)‾ e−2πi q⋅p/n\overline{G_w(p)} = \sum_q \overline{K_w(q)}\, e^{-2\pi i\, q \cdot p/n}. Line L6 divides by Ωνp\Omega \nu_p and takes the real part, so with the full kernel the output is the exact dirty image.

With a cut kernel, gridding and degridding stay exact adjoints of each other, so the image is the exact dirty image of the cut model. The kernel has unit energy by Parseval's theorem, because ∣Gw∣=1|G_w| = 1. If ESE_S is the energy kept by the cut, the error of each predicted visibility is at most 1−ES N ∥y∥2\sqrt{1 - E_S}\, \sqrt N\, \|y\|_2 by the Cauchy-Schwarz inequality. This bound holds for every sky, and it is loose for a sky of a few points. The full proof is below.

Proof: W-projection is exact with the full kernel, its gridding is the adjoint of its degridding, and a cut kernel has an error bounded by the dropped kernel energyfull

Setting. The image has n×nn \times n pixels with signed offsets p=(a,b)p = (a, b), −n/2≤a,b<n/2-n/2 \le a, b < n/2, and N=n2N = n^2. All index arithmetic on the grid is mod nn in each coordinate, and k⋅pk \cdot p is kva+kubk_v a + k_u b. The direction cosines are l=b Δll = b\,\Delta l and m=a Δlm = a\,\Delta l, with l2+m2<1l^2 + m^2 < 1 on the grid, and νp=1−l2−m2>0\nu_p = \sqrt{1 - l^2 - m^2} > 0. The DFT is f^(k)=∑pf(p) e−2πi k⋅p/n\hat f(k) = \sum_p f(p)\, e^{-2\pi i\, k \cdot p/n}, and its inverse is f(p)=1N∑kf^(k) e2πi k⋅p/nf(p) = \frac1N \sum_k \hat f(k)\, e^{2\pi i\, k \cdot p/n}.

For a real sky xx let yp=xp/νpy_p = x_p / \nu_p. For a real ww let Gw(p)=e−2πiw(νp−1)G_w(p) = e^{-2\pi i w(\nu_p - 1)} and Kw=1NG^wK_w = \frac1N \hat G_w. The model visibility at the grid point kk and height ww is

V(k,w)=∑pyp Gw(p) e−2πi k⋅p/n=yGw^(k).V(k, w) = \sum_p y_p\, G_w(p)\, e^{-2\pi i\, k \cdot p/n} = \widehat{y G_w}(k).

The visibilities are (kj,wj,Vj,ωj)(k_j, w_j, V_j, \omega_j) for j=1,…,mj = 1, \dots, m, with ωj>0\omega_j > 0 and Ω=∑jωj\Omega = \sum_j \omega_j. A support TT is a set of offsets qq; the full support is the whole grid, and the cut support of lines L7 to L9 is TS={q:∣qv∣,∣qu∣≤S}T_S = \{q : |q_v|, |q_u| \le S\}. For a support TT, degridding is

Pj(x)=∑q∈TKwj(q) y^(kj−q),P_j(x) = \sum_{q \in T} K_{w_j}(q)\, \hat y(k_j - q),

and lines L1 to L6 give the image

Dp=1Ω νp Re∑kF(k) e2πi k⋅p/n,F(k)=∑j∑q∈T,  kj−q=kωj Kwj(q)‾ Vj.D_p = \frac{1}{\Omega\, \nu_p}\, \mathrm{Re} \sum_k F(k)\, e^{2\pi i\, k \cdot p/n}, \qquad F(k) = \sum_j \sum_{q \in T,\; k_j - q = k} \omega_j\, \overline{K_{w_j}(q)}\, V_j .

Line L5 computes N⋅IDFT(F)N \cdot \mathrm{IDFT}(F), which is the sum over kk above.

Claim 1 (the w term is a convolution). For every kk and ww, V(k,w)=∑qKw(q) V(k−q,0)V(k, w) = \sum_q K_w(q)\, V(k - q, 0), where qq runs over the whole grid.

Proof. By the inverse DFT, Gw(p)=∑qKw(q) e2πi q⋅p/nG_w(p) = \sum_q K_w(q)\, e^{2\pi i\, q \cdot p/n}. Put this into the definition of V(k,w)V(k, w):

V(k,w)=∑qKw(q)∑pyp e−2πi (k−q)⋅p/n=∑qKw(q) y^(k−q).V(k, w) = \sum_q K_w(q) \sum_p y_p\, e^{-2\pi i\,(k - q) \cdot p/n} = \sum_q K_w(q)\, \hat y(k - q).

Since G0=1G_0 = 1, y^(k−q)=V(k−q,0)\hat y(k - q) = V(k - q, 0). □\square

So degridding with the full support gives Pj(x)=V(kj,wj)P_j(x) = V(k_j, w_j), the exact model visibility.

Claim 2 (the gridded image is the adjoint of degridding). Fix any support TT. For every real image xx and every set of data VjV_j,

∑pxp Dp=1Ω∑jωj Re(Vj Pj(x)‾).\sum_p x_p\, D_p = \frac1\Omega \sum_j \omega_j\, \mathrm{Re}\big(V_j\, \overline{P_j(x)}\big).

Proof. Write Pj(x)=∑pa~jp xpP_j(x) = \sum_p \tilde a_{jp}\, x_p with

a~jp=1νp∑q∈TKwj(q) e−2πi (kj−q)⋅p/n,\tilde a_{jp} = \frac{1}{\nu_p} \sum_{q \in T} K_{w_j}(q)\, e^{-2\pi i\,(k_j - q) \cdot p/n},

which follows from y^(k)=∑pxpνp−1e−2πi k⋅p/n\hat y(k) = \sum_p x_p \nu_p^{-1} e^{-2\pi i\, k \cdot p/n}. Each pair (j,q)(j, q) adds ωjKwj(q)‾Vj\omega_j \overline{K_{w_j}(q)} V_j to FF at k=kj−qk = k_j - q, so

∑kF(k) e2πi k⋅p/n=∑jωjVj∑q∈TKwj(q)‾ e2πi (kj−q)⋅p/n=∑jωjVj νp a~jp‾.\sum_k F(k)\, e^{2\pi i\, k \cdot p/n} = \sum_j \omega_j V_j \sum_{q \in T} \overline{K_{w_j}(q)}\, e^{2\pi i\,(k_j - q) \cdot p/n} = \sum_j \omega_j V_j\, \nu_p\, \overline{\tilde a_{jp}} .

Hence Dp=1Ω∑jωj Re(Vj a~jp‾)D_p = \frac1\Omega \sum_j \omega_j\, \mathrm{Re}(V_j\, \overline{\tilde a_{jp}}). Multiply by the real xpx_p and sum over pp. Because xpx_p is real, ∑pxpa~jp‾=Pj(x)‾\sum_p x_p \overline{\tilde a_{jp}} = \overline{P_j(x)}, and the real part is linear over real factors. □\square

Claim 3 (the full kernel gives the exact dirty image). With the full support, Dp=1Ω∑jωj Re(Vj ajp‾)D_p = \frac1\Omega \sum_j \omega_j\, \mathrm{Re}(V_j\, \overline{a_{jp}}) with ajp=Gwj(p) e−2πi kj⋅p/n/νpa_{jp} = G_{w_j}(p)\, e^{-2\pi i\, k_j \cdot p/n} / \nu_p.

Proof. By the proof of Claim 2 it is enough to show a~jp=ajp\tilde a_{jp} = a_{jp} for the full support. Then the sum over qq is the whole inverse DFT, ∑qKw(q) e2πi q⋅p/n=Gw(p)\sum_q K_w(q)\, e^{2\pi i\, q \cdot p/n} = G_w(p), so a~jp=νp−1e−2πi kj⋅p/nGwj(p)=ajp\tilde a_{jp} = \nu_p^{-1} e^{-2\pi i\, k_j \cdot p/n} G_{w_j}(p) = a_{jp}. □\square

Claim 4 (properties of the kernel). (a) K0(0)=1K_0(0) = 1 and K0(q)=0K_0(q) = 0 for q≠0q \ne 0. (b) ∑q∣Kw(q)∣2=1\sum_q |K_w(q)|^2 = 1. (c) K−w(q)=Kw(−q)‾K_{-w}(q) = \overline{K_w(-q)}.

Proof. (a) G0=1G_0 = 1, and the DFT of the constant 1 is NN at k=0k = 0 and 00 elsewhere. (b) By Parseval's theorem for this DFT, ∑q∣G^w(q)∣2=N∑p∣Gw(p)∣2=N⋅N\sum_q |\hat G_w(q)|^2 = N \sum_p |G_w(p)|^2 = N \cdot N, because ∣Gw(p)∣=1|G_w(p)| = 1. Divide by N2N^2. (c) G−w=Gw‾G_{-w} = \overline{G_w}, and f‾^(q)=f^(−q)‾\widehat{\overline f}(q) = \overline{\hat f(-q)} for every ff. Divide by NN. □\square

Claim 5 (the error of a cut kernel). Let E=∑q∈T∣Kw(q)∣2E = \sum_{q \in T} |K_w(q)|^2 be the energy that the support TT keeps, for the height w=wjw = w_j. Then

∣Pj(x)−V(kj,wj)∣≤1−E  N  ∥y∥2.\Big|P_j(x) - V(k_j, w_j)\Big| \le \sqrt{1 - E}\; \sqrt N\; \|y\|_2 .

Proof. By Claim 1 the difference is −∑q∉TKw(q) y^(kj−q)-\sum_{q \notin T} K_w(q)\, \hat y(k_j - q). By the Cauchy-Schwarz inequality its modulus is at most

(∑q∉T∣Kw(q)∣2)1/2(∑q∉T∣y^(kj−q)∣2)1/2≤1−E (∑k∣y^(k)∣2)1/2,\Big(\sum_{q \notin T} |K_w(q)|^2\Big)^{1/2} \Big(\sum_{q \notin T} |\hat y(k_j - q)|^2\Big)^{1/2} \le \sqrt{1 - E}\, \Big(\sum_k |\hat y(k)|^2\Big)^{1/2},

using Claim 4(b) and the fact that kj−qk_j - q meets each grid point at most once. Parseval's theorem gives ∑k∣y^(k)∣2=N∥y∥22\sum_k |\hat y(k)|^2 = N \|y\|_2^2. □\square

The bound holds for every sky, and it tends to 0 as TT grows to the full grid, where E=1E = 1. For the image, Claim 2 says that the cut-kernel image is the exact adjoint of the cut model, and the difference from the exact image at pixel pp is 1Ω∑jωj Re(Vj (a~jp−ajp)‾)\frac1\Omega \sum_j \omega_j\, \mathrm{Re}\big(V_j\, \overline{(\tilde a_{jp} - a_{jp})}\big), where ∣a~jp−ajp∣=νp−1∣∑q∉TKwj(q) e2πi q⋅p/n∣|\tilde a_{jp} - a_{jp}| = \nu_p^{-1} \big|\sum_{q \notin T} K_{w_j}(q)\, e^{2\pi i\, q \cdot p/n}\big| is the error of the cut kernel as an approximation of Gwj(p)G_{w_j}(p).

Claim 6 (the center needs no correction). If xx is zero outside the pixel p=0p = 0, then V(k,w)=V(k,0)V(k, w) = V(k, 0) for every ww, so the prediction without the ww term is exact for this sky.

Proof. At p=0p = 0, l=m=0l = m = 0, so ν0=1\nu_0 = 1 and Gw(0)=1G_w(0) = 1. The sum that defines V(k,w)V(k, w) has only the term p=0p = 0, which does not depend on ww. □\square

Complexity

One kernel costs a 2D FFT of NN pixels, Θ(Nlog⁡N)\Theta(N \log N), and there are PP distinct ww values, so the kernels cost Θ(PNlog⁡N)\Theta(P N \log N) and Θ(PS2)\Theta(P S^2) space. Gridding mm visibilities with (2S+1)2(2S + 1)^2 cells each costs Θ(mS2)\Theta(m S^2), and the final FFT costs Θ(Nlog⁡N)\Theta(N \log N). The total is Θ(mS2+PNlog⁡N)\Theta(m S^2 + P N \log N), against Θ(mN)\Theta(m N) for the direct sum. In real use mm is in the millions and SS grows with ∣wmax⁡∣|w_{\max}|, so the mS2m S^2 term usually dominates, and the kernels are computed once for a list of ww values and kept.

Properties

  • Linear. Both outputs are linear in the data, and gridding is the exact adjoint of degridding for every support. This keeps the major cycles of Cotton-Schwab CLEAN consistent.
  • Exact with the full kernel. On the grid model the only error is the cut of the kernel and, in practice, the rounding of ww to a listed value.
  • The kernel at w=0w = 0 is a delta. Then W-projection is plain gridding.
  • Symmetry in ww. G−w=Gw‾G_{-w} = \overline{G_w}, so K−w(q)=Kw(−q)‾K_{-w}(q) = \overline{K_w(-q)}, and one kernel serves ±w\pm w. A visibility with w<0w < 0 can also be replaced by its conjugate at (−u,−v,−w)(-u, -v, -w), because the sky is real.
  • Unit energy. ∑q∣Kw(q)∣2=1\sum_q |K_w(q)|^2 = 1 for every ww.
  • The support grows with ∣w∣|w| and with the field. The kernel reaches about ∣w∣ lmax⁡/Δu|w|\, l_{\max} / \Delta u cells, which is ∣w∣ n Δl lmax⁡|w|\, n\, \Delta l\, l_{\max}.

Variants and improvements

  • Kernel with an anti-aliasing taper. Real gridding uses a smooth kernel, often a prolate spheroidal function, to place off-grid visibilities. The w-projection kernel is then the transform of the taper times GwG_w, and the image is divided by the taper at the end. The taper also makes the kernel tails smaller.
  • W-stacking. Offringa et al. (2014) grid the visibilities into several planes by ww, transform each plane, multiply it by Gw‾\overline{G_w} in the image and add the planes. The error comes only from the spacing of the planes, and the cost does not grow with the kernel size.
  • Faceting. The field is split into small facets, each imaged with its own tangent plane, where the small-field approximation holds. Cornwell, Golap and Bhatnagar (2008) compare it with w-projection.
  • Snapshots. For a short time the baselines lie close to a tilted plane w=αu+βvw = \alpha u + \beta v. The part of ww on that plane is a change of coordinates in the image, so the kernel corrects only the small distance of each baseline from the plane, and each snapshot image is regridded to common coordinates.
  • Other direction-dependent effects. The same idea, a kernel in the uvuv plane per baseline, also corrects the primary beams of the antennas.

When to use it

Use W-projection when the dropped phase π∣w∣ (l2+m2)\pi |w|\, (l^2 + m^2) is not small over the field: low frequencies, long baselines and wide fields, as for low-frequency arrays. Use it inside the major cycle of Cotton-Schwab CLEAN, which needs a matched pair of predict and image steps. When ∣w∣|w| is very large, w-stacking or a mixed method can be cheaper, because the w-projection kernel grows with ∣w∣|w|. For a small field the plain dirty image is correct, and W-projection adds only cost.

Pitfalls

  • A kernel that is too small. The error falls slowly with SS because the kernel has tails from the sharp edge of the field. On the example, S=6S = 6 still leaves 6 percent. Use a taper and an SS that grows with ∣w∣|w|.
  • A one-cell kernel. Keeping only K(0,0)K(0, 0) is worse than no correction, because it scales the visibility down.
  • Mismatched gridding and degridding. If the predict step does not use the same kernels as the image step, the two are not adjoints, and the major cycles of CLEAN can stall or diverge.
  • The sign of ww and the conjugate. Gridding uses Kw‾\overline{K_w} and degridding uses KwK_w. A sign error moves sources away from the center instead of correcting them.
  • The factor 1/ν1/\nu. The measurement equation divides by ν\nu, and the image step divides by ν\nu again. Leaving it out gives wrong fluxes near the edge.
  • Memory. Kernels for large ∣w∣|w| on an oversampled grid are large, and there is one per listed ww.

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
w_projection.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/w-projection/. The authors are listed in prov/0A2NXG.jsonl.
"""W-projection on a small grid, with the exact sums to compare against.

The image is n x n, img[i][j]. Pixel (i, j) has the offsets a = i - n//2 and
b = j - n//2 and the direction cosines l = b dl, m = a dl, with
nn = sqrt(1 - l^2 - m^2). The uv cell is du = 1 / (n dl). A visibility is a
tuple (ku, kv, w, value, weight): it sits on the grid point u = ku du,
v = kv du, and w is any real number. The measurement equation is

    V = sum over pixels of x / nn * exp(-2 pi i (u l + v m + w (nn - 1))).

On this grid the equation is a DFT of y = x * G_w / nn with
G_w = exp(-2 pi i w (nn - 1)), so V_w = K_w (*) V_0 (circular convolution)
with the kernel K_w = DFT(G_w) / n^2. Cutting K_w to a small support is the
w-projection approximation. Kernels and grids are stored wrapped, with
offset 0 at index 0.
"""

import cmath
import math

from imgkit import dft2, idft2, ifftshift


def cosines(n, dl):
    """Lists (l, m, nn) per pixel, as three n x n images."""
    ls = [[(j - n // 2) * dl for j in range(n)] for _ in range(n)]
    ms = [[(i - n // 2) * dl for _ in range(n)] for i in range(n)]
    nns = [[math.sqrt(1.0 - l * l - m * m) for l, m in zip(rl, rm)] for rl, rm in zip(ls, ms)]
    return ls, ms, nns


def w_kernel(n, dl, w, support=None):
    """The kernel K_w as a dict {(qv, qu): value} over signed offsets.

    support = None keeps every offset; otherwise only |qv|, |qu| <= support.
    """
    _, _, nns = cosines(n, dl)
    g = [[cmath.exp(-2j * math.pi * w * (nn - 1.0)) for nn in row] for row in nns]  # @line L7
    full = dft2(ifftshift(g))  # @line L8
    lo, hi = -(n // 2), n - n // 2
    if support is not None:
        lo, hi = max(lo, -support), min(hi, support + 1)
    return {(qv, qu): full[qv % n][qu % n] / (n * n) for qv in range(lo, hi) for qu in range(lo, hi)}  # @line L9


def predict_direct(sky, vis, dl):
    """The exact model visibilities, by the sum over pixels."""
    n = len(sky)
    ls, ms, nns = cosines(n, dl)
    du = 1.0 / (n * dl)
    out = []
    for ku, kv, w, _, _ in vis:
        u, v = ku * du, kv * du
        acc = 0j
        for i in range(n):
            for j in range(n):
                if sky[i][j] != 0:
                    nn = nns[i][j]
                    acc += sky[i][j] / nn * cmath.exp(-2j * math.pi * (u * ls[i][j] + v * ms[i][j] + w * (nn - 1.0)))
        out.append(acc)
    return out


def image_direct(vis, n, dl):
    """The exact dirty image (1/W) sum_j weight_j Re(V_j conj(a_jp)), the adjoint of predict_direct."""
    ls, ms, nns = cosines(n, dl)
    du = 1.0 / (n * dl)
    total = sum(vis_j[4] for vis_j in vis)
    img = [[0.0] * n for _ in range(n)]
    for ku, kv, w, val, wt in vis:
        u, v = ku * du, kv * du
        for i in range(n):
            for j in range(n):
                nn = nns[i][j]
                a = cmath.exp(-2j * math.pi * (u * ls[i][j] + v * ms[i][j] + w * (nn - 1.0))) / nn
                img[i][j] += wt * (val * a.conjugate()).real / total
    return img


def _kernels(vis, n, dl, support):
    cache = {}
    for _, _, w, _, _ in vis:
        if w not in cache:
            cache[w] = w_kernel(n, dl, w, support)
    return cache


def w_project_image(vis, n, dl, support=None):
    """The dirty image by w-projection: grid each visibility through conj(K_w), one FFT, divide by nn."""
    kernels = _kernels(vis, n, dl, support)
    total = sum(vis_j[4] for vis_j in vis)
    grid = [[0j] * n for _ in range(n)]  # @line L1
    for ku, kv, w, val, wt in vis:  # @line L2
        kern = kernels[w]  # @line L3
        for (qv, qu), kq in kern.items():  # @line L4
            grid[(kv - qv) % n][(ku - qu) % n] += wt * kq.conjugate() * val
    img = idft2(grid)  # @line L5
    _, _, nns = cosines(n, dl)
    shifted = [[v * n * n for v in row] for row in img]
    # the grid index is wrapped; move offset 0 back to pixel n // 2
    back = [[shifted[(i - n // 2) % n][(j - n // 2) % n] for j in range(n)] for i in range(n)]
    return [[back[i][j].real / (total * nns[i][j]) for j in range(n)] for i in range(n)]  # @line L6


def w_project_predict(sky, vis, dl, support=None):
    """Model visibilities by w-projection: one FFT of x / nn, then each value through K_w."""
    n = len(sky)
    _, _, nns = cosines(n, dl)
    y = [[x / nn for x, nn in zip(rx, rn)] for rx, rn in zip(sky, nns)]
    v0 = dft2(ifftshift(y))
    kernels = _kernels(vis, n, dl, support)
    out = []
    for ku, kv, w, _, _ in vis:
        kern = kernels[w]
        out.append(sum(kq * v0[(kv - qv) % n][(ku - qu) % n] for (qv, qu), kq in kern.items()))
    return out
test_w_projection.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/w-projection/. The authors are listed in prov/0A2NXG.jsonl.

import random

from w_projection import (
    image_direct,
    predict_direct,
    w_kernel,
    w_project_image,
    w_project_predict,
)

N, DL = 16, 0.05


def page_data(wmax=6.0):
    """A source at the center and one near a corner, 40 grid visibilities with five w values."""
    rng = random.Random(1)
    sky = [[0.0] * N for _ in range(N)]
    sky[8][8] = 1.0
    sky[1][14] = 1.0
    vis = []
    for _ in range(40):
        ku, kv = rng.randint(-5, 5), rng.randint(-5, 5)
        w = rng.choice((-wmax, -wmax / 2, 0.0, wmax / 2, wmax))
        vis.append((ku, kv, w, 0, 1.0))
    vals = predict_direct(sky, vis, DL)
    return sky, [(ku, kv, w, v, wt) for (ku, kv, w, _, wt), v in zip(vis, vals)]


def rel_err(a, b):
    return max(abs(x - y) for x, y in zip(a, b)) / max(abs(y) for y in b)


def img_err(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def test_kernel_at_w_zero_is_a_delta():
    k = w_kernel(N, DL, 0.0)
    assert abs(k[(0, 0)] - 1.0) < 1e-12
    assert all(abs(v) < 1e-12 for q, v in k.items() if q != (0, 0))


def test_full_kernel_has_unit_energy():
    for w in (2.0, 6.0, -9.5):
        k = w_kernel(N, DL, w)
        assert len(k) == N * N
        assert abs(sum(abs(v) ** 2 for v in k.values()) - 1.0) < 1e-12


def test_full_kernel_is_exact():
    sky, vis = page_data()
    exact = [v for _, _, _, v, _ in vis]
    assert rel_err(w_project_predict(sky, vis, DL), exact) < 1e-12
    assert img_err(w_project_image(vis, N, DL), image_direct(vis, N, DL)) < 1e-12


def test_gridding_is_the_adjoint_of_degridding():
    rng = random.Random(6)
    _, vis = page_data()
    vis = [(ku, kv, w, complex(rng.gauss(0, 1), rng.gauss(0, 1)), rng.uniform(0.5, 2.0)) for ku, kv, w, _, _ in vis]
    x = [[rng.gauss(0, 1) for _ in range(N)] for _ in range(N)]
    total = sum(v[4] for v in vis)
    for support in (1, 3):
        img = w_project_image(vis, N, DL, support)
        pred = w_project_predict(x, vis, DL, support)
        lhs = sum(x[i][j] * img[i][j] for i in range(N) for j in range(N))
        rhs = sum(wt * (val * p.conjugate()).real for (_, _, _, val, wt), p in zip(vis, pred)) / total
        assert abs(lhs - rhs) < 1e-10


def test_error_falls_with_the_support():
    sky, vis = page_data()
    exact = [v for _, _, _, v, _ in vis]
    errs = [rel_err(w_project_predict(sky, vis, DL, s), exact) for s in (1, 2, 4, 6)]
    assert all(a > b for a, b in zip(errs, errs[1:]))
    assert errs[-1] < 0.07
    flat = [(ku, kv, 0.0, v, wt) for ku, kv, _, v, wt in vis]
    no_correction = rel_err(w_project_predict(sky, flat, DL, 0), exact)
    assert no_correction > 0.9 and errs[1] < 0.35


def test_a_source_at_the_center_needs_no_correction():
    sky, vis = page_data()
    sky[1][14] = 0.0
    exact = predict_direct(sky, vis, DL)
    flat = [(ku, kv, 0.0, v, wt) for ku, kv, _, v, wt in vis]
    assert rel_err(w_project_predict(sky, flat, DL, 0), exact) < 1e-12

History

The ww term was long handled by keeping the field small, or by splitting it into facets that each had their own tangent plane. Cornwell, Golap and Bhatnagar (2008) noted that the ww term is a multiplication in the image, so it is a convolution in the uvuv plane, and they applied it while gridding. Their paper compared the method with faceting. Offringa et al. (2014) moved the correction back to the image in w-stacking, in the WSClean imager.

References

  1. T. J. Cornwell, K. Golap and S. Bhatnagar, The noncoplanar baselines effect in radio interferometry, the W-projection algorithm, IEEE Journal of Selected Topics in Signal Processing 2(5), 2008, pp. 647 to 657 (the w term as a convolution in the uv plane, the kernel, its support and the comparison with faceting)
  2. A. R. Offringa et al., WSClean, an implementation of a fast, generic wide-field imager for radio astronomy, Monthly Notices of the Royal Astronomical Society 444(1), 2014, pp. 606 to 619 (w-stacking, the image-space alternative to w-projection)
  3. A. Richard Thompson, James M. Moran and George W. Swenson Jr., Interferometry and Synthesis in Radio Astronomy, third edition, Springer, 2017, Chapter 3, Analysis of the Interferometer Response (the measurement equation with the w term and the small-field approximation that drops it)

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