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.
- Solves
- Phase retrieval
- Time
- O(K N log N) worst
- Space
- O(N) extra
- Where
- K = the number of iterations; N = the number of pixels
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- 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 array of magnitudes , where is the DFT of an unknown image with pixels, and a support mask that holds every nonzero pixel of . Sometimes is also known to be real and nonnegative. The output is an image that is zero off (and nonnegative, if required) and whose DFT has magnitude . Such an image is equal to at best up to the trivial ambiguities. The DFT is unnormalized forward with on the inverse. Errors use the unitary DFT, so they are distances between images.
The algorithm
ERROR-REDUCTION(A, S, g₀, K)- 1
g ← P_S(g₀) - 2
for k ← 1 to K do - 3
G ← DFT(g) - 4
G′_u ← A_u · G_u / |G_u| for each frequency u ▷ A_u when G_u = 0 - 5
g′ ← IDFT(G′) - 6
g ← P_S(g′) - 7
return g
keeps on the support and sets off it. With nonnegativity it sets on the support. Lines L3 to L5 together are the magnitude projection : the nearest image whose DFT has magnitude . 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
The object error of is , the energy that line L6 removes.
Example
The object is a nonnegative block in the corner of an frame:
The support is the block, so the oversampling ratio is . The start is a random image with entries in , with nonnegativity on. These are measurements of the implementation with two fixed seeds:
| iteration | 0 | 1 | 2 | 5 | 10 | 50 | 100 | 200 | 500 |
|---|---|---|---|---|---|---|---|---|---|
| , seed 1 | 4.899 | 1.858 | 1.347 | 0.972 | 0.892 | 0.620 | 0.617 | 0.617 | 0.617 |
| , 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 be the image after passes and . Both projections are nearest point maps: by a per-frequency argument and Parseval's identity, by a per-pixel argument. Since has the right magnitude and satisfies the object constraint,
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 is not convex, and the iterates can stop at a point that is not a solution. Where no DFT entry is zero, has the gradient , so line L5 is the step 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 pixels and live in with and . The data are magnitudes for each frequency . Let , where is the DFT of (unnormalized forward, on the inverse). Let be the object constraint set: the images that are zero off the support , and, with nonnegativity, real and nonnegative on . Arithmetic is exact.
Let be the image of lines L3 to L5, and let be the image of line L6. Define and .
Lemma 1 (Parseval). For all images , .
Proof. The unitary DFT preserves inner products, and .
Lemma 2 (the magnitude step). , and for every . Also .
Proof. By line L4, the DFT of has magnitude at each , so . By Lemma 1, , and each term depends on one frequency. For complex numbers and with , the triangle inequality gives . If , the number of line L4 lies on the ray of and gives equality. If , each with gives , so the choice also gives equality. So line L4 minimizes each term, and the minimum is .
Lemma 3 (the object step). , and for every .
Proof. The squared distance is a sum over pixels, and the constraints act on each pixel alone. Off , every has , and line L6 sets . On without nonnegativity, is free, and line L6 keeps , with distance . On with nonnegativity, is real, and . The minimum over is at , which is what line L6 sets.
Theorem. Let be the image of line L1, let be the image after passes of the loop of line L2, and let . Then for every ,
In particular, .
Proof. Each is in : by line L1 and Lemma 3, and by line L6 and Lemma 3. Each is in by Lemma 2.
First inequality. , so Lemma 2 applied to gives .
Second inequality. , so Lemma 3 applied to gives .
Corollary (steepest descent). Let , seen as a function of the real numbers and . At each whose DFT has no zero entry, is differentiable and its gradient is , in the sense that for every direction . So line L5 is a steepest descent step with unit step, and line L6 projects it onto .
Proof. By Lemma 2 and Lemma 1, . For , at . So
The term is the DFT of at , so by Lemma 1 (in its inner product form) the sum is .
What is not claimed. The theorem does not say that . is not convex, so the iterates can stop at a point with that is not a solution. This stagnation is common in practice. The error is monotone, so it converges to some value , but can be positive.
Complexity
Each iteration does one forward and one inverse 2D DFT and other work. With a fast Fourier transform the cost is per iteration, so in total. With the direct sum it is per iteration for the row and column transforms. The extra space is for and . The number of iterations has no useful bound, because the method can stagnate.
Properties
- Monotone. 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 in the constraint set. Line L1 makes sure of this.
- Errors in different units. With the unnormalized DFT, the Fourier sum is times the object domain sum. Use the factor when you compare and .
- 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.
# 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
- 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)
- 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
- 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
- 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.
| 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 HKZC9V Edit this page History Report an error Markdown