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
- Model
- Real RAM
- Properties
- deterministicexactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
The angular spectrum method computes a monochromatic scalar field at a distance 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 sampled on an grid with spacing in a plane , the wavelength and a distance (positive or negative). The output is the field at the same grid points in the plane . The field obeys the Helmholtz equation with , which is the wave equation for one time frequency. The time dependence is , the convention of Goodman, so a wave that travels toward has the factor . With the opposite time convention the sign of the exponent in below changes.
With the continuous Fourier transform of this area, the exact answer for a field with no sources at is
for . The method computes this on the grid and replaces the second line, the evanescent part, by .
The algorithm
DFT2 and IDFT2 are the 2D DFT and its inverse with the factor . The index along an axis of samples stands for the signed index if and otherwise. The optional band limits and are for the plain method.
ANGULAR-SPECTRUM(u, d, λ, z) ▷ u is n1 x n2, spacing d- 1
U <- DFT2(u) - 2
for k <- 0 .. n1 - 1, l <- 0 .. n2 - 1 do - 3
fy <- k̄ / (n1 d), fx <- l̄ / (n2 d) - 4
w <- 1/λ^2 - fx^2 - fy^2 - 5
if w > 0 and |fx| <= bx and |fy| <= by then V[k][l] <- U[k][l] · exp(2πi z sqrt(w)) - 6
else V[k][l] <- 0 ▷ evanescent or outside the band limit - 7
return 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 . For the same lines back-propagate the field.
Padding. The DFT treats the field as periodic with the periods and , 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 changes fast between neighboring frequency samples, and the sampled aliases. Matsushima and Shimobaba (2009) cut the spectrum where the local frequency of the phase passes the Nyquist limit. With the frequency spacing of the (padded) grid along an axis, the condition for the phase gives
and the proof derives it.
Example
Take one row of samples, a field that does not change along , with spacing , the wavelength , the distance , and the slit . The frequencies are per m, and all of them are below per m, so every wave propagates. The table gives and the phase of modulo .
| index | (1/m) | (1/m) | ||
|---|---|---|---|---|
| 0 | 0 | 2.00000 | 0 | 2 |
| 1 | 0.125 | 1.99609 | 6.0375 | |
| 2 | 0.25 | 1.98431 | 5.2976 | |
| 3 | 0.375 | 1.96453 | 4.0545 | |
| 4 | 1.93649 | 2.2928 | 0 | |
| 5 | 1.96453 | 4.0545 | ||
| 6 | 1.98431 | 5.2976 | ||
| 7 | 1.99609 | 6.0375 |
The output intensities are . Their sum is , the energy of the input, because on every wave. The slit has spread to its neighbors. The Fresnel (paraxial) transfer function differs from in phase by rad at and by rad at . The error grows as , because the next term of after is .
Correctness
The proof works in the model that the DFT assumes. A grid field is a sum of the waves over the frequencies of the grid that solves the Helmholtz equation for , has bounded coefficients and has no wave that travels toward . Put into the Helmholtz equation, each coefficient obeys . So a propagating coefficient is and an evanescent one decays as . 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 , and the dropped evanescent part is at most times its size at , with 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 at large , 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 samples with spacing , so the periods are along and along . The DFT index along an axis of samples stands for the signed index , with if and otherwise, and for the frequency . Let be the set of frequency pairs for and . The wavelength is , and the time dependence is , so a wave with travels toward .
The model. A field on is a grid field if it has the form
with twice differentiable , if it solves the Helmholtz equation for , if each is bounded on , and if no wave of (1) travels toward . The last condition says that no source lies at .
Lemma 1 (the coefficients). For a grid field, put . If , then . If , then . If , then .
Proof. The functions for are orthogonal on one period. Put (1) into the Helmholtz equation and take the inner product with . Each Laplacian in and gives the factor , so
For the solutions are . The second term is a wave that travels toward , so and . For the solutions are , and the bound on forces . For the solutions are , and the bound forces .
Lemma 2 (sampling). Let for a grid field . Then the 2D DFT of is , where is the frequency pair of the index .
Proof. At the samples, , because is a multiple of and is a multiple of . So is the inverse DFT of the array , and the map from to the index pairs is a bijection. The DFT inverts the inverse DFT.
Theorem. Let be a grid field, let hold its samples at , and let be the output of ANGULAR-SPECTRUM for without the band limit. Write , where holds the terms of (1) with and the rest. Then
and the dropped part is small: , where is the Euclidean norm of the samples and , provided that no has .
Proof. By Lemma 2, line L1 gives . Line L4 computes . Lines L5 and L6 form if and otherwise. By Lemma 1, for . Line L7 takes the inverse DFT, and by the computation in the proof of Lemma 2 it returns the samples of , which is at .
For the bound, the samples of have the DFT for and elsewhere (no by hypothesis). By Lemma 1, . By the Parseval theorem for the DFT, the grid norm squared is times the sum of the squared DFT magnitudes, so the bound on each term gives the bound on the norm.
Corollary (properties of the propagator). Let be the map of the algorithm without the band limit, and let be the projector that keeps the DFT entries with and sets the rest to zero, so that . Then for all real , and :
- .
- , and if every has .
- , with equality if has no DFT entry with .
- , so back propagation is the adjoint of propagation.
Proof. In the DFT basis, is the diagonal map with entries for and otherwise. Item 1 follows from for and otherwise. Item 2 is item 1 with and , since for . Item 3 follows from for and the Parseval theorem. For item 4, the unnormalized DFT is times a unitary map , so with the diagonal , and . Since , this is .
Lemma 3 (the band limit). Let be the frequency spacing along one axis, and consider the phase along that axis for and . The sampled transfer function meets the Nyquist condition exactly for
Proof. , which increases with . The condition is, after squaring both nonnegative sides, , that is . Take the square root.
Lemma 3 is a statement about the sampling of , 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 a power of two, that is ; with direct sums it is , or with row and column transforms done directly. Lines L2 to L6 cost , with one square root and one complex exponential per entry. The memory holds two arrays of 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. where , 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 and then by equals propagation by .
- Reversible on the band. Propagation by and then by keeps the propagating band and deletes the rest. On a grid with every grid frequency propagates, and the round trip is the identity.
- Adjoint. The adjoint of propagation by is propagation by . 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 close to , where the Fresnel transform fails.
Variants and improvements
- Band-limited angular spectrum (Matsushima and Shimobaba 2009). Zero the spectrum outside the band limit 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 by . It is the paraxial approximation and is accurate when 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 , not . 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 the phase of varies by more than between frequency samples. The sampled 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 , used in some engineering books, the forward transfer function is . Mixing conventions propagates the field the wrong way.
- The frequency grid. For even , the index stands for the frequency , not . An off-by-one in the mapping of line L3 gives a wrong that still has modulus 1, so energy checks do not catch it.
- Evanescent waves in back propagation. Do not multiply by 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.
# 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
- 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
- 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)
- 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.
| 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 BPG5QE Edit this page History Report an error Markdown