Algorithm Search⌘K

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.

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
Properties
deterministicnot exactnot in placeoffline
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 A=∣DFT2(f)∣A = |\mathrm{DFT2}(f)| of an unknown nonnegative image ff with NN pixels. No support is given. The output is a nonnegative image with Fourier magnitude AA and a small support. A shift of ff, and the twin f(−r)f(-r), have the same data, so the answer is ff only up to these changes.

The algorithm

  1. SHRINKWRAP(A, g₀, K, β, T, σ₀, σ_min, d, τ, τ₀)
  2. 1S ← {r : |IDFT2(A²)(r)| ≥ τ₀ · max}
  3. 2g ← g₀; σ ← σ₀
  4. 3for k ← 1 to K do
  5. 4(g, g′) ← HIO-STEP(g, A, S, β)
  6. 5if k mod T = 0 then
  7. 6S ← {r : (G_σ ∗ |P_S g′|)(r) ≥ τ · max}
  8. 7σ ← max(d · σ, σ_min)
  9. 8return P_S(g′), S
  • Line L1 is the start. IDFT2(A2)\mathrm{IDFT2}(A^2) is the autocorrelation of ff, also called the Patterson function in crystallography. For f≥0f \ge 0 its support holds a shifted copy of the support of ff.
  • Line L4 is one HIO step with nonnegativity for the current support. g′g' is the image after the magnitude step.
  • Line L6 is the update. PSg′P_S g' is the current estimate, GσG_\sigma is a periodic Gaussian of width σ\sigma with sum 1, and the new support is the set of pixels where the blur is at least τ\tau times its maximum.
  • Line L7 makes the blur narrower, down to σmin⁡\sigma_{\min}.

Marchesini and coworkers used τ0=0.04\tau_0 = 0.04, β=0.9\beta = 0.9, T=20T = 20, τ=0.2\tau = 0.2, σ0=3\sigma_0 = 3 pixels, d=0.99d = 0.99 and σmin⁡=1.5\sigma_{\min} = 1.5 pixels for their images. These values are tuned. The blur must fit the size of the object, as the example shows.

Example

Take a 16×1616 \times 16 frame with the nonnegative 5×55 \times 5 object

(0121013420245310232200123)\begin{pmatrix} 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 \end{pmatrix}

at rows 3 to 7 and columns 4 to 8. Its support has 19 pixels. Only AA is given. The thresholded autocorrelation (line L1) has 49 pixels, a 7×77 \times 7 block around the origin. Run with σ0=1\sigma_0 = 1, σmin⁡=0.5\sigma_{\min} = 0.5, and the other values as above, from the random start of seed 1. The object error E0=∥g′−PSg′∥E_0 = \|g' - P_S g'\| at step kk, and the size of the support after the update at step kk (measurements of the implementation):

step kk 1 20 40 60 100 200 300 400
E0E_0 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 4.7×10−94.7 \times 10^{-9}. 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 2.7×10−72.7 \times 10^{-7} and 1.1×10−101.1 \times 10^{-10}.

For comparison, HIO with the fixed 49 pixel start support gets to within 0.0100.010, 0.00940.0094 and 0.00120.0012 after 400 steps from the same starts. With Marchesini's widths σ0=3\sigma_0 = 3 and σmin⁡=1.5\sigma_{\min} = 1.5, 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. IDFT2(A2)\mathrm{IDFT2}(A^2) is the autocorrelation c(t)=∑rf(r+t)f(r)‾c(t) = \sum_r f(r + t) \overline{f(r)}.
  • The start is safe before the threshold. For f≥0f \ge 0, c>0c > 0 on a shifted copy of the support of ff. The threshold of line L1 is a tuned choice and can cut this.
  • Solutions are fixed points. If g=zg = z is a nonnegative image with magnitude AA and the support holds the support of zz, the HIO step keeps zz.
  • The update keeps a solution in some cases. If k(0)min⁡z>0z≥τmax⁡zk(0) \min_{z > 0} z \ge \tau \max z, where k(0)k(0) is the center value of the Gaussian, the new support holds the support of zz.
Proof: The autocorrelation start, the fixed point property, and when the support update keeps the supportfull

Images have n1×n2n_1 \times n_2 pixels, and indices are taken modulo n1n_1 and n2n_2. The DFT is F(k)=∑tf(t) e−2πi⟨t,k⟩F(k) = \sum_t f(t)\, e^{-2\pi i \langle t, k \rangle} with ⟨t,k⟩=t1k1/n1+t2k2/n2\langle t, k \rangle = t_1 k_1 / n_1 + t_2 k_2 / n_2, and the inverse has the factor 1/(n1n2)1/(n_1 n_2). The data are A=∣F∣A = |F|. 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 IDFT2(A2)\mathrm{IDFT2}(A^2), and this is the periodic autocorrelation

c(t)=∑rf(r+t) f(r)‾.c(t) = \sum_r f(r + t)\, \overline{f(r)} .

