Algorithm Search⌘K

Algorithmcore

Gerchberg-Saxton algorithm

Also called GS algorithm.

Find a phase that fits known magnitudes in two planes linked by a Fourier transform, by putting each magnitude on in turn and keeping the phase. The error never grows.

Time
O(K n log n) worst
Space
O(n) extra
Where
K = the number of iterations; n = the number of samples in each plane
Properties
deterministicnot exactnot in placeoffline
Origin
Ralph W. Gerchberg, W. Owen Saxton, 1972

The Gerchberg-Saxton algorithm is one of the first iterative methods for phase retrieval. The magnitude of a complex field is known in two planes, an image plane and a diffraction plane, that a Fourier transform links. The phase is not known in either plane. The algorithm starts with any phase. It goes back and forth between the planes, and in each plane it puts on the known magnitude and keeps the current phase. Each step is a nearest point projection, so the error never grows (Fienup 1982). It can still stop before it finds a solution.

In plain words

You know how bright a light field is at two places: right at an object, and far away, where the light has spread out. You do not know how the waves line up at either place. The far field is the Fourier transform of the near field.

Guess the alignment at the object. Use the known brightness there, compute the far field, and look at it. Its brightness is wrong. Replace the brightness with the measured one and keep the alignment. Go back to the object, and do the same there. Repeat.

Each round fixes one place and spoils the other a little. The disagreement never grows. Often it falls to zero and the alignment is found. Sometimes it gets stuck.

The problem

The input is two arrays of magnitudes of length nn: aj=∣fj∣a_j = |f_j| in the object plane and Au=∣Fu∣A_u = |F_u| in the Fourier plane, where FF is the DFT of an unknown complex signal ff. The DFT is unnormalized forward with 1/n1/n on the inverse. The output is a signal gg with ∣gj∣=aj|g_j| = a_j and ∣Gu∣=Au|G_u| = A_u for all jj and uu. The same steps work in 2D, with the 2D DFT. At best, gg equals ff up to a constant phase factor eiϕe^{i\phi}, which no magnitude can see.

The algorithm

  1. GERCHBERG-SAXTON(a, A, φ, K)
  2. 1g_j ← a_j · e^{iφ_j} for each j
  3. 2for k ← 1 to K do
  4. 3G ← DFT(g)
  5. 4G′_u ← A_u · G_u / |G_u| for each u ▷ A_u when G_u = 0
  6. 5g′ ← IDFT(G′)
  7. 6g_j ← a_j · g′_j / |g′_j| for each j ▷ a_j when g′_j = 0
  8. 7return g

Lines L3 to L5 replace the Fourier magnitude and keep the phase. Line L6 does the same in the object plane. The error is measured with the unitary DFT, so that it is a distance between signals:

EF(g)2=1n∑u(∣Gu∣−Au)2,E0(g′)2=∑j(∣gj′∣−aj)2.E_F(g)^2 = \frac{1}{n}\sum_u \bigl(|G_u| - A_u\bigr)^2, \qquad E_0(g')^2 = \sum_j \bigl(|g'_j| - a_j\bigr)^2 .

Example

Take f=(1,i,−1,2,0,0,0,0)f = (1, i, -1, 2, 0, 0, 0, 0), a signal of length 8 whose last four samples are zero. So a=(1,1,1,2,0,0,0,0)a = (1, 1, 1, 2, 0, 0, 0, 0). Its DFT magnitudes are

A=(5, 2−1, 13, 3+2, 5, 1+2, 5, 3−2)≈(2.236,0.414,3.606,4.414,2.236,2.414,2.236,1.586).A = \bigl(\sqrt5,\ \sqrt2 - 1,\ \sqrt{13},\ 3 + \sqrt2,\ \sqrt5,\ 1 + \sqrt2,\ \sqrt5,\ 3 - \sqrt2\bigr) \approx (2.236, 0.414, 3.606, 4.414, 2.236, 2.414, 2.236, 1.586).

For example F0=1+i−1+2=2+iF_0 = 1 + i - 1 + 2 = 2 + i, so A0=5A_0 = \sqrt5. The start phases ϕ\phi are random. These are measurements of the implementation with seed 1:

iteration kk 0 1 2 5 10 20 50 100
EF(gk)E_F(g_k) 1.16 0.816 0.642 0.368 0.0611 4.6e-4 2.9e-10 8e-17

The result is g=cfg = c f with c≈0.143−0.990ic \approx 0.143 - 0.990i, so ∣c∣=1|c| = 1: the signal is found up to a global phase, which is the best possible. Seeds 2 to 5 also reach errors near 10−1610^{-16} within 200 iterations. The zeros in aa help: they act like a support constraint, as in the error reduction algorithm. With no zeros in aa, the same code from random starts often stops at an error near 10−210^{-2}.

