Algorithm Search⌘K

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.

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
Properties
deterministicexact for consistent slopesiterativelinearminimum norm
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 s=Gφ+es = G\varphi + e with a sparse difference matrix GG, and the method solves the least squares problem min⁡φ∥Gφ−s∥2\min_\varphi \lVert G\varphi - s\rVert^2. 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 φ\varphi lives on an n×nn \times n grid of points with spacing hh; φi,j\varphi_{i,j} has row ii (the yy index) and column jj (the xx index). The data are slopes times hh, so they have the units of phase. Three geometries are in use:

  • Hudgin. Each measurement is the difference of two neighbor points: di,jx=φi,j+1−φi,jd^x_{i,j} = \varphi_{i,j+1} - \varphi_{i,j} and di,jy=φi+1,j−φi,jd^y_{i,j} = \varphi_{i+1,j} - \varphi_{i,j}. There are 2n(n−1)2n(n-1) 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 xx slope is the mean of the two xx differences of the square: di,jx=12(φi,j+1+φi+1,j+1−φi,j−φi+1,j)d^x_{i,j} = \tfrac12(\varphi_{i,j+1} + \varphi_{i+1,j+1} - \varphi_{i,j} - \varphi_{i+1,j}), and the same for yy. There are 2(n−1)22(n-1)^2 measurements.
  • Southwell. The slopes sx,sys^x, s^y are measured at the phase points. The model is that the mean of two neighbor slopes times hh is the phase difference: φi,j+1−φi,j=h2(si,jx+si,j+1x)\varphi_{i,j+1} - \varphi_{i,j} = \tfrac h2 (s^x_{i,j} + s^x_{i,j+1}). This is the Hudgin matrix with averaged data.

In each case s=Gφ+es = G\varphi + e with a known sparse matrix GG and noise ee, white with variance σ2\sigma^2 per measurement in the usual analysis. The output is the minimum norm least squares solution φ†=G†s\varphi^\dagger = G^\dagger s (see pseudoinverse).

The algorithm

The normal equations GTGφ=GTsG^T G \varphi = G^T s have a symmetric positive semidefinite matrix, and the right side is in its range. Conjugate gradients from φ=0\varphi = 0 solve them without forming the matrix; each step applies GG and GTG^T once.

  1. ZONAL-LS(s, G, K, tol) ▷ s = slopes times h; G = Hudgin or Fried differences
  2. 1b ← G^T s ▷ minus a discrete divergence of the slopes
  3. 2phi ← 0; r ← b; p ← r
  4. 3repeat at most K times, while ||r|| > tol · ||b||
  5. 4q ← G^T (G p) ▷ a discrete Laplacian applied to p
  6. 5a ← <r, r> / <p, q>
  7. 6phi ← phi + a · p
  8. 7r' ← r - a · q
  9. 8p ← r' + (<r', r'> / <r, r>) · p; r ← r'
  10. 9phi ← phi minus its projection on the null space of G ▷ piston; for Fried also waffle
  11. 10return phi

For Southwell data, first form the Hudgin data di,jx=h2(si,jx+si,j+1x)d^x_{i,j} = \tfrac h2(s^x_{i,j} + s^x_{i,j+1}) and di,jy=h2(si,jy+si+1,jy)d^y_{i,j} = \tfrac h2(s^y_{i,j} + s^y_{i+1,j}), 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, GG is the forward difference and GTG^T is minus the backward difference divergence, so GTGG^T G 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 −1-1 for each neighbor.

Example

One loop. Take the 2×22 \times 2 Hudgin grid with four measurements around one square: d0,0x=1d^x_{0,0} = 1 (top edge) and 00 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 11. Least squares spreads this misfit equally over the four edges: the fitted differences are 3/43/4 on the top edge, 1/41/4 on the bottom edge and 1/41/4 and −1/4-1/4 on the left and right edges, and each fitted value differs from its datum by 1/41/4, so the residual norm squared is 4⋅(1/4)2=1/44 \cdot (1/4)^2 = 1/4. The minimum norm solution is

φ=(−3/83/8−1/81/8),\varphi = \begin{pmatrix} -3/8 & 3/8 \\ -1/8 & 1/8 \end{pmatrix},

with mean zero. The test runs the code in exact rational arithmetic and gets this matrix; CG stops after two steps, because GTGG^T G has two distinct nonzero eigenvalues here (2 and 4).

