Algorithm Search⌘K

Algorithmadvanced

Relaxed averaged alternating reflections

Also called RAAR.

Phase retrieval by a step that mixes the Douglas-Rachford reflection step with the magnitude projection. For convex sets that meet, its fixed points are exactly the solutions.

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
D. Russell Luke, 2005

Relaxed averaged alternating reflections (RAAR) is a fixed point iteration for phase retrieval and other problems of the form "find a point in two sets at once". Luke (2005) built it from the Douglas-Rachford step, which is hybrid input-output with β=1\beta = 1. Each step takes the average β\beta of the Douglas-Rachford step and 1−β1 - \beta of the plain magnitude projection. For two convex sets that meet, the fixed points of RAAR are exactly the points in both sets, and the iterates converge. For phase retrieval the magnitude set is not convex, and RAAR is a heuristic that often escapes the stagnation of error reduction.

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.

A reflection goes past the repaired picture by the same distance again, like a mirror. One method reflects through the first rule, reflects through the second rule, and then goes half way back to the start. That method can drift when the data has noise. RAAR mixes it with the plain brightness repair. The mix keeps the drift small, and for simple rules the method stops only at a picture that obeys both rules.

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 uses two nearest point maps: PSP_S onto CC and PMP_M onto MM. PMP_M is the magnitude step of error reduction. A reflection is R=2P−IR = 2P - I: it maps xx to the point on the other side of PxP x.

The algorithm

  1. RAAR(A, S, x₀, K, β)
  2. 1x ← x₀
  3. 2for k ← 1 to K do
  4. 3p ← P_M(x)
  5. 4r ← 2p − x
  6. 5q ← P_S(r)
  7. 6x ← (β/2) · (2q − r + x) + (1 − β) · p
  8. 7return P_M(x)

Line L4 is the reflection RMxR_M x, and 2q−r2q - r is RSRMxR_S R_M x. So line L6 is

V(x)=β2(RSRMx+x)+(1−β)PMx.V(x) = \tfrac{\beta}{2}\bigl(R_S R_M x + x\bigr) + (1 - \beta) P_M x .

The first term is the Douglas-Rachford step, the average of xx and its double reflection. At β=1\beta = 1 RAAR is that step, which is HIO with β=1\beta = 1. Line L7 returns PMxP_M x, which has the measured magnitude; the iterate xx itself is not the answer.

For a support without nonnegativity, PSP_S keeps the values on SS and sets the rest to zero, and the step has a simple pointwise form, with p=PMxp = P_M x:

  • on SS: the new value is pp;
  • off SS: the new value is βx+(1−2β)p\beta x + (1 - 2\beta) p.

HIO gives x−βpx - \beta p off SS. The value of β\beta is tuned to the problem.

Example

Use the 4×44 \times 4 nonnegative object of the error reduction, HIO and difference map 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. Start from the random image of seed 1, from which error reduction stops at the error 0.617. Take β=0.95\beta = 0.95. The distance from the estimate PMxP_M x to the object set, ∥PMx−PSPMx∥\|P_M x - P_S P_M x\|, at step kk (measurements of the implementation):

step kk 0 1 2 5 10 20 50 100 150 200 250
distance 6.2 5.6 3.4 1.1 0.26 0.04 7.9e-4 1.2e-5 2.6e-7 4.5e-9 1e-10

The estimate is the twin f(3−i,3−j)f(3 - i, 3 - j) to within 3.2×10−103.2 \times 10^{-10}. The twin has the same Fourier magnitude and fits the same support.

The value of β\beta matters. Over the random starts of seeds 1, 2 and 3, with 300 steps:

β\beta 0.5 0.7 0.8 0.9 0.95
starts that reach a solution 0 of 3 1 of 3 2 of 3 2 of 3 3 of 3

With β=0.5\beta = 0.5 every start stagnates, as error reduction does. These numbers hold for this small example only.

Correctness

