Algorithm Search⌘K

Algorithmadvanced

Extended ptychographical iterative engine

Also called ePIE, ptychographical iterative engine.

Update the object and the probe estimates in turn from each diffraction pattern by replacing the modulus and taking a weighted gradient step.

Time
O(K J m^2 log m) worst
Space
O(n^2 + m^2) extra
Where
J = the number of scan positions; K = the number of sweeps; m = the side of the m x m probe window, a power of two; n = the side of the n x n object
Properties
randomizednot exactnot in placeoffline
Origin
Andrew M. Maiden, John M. Rodenburg, 2009

The extended ptychographical iterative engine (ePIE) is an iterative method for ptychography. It finds a complex object and the complex illumination (the probe) from many far-field diffraction patterns, each recorded with the probe at a different position on the object, where neighboring positions overlap. For each position in turn, it replaces the moduli of the predicted pattern by the measured ones and then moves the object and the probe a step toward the corrected exit wave. It is a local, pattern-by-pattern method for phase retrieval, and the overlap of the positions supplies the constraint that a single pattern does not.

In plain words

A small spot of coherent light lights up part of a sample, and a camera far away records how the light spreads. The camera keeps only the brightness, not the phase. The spot then moves a little, so that the new spot overlaps the old one, and the camera records again.

The method keeps a guess of the sample and a guess of the spot. For one pattern, it predicts what the camera should see, keeps the predicted phase, and puts in the measured brightness. That gives a better guess of the light just after the sample. The method then changes the sample guess where the spot is bright, and the spot guess where the sample lets light through. Then it goes to the next position, in a random order. Each part of the sample is seen several times, so the guesses must agree with many patterns at once.

The problem

The object OO is an n1×n2n_1 \times n_2 complex image, the probe PP an m1×m2m_1 \times m_2 complex image, and R1,…,RJR_1, \dots, R_J are the offsets of the probe window in the object. OjO_j is the window of OO at RjR_j, and the exit wave is the pixelwise product ψj=P⊙Oj\psi_j = P \odot O_j, the thin-object model. The far field is the 2D DFT FF, unnormalized as in this area. The data are the amplitudes

aj=∣F(P⊙Oj)∣,j=1,…,J,a_j = |F(P \odot O_j)|, \qquad j = 1, \dots, J,

the square roots of the measured intensities. The task is to find OO, and usually PP as well, from the aja_j and the offsets. The answer can only be unique up to the ambiguities of the model, such as (cO,P/c)(cO, P/c) for a complex constant cc (see Correctness).

The algorithm

The step sizes α\alpha and β\beta lie in (0,2](0, 2]; Maiden and Rodenburg used α=β=1\alpha = \beta = 1.

  1. EPIE(a_1..a_J, R_1..R_J, O, P, K, α, β)
  2. 1for sweep <- 1 .. K do
  3. 2draw a random order of the positions
  4. for each position j in that order do
  5. 3ψ <- P ⊙ O_j ▷ exit wave
  6. 4Ψ <- F ψ
  7. 5ψ' <- F^-1 ( a_j · Ψ / |Ψ| ) ▷ phase 0 where Ψ = 0
  8. 6Δ <- ψ' - ψ
  9. 7O_j <- O_j + α · conj(P) / max|P|^2 · Δ
  10. 8P <- P + β · conj(O_j,old) / max|O_j,old|^2 · Δ
  11. 9return O, P

Line L5 is the modulus replacement of the error-reduction algorithm, applied to one pattern. Line L7 changes only the pixels of the object under the window. Line L8 uses the window as it was before line L7. To recover the object with a known probe, skip line L8; that is close to the original PIE of Rodenburg and Faulkner (2004), which used a different weighting of the object update.

Example

One pixel of the object step. Take α=1\alpha = 1 and the residual Δ=ψ′−ψ\Delta = \psi' - \psi at two pixels of the window. At a pixel where ∣P∣2=max⁡∣P∣2|P|^2 = \max |P|^2, line L7 changes the exit wave by exactly Δ\Delta, so the new exit wave there equals ψ′\psi'. At a pixel where ∣P∣2=0.25max⁡∣P∣2|P|^2 = 0.25 \max |P|^2, the exit wave moves a quarter of the way, and the residual shrinks to 0.750.75 of its size. Where the probe is zero, the object does not change at all, which is right because the data say nothing about it there.