The waffle. On a 3×33 \times 3 Fried grid, add the checkerboard wi,j=(−1)i+jw_{i,j} = (-1)^{i+j} to any phase. In each square the two xx differences are wi,j+1−wi,j=−2wi,jw_{i,j+1} - w_{i,j} = -2w_{i,j} and wi+1,j+1−wi+1,j=2wi,jw_{i+1,j+1} - w_{i+1,j} = 2w_{i,j}, so their mean is zero, and the same for yy. The sensor does not see ww. 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 8×88 \times 8 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 3×10−143 \times 10^{-14} after 32 steps.

Noise. With white noise of variance σ2\sigma^2 on each Hudgin difference, the mean square error of the reconstructed phase per point is (σ2/n2)∑1/λ(\sigma^2/n^2)\sum 1/\lambda, summed over the nonzero eigenvalues λp,q=4sin⁡2(πp/2n)+4sin⁡2(πq/2n)\lambda_{p,q} = 4\sin^2(\pi p/2n) + 4\sin^2(\pi q/2n) of the Neumann Laplacian. Computed from this formula:

nn 4 8 16 32 64 128
error variance per point /σ2/\sigma^2 0.493 0.632 0.755 0.872 0.985 1.097
condition number of GTGG^T G on the range 11.7 50.5 206.2 828.7 3318.8 13279.0

The noise grows only like ln⁡n\ln n, by about 0.110.11 each time nn 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 n2n^2, so plain iterations need many steps on a large grid.

Correctness

The full proof is in proofs/correctness.md. The main facts:

  1. Normal equations. φ\varphi minimizes ∥Gφ−s∥2\lVert G\varphi - s\rVert^2 if and only if GTGφ=GTsG^TG\varphi = G^Ts. For Hudgin, GTGG^TG is the Neumann 5-point Laplacian, so the problem is a discrete Poisson equation.
  2. Null space. For Hudgin (and Southwell), the null space of GG is the constants (piston), because the grid graph is connected. For Fried with n≥2n \ge 2, it is spanned by the piston and the waffle (−1)i+j(-1)^{i+j}, and nothing else.
  3. CG gives the minimum norm solution. The right side GTsG^Ts is orthogonal to the null space, and every CG iterate from 00 stays in the range of GTGG^TG. So CG converges to the unique least squares solution in that range, which is G†sG^\dagger s, in at most as many steps as GTGG^TG has distinct nonzero eigenvalues (exact arithmetic).
  4. Exact data. If s=Gφ∗s = G\varphi^\ast, the output is φ∗\varphi^\ast minus its projection on the null space: the true phase up to piston (and waffle for Fried).
  5. Southwell is exact for quadratics. If φ\varphi is a polynomial of degree at most 2 in xx and yy and the slopes are exact, then h2(si,jx+si,j+1x)\tfrac h2(s^x_{i,j} + s^x_{i,j+1}) 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 φ\varphi is a real vector indexed by the points (i,j)(i, j) of an n×nn \times n grid, n≥2n \ge 2. The data ss are real, and GG 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 GTGφ=GTsG^TG\varphi = G^Ts from φ0=0\varphi_0 = 0, then the removal of the null space component.

Claim 1 (normal equations). φ\varphi minimizes f(φ)=∥Gφ−s∥2f(\varphi) = \lVert G\varphi - s\rVert^2 if and only if GTGφ=GTsG^TG\varphi = G^Ts.

Proof. ff is a convex quadratic with gradient 2GT(Gφ−s)2G^T(G\varphi - s). A convex differentiable function has its minimum exactly where the gradient is zero. □\square

Claim 2 (Hudgin normal matrix). For the Hudgin geometry, (GTGφ)i,j=∑(k,l)∼(i,j)(φi,j−φk,l)(G^TG\varphi)_{i,j} = \sum_{(k,l) \sim (i,j)} (\varphi_{i,j} - \varphi_{k,l}), the sum over the grid neighbors of (i,j)(i,j). So GTGG^TG is the graph Laplacian of the grid, which is the 5-point Laplacian with Neumann boundary.

Proof. φTGTGφ=∥Gφ∥2=∑edges {p,q}(φp−φq)2\varphi^TG^TG\varphi = \lVert G\varphi\rVert^2 = \sum_{\text{edges } \{p,q\}} (\varphi_p - \varphi_q)^2, since each row of GG is one edge difference. The quadratic form ∑edges(φp−φq)2\sum_{\text{edges}}(\varphi_p - \varphi_q)^2 is the form of the graph Laplacian D−WD - W, with DD the diagonal of degrees and WW the adjacency matrix. Two symmetric matrices with the same quadratic form are equal. □\square