Correctness

Line L4 gives the nearest point to GG among the spectra with magnitude AA, one frequency at a time: for ∣w∣=a|w| = a, ∣z−w∣≥∣∣z∣−a∣|z - w| \ge \bigl||z| - a\bigr|, with equality at w=az/∣z∣w = a z / |z|. By Parseval's identity for the unitary DFT, lines L3 to L5 are the nearest signal with Fourier magnitude AA. Line L6 is the nearest signal with object magnitude aa. With gk′g'_k the signal of line L5,

EF(gk+1)≤∥gk+1−gk′∥=E0(gk′)≤∥gk′−gk∥=EF(gk).E_F(g_{k+1}) \le \|g_{k+1} - g'_k\| = E_0(g'_k) \le \|g'_k - g_k\| = E_F(g_k).

So the error does not increase, and a run that reaches error zero has found a signal that fits both magnitudes. This is a theorem. Neither set is convex, so there is no theorem that the error reaches zero. The full proof is below.

Proof: The Gerchberg-Saxton error never increasesfull

The setting is that of the algorithm. Signals have length nn and live in Cn\mathbb{C}^n with ⟨u,v⟩=∑juj‾ vj\langle u, v\rangle = \sum_j \overline{u_j}\, v_j and ∥u∥2=⟨u,u⟩\|u\|^2 = \langle u, u\rangle. The DFT is unnormalized forward, with 1/n1/n on the inverse. The data are object magnitudes aj≥0a_j \ge 0 and Fourier magnitudes Au≥0A_u \ge 0. Let O={g:∣gj∣=aj for all j}O = \{g : |g_j| = a_j \text{ for all } j\} and M={g:∣Gu∣=Au for all u}M = \{g : |G_u| = A_u \text{ for all } u\}, where GG is the DFT of gg. Arithmetic is exact.

Let PMgP_M g be the signal of lines L3 to L5 and POg′P_O g' the signal of line L6. Define EF(g)=∥g−PMg∥E_F(g) = \|g - P_M g\| and E0(g′)=∥g′−POg′∥E_0(g') = \|g' - P_O g'\|.

Lemma 1 (one entry). Let z∈Cz \in \mathbb{C} and a≥0a \ge 0. Let w∗=az/∣z∣w^\ast = a z / |z| if z≠0z \ne 0 and w∗=aw^\ast = a if z=0z = 0. Then ∣z−w∗∣=∣∣z∣−a∣≤∣z−w∣|z - w^\ast| = \bigl||z| - a\bigr| \le |z - w| for every ww with ∣w∣=a|w| = a.

Proof. The triangle inequality gives ∣z−w∣≥∣∣z∣−∣w∣∣=∣∣z∣−a∣|z - w| \ge \bigl||z| - |w|\bigr| = \bigl||z| - a\bigr|. If z≠0z \ne 0, w∗w^\ast lies on the ray from 00 through zz at distance aa, so ∣z−w∗∣=∣∣z∣−a∣|z - w^\ast| = \bigl||z| - a\bigr|. If z=0z = 0, ∣z−w∗∣=a=∣∣z∣−a∣|z - w^\ast| = a = \bigl||z| - a\bigr|. □\square

Lemma 2 (the two steps are nearest points). POg′∈OP_O g' \in O and ∥g′−POg′∥≤∥g′−h∥\|g' - P_O g'\| \le \|g' - h\| for all h∈Oh \in O. PMg∈MP_M g \in M and ∥g−PMg∥≤∥g−h∥\|g - P_M g\| \le \|g - h\| for all h∈Mh \in M, and EF(g)2=1n∑u(∣Gu∣−Au)2E_F(g)^2 = \frac{1}{n}\sum_u (|G_u| - A_u)^2.

Proof. The first claim is Lemma 1 applied to each entry, because ∥g′−h∥2=∑j∣gj′−hj∣2\|g' - h\|^2 = \sum_j |g'_j - h_j|^2. For the second, the unitary DFT n−1/2Fn^{-1/2} F preserves norms, so ∥g−h∥2=1n∑u∣Gu−Hu∣2\|g - h\|^2 = \frac{1}{n}\sum_u |G_u - H_u|^2 (Parseval). Line L4 applies the map of Lemma 1 to each GuG_u with a=Aua = A_u, so it minimizes each term, and line L5 returns to the signal domain. The minimum value is 1n∑u(∣Gu∣−Au)2\frac{1}{n}\sum_u (|G_u| - A_u)^2. □\square