The proof page proves these facts for two closed convex sets AA and BB in place of CC and MM.

  • Firmly nonexpansive. The reflections are nonexpansive, so the Douglas-Rachford step is firmly nonexpansive, and so is its convex combination with PBP_B.
  • Fixed points are solutions. For 0<β<10 < \beta < 1 and A∩BA \cap B nonempty, V(x)=xV(x) = x holds exactly for x∈A∩Bx \in A \cap B. At β=1\beta = 1 only PBxP_B x is a solution, which is why the read-out is PMxP_M x.
  • Convergence. If VV has a fixed point, the distance from xkx_k to each fixed point never grows, and xkx_k converges to a fixed point.

MM is not convex, so none of this applies to phase retrieval. There, a fixed point need not give a solution, and there is no convergence proof. The example shows that RAAR can still find a solution where error reduction stagnates.

Proof: RAAR for two convex sets that meet, its fixed points and its convergencefull

The space is CN\mathbb{C}^N with the real inner product ⟨u,v⟩=Re⁡∑rur‾vr\langle u, v \rangle = \operatorname{Re} \sum_r \overline{u_r} v_r and its norm. AA and BB are closed convex sets with nearest point maps PAP_A and PBP_B (in the algorithm, AA is the object set of PSP_S and BB is the magnitude set of PMP_M). The reflections are RA=2PA−IR_A = 2P_A - I and RB=2PB−IR_B = 2P_B - I. For 0<β≤10 < \beta \le 1 the RAAR map of lines L3 to L6 is

V(x)=β2(RARBx+x)+(1−β)PBx.V(x) = \tfrac{\beta}{2}\bigl(R_A R_B x + x\bigr) + (1 - \beta) P_B x .

Line L6 writes this as β2(2q−r+x)+(1−β)p\tfrac{\beta}{2}(2q - r + x) + (1 - \beta)p with p=PBxp = P_B x, r=2p−x=RBxr = 2p - x = R_B x and q=PArq = P_A r; then 2q−r=RARBx2q - r = R_A R_B x, so the two forms agree.

A map FF is nonexpansive if ∥Fx−Fy∥≤∥x−y∥\|Fx - Fy\| \le \|x - y\| for all x,yx, y, and firmly nonexpansive if ∥Fx−Fy∥2≤⟨Fx−Fy,x−y⟩\|Fx - Fy\|^2 \le \langle Fx - Fy, x - y \rangle for all x,yx, y.

Lemma 1. FF is firmly nonexpansive if and only if 2F−I2F - I is nonexpansive.

Proof. Put a=Fx−Fya = Fx - Fy and d=x−yd = x - y. Then ∥(2F−I)x−(2F−I)y∥2=∥2a−d∥2=4∥a∥2−4⟨a,d⟩+∥d∥2\|(2F - I)x - (2F - I)y\|^2 = \|2a - d\|^2 = 4\|a\|^2 - 4\langle a, d \rangle + \|d\|^2. This is at most ∥d∥2\|d\|^2 if and only if ∥a∥2≤⟨a,d⟩\|a\|^2 \le \langle a, d \rangle. □\square

Lemma 2. For a closed convex set CC, the nearest point p=PCxp = P_C x is the point of CC with ⟨x−p,w−p⟩≤0\langle x - p, w - p \rangle \le 0 for all w∈Cw \in C, and PCP_C is firmly nonexpansive.

