Algorithm Search⌘K

Algorithmadvanced

Knox-Thompson method

Also called cross-spectrum method.

Recover object Fourier phases from the average cross spectrum of speckle images at neighboring frequencies, summed along paths.

Time
Θ(F N log N) worst · average · best
Space
Θ(N) extra
Where
F = the number of frames; N = the number of pixels in a frame
Properties
deterministicnot iterativenot linearneeds reference star for modulusnot shift invariant
Origin
Keith T. Knox, Brian J. Thompson, 1974

The Knox-Thompson method recovers the Fourier phase of an object from many short exposures taken through atmospheric turbulence. It averages the cross spectrum I(u) I(u+Δ)‾I(u)\, \overline{I(u + \Delta)} of the frames at two close frequencies, whose phase is the difference of the object phases, and it adds these differences along paths from the origin of the frequency plane. Speckle interferometry gives only the Fourier modulus of the object. Speckle masking gets the phase from the bispectrum, which is free of image motion; the cross spectrum is not, but it is a two-frequency quantity and cheaper to store.

In plain words

A telescope on the ground sees a star through moving air. A very short exposure freezes the air, and the image breaks into many small bright spots, called speckles. Each spot still holds fine detail, but the pattern changes from frame to frame. Speckle interferometry keeps the strength of each fine detail and loses its position. The Knox-Thompson method keeps the positions too. For each frame it compares every detail with its close neighbor detail. The air changes both in almost the same way, so the comparison, averaged over many frames, shows how the object moves from one detail to the next. Starting from the coarsest detail, the method walks outward and adds up these small steps. With the strengths from speckle interferometry, this gives an image at the full resolution of the telescope.

The problem

The object oo is a real nonnegative image on an n×nn \times n periodic grid, with N=n2N = n^2 and the DFT O(u)=∣O(u)∣ eiφ(u)O(u) = |O(u)|\, e^{i\varphi(u)} at the signed frequencies u=(u1,u2)u = (u_1, u_2). A short exposure ff is if=o∗sfi_f = o \ast s_f, where sfs_f is the instantaneous point spread function: the squared modulus of the Fourier transform of the pupil field P eiψfP\, e^{i\psi_f}, with the pupil PP and the random phase screen ψf\psi_f of the air. In the frequency plane,

If(u)=O(u) Tf(u),I_f(u) = O(u)\, T_f(u),

where TfT_f is the optical transfer function of frame ff, scaled to Tf(0)=1T_f(0) = 1. The transfer function is random and has random phases, so the average ⟨If⟩\langle I_f \rangle keeps only the low frequencies (the long exposure), and the average power spectrum ⟨∣If∣2⟩=∣O∣2⟨∣T∣2⟩\langle |I_f|^2 \rangle = |O|^2 \langle |T|^2 \rangle keeps the modulus but not the phase.

The input is FF frame spectra and a radius RR inside the cutoff of the telescope. The output is an estimate of φ(u)\varphi(u) for ∣u∣≤R|u| \le R. With ∣O∣|O| from speckle interferometry, the inverse DFT of ∣O∣ eiφ|O|\, e^{i\varphi} is the image.

The algorithm

For an offset Δ\Delta, the average cross spectrum factors as

C(u,Δ)=⟨If(u) If(u+Δ)‾⟩=O(u) O(u+Δ)‾  H(u,Δ),H(u,Δ)=⟨Tf(u) Tf(u+Δ)‾⟩.C(u, \Delta) = \big\langle I_f(u)\, \overline{I_f(u + \Delta)} \big\rangle = O(u)\, \overline{O(u + \Delta)}\; H(u, \Delta), \qquad H(u, \Delta) = \big\langle T_f(u)\, \overline{T_f(u + \Delta)} \big\rangle .