Claim 3 (Hudgin null space). For Hudgin, Gφ=0G\varphi = 0 if and only if φ\varphi is constant.

Proof. If Gφ=0G\varphi = 0, then φp=φq\varphi_p = \varphi_q for every edge. The grid graph is connected, so φ\varphi takes one value on all points. Conversely a constant gives zero differences. □\square

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 n≥2n \ge 2, Gφ=0G\varphi = 0 if and only if φ=a 1+b w\varphi = a\,\mathbf 1 + b\,w with wi,j=(−1)i+jw_{i,j} = (-1)^{i+j}.

Proof. Take one square with the corners φi,j=A\varphi_{i,j} = A, φi,j+1=B\varphi_{i,j+1} = B, φi+1,j=C\varphi_{i+1,j} = C and φi+1,j+1=D\varphi_{i+1,j+1} = D. Its two measurements are zero when B+D−A−C=0B + D - A - C = 0 and C+D−A−B=0C + D - A - B = 0. The sum gives 2D−2A=02D - 2A = 0 and the difference gives 2B−2C=02B - 2C = 0. So in every square the two diagonal corners are equal: φi,j=φi+1,j+1\varphi_{i,j} = \varphi_{i+1,j+1} and φi,j+1=φi+1,j\varphi_{i,j+1} = \varphi_{i+1,j}. These are steps (±1,±1)(\pm1, \pm1) on the grid, and they keep the parity of i+ji + j. 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; n≥2n \ge 2). So φ\varphi is constant, say pp, on the points with i+ji + j even, and constant, say qq, on the points with i+ji + j odd. This is a1+bwa\mathbf 1 + bw with a=(p+q)/2a = (p + q)/2 and b=(p−q)/2b = (p - q)/2. Conversely, the computation on the page shows that ww gives zero for every square, and so does 1\mathbf 1. □\square

The vectors 1\mathbf 1 and ww are orthogonal for even nn. For odd nn the sum of ww is 11, so the code uses w−1/n2w - \mathbf 1/n^2, which spans the same plane with 1\mathbf 1 and is orthogonal to it.

Claim 5 (CG returns the minimum norm solution). Let M=GTGM = G^TG and b=GTsb = G^Ts. In exact arithmetic CG from 00 stops after at most tt steps, where tt is the number of distinct nonzero eigenvalues of MM, with φt=G†s\varphi_t = G^\dagger s.

Proof. The null space of MM equals the null space of GG, since Mφ=0M\varphi = 0 gives ∥Gφ∥2=φTMφ=0\lVert G\varphi\rVert^2 = \varphi^T M\varphi = 0. The vector b=GTsb = G^Ts is in the range of GTG^T, which is the orthogonal complement of the null space of GG. Let VV be this range; MM maps VV into VV and is positive definite on VV. Every CG quantity (rr, pp, qq, φ\varphi) is a linear combination of b,Mb,M2b,…b, Mb, M^2b, \dots, so all of them stay in VV. On VV, CG is the standard method for a symmetric positive definite matrix, and the standard theory applies: φk\varphi_k minimizes the MM-norm of the error over the Krylov space span{b,…,Mk−1b}\mathrm{span}\{b, \dots, M^{k-1}b\}, and the Krylov space stops growing after at most tt steps, when it contains the solution. So CG reaches the unique solution φ∗∈V\varphi^\ast \in V of Mφ=bM\varphi = b, and the residual becomes 00. By Claim 1, φ∗\varphi^\ast is a least squares solution. Every least squares solution is φ∗+z\varphi^\ast + z with zz in the null space, and ∥φ∗+z∥2=∥φ∗∥2+∥z∥2\lVert\varphi^\ast + z\rVert^2 = \lVert\varphi^\ast\rVert^2 + \lVert z\rVert^2 because φ∗⊥z\varphi^\ast \perp z. So φ∗\varphi^\ast is the one of minimum norm, which is G†sG^\dagger s. Line L9 subtracts the projection on the null space, which is zero in exact arithmetic. □\square

Claim 6 (exact data). If s=Gφ∗s = G\varphi^\ast, the output is φ∗−Pφ∗\varphi^\ast - P\varphi^\ast, with PP the orthogonal projection on the null space of GG.

Proof. φ∗−Pφ∗\varphi^\ast - P\varphi^\ast is in VV and has G(φ∗−Pφ∗)=sG(\varphi^\ast - P\varphi^\ast) = s, so it is a least squares solution with zero residual, in VV. By Claim 5 it is the output. □\square