Theorem. Let g0g_0 be the signal of line L1, gkg_k the signal after kk passes of the loop of line L2, and gk′=PMgkg'_k = P_M g_k. Then for every k≥0k \ge 0,

EF(gk+1)≤E0(gk′)≤EF(gk),E_F(g_{k+1}) \le E_0(g'_k) \le E_F(g_k),

so EF(g0)≥EF(g1)≥EF(g2)≥⋯E_F(g_0) \ge E_F(g_1) \ge E_F(g_2) \ge \cdots.

Proof. Line L1 gives ∣g0∣=a|g_0| = a, so g0∈Og_0 \in O, and line L6 with Lemma 2 gives gk+1=POgk′∈Og_{k+1} = P_O g'_k \in O. Lemma 2 gives gk′∈Mg'_k \in M.

Since gk′∈Mg'_k \in M, Lemma 2 for gk+1g_{k+1} gives EF(gk+1)=∥gk+1−PMgk+1∥≤∥gk+1−gk′∥=E0(gk′)E_F(g_{k+1}) = \|g_{k+1} - P_M g_{k+1}\| \le \|g_{k+1} - g'_k\| = E_0(g'_k).

Since gk∈Og_k \in O, Lemma 2 for gk′g'_k gives E0(gk′)=∥gk′−POgk′∥≤∥gk′−gk∥=EF(gk)E_0(g'_k) = \|g'_k - P_O g'_k\| \le \|g'_k - g_k\| = E_F(g_k). □\square

Corollary (fixed points). If f∈O∩Mf \in O \cap M, the start g0=fg_0 = f gives gk=fg_k = f for all kk. If the run reaches EF(gk)=0E_F(g_k) = 0, then gk∈O∩Mg_k \in O \cap M, so gkg_k is consistent with both magnitudes.

Proof. For f∈O∩Mf \in O \cap M, Lemma 1 maps each entry and each Fourier coefficient to itself, so PMf=fP_M f = f and POf=fP_O f = f. If EF(gk)=0E_F(g_k) = 0 then gk=PMgk∈Mg_k = P_M g_k \in M, and gk∈Og_k \in O by the theorem. □\square

What is not claimed. OO and MM are not convex. The error is monotone, so it converges, but the limit can be positive: the iteration can stagnate at a point that is in neither set. Even at error zero, the result is fixed only up to the ambiguities that the two magnitudes leave, at least a global phase factor.

Complexity

Each iteration does one DFT and one inverse DFT and O(n)O(n) other work. With a fast Fourier transform the cost is O(nlog⁡n)O(n \log n) per iteration and O(Knlog⁡n)O(K n \log n) in total, and O(n2)O(n^2) per iteration with the direct sum. The extra space is O(n)O(n). On an image of n=n1n2n = n_1 n_2 pixels, the 2D FFT also costs O(nlog⁡n)O(n \log n).

Properties

  • Monotone. The error EFE_F does not increase (a theorem).
  • Fixed points. Every signal that fits both magnitudes is a fixed point. Stagnation points are fixed points too.
  • Global phase. If gg is a solution, so is eiϕge^{i\phi} g. The output depends on the start through this factor.
  • Local. The result depends on the start.

Variants and improvements

  • Error reduction. Fienup replaced the object magnitude by a support and nonnegativity, for the case of one intensity measurement.
  • Hybrid input-output. A feedback step that escapes most stagnation points.
  • Griffin-Lim algorithm. The same alternation for the magnitudes of a short-time Fourier transform, used for audio.
  • Weighted and phase-only holograms. To design a phase plate or a phase-only light modulator that makes a wanted far field, one runs GS with a uniform object magnitude. Weighted versions change the target magnitude between iterations to make the far field more uniform. This is a heuristic with no error guarantee.
  • Other propagators. Replace the DFT with a Fresnel propagator for two planes at a finite distance, or use more than two planes. This is close to phase diversity.
  • Transport of intensity. For two planes that are very close, the transport-of-intensity equation gives the phase directly: it is a Poisson equation for the phase, and a fast Poisson solver replaces the iteration.

When to use it

Use GS when you have a reliable magnitude in two planes and a Fourier (or Fresnel) model links them, for example to find the phase of a wavefront from an in-focus and a far-field image, or to design a phase-only hologram. If you have only one magnitude and a support, use error reduction, hybrid input-output or one of the newer projection methods. If the data are noisy, the error will not reach zero; stop when it reaches the noise level.

Pitfalls

  • The centered transform. Optical data usually have the zero frequency in the middle. Shift the data with fftshift before you compare them with an unshifted DFT, or the two planes do not match.
  • Intensity and magnitude. Detectors measure the intensity ∣Fu∣2|F_u|^2. Take the square root first.
  • The scale of the DFT. With the unnormalized DFT, ∑u∣Fu∣2=n∑j∣fj∣2\sum_u |F_u|^2 = n \sum_j |f_j|^2. Data that break this energy balance are inconsistent, and the error cannot reach zero.
  • Zeros. Where Gu=0G_u = 0, the phase is not defined. Any fixed choice keeps the proof valid; line L4 uses phase zero.
  • Stagnation. A flat error that is not zero is a stagnation point, not a solution. Restart from other phases.

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.

gerchberg_saxton_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gerchberg-saxton-algorithm/. The authors are listed in prov/QDZSDB.jsonl.

"""The Gerchberg-Saxton algorithm: a phase from two magnitudes.

A complex signal f of length n is unknown. Its magnitude a = |f| in the
object plane and the magnitude A = |DFT(f)| in the Fourier plane are known
(unnormalized forward DFT, 1/n on the inverse, as in imgkit). Each iteration
puts the known magnitude on one plane and keeps the phase, then does the
same on the other plane. The errors use the unitary DFT:

    E_F(g)^2 = (1 / n) sum_u (|G_u| - A_u)^2,
    E_0(g')^2 = sum_j (|g'_j| - a_j)^2.

E_F does not increase from one iteration to the next.
"""

import cmath
import math

from imgkit import dft, idft


def with_magnitude(z, mag):
    """The vector with magnitudes mag and the phases of z (phase 0 where z is 0)."""
    return [m * v / abs(v) if abs(v) > 0.0 else complex(m) for v, m in zip(z, mag)]


def fourier_projection(g, amp):
    """P_F g: a nearest signal to g whose DFT magnitude is amp."""
    return idft(with_magnitude(dft(g), amp))


def fourier_error(g, amp):
    """E_F(g) = ||g - P_F g||."""
    n = len(g)
    return math.sqrt(sum((abs(v) - a) ** 2 for v, a in zip(dft(g), amp)) / n)


def object_error(gp, mag):
    """E_0(g') = ||g' - P_O g'||."""
    return math.sqrt(sum((abs(v) - a) ** 2 for v, a in zip(gp, mag)))


def gerchberg_saxton(mag, amp, phase0, iters):
    """Run Gerchberg-Saxton. Returns (g, errors) with errors[k] = E_F(g_k), k = 0 .. iters."""
    g = [m * cmath.exp(1j * p) for m, p in zip(mag, phase0)]  # @line L1
    n = len(g)
    errors = []
    for _ in range(iters):  # @line L2
        gf = dft(g)  # @line L3
        errors.append(math.sqrt(sum((abs(v) - a) ** 2 for v, a in zip(gf, amp)) / n))
        gpf = with_magnitude(gf, amp)  # @line L4
        gp = idft(gpf)  # @line L5
        g = with_magnitude(gp, mag)  # @line L6
    errors.append(fourier_error(g, amp))
    return g, errors  # @line L7
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_gerchberg_saxton_algorithm.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gerchberg-saxton-algorithm/. The authors are listed in prov/QDZSDB.jsonl.

import cmath
import math
import random

from gerchberg_saxton_algorithm import (
    fourier_error,
    fourier_projection,
    gerchberg_saxton,
    object_error,
    with_magnitude,
)
from imgkit import dft, idft


def dist(a, b):
    return math.sqrt(sum(abs(x - y) ** 2 for x, y in zip(a, b)))


def dist_up_to_phase(g, f):
    """min over c with |c| = 1 of ||g - c f||."""
    ip = sum(x.conjugate() * y for x, y in zip(f, g))
    c = ip / abs(ip) if abs(ip) > 0 else 1.0
    return dist(g, [c * v for v in f])


def problem(seed, n=16, k=8):
    """A complex signal with k nonzero entries, padded with zeros to length n."""
    rng = random.Random(seed)
    f = [rng.uniform(0.5, 1.5) * cmath.exp(1j * rng.uniform(-math.pi, math.pi)) if j < k else 0j
         for j in range(n)]
    mag = [abs(v) for v in f]
    amp = [abs(v) for v in dft(f)]
    return f, mag, amp


def test_fourier_projection_is_a_nearest_point() -> None:
    rng = random.Random(1)
    _, _, amp = problem(1)
    g = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(16)]
    p = fourier_projection(g, amp)
    assert max(abs(abs(v) - a) for v, a in zip(dft(p), amp)) < 1e-9
    d0 = dist(g, p)
    assert abs(d0 - fourier_error(g, amp)) < 1e-9
    for _ in range(100):
        other = idft([a * cmath.exp(1j * rng.uniform(0, 2 * math.pi)) for a in amp])
        assert dist(g, other) >= d0 - 1e-9