If the screen statistics do not change when ψ\psi is replaced by −ψ-\psi, as for a Gaussian screen, then HH is real. Where H>0H > 0, the phase of CC is φ(u)−φ(u+Δ)\varphi(u) - \varphi(u + \Delta). The method uses the two unit offsets e1=(1,0)e_1 = (1, 0) and e2=(0,1)e_2 = (0, 1), sets φ(0)=0\varphi(0) = 0 because O(0)O(0) is the total flux, and walks outward in the order of ∣u1∣+∣u2∣|u_1| + |u_2|.

  1. KNOX-THOMPSON(I_1, ..., I_F, R)
  2. 1C_e(u) ← (1/F) Σ_f I_f(u) · conj(I_f(u + e)) for e ∈ {e1, e2} and every u
  3. 2φ(0) ← 0
  4. 3for each u ≠ 0 with |u| ≤ R, in the order of |u1| + |u2| do
  5. 4z ← 0
  6. 5for each known neighbor p = u ∓ e with |p1| + |p2| = |u1| + |u2| - 1 do
  7. 6z ← z + e^{iφ(p)} · conj(C_e(p)) if u = p + e, or e^{iφ(p)} · C_e(u) if u = p - e
  8. 7φ(u) ← arg z
  9. 8return φ
  10. RECONSTRUCT(M, φ, R) ▷ M is the modulus from speckle interferometry
  11. 9return Re IDFT(M(u) e^{iφ(u)} for |u| ≤ R, 0 elsewhere)

Line L6 adds a phasor and not an angle, so there is no wrapping of phases, and a neighbor with a larger ∣Ce∣|C_e| has more weight. A frequency off the axes has two neighbors closer to the origin, and line L7 combines both paths. The modulus MM comes from the same frames: M2=⟨∣If∣2⟩/⟨∣T∣2⟩M^2 = \langle |I_f|^2 \rangle / \langle |T|^2 \rangle, where ⟨∣T∣2⟩\langle |T|^2 \rangle is the power spectrum of frames of a point source, the reference star.

Example

Take n=16n = 16, a disk pupil of diameter d=6d = 6 cells, and an object of three points: flux 1 at the offset (0,0)(0, 0), 0.6 at (2,1)(2, 1) and 0.35 at (−1,3)(-1, 3). Each phase screen is filtered white noise with the power spectrum ∣f∣−11/3|f|^{-11/3} of Kolmogorov turbulence and an expected rms phase of 3 radians, from random.Random(seed). The transfer function of a frame is zero at ∣u1∣≥6|u_1| \ge 6 or ∣u2∣≥6|u_2| \ge 6.

Along the u1u_1 axis, the transfer function without turbulence is 1, 0.8125, 0.625, 0.4375, 0.25 and 0.125 at u1=0,…,5u_1 = 0, \dots, 5. The long exposure keeps ∣⟨T⟩∣=0.281|\langle T \rangle| = 0.281 at u1=1u_1 = 1 and 0.030 at u1=2u_1 = 2, so it loses everything beyond the first ring. The speckle transfer function ⟨∣T∣2⟩\langle |T|^2 \rangle is 1, 0.155, 0.040, 0.020, 0.011 and 0.005, and H(u,e1)H(u, e_1) is 0.300, 0.044, 0.017, 0.009 and 0.004 at u1=0,…,4u_1 = 0, \dots, 4: small, but positive up to the cutoff.

The method recovers the 49 phases with ∣u∣≤4|u| \le 4. The table gives the largest and the rms phase error, in radians, with independent screens (seed 1) and with antithetic pairs, where each screen ψ\psi is also used as −ψ-\psi.

frames largest error rms error
1 2.903 1.495
10 0.466 0.223
30 1.210 0.677
100 0.788 0.402
300 0.197 0.101
1 antithetic pair 3.142 2.105
50 antithetic pairs 0 to rounding 0 to rounding

One frame gives no useful phase. The error falls with the number of frames, but not at every step, because a few unlucky frames can dominate a small sample. An antithetic pair makes every averaged HH exactly real, so each phase is exact or off by π\pi; with one pair HH is negative at some frequencies, and with 50 pairs it is positive at all 49 and the phases are exact. With the modulus from 50 antithetic pairs of a reference star (seed 2), the image differs from the object, cut to ∣u∣≤4|u| \le 4, by at most 0.0075, against its peak of 0.193, and the brightest pixel is at the true position.

Correctness

The factorization of CC is the linearity of the average, because OO does not change from frame to frame. If the law of ψ\psi is the same as the law of −ψ-\psi, then TT and T‾\overline{T} have the same law, because the PSF of −ψ-\psi is the PSF of ψ\psi turned by 180 degrees. So H(u,Δ)H(u, \Delta) equals its own conjugate and is real. Where H>0H > 0 along every step that line L6 uses, each term added to zz is eiφ(u)e^{i\varphi(u)} times a positive number, by induction on ∣u1∣+∣u2∣|u_1| + |u_2|, so line L7 returns φ(u)\varphi(u) exactly. The sample average converges to the expected value as F→∞F \to \infty by the law of large numbers, so the computed phases converge to φ\varphi wherever the expected HH is positive. That H>0H > 0 for unit offsets is an assumption about the turbulence: it holds when the offset is small against the size of a seeing cell in the frequency plane, and it held at every frequency of the example. The full proof is below.