Proof. Take the DFT of cc and put s=r+ts = r + t:

∑tc(t)e−2πi⟨t,k⟩=∑rf(r)‾e2πi⟨r,k⟩∑sf(s)e−2πi⟨s,k⟩=F(k)‾ F(k)=A(k)2.\sum_t c(t) e^{-2\pi i \langle t, k \rangle} = \sum_r \overline{f(r)} e^{2\pi i \langle r, k \rangle} \sum_s f(s) e^{-2\pi i \langle s, k \rangle} = \overline{F(k)}\, F(k) = A(k)^2 .

The inverse DFT of A2A^2 is therefore cc. □\square

So the start needs only the data.

Lemma 2 (the autocorrelation holds a shifted support). Let f≥0f \ge 0 and let r0r_0 be a pixel with f(r0)>0f(r_0) > 0. Then c(t)>0c(t) > 0 for every tt with f(r0+t)>0f(r_0 + t) > 0. So the set {t:c(t)>0}\{t : c(t) > 0\} contains the support of ff shifted by −r0-r_0.

Proof. Every term of c(t)=∑rf(r+t)f(r)c(t) = \sum_r f(r + t) f(r) is at least 00, and the term r=r0r = r_0 is f(r0+t)f(r0)>0f(r_0 + t) f(r_0) > 0. □\square

The algorithm thresholds ∣c∣|c| at a fraction (4 percent) of its maximum. Lemma 2 is about the set where c>0c > 0; 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 AA, so a shifted support is as good as the true one.

Lemma 3 (fixed points). Let z≥0z \ge 0 have ∣DFT2(z)∣=A|\mathrm{DFT2}(z)| = A, and let the current support SS contain the support of zz. Then the HIO step of line L4 maps zz to zz, and the estimate PS(Re PMz)P_S(\mathrm{Re}\, P_M z) is zz.

Proof. zz already has the Fourier magnitude AA, so PMz=zP_M z = z (the magnitude step keeps the phase and sets the magnitude, which is already AA), and g′=zg' = z is real. On SS, g′(r)=z(r)≥0g'(r) = z(r) \ge 0, so the step keeps z(r)z(r). Off SS, z(r)=0z(r) = 0 because SS holds the support of zz, and the step gives z(r)−β⋅0=0z(r) - \beta \cdot 0 = 0. So the new image is zz. The estimate keeps the nonnegative real part on SS, which is zz. □\square

Lemma 4 (when the update keeps the support). Let z≥0z \ge 0, let kk be the Gaussian kernel of line L6 (nonnegative, sum 1, value k(0)k(0) at the center), and let τ∈(0,1)\tau \in (0, 1) be the threshold. If k(0)min⁡{z(r):z(r)>0}≥τmax⁡rz(r)k(0) \min\{z(r) : z(r) > 0\} \ge \tau \max_r z(r), then the new support {r:(k∗z)(r)≥τmax⁡(k∗z)}\{r : (k * z)(r) \ge \tau \max (k * z)\} contains the support of zz.

Proof. All terms of (k∗z)(r)=∑qk(q)z(r−q)(k * z)(r) = \sum_q k(q) z(r - q) are at least 00, so (k∗z)(r)≥k(0)z(r)(k * z)(r) \ge k(0) z(r). Also (k∗z)(r)≤max⁡z∑qk(q)=max⁡z(k * z)(r) \le \max z \sum_q k(q) = \max z, so max⁡(k∗z)≤max⁡z\max(k * z) \le \max z. For rr with z(r)>0z(r) > 0,

(k∗z)(r)≥k(0)z(r)≥k(0)min⁡z>0z≥τmax⁡z≥τmax⁡(k∗z).□(k * z)(r) \ge k(0) z(r) \ge k(0) \min_{z > 0} z \ge \tau \max z \ge \tau \max(k * z). \qquad \square

Corollary. If an iterate reaches a solution z≥0z \ge 0 while the support holds the support of zz, and the condition of Lemma 4 holds for the current σ\sigma and τ\tau, then every later step and every later update keeps zz and a support that holds the support of zz.

Proof. Lemma 3 for the steps, Lemma 4 for the updates (the update is applied to the estimate, which is zz by Lemma 3), and induction. □\square

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 O(Nlog⁡N)O(N \log N) with a fast Fourier transform. Each update is one blur. The implementation blurs by direct periodic convolution, O(N2)O(N^2) per update; a blur through the FFT costs O(Nlog⁡N)O(N \log N). The start is one inverse FFT. With KK steps and an update every TT steps, the total is O(KNlog⁡N+(K/T)N2)O(K N \log N + (K/T) N^2), or O(KNlog⁡N)O(K N \log N) with FFT blurs. The extra space is O(N)O(N).

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 σ=3\sigma = 3 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.

imgkit.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

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
  • at least three sources
  • a scene preset for the example