def test_object_projection_is_a_nearest_point() -> None:
    rng = random.Random(2)
    _, mag, _ = problem(2)
    g = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(16)]
    p = with_magnitude(g, mag)
    d0 = dist(g, p)
    assert abs(d0 - object_error(g, mag)) < 1e-12
    for _ in range(100):
        other = [m * cmath.exp(1j * rng.uniform(0, 2 * math.pi)) for m in mag]
        assert dist(g, other) >= d0 - 1e-12


def test_true_signal_is_a_fixed_point() -> None:
    f, mag, amp = problem(3)
    g, errors = gerchberg_saxton(mag, amp, [cmath.phase(v) for v in f], 3)
    assert dist(g, f) < 1e-9
    assert max(errors) < 1e-9


def test_error_never_increases() -> None:
    rng = random.Random(4)
    for seed in (5, 6, 7):
        _, mag, amp = problem(seed)
        phase0 = [rng.uniform(-math.pi, math.pi) for _ in range(16)]
        _, errors = gerchberg_saxton(mag, amp, phase0, 60)
        for e0, e1 in zip(errors, errors[1:]):
            assert e1 <= e0 + 1e-10
        assert errors[-1] < errors[0]


def test_error_sandwich_of_one_step() -> None:
    rng = random.Random(8)
    _, mag, amp = problem(9)
    g = [m * cmath.exp(1j * rng.uniform(-math.pi, math.pi)) for m in mag]
    for _ in range(5):
        gp = fourier_projection(g, amp)
        e_f = fourier_error(g, amp)
        e_0 = object_error(gp, mag)
        g_next = with_magnitude(gp, mag)
        assert fourier_error(g_next, amp) <= e_0 + 1e-10
        assert e_0 <= e_f + 1e-10
        g = g_next


