Algorithm Search⌘K

Algorithmcore

Error reduction algorithm

Also called Fienup error reduction.

Alternate between the measured Fourier magnitude and a support (and nonnegativity) constraint. The error never grows, but the iteration often stops short of a solution.

Time
O(K N log N) worst
Space
O(N) extra
Where
K = the number of iterations; N = the number of pixels
Properties
deterministicnot exactnot in placeoffline
Origin
James R. Fienup, 1978

The error reduction algorithm solves the phase retrieval problem with a known support. It alternates two projections: it puts the measured Fourier magnitude on the current image and keeps the phase, then it sets the image to zero off the support (and, if the object is known to be nonnegative, clips it there). Fienup (1982) showed that the Fourier error never grows from one iteration to the next, and that each iteration is a steepest descent step with unit step on the squared error. The error can stop at a positive value, so error reduction often stagnates before it finds a solution. The hybrid input-output algorithm was made to get past this.

In plain words

You have a picture that you cannot see. You know how bright each spot of its diffraction pattern is, and you know that the object fits inside a small box. You want the picture back.

Start with any guess. Compute its diffraction pattern. The brightness is wrong, so replace it with the measured brightness and keep the rest. Go back to a picture. Now the picture has some stuff outside the box, and maybe some negative values. Remove them. That is one round.

Each round fixes one rule and breaks the other a little. The amount by which the two rules disagree can never grow. But it can stop shrinking before it gets to zero. Then the guess is stuck, and more rounds do not help.

The problem

The input is an n1×n2n_1 \times n_2 array of magnitudes Au=∣Fu∣A_u = |F_u|, where FF is the DFT of an unknown image ff with N=n1n2N = n_1 n_2 pixels, and a support mask SS that holds every nonzero pixel of ff. Sometimes ff is also known to be real and nonnegative. The output is an image gg that is zero off SS (and nonnegative, if required) and whose DFT has magnitude AA. Such an image is equal to ff at best up to the trivial ambiguities. The DFT is unnormalized forward with 1/N1/N on the inverse. Errors use the unitary DFT, so they are distances between images.

The algorithm

  1. ERROR-REDUCTION(A, S, g₀, K)
  2. 1g ← P_S(g₀)
  3. 2for k ← 1 to K do
  4. 3G ← DFT(g)
  5. 4G′_u ← A_u · G_u / |G_u| for each frequency u ▷ A_u when G_u = 0
  6. 5g′ ← IDFT(G′)
  7. 6g ← P_S(g′)
  8. 7return g