Proof: The Knox-Thompson recursion returns the object phase wherever the cross-spectrum transfer function is positive, and the sample phases converge to itfull

Setting. The grid is n×nn \times n and periodic, N=n2N = n^2, and frequencies u=(u1,u2)u = (u_1, u_2) are signed, with arithmetic mod nn. The object oo is real and nonnegative with ∑o>0\sum o > 0, and O(u)=∣O(u)∣eiφ(u)O(u) = |O(u)| e^{i\varphi(u)} is its DFT. The pupil PP is a real function on the grid. For a real phase screen ψ\psi, the PSF is sψ=∣F(Peiψ)∣2s_\psi = |\mathcal F(P e^{i\psi})|^2 and the transfer function is Tψ=F(sψ)/F(sψ)(0)T_\psi = \mathcal F(s_\psi) / \mathcal F(s_\psi)(0). The screens ψ1,…,ψF\psi_1, \dots, \psi_F are independent with a common law μ\mu, and frame ff has If=O TψfI_f = O\, T_{\psi_f}.

For e∈{e1,e2}e \in \{e_1, e_2\} define the sample and expected cross spectra and the transfer function

CeF(u)=1F∑f=1FIf(u) If(u+e)‾,He(u)=E[Tψ(u) Tψ(u+e)‾],Ce(u)=O(u) O(u+e)‾ He(u).C^F_e(u) = \frac1F \sum_{f=1}^F I_f(u)\, \overline{I_f(u + e)}, \qquad H_e(u) = \mathbb E\big[T_\psi(u)\, \overline{T_\psi(u + e)}\big], \qquad C_e(u) = O(u)\, \overline{O(u + e)}\, H_e(u).

Let U={u:∣u∣≤R}U = \{u : |u| \le R\}, ordered by ∣u1∣+∣u2∣|u_1| + |u_2| as in line L3. A step is a pair (p,u)(p, u) with p,u∈Up, u \in U, u−p=±eu - p = \pm e and ∣p1∣+∣p2∣=∣u1∣+∣u2∣−1|p_1| + |p_2| = |u_1| + |u_2| - 1; these are the pairs that line L6 uses.

Claim 1 (the cross spectrum factors). CeF(u)=O(u) O(u+e)‾  1F∑fTψf(u) Tψf(u+e)‾C^F_e(u) = O(u)\, \overline{O(u + e)}\; \frac1F \sum_f T_{\psi_f}(u)\, \overline{T_{\psi_f}(u + e)}, and E[CeF(u)]=Ce(u)\mathbb E[C^F_e(u)] = C_e(u).

Proof. If(u) If(u+e)‾=O(u)Tf(u) O(u+e)‾ Tf(u+e)‾I_f(u)\, \overline{I_f(u + e)} = O(u) T_f(u)\, \overline{O(u + e)}\, \overline{T_f(u + e)}, and OO does not depend on ff. Take the mean over ff, then the expectation; TT is bounded by Claim 2, so the expectation exists. □\square

Claim 2 (the transfer function of one frame). Tψ(0)=1T_\psi(0) = 1, ∣Tψ(u)∣≤1|T_\psi(u)| \le 1, and Tψ(−u)=Tψ(u)‾T_\psi(-u) = \overline{T_\psi(u)}. For the screen −ψ-\psi, T−ψ=Tψ‾T_{-\psi} = \overline{T_\psi}.

Proof. sψ≥0s_\psi \ge 0 and sψ≠0s_\psi \ne 0 when P≠0P \ne 0, so F(sψ)(0)=∑sψ>0\mathcal F(s_\psi)(0) = \sum s_\psi > 0, and ∣F(sψ)(u)∣≤∑sψ|\mathcal F(s_\psi)(u)| \le \sum s_\psi. Since sψs_\psi is real, F(sψ)(−u)=F(sψ)(u)‾\mathcal F(s_\psi)(-u) = \overline{\mathcal F(s_\psi)(u)}. For the last part, PP is real, so Pe−iψ=Peiψ‾P e^{-i\psi} = \overline{P e^{i\psi}}, and F(gˉ)(x)=F(g)(−x)‾\mathcal F(\bar g)(x) = \overline{\mathcal F(g)(-x)}. Hence s−ψ(x)=sψ(−x)s_{-\psi}(x) = s_\psi(-x), and F(s−ψ)(u)=F(sψ)(−u)=F(sψ)(u)‾\mathcal F(s_{-\psi})(u) = \mathcal F(s_\psi)(-u) = \overline{\mathcal F(s_\psi)(u)}. The scale ∑s\sum s is the same for both. □\square

