Algorithmadvanced
Speckle masking
Also called bispectrum imaging, triple correlation imaging.
Recover the Fourier phase of an object from short exposure speckle images by averaging their bispectrum, whose phase is free of turbulence.
- Time
- Θ(F N (log N + V)) worst · average · best
- Space
- Θ(V N) extra
- Where
- F = the number of frames; N = the number of pixels in a frame; V = the number of offsets v kept in the bispectrum
- Model
- Real RAM
- Properties
- deterministicnot iterativenot linearneeds reference star for modulusshift invariant
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gerd Weigelt, 1977
Speckle masking recovers the Fourier phase of an object from many short exposures taken through atmospheric turbulence. It averages the bispectrum of the frames, whose phase is the closure phase of the object, and it recovers by a recursion over the frequency plane. Speckle interferometry gives only the Fourier modulus. The Knox-Thompson method gets the phase from a cross spectrum, which image motion disturbs; the bispectrum does not change when a frame moves, but in return it loses the position of the object.
In plain words
A short exposure through moving air breaks the image of a star into many small spots, called speckles. Each frame still holds the fine detail, but the air mixes up where it is. Speckle masking takes three details at a time, chosen so that the third one is the sum of the first two. The air changes the three positions in a way that cancels in a fixed combination, and so does any motion of the whole frame. Averaged over many frames, this combination gives a sum of three object positions that the air does not hide. From these sums the method builds the position of each detail, step by step, out from the coarsest one. Only one thing stays unknown: where the whole object is in the frame. With the strengths of the details 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 the instantaneous PSF is the squared modulus of the Fourier transform of the pupil field for a random phase screen . In the frequency plane , with the random optical transfer function and .
The input is frame spectra, a set of offsets and a radius inside the cutoff of the telescope. The output is an estimate of for , up to a term that is linear in . With from speckle interferometry, the inverse DFT of is the image, up to a shift.
The algorithm
The average bispectrum factors as
If the screen statistics do not change when is replaced by , the speckle masking transfer function is real. Where , the phase of is the closure phase , and so
A shift of a frame multiplies by , and the three factors cancel in . The same cancellation means that and have the same closure phases for every vector , so and are free. The recursion sets them to given values, by default 0, and walks outward with the two offsets .
SPECKLE-MASKING(I_1, ..., I_F, R, τ1, τ2) ▷ τ1, τ2 fix the free linear term- 1
B_e(u) ← (1/F) Σ_f I_f(u) · I_f(e) · conj(I_f(u + e)) for e ∈ {e1, e2} and every u - 2
φ(0) ← 0, φ(e1) ← τ1, φ(e2) ← τ2 - 3
for each other u 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) + φ(e))} · conj(B_e(p)) if u = p + e, or e^{i(φ(p) - φ(e))} · B_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)
The full bispectrum of an image has a value for every pair , which is values. The recursion needs only small offsets , so implementations keep a few planes of near the origin; this page keeps the two unit offsets, which is values. Line L6 adds phasors weighted by , so there is no wrapping of angles, and a frequency off the axes combines two paths.
Example
The setup is the same as on the Knox-Thompson page: , a disk pupil of diameter 6 cells, phase screens with the Kolmogorov power spectrum and an expected rms phase of 3 radians, and an object of three points with flux 1 at , 0.6 at and 0.35 at . The object has and , which the bispectrum cannot see. Along the axis, the transfer function , measured on a point source with 50 antithetic pairs of screens (seed 2), is 0.155, 0.0269, 0.0094, 0.0042 and 0.0021 at . At it is , the value that speckle interferometry uses.
The method recovers the 49 phases with . The table gives the phase error in radians after the free linear term is removed, with independent screens (seed 1). The last column is the rms error of the Knox-Thompson method on the same frames.
| frames | largest error | rms error | rms error of Knox-Thompson |
|---|---|---|---|
| 1 | 3.048 | 1.860 | 1.495 |
| 10 | 0.621 | 0.190 | 0.223 |
| 30 | 0.203 | 0.105 | 0.677 |
| 100 | 0.112 | 0.051 | 0.402 |
| 300 | 0.052 | 0.028 | 0.101 |
With 50 antithetic pairs, where each screen is also used as , the averaged is exactly real and positive at all 49 frequencies, and the phases are exact to rounding. They stay exact when every frame is moved by a random shift of up to 2 pixels in each direction, because the bispectrum does not change. With one antithetic pair, is negative at some frequencies and the largest error is . With the modulus from 50 antithetic pairs of a reference star (seed 2), the image differs from the object, cut to and moved by the free linear term, by at most 0.0075, against its peak of 0.193.
Correctness
The factorization of holds because is the same in every frame. If the law of equals 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. A frame shift multiplies the three factors by , and , whose product is 1. Where on every step of the recursion, each term of line L6 is times a positive number, where is the object phase with the linear term set by ; by induction on , line L7 returns . As , the sample bispectrum converges to by the law of large numbers, so the returned phases converge to . That on the steps is an assumption about the turbulence; it held at every frequency of the example. The full proof is below.
Proof: The speckle masking recursion returns the object phase up to a linear term wherever the bispectrum 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 bispectrum, the transfer function and the expected bispectrum
Let with , ordered by as in line L3. A step is a pair with , and ; these are the pairs that line L6 uses. For the values of line L2, let and . Then , and .
Claim 1 (the bispectrum factors). , and .
Proof. Each of the three factors of is times at the same frequency, 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 . is real, so , and . Hence , and since is real, . The scale is the same for both screens.
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, the triple product for is the conjugate of the triple product for . Under a symmetric law both have the same expectation, 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 (image motion and linear phase terms). If frame is moved by , so that becomes , then does not change. For every real vector , .
Proof. The three factors of the frame bispectrum get , and , and the product of the three is 1. For the second part, .
So no bispectrum, sample or expected, can tell from . The recursion returns , which is the object phase up to the linear term , a shift of the reconstructed image.
Claim 5 (the recursion is exact on positive data). Suppose the bispectra 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 Claim 4, . Line L2 sets , and . Now use induction in the order of line L3, and assume that is correct for every before . Every with has at least one step : move one unit toward the origin along a nonzero coordinate; this lowers by one and does not raise , so , and comes before . Write for positive numbers. For a step with , the term of line L6 is
For a step with , so , the term is
Every term is times a positive number, and there is at least one term, so and line L7 returns .
With antithetic pairs, Claim 3 makes the real sample transfer function, so Claim 5 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 6 (convergence in the number of frames). Suppose the law of is symmetric, on the steps as in Claim 5, and on . Then, with probability 1, the phases returned from converge to on as .
Proof. The triple products 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 5, the recursion applied to returns , and in the proof of Claim 5 every is nonzero. Each is a continuous function of the bispectra 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 . By Claim 4 the same holds when the frames move.
Remark (what is assumed). Claim 6 assumes on the steps. Claim 3 gives only that is real. At the value is , the transfer function of speckle interferometry, and it is positive unless almost surely. At other , positivity is a property of the turbulence, and the proof does not cover the sign of in general.
Complexity
Each frame needs one FFT, , and one triple product per frequency and offset, , so frames cost . The recursion is . The extra space is for the kept planes of the bispectrum; the full bispectrum would need . As for every speckle method, the real cost is the number of frames.
Properties
- Free of image motion. A shift of a frame does not change its bispectrum, so random tip and tilt of the air do not lower .
- The position is lost. The closure phases do not fix and , so the image comes out at an arbitrary place. A long exposure or a known feature fixes the shift.
- The phase of a point-symmetric object is trivial. Then is 0 or after centering, and the bispectrum adds little to the power spectrum.
- Errors add along paths. A wrong closure phase goes into every frequency after it on the path.
- Phase only. The modulus comes from speckle interferometry with a reference star.
Variants and improvements
- More offsets and least squares. Keep more planes of and solve for all phases at once by weighted least squares on the closure phases, which spreads the error over many paths.
- Full triple correlation. Weigelt (1977) worked with the triple correlation of the frames in the image domain, whose Fourier transform is the bispectrum.
- Photon-noise bias correction. In photon-counting data the bispectrum has bias terms from the photon count, which must be removed before the phase is formed.
- Closure phases in radio and optical interferometry. The bispectrum phase of three antennas or apertures is free of the phase errors of each antenna, the same cancellation as here. See aperture synthesis.
When to use it
Use speckle masking on short exposures of an object through turbulence when a diffraction-limited image is needed without adaptive optics, and in particular when image motion is large or the object is faint, where the Knox-Thompson method is weaker. If the position of the object matters, fix it from a long exposure. For bright, compact objects, lucky imaging is simpler.
Pitfalls
- Too few frames. is small at high frequencies, and the noise of the bispectrum needs many frames to average down.
- Forgetting the free linear term. Comparing the result with the truth without removing gives a large apparent error, and the image is shifted.
- Adding angles instead of phasors. Sums of angles wrap at ; line L6 adds phasors.
- Memory. The full bispectrum of a 2D image is 4D. Keep only the planes of small that the recursion uses.
- 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.
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
speckle_masking.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/speckle-masking/. The authors are listed in prov/A53FCA.jsonl.
"""Speckle masking (bispectrum 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.
The bispectrum is kept only on the plane v in {e1, e2}: B_e(u) is the mean of
I(u) I(e) conj(I(u + e)).
"""
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 shift_frames(frames, seed, max_shift):
"""Move each frame by a random whole-pixel shift with |t1|, |t2| <= max_shift (image motion)."""
rng = random.Random(seed)
n = len(frames[0])
out = []
for f in frames:
t1, t2 = rng.randint(-max_shift, max_shift), rng.randint(-max_shift, max_shift)
out.append([[f[k1][k2] * cmath.exp(-2j * math.pi * (k1 * t1 + k2 * t2) / n) for k2 in range(n)] for k1 in range(n)])
return out
def bispectra(frames):
"""B_e(u) = mean of I(u) I(e) conj(I(u + e)) for e = e1 and e = e2."""
n = len(frames[0])
out = []
for e1, e2 in (E1, E2):
b = [[0j] * n for _ in range(n)]
for f in frames: # @line L1
ie = f[e1][e2]
for k1 in range(n):
for k2 in range(n):
b[k1][k2] += f[k1][k2] * ie * f[(k1 + e1) % n][(k2 + e2) % n].conjugate()
out.append([[v / len(frames) for v in row] for row in b])
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 speckle_masking_phase(bis, n, radius, tilt=(0.0, 0.0)):
"""Object phases phi(u) for |u| <= radius from the bispectra (B_e1, B_e2).
tilt gives phi(e1) and phi(e2), which the bispectrum does not fix; they set
the position of the image.
"""
order = disk_order(n, radius)
phase = {(0, 0): 0.0, E1: tilt[0], E2: tilt[1]} # @line L2
for u in order[1:]: # @line L3
if u in phase:
continue
z = 0j # @line L4
steps = abs(u[0]) + abs(u[1])
for b, e, pe in zip(bis, (E1, E2), tilt): # @line L5
for sgn in (1, -1):
p = (u[0] - sgn * e[0], u[1] - sgn * e[1])
if p not in phase or abs(p[0]) + abs(p[1]) != steps - 1:
continue
if sgn == 1: # u = p + e: arg B_e(p) = phi(p) + phi(e) - phi(u)
z += cmath.exp(1j * (phase[p] + pe)) * b[p[0] % n][p[1] % n].conjugate() # @line L6
else: # u = p - e: arg B_e(u) = phi(u) + phi(e) - phi(p)
z += cmath.exp(1j * (phase[p] - pe)) * b[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 phase error after removing the linear term that the bispectrum cannot see, in [0, pi]."""
a1 = cmath.phase(obj[1][0]) - phase[E1]
a2 = cmath.phase(obj[0][1]) - phase[E2]
worst = 0.0
for u, ph in phase.items():
want = cmath.phase(obj[u[0] % n][u[1] % n]) - a1 * u[0] - a2 * u[1]
worst = max(worst, abs(cmath.phase(cmath.exp(1j * (ph - want)))))
return worst
test_speckle_masking.py 87 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/speckle-masking/. The authors are listed in prov/A53FCA.jsonl.
import cmath
import math
from speckle_masking import (
bispectra,
modulus_from_reference,
object_spectrum,
phase_error,
power_spectrum,
reconstruct,
shift_frames,
simulate_frames,
speckle_masking_phase,
)
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):
a1 = cmath.phase(obj[1][0]) - phase[(1, 0)]
a2 = cmath.phase(obj[0][1]) - phase[(0, 1)]
errs = [wrap(ph - cmath.phase(obj[u[0] % N][u[1] % N]) + a1 * u[0] + a2 * u[1]) for u, ph in phase.items()]
return math.sqrt(sum(e * e for e in errs) / len(errs))
def test_bispectrum_does_not_see_image_motion():
obj = object_spectrum(POINTS, N)
frames = simulate_frames(obj, N, D, SIGMA, 4, 3)
still = bispectra(frames)
moved = bispectra(shift_frames(frames, 9, 3))
for a, b in zip(still, moved):
for ra, rb in zip(a, b):
for x, y in zip(ra, rb):
assert abs(x - y) < 1e-12
def test_antithetic_bispectrum_has_the_closure_phase():
obj = object_spectrum(POINTS, N)
b1, _ = bispectra(simulate_frames(obj, N, D, SIGMA, 3, 7))
ph = [[cmath.phase(v) for v in row] for row in obj]
for k1 in range(N):
for k2 in range(N):
if abs(b1[k1][k2]) > 1e-9:
want = ph[k1][k2] + ph[1][0] - ph[(k1 + 1) % N][k2]
d = wrap(cmath.phase(b1[k1][k2]) - want)
assert d < 1e-7 or abs(d - math.pi) < 1e-7
def test_antithetic_average_gives_the_phase_up_to_a_shift():
obj = object_spectrum(POINTS, N)
frames = shift_frames(simulate_frames(obj, N, D, SIGMA, 50, 1), 5, 2)
phase = speckle_masking_phase(bispectra(frames), N, RADIUS)
assert len(phase) == 49
assert phase_error(phase, obj, N) < 1e-9
tilted = speckle_masking_phase(bispectra(frames), N, RADIUS, tilt=(cmath.phase(obj[1][0]), cmath.phase(obj[0][1])))
for u, ph in tilted.items():
assert wrap(ph - cmath.phase(obj[u[0] % N][u[1] % N])) < 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(speckle_masking_phase(bispectra(frames[:1]), N, RADIUS), obj)
many = rms_error(speckle_masking_phase(bispectra(frames), N, RADIUS), obj)
assert one > 1.0
assert many < 0.05
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)
tilt = (cmath.phase(obj[1][0]), cmath.phase(obj[0][1]))
phase = speckle_masking_phase(bispectra(frames), N, RADIUS, tilt)
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
History
Labeyrie (1970) showed that the average power spectrum of short exposures keeps the diffraction-limited modulus, and Knox and Thompson (1974) recovered the phase from cross spectra. Weigelt (1977) introduced speckle masking with triple correlations, and Lohmann, Weigelt and Wirnitzer (1983) gave its theory in terms of the bispectrum and its transfer function. Bartelt, Lohmann and Wirnitzer (1984) studied the recursive recovery of the phase and the modulus from bispectra, and Ayers, Northcott and Dainty (1988) compared speckle masking with the Knox-Thompson method.
References
- G. P. Weigelt, Modified astronomical speckle interferometry 'speckle masking', Optics Communications 21(1), 1977, pp. 55 to 59 (the triple correlation of the frames and the reconstruction of the object)
- A. W. Lohmann, G. Weigelt and B. Wirnitzer, Speckle masking in astronomy, triple correlation theory and applications, Applied Optics 22(24), 1983, pp. 4028 to 4037 (the bispectrum, the speckle masking transfer function and the recursion for the phase)
- H. Bartelt, A. W. Lohmann and B. Wirnitzer, Phase and amplitude recovery from bispectra, Applied Optics 23(18), 1984, the article from page 3121 (recursive recovery of the Fourier phase from the bispectrum)
- 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 bispectrum and the cross spectrum on simulated and real data)
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 A53FCA Edit this page History Report an error Markdown