PS(g′)P_S(g') keeps g′(r)g'(r) on the support and sets 00 off it. With nonnegativity it sets max⁡(Re⁡g′(r),0)\max(\operatorname{Re} g'(r), 0) on the support. Lines L3 to L5 together are the magnitude projection PMP_M: the nearest image whose DFT has magnitude AA. Line L6 is the nearest image that satisfies the object constraint. Line L1 starts inside the constraint set, which the proof needs.

The Fourier error of an image is

EF(g)2=1N∑u(∣Gu∣−Au)2=∥g−PMg∥2.E_F(g)^2 = \frac{1}{N} \sum_u \bigl(|G_u| - A_u\bigr)^2 = \|g - P_M g\|^2 .

The object error of g′g' is E0(g′)2=∥g′−PSg′∥2E_0(g')^2 = \|g' - P_S g'\|^2, the energy that line L6 removes.

Example

The object is a 4×44 \times 4 nonnegative block in the corner of an 8×88 \times 8 frame:

f=(1201031021410102).f = \begin{pmatrix} 1 & 2 & 0 & 1 \\ 0 & 3 & 1 & 0 \\ 2 & 1 & 4 & 1 \\ 0 & 1 & 0 & 2 \end{pmatrix}.

The support SS is the 4×44 \times 4 block, so the oversampling ratio is 64/16=464 / 16 = 4. The start is a random image with entries in [0,1][0, 1], with nonnegativity on. These are measurements of the implementation with two fixed seeds:

iteration kk 0 1 2 5 10 50 100 200 500
EFE_F, seed 1 4.899 1.858 1.347 0.972 0.892 0.620 0.617 0.617 0.617
EFE_F, seed 2 4.481 1.698 1.283 0.882 0.749 0.586 0.472 0.435 0.227

The error never grows. In the first run it stops at 0.617 after about 100 iterations and does not move again: this is stagnation at a point that is not a solution. In the second run it is still falling slowly at 500 iterations. The large drop in the first iterations, then a long slow tail, is the typical behavior.

Correctness

Let gkg_k be the image after kk passes and gk′=PMgkg'_k = P_M g_k. Both projections are nearest point maps: PMP_M by a per-frequency argument and Parseval's identity, PSP_S by a per-pixel argument. Since gk′g'_k has the right magnitude and gkg_k satisfies the object constraint,

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. This is a theorem. It does not say that the error goes to zero: the set of images with magnitude AA is not convex, and the iterates can stop at a point that is not a solution. Where no DFT entry is zero, B(g)=12EF(g)2B(g) = \frac{1}{2}E_F(g)^2 has the gradient g−PMgg - P_M g, so line L5 is the step g−∇B(g)g - \nabla B(g) and line L6 projects it. This is Fienup's steepest descent view. The full proof is below.

Proof: The error of error reduction never increasesfull

The setting is that of the algorithm. Images have NN pixels and live in CN\mathbb{C}^N with ⟨u,v⟩=∑ru(r)‾ v(r)\langle u, v\rangle = \sum_r \overline{u(r)}\, v(r) and ∥u∥2=⟨u,u⟩\|u\|^2 = \langle u, u\rangle. The data are magnitudes Au≥0A_u \ge 0 for each frequency uu. Let M={g:∣Gu∣=Au for all u}M = \{g : |G_u| = A_u \text{ for all } u\}, where GG is the DFT of gg (unnormalized forward, 1/N1/N on the inverse). Let CC be the object constraint set: the images that are zero off the support SS, and, with nonnegativity, real and nonnegative on SS. Arithmetic is exact.

Let PMgP_M g be the image of lines L3 to L5, and let PCg′P_C g' be the image of line L6. Define EF(g)=∥g−PMg∥E_F(g) = \|g - P_M g\| and E0(g′)=∥g′−PCg′∥E_0(g') = \|g' - P_C g'\|.

Lemma 1 (Parseval). For all images g,hg, h, ∥g−h∥2=1N∑u∣Gu−Hu∣2\|g - h\|^2 = \frac{1}{N} \sum_u |G_u - H_u|^2.

Proof. The unitary DFT Fu=N−1/2FF_u = N^{-1/2} F preserves inner products, and Fu(g−h)=N−1/2(G−H)F_u(g - h) = N^{-1/2}(G - H). □\square

Lemma 2 (the magnitude step). PMg∈MP_M g \in M, and ∥g−PMg∥≤∥g−h∥\|g - P_M g\| \le \|g - h\| for every h∈Mh \in M. Also EF(g)2=1N∑u(∣Gu∣−Au)2E_F(g)^2 = \frac{1}{N}\sum_u (|G_u| - A_u)^2.

Proof. By line L4, the DFT of PMgP_M g has magnitude AuA_u at each uu, so PMg∈MP_M g \in M. By Lemma 1, ∥g−h∥2=1N∑u∣Gu−Hu∣2\|g - h\|^2 = \frac{1}{N}\sum_u |G_u - H_u|^2, and each term depends on one frequency. For complex numbers zz and ww with ∣w∣=a|w| = a, the triangle inequality gives ∣z−w∣≥∣∣z∣−a∣|z - w| \ge \bigl||z| - a\bigr|. If z≠0z \ne 0, the number az/∣z∣a z / |z| of line L4 lies on the ray of zz and gives equality. If z=0z = 0, each ww with ∣w∣=a|w| = a gives ∣z−w∣=a=∣∣z∣−a∣|z - w| = a = \bigl||z| - a\bigr|, so the choice w=aw = a also gives equality. So line L4 minimizes each term, and the minimum is 1N∑u(∣Gu∣−Au)2\frac{1}{N}\sum_u (|G_u| - A_u)^2. □\square

