Algorithm Search⌘K

Algorithmadvanced

Difference map

Also called Elser difference map.

Find a point in the intersection of two sets, such as a support set and a Fourier magnitude set, by a fixed point map built from both projections. With gamma_S = -1 and gamma_M = 1/beta it is HIO.

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
Veit Elser, 2003

The difference map is a fixed point iteration for phase retrieval and other problems of the form "find a point in two sets at once". It uses only the two projections: here PSP_S onto the images that fit the support, and PMP_M onto the images whose Fourier transform has the measured magnitude. Elser (2003) built it so that every fixed point gives a solution through a simple read-out, unlike the fixed points of error reduction. It is a family with parameters β\beta, γS\gamma_S and γM\gamma_M. The choice γS=−1\gamma_S = -1, γM=1/β\gamma_M = 1/\beta gives Fienup's hybrid input-output with feedback β\beta; Elser's own choice is γS=−1/β\gamma_S = -1/\beta, γM=1/β\gamma_M = 1/\beta, and the two agree at β=1\beta = 1.

In plain words

You look for a picture that obeys two rules: it must fit in a box, and its diffraction pattern must have the measured brightness. For each rule there is an easy repair: the nearest picture that obeys that rule.

The difference map makes two estimates from the current guess. One estimate first moves the guess a little with the box repair, then repairs the brightness. The other estimate does the same in the other order. If both rules can be met, a good guess makes the two estimates agree. So the map moves the guess by the difference between the two estimates.

When the guess stops moving, the two estimates agree, and that common picture obeys both rules. The guess itself is only a tool to get there.

The problem

The input is the Fourier magnitude AA of an unknown image with NN pixels, a support mask SS, and maybe nonnegativity. The output is an image in both sets CC (the images that fit the support and the sign) and MM (the images whose DFT has magnitude AA). The method needs only the two maps PSP_S and PMP_M, each a nearest point map onto its set. PMP_M is the magnitude step of error reduction.

The algorithm

  1. DIFFERENCE-MAP(A, S, x₀, K, β, γ_S, γ_M)
  2. 1x ← x₀
  3. 2for k ← 1 to K do
  4. 3f_S ← (1 + γ_S) · P_S(x) − γ_S · x
  5. 4f_M ← (1 + γ_M) · P_M(x) − γ_M · x
  6. 5x ← x + β · (P_S(f_M) − P_M(f_S))
  7. 6return P_M(f_S)

Lines L3 and L4 make the two estimates. Line L5 moves xx by β\beta times the difference of the projected estimates. Line L6 is the read-out: at a fixed point, PM(fS)P_M(f_S) and PS(fM)P_S(f_M) are equal, and the common value is a solution. Each step calls PMP_M twice and PSP_S twice. In Elser's notation the support constraint is π1\pi_1 and the magnitude constraint is π2\pi_2; changing the sign of β\beta exchanges the roles of the two sets.

The parameters:

  • Elser's choice is γS=−1/β\gamma_S = -1/\beta and γM=1/β\gamma_M = 1/\beta. The value of β\beta is tuned to the problem.
  • With γS=−1\gamma_S = -1, γM=1/β\gamma_M = 1/\beta and a support constraint only, line L3 gives fS=xf_S = x, and the step is HIO with feedback β\beta (Luke 2005 states this; the proof below checks it).
  • With β=1\beta = 1, γS=−1\gamma_S = -1 and γM=1\gamma_M = 1, it is the Douglas-Rachford step x+PS(2PMx−x)−PMxx + P_S(2P_M x - x) - P_M x.

Example

Use the 4×44 \times 4 nonnegative object of the error reduction and HIO pages,

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

in the corner of an 8×88 \times 8 frame, with the 4×44 \times 4 support and nonnegativity. Take β=0.9\beta = 0.9, γS=−1/0.9\gamma_S = -1/0.9 and γM=1/0.9\gamma_M = 1/0.9, and the random start of seed 1, from which error reduction stops at the error 0.617. The gap ∥PS(fM)−PM(fS)∥\|P_S(f_M) - P_M(f_S)\| at step kk (measurements of the implementation):

step kk 0 1 2 5 10 20 50 100 150 200 249
gap 6.3 5.9 4.5 1.4 0.55 0.079 0.0011 1.1e-6 0.095 1.5e-5 1.7e-8