Claim 3 (a symmetric law gives a real transfer function). If ψ\psi and −ψ-\psi have the same law μ\mu, then He(u)H_e(u) is real for every uu. If the screens come in pairs ψ,−ψ\psi, -\psi, then the sample transfer function 1F∑fTψf(u) Tψf(u+e)‾\frac1F \sum_f T_{\psi_f}(u)\, \overline{T_{\psi_f}(u + e)} is real for every FF.

Proof. By Claim 2, T−ψ(u) T−ψ(u+e)‾=Tψ(u) Tψ(u+e)‾‾T_{-\psi}(u)\, \overline{T_{-\psi}(u + e)} = \overline{T_\psi(u)\, \overline{T_\psi(u + e)}}. Under a symmetric law the left side has the same expectation as the product for ψ\psi, so He(u)=He(u)‾H_e(u) = \overline{H_e(u)}. For a pair, the two terms are conjugates, and their sum is real. □\square

A Gaussian screen with zero mean, such as filtered white noise, has a symmetric law.

Claim 4 (the recursion is exact on positive data). Suppose the cross spectra used by the recursion are C^e(u)=O(u) O(u+e)‾ he(u)\hat C_e(u) = O(u)\, \overline{O(u + e)}\, h_e(u) with he(u)h_e(u) real, and he(p)>0h_e(p) > 0 for every step (p,p+e)(p, p + e) and he(u)>0h_e(u) > 0 for every step (p,u)(p, u) with u=p−eu = p - e. Suppose also that O(u)≠0O(u) \ne 0 on UU. Then lines L2 to L8 return φ(u)\varphi(u) for every u∈Uu \in U, mod 2π2\pi.

Proof. By induction in the order of line L3. φ(0)=0\varphi(0) = 0 is correct because O(0)=∑o>0O(0) = \sum o > 0. Take u≠0u \ne 0 and assume φ(p)\varphi(p) is correct for all pp before uu. Every u∈Uu \in U, u≠0u \neq 0, has at least one step (p,u)(p, u): move one unit toward the origin along a nonzero coordinate; this lowers ∣u1∣+∣u2∣|u_1| + |u_2| by one and does not raise ∣u∣|u|, so p∈Up \in U. For a step with u=p+eu = p + e, the term is

eiφ(p) C^e(p)‾=eiφ(p) ∣O(p)∣ e−iφ(p) ∣O(u)∣ eiφ(u) he(p)=∣O(p)∣ ∣O(u)∣ he(p)  eiφ(u).e^{i\varphi(p)}\, \overline{\hat C_e(p)} = e^{i\varphi(p)}\, |O(p)|\, e^{-i\varphi(p)}\, |O(u)|\, e^{i\varphi(u)}\, h_e(p) = |O(p)|\,|O(u)|\, h_e(p)\; e^{i\varphi(u)} .

For a step with u=p−eu = p - e, so p=u+ep = u + e, the term is

eiφ(p) C^e(u)=eiφ(p) ∣O(u)∣ eiφ(u) ∣O(p)∣ e−iφ(p) he(u)=∣O(u)∣ ∣O(p)∣ he(u)  eiφ(u).e^{i\varphi(p)}\, \hat C_e(u) = e^{i\varphi(p)}\, |O(u)|\, e^{i\varphi(u)}\, |O(p)|\, e^{-i\varphi(p)}\, h_e(u) = |O(u)|\,|O(p)|\, h_e(u)\; e^{i\varphi(u)} .

Every term is eiφ(u)e^{i\varphi(u)} times a positive number, and there is at least one term, so z=c eiφ(u)z = c\, e^{i\varphi(u)} with c>0c > 0, and line L7 returns φ(u)\varphi(u). □\square

With antithetic pairs, Claim 3 makes heh_e the real sample transfer function, so Claim 4 applies as soon as it is positive on the steps. With one pair it can be negative at some frequencies, and then the phase there and after it on the path can be off by π\pi.