Lemma 3 (the object step). PCg′∈CP_C g' \in C, and ∥g′−PCg′∥≤∥g′−h∥\|g' - P_C g'\| \le \|g' - h\| for every h∈Ch \in C.

Proof. The squared distance is a sum over pixels, and the constraints act on each pixel alone. Off SS, every h∈Ch \in C has h(r)=0h(r) = 0, and line L6 sets 00. On SS without nonnegativity, h(r)h(r) is free, and line L6 keeps g′(r)g'(r), with distance 00. On SS with nonnegativity, h(r)=t≥0h(r) = t \ge 0 is real, and ∣g′(r)−t∣2=(Re⁡g′(r)−t)2+(Im⁡g′(r))2|g'(r) - t|^2 = (\operatorname{Re} g'(r) - t)^2 + (\operatorname{Im} g'(r))^2. The minimum over t≥0t \ge 0 is at t=max⁡(Re⁡g′(r),0)t = \max(\operatorname{Re} g'(r), 0), which is what line L6 sets. □\square

Theorem. Let g0=PC(input)g_0 = P_C(\text{input}) be the image of line L1, let gkg_k be the image after kk passes of the loop of line L2, and let 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).

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

Proof. Each gkg_k is in CC: g0g_0 by line L1 and Lemma 3, and gk+1=PCgk′g_{k+1} = P_C g'_k by line L6 and Lemma 3. Each gk′g'_k is in MM by Lemma 2.

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

Second inequality. gk∈Cg_k \in C, so Lemma 3 applied to gk′g'_k gives E0(gk′)=∥gk′−PCgk′∥≤∥gk′−gk∥=∥PMgk−gk∥=EF(gk)E_0(g'_k) = \|g'_k - P_C g'_k\| \le \|g'_k - g_k\| = \|P_M g_k - g_k\| = E_F(g_k). □\square

Corollary (steepest descent). Let B(g)=12EF(g)2B(g) = \frac{1}{2} E_F(g)^2, seen as a function of the 2N2N real numbers Re⁡g(r)\operatorname{Re} g(r) and Im⁡g(r)\operatorname{Im} g(r). At each gg whose DFT has no zero entry, BB is differentiable and its gradient is g−PMgg - P_M g, in the sense that ddtB(g+td)∣t=0=Re⁡⟨g−PMg,d⟩\frac{d}{dt} B(g + t d)\big|_{t=0} = \operatorname{Re}\langle g - P_M g, d\rangle for every direction dd. So line L5 is a steepest descent step g−1⋅∇B(g)g - 1 \cdot \nabla B(g) with unit step, and line L6 projects it onto CC.

Proof. By Lemma 2 and Lemma 1, B(g)=12N∑u(∣Gu∣−Au)2B(g) = \frac{1}{2N}\sum_u (|G_u| - A_u)^2. For Gu≠0G_u \ne 0, ddt∣Gu+tDu∣=Re⁡(Gu‾Du)/∣Gu∣\frac{d}{dt}|G_u + t D_u| = \operatorname{Re}(\overline{G_u} D_u)/|G_u| at t=0t = 0. So

ddtB(g+td)∣t=0=1N∑u(∣Gu∣−Au)Re⁡(Gu‾Du)∣Gu∣=1N∑uRe⁡(Gu−AuGu/∣Gu∣‾  Du).\frac{d}{dt} B(g + t d)\Big|_{t=0} = \frac{1}{N}\sum_u (|G_u| - A_u)\frac{\operatorname{Re}(\overline{G_u} D_u)}{|G_u|} = \frac{1}{N}\sum_u \operatorname{Re}\Bigl(\overline{G_u - A_u G_u/|G_u|}\; D_u\Bigr).