A small run (measurement). The test file builds a random 12×1212 \times 12 object with moduli in [0.6,1][0.6, 1] and phases in [−1.2,1.2][-1.2, 1.2], an 8×88 \times 8 Gaussian probe with a quadratic phase, and a 3×33 \times 3 grid of positions with a step of 2 pixels, so neighboring windows overlap by 75 percent along each axis. The probe is known, the start object is all ones, and the order uses the seed 2. The table gives the data error ∑j∥∣Fψj∣−aj∥2/∑j∥aj∥2\sum_j \||F\psi_j| - a_j\|^2 / \sum_j \|a_j\|^2 and the largest error of the object on the central 8×88 \times 8 pixels after the best global phase.

sweeps data error object error
0 4.26×10−14.26 \times 10^{-1}
1 6.22×10−26.22 \times 10^{-2} 0.784
5 1.83×10−21.83 \times 10^{-2} 0.472
10 1.04×10−21.04 \times 10^{-2} 0.383
20 2.78×10−32.78 \times 10^{-3} 0.266
40 1.03×10−31.03 \times 10^{-3} 0.139
60 5.57×10−45.57 \times 10^{-4} 0.087

The error falls fast in the first sweep and then slowly. When the probe is also unknown, the joint test on a 1D scan starts from the right probe modulus with no phase, and after 150 sweeps the data error is less than 1/50 of its value after the first sweep but does not reach zero, since the joint problem is harder.

Correctness

The proof shows what each step guarantees; there is no proof of global convergence, and the problem is not convex.

  • Line L5 is a projection (theorem). It returns the nearest exit wave whose far field has the measured moduli at position jj.
  • Line L7 is a gradient step that does not increase the residual (theorem). It is a step along the negative gradient of ∥P⊙Oj−ψ′∥2\|P \odot O_j - \psi'\|^2 with respect to the object. At each pixel the new residual is (1−α∣P∣2/max⁡∣P∣2)(1 - \alpha |P|^2/\max|P|^2) times the old one, a factor in [−1,1][-1, 1] for 0<α≤20 < \alpha \le 2. With a fixed probe, the data error at the current position therefore does not grow. Line L8 has the same property with the roles of object and probe exchanged.
  • A consistent pair is a fixed point (theorem). If an object and probe fit all the data, then ψ′=ψ\psi' = \psi at every step and nothing changes.
  • Ambiguities (theorem). The data do not change under (cO,P/c)(cO, P/c), under a linear phase ramp on the object with the opposite ramp on the probe, and under a global phase. No algorithm can resolve these from the data alone.
  • What is not proved. The total error can grow within a sweep, because a step at one position changes pixels that other positions share. The joint update of object and probe is not covered by the per-pixel bound. Convergence in practice is a measurement.
Proof: What each ePIE step guaranteespartial

ePIE has no proof of global convergence; the problem it solves is not convex. This page proves what holds for each step: the modulus replacement is a nearest-point projection, the object and probe updates are gradient steps that do not increase the residual at the current position, a pair that fits all the data is a fixed point, and the data cannot tell apart the pairs of a few known families.

Notation. The object OO is an n1×n2n_1 \times n_2 complex image and the probe PP an m1×m2m_1 \times m_2 complex image, with N=m1m2N = m_1 m_2 pixels. For a position jj, OjO_j is the window of OO under the probe, and ψj=P⊙Oj\psi_j = P \odot O_j is the exit wave, where ⊙\odot is the pixelwise product. FF is the unnormalized 2D DFT, so F/NF/\sqrt{N} is unitary and ∥Fx∥=N ∥x∥\|F x\| = \sqrt{N}\, \|x\|. The data are the amplitudes aj≥0a_j \ge 0. The modulus set of position jj is

Mj={ψ:∣Fψ∣=aj entry by entry}.M_j = \{\psi : |F\psi| = a_j \text{ entry by entry}\}.

For a complex image xx let πj(x)\pi_j(x) be the output of lines L4 and L5: πj(x)=F−1Rj(Fx)\pi_j(x) = F^{-1} R_j(F x), where Rj(Y)R_j(Y) is ajY/∣Y∣a_j Y/|Y| at entries with Y≠0Y \ne 0 and aja_j at entries with Y=0Y = 0.

Lemma 1 (modulus replacement is a projection). For every xx, πj(x)∈Mj\pi_j(x) \in M_j and ∥x−πj(x)∥=min⁡ψ∈Mj∥x−ψ∥\|x - \pi_j(x)\| = \min_{\psi \in M_j} \|x - \psi\|.