def test_consistent_pair_from_a_nearby_start() -> None:
    # Known answer: a consistent pair (mag, amp) of a zero padded signal and a start
    # within 0.3 rad of the true phase. The result must match f up to a global phase.
    rng = random.Random(10)
    for seed in (11, 12, 13):
        f, mag, amp = problem(seed)
        phase0 = [cmath.phase(v) + rng.uniform(-0.3, 0.3) for v in f]
        g, errors = gerchberg_saxton(mag, amp, phase0, 250)
        assert errors[-1] < 1e-9
        assert dist_up_to_phase(g, f) < 1e-8 * math.sqrt(sum(m * m for m in mag))


def test_example_of_the_page() -> None:
    f = [1, 1j, -1, 2, 0, 0, 0, 0]
    mag = [abs(v) for v in f]
    amp = [abs(v) for v in dft(f)]
    s2 = math.sqrt(2)
    expected = [math.sqrt(5), s2 - 1, math.sqrt(13), 3 + s2, math.sqrt(5), 1 + s2, math.sqrt(5), 3 - s2]
    assert max(abs(a - b) for a, b in zip(amp, expected)) < 1e-12
    for seed in range(1, 6):
        rng = random.Random(seed)
        phase0 = [rng.uniform(-math.pi, math.pi) for _ in f]
        g, errors = gerchberg_saxton(mag, amp, phase0, 200)
        assert errors[-1] < 1e-12
        assert dist_up_to_phase(g, f) < 1e-10

History

Gerchberg and Saxton published the algorithm in 1972. They wanted the phase of the electron wave in an electron microscope, from one picture in the image plane and one in the diffraction plane. Fienup (1978, 1982) changed it for the case of one intensity measurement and constraints in the object domain, which gave the error reduction and hybrid input-output algorithms, and proved that the error of the alternation does not increase.

References

  1. R. W. Gerchberg and W. O. Saxton, A practical algorithm for the determination of phase from image and diffraction plane pictures, Optik 35(2), 1972, pages 237 to 246, the iteration between the image plane and the diffraction plane
  2. J. R. Fienup, Phase retrieval algorithms, a comparison, Applied Optics 21(15), 1982, 2758 to 2769, the Gerchberg-Saxton algorithm as the parent of error reduction, and the proof that the error does not increase
  3. Yoav Shechtman, Yonina C. Eldar, Oren Cohen, Henry N. Chapman, Jianwei Miao and Mordechai Segev, Phase retrieval with application to optical imaging, a contemporary overview, IEEE Signal Processing Magazine 32(3), 2015, 87 to 109, the section on alternating projection algorithms

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
  • a scene preset for the example