Proof. The first claim is the standard variational form of the nearest point: for w∈Cw \in C and t∈(0,1]t \in (0, 1], the point p+t(w−p)p + t(w - p) is in CC, so ∥x−p∥2≤∥x−p−t(w−p)∥2=∥x−p∥2−2t⟨x−p,w−p⟩+t2∥w−p∥2\|x - p\|^2 \le \|x - p - t(w - p)\|^2 = \|x - p\|^2 - 2t\langle x - p, w - p \rangle + t^2\|w - p\|^2. Divide by tt and let t→0t \to 0. For the second claim, put p=PCxp = P_C x and p′=PCyp' = P_C y. The inequality for xx with w=p′w = p' and the one for yy with w=pw = p add to ⟨(x−y)−(p−p′),p′−p⟩≤0\langle (x - y) - (p - p'), p' - p \rangle \le 0, which is ∥p−p′∥2≤⟨p−p′,x−y⟩\|p - p'\|^2 \le \langle p - p', x - y \rangle. □\square

Lemma 3. VV is firmly nonexpansive.

Proof. By Lemmas 1 and 2, RAR_A and RBR_B are nonexpansive, so RARBR_A R_B is nonexpansive. T=12(RARB+I)T = \tfrac12(R_A R_B + I) has 2T−I=RARB2T - I = R_A R_B, so TT is firmly nonexpansive by Lemma 1. Now V=βT+(1−β)PBV = \beta T + (1 - \beta) P_B, and

2V−I=β(2T−I)+(1−β)(2PB−I),2V - I = \beta(2T - I) + (1 - \beta)(2P_B - I),

a convex combination of two nonexpansive maps, which is nonexpansive by the triangle inequality. By Lemma 1, VV is firmly nonexpansive. □\square

Theorem 1 (fixed points). Let 0<β<10 < \beta < 1 and let A∩BA \cap B be nonempty. Then V(x)=xV(x) = x if and only if x∈A∩Bx \in A \cap B.

Proof. If x∈A∩Bx \in A \cap B, then PBx=xP_B x = x, RBx=xR_B x = x, RAx=xR_A x = x, so V(x)=β2(2x)+(1−β)x=xV(x) = \tfrac{\beta}{2}(2x) + (1 - \beta)x = x.

Conversely, let V(x)=xV(x) = x and take any z∈A∩Bz \in A \cap B. With pp, rr, qq as above, β2(2q−r+x)=β(q−p+x)\tfrac{\beta}{2}(2q - r + x) = \beta(q - p + x), so the fixed point equation is x=βx+β(q−p)+(1−β)px = \beta x + \beta(q - p) + (1 - \beta)p, that is, (1−β)(x−p)=β(q−p)(1 - \beta)(x - p) = \beta(q - p). Put u=x−pu = x - p and c=(1−β)/β>0c = (1 - \beta)/\beta > 0. Then q=p+cuq = p + c u and r=p−ur = p - u.

Lemma 2 for p=PBxp = P_B x with w=z∈Bw = z \in B gives ⟨u,z−p⟩≤0\langle u, z - p \rangle \le 0.

Lemma 2 for q=PArq = P_A r with w=z∈Aw = z \in A gives ⟨r−q,z−q⟩≤0\langle r - q, z - q \rangle \le 0. Here r−q=−(1+c)ur - q = -(1 + c)u, so ⟨u,z−q⟩≥0\langle u, z - q \rangle \ge 0, that is, ⟨u,z−p⟩≥c∥u∥2\langle u, z - p \rangle \ge c\|u\|^2.

So c∥u∥2≤⟨u,z−p⟩≤0c\|u\|^2 \le \langle u, z - p \rangle \le 0, and u=0u = 0. Then x=p∈Bx = p \in B and q=p=xq = p = x, so x=PAr∈Ax = P_A r \in A. □\square

For β=1\beta = 1 (Douglas-Rachford) the argument gives only c=0c = 0, and the fixed points are the points xx with PBx∈A∩BP_B x \in A \cap B; the iterate itself need not be a solution. This is why the implementation returns PBx=PMxP_B x = P_M x (line L7) for all β\beta.

Theorem 2 (convergence). Let 0<β≤10 < \beta \le 1, let VV have a fixed point, and let xk+1=V(xk)x_{k+1} = V(x_k). Then for every fixed point zz the distance ∥xk−z∥\|x_k - z\| never grows, and xkx_k converges to a fixed point x∗x^\ast. For β<1\beta < 1 and A∩BA \cap B nonempty, x∗∈A∩Bx^\ast \in A \cap B, and the read-out PBxkP_B x_k converges to x∗x^\ast.

Proof. For firmly nonexpansive VV and Vz=zVz = z, with a=Vx−za = Vx - z and d=x−zd = x - z, we have ∥a∥2≤⟨a,d⟩\|a\|^2 \le \langle a, d \rangle, and so

∥x−Vx∥2=∥d−a∥2=∥d∥2−2⟨a,d⟩+∥a∥2≤∥d∥2−∥a∥2.\|x - Vx\|^2 = \|d - a\|^2 = \|d\|^2 - 2\langle a, d\rangle + \|a\|^2 \le \|d\|^2 - \|a\|^2 .

So ∥xk+1−z∥2+∥xk−xk+1∥2≤∥xk−z∥2\|x_{k+1} - z\|^2 + \|x_k - x_{k+1}\|^2 \le \|x_k - z\|^2. The distance to zz never grows, the sequence is bounded, and summing over kk gives ∑k∥xk−xk+1∥2≤∥x0−z∥2\sum_k \|x_k - x_{k+1}\|^2 \le \|x_0 - z\|^2, so ∥xk−Vxk∥→0\|x_k - V x_k\| \to 0. In CN\mathbb{C}^N a bounded sequence has a convergent subsequence xkj→x∗x_{k_j} \to x^\ast. VV is continuous (it is nonexpansive), so x∗−Vx∗=lim⁡(xkj−Vxkj)=0x^\ast - V x^\ast = \lim (x_{k_j} - V x_{k_j}) = 0, and x∗x^\ast is a fixed point. Take z=x∗z = x^\ast: the distance ∥xk−x∗∥\|x_k - x^\ast\| never grows and has a subsequence that tends to 00, so it tends to 00. The last claim follows from Theorem 1 and the continuity of PBP_B, since PBx∗=x∗P_B x^\ast = x^\ast. □\square

The support form. If AA is the subspace of images that are zero off a support SS (no sign constraint), then PAP_A keeps the values on SS and sets the rest to zero, and for any PBP_B, convex or not,

V(x)(t)=p(t) for t∈S,V(x)(t)=βx(t)+(1−2β)p(t) for t∉S.V(x)(t) = p(t) \text{ for } t \in S, \qquad V(x)(t) = \beta x(t) + (1 - 2\beta) p(t) \text{ for } t \notin S .

Proof. On SS, q=r=2p−xq = r = 2p - x and β2(2q−r+x)=β2(2p)=βp\tfrac{\beta}{2}(2q - r + x) = \tfrac{\beta}{2}(2p) = \beta p, so V(x)=βp+(1−β)p=pV(x) = \beta p + (1 - \beta)p = p. Off SS, q=0q = 0 and β2(−r+x)=β(x−p)\tfrac{\beta}{2}(-r + x) = \beta(x - p), so V(x)=βx−βp+(1−β)p=βx+(1−2β)pV(x) = \beta x - \beta p + (1 - \beta)p = \beta x + (1 - 2\beta)p. □\square

Compare HIO, which gives x−βpx - \beta p off SS: at β=1\beta = 1 the two agree.

What is not claimed. The magnitude set MM of phase retrieval is not convex, PMP_M is not firmly nonexpansive, and none of the theorems above applies to it. For phase retrieval RAAR is a heuristic with the fixed point property of the support form: if x=V(x)x = V(x) and β<1\beta < 1, then off SS we get (1−β)x=(1−2β)p(1 - \beta)x = (1 - 2\beta)p, which does not force p=0p = 0 there, so a fixed point need not give a solution. The tests check Lemma 3 and Theorem 2 on two convex sets, the support form, the case β=1\beta = 1, and that the true object is a fixed point; the reconstruction test on the page example is a measurement.

Complexity

Each step does one magnitude projection, which is 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, the same as HIO and about half the cost of a step of the difference map with Elser's parameters. The extra space is O(N)O(N).

Properties

  • Firmly nonexpansive for convex sets, for every β\beta in (0,1](0, 1].
  • Fixed points are solutions for convex sets that meet and β<1\beta < 1.
  • Not monotone for phase retrieval. The error can grow for a while.
  • Generic. It needs only the two nearest point maps.

Variants and improvements

  • Douglas-Rachford and HIO. The case β=1\beta = 1.
  • Difference map. Another family of fixed point maps built from the two projections; with suitable parameters it also contains HIO.
  • Shrinkwrap. The support can be updated during the run.
  • Many sets. As with the difference map, several constraints can be written as two sets in a product space.
  • Ptychography. Projection methods of the same kind are used with many overlapping measurements.

When to use it

Use RAAR in place of HIO when the data is noisy, when the support is only roughly known, or when HIO does not settle. It costs the same per step. Try several values of β\beta and several starts, and read the answer from PMxP_M x.

Pitfalls

  • Reading xx. The iterate xx is not the answer. Use PMxP_M x, or the result of a few steps of error reduction from it.
  • A small β\beta. With β=0.5\beta = 0.5, every start in the example stagnates, as error reduction does.
  • Convex theory for a nonconvex problem. The fixed point and convergence results hold for convex sets. They do not apply to the magnitude set.
  • Mixed conventions. Papers swap the names of the two sets. Check the case β=1\beta = 1 against HIO on your own code.

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
raar.py 75 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/raar/. The authors are listed in prov/MJJXEG.jsonl.

"""Luke's relaxed averaged alternating reflections (RAAR).

For two nearest point maps P_S and P_M and the reflections R = 2 P - I,

    V(x) = (beta / 2) (R_S R_M x + x) + (1 - beta) P_M x,   0 < beta <= 1.

At beta = 1 this is the Douglas-Rachford map. Images are lists of rows. The
phase retrieval version uses P_M, which puts the Fourier magnitude
A = |DFT2(f)| on an image (unnormalized DFT, as in imgkit), and P_S, which
keeps the image on the support S (the nonnegative real part with
positive=True) and sets zero off it. The estimate is P_M x.

For two closed convex sets that meet, V is firmly nonexpansive, its fixed
points are the points of the intersection (for 0 < beta < 1), and the
iterates converge to one of them. For phase retrieval the magnitude set is
not convex, and there is no convergence proof.
"""

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 support_projection(support, positive=False):
    """The map P_S for a support mask, as a function of an image."""
    def proj(g):
        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)]
    return proj