Proof. Put Y=FxY = F x. For one entry, a complex number zz with ∣z∣=a|z| = a obeys ∣Y−z∣≥∣∣Y∣−a∣|Y - z| \ge \big||Y| - a\big| by the triangle inequality, with equality at z=aY/∣Y∣z = a Y/|Y| if Y≠0Y \ne 0 and at every such zz if Y=0Y = 0. So Rj(Y)R_j(Y) is a nearest point to YY in the set {Z:∣Z∣=aj}\{Z : |Z| = a_j\}, entry by entry, hence in the product set. Since ∥Fx−Fψ∥=N∥x−ψ∥\|F x - F\psi\| = \sqrt{N} \|x - \psi\|, a nearest point to YY among the FψF\psi with ψ∈Mj\psi \in M_j gives a nearest point to xx in MjM_j. □\square

The set MjM_j is not convex, and the nearest point is not unique where YY has a zero entry with aj>0a_j > 0. Lemma 1 also gives the identity ∥∣Fx∣−aj∥=N ∥x−πj(x)∥\big\| |F x| - a_j \big\| = \sqrt{N}\, \|x - \pi_j(x)\|, so the data error at one position is a distance to MjM_j.

Lemma 2 (the object step). Fix the probe and a position jj. Let ψ=P⊙Oj\psi = P \odot O_j and ψ′=πj(ψ)\psi' = \pi_j(\psi) (lines L3 to L5), and let p=max⁡∣P∣2>0p = \max |P|^2 > 0. Line L7 sets

Ojnew=Oj+αp P‾⊙(ψ′−ψ).O_j^{\text{new}} = O_j + \frac{\alpha}{p}\, \overline{P} \odot (\psi' - \psi).

(a) This is a step of size α/p\alpha/p along the negative gradient, in the Wirtinger sense, of f(Oj)=∥P⊙Oj−ψ′∥2f(O_j) = \|P \odot O_j - \psi'\|^2 with respect to Oj‾\overline{O_j}, with ψ′\psi' held fixed.

(b) At each pixel, P Ojnew−ψ′=(1−α∣P∣2/p)(ψ−ψ′)P\, O_j^{\text{new}} - \psi' = \big(1 - \alpha |P|^2/p\big)(\psi - \psi').

(c) For 0<α≤20 < \alpha \le 2, the factor in (b) lies in [−1,1][-1, 1], so ∣P Ojnew−ψ′∣≤∣ψ−ψ′∣|P\, O_j^{\text{new}} - \psi'| \le |\psi - \psi'| at every pixel.