The term Gu−AuGu/∣Gu∣G_u - A_u G_u / |G_u| is the DFT of g−PMgg - P_M g at uu, so by Lemma 1 (in its inner product form) the sum is Re⁡⟨g−PMg,d⟩\operatorname{Re}\langle g - P_M g, d\rangle. □\square

What is not claimed. The theorem does not say that EF(gk)→0E_F(g_k) \to 0. MM is not convex, so the iterates can stop at a point with EF>0E_F > 0 that is not a solution. This stagnation is common in practice. The error is monotone, so it converges to some value E∗≥0E^\ast \ge 0, but E∗E^\ast can be positive.

Complexity

Each iteration does one forward and one inverse 2D 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, so O(KNlog⁡N)O(K N \log N) in total. With the direct sum it is O(N(n1+n2))O(N(n_1 + n_2)) per iteration for the row and column transforms. The extra space is O(N)O(N) for GG and g′g'. The number of iterations KK has no useful bound, because the method can stagnate.

Properties

  • Monotone. EF(gk+1)≤E0(gk′)≤EF(gk)E_F(g_{k+1}) \le E_0(g'_k) \le E_F(g_k) at every step (a theorem).
  • Fixed points. Every solution is a fixed point. The converse is false: stagnation points are fixed points too.
  • Local. It is a descent method on a nonconvex function, so the result depends on the start.
  • Ambiguities remain. A result can be a shift (if the support allows it), a conjugate reversal or a global phase factor of the object. Compare results only up to these.

Variants and improvements

  • Gerchberg-Saxton. The same alternation with a known magnitude in both planes instead of a support.
  • Hybrid input-output. Off the support, it pushes the iterate away from the constraint violation instead of setting it to zero. It escapes most stagnation points, but it has no monotone error and no convergence proof.
  • Difference map and RAAR. Fixed point iterations built from the same two projections that are less likely to stagnate.
  • Shrinkwrap. Starts with a loose support and makes it smaller during the run.
  • Gradient methods. The steepest descent view leads to conjugate gradient and other descent methods on the same error. Fienup compared them in 1982.

When to use it

Use error reduction as a baseline, and as a final polish: a common recipe runs hybrid input-output for some hundreds of iterations and ends with some error reduction iterations, which reduce the error and never increase it. Do not use it alone from a random start on a hard problem, because it stagnates.

Pitfalls

  • Starting outside the constraint set. The proof needs g0g_0 in the constraint set. Line L1 makes sure of this.
  • Errors in different units. With the unnormalized DFT, the Fourier sum is NN times the object domain sum. Use the factor 1/N1/N when you compare EFE_F and E0E_0.
  • Taking a monotone error as success. A small, flat error is not a solution. Check it against the noise level, and try several starts.
  • A support that is too tight or too loose. A support that misses part of the object has no solution. A support that is much too large gives too few constraints for uniqueness; see oversampling.
  • Comparing with the truth. Align the result for shift, conjugate reversal and global phase before you compute an error against the true object.

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.

error_reduction_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/error-reduction-algorithm/. The authors are listed in prov/HKZC9V.jsonl.

"""Fienup's error reduction algorithm for phase retrieval with a support.

Images are lists of rows. The data are the Fourier magnitudes A = |DFT2(f)|
of an unknown image f (unnormalized DFT, as in imgkit). The object
constraint is a support mask S (a list of rows of booleans), with or without
nonnegativity. Each iteration is a magnitude projection P_M followed by an
object projection P_S. The errors use the unitary DFT, so they are distances
in the object domain (N = n1 n2 is the number of pixels):

    E_F(g)^2 = (1 / N) sum_u (|G_u| - A_u)^2 = ||g - P_M g||^2,
    E_0(g')^2 = ||g' - P_S g'||^2.

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

import math

from imgkit import dft2, idft2


def replace_magnitude(gf, amp):
    """The spectrum with magnitude amp and the phase of gf (phase 0 where gf is 0)."""
    out = []
    for row_g, row_a in zip(gf, amp):
        new_row = []
        for v, a in zip(row_g, row_a):
            r = abs(v)
            new_row.append(a * v / r if r > 0.0 else complex(a))
        out.append(new_row)
    return out


def magnitude_projection(g, amp):
    """P_M g: a nearest image to g whose Fourier magnitude is amp."""
    return idft2(replace_magnitude(dft2(g), amp))


def object_projection(gp, support, positive=False):
    """P_S g': keep g' on the support (its nonnegative real part if positive), 0 off it."""
    out = []
    for row_g, row_s in zip(gp, support):
        new_row = []
        for v, inside in zip(row_g, row_s):
            if not inside:
                new_row.append(0.0)
            elif positive:
                new_row.append(max(complex(v).real, 0.0))
            else:
                new_row.append(v)
        out.append(new_row)
    return out


def fourier_error(g, amp):
    """E_F(g) = ||g - P_M g||, computed in the Fourier domain."""
    gf = dft2(g)
    n = len(gf) * len(gf[0])
    s = sum((abs(v) - a) ** 2 for row_g, row_a in zip(gf, amp) for v, a in zip(row_g, row_a))
    return math.sqrt(s / n)


def object_error(gp, support, positive=False):
    """E_0(g') = ||g' - P_S g'||."""
    proj = object_projection(gp, support, positive)
    return math.sqrt(sum(abs(v - p) ** 2 for rv, rp in zip(gp, proj) for v, p in zip(rv, rp)))


def error_reduction(amp, support, g0, iters, positive=False):
    """Run error reduction. Returns (g, errors) with errors[k] = E_F(g_k), k = 0 .. iters."""
    g = object_projection(g0, support, positive)  # @line L1
    errors = []
    n = len(amp) * len(amp[0])
    for _ in range(iters):  # @line L2
        gf = dft2(g)  # @line L3
        errors.append(math.sqrt(sum((abs(v) - a) ** 2 for rg, ra in zip(gf, amp) for v, a in zip(rg, ra)) / n))
        gpf = replace_magnitude(gf, amp)  # @line L4
        gp = idft2(gpf)  # @line L5
        g = object_projection(gp, support, positive)  # @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_error_reduction_algorithm.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/error-reduction-algorithm/. The authors are listed in prov/HKZC9V.jsonl.

import cmath
import math
import random

from error_reduction_algorithm import (
    error_reduction,
    fourier_error,
    magnitude_projection,
    object_error,
    object_projection,
)
from imgkit import dft2, idft2


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


def problem(seed, n=8, k=4):
    """A nonnegative k x k object in the corner of an n x n frame, its support and magnitudes."""
    rng = random.Random(seed)
    f = [[rng.uniform(0.2, 1.0) if i < k and j < k else 0.0 for j in range(n)] for i in range(n)]
    support = [[i < k and j < k for j in range(n)] for i in range(n)]
    amp = [[abs(v) for v in row] for row in dft2(f)]
    return f, support, amp


def random_image(rng, n, cplx=True):
    if cplx:
        return [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)] for _ in range(n)]
    return [[rng.uniform(0, 1) for _ in range(n)] for _ in range(n)]