Claim 5 (convergence in the number of frames). Suppose the law of ψ\psi is symmetric, He>0H_e > 0 on the steps as in Claim 4, and O≠0O \ne 0 on UU. Then, with probability 1, the phases returned from CeFC^F_e converge to φ\varphi on UU as F→∞F \to \infty.

Proof. The terms Tψf(u) Tψf(u+e)‾T_{\psi_f}(u)\, \overline{T_{\psi_f}(u + e)} are independent, have the same law and are bounded by 1 (Claim 2). By the strong law of large numbers their mean converges to He(u)H_e(u) with probability 1, for each of the finitely many uu and ee, so CeF→CeC^F_e \to C_e by Claim 1. By Claims 3 and 4, the recursion applied to CeC_e returns φ\varphi, and in the proof of Claim 4 every zz is nonzero. The recursion is continuous at such data: each zz is a continuous function of the cross spectra and of the earlier phases through eiφ(p)e^{i\varphi(p)}, and arg⁡\arg is continuous at a nonzero zz (as a map to the circle). By induction in the order of line L3, every returned phase converges to φ(u)\varphi(u) mod 2π2\pi. □\square

Remark (what is assumed). Claim 5 assumes He>0H_e > 0 on the steps. Claim 3 gives only that HeH_e is real. Positivity is a property of the turbulence and of the offset: He(0)=E[T(e)‾]H_e(0) = \mathbb E[\overline{T(e)}] is the long-exposure transfer function at ee, and HeH_e is small when the offset is larger than a seeing cell in the frequency plane. The proof does not cover the sign of HeH_e in general.

Complexity

Each frame needs one FFT, Θ(Nlog⁡N)\Theta(N \log N), and two products per frequency, Θ(N)\Theta(N), so FF frames cost Θ(FNlog⁡N)\Theta(F N \log N). The recursion visits each frequency once with at most four neighbors, Θ(N)\Theta(N). The extra space is Θ(N)\Theta(N) for the two cross spectra and the power spectrum, which are accumulated frame by frame. The real cost is the number of frames: the noise of CC falls as 1/F1/\sqrt F, and HH is small at high frequencies, so thousands of frames are usual.

Properties

  • It keeps the position of the object. φ(e1)\varphi(e_1) and φ(e2)\varphi(e_2) come from the data, so the image is placed where the object is, in the average over the frames.
  • It is not invariant to frame motion. A shift tt of frame ff multiplies its term in CC by e2πi Δ⋅t/ne^{2\pi i\, \Delta \cdot t / n}. Random motion lowers ∣H∣|H|, and only its symmetry keeps HH real.
  • It needs only two frequencies at a time. The stored cross spectra have 2N2N values, against the much larger bispectrum of speckle masking.
  • Errors add along paths. A wrong step at one frequency goes into every frequency after it on the path, so the error grows with ∣u∣|u|.
  • Phase only. The method gives no modulus; the modulus comes from speckle interferometry and a reference star.

Variants and improvements

  • More offsets and least squares. Use more offsets Δ\Delta and solve for all phases at once by least squares on the phase differences, in the same way as least squares phase unwrapping. This spreads the error over many paths.
  • Speckle masking. The bispectrum ⟨I(u) I(v) I(u+v)‾⟩\langle I(u)\, I(v)\, \overline{I(u + v)} \rangle is free of frame motion. See speckle masking. Ayers, Northcott and Dainty (1988) compare the two methods.
  • Frame selection. Keep the best frames first, as in lucky imaging, then apply the method to them.

When to use it

Use the Knox-Thompson method on short exposures of a bright object through turbulence, when a diffraction-limited image is needed and there is no adaptive optics. It needs many frames, each shorter than the time in which the air changes, and a reference star for the modulus. For faint objects, or when frame motion is large, speckle masking is more robust. For bright and compact objects, lucky imaging is simpler.