The gap falls to 10−610^{-6}, jumps back up to 0.0950.095 near step 150, and then falls again to 10−810^{-8}. The read-out is the twin f(3−i,3−j)f(3 - i, 3 - j) of the object to within 3×10−83 \times 10^{-8}; the twin has the same Fourier magnitude and fits the same support. Seeds 2 and 3 also reach a gap below 10−610^{-6} within 250 steps.

Correctness

Three facts are proved below.

  • Fixed points give solutions. If D(x)=xD(x) = x and β≠0\beta \ne 0, then PS(fM(x))=PM(fS(x))P_S(f_M(x)) = P_M(f_S(x)). The left side is in the support set and the right side is in the magnitude set, so the common image is in both.
  • Solutions are fixed points. For a solution zz, both projections leave zz unchanged, so fS(z)=fM(z)=zf_S(z) = f_M(z) = z and D(z)=zD(z) = z, for all parameters.
  • HIO is a special case. With γS=−1\gamma_S = -1, γM=1/β\gamma_M = 1/\beta and a linear support projection, D(x)=x+(β+1)PSPMx−PSx−βPMxD(x) = x + (\beta + 1)P_S P_M x - P_S x - \beta P_M x. This is PMxP_M x on the support and x−βPMxx - \beta P_M x off it: the HIO step.

There is no theorem that the iteration reaches a fixed point. The magnitude set is not convex. The gap is not monotone, as the example shows.

Proof: Fixed points of the difference map give solutions, and HIO is a special casefull

The setting is that of the algorithm. Images have NN pixels. MM is the set of images whose DFT has magnitude AA, and PMP_M (the magnitude step) maps each image to a nearest point of MM. CC is the object constraint set (zero off the support SS, and, with nonnegativity, real and nonnegative on SS), and PSP_S maps each image to its nearest point of CC. A solution is an image in C∩MC \cap M. The parameters are real numbers β≠0\beta \ne 0, γS\gamma_S and γM\gamma_M. Arithmetic is exact.

With

fS(x)=(1+γS)PS(x)−γSx,fM(x)=(1+γM)PM(x)−γMx,f_S(x) = (1 + \gamma_S) P_S(x) - \gamma_S x, \qquad f_M(x) = (1 + \gamma_M) P_M(x) - \gamma_M x,

the difference map is D(x)=x+β [PS(fM(x))−PM(fS(x))]D(x) = x + \beta\,[P_S(f_M(x)) - P_M(f_S(x))], as in lines L3 to L5, and the read-out of line L6 is PM(fS(x))P_M(f_S(x)).

Two facts about the projections are used. (a) PS(x)∈CP_S(x) \in C and PM(x)∈MP_M(x) \in M for every xx, by construction. (b) PS(c)=cP_S(c) = c for c∈Cc \in C and PM(m)=mP_M(m) = m for m∈Mm \in M: a point of a set is its own nearest point (for PMP_M, line L4 maps GuG_u to AuGu/∣Gu∣=GuA_u G_u / |G_u| = G_u when ∣Gu∣=Au>0|G_u| = A_u > 0, and 00 to Au=0A_u = 0).

Theorem 1 (fixed points give solutions). If D(x)=xD(x) = x, then PS(fM(x))=PM(fS(x))P_S(f_M(x)) = P_M(f_S(x)), and this image is a solution.

Proof. D(x)=xD(x) = x means β [PS(fM(x))−PM(fS(x))]=0\beta\,[P_S(f_M(x)) - P_M(f_S(x))] = 0, and β≠0\beta \ne 0, so the two images are equal; call the image zz. By (a), z=PS(fM(x))∈Cz = P_S(f_M(x)) \in C and z=PM(fS(x))∈Mz = P_M(f_S(x)) \in M. So z∈C∩Mz \in C \cap M. □\square

This is why the read-out is not xx itself: a fixed point xx need not be in either set, but the two projected estimates agree there and give a solution. Away from a fixed point, ∥D(x)−x∥/∣β∣=∥PS(fM(x))−PM(fS(x))∥\|D(x) - x\| / |\beta| = \|P_S(f_M(x)) - P_M(f_S(x))\| measures how far the two estimates are apart, which is the gap the implementation reports.

Theorem 2 (solutions are fixed points). If z∈C∩Mz \in C \cap M, then D(z)=zD(z) = z and the read-out at zz is zz, for all values of the parameters.