def test_magnitude_projection_is_a_nearest_point() -> None:
    rng = random.Random(1)
    _, _, amp = problem(1)
    g = random_image(rng, 8)
    p = magnitude_projection(g, amp)
    assert max(abs(abs(v) - a) for rv, ra in zip(dft2(p), amp) for v, a in zip(rv, ra)) < 1e-9
    d0 = dist(g, p)
    assert abs(d0 - fourier_error(g, amp)) < 1e-9
    for _ in range(50):
        phases = [[cmath.exp(1j * rng.uniform(0, 2 * math.pi)) for _ in range(8)] for _ in range(8)]
        other = idft2([[a * ph for a, ph in zip(ra, rp)] for ra, rp in zip(amp, phases)])
        assert dist(g, other) >= d0 - 1e-9


def test_object_projection_is_a_nearest_point() -> None:
    rng = random.Random(2)
    _, support, _ = problem(2)
    g = random_image(rng, 8)
    for positive in (False, True):
        p = object_projection(g, support, positive)
        d0 = dist(g, p)
        assert abs(d0 - object_error(g, support, positive)) < 1e-12
        for _ in range(50):
            q = [[(rng.uniform(0, 2) if positive else complex(rng.gauss(0, 1), rng.gauss(0, 1))) if s else 0.0
                  for s in row] for row in support]
            assert dist(g, q) >= d0 - 1e-12