def raar_step(x, proj_s, proj_m, beta):
    """One RAAR step for the nearest point maps proj_s and proj_m."""
    p = proj_m(x)  # @line L3
    r = [[2 * u - v for u, v in zip(rp, rx)] for rp, rx in zip(p, x)]  # @line L4
    q = proj_s(r)  # @line L5
    return [[0.5 * beta * (2 * a - b + v) + (1 - beta) * u
             for a, b, v, u in zip(rq, rr, rx, rp)]
            for rq, rr, rx, rp in zip(q, r, x, p)]  # @line L6


def raar_generic(proj_s, proj_m, x0, iters, beta):
    """Run RAAR for any two nearest point maps. Returns the list of iterates x_0 .. x_iters."""
    x = [list(row) for row in x0]  # @line L1
    path = [x]
    for _ in range(iters):  # @line L2
        x = raar_step(x, proj_s, proj_m, beta)
        path.append(x)
    return path


def raar(amp, support, x0, iters, beta=0.9, positive=False):
    """RAAR for phase retrieval. Returns (estimate, x) with estimate = P_M x."""
    proj_s = support_projection(support, positive)
    proj_m = lambda g: magnitude_projection(g, amp)  # noqa: E731
    x = raar_generic(proj_s, proj_m, x0, iters, beta)[-1]
    return proj_m(x), x  # @line L7


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_raar.py 112 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/raar/. The authors are listed in prov/MJJXEG.jsonl.