Proof. By (b), PS(z)=zP_S(z) = z and PM(z)=zP_M(z) = z. So fS(z)=(1+γS)z−γSz=zf_S(z) = (1 + \gamma_S) z - \gamma_S z = z and in the same way fM(z)=zf_M(z) = z. Then PS(fM(z))=zP_S(f_M(z)) = z and PM(fS(z))=zP_M(f_S(z)) = z, so D(z)=z+β(z−z)=zD(z) = z + \beta(z - z) = z, and the read-out is zz. □\square

Theorem 3 (HIO is a special case). Take a support constraint without nonnegativity, so that PSP_S (keep the values on SS, set zero off SS) is linear. Take γS=−1\gamma_S = -1 and γM=1/β\gamma_M = 1/\beta. Then for every xx, with p=PM(x)p = P_M(x),

D(x)(r)=p(r) for r∈S,D(x)(r)=x(r)−β p(r) for r∉S,D(x)(r) = p(r) \text{ for } r \in S, \qquad D(x)(r) = x(r) - \beta\,p(r) \text{ for } r \notin S,

which is the hybrid input-output step with feedback β\beta. With β=1\beta = 1 (so γS=−1\gamma_S = -1 and γM=1\gamma_M = 1, Elser's choice γS=−1/β\gamma_S = -1/\beta, γM=1/β\gamma_M = 1/\beta at β=1\beta = 1), it is the Douglas-Rachford step x+PS(2p−x)−px + P_S(2p - x) - p.

Proof. With γS=−1\gamma_S = -1, fS(x)=0⋅PS(x)+x=xf_S(x) = 0 \cdot P_S(x) + x = x, so PM(fS(x))=pP_M(f_S(x)) = p. With γM=1/β\gamma_M = 1/\beta, fM(x)=(1+1/β) p−x/βf_M(x) = (1 + 1/\beta)\,p - x/\beta. PSP_S is linear, so

D(x)=x+β[(1+1β)PS(p)−1βPS(x)−p]=x+(β+1)PS(p)−PS(x)−βp.D(x) = x + \beta\Bigl[(1 + \tfrac{1}{\beta}) P_S(p) - \tfrac{1}{\beta} P_S(x) - p\Bigr] = x + (\beta + 1) P_S(p) - P_S(x) - \beta p .

On SS, PSP_S is the identity, and this is x+(β+1)p−x−βp=px + (\beta + 1) p - x - \beta p = p. Off SS, PSP_S gives zero, and this is x−βpx - \beta p. For β=1\beta = 1 the formula is x+2PS(p)−PS(x)−p=x+PS(2p−x)−px + 2P_S(p) - P_S(x) - p = x + P_S(2p - x) - p by linearity. □\square

What is not claimed. MM is not convex, and no theorem says that the difference map reaches a fixed point. The gap is not monotone in general; the test file does not check a monotone quantity. Elser's choice γS=−1/β\gamma_S = -1/\beta, γM=1/β\gamma_M = 1/\beta comes from a local analysis near a fixed point, and the value of β\beta is tuned. With nonnegativity, PSP_S is not linear and Theorem 3 does not hold as stated.

Complexity

Each step does two magnitude projections, each one forward and one inverse 2D DFT, and O(N)O(N) other work. With a fast Fourier transform that is O(Nlog⁡N)O(N \log N) per step and O(KNlog⁡N)O(K N \log N) in total, about twice the cost of an HIO step. In the HIO case γS=−1\gamma_S = -1 one projection is not needed, because fS=xf_S = x. The extra space is O(N)O(N).

Properties

  • Fixed points are solutions (through the read-out), for every choice of the parameters.
  • Not monotone. The gap can grow for a while.
  • Symmetric in the two sets. Changing the sign of β\beta swaps their roles.
  • Generic. It needs only the two projections, so it applies to any problem that splits into two constraint sets with easy projections.

Variants and improvements

  • Hybrid input-output. The case γS=−1\gamma_S = -1, γM=1/β\gamma_M = 1/\beta.
  • Douglas-Rachford. The case β=1\beta = 1, γS=−1\gamma_S = -1, γM=1\gamma_M = 1.
  • RAAR. Luke's relaxation of the Douglas-Rachford step, made for noisy and inconsistent data.
  • Many sets. A problem with several constraints can be written as two sets in a product space: one set is the product of all constraint sets, and the other set holds the tuples whose copies are all equal. Then the difference map applies as it is.
  • Shrinkwrap. The support can be updated during the run, as with HIO.

When to use it

Use the difference map when HIO stagnates or when you want one code for several constraint pairs. In phase retrieval with a support it is a direct alternative to HIO and RAAR; which works best depends on the data, and it is usual to try more than one. Read the answer from PM(fS)P_M(f_S), not from xx.

Pitfalls

  • Reading xx. The iterate xx is not the answer. Use the read-out of line L6.
  • Mixed conventions. Papers swap the names of the two sets, the sign of β\beta, and the signs of the γ\gamma. Check the HIO special case on your own code before you trust a parameter value from a paper.
  • Stopping on a small gap. The gap can be small for a short time and then grow, as in the example. Stop on a small gap that stays small, or check the read-out against the data.
  • Nonnegativity breaks linearity. With a sign constraint, PSP_S is not linear, and the HIO identity holds only approximately.

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.

difference_map.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/difference-map/. The authors are listed in prov/CRHCPN.jsonl.

"""Elser's difference map for phase retrieval with a support.

Images are lists of rows. P_M puts the Fourier magnitude A = |DFT2(f)| on an
image (unnormalized DFT, as in imgkit). P_S is the object projection: zero
off the support S, and with positive=True the nonnegative real part on S.
With the estimates

    f_S(x) = (1 + gamma_S) P_S(x) - gamma_S x,
    f_M(x) = (1 + gamma_M) P_M(x) - gamma_M x,

one step is x <- x + beta (P_S(f_M(x)) - P_M(f_S(x))). Elser's choice is
gamma_S = -1 / beta and gamma_M = 1 / beta. The choice gamma_S = -1 and
gamma_M = 1 / beta gives Fienup's HIO with feedback beta (support only).
At a fixed point, P_M(f_S(x)) = P_S(f_M(x)) is a solution.
"""

import math

from imgkit import 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(g, support, positive=False):
    """P_S g: g on the support (its nonnegative real part if positive), 0 off it."""
    return [[(max(complex(v).real, 0.0) if positive else v) if s else 0.0 for v, s in zip(rv, rs)]
            for rv, rs in zip(g, support)]


def combine(a, x, ca, cx):
    """The image ca a + cx x."""
    return [[ca * u + cx * v for u, v in zip(ra, rx)] for ra, rx in zip(a, x)]


def dm_step(x, amp, support, beta, gamma_s, gamma_m, positive=False):
    """One difference map step. Returns (x_next, estimate) with estimate = P_M(f_S(x))."""
    f_s = combine(object_projection(x, support, positive), x, 1 + gamma_s, -gamma_s)  # @line L3
    f_m = combine(magnitude_projection(x, amp), x, 1 + gamma_m, -gamma_m)  # @line L4
    p_m = magnitude_projection(f_s, amp)
    p_s = object_projection(f_m, support, positive)
    x_next = [[v + beta * (s - m) for v, s, m in zip(rv, rs, rm)]
              for rv, rs, rm in zip(x, p_s, p_m)]  # @line L5
    return x_next, p_m


def difference_map(amp, support, x0, iters, beta=0.9, gamma_s=None, gamma_m=None, positive=False):
    """Run the difference map. Returns (estimate, x, gaps).

    gaps[k] = ||x_{k+1} - x_k|| / |beta| = ||P_S(f_M) - P_M(f_S)||, which is zero
    exactly at a fixed point. The defaults are Elser's gamma_S = -1 / beta and
    gamma_M = 1 / beta.
    """
    if gamma_s is None:
        gamma_s = -1.0 / beta
    if gamma_m is None:
        gamma_m = 1.0 / beta
    x = [list(row) for row in x0]  # @line L1
    estimate = x
    gaps = []
    for _ in range(iters):  # @line L2
        x_next, estimate = dm_step(x, amp, support, beta, gamma_s, gamma_m, positive)
        gaps.append(math.sqrt(sum(abs(a - b) ** 2 for ra, rb in zip(x_next, x) for a, b in zip(ra, rb)))
                    / abs(beta))
        x = x_next
    return estimate, x, gaps  # @line L6
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_difference_map.py 76 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/difference-map/. The authors are listed in prov/CRHCPN.jsonl.

import math
import random

from difference_map import difference_map, dm_step, magnitude_projection, object_projection
from imgkit import dft2

OBJ = [[1, 2, 0, 1], [0, 3, 1, 0], [2, 1, 4, 1], [0, 1, 0, 2]]


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 page_problem():
    f = [[float(OBJ[i][j]) if i < 4 and j < 4 else 0.0 for j in range(8)] for i in range(8)]
    twin = [[float(OBJ[3 - i][3 - j]) if i < 4 and j < 4 else 0.0 for j in range(8)] for i in range(8)]
    support = [[i < 4 and j < 4 for j in range(8)] for i in range(8)]
    amp = [[abs(v) for v in row] for row in dft2(f)]
    return f, twin, support, amp


def random_complex(rng):
    return [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(8)] for _ in range(8)]