def test_true_object_is_a_fixed_point() -> None:
    f, support, amp = problem(3)
    for positive in (False, True):
        g, errors = error_reduction(amp, support, f, 3, positive)
        assert dist(g, f) < 1e-9
        assert max(errors) < 1e-9


def test_error_never_increases() -> None:
    rng = random.Random(4)
    for seed, positive in ((5, True), (6, False)):
        _, support, amp = problem(seed)
        g0 = random_image(rng, 8, cplx=not positive)
        _, errors = error_reduction(amp, support, g0, 40, positive)
        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(7)
    _, support, amp = problem(8)
    g = object_projection(random_image(rng, 8, cplx=False), support, True)
    for _ in range(5):
        gp = magnitude_projection(g, amp)
        e_f = fourier_error(g, amp)
        e_0 = object_error(gp, support, True)
        g_next = object_projection(gp, support, True)
        assert fourier_error(g_next, amp) <= e_0 + 1e-10
        assert e_0 <= e_f + 1e-10
        g = g_next


def test_step_is_steepest_descent_with_unit_step() -> None:
    rng = random.Random(9)
    _, _, amp = problem(10)
    g = random_image(rng, 8)
    grad = [[v - p for v, p in zip(rv, rp)] for rv, rp in zip(g, magnitude_projection(g, amp))]
    for _ in range(4):
        d = random_image(rng, 8)
        h = 1e-5
        plus = [[v + h * w for v, w in zip(rv, rd)] for rv, rd in zip(g, d)]
        minus = [[v - h * w for v, w in zip(rv, rd)] for rv, rd in zip(g, d)]
        fd = (0.5 * fourier_error(plus, amp) ** 2 - 0.5 * fourier_error(minus, amp) ** 2) / (2 * h)
        exact = sum((a.conjugate() * b).real for ra, rb in zip(grad, d) for a, b in zip(ra, rb))
        assert abs(fd - exact) < 1e-6 * (1 + abs(exact))

History

Gerchberg and Saxton (1972) described the alternation between two planes with known magnitudes. Fienup (1978) used the same idea with one Fourier magnitude and constraints in the object domain, such as a support and nonnegativity. In his 1982 comparison of phase retrieval algorithms, Fienup called this method error reduction, proved that its error does not increase, showed that it is a form of steepest descent, and proposed the input-output algorithms, among them hybrid input-output.

References

  1. J. R. Fienup, Phase retrieval algorithms, a comparison, Applied Optics 21(15), 1982, 2758 to 2769, the section on the error-reduction algorithm (the error does not increase) and the section on gradient search methods (error reduction as steepest descent)
  2. J. R. Fienup, Reconstruction of an object from the modulus of its Fourier transform, Optics Letters 3(1), 1978, 27 to 29, the iterative method with object domain constraints
  3. 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 two planes with known magnitudes
  4. 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