Pitfalls

  • Too large an offset. H(u,Δ)H(u, \Delta) falls fast when Δ\Delta is larger than a seeing cell in the frequency plane. Use unit offsets on a grid that samples the cutoff well.
  • Too few frames. The phases at high frequencies have a small ∣H∣|H|, and their noise needs many frames to average down.
  • Adding angles instead of phasors. Sums of angles wrap at ±π\pm\pi, and the mean of two angles near ±π\pm\pi is wrong; line L6 adds phasors to avoid this.
  • A changed atmosphere for the reference star. The modulus uses ⟨∣T∣2⟩\langle |T|^2 \rangle from another star at another time. If the seeing changed, the modulus is wrong, while the phase is not affected.
  • Photon noise. In photon-counting data the power spectrum has a bias from the photon count, and it must be removed before the modulus is formed.

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
knox_thompson_method.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/knox-thompson-method/. The authors are listed in prov/SH6M7B.jsonl.
"""Knox-Thompson phase recovery from simulated speckle frames.

Images are n x n and periodic. A frequency is a signed pair u = (u1, u2) with
-n/2 <= u1, u2 < n/2; a spectrum stores it at index [u1 mod n][u2 mod n]. The
object is a dict {(a, b): flux} of points at signed pixel offsets, so its
spectrum is O(u) = sum flux * exp(-2 pi i (u1 a + u2 b) / n).

A frame is made by one random phase screen over a disk pupil: the pupil field
P = mask * exp(i phi), the PSF |DFT(P)|^2, and the transfer function
T = DFT(PSF) / T(0). The frame spectrum is I = O * T. With a pupil of
diameter d < n / 2, T is zero beyond about d cells, so nothing wraps.
"""

import cmath
import math
import random

from imgkit import dft2, fftshift, idft2

E1, E2 = (1, 0), (0, 1)


def signed(k, n):
    """The signed frequency of index k."""
    return k if k < n - n // 2 else k - n


def object_spectrum(points, n):
    """O(u) for a dict {(a, b): flux} of point sources."""
    out = [[0j] * n for _ in range(n)]
    for k1 in range(n):
        for k2 in range(n):
            out[k1][k2] = sum(f * cmath.exp(-2j * math.pi * (k1 * a + k2 * b) / n) for (a, b), f in points.items())
    return out


def screen_amplitude(n, sigma):
    """Amplitudes |f|^(-11/6) of a Kolmogorov screen, scaled so that the expected rms phase is sigma."""
    amp = [[0.0] * n for _ in range(n)]
    for k1 in range(n):
        for k2 in range(n):
            f2 = signed(k1, n) ** 2 + signed(k2, n) ** 2
            amp[k1][k2] = 0.0 if f2 == 0 else f2 ** (-11.0 / 12.0)
    scale = sigma / math.sqrt(sum(a * a for row in amp for a in row))
    return [[a * scale for a in row] for row in amp]


def phase_screen(rng, amp):
    """A random phase screen: the real part of filtered complex white noise."""
    n = len(amp)
    spec = [[a * complex(rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)) for a in row] for row in amp]
    field = idft2(spec)
    return [[(v * n * n).real for v in row] for row in field]


def pupil_mask(n, d):
    """1 on the cells of a disk of diameter d at the center of the grid, 0 elsewhere."""
    c, r2 = n / 2.0 - 0.5, (d / 2.0) ** 2
    return [[1.0 if (i - c) ** 2 + (j - c) ** 2 <= r2 else 0.0 for j in range(n)] for i in range(n)]


def transfer_function(screen, mask):
    """The transfer function of one short exposure, with T(0) = 1."""
    field = dft2([[m * cmath.exp(1j * p) for m, p in zip(rm, rp)] for rm, rp in zip(mask, screen)])
    psf = [[abs(v) ** 2 for v in row] for row in field]
    t = dft2(psf)
    t0 = t[0][0].real
    return [[v / t0 for v in row] for row in t]


def simulate_frames(obj, n, d, sigma, draws, seed, antithetic=True):
    """Frame spectra I = O T for draws random screens.

    With antithetic = True each screen phi is also used as -phi, whose transfer
    function is conj(T). The pair keeps the symmetry phi -> -phi of the screen
    statistics exactly in the sample.
    """
    rng = random.Random(seed)
    amp = screen_amplitude(n, sigma)
    mask = pupil_mask(n, d)
    frames = []
    for _ in range(draws):
        t = transfer_function(phase_screen(rng, amp), mask)
        frames.append([[o * v for o, v in zip(ro, rt)] for ro, rt in zip(obj, t)])
        if antithetic:
            frames.append([[o * v.conjugate() for o, v in zip(ro, rt)] for ro, rt in zip(obj, t)])
    return frames


