Algorithmadvanced
Zonal wavefront reconstruction
Also called Shack-Hartmann wavefront reconstruction, Southwell reconstruction.
Recover a wavefront on a grid of phase points from measured slopes by least squares. The normal equations are a discrete Poisson equation; piston, and waffle for Fried, are lost.
- Solves
- Linear least squares
- Time
- Θ(K n^2) worst · average · best
- Space
- Θ(n^2) extra
- Where
- K = the number of conjugate gradient iterations; n = the number of phase points along one side of the grid
- Model
- Real RAM
- Properties
- deterministicexact for consistent slopesiterativelinearminimum norm
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David L. Fried, Richard H. Hudgin, W. H. Southwell, 1977
Zonal wavefront reconstruction recovers the phase of an optical wavefront at the points of a grid from measurements of its slopes. A Shack-Hartmann sensor, for example, puts an array of small lenses in the beam; each lens forms a spot, and the shift of the spot is proportional to the mean slope of the wavefront over that lens. "Zonal" means that the unknowns are the phase values at the grid points, one per zone, as opposed to a modal method, which fits the coefficients of a few smooth modes such as Zernike polynomials. The slopes are differences of phase values, so the data are with a sparse difference matrix , and the method solves the least squares problem . Its normal equations are a discrete Poisson equation with Neumann boundary data. Two things are never seen by the sensor: the mean phase (piston), and in the Fried geometry also the checkerboard "waffle" mode. The method returns the minimum norm solution, which sets these to zero. The same least squares problem, with wrapped phase differences as data, is least squares phase unwrapping.
In plain words
Think of a hilly field that you cannot see. You can only stand at points of a grid and measure how steep the ground is toward the east and toward the north. Each measurement tells you the height difference between two neighbor points, with some error. From all these differences you want the heights. With no errors, you could walk from one corner and add up the differences, and every path would agree. With errors, paths disagree. Least squares picks the heights whose differences match all the measurements as well as possible in total. The absolute height of the field is never measured, only differences, so the answer is fixed only up to a constant; you set the mean height to zero. In one sensor layout there is one more blind pattern, a checkerboard of up and down, which gives zero in every measurement.
The problem
The phase lives on an grid of points with spacing ; has row (the index) and column (the index). The data are slopes times , so they have the units of phase. Three geometries are in use:
- Hudgin. Each measurement is the difference of two neighbor points: and . There are measurements.
- Fried. The sensor sits at the center of each square of four phase points, the usual layout for a Shack-Hartmann sensor in front of a deformable mirror. The slope is the mean of the two differences of the square: , and the same for . There are measurements.
- Southwell. The slopes are measured at the phase points. The model is that the mean of two neighbor slopes times is the phase difference: . This is the Hudgin matrix with averaged data.
In each case with a known sparse matrix and noise , white with variance per measurement in the usual analysis. The output is the minimum norm least squares solution (see pseudoinverse).
The algorithm
The normal equations have a symmetric positive semidefinite matrix, and the right side is in its range. Conjugate gradients from solve them without forming the matrix; each step applies and once.
ZONAL-LS(s, G, K, tol) ▷ s = slopes times h; G = Hudgin or Fried differences- 1
b ← G^T s ▷ minus a discrete divergence of the slopes - 2
phi ← 0; r ← b; p ← r - 3
repeat at most K times, while ||r|| > tol · ||b|| - 4
q ← G^T (G p) ▷ a discrete Laplacian applied to p - 5
a ← <r, r> / <p, q> - 6
phi ← phi + a · p - 7
r' ← r - a · q - 8
p ← r' + (<r', r'> / <r, r>) · p; r ← r' - 9
phi ← phi minus its projection on the null space of G ▷ piston; for Fried also waffle - 10
return phi
For Southwell data, first form the Hudgin data and , then run the Hudgin version. Line L9 removes rounding drift; in exact arithmetic every iterate is already orthogonal to the null space.
For the Hudgin geometry, is the forward difference and is minus the backward difference divergence, so is the 5-point Laplacian with Neumann boundary: a row has the number of neighbors of the point on the diagonal (4 inside, 3 on an edge, 2 at a corner) and for each neighbor.
Example
One loop. Take the Hudgin grid with four measurements around one square: (top edge) and on the other three edges. The four differences around the loop should add to zero (the curl of a gradient is zero), but they add to . Least squares spreads this misfit equally over the four edges: the fitted differences are on the top edge, on the bottom edge and and on the left and right edges, and each fitted value differs from its datum by , so the residual norm squared is . The minimum norm solution is
with mean zero. The test runs the code in exact rational arithmetic and gets this matrix; CG stops after two steps, because has two distinct nonzero eigenvalues here (2 and 4).
The waffle. On a Fried grid, add the checkerboard to any phase. In each square the two differences are and , so their mean is zero, and the same for . The sensor does not see . A deformable mirror driven by a Fried reconstructor can build up waffle over time, since nothing measures it.
CG on a random phase. A measurement on one seed: an Hudgin grid with a random Gaussian phase and exact data. The relative error of the CG iterate is 0.58 after 1 step, 0.36 after 4, 0.18 after 8, 0.0052 after 16 and after 32 steps.
Noise. With white noise of variance on each Hudgin difference, the mean square error of the reconstructed phase per point is , summed over the nonzero eigenvalues of the Neumann Laplacian. Computed from this formula:
| 4 | 8 | 16 | 32 | 64 | 128 | |
|---|---|---|---|---|---|---|
| error variance per point | 0.493 | 0.632 | 0.755 | 0.872 | 0.985 | 1.097 |
| condition number of on the range | 11.7 | 50.5 | 206.2 | 828.7 | 3318.8 | 13279.0 |
The noise grows only like , by about each time doubles. Fried (1977) and Hudgin (1977) both studied this noise propagation; its slow growth is the reason why zonal reconstruction works for large sensors. The condition number grows like , so plain iterations need many steps on a large grid.
Correctness
The full proof is in proofs/correctness.md. The main facts:
- Normal equations. minimizes if and only if . For Hudgin, is the Neumann 5-point Laplacian, so the problem is a discrete Poisson equation.
- Null space. For Hudgin (and Southwell), the null space of is the constants (piston), because the grid graph is connected. For Fried with , it is spanned by the piston and the waffle , and nothing else.
- CG gives the minimum norm solution. The right side is orthogonal to the null space, and every CG iterate from stays in the range of . So CG converges to the unique least squares solution in that range, which is , in at most as many steps as has distinct nonzero eigenvalues (exact arithmetic).
- Exact data. If , the output is minus its projection on the null space: the true phase up to piston (and waffle for Fried).
- Southwell is exact for quadratics. If is a polynomial of degree at most 2 in and and the slopes are exact, then equals the phase difference exactly (the trapezoid rule is exact for a linear integrand), so Southwell recovers defocus, astigmatism and tilt up to piston.
Proof: Zonal least squares returns the minimum norm phase, and the null space is piston (and waffle for Fried)full
Setting. The phase is a real vector indexed by the points of an grid, . The data are real, and is the difference matrix of the Hudgin or the Fried geometry, as defined on the page. The algorithm is lines L1 to L10: conjugate gradients (CG) on from , then the removal of the null space component.
Claim 1 (normal equations). minimizes if and only if .
Proof. is a convex quadratic with gradient . A convex differentiable function has its minimum exactly where the gradient is zero.
Claim 2 (Hudgin normal matrix). For the Hudgin geometry, , the sum over the grid neighbors of . So is the graph Laplacian of the grid, which is the 5-point Laplacian with Neumann boundary.
Proof. , since each row of is one edge difference. The quadratic form is the form of the graph Laplacian , with the diagonal of degrees and the adjacency matrix. Two symmetric matrices with the same quadratic form are equal.
Claim 3 (Hudgin null space). For Hudgin, if and only if is constant.
Proof. If , then for every edge. The grid graph is connected, so takes one value on all points. Conversely a constant gives zero differences.
The Southwell geometry uses the Hudgin matrix with other data, so it has the same null space.
Claim 4 (Fried null space). For Fried with , if and only if with .
Proof. Take one square with the corners , , and . Its two measurements are zero when and . The sum gives and the difference gives . So in every square the two diagonal corners are equal: and . These are steps on the grid, and they keep the parity of . Any two points of the same parity are joined by a path of such steps inside the grid (move diagonally, and zigzag where a border is reached; ). So is constant, say , on the points with even, and constant, say , on the points with odd. This is with and . Conversely, the computation on the page shows that gives zero for every square, and so does .
The vectors and are orthogonal for even . For odd the sum of is , so the code uses , which spans the same plane with and is orthogonal to it.
Claim 5 (CG returns the minimum norm solution). Let and . In exact arithmetic CG from stops after at most steps, where is the number of distinct nonzero eigenvalues of , with .
Proof. The null space of equals the null space of , since gives . The vector is in the range of , which is the orthogonal complement of the null space of . Let be this range; maps into and is positive definite on . Every CG quantity (, , , ) is a linear combination of , so all of them stay in . On , CG is the standard method for a symmetric positive definite matrix, and the standard theory applies: minimizes the -norm of the error over the Krylov space , and the Krylov space stops growing after at most steps, when it contains the solution. So CG reaches the unique solution of , and the residual becomes . By Claim 1, is a least squares solution. Every least squares solution is with in the null space, and because . So is the one of minimum norm, which is . Line L9 subtracts the projection on the null space, which is zero in exact arithmetic.
Claim 6 (exact data). If , the output is , with the orthogonal projection on the null space of .
Proof. is in and has , so it is a least squares solution with zero residual, in . By Claim 5 it is the output.
Claim 7 (Southwell is exact for quadratic phases). Let be a polynomial of degree at most 2, sampled at the grid points with spacing , and let and at the points. Then the Southwell data are the exact Hudgin differences of the samples, and the output is the samples minus their mean.
Proof. Along one grid row, . The integrand is linear in , and the trapezoid rule is exact for linear functions. The same holds along columns. So the data are for the Hudgin , and Claim 6 gives the result.
Claim 8 (noise). If with white of variance , the error of the Hudgin output (on the part outside the null space) has the total variance , the sum over the nonzero eigenvalues of the Neumann Laplacian, for .
Proof. The covariance of is , a standard identity of the pseudoinverse. Its trace is the sum of the inverse nonzero eigenvalues. The 1D Neumann path Laplacian has the eigenvectors with eigenvalues , and the grid Laplacian is the Kronecker sum of two of them, so its eigenvalues are the sums.
The tests check Claims 2, 3 and 4 (by the eigenvalues of the dense normal matrix), Claim 5 (against a dense solve of , whose unique solution is , and on the exact rational example of the page), Claim 6 for both geometries, Claim 7, and the adjoint pair , .
Complexity
In the real-RAM model, one application of or costs , so one CG step costs and steps cost , with extra space. The condition number of on its range grows like (table above), so CG needs steps for a relative error , which gives in total. Other solvers of the same system:
- Dense Gaussian elimination on the matrix: . An adaptive optics system with a fixed geometry precomputes the reconstructor matrix once and then applies it to each slope frame by a matrix-vector product, per frame.
- For Hudgin and Southwell the matrix is the Neumann Laplacian, which the 2D DCT diagonalizes (fast DCT), so a direct solve costs . Freischlad and Koliopoulos (1986) used Fourier transforms in this way. The same trick solves least squares phase unwrapping.
- Multigrid solves the Poisson system to a fixed accuracy in .
- Gauss-Seidel and Jacobi sweeps, used in early hardware reconstructors, need sweeps.
Properties
- Linear in the data: the output is .
- Minimum norm: piston (and waffle for Fried) is set to zero. Any other choice is a constant (or a waffle) added to the result.
- The residual is the part of the data that is not a gradient. On a grid it is a sum of loop (curl) components; for a smooth wavefront in a weak turbulence it is noise, but at a branch point of the phase (strong scintillation) the true field has curl, and least squares cannot represent it.
- Noise propagation is low: the error variance per point grows like .
Variants and improvements
- Weighted least squares. Weight each slope by the inverse of its noise variance, for example by the spot photon count. The matrix is then a weighted Laplacian, and CG still applies.
- Modal reconstruction. Fit the coefficients of a few Zernike or Karhunen-Loeve modes instead of the phase at every point. This is a small dense least squares problem; it filters noise but cannot represent detail finer than the modes.
- Minimum variance (MAP) reconstruction. Add a prior covariance of the phase, for example the Kolmogorov statistics of turbulence, which turns the problem into a regularized one, like Tikhonov regularization, and removes the null space.
- Branch point reconstruction. For strong turbulence, add a reconstruction of the rotational part of the field, as in phase unwrapping with residues (see phase unwrapping).
- Curvature sensing. A curvature sensor measures the Laplacian of the phase directly, with the slopes at the edge as Neumann data; the same Poisson solver applies.
When to use it
Use zonal least squares to turn Shack-Hartmann, shearing interferometer or pyramid sensor slopes into a phase map, in adaptive optics and in optical testing. It is the default when the wavefront may have structure at the scale of the sensor grid. Use the Fried geometry when the sensor and the actuators are laid out with sensors at the centers of the actuator squares, and filter or penalize the waffle mode. Use a modal fit when only low order aberrations matter and the noise is high. To estimate the aberration from images instead of slopes, use phase diversity.
Pitfalls
- The sensor never sees piston, so the absolute phase is unknown. Do not compare two reconstructions without removing the mean.
- In the Fried geometry the waffle mode is invisible. A closed loop that integrates the reconstructor output can let it grow; remove it as in line L9 or penalize it.
- Mixing up the geometries gives a wrong reconstructor. Fried slopes fed to a Hudgin matrix give an error of the same size as the signal.
- The slopes must be multiplied by the spacing (and by the factor from spot shift to slope) before they are phase differences.
- A grid with holes, such as a circular pupil with a central obstruction, must use only the measurements inside the pupil. The null space can grow if the pupil splits into parts that no measurement connects, and then each part has its own piston.
- Stopping CG with a loose tolerance leaves the low spatial frequencies, which converge last, partly fitted.
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/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
zonal_wavefront_reconstruction.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zonal-wavefront-reconstruction/. The authors are listed in prov/4DD2FS.jsonl.
"""Zonal wavefront reconstruction: least squares phase from slope data.
The phase is an N x N list of rows phi[i][j]: row i is the y index and
column j the x index, with grid spacing h. Slope data are stored as
"slope times h", that is as phase differences, in a pair (dx, dy):
- Hudgin: dx[i][j] = phi[i][j+1] - phi[i][j] (N rows, N - 1 columns) and
dy[i][j] = phi[i+1][j] - phi[i][j] (N - 1 rows, N columns).
- Fried: one subaperture per square of four phase points, both arrays
(N - 1) x (N - 1), each slope the mean of the two edge differences.
- Southwell: slopes sx, sy measured at the phase points (N x N); the mean
of two neighbor slopes times h is the difference between them, which
gives Hudgin data (southwell_to_hudgin).
reconstruct() solves the normal equations G^T G phi = G^T s by conjugate
gradients and returns the minimum norm least squares solution. Works with
float and with fractions.Fraction values (exact arithmetic).
"""
def _zeros(n1, n2, like=0):
return [[0 * like for _ in range(n2)] for _ in range(n1)]
def hudgin_forward(phi):
"""G phi for the Hudgin geometry: neighbor differences along x and y."""
n = len(phi)
dx = [[phi[i][j + 1] - phi[i][j] for j in range(n - 1)] for i in range(n)]
dy = [[phi[i + 1][j] - phi[i][j] for j in range(n)] for i in range(n - 1)]
return dx, dy
def hudgin_adjoint(s, n):
"""G^T s for the Hudgin geometry: minus the backward divergence of (dx, dy)."""
dx, dy = s
out = _zeros(n, n)
for i in range(n):
for j in range(n - 1):
out[i][j + 1] += dx[i][j]
out[i][j] -= dx[i][j]
for i in range(n - 1):
for j in range(n):
out[i + 1][j] += dy[i][j]
out[i][j] -= dy[i][j]
return out
def fried_forward(phi):
"""G phi for the Fried geometry: the mean x and y differences of each 2 x 2 square."""
n = len(phi)
dx = [[(phi[i][j + 1] + phi[i + 1][j + 1] - phi[i][j] - phi[i + 1][j]) / 2
for j in range(n - 1)] for i in range(n - 1)]
dy = [[(phi[i + 1][j] + phi[i + 1][j + 1] - phi[i][j] - phi[i][j + 1]) / 2
for j in range(n - 1)] for i in range(n - 1)]
return dx, dy
def fried_adjoint(s, n):
"""G^T s for the Fried geometry."""
dx, dy = s
out = _zeros(n, n)
for i in range(n - 1):
for j in range(n - 1):
a, b = dx[i][j] / 2, dy[i][j] / 2
out[i][j + 1] += a
out[i + 1][j + 1] += a
out[i][j] -= a
out[i + 1][j] -= a
out[i + 1][j] += b
out[i + 1][j + 1] += b
out[i][j] -= b
out[i][j + 1] -= b
return out
GEOMETRIES = {
"hudgin": (hudgin_forward, hudgin_adjoint),
"fried": (fried_forward, fried_adjoint),
}
def southwell_to_hudgin(sx, sy, h=1):
"""Southwell data: slopes at the phase points. Returns Hudgin difference data.
The model is phi[i][j+1] - phi[i][j] = h (sx[i][j] + sx[i][j+1]) / 2, and
the same along y, so the normal matrix is the one of Hudgin.
"""
n = len(sx)
dx = [[h * (sx[i][j] + sx[i][j + 1]) / 2 for j in range(n - 1)] for i in range(n)]
dy = [[h * (sy[i][j] + sy[i + 1][j]) / 2 for j in range(n)] for i in range(n - 1)]
return dx, dy
def null_space(geometry, n):
"""An orthogonal basis of the null space of G: piston, and for Fried also the waffle mode.
For odd n the checkerboard (-1)^(i+j) has the sum 1, so its mean is
removed to make it orthogonal to the piston.
"""
piston = [[1] * n for _ in range(n)]
if geometry == "fried":
waffle = [[1 if (i + j) % 2 == 0 else -1 for j in range(n)] for i in range(n)]
if n % 2 == 1:
c = 1 / (n * n)
waffle = [[v - c for v in row] for row in waffle]
return [piston, waffle]
return [piston]
def _dot(a, b):
return sum(p * q for ra, rb in zip(a, b) for p, q in zip(ra, rb))
def _sdot(s, t):
return _dot(s[0], t[0]) + _dot(s[1], t[1])
def _axpy(x, a, y):
return [[p + a * q for p, q in zip(rx, ry)] for rx, ry in zip(x, y)]
def project_out_null(phi, geometry):
"""Remove the components of phi along the null space modes (they are orthogonal)."""
n = len(phi)
for z in null_space(geometry, n):
c = _dot(z, phi) / _dot(z, z)
phi = _axpy(phi, -c, z)
return phi
def residual_norm2(phi, s, geometry):
"""||G phi - s||^2."""
fwd = GEOMETRIES[geometry][0]
g = fwd(phi)
return sum((p - q) ** 2 for a, b in zip(g, s) for ra, rb in zip(a, b) for p, q in zip(ra, rb))
def reconstruct(s, n, geometry="hudgin", iters=None, tol=0):
"""Minimum norm least squares phase from difference data s = (dx, dy).
Conjugate gradients on G^T G phi = G^T s from phi = 0. Stops after iters
steps (default n * n) or when ||r|| <= tol ||b||. With Fraction data and
tol = 0 it stops at the exact solution.
"""
fwd, adj = GEOMETRIES[geometry]
if iters is None:
iters = n * n
b = adj(s, n) # @line L1
phi = _zeros(n, n) # @line L2
r = b
p = r
rr = _dot(r, r)
stop = tol * tol * rr
for _ in range(iters): # @line L3
if rr == 0 or rr <= stop:
break
q = adj(fwd(p), n) # @line L4
a = rr / _dot(p, q) # @line L5
phi = _axpy(phi, a, p) # @line L6
r = _axpy(r, -a, q) # @line L7
rr_new = _dot(r, r) # @line L8
p = _axpy(r, rr_new / rr, p)
rr = rr_new
phi = project_out_null(phi, geometry) # @line L9
return phi # @line L10
def normal_matrix(geometry, n):
"""The dense n^2 x n^2 matrix G^T G, built column by column (for tests)."""
fwd, adj = GEOMETRIES[geometry]
cols = []
for k in range(n * n):
e = _zeros(n, n)
e[k // n][k % n] = 1
col = adj(fwd(e), n)
cols.append([v for row in col for v in row])
return [[cols[c][r] for c in range(n * n)] for r in range(n * n)]
test_zonal_wavefront_reconstruction.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zonal-wavefront-reconstruction/. The authors are listed in prov/4DD2FS.jsonl.
import math
import random
from fractions import Fraction as F
from imgla import adjoint_gap, solve, sym_eig
from zonal_wavefront_reconstruction import (
GEOMETRIES,
fried_forward,
hudgin_forward,
normal_matrix,
null_space,
project_out_null,
reconstruct,
residual_norm2,
southwell_to_hudgin,
)
def rand_grid(rng, n1, n2):
return [[rng.gauss(0, 1) for _ in range(n2)] for _ in range(n1)]
def max_diff(a, b):
return max(abs(p - q) for ra, rb in zip(a, b) for p, q in zip(ra, rb))
def flat_s(s):
return [v for part in s for row in part for v in row]
def test_adjoint_test_both_geometries():
rng = random.Random(7)
n = 6
for geo, shapes in (("hudgin", ((n, n - 1), (n - 1, n))), ("fried", ((n - 1, n - 1), (n - 1, n - 1)))):
fwd, adj = GEOMETRIES[geo]
x = rand_grid(rng, n, n)
y = tuple(rand_grid(rng, *sh) for sh in shapes)
def a(v):
return [flat_s(fwd(v))]
def ah(w):
vals = w[0]
k = shapes[0][0] * shapes[0][1]
dx = [vals[i * shapes[0][1]:(i + 1) * shapes[0][1]] for i in range(shapes[0][0])]
rest = vals[k:]
dy = [rest[i * shapes[1][1]:(i + 1) * shapes[1][1]] for i in range(shapes[1][0])]
return adj((dx, dy), n)
assert adjoint_gap(a, ah, x, [flat_s(y)]) < 1e-12
def test_two_by_two_loop_exact():
# One loop of four Hudgin edges with the slope 1 on the top edge only.
s = ([[F(1)], [F(0)]], [[F(0), F(0)]])
phi = reconstruct(s, 2, "hudgin", tol=0)
assert phi == [[F(-3, 8), F(3, 8)], [F(-1, 8), F(1, 8)]]
# The fitted differences are (3/4, 1/4) along x and (1/4, -1/4) along y.
dx, dy = hudgin_forward(phi)
assert dx == [[F(3, 4)], [F(1, 4)]] and dy == [[F(1, 4), F(-1, 4)]]
assert residual_norm2(phi, s, "hudgin") == F(1, 4)
def test_hudgin_exact_data_recovers_phase_up_to_piston():
rng = random.Random(3)
n = 8
true = rand_grid(rng, n, n)
got = reconstruct(hudgin_forward(true), n, "hudgin", tol=1e-13)
assert max_diff(got, project_out_null(true, "hudgin")) < 1e-9
def test_fried_exact_data_loses_piston_and_waffle():
rng = random.Random(4)
n = 7
true = rand_grid(rng, n, n)
waffle = null_space("fried", n)[1]
with_waffle = [[t + 0.8 * w + 2.0 for t, w in zip(rt, rw)] for rt, rw in zip(true, waffle)]
# The waffle and the piston give zero slopes.
assert max(abs(v) for v in flat_s(fried_forward(waffle))) == 0
got = reconstruct(fried_forward(with_waffle), n, "fried", tol=1e-13)
assert max_diff(got, project_out_null(true, "fried")) < 1e-9
def test_null_space_dimensions_by_eigenvalues():
for geo, dim in (("hudgin", 1), ("fried", 2)):
for n in (3, 4, 5):
w, _ = sym_eig(normal_matrix(geo, n))
assert sum(1 for v in w if abs(v) < 1e-9) == dim
def test_hudgin_normal_matrix_is_neumann_laplacian():
n = 4
m = normal_matrix("hudgin", n)
for i in range(n):
for j in range(n):
k = i * n + j
nbrs = [(i + di, j + dj) for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1))
if 0 <= i + di < n and 0 <= j + dj < n]
assert m[k][k] == len(nbrs)
for a, b in nbrs:
assert m[k][a * n + b] == -1
assert sum(m[k]) == 0
def test_noisy_slopes_match_brute_force_min_norm():
rng = random.Random(11)
n = 5
for geo in ("hudgin", "fried"):
fwd, adj = GEOMETRIES[geo]
true = rand_grid(rng, n, n)
dx, dy = fwd(true)
s = ([[v + rng.gauss(0, 0.1) for v in row] for row in dx],
[[v + rng.gauss(0, 0.1) for v in row] for row in dy])
got = reconstruct(s, n, geo, tol=1e-14)
# Brute force: (G^T G + sum z z^T / |z|^2) phi = G^T s has the min norm solution.
m = normal_matrix(geo, n)
for z in null_space(geo, n):
zf = [v for row in z for v in row]
zz = sum(v * v for v in zf)
m = [[m[r][c] + zf[r] * zf[c] / zz for c in range(n * n)] for r in range(n * n)]
b = [v for row in adj(s, n) for v in row]
ref = solve(m, b)
assert max(abs(g - r) for g, r in zip([v for row in got for v in row], ref)) < 1e-8
# The residual is orthogonal to the range: G^T (G phi - s) = 0.
g = fwd(got)
res = tuple([[p - q for p, q in zip(ra, rb)] for ra, rb in zip(a, b2)] for a, b2 in zip(g, s))
assert max(abs(v) for row in adj(res, n) for v in row) < 1e-8
def test_southwell_is_exact_for_quadratic_wavefronts():
n, h = 6, 0.25
xs = [-0.625 + h * j for j in range(n)]
# Defocus plus astigmatism plus tilt: phi = 2 (x^2 + y^2) + 0.5 x y + 0.3 x.
def phi(x, y):
return 2 * (x * x + y * y) + 0.5 * x * y + 0.3 * x
true = [[phi(xs[j], xs[i]) for j in range(n)] for i in range(n)]
sx = [[4 * xs[j] + 0.5 * xs[i] + 0.3 for j in range(n)] for i in range(n)]
sy = [[4 * xs[i] + 0.5 * xs[j] for j in range(n)] for i in range(n)]
got = reconstruct(southwell_to_hudgin(sx, sy, h), n, "hudgin", tol=1e-14)
assert max_diff(got, project_out_null(true, "hudgin")) < 1e-10
def test_cg_stops_early_with_tolerance_and_is_close():
rng = random.Random(5)
n = 8
true = rand_grid(rng, n, n)
s = hudgin_forward(true)
loose = reconstruct(s, n, "hudgin", tol=1e-3)
ref = project_out_null(true, "hudgin")
err = math.sqrt(sum((p - q) ** 2 for rp, rq in zip(loose, ref) for p, q in zip(rp, rq)))
nrm = math.sqrt(sum(q * q for rq in ref for q in rq))
assert err < 0.05 * nrm
History
D. L. Fried (1977) and R. H. Hudgin (1977) published least squares reconstructors from phase difference measurements in the same issue of the Journal of the Optical Society of America, for compensated imaging through the atmosphere. Fried used the geometry that now carries his name, and Hudgin used differences between neighbor points; both studied how the measurement noise propagates into the phase. W. H. Southwell (1980) compared zonal and modal estimation and introduced the geometry with slopes at the phase points. Later work added Fourier solvers, sparse and multigrid methods for very large adaptive optics systems, and minimum variance reconstructors.
References
- David L. Fried, Least-square fitting a wave-front distortion estimate to an array of phase-difference measurements, Journal of the Optical Society of America 67(3), 1977, pages 370 to 375
- Richard H. Hudgin, Wave-front reconstruction for compensated imaging, Journal of the Optical Society of America 67(3), 1977, pages 375 to 378
- W. H. Southwell, Wave-front estimation from wave-front slope measurements, Journal of the Optical Society of America 70(8), 1980, pages 998 to 1006 (zonal and modal estimates, the three sampling geometries and the noise propagation)
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 4DD2FS Edit this page History Report an error Markdown