def hio_reference(x, amp, support, beta):
    """Fienup's HIO step for a support constraint only, written out directly."""
    p = magnitude_projection(x, amp)
    return [[p[i][j] if support[i][j] else x[i][j] - beta * p[i][j] for j in range(8)] for i in range(8)]


def test_hio_is_the_case_gamma_s_minus_one_gamma_m_one_over_beta() -> None:
    rng = random.Random(1)
    _, _, support, amp = page_problem()
    for beta in (0.5, 0.9, 1.0):
        x = random_complex(rng)
        step, _ = dm_step(x, amp, support, beta, -1.0, 1.0 / beta)
        assert dist(step, hio_reference(x, amp, support, beta)) < 1e-12


def test_beta_one_with_elser_choice_is_douglas_rachford() -> None:
    rng = random.Random(2)
    _, _, support, amp = page_problem()
    x = random_complex(rng)
    pm = magnitude_projection(x, amp)
    ps = object_projection([[2 * p - v for p, v in zip(rp, rv)] for rp, rv in zip(pm, x)], support)
    dr = [[v + s - p for v, s, p in zip(rv, rs, rp)] for rv, rs, rp in zip(x, ps, pm)]
    step, _ = dm_step(x, amp, support, 1.0, -1.0, 1.0)
    assert dist(step, dr) < 1e-12


