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
- Model
- Real RAM
- Properties
- deterministicnot iterativenot linearneeds reference star for modulusnot shift invariant
- Evidence
- Proof sketchCode in 1 languages
- 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 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 is a real nonnegative image on an periodic grid, with and the DFT at the signed frequencies . A short exposure is , where is the instantaneous point spread function: the squared modulus of the Fourier transform of the pupil field , with the pupil and the random phase screen of the air. In the frequency plane,
where is the optical transfer function of frame , scaled to . The transfer function is random and has random phases, so the average keeps only the low frequencies (the long exposure), and the average power spectrum keeps the modulus but not the phase.
The input is frame spectra and a radius inside the cutoff of the telescope. The output is an estimate of for . With from speckle interferometry, the inverse DFT of is the image.
The algorithm
For an offset , the average cross spectrum factors as
If the screen statistics do not change when is replaced by , as for a Gaussian screen, then is real. Where , the phase of is . The method uses the two unit offsets and , sets because is the total flux, and walks outward in the order of .
KNOX-THOMPSON(I_1, ..., I_F, R)- 1
C_e(u) ← (1/F) Σ_f I_f(u) · conj(I_f(u + e)) for e ∈ {e1, e2} and every u - 2
φ(0) ← 0 - 3
for each u ≠ 0 with |u| ≤ R, in the order of |u1| + |u2| do - 4
z ← 0 - 5
for each known neighbor p = u ∓ e with |p1| + |p2| = |u1| + |u2| - 1 do - 6
z ← z + e^{iφ(p)} · conj(C_e(p)) if u = p + e, or e^{iφ(p)} · C_e(u) if u = p - e - 7
φ(u) ← arg z - 8
return φ RECONSTRUCT(M, φ, R) ▷ M is the modulus from speckle interferometry- 9
return 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 has more weight. A frequency off the axes has two neighbors closer to the origin, and line L7 combines both paths. The modulus comes from the same frames: , where is the power spectrum of frames of a point source, the reference star.
Example
Take , a disk pupil of diameter cells, and an object of three points: flux 1 at the offset , 0.6 at and 0.35 at . Each phase screen is filtered white noise with the power spectrum of Kolmogorov turbulence and an expected rms phase of 3 radians, from random.Random(seed). The transfer function of a frame is zero at or .
Along the axis, the transfer function without turbulence is 1, 0.8125, 0.625, 0.4375, 0.25 and 0.125 at . The long exposure keeps at and 0.030 at , so it loses everything beyond the first ring. The speckle transfer function is 1, 0.155, 0.040, 0.020, 0.011 and 0.005, and is 0.300, 0.044, 0.017, 0.009 and 0.004 at : small, but positive up to the cutoff.
The method recovers the 49 phases with . The table gives the largest and the rms phase error, in radians, with independent screens (seed 1) and with antithetic pairs, where each screen is also used as .
| 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 exactly real, so each phase is exact or off by ; with one pair 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 , by at most 0.0075, against its peak of 0.193, and the brightest pixel is at the true position.
Correctness
The factorization of is the linearity of the average, because does not change from frame to frame. If the law of is the same as the law of , then and have the same law, because the PSF of is the PSF of turned by 180 degrees. So equals its own conjugate and is real. Where along every step that line L6 uses, each term added to is times a positive number, by induction on , so line L7 returns exactly. The sample average converges to the expected value as by the law of large numbers, so the computed phases converge to wherever the expected is positive. That 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 and periodic, , and frequencies are signed, with arithmetic mod . The object is real and nonnegative with , and is its DFT. The pupil is a real function on the grid. For a real phase screen , the PSF is and the transfer function is . The screens are independent with a common law , and frame has .
For define the sample and expected cross spectra and the transfer function
Let , ordered by as in line L3. A step is a pair with , and ; these are the pairs that line L6 uses.
Claim 1 (the cross spectrum factors). , and .
Proof. , and does not depend on . Take the mean over , then the expectation; is bounded by Claim 2, so the expectation exists.
Claim 2 (the transfer function of one frame). , , and . For the screen , .
Proof. and when , so , and . Since is real, . For the last part, is real, so , and . Hence , and . The scale is the same for both.
Claim 3 (a symmetric law gives a real transfer function). If and have the same law , then is real for every . If the screens come in pairs , then the sample transfer function is real for every .
Proof. By Claim 2, . Under a symmetric law the left side has the same expectation as the product for , so . For a pair, the two terms are conjugates, and their sum is real.
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 with real, and for every step and for every step with . Suppose also that on . Then lines L2 to L8 return for every , mod .
Proof. By induction in the order of line L3. is correct because . Take and assume is correct for all before . Every , , has at least one step : move one unit toward the origin along a nonzero coordinate; this lowers by one and does not raise , so . For a step with , the term is
For a step with , so , the term is
Every term is times a positive number, and there is at least one term, so with , and line L7 returns .
With antithetic pairs, Claim 3 makes 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 .
Claim 5 (convergence in the number of frames). Suppose the law of is symmetric, on the steps as in Claim 4, and on . Then, with probability 1, the phases returned from converge to on as .
Proof. The terms are independent, have the same law and are bounded by 1 (Claim 2). By the strong law of large numbers their mean converges to with probability 1, for each of the finitely many and , so by Claim 1. By Claims 3 and 4, the recursion applied to returns , and in the proof of Claim 4 every is nonzero. The recursion is continuous at such data: each is a continuous function of the cross spectra and of the earlier phases through , and is continuous at a nonzero (as a map to the circle). By induction in the order of line L3, every returned phase converges to mod .
Remark (what is assumed). Claim 5 assumes on the steps. Claim 3 gives only that is real. Positivity is a property of the turbulence and of the offset: is the long-exposure transfer function at , and is small when the offset is larger than a seeing cell in the frequency plane. The proof does not cover the sign of in general.
Complexity
Each frame needs one FFT, , and two products per frequency, , so frames cost . The recursion visits each frequency once with at most four neighbors, . The extra space is 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 falls as , and is small at high frequencies, so thousands of frames are usual.
Properties
- It keeps the position of the object. and 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 of frame multiplies its term in by . Random motion lowers , and only its symmetry keeps real.
- It needs only two frequencies at a time. The stored cross spectra have 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 .
- 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 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 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. falls fast when 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 , and their noise needs many frames to average down.
- Adding angles instead of phasors. Sums of angles wrap at , and the mean of two angles near is wrong; line L6 adds phasors to avoid this.
- A changed atmosphere for the reference star. The modulus uses 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.
# 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
- 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)
- 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)
- 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.
| 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 SH6M7B Edit this page History Report an error Markdown