def cross_spectra(frames):
    """C_e(u) = mean of I(u) conj(I(u + e)) for e = e1 and e = e2."""
    n = len(frames[0])
    out = []
    for e1, e2 in (E1, E2):
        c = [[0j] * n for _ in range(n)]
        for f in frames:  # @line L1
            for k1 in range(n):
                for k2 in range(n):
                    c[k1][k2] += f[k1][k2] * f[(k1 + e1) % n][(k2 + e2) % n].conjugate()
        out.append([[v / len(frames) for v in row] for row in c])
    return out


def disk_order(n, radius):
    """The signed frequencies with |u| <= radius, sorted by |u1| + |u2|."""
    h = n // 2
    pts = [(a, b) for a in range(-h, n - h) for b in range(-h, n - h) if a * a + b * b <= radius * radius]
    return sorted(pts, key=lambda u: (abs(u[0]) + abs(u[1]), u))


def knox_thompson_phase(cross, n, radius):
    """Object phases phi(u) for |u| <= radius from the cross spectra (C_e1, C_e2)."""
    order = disk_order(n, radius)
    phase = {(0, 0): 0.0}  # @line L2
    for u in order[1:]:  # @line L3
        z = 0j  # @line L4
        steps = abs(u[0]) + abs(u[1])
        for c, (e1, e2) in zip(cross, (E1, E2)):  # @line L5
            for sgn in (1, -1):
                p = (u[0] - sgn * e1, u[1] - sgn * e2)
                if p not in phase or abs(p[0]) + abs(p[1]) != steps - 1:
                    continue
                if sgn == 1:  # u = p + e: arg C_e(p) = phi(p) - phi(u)
                    z += cmath.exp(1j * phase[p]) * c[p[0] % n][p[1] % n].conjugate()  # @line L6
                else:  # u = p - e: arg C_e(u) = phi(u) - phi(p)
                    z += cmath.exp(1j * phase[p]) * c[u[0] % n][u[1] % n]
        phase[u] = cmath.phase(z) if z != 0 else 0.0  # @line L7
    return phase  # @line L8


def power_spectrum(frames):
    """The mean of |I(u)|^2 over the frames (speckle interferometry)."""
    n = len(frames[0])
    return [[sum(abs(f[k1][k2]) ** 2 for f in frames) / len(frames) for k2 in range(n)] for k1 in range(n)]


def modulus_from_reference(obj_power, ref_power, phase):
    """|O(u)| = sqrt(<|I|^2> / <|T|^2>) on the frequencies of phase, from a point source reference."""
    n = len(obj_power)
    out = {}
    for u in phase:
        k1, k2 = u[0] % n, u[1] % n
        out[u] = math.sqrt(max(obj_power[k1][k2], 0.0) / ref_power[k1][k2]) if ref_power[k1][k2] > 0 else 0.0
    return out


def reconstruct(modulus, phase, n):
    """The real image with spectrum modulus * exp(i phase) on the given frequencies, center at n // 2."""
    spec = [[0j] * n for _ in range(n)]
    for u, ph in phase.items():
        spec[u[0] % n][u[1] % n] = modulus[u] * cmath.exp(1j * ph)  # @line L9
    img = idft2(spec)
    return fftshift([[v.real for v in row] for row in img])


def phase_error(phase, obj, n):
    """The largest |phi(u) - arg O(u)| over the recovered frequencies, wrapped to [0, pi]."""
    worst = 0.0
    for u, ph in phase.items():
        d = cmath.phase(cmath.exp(1j * (ph - cmath.phase(obj[u[0] % n][u[1] % n]))))
        worst = max(worst, abs(d))
    return worst
test_knox_thompson_method.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/knox-thompson-method/. The authors are listed in prov/SH6M7B.jsonl.

import cmath
import math
import random

from knox_thompson_method import (
    cross_spectra,
    knox_thompson_phase,
    modulus_from_reference,
    object_spectrum,
    phase_error,
    phase_screen,
    power_spectrum,
    pupil_mask,
    reconstruct,
    screen_amplitude,
    simulate_frames,
    transfer_function,
)

N, D, SIGMA, RADIUS = 16, 6, 3.0, 4
POINTS = {(0, 0): 1.0, (2, 1): 0.6, (-1, 3): 0.35}


def wrap(a):
    return abs(cmath.phase(cmath.exp(1j * a)))


def rms_error(phase, obj):
    errs = [wrap(ph - cmath.phase(obj[u[0] % N][u[1] % N])) for u, ph in phase.items()]
    return math.sqrt(sum(e * e for e in errs) / len(errs))