def test_solution_is_a_fixed_point_and_is_read_out() -> None:
    f, _, support, amp = page_problem()
    for beta, positive in ((0.9, True), (0.7, False), (-0.8, True)):
        step, est = dm_step(f, amp, support, beta, -1.0 / beta, 1.0 / beta, positive)
        assert dist(step, f) < 1e-9
        assert dist(est, f) < 1e-9


def test_reconstruction_on_the_page_example() -> None:
    # Measurement, not a theorem: beta = 0.9 with Elser's gamma values, 250 steps,
    # three seeds. The two read-outs agree and give the object or its twin.
    f, twin, support, amp = page_problem()
    for seed in (1, 2, 3):
        rng = random.Random(seed)
        x0 = [[rng.uniform(0, 1) for _ in range(8)] for _ in range(8)]
        est, x, gaps = difference_map(amp, support, x0, 250, beta=0.9, positive=True)
        assert gaps[-1] < 1e-6
        f_m = [[(1 + 1 / 0.9) * p - v / 0.9 for p, v in zip(rp, rv)]
               for rp, rv in zip(magnitude_projection(x, amp), x)]
        other = object_projection(f_m, support, True)
        assert dist(est, other) < 1e-5
        assert min(dist(est, f), dist(est, twin)) < 1e-5

History

Elser (2003) proposed the difference map in a paper on phase retrieval by iterated projections, with a preprint in 2001. He showed that at β=1\beta = 1 it reproduces Fienup's HIO with feedback 1, and chose γS=−1/β\gamma_S = -1/\beta and γM=1/β\gamma_M = 1/\beta. Bauschke, Combettes and Luke (2002) had shown that HIO with β=1\beta = 1 is Douglas-Rachford. Luke (2005) placed the difference map, HIO and his RAAR in one framework of reflections.

References

  1. Veit Elser, Phase retrieval by iterated projections, Journal of the Optical Society of America A 20(1), 2003, 40 to 55, the definition of the difference map with the estimates f_1 and f_2, the choice gamma_1 = -1/beta and gamma_2 = 1/beta, the read-out of the solution at a fixed point, and the relation to HIO (preprint arXiv math/0111080)
  2. D. Russell Luke, Relaxed averaged alternating reflections for diffraction imaging, Inverse Problems 21(1), 2005, 37 to 50, the statement that HIO for the support constraint is the difference map with gamma_1 = -1 and gamma_2 = 1/beta (preprint arXiv math/0405208)
  3. Heinz H. Bauschke, Patrick L. Combettes and D. Russell Luke, Phase retrieval, error reduction algorithm, and Fienup variants, a view from convex optimization, Journal of the Optical Society of America A 19(7), 2002, 1334 to 1345, HIO with beta = 1 as the Douglas-Rachford algorithm

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