Claim 7 (Southwell is exact for quadratic phases). Let φ(x,y)\varphi(x, y) be a polynomial of degree at most 2, sampled at the grid points with spacing hh, and let sx=∂φ/∂xs^x = \partial\varphi/\partial x and sy=∂φ/∂ys^y = \partial\varphi/\partial y 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, φ(x+h,y)−φ(x,y)=∫xx+h∂xφ(t,y) dt\varphi(x + h, y) - \varphi(x, y) = \int_x^{x+h} \partial_x\varphi(t, y)\, dt. The integrand is linear in tt, and the trapezoid rule h2(∂xφ(x,y)+∂xφ(x+h,y))\tfrac h2(\partial_x\varphi(x, y) + \partial_x\varphi(x + h, y)) is exact for linear functions. The same holds along columns. So the data are Gφ∗G\varphi^\ast for the Hudgin GG, and Claim 6 gives the result. □\square

Claim 8 (noise). If s=Gφ∗+es = G\varphi^\ast + e with ee white of variance σ2\sigma^2, the error G†eG^\dagger e of the Hudgin output (on the part outside the null space) has the total variance σ2trace⁡((GTG)†)=σ2∑λ≠01/λ\sigma^2 \operatorname{trace}((G^TG)^\dagger) = \sigma^2 \sum_{\lambda \ne 0} 1/\lambda, the sum over the nonzero eigenvalues of the Neumann Laplacian, λp,q=4sin⁡2(πp/(2n))+4sin⁡2(πq/(2n))\lambda_{p,q} = 4\sin^2(\pi p/(2n)) + 4\sin^2(\pi q/(2n)) for 0≤p,q<n0 \le p, q < n.

Proof. The covariance of G†eG^\dagger e is σ2G†(G†)T=σ2(GTG)†\sigma^2 G^\dagger (G^\dagger)^T = \sigma^2 (G^TG)^\dagger, a standard identity of the pseudoinverse. Its trace is the sum of the inverse nonzero eigenvalues. The 1D Neumann path Laplacian has the eigenvectors cos⁡(πp(j+1/2)/n)\cos(\pi p(j + 1/2)/n) with eigenvalues 4sin⁡2(πp/(2n))4\sin^2(\pi p/(2n)), and the grid Laplacian is the Kronecker sum of two of them, so its eigenvalues are the sums. □\square

The tests check Claims 2, 3 and 4 (by the eigenvalues of the dense normal matrix), Claim 5 (against a dense solve of (M+∑zzzT/∥z∥2)φ=b(M + \sum_z zz^T/\lVert z\rVert^2)\varphi = b, whose unique solution is G†sG^\dagger s, and on the exact rational example of the page), Claim 6 for both geometries, Claim 7, and the adjoint pair GG, GTG^T.

Complexity

In the real-RAM model, one application of GG or GTG^T costs Θ(n2)\Theta(n^2), so one CG step costs Θ(n2)\Theta(n^2) and KK steps cost Θ(Kn2)\Theta(Kn^2), with Θ(n2)\Theta(n^2) extra space. The condition number of GTGG^TG on its range grows like n2n^2 (table above), so CG needs K=O(nlog⁡(1/ε))K = O(n \log(1/\varepsilon)) steps for a relative error ε\varepsilon, which gives O(n3log⁡(1/ε))O(n^3 \log(1/\varepsilon)) in total. Other solvers of the same system:

  • Dense Gaussian elimination on the n2×n2n^2 \times n^2 matrix: Θ(n6)\Theta(n^6). An adaptive optics system with a fixed geometry precomputes the reconstructor matrix G†G^\dagger once and then applies it to each slope frame by a matrix-vector product, Θ(n4)\Theta(n^4) per frame.
  • For Hudgin and Southwell the matrix is the Neumann Laplacian, which the 2D DCT diagonalizes (fast DCT), so a direct solve costs Θ(n2log⁡n)\Theta(n^2 \log n). 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 Θ(n2)\Theta(n^2).
  • Gauss-Seidel and Jacobi sweeps, used in early hardware reconstructors, need O(n2)O(n^2) sweeps.

Properties

  • Linear in the data: the output is G†sG^\dagger s.
  • 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 Gφ−sG\varphi - s 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 ln⁡n\ln n.

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 hh (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.

imgla.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""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

  1. 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
  2. Richard H. Hudgin, Wave-front reconstruction for compensated imaging, Journal of the Optical Society of America 67(3), 1977, pages 375 to 378
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example