import random

from imgkit import dft2, idft2
from raar import distance, magnitude_projection, raar, raar_generic, raar_step, support_projection

OBJ = [[1, 2, 0, 1], [0, 3, 1, 0], [2, 1, 4, 1], [0, 1, 0, 2]]
SUPPORT = [[i < 4 and j < 4 for j in range(8)] for i in range(8)]


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)]
    amp = [[abs(v) for v in row] for row in dft2(f)]
    return f, twin, amp


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


def convex_problem(seed):
    """A = images on the support, B = images with known DFT values on a random half of the
    frequencies. Both are convex, and the true image f is in both."""
    rng = random.Random(seed)
    f = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) if SUPPORT[i][j] else 0j for j in range(8)]
         for i in range(8)]
    known = [[rng.random() < 0.5 for _ in range(8)] for _ in range(8)]
    ff = dft2(f)

    def proj_b(x):
        xf = dft2(x)
        for i in range(8):
            for j in range(8):
                if known[i][j]:
                    xf[i][j] = ff[i][j]
        return idft2(xf)

    return f, support_projection(SUPPORT), proj_b, rng


def real_inner(a, b):
    return sum((u.conjugate() * v).real for ra, rb in zip(a, b) for u, v in zip(ra, rb))


def test_beta_one_is_douglas_rachford() -> None:
    rng = random.Random(1)
    _, _, amp = page_problem()
    x = random_complex(rng)
    ps = support_projection(SUPPORT)
    pm = magnitude_projection(x, amp)
    dr = [[v + s - p for v, s, p in zip(rv, rs, rp)]
          for rv, rs, rp in zip(x, ps([[2 * p - v for p, v in zip(rp, rv)] for rp, rv in zip(pm, x)]), pm)]
    step = raar_step(x, ps, lambda g: magnitude_projection(g, amp), 1.0)
    assert distance(step, dr) < 1e-12


