Algorithm Search⌘K

Algorithmcore

Angular spectrum method

Also called angular spectrum propagation.

Propagate a sampled scalar field by a distance z: take its 2D DFT, multiply by exp(2 pi i z sqrt(1/lambda^2 - f^2)), drop evanescent waves and transform back. Exact for periodic band-limited fields.

Time
O(n^2 log n) worst
Space
O(n^2) extra
Where
n = the side of an n x n sample grid, a power of two, with an FFT
Properties
deterministicexactnot in placeoffline

The angular spectrum method computes a monochromatic scalar field at a distance zz from its samples in one plane. It writes the field as a sum of plane waves with the 2D discrete Fourier transform, moves each plane wave by its own phase factor, drops the evanescent waves, and sums the waves again. In the periodic model of the sample grid the result is exact, which this page proves; for a real aperture it is accurate when the grid is padded and the transfer function is sampled well. It is the propagation step of digital holography reconstruction, of the transport of intensity equation and of many methods for phase retrieval.

In plain words

Light that leaves a plane can be split into many flat waves, each one going in a slightly different direction. A flat wave is easy to move forward: it only shifts its phase, by an amount that depends on its direction and on the distance. So the method splits the field into flat waves with a Fourier transform, turns the phase of each wave by the right amount, and adds the waves back together.

Some of the waves in the split do not travel. They change too fast across the plane for the given color of light, and they die out within a few wavelengths. The method throws them away. Everything else is moved without any loss, so moving forward and then backward by the same distance gives the start field again.

The problem

The input is a complex field uu sampled on an n1×n2n_1 \times n_2 grid with spacing dd in a plane z=0z = 0, the wavelength λ\lambda and a distance zz (positive or negative). The output is the field at the same grid points in the plane zz. The field obeys the Helmholtz equation ∇2U+k2U=0\nabla^2 U + k^2 U = 0 with k=2π/λk = 2\pi/\lambda, which is the wave equation for one time frequency. The time dependence is e−iωte^{-i\omega t}, the convention of Goodman, so a wave that travels toward +z+z has the factor e+ikze^{+ikz}. With the opposite time convention the sign of the exponent in HH below changes.

With the continuous Fourier transform Fu(f)=∫u(r)e−2πif⋅r dr\mathcal{F} u(f) = \int u(r) e^{-2\pi i f \cdot r}\, dr of this area, the exact answer for a field with no sources at z>0z > 0 is