def test_transfer_function_of_one_frame():
    rng = random.Random(4)
    t = transfer_function(phase_screen(rng, screen_amplitude(N, SIGMA)), pupil_mask(N, D))
    assert abs(t[0][0] - 1.0) < 1e-12
    for k1 in range(N):
        for k2 in range(N):
            assert abs(t[k1][k2] - t[-k1 % N][-k2 % N].conjugate()) < 1e-12
            assert abs(t[k1][k2]) <= 1.0 + 1e-12
            if min(k1, N - k1) >= D or min(k2, N - k2) >= D:
                assert abs(t[k1][k2]) < 1e-12


def test_antithetic_cross_spectrum_has_the_object_phase_difference():
    obj = object_spectrum(POINTS, N)
    c1, _ = cross_spectra(simulate_frames(obj, N, D, SIGMA, 3, 7, antithetic=True))
    for k1 in range(N):
        for k2 in range(N):
            if abs(c1[k1][k2]) > 1e-9:
                want = cmath.phase(obj[k1][k2]) - cmath.phase(obj[(k1 + 1) % N][k2])
                d = wrap(cmath.phase(c1[k1][k2]) - want)
                assert d < 1e-7 or abs(d - math.pi) < 1e-7


def test_antithetic_average_gives_the_exact_phase():
    obj = object_spectrum(POINTS, N)
    phase = knox_thompson_phase(cross_spectra(simulate_frames(obj, N, D, SIGMA, 50, 1)), N, RADIUS)
    assert len(phase) == 49
    assert phase_error(phase, obj, N) < 1e-9
    for (a, b), ph in phase.items():
        assert wrap(ph + phase[(-a, -b)]) < 1e-9


def test_one_frame_is_not_enough_and_averaging_converges():
    obj = object_spectrum(POINTS, N)
    frames = simulate_frames(obj, N, D, SIGMA, 300, 1, antithetic=False)
    one = rms_error(knox_thompson_phase(cross_spectra(frames[:1]), N, RADIUS), obj)
    many = rms_error(knox_thompson_phase(cross_spectra(frames), N, RADIUS), obj)
    assert one > 1.0
    assert many < 0.15


def test_reconstruction_with_a_reference_star():
    obj = object_spectrum(POINTS, N)
    frames = simulate_frames(obj, N, D, SIGMA, 50, 1)
    ref = simulate_frames(object_spectrum({(0, 0): 1.0}, N), N, D, SIGMA, 50, 2)
    phase = knox_thompson_phase(cross_spectra(frames), N, RADIUS)
    img = reconstruct(modulus_from_reference(power_spectrum(frames), power_spectrum(ref), phase), phase, N)
    exact = {u: abs(obj[u[0] % N][u[1] % N]) for u in phase}
    true = reconstruct(exact, {u: cmath.phase(obj[u[0] % N][u[1] % N]) for u in phase}, N)
    peak = max(max(row) for row in true)
    assert max(abs(a - b) for ra, rb in zip(img, true) for a, b in zip(ra, rb)) < 0.05 * peak
    assert img[N // 2][N // 2] == max(max(row) for row in img)

History

Labeyrie (1970) showed that the average power spectrum of short exposures keeps the diffraction-limited modulus of the object, but not its phase. Knox and Thompson (1974) found that the cross spectrum at two close frequencies keeps the phase differences, and that a recursion gives the phase. Weigelt (1977) introduced speckle masking with triple correlations, and Lohmann, Weigelt and Wirnitzer (1983) wrote it with the bispectrum. Ayers, Northcott and Dainty (1988) compared the two phase methods.

References

  1. K. T. Knox and B. J. Thompson, Recovery of images from atmospherically degraded short-exposure photographs, The Astrophysical Journal 193, 1974, pp. L45 to L48 (the cross spectrum of the frames, its transfer function and the recursion for the phase)
  2. G. R. Ayers, M. J. Northcott and J. C. Dainty, Knox-Thompson and triple-correlation imaging through atmospheric turbulence, Journal of the Optical Society of America A 5(7), 1988, the article from page 963 (a comparison of the cross spectrum and the bispectrum on simulated and real data)
  3. Joseph W. Goodman, Statistical Optics, second edition, Wiley, 2015, the chapter on imaging through randomly inhomogeneous media (short exposures, speckle interferometry and the recovery of the phase)

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