Algorithmadvanced
Shrinkwrap
Also called shrinkwrap support update.
Phase retrieval without a known support. Start from the thresholded autocorrelation, run HIO, and every few steps set the support to a threshold of a blurred copy of the estimate.
- Solves
- Phase retrieval
- Time
- O(K N log N + (K / T) N^2) worst
- Space
- O(N) extra
- Where
- K = the number of iterations; N = the number of pixels; T = the steps between support updates
- Model
- Real RAM
- Properties
- deterministicnot exactnot in placeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Stefano Marchesini, Henry N. Chapman, John C. H. Spence, 2003
Shrinkwrap is a method for phase retrieval when the support of the object is not known. Marchesini and coworkers (2003) proposed it for x-ray diffraction. It starts with a loose support from the autocorrelation, which the data give directly. It runs hybrid input-output with that support. Every few steps it blurs the current estimate with a Gaussian and takes the pixels above a fraction of the maximum as the new support. As the estimate improves, the support shrinks around the object.
In plain words
To find the lost phases you need to know where the object is, but you do not know that before you have the object. Shrinkwrap solves both at once.
The measured pattern gives one free clue: a blurry map of all the distances inside the object. That map is larger than the object, so it is a safe first box. You run the usual repair method in that box for a while. Then you blur the current picture and keep only its bright part as the new box. The box fits the object a little better each time, and a better box gives a better picture.
The problem
The input is the Fourier magnitude of an unknown nonnegative image with pixels. No support is given. The output is a nonnegative image with Fourier magnitude and a small support. A shift of , and the twin , have the same data, so the answer is only up to these changes.
The algorithm
SHRINKWRAP(A, g₀, K, β, T, σ₀, σ_min, d, τ, τ₀)- 1
S ← {r : |IDFT2(A²)(r)| ≥ τ₀ · max} - 2
g ← g₀; σ ← σ₀ - 3
for k ← 1 to K do - 4
(g, g′) ← HIO-STEP(g, A, S, β) - 5
if k mod T = 0 then - 6
S ← {r : (G_σ ∗ |P_S g′|)(r) ≥ τ · max} - 7
σ ← max(d · σ, σ_min) - 8
return P_S(g′), S
- Line L1 is the start. is the autocorrelation of , also called the Patterson function in crystallography. For its support holds a shifted copy of the support of .
- Line L4 is one HIO step with nonnegativity for the current support. is the image after the magnitude step.
- Line L6 is the update. is the current estimate, is a periodic Gaussian of width with sum 1, and the new support is the set of pixels where the blur is at least times its maximum.
- Line L7 makes the blur narrower, down to .
Marchesini and coworkers used , , , , pixels, and pixels for their images. These values are tuned. The blur must fit the size of the object, as the example shows.
Example
Take a frame with the nonnegative object
at rows 3 to 7 and columns 4 to 8. Its support has 19 pixels. Only is given. The thresholded autocorrelation (line L1) has 49 pixels, a block around the origin. Run with , , and the other values as above, from the random start of seed 1. The object error at step , and the size of the support after the update at step (measurements of the implementation):
| step | 1 | 20 | 40 | 60 | 100 | 200 | 300 | 400 |
|---|---|---|---|---|---|---|---|---|
| 9.31 | 1.2 | 1.05 | 0.26 | 0.0175 | 6.7e-4 | 4.8e-6 | 4.1e-8 | |
| support size | 49 | 24 | 25 | 22 | 22 | 22 | 22 | 21 |
After 400 steps the estimate is the object shifted by 10 rows and 11 columns (with wrap around), to within . The final support has 21 pixels and holds the 19 pixels of the shifted object. The starts of seeds 2 and 3 give the object or its twin, up to a shift, to within and .
For comparison, HIO with the fixed 49 pixel start support gets to within , and after 400 steps from the same starts. With Marchesini's widths and , which suit images much larger than this one, the support stays at 71 to 80 pixels, and seeds 1 and 3 do not find the object.
Correctness
The proof page shows four facts. There is no theorem that shrinkwrap finds the object.
- The start uses only the data. is the autocorrelation .
- The start is safe before the threshold. For , on a shifted copy of the support of . The threshold of line L1 is a tuned choice and can cut this.
- Solutions are fixed points. If is a nonnegative image with magnitude and the support holds the support of , the HIO step keeps .
- The update keeps a solution in some cases. If , where is the center value of the Gaussian, the new support holds the support of .
Proof: The autocorrelation start, the fixed point property, and when the support update keeps the supportfull
Images have pixels, and indices are taken modulo and . The DFT is with , and the inverse has the factor . The data are . Arithmetic is exact. There is no claim that shrinkwrap converges; what is proved is that each part does what the algorithm uses it for.
Lemma 1 (the start is the autocorrelation). Line L1 computes , and this is the periodic autocorrelation
Proof. Take the DFT of and put :
The inverse DFT of is therefore .
So the start needs only the data.
Lemma 2 (the autocorrelation holds a shifted support). Let and let be a pixel with . Then for every with . So the set contains the support of shifted by .
Proof. Every term of is at least , and the term is .
The algorithm thresholds at a fraction (4 percent) of its maximum. Lemma 2 is about the set where ; the threshold makes the start tighter and is a tuned choice, so the thresholded start need not hold a shifted support. A shift of the object does not change , so a shifted support is as good as the true one.
Lemma 3 (fixed points). Let have , and let the current support contain the support of . Then the HIO step of line L4 maps to , and the estimate is .
Proof. already has the Fourier magnitude , so (the magnitude step keeps the phase and sets the magnitude, which is already ), and is real. On , , so the step keeps . Off , because holds the support of , and the step gives . So the new image is . The estimate keeps the nonnegative real part on , which is .
Lemma 4 (when the update keeps the support). Let , let be the Gaussian kernel of line L6 (nonnegative, sum 1, value at the center), and let be the threshold. If , then the new support contains the support of .
Proof. All terms of are at least , so . Also , so . For with ,
Corollary. If an iterate reaches a solution while the support holds the support of , and the condition of Lemma 4 holds for the current and , then every later step and every later update keeps and a support that holds the support of .
Proof. Lemma 3 for the steps, Lemma 4 for the updates (the update is applied to the estimate, which is by Lemma 3), and induction.
What is not claimed. There is no theorem that shrinkwrap reaches a solution, that the support shrinks to the true support, or that it stays near it. The condition of Lemma 4 is sufficient, not necessary; for an object with a large range of values it fails, and a weak pixel at the edge of the object can then drop out of the support. The thresholds 4 and 20 percent, the update every 20 steps and the widths of the Gaussian are tuned values. The tests check Lemmas 1 to 4 and one reconstruction as a measurement.
Complexity
Each HIO step costs with a fast Fourier transform. Each update is one blur. The implementation blurs by direct periodic convolution, per update; a blur through the FFT costs . The start is one inverse FFT. With steps and an update every steps, the total is , or with FFT blurs. The extra space is .
Properties
- Needs no support. Only the Fourier magnitude and nonnegativity, or another object constraint.
- Heuristic. No convergence proof; the parameters are tuned.
- Gives the object up to a shift and the twin, because the data do not fix them.
- Works with any iteration. HIO can be replaced by RAAR or the difference map in line L4.
Variants and improvements
- Other iterations. RAAR or the difference map in place of HIO.
- Complex objects. Marchesini and coworkers also report complex objects; then line L4 uses the support constraint without nonnegativity, and line L6 blurs the modulus.
- Missing data. Pixels of the pattern behind a beam stop can be left free in the magnitude step, as in the original paper.
- Final polish. A few steps of error reduction with the final support reduce the error further.
- Ptychography. Many overlapping patterns make the support constraint less important.
When to use it
Use shrinkwrap for coherent diffraction imaging of an isolated object when the support is not known well. Choose the blur width from the size of the object in pixels, and try several starts.
Pitfalls
- A blur that is too wide. The support then stays too large, as in the example with on a small object.
- A threshold that is too high. Weak parts of the object fall out of the support and are lost.
- Comparing with the truth. The answer can be shifted, and it can be the twin. Compare up to shifts and the twin.
- Noise. Marchesini and coworkers expect the method to fail when the noise in the estimate becomes larger than the update threshold, because the noise then shapes the support.
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
# 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
shrinkwrap.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shrinkwrap/. The authors are listed in prov/J58G2A.jsonl.
"""Shrinkwrap: phase retrieval with a support that is updated during the run.
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 support is not
given. It starts as the thresholded autocorrelation IDFT2(A^2), which holds
a shifted copy of the support of a nonnegative object. The iteration is HIO.
Every `every` steps the current object estimate is blurred with a Gaussian
of width sigma, and the new support is the set of pixels where the blur is
at least `thresh` times its maximum. Then sigma shrinks by the factor
`decay`, down to sigma_min. The default values (threshold 0.04 for the
autocorrelation, 0.2 for the update, every 20 steps, sigma from 3 to 1.5 by
1 percent) are the ones Marchesini et al. (2003) report; they are tuned,
not derived. There is no convergence proof.
"""
import math
from imgkit import circ_conv2, dft2, idft2
def magnitude_projection(g, amp):
"""P_M g: the nearest image to g whose Fourier magnitude is amp."""
gf = dft2(g)
for row_g, row_a in zip(gf, amp):
for j, (v, a) in enumerate(zip(row_g, row_a)):
r = abs(v)
row_g[j] = a * v / r if r > 0.0 else complex(a)
return idft2(gf)
def object_projection(gp, support):
"""P_S g': the nonnegative real part of g' on the support, 0 off it."""
return [[max(complex(v).real, 0.0) if s else 0.0 for v, s in zip(rv, rs)]
for rv, rs in zip(gp, support)]
def object_error(gp, support):
"""E_0(g') = ||g' - P_S g'||."""
proj = object_projection(gp, support)
return math.sqrt(sum(abs(v - p) ** 2 for rv, rp in zip(gp, proj) for v, p in zip(rv, rp)))
def hio_step(g, amp, support, beta):
"""One HIO step with nonnegativity. Returns (g_next, g') with g' = Re P_M g."""
gp = [[complex(v).real for v in row] for row in magnitude_projection(g, amp)]
out = [[p if s and p >= 0.0 else v - beta * p for v, p, s in zip(rv, rp, rs)]
for rv, rp, rs in zip(g, gp, support)]
return out, gp
def autocorrelation(amp):
"""IDFT2(A^2): the periodic autocorrelation c(t) = sum_r f(r + t) conj(f(r))."""
return idft2([[a * a for a in row] for row in amp])
def threshold_support(img, frac):
"""The pixels where |img| is at least frac times its maximum."""
top = max(abs(v) for row in img for v in row)
return [[abs(v) >= frac * top for v in row] for row in img]
def gaussian_kernel(n1, n2, sigma):
"""A periodic Gaussian of width sigma, centered at (0, 0), with sum 1."""
def w(i, n):
d = min(i, n - i)
return math.exp(-d * d / (2.0 * sigma * sigma))
k = [[w(i, n1) * w(j, n2) for j in range(n2)] for i in range(n1)]
total = sum(sum(row) for row in k)
return [[v / total for v in row] for row in k]
def update_support(est, sigma, thresh):
"""Blur |est| with a Gaussian of width sigma and keep the pixels at or above thresh times the maximum."""
blur = circ_conv2([[abs(v) for v in row] for row in est], gaussian_kernel(len(est), len(est[0]), sigma))
return threshold_support(blur, thresh)
def shrinkwrap(amp, g0, iters, beta=0.9, every=20, sigma0=3.0, sigma_min=1.5, decay=0.99,
thresh=0.2, auto_thresh=0.04):
"""Run HIO with shrinkwrap support updates. Returns (estimate, support, errors)."""
support = threshold_support(autocorrelation(amp), auto_thresh) # @line L1
g = [list(row) for row in g0] # @line L2
sigma = sigma0
errors = []
gp = g
for k in range(1, iters + 1): # @line L3
g, gp = hio_step(g, amp, support, beta) # @line L4
errors.append(object_error(gp, support))
if k % every == 0: # @line L5
support = update_support(object_projection(gp, support), sigma, thresh) # @line L6
sigma = max(decay * sigma, sigma_min) # @line L7
return object_projection(gp, support), support, errors # @line L8
def distance(a, b):
"""The Euclidean distance between two images."""
return math.sqrt(sum(abs(u - v) ** 2 for ra, rb in zip(a, b) for u, v in zip(ra, rb)))
test_shrinkwrap.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shrinkwrap/. The authors are listed in prov/J58G2A.jsonl.
import random
from imgkit import dft2
from shrinkwrap import (autocorrelation, distance, gaussian_kernel, hio_step, object_projection,
shrinkwrap, threshold_support, update_support)
N = 16
BLOB = [[0, 1, 2, 1, 0], [1, 3, 4, 2, 0], [2, 4, 5, 3, 1], [0, 2, 3, 2, 2], [0, 0, 1, 2, 3]]
def page_object():
f = [[0.0] * N for _ in range(N)]
for i in range(5):
for j in range(5):
f[3 + i][4 + j] = float(BLOB[i][j])
return f
def amplitudes(f):
return [[abs(v) for v in row] for row in dft2(f)]
def shifted(img, a, b):
n1, n2 = len(img), len(img[0])
return [[img[(i - a) % n1][(j - b) % n2] for j in range(n2)] for i in range(n1)]
def test_autocorrelation_is_the_direct_sum() -> None:
rng = random.Random(1)
f = [[complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(8)] for _ in range(8)]
c = autocorrelation(amplitudes(f))
for a in range(8):
for b in range(8):
direct = sum(f[(i + a) % 8][(j + b) % 8] * f[i][j].conjugate()
for i in range(8) for j in range(8))
assert abs(c[a][b] - direct) < 1e-9
def test_autocorrelation_holds_a_shifted_support() -> None:
# For f >= 0 and r0 in the support, c(t) >= f(r0) f(r0 + t) > 0 for every t in supp f - r0.
f = page_object()
c = autocorrelation(amplitudes(f))
top = max(abs(v) for row in c for v in row)
r0 = (3, 5)
for i in range(N):
for j in range(N):
if f[i][j] > 0:
assert c[(i - r0[0]) % N][(j - r0[1]) % N].real > 1e-9 * top
def test_gaussian_kernel() -> None:
k = gaussian_kernel(16, 16, 1.5)
assert abs(sum(sum(row) for row in k) - 1.0) < 1e-12
assert k[0][0] == max(max(row) for row in k)
for i in range(16):
for j in range(16):
assert abs(k[i][j] - k[(-i) % 16][(-j) % 16]) < 1e-15
def test_threshold_supports_are_nested() -> None:
rng = random.Random(2)
img = [[rng.random() for _ in range(N)] for _ in range(N)]
low, high = threshold_support(img, 0.2), threshold_support(img, 0.6)
assert all(lo or not hi for rl, rh in zip(low, high) for lo, hi in zip(rl, rh))
assert sum(map(sum, high)) < sum(map(sum, low))
def test_update_keeps_the_support_under_the_lemma_condition() -> None:
# If min f * k(0) >= thresh * max f on supp f (f >= 0), the update holds supp f.
f = [[v + 2.0 if v > 0 else 0.0 for v in row] for row in page_object()]
sigma, thresh = 0.5, 0.2
k0 = gaussian_kernel(N, N, sigma)[0][0]
vals = [v for row in f for v in row if v > 0]
assert min(vals) * k0 >= thresh * max(vals)
new = update_support(f, sigma, thresh)
assert all(s or v == 0 for rs, rv in zip(new, f) for s, v in zip(rs, rv))
def test_true_object_is_a_fixed_point_of_the_hio_step() -> None:
f = page_object()
support = [[v > 0 for v in row] for row in f]
g, gp = hio_step(f, amplitudes(f), support, 0.9)
assert distance(g, f) < 1e-9
assert distance(object_projection(gp, support), f) < 1e-9
def test_reconstruction_on_the_page_example() -> None:
# Measurement, not a theorem. The support is not given; the answer is the object or its
# twin up to a cyclic shift, and the final support holds the support of that copy.
f = page_object()
twin = [[f[(-i) % N][(-j) % N] for j in range(N)] for i in range(N)]
rng = random.Random(3)
g0 = [[rng.random() for _ in range(N)] for _ in range(N)]
est, support, _ = shrinkwrap(amplitudes(f), g0, 300, sigma0=1.0, sigma_min=0.5)
best = min((distance(est, shifted(ref, a, b)), ref, a, b)
for ref in (f, twin) for a in range(N) for b in range(N))
assert best[0] < 1e-4
copy = shifted(best[1], best[2], best[3])
assert all(s or v == 0 for rs, rv in zip(support, copy) for s, v in zip(rs, rv))
History
The support of the autocorrelation as a bound for the object comes from the vector space methods of crystallography, which the paper cites through Buerger (1959). Marchesini and coworkers (2003) made the support update part of the iteration, with the blur and threshold step. They reconstructed an image of a test object made of gold balls from an x-ray diffraction pattern at a wavelength of 2.1 nm alone. They also compared HIO with fixed supports of known accuracy under Poisson noise, and found that HIO needs a support known at about the resolution of the reconstruction.
References
- S. Marchesini, H. He, H. N. Chapman, S. P. Hau-Riege, A. Noy, M. R. Howells, U. Weierstall and J. C. H. Spence, X-ray image reconstruction from a diffraction pattern alone, Physical Review B 68, 2003, 140101(R), the description of the algorithm, with the start from the autocorrelation at the 4 percent level, HIO with beta = 0.9, the update every 20 iterations with a Gaussian of width sigma from 3 pixels down by 1 percent per update to 1.5 pixels, and the threshold at 20 percent (preprint arXiv physics/0306174)
- J. R. Fienup, Phase retrieval algorithms, a comparison, Applied Optics 21(15), 1982, 2758 to 2769, the hybrid input-output algorithm used for the steps between updates
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 J58G2A Edit this page History Report an error Markdown