def test_pointwise_form_for_a_support() -> None:
    # Support only: V x = P_M x on the support and beta x + (1 - 2 beta) P_M x off it.
    rng = random.Random(2)
    _, _, amp = page_problem()
    x = random_complex(rng)
    pm = magnitude_projection(x, amp)
    for beta in (0.3, 0.75, 0.9):
        step = raar_step(x, support_projection(SUPPORT), lambda g: magnitude_projection(g, amp), beta)
        for i in range(8):
            for j in range(8):
                want = pm[i][j] if SUPPORT[i][j] else beta * x[i][j] + (1 - 2 * beta) * pm[i][j]
                assert abs(step[i][j] - want) < 1e-12


def test_firmly_nonexpansive_for_convex_sets() -> None:
    _, proj_a, proj_b, rng = convex_problem(3)
    for beta in (0.5, 0.9, 1.0):
        for _ in range(5):
            x, y = random_complex(rng), random_complex(rng)
            vx, vy = raar_step(x, proj_a, proj_b, beta), raar_step(y, proj_a, proj_b, beta)
            d = [[u - v for u, v in zip(ru, rv)] for ru, rv in zip(vx, vy)]
            e = [[u - v for u, v in zip(ru, rv)] for ru, rv in zip(x, y)]
            assert real_inner(d, d) <= real_inner(d, e) + 1e-9


def test_convex_case_is_fejer_monotone_and_converges() -> None:
    # The distance to the point f of the intersection never grows (Fejer monotone). Here the
    # intersection is the single point f (16 unknowns, about 32 equations), so the limit is f.
    f, proj_a, proj_b, rng = convex_problem(4)
    x0 = random_complex(rng)
    path = raar_generic(proj_a, proj_b, x0, 200, 0.8)
    dists = [distance(x, f) for x in path]
    for d0, d1 in zip(dists, dists[1:]):
        assert d1 <= d0 + 1e-10
    assert distance(proj_b(path[-1]), f) < 1e-9


def test_true_object_is_a_fixed_point() -> None:
    f, _, amp = page_problem()
    for beta in (0.5, 0.95):
        est, x = raar(amp, SUPPORT, f, 3, beta, positive=True)
        assert distance(x, f) < 1e-9
        assert distance(est, f) < 1e-9


def test_reconstruction_on_the_page_example() -> None:
    # Measurement, not a theorem: beta = 0.95, 250 steps, nonnegativity, three seeds.
    f, twin, 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, _ = raar(amp, SUPPORT, x0, 250, 0.95, positive=True)
        assert min(distance(est, f), distance(est, twin)) < 1e-6

History

The Douglas-Rachford method comes from the numerical solution of heat flow problems in the 1950s and was later studied as a splitting method for monotone operators. Bauschke, Combettes and Luke (2002) showed that Fienup's HIO with β=1\beta = 1 is the Douglas-Rachford method for phase retrieval. Luke (2005) proposed RAAR as a relaxation of this method. He studied the fixed points for convex sets, also for sets that do not meet, where the Douglas-Rachford method has no fixed points.

References

  1. D. Russell Luke, Relaxed averaged alternating reflections for diffraction imaging, Inverse Problems 21(1), 2005, 37 to 50, the definition of the RAAR map as a relaxation of the averaged alternating reflections, its pointwise form for a support constraint, and the analysis of its fixed points for convex sets (preprint arXiv math/0405208)
  2. 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, and the projection and reflection notation

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