U(⋅,z)=F−1[FU(⋅,0) Hz],Hz(fx,fy)={e2πiz1/λ2−fx2−fy2fx2+fy2<1/λ2,e−2πzfx2+fy2−1/λ2otherwise,U(\cdot, z) = \mathcal{F}^{-1}\big[\mathcal{F} U(\cdot, 0)\, H_z\big], \qquad H_z(f_x, f_y) = \begin{cases} e^{2\pi i z \sqrt{1/\lambda^2 - f_x^2 - f_y^2}} & f_x^2 + f_y^2 < 1/\lambda^2, \\ e^{-2\pi z \sqrt{f_x^2 + f_y^2 - 1/\lambda^2}} & \text{otherwise,} \end{cases}

for z≥0z \ge 0. The method computes this on the grid and replaces the second line, the evanescent part, by 00.

The algorithm

DFT2 and IDFT2 are the 2D DFT and its inverse with the factor 1/(n1n2)1/(n_1 n_2). The index kk along an axis of nn samples stands for the signed index kˉ=k\bar k = k if 2k<n2k < n and kˉ=k−n\bar k = k - n otherwise. The optional band limits bxb_x and byb_y are +∞+\infty for the plain method.

  1. ANGULAR-SPECTRUM(u, d, λ, z) ▷ u is n1 x n2, spacing d
  2. 1U <- DFT2(u)
  3. 2for k <- 0 .. n1 - 1, l <- 0 .. n2 - 1 do
  4. 3fy <- k̄ / (n1 d), fx <- l̄ / (n2 d)
  5. 4w <- 1/λ^2 - fx^2 - fy^2
  6. 5if w > 0 and |fx| <= bx and |fy| <= by then V[k][l] <- U[k][l] · exp(2πi z sqrt(w))
  7. 6else V[k][l] <- 0 ▷ evanescent or outside the band limit
  8. 7return IDFT2(V)

Line L3 maps each DFT index to its spatial frequency in cycles per unit length. Line L5 applies the transfer function of free space to a wave that propagates. Line L6 drops the evanescent waves, for which w≤0w \le 0. For z<0z < 0 the same lines back-propagate the field.

Padding. The DFT treats the field as periodic with the periods n1dn_1 d and n2dn_2 d, so light that leaves one side of the window comes back in at the other side. To approximate a field in an infinite plane, put the field in the center of a grid twice as large in each direction, filled with zeros, run the algorithm, and keep the center.

The band limit. At a long distance the phase of HH changes fast between neighboring frequency samples, and the sampled HH aliases. Matsushima and Shimobaba (2009) cut the spectrum where the local frequency of the phase passes the Nyquist limit. With the frequency spacing Δu=1/(nd)\Delta u = 1/(n d) of the (padded) grid along an axis, the condition ∣∂fφ∣ Δu≤π|\partial_f \varphi|\, \Delta u \le \pi for the phase φ(f)=2πz1/λ2−f2\varphi(f) = 2\pi z\sqrt{1/\lambda^2 - f^2} gives

b=1λ(2Δu z)2+1,b = \frac{1}{\lambda\sqrt{(2\Delta u\, z)^2 + 1}},

and the proof derives it.

Example

Take one row of n=8n = 8 samples, a field that does not change along yy, with spacing d=1 μmd = 1\ \mu\text{m}, the wavelength λ=0.5 μm\lambda = 0.5\ \mu\text{m}, the distance z=10 μmz = 10\ \mu\text{m}, and the slit u=[0,0,0,1,1,0,0,0]u = [0, 0, 0, 1, 1, 0, 0, 0]. The frequencies are f=kˉ/8f = \bar k / 8 per μ\mum, and all of them are below 1/λ=21/\lambda = 2 per μ\mum, so every wave propagates. The table gives fz=1/λ2−f2f_z = \sqrt{1/\lambda^2 - f^2} and the phase of HH modulo 2π2\pi.

index kk ff (1/μ\mum) fzf_z (1/μ\mum) arg⁡H mod 2π\arg H \bmod 2\pi u^k\hat u_k
0 0 2.00000 0 2
1 0.125 1.99609 6.0375 −1.7071−0.7071i-1.7071 - 0.7071i
2 0.25 1.98431 5.2976 1+i1 + i
3 0.375 1.96453 4.0545 −0.2929−0.7071i-0.2929 - 0.7071i
4 −0.5-0.5 1.93649 2.2928 0
5 −0.375-0.375 1.96453 4.0545 −0.2929+0.7071i-0.2929 + 0.7071i
6 −0.25-0.25 1.98431 5.2976 1−i1 - i
7 −0.125-0.125 1.99609 6.0375 −1.7071+0.7071i-1.7071 + 0.7071i

The output intensities ∣vj∣2|v_j|^2 are [0.0025,0.0405,0.2465,0.7105,0.7105,0.2465,0.0405,0.0025][0.0025, 0.0405, 0.2465, 0.7105, 0.7105, 0.2465, 0.0405, 0.0025]. Their sum is 22, the energy of the input, because ∣H∣=1|H| = 1 on every wave. The slit has spread to its neighbors. The Fresnel (paraxial) transfer function e2πiz/λe−iπλzf2e^{2\pi i z/\lambda} e^{-i\pi\lambda z f^2} differs from HH in phase by 0.000240.00024 rad at f=0.125f = 0.125 and by 0.0630.063 rad at f=0.5f = 0.5. The error grows as f4f^4, because the next term of 1−λ2f2\sqrt{1 - \lambda^2 f^2} after 1−λ2f2/21 - \lambda^2 f^2/2 is −λ4f4/8-\lambda^4 f^4/8.

Correctness

The proof works in the model that the DFT assumes. A grid field is a sum of the waves cf(z)e2πi(fxx+fyy)c_f(z) e^{2\pi i (f_x x + f_y y)} over the frequencies of the grid that solves the Helmholtz equation for z>0z > 0, has bounded coefficients and has no wave that travels toward −z-z. Put into the Helmholtz equation, each coefficient obeys cf′′+4π2(1/λ2−∣f∣2)cf=0c_f'' + 4\pi^2 (1/\lambda^2 - |f|^2) c_f = 0. So a propagating coefficient is cf(0)e2πizwfc_f(0) e^{2\pi i z\sqrt{w_f}} and an evanescent one decays as e−2πz−wfe^{-2\pi z\sqrt{-w_f}}. The DFT of the samples gives the coefficients exactly, because each grid frequency has its own DFT index. Hence the output is the exact propagating part of the field at zz, and the dropped evanescent part is at most e−2πzγe^{-2\pi z\gamma} times its size at z=0z = 0, with γ\gamma the smallest decay rate on the grid.

This is a theorem about the periodic model. For a field in an infinite plane, the method has two errors that the theorem does not cover: the wrap-around of the periodic DFT, which the padding reduces, and the sampling of HH at large zz, which the band limit controls.

Proof: The angular spectrum method is exact for periodic band-limited fieldsfull

The setting is that of the algorithm. The grid has n1×n2n_1 \times n_2 samples with spacing dd, so the periods are L1=n1dL_1 = n_1 d along yy and L2=n2dL_2 = n_2 d along xx. The DFT index kk along an axis of nn samples stands for the signed index kˉ\bar k, with kˉ=k\bar k = k if 2k<n2k < n and kˉ=k−n\bar k = k - n otherwise, and for the frequency kˉ/(nd)\bar k / (n d). Let Λ\Lambda be the set of frequency pairs f=(fx,fy)=(lˉ/L2,kˉ/L1)f = (f_x, f_y) = (\bar l / L_2, \bar k / L_1) for 0≤k<n10 \le k < n_1 and 0≤l<n20 \le l < n_2. The wavelength is λ>0\lambda > 0, and the time dependence is e−iωte^{-i\omega t}, so a wave e2πi(f⋅r+fzz)e^{2\pi i (f \cdot r + f_z z)} with fz>0f_z > 0 travels toward +z+z.

The model. A field U(x,y,z)U(x, y, z) on z≥0z \ge 0 is a grid field if it has the form

U(x,y,z)=∑f∈Λcf(z) e2πi(fxx+fyy)(1)U(x, y, z) = \sum_{f \in \Lambda} c_f(z)\, e^{2\pi i (f_x x + f_y y)} \tag{1}

with twice differentiable cfc_f, if it solves the Helmholtz equation ∇2U+(2π/λ)2U=0\nabla^2 U + (2\pi/\lambda)^2 U = 0 for z>0z > 0, if each cfc_f is bounded on z≥0z \ge 0, and if no wave of (1) travels toward −z-z. The last condition says that no source lies at z>0z > 0.

Lemma 1 (the coefficients). For a grid field, put wf=1/λ2−∣f∣2w_f = 1/\lambda^2 - |f|^2. If wf>0w_f > 0, then cf(z)=cf(0) e2πizwfc_f(z) = c_f(0)\, e^{2\pi i z \sqrt{w_f}}. If wf<0w_f < 0, then cf(z)=cf(0) e−2πz−wfc_f(z) = c_f(0)\, e^{-2\pi z \sqrt{-w_f}}. If wf=0w_f = 0, then cf(z)=cf(0)c_f(z) = c_f(0).

Proof. The functions e2πif⋅re^{2\pi i f \cdot r} for f∈Λf \in \Lambda are orthogonal on one period. Put (1) into the Helmholtz equation and take the inner product with e2πif⋅re^{2\pi i f \cdot r}. Each Laplacian in xx and yy gives the factor −4π2∣f∣2-4\pi^2 |f|^2, so

cf′′(z)+4π2wf cf(z)=0.c_f''(z) + 4\pi^2 w_f\, c_f(z) = 0.

For wf>0w_f > 0 the solutions are Ae2πizwf+Be−2πizwfA e^{2\pi i z\sqrt{w_f}} + B e^{-2\pi i z\sqrt{w_f}}. The second term is a wave that travels toward −z-z, so B=0B = 0 and A=cf(0)A = c_f(0). For wf<0w_f < 0 the solutions are Ae−2πz−wf+Be2πz−wfA e^{-2\pi z\sqrt{-w_f}} + B e^{2\pi z\sqrt{-w_f}}, and the bound on cfc_f forces B=0B = 0. For wf=0w_f = 0 the solutions are A+BzA + B z, and the bound forces B=0B = 0. □\square

Lemma 2 (sampling). Let uij=U(jd,id,0)u_{ij} = U(j d, i d, 0) for a grid field UU. Then the 2D DFT of uu is u^kl=n1n2 cf(0)\hat u_{kl} = n_1 n_2\, c_f(0), where ff is the frequency pair of the index (k,l)(k, l).

Proof. At the samples, e2πi(fxjd+fyid)=e2πi(lˉj/n2+kˉi/n1)=e2πi(lj/n2+ki/n1)e^{2\pi i (f_x j d + f_y i d)} = e^{2\pi i (\bar l j / n_2 + \bar k i / n_1)} = e^{2\pi i (l j / n_2 + k i / n_1)}, because lˉ−l\bar l - l is a multiple of n2n_2 and kˉ−k\bar k - k is a multiple of n1n_1. So uu is the inverse DFT of the array n1n2 cf(0)n_1 n_2\, c_f(0), and the map from Λ\Lambda to the index pairs is a bijection. The DFT inverts the inverse DFT. □\square

Theorem. Let UU be a grid field, let uu hold its samples at z=0z = 0, and let vv be the output of ANGULAR-SPECTRUM(u,d,λ,z)(u, d, \lambda, z) for z≥0z \ge 0 without the band limit. Write U=Up+UeU = U_p + U_e, where UpU_p holds the terms of (1) with wf>0w_f > 0 and UeU_e the rest. Then

vij=Up(jd,id,z)for all i,j,v_{ij} = U_p(j d, i d, z) \quad \text{for all } i, j,

and the dropped part is small: ∥Ue(⋅,z)∥grid≤e−2πzγ∥Ue(⋅,0)∥grid\|U_e(\cdot, z)\|_{\mathrm{grid}} \le e^{-2\pi z \gamma} \|U_e(\cdot, 0)\|_{\mathrm{grid}}, where ∥⋅∥grid\|\cdot\|_{\mathrm{grid}} is the Euclidean norm of the samples and γ=min⁡{−wf:f∈Λ,wf<0}\gamma = \min\{\sqrt{-w_f} : f \in \Lambda, w_f < 0\}, provided that no f∈Λf \in \Lambda has wf=0w_f = 0.

Proof. By Lemma 2, line L1 gives u^kl=n1n2cf(0)\hat u_{kl} = n_1 n_2 c_f(0). Line L4 computes wfw_f. Lines L5 and L6 form Vkl=n1n2cf(0)e2πizwfV_{kl} = n_1 n_2 c_f(0) e^{2\pi i z\sqrt{w_f}} if wf>0w_f > 0 and Vkl=0V_{kl} = 0 otherwise. By Lemma 1, Vkl=n1n2cf(z)V_{kl} = n_1 n_2 c_f(z) for wf>0w_f > 0. Line L7 takes the inverse DFT, and by the computation in the proof of Lemma 2 it returns the samples of ∑wf>0cf(z)e2πif⋅r\sum_{w_f > 0} c_f(z) e^{2\pi i f \cdot r}, which is UpU_p at zz.

For the bound, the samples of Ue(⋅,z)U_e(\cdot, z) have the DFT n1n2cf(z)n_1 n_2 c_f(z) for wf<0w_f < 0 and 00 elsewhere (no wf=0w_f = 0 by hypothesis). By Lemma 1, ∣cf(z)∣=∣cf(0)∣e−2πz−wf≤∣cf(0)∣e−2πzγ|c_f(z)| = |c_f(0)| e^{-2\pi z\sqrt{-w_f}} \le |c_f(0)| e^{-2\pi z \gamma}. By the Parseval theorem for the DFT, the grid norm squared is (n1n2)−1(n_1 n_2)^{-1} times the sum of the squared DFT magnitudes, so the bound on each term gives the bound on the norm. □\square

Corollary (properties of the propagator). Let PzP_z be the map u↦vu \mapsto v of the algorithm without the band limit, and let BB be the projector that keeps the DFT entries with wf>0w_f > 0 and sets the rest to zero, so that B=P0B = P_0. Then for all real zz, z1z_1 and z2z_2:

  1. Pz1Pz2=Pz1+z2P_{z_1} P_{z_2} = P_{z_1 + z_2}.
  2. P−zPz=BP_{-z} P_z = B, and P−zPz=IP_{-z} P_z = I if every f∈Λf \in \Lambda has wf>0w_f > 0.
  3. ∥Pzu∥=∥Bu∥≤∥u∥\|P_z u\| = \|B u\| \le \|u\|, with equality if uu has no DFT entry with wf≤0w_f \le 0.
  4. Pz∗=P−zP_z^* = P_{-z}, so back propagation is the adjoint of propagation.

Proof. In the DFT basis, PzP_z is the diagonal map with entries hf(z)=e2πizwfh_f(z) = e^{2\pi i z\sqrt{w_f}} for wf>0w_f > 0 and 00 otherwise. Item 1 follows from hf(z1)hf(z2)=hf(z1+z2)h_f(z_1) h_f(z_2) = h_f(z_1 + z_2) for wf>0w_f > 0 and 0⋅0=00 \cdot 0 = 0 otherwise. Item 2 is item 1 with z1=−zz_1 = -z and z2=zz_2 = z, since hf(0)=1h_f(0) = 1 for wf>0w_f > 0. Item 3 follows from ∣hf(z)∣=1|h_f(z)| = 1 for wf>0w_f > 0 and the Parseval theorem. For item 4, the unnormalized DFT is n1n2\sqrt{n_1 n_2} times a unitary map QQ, so Pz=Q∗DzQP_z = Q^* D_z Q with the diagonal DzD_z, and Pz∗=Q∗Dz‾QP_z^* = Q^* \overline{D_z} Q. Since hf(z)‾=hf(−z)\overline{h_f(z)} = h_f(-z), this is P−zP_{-z}. □\square

Lemma 3 (the band limit). Let Δu=1/(nd)\Delta u = 1/(n d) be the frequency spacing along one axis, and consider the phase φ(f)=2πz1/λ2−f2\varphi(f) = 2\pi z\sqrt{1/\lambda^2 - f^2} along that axis for z>0z > 0 and 0≤f<1/λ0 \le f < 1/\lambda. The sampled transfer function meets the Nyquist condition ∣φ′(f)∣ Δu≤π|\varphi'(f)|\, \Delta u \le \pi exactly for

f≤flim⁡=1λ(2Δu z)2+1.f \le f_{\lim} = \frac{1}{\lambda \sqrt{(2 \Delta u\, z)^2 + 1}}.

Proof. ∣φ′(f)∣=2πzf/1/λ2−f2|\varphi'(f)| = 2\pi z f / \sqrt{1/\lambda^2 - f^2}, which increases with ff. The condition 2πzfΔu≤π1/λ2−f22\pi z f \Delta u \le \pi \sqrt{1/\lambda^2 - f^2} is, after squaring both nonnegative sides, 4z2Δu2f2≤1/λ2−f24 z^2 \Delta u^2 f^2 \le 1/\lambda^2 - f^2, that is f2(4z2Δu2+1)≤1/λ2f^2 (4 z^2 \Delta u^2 + 1) \le 1/\lambda^2. Take the square root. □\square

Lemma 3 is a statement about the sampling of HH, which matters for the aperiodic problem with a padded grid. In the periodic model of the theorem the method is exact without any band limit.

Complexity

In the real RAM model, line L1 and line L7 each cost one 2D DFT. With the fast Fourier transform and n1=n2=nn_1 = n_2 = n a power of two, that is O(n2log⁡n)O(n^2 \log n); with direct sums it is O(n4)O(n^4), or O(n3)O(n^3) with row and column transforms done directly. Lines L2 to L6 cost O(n2)O(n^2), with one square root and one complex exponential per entry. The memory holds two arrays of n2n^2 complex numbers. Padding by a factor two in each direction multiplies the grid by four. The method is not iterative.

Properties

These follow from the diagonal form of the method in the DFT basis (proved in the proof).

  • Unitary on the propagating band. ∣H∣=1|H| = 1 where w>0w > 0, so the method keeps the energy of every field whose DFT has no evanescent entries. In general it returns the energy of the propagating band, which is at most the input energy.
  • Group property. Propagation by z1z_1 and then by z2z_2 equals propagation by z1+z2z_1 + z_2.
  • Reversible on the band. Propagation by zz and then by −z-z keeps the propagating band and deletes the rest. On a grid with d≥λ/2d \ge \lambda/\sqrt{2} every grid frequency propagates, and the round trip is the identity.
  • Adjoint. The adjoint of propagation by zz is propagation by −z-z. Iterative methods use this as the exact adjoint of the forward model.
  • No restriction on the distance in the model. The method needs no paraxial approximation and works at zz close to 00, where the Fresnel transform fails.

Variants and improvements

  • Band-limited angular spectrum (Matsushima and Shimobaba 2009). Zero the spectrum outside the band limit bb above. This removes the aliasing of the sampled transfer function at long distances, at the cost of a lower resolution there.
  • Fresnel transfer function. Replace HH by eikze−iπλz(fx2+fy2)e^{ikz} e^{-i\pi\lambda z (f_x^2 + f_y^2)}. It is the paraxial approximation and is accurate when λ∣f∣\lambda |f| is small for all waves with energy.
  • Fresnel transform with one FFT. For long distances, the Fresnel integral can be written as one Fourier transform with a quadratic phase factor before and after it. The output grid spacing is then λz/(nd)\lambda z/(n d), not dd. This form is common in digital holography.
  • Shifted and scaled angular spectrum. Variants change the output window or its sampling, for example to propagate to a tilted or offset plane. They are outside this page.
  • Nonuniform output. With a nonuniform FFT, the plane waves can be summed on a grid that differs from the input grid.

When to use it

Use the angular spectrum method to propagate a coherent field over short and middle distances, where the field stays mostly inside the window: refocusing in digital holography, defocus series for the transport of intensity equation, the near field step of ptychography, and the simulation of diffraction. It keeps the grid spacing, which makes it the natural choice when the input and output planes must line up pixel by pixel. For the far field, a single Fourier transform (the Fraunhofer approximation) is cheaper and keeps the sampling right. For long distances in the near field, use the band limit or the Fresnel transform.

Pitfalls

  • Wrap-around. Without padding, light that leaves the window at one side enters at the other. The result is the field of a periodic array of copies of the object.
  • Aliasing of the transfer function. At large zz the phase of HH varies by more than π\pi between frequency samples. The sampled HH then describes the wrong field, often with ghost copies. The band limit, or a Fresnel transform, avoids this.
  • The sign convention. With the time dependence e+iωte^{+i\omega t}, used in some engineering books, the forward transfer function is e−2πiz⋅e^{-2\pi i z\sqrt{\cdot}}. Mixing conventions propagates the field the wrong way.
  • The frequency grid. For even nn, the index n/2n/2 stands for the frequency −n/(2nd)-n/(2 n d), not +n/(2nd)+n/(2nd). An off-by-one in the mapping of line L3 gives a wrong HH that still has modulus 1, so energy checks do not catch it.
  • Evanescent waves in back propagation. Do not multiply by e+2πz−we^{+2\pi z\sqrt{-w}} to undo the decay. That amplifies noise without limit, which is an ill-posed step; line L6 sets these waves to zero in both directions.
  • Scalar model. The method propagates one scalar component. It ignores the coupling of polarization components, which matters at high numerical aperture.

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.

angular_spectrum_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/angular-spectrum-method/. The authors are listed in prov/BPG5QE.jsonl.

"""Angular spectrum propagation of a sampled scalar field.

Conventions:
- The field u is an n1 x n2 image, u[i][j] at y = i d and x = j d, with the
  sample spacing d. The grid is periodic with the periods n1 d and n2 d.
- Time dependence exp(-i omega t), so the plane wave exp(2 pi i (fx x + fy y
  + fz z)) with fz > 0 travels toward +z.
- The DFT is unnormalized forward with exp(-2 pi i j k / n), and the inverse
  has 1 / n (imgkit). DFT index k stands for the frequency k / (n d) for
  k < n / 2 and (k - n) / (n d) otherwise.
- Transfer function H(fx, fy) = exp(2 pi i z sqrt(1 / lambda^2 - fx^2 - fy^2))
  where the root is real and positive, and 0 elsewhere (evanescent waves are
  dropped).

Cost: two 2D DFTs and O(n1 n2) other work, so O(n^2 log n) for an n x n
grid with n a power of two.
"""

import cmath
import math

from imgkit import dft2, idft2


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


def frequencies(n, d):
    """The spatial frequencies (cycles per unit length) of the n DFT indices."""
    return [signed_index(k, n) / (n * d) for k in range(n)]


def band_limit(n, d, wavelength, z):
    """The band limit of Matsushima and Shimobaba for an axis of n samples.

    With the frequency spacing du = 1 / (n d), the sampled transfer function
    has a phase step of at most pi between neighbors for |f| below
    1 / (wavelength sqrt((2 du z)^2 + 1)).
    """
    du = 1.0 / (n * d)
    return 1.0 / (wavelength * math.sqrt((2.0 * du * z) ** 2 + 1.0))


def transfer_function(n1, n2, d, wavelength, z, limit=False):
    """H on the DFT grid, in DFT order, with evanescent entries set to 0."""
    fys, fxs = frequencies(n1, d), frequencies(n2, d)
    inv2 = 1.0 / (wavelength * wavelength)
    ly = band_limit(n1, d, wavelength, abs(z)) if limit else math.inf
    lx = band_limit(n2, d, wavelength, abs(z)) if limit else math.inf
    h = [[0j] * n2 for _ in range(n1)]
    for k, fy in enumerate(fys):
        for l, fx in enumerate(fxs):
            w = inv2 - fx * fx - fy * fy
            if w > 0.0 and abs(fx) <= lx and abs(fy) <= ly:
                h[k][l] = cmath.exp(2j * math.pi * z * math.sqrt(w))
    return h


def angular_spectrum(u, d, wavelength, z, limit=False):
    """The field at distance z from the sampled field u (periodic model)."""
    n1, n2 = len(u), len(u[0])
    spec = dft2(u)  # @line L1
    fys, fxs = frequencies(n1, d), frequencies(n2, d)
    inv2 = 1.0 / (wavelength * wavelength)
    ly = band_limit(n1, d, wavelength, abs(z)) if limit else math.inf
    lx = band_limit(n2, d, wavelength, abs(z)) if limit else math.inf
    out = [[0j] * n2 for _ in range(n1)]
    for k in range(n1):  # @line L2
        for l in range(n2):
            fy, fx = fys[k], fxs[l]  # @line L3
            w = inv2 - fx * fx - fy * fy  # @line L4
            if w > 0.0 and abs(fx) <= lx and abs(fy) <= ly:  # @line L5
                out[k][l] = spec[k][l] * cmath.exp(2j * math.pi * z * math.sqrt(w))
            else:
                out[k][l] = 0j  # @line L6
    return idft2(out)  # @line L7


def angular_spectrum_padded(u, d, wavelength, z, limit=False):
    """Propagate u embedded in a grid twice as large (zeros around it), then crop.

    The padding keeps light that leaves the window from wrapping around to
    the other side, so the result approximates the aperiodic field.
    """
    n1, n2 = len(u), len(u[0])
    big = [[0j] * (2 * n2) for _ in range(2 * n1)]
    for i in range(n1):
        for j in range(n2):
            big[i + n1 // 2][j + n2 // 2] = u[i][j]
    res = angular_spectrum(big, d, wavelength, z, limit)
    return [row[n2 // 2:n2 // 2 + n2] for row in res[n1 // 2:n1 // 2 + n1]]


def fresnel_transfer(n1, n2, d, wavelength, z):
    """The paraxial (Fresnel) transfer function exp(2 pi i z / lambda) exp(-i pi lambda z f^2)."""
    fys, fxs = frequencies(n1, d), frequencies(n2, d)
    c = cmath.exp(2j * math.pi * z / wavelength)
    return [[c * cmath.exp(-1j * math.pi * wavelength * z * (fx * fx + fy * fy)) for fx in fxs] for fy in fys]
imgkit.py 322 lines
# 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
test_angular_spectrum_method.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/angular-spectrum-method/. The authors are listed in prov/BPG5QE.jsonl.

import cmath
import math
import random

from angular_spectrum_method import (
    angular_spectrum,
    angular_spectrum_padded,
    band_limit,
    frequencies,
    fresnel_transfer,
    transfer_function,
)
from imgkit import dft2, img_dot, img_norm


def rand_field(rng, n1, n2):
    return [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n2)] for _ in range(n1)]


def max_diff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def direct_propagation(u, d, wavelength, z):
    """Reference: the sum of plane waves with explicit O(n^4) Fourier sums, no FFT."""
    n1, n2 = len(u), len(u[0])
    fys, fxs = frequencies(n1, d), frequencies(n2, d)
    coef = {}
    for k in range(n1):
        for l in range(n2):
            c = sum(u[i][j] * cmath.exp(-2j * math.pi * (i * k / n1 + j * l / n2)) for i in range(n1) for j in range(n2))
            w = 1.0 / wavelength ** 2 - fxs[l] ** 2 - fys[k] ** 2
            coef[k, l] = c * cmath.exp(2j * math.pi * z * math.sqrt(w)) if w > 0 else 0j
    out = []
    for i in range(n1):
        row = []
        for j in range(n2):
            row.append(sum(v * cmath.exp(2j * math.pi * (i * k / n1 + j * l / n2)) for (k, l), v in coef.items()) / (n1 * n2))
        out.append(row)
    return out


def test_plane_wave_gets_the_phase_of_h():
    n, d, lam, z = 8, 1.0, 0.5, 3.7
    for kx, ky in ((0, 0), (1, 0), (2, -3), (-4, 3)):
        fx, fy = kx / (n * d), ky / (n * d)
        u = [[cmath.exp(2j * math.pi * (fx * j * d + fy * i * d)) for j in range(n)] for i in range(n)]
        out = angular_spectrum(u, d, lam, z)
        g = cmath.exp(2j * math.pi * z * math.sqrt(1 / lam ** 2 - fx * fx - fy * fy))
        assert max_diff(out, [[g * v for v in row] for row in u]) < 1e-12


def test_matches_direct_plane_wave_sum():
    rng = random.Random(3)
    u = rand_field(rng, 6, 8)
    for d, lam in ((1.0, 0.5), (0.3, 0.5)):  # all waves propagate; some are evanescent
        a = angular_spectrum(u, d, lam, 2.5)
        b = direct_propagation(u, d, lam, 2.5)
        assert max_diff(a, b) < 1e-10


def test_worked_example():
    out = angular_spectrum([[0, 0, 0, 1, 1, 0, 0, 0]], 1.0, 0.5, 10.0)
    inten = [abs(v) ** 2 for v in out[0]]
    want = [0.0025, 0.0405, 0.2465, 0.7105, 0.7105, 0.2465, 0.0405, 0.0025]
    assert all(abs(a - b) < 5e-5 for a, b in zip(inten, want))
    assert abs(sum(inten) - 2.0) < 1e-12


def test_parseval_on_propagating_band():
    rng = random.Random(5)
    u = rand_field(rng, 8, 8)
    # d = 1 and lambda = 0.5: every grid frequency propagates, so the energy is kept.
    out = angular_spectrum(u, 1.0, 0.5, 7.0)
    assert abs(img_norm(out) - img_norm(u)) < 1e-10 * img_norm(u)


def test_evanescent_energy_is_removed():
    rng = random.Random(6)
    u = rand_field(rng, 8, 8)
    d, lam = 0.2, 0.5  # max |f| = 2.5 * sqrt(2) > 1 / lambda = 2
    spec = dft2(u)
    fs = frequencies(8, d)
    band = sum(abs(spec[k][l]) ** 2 for k in range(8) for l in range(8) if fs[k] ** 2 + fs[l] ** 2 < 1 / lam ** 2) / 64
    out = angular_spectrum(u, d, lam, 1.3)
    assert abs(img_norm(out) ** 2 - band) < 1e-9 * band
    assert img_norm(out) < img_norm(u)


def test_forward_then_back_is_projection_on_band():
    rng = random.Random(7)
    u = rand_field(rng, 8, 8)
    d, lam, z = 0.2, 0.5, 4.0
    back = angular_spectrum(angular_spectrum(u, d, lam, z), d, lam, -z)
    proj = angular_spectrum(u, d, lam, 0.0)  # z = 0 keeps exactly the propagating band
    assert max_diff(back, proj) < 1e-11
    # On a grid where every wave propagates, z then -z is the identity.
    back2 = angular_spectrum(angular_spectrum(u, 1.0, lam, z), 1.0, lam, -z)
    assert max_diff(back2, u) < 1e-11


def test_composition_of_distances():
    rng = random.Random(8)
    u = rand_field(rng, 8, 8)
    a = angular_spectrum(angular_spectrum(u, 0.4, 0.5, 1.5), 0.4, 0.5, 2.25)
    b = angular_spectrum(u, 0.4, 0.5, 3.75)
    assert max_diff(a, b) < 1e-11


def test_adjoint_is_back_propagation():
    rng = random.Random(9)
    x, y = rand_field(rng, 8, 8), rand_field(rng, 8, 8)
    d, lam, z = 0.25, 0.5, 2.0
    ax = angular_spectrum(x, d, lam, z)
    ahy = angular_spectrum(y, d, lam, -z)
    gap = abs(img_dot(ax, y) - img_dot(x, ahy))
    assert gap <= 1e-10 * img_norm(ax) * img_norm(y)


def test_band_limit_keeps_phase_steps_below_pi():
    n, d, lam = 16, 1.0, 0.5
    for z in (50.0, 400.0, 3000.0):
        lim = band_limit(n, d, lam, z)
        du = 1.0 / (n * d)
        f = 0.0
        while f + du <= lim:
            p0 = 2 * math.pi * z * math.sqrt(1 / lam ** 2 - f * f)
            p1 = 2 * math.pi * z * math.sqrt(1 / lam ** 2 - (f + du) ** 2)
            assert abs(p1 - p0) <= math.pi + 1e-9
            f += du
        # The local frequency of the phase, |d phase / df| / (2 pi), equals
        # 1 / (2 du) at the limit and is larger past it.
        def slope(f):
            return 2 * math.pi * z * f / math.sqrt(1 / lam ** 2 - f * f)
        assert abs(slope(lim) * du - math.pi) < 1e-9
        assert slope(lim * 1.02) * du > math.pi


def test_band_limited_h_is_zero_outside_limit():
    h = transfer_function(16, 16, 1.0, 0.5, 400.0, limit=True)
    lim = band_limit(16, 1.0, 0.5, 400.0)
    fs = frequencies(16, 1.0)
    for k in range(16):
        for l in range(16):
            inside = abs(fs[k]) <= lim and abs(fs[l]) <= lim
            assert (abs(h[k][l]) > 0.5) == inside


def test_fresnel_agrees_for_small_angles():
    n, d, lam, z = 8, 4.0, 0.5, 20.0  # max |f| lambda = 0.088, paraxial
    h = transfer_function(n, n, d, lam, z)
    hf = fresnel_transfer(n, n, d, lam, z)
    fs = frequencies(n, d)
    for k in range(n):
        for l in range(n):
            f2 = fs[k] ** 2 + fs[l] ** 2
            bound = 2 * math.pi * z * lam ** 3 * f2 * f2 / 8 * 1.05 + 1e-12
            assert abs(h[k][l] - hf[k][l]) <= bound


def test_padded_matches_unpadded_inside_when_no_wrap():
    # A narrow field at a short distance: little light reaches the window edge.
    u = [[0j] * 8 for _ in range(8)]
    u[3][3] = u[3][4] = u[4][3] = u[4][4] = 1 + 0j
    a = angular_spectrum_padded(u, 1.0, 0.5, 0.0)
    assert max_diff(a, u) < 1e-12

History

The representation of a monochromatic field by plane waves, and its propagation by the transfer function of free space, is classical in scalar diffraction theory; Goodman gives it in the chapter on the foundations of scalar diffraction theory. Schnars and Juptner (1994) recorded a hologram on a CCD and reconstructed it by numerical propagation, which made numerical propagation the core of digital holography. Matsushima and Shimobaba (2009) analyzed the sampling of the transfer function and introduced the band limit that extends the method to longer distances.

References

  1. Joseph W. Goodman, Introduction to Fourier Optics, third edition, Roberts and Company, 2005, Chapter 3, the section on the angular spectrum of plane waves (propagation of the angular spectrum, evanescent waves, the transfer function of free space); Chapter 4 for the Fresnel approximation
  2. Kyoji Matsushima and Tomoyoshi Shimobaba, Band-limited angular spectrum method for numerical simulation of free-space propagation in far and near fields, Optics Express 17(22), 2009, 19662 to 19673, the sampling problem of the transfer function at long distances and the band limit (general locator)
  3. Ulf Schnars and Werner Juptner, Direct recording of holograms by a CCD target and numerical reconstruction, Applied Optics 33(2), 1994, 179 to 181, numerical propagation of a recorded field as the reconstruction step of digital holography (general locator)

Where this leads

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.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
  • History with a source
  • a scene preset for the example