Proof. (a) f=∑∣PO−ψ′∣2f = \sum |P O - \psi'|^2 over the pixels, and ∂f/∂O‾=P‾(PO−ψ′)=−P‾(ψ′−ψ)\partial f/\partial \overline{O} = \overline{P}(P O - \psi') = -\overline{P}(\psi' - \psi) at each pixel. (b) Multiply the update by PP and subtract ψ′\psi': POj+(α/p)∣P∣2(ψ′−ψ)−ψ′=(1−α∣P∣2/p)(ψ−ψ′)P O_j + (\alpha/p)|P|^2 (\psi' - \psi) - \psi' = (1 - \alpha |P|^2/p)(\psi - \psi'). (c) 0≤∣P∣2/p≤10 \le |P|^2/p \le 1, so the factor lies in [1−α,1]⊂[−1,1][1 - \alpha, 1] \subset [-1, 1]. □\square

The division by the maximum of ∣P∣2|P|^2, not by ∣P∣2|P|^2 at each pixel, is what keeps the step stable: where the probe is weak, the factor is close to 11 and the object barely changes, so noise in dark parts of the probe is not amplified.

Corollary 1 (the data error at the current position does not grow). With a fixed probe and 0<α≤20 < \alpha \le 2, the object step does not increase the distance of the exit wave at position jj to MjM_j:

dist⁡(P⊙Ojnew,Mj)≤∥P⊙Ojnew−ψ′∥≤∥ψ−ψ′∥=dist⁡(ψ,Mj).\operatorname{dist}(P \odot O_j^{\text{new}}, M_j) \le \|P \odot O_j^{\text{new}} - \psi'\| \le \|\psi - \psi'\| = \operatorname{dist}(\psi, M_j).

Proof. The first inequality holds because ψ′∈Mj\psi' \in M_j. The second is Lemma 2(c) summed over the pixels. The equality is Lemma 1. □\square

By the identity after Lemma 1, the data error ∥∣F(P⊙Oj)∣−aj∥\big\||F(P \odot O_j)| - a_j\big\| at position jj does not grow either. The step changes the pixels that position jj shares with other positions, so the total error over all positions can grow in one step. This is why the corollary is not a convergence proof.

Lemma 3 (the probe step). Fix the object and let o=max⁡∣Oj∣2>0o = \max |O_j|^2 > 0. Line L8 sets Pnew=P+(β/o) Oj‾⊙(ψ′−ψ)P^{\text{new}} = P + (\beta/o)\, \overline{O_j} \odot (\psi' - \psi). With OjO_j fixed, the statements of Lemma 2 and Corollary 1 hold with the roles of PP and OjO_j exchanged and α\alpha replaced by β\beta.

Proof. The exit wave P⊙OjP \odot O_j is symmetric in PP and OjO_j, and the proofs use nothing else. □\square

ePIE applies both steps from the same old pair (the code computes the probe step from the old window OjO_j). The new exit wave is then

PnewOjnew−ψ′=(1−α∣P∣2p−β∣Oj∣2o)(ψ−ψ′)+αβp o P‾ Oj‾ (ψ′−ψ)2,P^{\text{new}} O_j^{\text{new}} - \psi' = \Big(1 - \frac{\alpha |P|^2}{p} - \frac{\beta |O_j|^2}{o}\Big)(\psi - \psi') + \frac{\alpha\beta}{p\, o}\, \overline{P}\, \overline{O_j}\, (\psi' - \psi)^2,

which follows by multiplying out the two updates. The first factor can leave [−1,1][-1, 1] for α=β=1\alpha = \beta = 1, and the second term is of second order in the residual. So the joint step is not covered by Lemma 2, and no monotone decrease is claimed for it. For small residuals the joint step behaves like a gradient step on both factors, which is a heuristic, not a theorem.

Lemma 4 (fixed points). If a pair (O,P)(O, P) fits all the data, that is ∣F(P⊙Oj)∣=aj|F(P \odot O_j)| = a_j for every jj, then ePIE started at (O,P)(O, P) returns (O,P)(O, P) unchanged, for every order of the positions and all α\alpha and β\beta.

Proof. At each step ψ∈Mj\psi \in M_j. Where Fψ≠0F\psi \ne 0, RjR_j returns ajFψ/∣Fψ∣=Fψa_j F\psi/|F\psi| = F\psi; where Fψ=0F\psi = 0, aj=0a_j = 0 and RjR_j returns 00. So ψ′=ψ\psi' = \psi, line L6 gives ψ′−ψ=0\psi' - \psi = 0, and lines L7 and L8 change nothing. By induction over the steps, the pair never changes. □\square

Lemma 5 (ambiguities). The data error is the same for (O,P)(O, P) and for each of these pairs:

  1. (c O,P/c)(c\, O, P/c) for a complex c≠0c \ne 0, which includes a global phase factor c=eiθc = e^{i\theta} on the object alone with e−iθe^{-i\theta} on the probe, and a global phase of both;
  2. (Oeik⋅r,Pe−ik⋅r)(O e^{i k \cdot r}, P e^{-i k \cdot r}) for a real vector kk, where rr is the pixel position in the object and in the probe frame;
  3. (eiθO,P)(e^{i\theta} O, P) and (O,eiθP)(O, e^{i\theta} P) for real θ\theta.

Proof. In case 1 the exit wave does not change. In case 2 the exit wave at the window offset RjR_j is P(r′)O(Rj+r′)eik⋅RjP(r') O(R_j + r') e^{i k \cdot R_j}, the old exit wave times a constant of modulus 1, and ∣F∣|F| ignores a constant phase factor. Case 3 is a constant phase factor on every exit wave. □\square

So ePIE can at best recover the object up to these changes. With a known, fixed probe, cases 1 and 2 cannot occur, and the global phase of case 3 remains. Whether the data fix the object up to that phase alone is a question of uniqueness, which depends on the overlap of the windows; this proof does not cover it.

What is not proved. There is no proof that ePIE converges to a pair that fits the data, or to the true pair up to Lemma 5, from a general start. The tests on the page are measurements on small synthetic cases. The analysis of ePIE and related methods as stochastic or alternating minimization schemes is the subject of later work and is outside this proof.

Complexity

In the real RAM model with the fast Fourier transform, each position costs two DFTs of size m×mm \times m, O(m2log⁡m)O(m^2 \log m), plus O(m2)O(m^2) for the products and the updates. One sweep over JJ positions costs O(Jm2log⁡m)O(J m^2 \log m), and KK sweeps cost O(KJm2log⁡m)O(K J m^2 \log m). The method stores the object, O(n2)O(n^2), and the probe and a few work arrays of size m2m^2. The number of sweeps that a reconstruction needs depends on the data, the overlap and the noise, and has no general bound.

Properties

  • Sequential. Each position updates the estimates before the next one is used, like stochastic gradient descent over the positions. The random order breaks the drift that a fixed order can cause.
  • Local. Each update touches only the m×mm \times m window, so memory per step is small and very large objects are possible.
  • Stable in weak light. The step is divided by the maximum of ∣P∣2|P|^2, not by ∣P∣2|P|^2 at each pixel, so the update is small where the probe is weak and noise there is not amplified.
  • Not deterministic as stated. The order of the positions is random. A fixed seed makes a run repeatable.

Variants and improvements

  • PIE (Rodenburg and Faulkner 2004). The same scheme with a known probe and a different weighting of the object update.
  • Difference map for ptychography (Thibault et al. 2008). Updates all positions at once with the difference map, and refines object and probe together. It is less prone to stagnation and maps well to parallel hardware, at the cost of memory for all exit waves.
  • rPIE and mPIE (Maiden, Johnson and Li 2017). rPIE blends the per-pixel weight ∣P∣2|P|^2 with its maximum to give a regularized step. mPIE adds momentum over the sweeps.
  • Position correction. The scan positions are often not known exactly. Extensions refine them during the reconstruction.
  • Mixed states and multislice. Partial coherence is modeled with several probe modes, and thick objects with several slices separated by angular spectrum propagation.
  • Maximum likelihood. For low counts, a Poisson model of the noise replaces the modulus replacement by a gradient of the likelihood.
  • Fourier ptychography. The same update structure, with the roles of real space and Fourier space exchanged, gives the usual solver for Fourier ptychography.

When to use it

Use ePIE for scanning ptychography with X-rays, electrons or visible light, when the probe is not known well and the data set is large. It is simple, needs only two FFTs per position and little memory, and recovers the probe as a by-product. For data with strong noise, a model with a known probe error or a need for parallel speed, a difference map or a likelihood method may be better. For a single diffraction pattern with a support constraint, use the methods of coherent diffraction imaging such as hybrid input-output.

Pitfalls

  • Too little overlap. With little overlap the patterns do not constrain each other, and the reconstruction fails. Experimental studies suggest an overlap of the probe area of about 60 percent or more; this is a guideline from measurements, not a theorem.
  • Raster grid pathology. On a perfectly regular grid of positions, joint recovery of object and probe can produce a periodic artifact with the period of the grid. Thibault et al. (2009) describe this; a small random offset of the positions avoids it.
  • Scale and ramp ambiguities. The returned object can carry a constant factor and a linear phase ramp that belong to the probe. Normalize the object, for example to a known empty region, before comparing results.
  • Wrong amplitudes. The data are the square roots of the intensities. Using the intensities directly makes the modulus replacement wrong.
  • Too large steps. Values of α\alpha above 2 make the residual grow at the bright pixels of the probe.
  • The thin-object model. The product P⊙OjP \odot O_j assumes that the object is thin compared with the depth of field. Thick objects need a multislice model.

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.

epie.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epie/. The authors are listed in prov/RV95GV.jsonl.

"""The extended ptychographical iterative engine (ePIE) of Maiden and Rodenburg.

Conventions:
- The object O is an n1 x n2 complex image and the probe P an m1 x m2
  complex image. Position j is the offset (r, c) of the probe window in the
  object, with r + m1 <= n1 and c + m2 <= n2. O_j is the m1 x m2 patch
  O[r + a][c + b].
- The exit wave at position j is psi_j = P * O_j (pixelwise). The far field
  is its unnormalized 2D DFT (imgkit), and the data are the amplitudes
  a_j = |DFT2(psi_j)|, the square roots of the measured intensities.
- One sweep visits every position once, in a random order drawn from
  random.Random(seed).

Cost per sweep: J positions, each with two m1 x m2 DFTs and O(m1 m2) other
work, so O(J m^2 log m) for m x m probes of power-of-two size.
"""

import random

from imgkit import dft2, idft2


def patch(obj, pos, m1, m2):
    """The m1 x m2 patch of obj at the offset pos = (r, c)."""
    r, c = pos
    return [row[c:c + m2] for row in obj[r:r + m1]]


def exit_wave(obj, probe, pos):
    """psi = P * O_j, pixelwise."""
    m1, m2 = len(probe), len(probe[0])
    o = patch(obj, pos, m1, m2)
    return [[p * v for p, v in zip(rp, ro)] for rp, ro in zip(probe, o)]


def forward_amplitudes(obj, probe, positions):
    """The noiseless data a_j = |DFT2(P * O_j)| for every position."""
    return [[[abs(v) for v in row] for row in dft2(exit_wave(obj, probe, pos))] for pos in positions]


def modulus_replace(spec, amp):
    """The nearest point to spec with modulus amp, entry by entry.

    An entry with spec = 0 has no phase; it gets the phase 0, which is one of
    the nearest points.
    """
    out = []
    for rs, ra in zip(spec, amp):
        row = []
        for s, a in zip(rs, ra):
            m = abs(s)
            row.append(a * s / m if m > 0.0 else complex(a))
        out.append(row)
    return out


def data_error(amps, positions, obj, probe):
    """sum_j || |DFT2(P * O_j)| - a_j ||^2 / sum_j ||a_j||^2."""
    num = den = 0.0
    for a, pos in zip(amps, positions):
        spec = dft2(exit_wave(obj, probe, pos))
        for rs, ra in zip(spec, a):
            for s, v in zip(rs, ra):
                num += (abs(s) - v) ** 2
                den += v * v
    return num / den


def epie(amps, positions, obj, probe, sweeps, alpha=1.0, beta=1.0, seed=0, update_probe=True):
    """Run ePIE and return the object and probe estimates.

    amps[j] holds the measured amplitudes for positions[j]. obj and probe are
    the start guesses; they are copied, not changed. With update_probe=False
    the probe stays fixed, which gives the PIE-like object-only update.
    """
    obj = [list(row) for row in obj]
    probe = [list(row) for row in probe]
    m1, m2 = len(probe), len(probe[0])
    rng = random.Random(seed)
    order = list(range(len(positions)))
    for _ in range(sweeps):  # @line L1
        rng.shuffle(order)  # @line L2
        for j in order:
            r, c = positions[j]
            o = patch(obj, (r, c), m1, m2)
            psi = [[p * v for p, v in zip(rp, ro)] for rp, ro in zip(probe, o)]  # @line L3
            spec = dft2(psi)  # @line L4
            psi2 = idft2(modulus_replace(spec, amps[j]))  # @line L5
            diff = [[x - y for x, y in zip(r2, r1)] for r2, r1 in zip(psi2, psi)]  # @line L6
            pmax = max(abs(p) ** 2 for row in probe for p in row)
            omax = max(abs(v) ** 2 for row in o for v in row)
            for a in range(m1):  # @line L7
                for b in range(m2):
                    obj[r + a][c + b] = o[a][b] + alpha * probe[a][b].conjugate() / pmax * diff[a][b]
            if update_probe and omax > 0.0:  # @line L8
                probe = [
                    [probe[a][b] + beta * o[a][b].conjugate() / omax * diff[a][b] for b in range(m2)]
                    for a in range(m1)
                ]
    return obj, probe  # @line L9
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_epie.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/epie/. The authors are listed in prov/RV95GV.jsonl.

import cmath
import math
import random

from epie import data_error, epie, exit_wave, forward_amplitudes, modulus_replace, patch
from imgkit import dft2, idft2


def rand_obj(rng, n1, n2):
    return [[rng.uniform(0.6, 1.0) * cmath.exp(1j * rng.uniform(-1.2, 1.2)) for _ in range(n2)] for _ in range(n1)]


def gauss_probe(m1, m2):
    ca, cb = (m1 - 1) / 2, (m2 - 1) / 2
    return [
        [math.exp(-((a - ca) ** 2 + (b - cb) ** 2) / 8.0) * cmath.exp(0.3j * ((a - ca) ** 2 + (b - cb) ** 2)) for b in range(m2)]
        for a in range(m1)
    ]


def max_diff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def aligned_error(est, true, rows, cols):
    """Max error of est against true on a region, after the best global phase."""
    num = sum(est[i][j].conjugate() * true[i][j] for i in rows for j in cols)
    g = num / abs(num)
    return max(abs(est[i][j] * g - true[i][j]) for i in rows for j in cols)


def test_forward_matches_direct_dft():
    rng = random.Random(1)
    obj, probe = rand_obj(rng, 6, 7), gauss_probe(3, 4)
    pos = (2, 1)
    amps = forward_amplitudes(obj, probe, [pos])[0]
    for k in range(3):
        for l in range(4):
            s = sum(
                probe[a][b] * obj[2 + a][1 + b] * cmath.exp(-2j * math.pi * (a * k / 3 + b * l / 4))
                for a in range(3)
                for b in range(4)
            )
            assert abs(abs(s) - amps[k][l]) < 1e-12


def test_modulus_replacement_is_nearest_point():
    rng = random.Random(2)
    spec = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(4)] for _ in range(4)]
    amp = [[rng.uniform(0, 2) for _ in range(4)] for _ in range(4)]
    best = modulus_replace(spec, amp)
    for i in range(4):
        for j in range(4):
            assert abs(abs(best[i][j]) - amp[i][j]) < 1e-12
            d = abs(best[i][j] - spec[i][j])
            assert abs(d - abs(abs(spec[i][j]) - amp[i][j])) < 1e-12
            for _ in range(20):
                z = amp[i][j] * cmath.exp(1j * rng.uniform(-math.pi, math.pi))
                assert d <= abs(z - spec[i][j]) + 1e-12
    assert modulus_replace([[0j]], [[1.5]]) == [[1.5 + 0j]]


def test_true_pair_is_fixed_point():
    rng = random.Random(3)
    obj, probe = rand_obj(rng, 8, 8), gauss_probe(4, 4)
    pos = [(r, c) for r in (0, 2, 4) for c in (0, 2, 4)]
    amps = forward_amplitudes(obj, probe, pos)
    o, p = epie(amps, pos, obj, probe, 3)
    assert max_diff(o, obj) < 1e-12
    assert max_diff(p, probe) < 1e-12
    assert data_error(amps, pos, o, p) < 1e-24


def test_one_step_matches_the_update_formulas():
    rng = random.Random(4)
    obj, probe = rand_obj(rng, 4, 8), gauss_probe(4, 4)
    pos = [(0, 3)]
    amps = [[[rng.uniform(0.2, 3.0) for _ in range(4)] for _ in range(4)]]
    psi = exit_wave(obj, probe, pos[0])
    psi2 = idft2(modulus_replace(dft2(psi), amps[0]))
    o_old = patch(obj, pos[0], 4, 4)
    pmax = max(abs(v) ** 2 for row in probe for v in row)
    omax = max(abs(v) ** 2 for row in o_old for v in row)
    for alpha, beta in ((1.0, 1.0), (0.5, 0.2), (2.0, 1.0)):
        o, p = epie(amps, pos, obj, probe, 1, alpha=alpha, beta=beta)
        for a in range(4):
            for b in range(4):
                d = psi2[a][b] - psi[a][b]
                want_o = o_old[a][b] + alpha * probe[a][b].conjugate() / pmax * d
                want_p = probe[a][b] + beta * o_old[a][b].conjugate() / omax * d
                assert abs(o[a][3 + b] - want_o) < 1e-12
                assert abs(p[a][b] - want_p) < 1e-12
        # Pixels outside the window do not change.
        assert all(o[a][b] == obj[a][b] for a in range(4) for b in range(3))
        assert all(o[a][7] == obj[a][7] for a in range(4))


def test_object_step_shrinks_the_residual_per_pixel():
    rng = random.Random(5)
    obj, probe = rand_obj(rng, 4, 4), gauss_probe(4, 4)
    pos = [(0, 0)]
    amps = [[[rng.uniform(0.2, 3.0) for _ in range(4)] for _ in range(4)]]
    psi = exit_wave(obj, probe, pos[0])
    psi2 = idft2(modulus_replace(dft2(psi), amps[0]))
    pmax = max(abs(v) ** 2 for row in probe for v in row)
    for alpha in (0.1, 0.7, 1.0, 1.5, 2.0):
        o, _ = epie(amps, pos, obj, probe, 1, alpha=alpha, update_probe=False)
        new = exit_wave(o, probe, pos[0])
        for a in range(4):
            for b in range(4):
                before = abs(psi[a][b] - psi2[a][b])
                after = abs(new[a][b] - psi2[a][b])
                factor = abs(1 - alpha * abs(probe[a][b]) ** 2 / pmax)
                assert abs(after - factor * before) < 1e-12
                assert after <= before + 1e-12


def test_ambiguities_leave_the_data_unchanged():
    rng = random.Random(6)
    obj, probe = rand_obj(rng, 8, 10), gauss_probe(4, 4)
    pos = [(r, c) for r in (0, 2, 4) for c in (0, 3, 6)]
    amps = forward_amplitudes(obj, probe, pos)
    c = 1.7 * cmath.exp(0.4j)
    o2 = [[c * v for v in row] for row in obj]
    p2 = [[v / c for v in row] for row in probe]
    assert data_error(amps, pos, o2, p2) < 1e-24
    # A phase ramp on the object and the opposite ramp on the probe.
    kx, ky = 0.37, -0.21
    o3 = [[v * cmath.exp(1j * (kx * j + ky * i)) for j, v in enumerate(row)] for i, row in enumerate(obj)]
    p3 = [[v * cmath.exp(-1j * (kx * b + ky * a)) for b, v in enumerate(row)] for a, row in enumerate(probe)]
    assert data_error(amps, pos, o3, p3) < 1e-24


def test_known_probe_recovers_the_object():
    rng = random.Random(1)
    obj, probe = rand_obj(rng, 12, 12), gauss_probe(8, 8)
    pos = [(r, c) for r in (0, 2, 4) for c in (0, 2, 4)]
    amps = forward_amplitudes(obj, probe, pos)
    start = [[1 + 0j] * 12 for _ in range(12)]
    o1, _ = epie(amps, pos, start, probe, 1, update_probe=False, seed=2)
    o, _ = epie(amps, pos, start, probe, 60, update_probe=False, seed=2)
    assert data_error(amps, pos, o, probe) < 1e-3 < data_error(amps, pos, o1, probe)
    inner = range(2, 10)
    assert aligned_error(o, obj, inner, inner) < 0.15 < aligned_error(o1, obj, inner, inner)


def test_joint_recovery_lowers_the_data_error():
    rng = random.Random(1)
    obj, probe = rand_obj(rng, 1, 40), gauss_probe(1, 8)
    pos = [(0, c) for c in range(33)]
    amps = forward_amplitudes(obj, probe, pos)
    start = [[1 + 0j] * 40]
    guess = [[abs(v) for v in probe[0]]]  # the right modulus, no phase
    o1, p1 = epie(amps, pos, start, guess, 1, seed=2)
    o, p = epie(amps, pos, start, guess, 150, seed=2)
    e1, e = data_error(amps, pos, o1, p1), data_error(amps, pos, o, p)
    assert e < 0.02 * e1
    assert e < 1e-2


def test_same_seed_same_result():
    rng = random.Random(7)
    obj, probe = rand_obj(rng, 1, 16), gauss_probe(1, 4)
    pos = [(0, c) for c in range(0, 13, 2)]
    amps = forward_amplitudes(obj, probe, pos)
    start = [[1 + 0j] * 16]
    a = epie(amps, pos, start, probe, 5, seed=11)
    b = epie(amps, pos, start, probe, 5, seed=11)
    assert a == b

History

Hoppe (1969) proposed to find the phases of electron diffraction from patterns recorded with an inhomogeneous illumination, the idea that was later called ptychography. Rodenburg and Faulkner (2004) gave the ptychographical iterative engine (PIE), which updates the object from each pattern in turn with a known probe. Thibault and coworkers (2008) reconstructed both the object and the probe with the difference map. Maiden and Rodenburg (2009) added a probe update to PIE, which gave ePIE, and visited the positions in random order. Maiden, Johnson and Li (2017) later proposed the rPIE and mPIE variants.

References

  1. Andrew M. Maiden and John M. Rodenburg, An improved ptychographical phase retrieval algorithm for diffractive imaging, Ultramicroscopy 109(10), 2009, 1256 to 1262, the ePIE object and probe update functions and the random order of the positions (general locator)
  2. J. M. Rodenburg and H. M. L. Faulkner, A phase retrieval algorithm for shifting illumination, Applied Physics Letters 85(20), 2004, 4795 to 4797, the PIE object update with a known probe (general locator)
  3. Pierre Thibault, Martin Dierolf, Andreas Menzel, Oliver Bunk, Christian David and Franz Pfeiffer, High-resolution scanning X-ray diffraction microscopy, Science 321(5887), 2008, 379 to 382, the joint reconstruction of object and probe with the difference map (general locator)
  4. Pierre Thibault, Martin Dierolf, Oliver Bunk, Andreas Menzel and Franz Pfeiffer, Probe retrieval in ptychographic coherent diffractive imaging, Ultramicroscopy 109(4), 2009, 338 to 343, probe retrieval and the artifacts of scans on a regular grid (general locator)
  5. W. Hoppe, Beugung im inhomogenen Primarstrahlwellenfeld. I. Prinzip einer Phasenmessung von Elektronenbeugungsinterferenzen, Acta Crystallographica A 25(4), 1969, 495 to 501, the principle of phase measurement with an inhomogeneous illumination (general locator)
  6. Andrew Maiden, Daniel Johnson and Peng Li, Further improvements to the ptychographical iterative engine, Optica 4(7), 2017, 736, the regularized rPIE update and the momentum variant mPIE (general locator)

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 correctness
  • 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