Algorithm Search⌘K

Techniqueadvanced

Transport of intensity equation

Also called TIE phase retrieval.

Recover phase from the derivative of intensity along the optical axis by solving the Poisson-type equation that links the two.

The transport of intensity equation (TIE) links the change of the intensity of a paraxial beam along the optical axis to the phase in a plane across the beam. If you record two or three images at small known distances around focus, the difference of the images gives the derivative of the intensity, and the phase follows from a Poisson equation. The method is a non-iterative solution of phase retrieval from intensities in several planes. It needs no reference wave, no iteration and only a standard microscope with a focus drive, and it also works with partially coherent light. It is used in optical microscopy, electron microscopy and X-ray imaging.

In plain words

Light that passes through a clear object, such as a living cell, is bent a little but hardly dimmed. In focus the cell is almost invisible, because a camera sees only brightness. Move the camera a short distance and the bent light starts to collect in some places and spread out in others. A part of the cell that acts like a weak lens makes a bright spot on one side of focus and a dark spot on the other.

So you take one image a little before focus and one a little after. Their difference shows where the light is gathering and where it is leaving. From this pattern you can work back to the shape of the delay that the object put on the light, which is the phase. The work back is a standard equation that a computer solves quickly.

When it applies

  • A paraxial beam. The light travels mostly along one axis, and the field changes slowly across the beam on the scale of the wavelength. Under the paraxial wave equation the intensity II and the phase ϕ\phi in a plane obey
−k∂I∂z=∇⋅(I∇ϕ),k=2πλ,-k \frac{\partial I}{\partial z} = \nabla \cdot (I \nabla \phi), \qquad k = \frac{2\pi}{\lambda},

where ∇\nabla acts across the beam (a theorem; the proof derives it).

  • Images at known defocus. You can record the intensity in two or three planes at known distances ±Δz\pm\Delta z around the plane of interest, with the same alignment and magnification.
  • A positive intensity in the field of view, because the method divides by II. Dark regions, such as opaque parts of the object or zeros of a speckle field, break it.
  • A smooth phase. The equation holds for the phase without the wrapping into (−π,π](-\pi, \pi], and the result is the continuous phase. Phase jumps and vortices, which carry a phase singularity at a zero of the intensity, are outside its scope.
  • Partial coherence. Paganin and Nugent's analysis shows that the equation keeps a meaning for partially coherent light, where the phase is replaced by a quantity defined through the energy flux.

The template

Teague (1983) wrote the flux I∇ϕI \nabla\phi as the gradient of an auxiliary function ψ\psi. Then the equation splits into two Poisson equations:

∇2ψ=−k∂I∂z,∇2ϕ=∇⋅(∇ψI).\nabla^2 \psi = -k \frac{\partial I}{\partial z}, \qquad \nabla^2 \phi = \nabla \cdot \Big(\frac{\nabla\psi}{I}\Big).

On a periodic grid each Poisson equation is solved with one forward and one inverse FFT: divide the coefficient at frequency f≠0f \ne 0 by −4π2∣f∣2-4\pi^2|f|^2 and set the mean to zero. This is the approach of Paganin and Nugent (1998).

  1. TIE-PHASE(I_-, I_0, I_+, Δz, λ)
  2. 1D ← (I_+ - I_-) / (2 Δz) ▷ central difference for dI/dz
  3. 2ψ ← SOLVE-POISSON(-k D) ▷ FFT, divide by -4π²|f|², mean 0
  4. 3g ← ∇ψ ▷ spectral gradient
  5. 4g ← g / I_0 ▷ point by point
  6. 5return SOLVE-POISSON(∇ · g) ▷ φ up to a constant

Each step costs a fixed number of FFTs, so a phase image of n×nn \times n pixels costs O(n2log⁡n)O(n^2 \log n) (with nn a power of two). For a uniform intensity I0I_0 the lines collapse to one solve, ∇2ϕ=−(k/I0) ∂zI\nabla^2\phi = -(k/I_0)\, \partial_z I.

The method returns ϕ\phi up to a constant when the flux I∇ϕI\nabla\phi is a gradient, which always holds for a uniform intensity (a theorem, in the proof). If II varies, the flux can have a part without divergence, which the data do not see and the method sets to zero.

Classic examples

  • A pure phase object. The test file builds a 32×3232 \times 32 grid with pixel size 1 and wavelength 0.50.5 in the same length unit, a uniform amplitude and a phase made of four Gaussian bumps of width 3 pixels and up to 1 radian. The defocused images come from exact angular spectrum propagation. The relative error of the recovered phase, after the means are removed, is as follows (measurement). The noisy column adds Gaussian noise with standard deviation 10−310^{-3} of the mean intensity to each image.
Δz\Delta z 1 4 16 32 64
no noise 3e-4 2e-4 4.6e-3 0.019 0.068
noise 10−310^{-3} 0.087 0.022 0.0073 0.019 0.068

Without noise the error grows with the step, because the central difference has an error of order Δz2\Delta z^2. With noise the error falls as the step grows at first, because the noise in DD is divided by Δz\Delta z, and the best step here is near 16.

  • An absorbing object. The same phase with an amplitude that varies by up to about 30 percent. With Δz=4\Delta z = 4, the full two-step method gives a relative error of 0.0094, and the one-step formula for a uniform intensity, with the mean intensity in place of I0I_0, gives 0.113 (measurement). The remaining error of the full method is the part of the flux that is not a gradient.
  • Bright field microscopy of cells. A focus series of an unstained cell gives a quantitative phase map, that is, the optical thickness, without a special phase contrast optic.
  • X-ray and electron imaging. Propagation-based phase contrast with X-rays and the focus series of transmission electron microscopes use the same equation. For a homogeneous object of one material, Paganin and coworkers (2002) found the phase and the amplitude from a single defocused image.

Variations

  • Higher order differences. More planes, used in a higher order finite difference or a fit along zz, reduce the bias of order Δz2\Delta z^2 and average the noise.
  • Other solvers. The Poisson equations can also be solved with finite differences, multigrid or spectral methods with other boundary conditions, for example with a mirror extension of the images, which avoids the jumps that periodic wrapping causes at the image edge.
  • Regularized inversion. Adding a small constant to 4π2∣f∣24\pi^2|f|^2 in the denominator damps the noise at the lowest frequencies, at the cost of a bias in the slow parts of the phase. This is a heuristic trade, and it helps only when the phase has little content at the lowest frequencies.
  • One image of a homogeneous object. If the ratio of phase shift to absorption of the material is known, one defocused image is enough (Paganin and coworkers 2002).
  • Iterative refinement. The TIE phase is a good start for an iterative method such as Gerchberg-Saxton on the same focus series, which can then fit the data at larger defocus where the equation is no longer accurate.

Pitfalls

  • The wrong step. A small Δz\Delta z amplifies the noise, and a large one adds bias and breaks the linear model. Measure the noise and try several steps.
  • Low frequency noise. The inverse Laplacian multiplies the noise at frequency ff by 1/∣f∣21/|f|^2. The result often shows slow, cloudy errors in the phase even when the images look clean.
  • Edges of the field. The FFT solver assumes that the images repeat periodically. Light that enters or leaves the field of view between the planes, or a phase that does not match at opposite edges, adds errors near the border.
  • Zeros of the intensity. Division by II fails where the intensity is near zero. Use a small floor or exclude these regions, and do not expect correct phase there.
  • Uniform-intensity formula on an absorbing object. The one-step formula is exact only for a uniform intensity. In the test above it gave an error ten times larger than the full method.
  • Misalignment between planes. A lateral shift or a change of magnification between the images looks like a phase gradient. Register the images first.
  • Missing flux part. If the flux has a part without divergence, no TIE solver can see it. This matters for objects with strong absorption next to strong phase gradients.

Code

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
transport_of_intensity_equation.py 88 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transport-of-intensity-equation/. The authors are listed in prov/5EFCMW.jsonl.

"""Phase from a defocus series with the transport of intensity equation (TIE).

Conventions:
- Images are n1 x n2 lists of rows on a periodic grid with spacing d,
  pixel (i, j) at y = i d and x = j d. The DFT is unnormalized forward with
  exp(-2 pi i j k / n) (imgkit); index k stands for k if 2 k < n, else k - n.
- Time dependence exp(-i omega t), so the paraxial field is
  U = sqrt(I) exp(i phi) exp(i k z) and the TIE reads
  div(I grad phi) = -k dI/dz with k = 2 pi / wavelength.
- The phase is found up to an additive constant; the result has mean 0.

Method (Teague 1983): write I grad phi = grad psi. Then lap psi = -k dI/dz,
and lap phi = div(grad psi / I). Both Poisson equations are solved with the
FFT. The intensity derivative comes from a central difference of two images
at -dz and +dz.

Cost: a fixed number of 2D DFTs, O(n^2 log n) for n x n images with n a
power of two.
"""

import math

from imgkit import dft2, idft2


def _freqs(n, d):
    return [(k if 2 * k < n else k - n) / (n * d) for k in range(n)]


def inverse_laplacian(rhs, d):
    """The mean-zero periodic solution u of lap u = rhs - mean(rhs).

    In Fourier space, U(f) = -RHS(f) / (4 pi^2 |f|^2), and U(0) = 0.
    """
    n1, n2 = len(rhs), len(rhs[0])
    fy, fx = _freqs(n1, d), _freqs(n2, d)
    spec = dft2(rhs)
    for k in range(n1):
        for l in range(n2):
            q = 4.0 * math.pi * math.pi * (fx[l] ** 2 + fy[k] ** 2)
            spec[k][l] = 0j if k == 0 and l == 0 else -spec[k][l] / q
    return [[v.real for v in row] for row in idft2(spec)]


def gradient(u, d):
    """The spectral gradient (du/dx, du/dy) of a periodic real image."""
    n1, n2 = len(u), len(u[0])
    fy, fx = _freqs(n1, d), _freqs(n2, d)
    spec = dft2(u)
    gx = [[2j * math.pi * fx[l] * spec[k][l] for l in range(n2)] for k in range(n1)]
    gy = [[2j * math.pi * fy[k] * spec[k][l] for l in range(n2)] for k in range(n1)]
    if n2 % 2 == 0:  # the Nyquist column has no sign; drop it so the result is real
        for k in range(n1):
            gx[k][n2 // 2] = 0j
    if n1 % 2 == 0:
        gy[n1 // 2] = [0j] * n2
    return [[v.real for v in row] for row in idft2(gx)], [[v.real for v in row] for row in idft2(gy)]


def divergence(gx, gy, d):
    """The spectral divergence d gx/dx + d gy/dy."""
    ax, _ = gradient(gx, d)
    _, by = gradient(gy, d)
    return [[a + b for a, b in zip(ra, rb)] for ra, rb in zip(ax, by)]


def tie_phase(i_minus, i_focus, i_plus, dz, d, wavelength):
    """The phase in the focal plane from the intensities at -dz, 0 and +dz.

    i_focus must be positive everywhere.
    """
    k = 2.0 * math.pi / wavelength
    didz = [[(p - m) / (2.0 * dz) for p, m in zip(rp, rm)] for rp, rm in zip(i_plus, i_minus)]  # @line L1
    psi = inverse_laplacian([[-k * v for v in row] for row in didz], d)  # @line L2
    gx, gy = gradient(psi, d)  # @line L3
    gx = [[a / i for a, i in zip(ra, ri)] for ra, ri in zip(gx, i_focus)]  # @line L4
    gy = [[a / i for a, i in zip(ra, ri)] for ra, ri in zip(gy, i_focus)]
    return inverse_laplacian(divergence(gx, gy, d), d)  # @line L5


def tie_phase_uniform(i_minus, i_plus, intensity, dz, d, wavelength):
    """The special case of a uniform intensity I0: lap phi = -(k / I0) dI/dz."""
    k = 2.0 * math.pi / wavelength
    rhs = [[-k / intensity * (p - m) / (2.0 * dz) for p, m in zip(rp, rm)] for rp, rm in zip(i_plus, i_minus)]
    return inverse_laplacian(rhs, d)
test_transport_of_intensity_equation.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/transport-of-intensity-equation/. The authors are listed in prov/5EFCMW.jsonl.

import cmath
import math
import random

from imgkit import dft2, idft2
from transport_of_intensity_equation import divergence, gradient, inverse_laplacian, tie_phase, tie_phase_uniform

N = 32
D = 1.0
WL = 0.5
K = 2.0 * math.pi / WL


def freqs(n, d):
    return [(k if 2 * k < n else k - n) / (n * d) for k in range(n)]


def band_limited(seed, kmax, amp):
    """A real periodic image with random Fourier modes 0 < |k|, |l| <= kmax, mean zero."""
    rng = random.Random(seed)
    spec = [[0j] * N for _ in range(N)]
    for k in range(-kmax, kmax + 1):
        for l in range(-kmax, kmax + 1):
            if (k, l) > (0, 0):
                c = complex(rng.gauss(0, 1), rng.gauss(0, 1))
                spec[k % N][l % N] = c
                spec[-k % N][-l % N] = c.conjugate()
    u = [[v.real for v in row] for row in idft2(spec)]
    s = amp / max(abs(v) for row in u for v in row)
    return [[s * v for v in row] for row in u]


def spectral_laplacian(u):
    fy = fx = freqs(N, D)
    spec = dft2(u)
    for k in range(N):
        for l in range(N):
            spec[k][l] *= -4.0 * math.pi * math.pi * (fx[l] ** 2 + fy[k] ** 2)
    return [[v.real for v in row] for row in idft2(spec)]


def propagate(u, z):
    """Angular spectrum propagation over a distance z (exp(-i omega t) convention)."""
    f = freqs(N, D)
    s = dft2(u)
    for k in range(N):
        for l in range(N):
            s[k][l] *= cmath.exp(2j * math.pi * z * math.sqrt(1.0 / WL ** 2 - f[k] ** 2 - f[l] ** 2))
    return idft2(s)


def bumps(seed, amp, width):
    """A sum of four periodic Gaussian bumps of random sign."""
    rng = random.Random(seed)
    cs = [(rng.uniform(0, N), rng.uniform(0, N), rng.uniform(-1, 1)) for _ in range(4)]
    out = [[0.0] * N for _ in range(N)]
    for i in range(N):
        for j in range(N):
            v = 0.0
            for cy, cx, a in cs:
                for sy in (-N, 0, N):
                    for sx in (-N, 0, N):
                        v += a * math.exp(-((i - cy + sy) ** 2 + (j - cx + sx) ** 2) / (2 * width ** 2))
            out[i][j] = amp * v
    return out


def demean(a):
    m = sum(map(sum, a)) / (len(a) * len(a[0]))
    return [[v - m for v in row] for row in a]


def rel_error(a, b):
    """Relative error of a against b after both means are removed (phase is up to a constant)."""
    a, b = demean(a), demean(b)
    num = sum((x - y) ** 2 for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    return math.sqrt(num / sum(y * y for row in b for y in row))


def defocus_series(amp, phi, dz, sigma=0.0, seed=0):
    rng = random.Random(seed)
    u0 = [[a * cmath.exp(1j * p) for a, p in zip(ra, rp)] for ra, rp in zip(amp, phi)]
    i0 = [[abs(v) ** 2 for v in row] for row in u0]
    im = [[abs(v) ** 2 + (rng.gauss(0, sigma) if sigma else 0.0) for v in row] for row in propagate(u0, -dz)]
    ip = [[abs(v) ** 2 + (rng.gauss(0, sigma) if sigma else 0.0) for v in row] for row in propagate(u0, dz)]
    return im, i0, ip


def test_inverse_laplacian_inverts_the_spectral_laplacian():
    u = band_limited(1, 6, 1.0)
    back = inverse_laplacian(spectral_laplacian(u), D)
    assert max(abs(a - b) for ra, rb in zip(back, u) for a, b in zip(ra, rb)) < 1e-12
    assert abs(sum(map(sum, back))) < 1e-10


def test_gradient_and_divergence_of_a_sine():
    u = [[math.sin(2 * math.pi * (3 * j + 2 * i) / N) for j in range(N)] for i in range(N)]
    gx, gy = gradient(u, D)
    for i in range(N):
        for j in range(N):
            c = math.cos(2 * math.pi * (3 * j + 2 * i) / N) * 2 * math.pi / N
            assert abs(gx[i][j] - 3 * c) < 1e-12
            assert abs(gy[i][j] - 2 * c) < 1e-12
    lap = divergence(gx, gy, D)
    want = spectral_laplacian(u)
    assert max(abs(a - b) for ra, rb in zip(lap, want) for a, b in zip(ra, rb)) < 1e-12


def test_uniform_intensity_is_exact_for_tie_data():
    # Data that satisfy the TIE exactly: dI/dz = -(I0 / k) lap phi.
    phi = band_limited(2, 7, 2.0)
    i0 = 0.7
    didz = [[-(i0 / K) * v for v in row] for row in spectral_laplacian(phi)]
    dz = 0.3
    im = [[i0 - dz * v for v in row] for row in didz]
    ip = [[i0 + dz * v for v in row] for row in didz]
    focus = [[i0] * N for _ in range(N)]
    assert rel_error(tie_phase(im, focus, ip, dz, D, WL), phi) < 1e-12
    assert rel_error(tie_phase_uniform(im, ip, i0, dz, D, WL), phi) < 1e-12


def test_curl_free_flux_with_varying_intensity():
    # I = exp(-psi) and phi = exp(psi) give I grad phi = grad psi, so the
    # Teague assumption holds exactly; only the spectral derivative of a
    # function that is not band-limited adds a small error.
    psi = band_limited(3, 3, 0.4)
    intensity = [[math.exp(-v) for v in row] for row in psi]
    phi = [[math.exp(v) for v in row] for row in psi]
    didz = [[-v / K for v in row] for row in spectral_laplacian(psi)]
    dz = 0.5
    im = [[a - dz * v for a, v in zip(ra, rv)] for ra, rv in zip(intensity, didz)]
    ip = [[a + dz * v for a, v in zip(ra, rv)] for ra, rv in zip(intensity, didz)]
    assert rel_error(tie_phase(im, intensity, ip, dz, D, WL), phi) < 1e-6


def test_defocus_series_of_a_phase_object():
    phi = bumps(1, 1.0, 3.0)
    flat = [[1.0] * N for _ in range(N)]
    im, i0, ip = defocus_series(flat, phi, 4.0)
    assert rel_error(tie_phase(im, i0, ip, 4.0, D, WL), phi) < 1e-3
    im, i0, ip = defocus_series(flat, phi, 64.0)
    assert rel_error(tie_phase(im, i0, ip, 64.0, D, WL), phi) > 0.03


def test_absorbing_object_needs_the_full_equation():
    phi = bumps(1, 1.0, 3.0)
    amp = [[math.exp(v) for v in row] for row in bumps(2, 0.3, 4.0)]
    im, i0, ip = defocus_series(amp, phi, 4.0)
    assert rel_error(tie_phase(im, i0, ip, 4.0, D, WL), phi) < 0.02
    mean_i = sum(map(sum, i0)) / (N * N)
    assert rel_error(tie_phase_uniform(im, ip, mean_i, 4.0, D, WL), phi) > 0.05


def test_noise_and_bias_trade_off_in_the_defocus():
    phi = bumps(1, 1.0, 3.0)
    flat = [[1.0] * N for _ in range(N)]
    err = {}
    for dz in (1.0, 16.0, 64.0):
        im, i0, ip = defocus_series(flat, phi, dz, sigma=1e-3, seed=5)
        err[dz] = rel_error(tie_phase(im, i0, ip, dz, D, WL), phi)
    assert err[16.0] < 0.015
    assert err[1.0] > 4 * err[16.0]
    assert err[64.0] > 4 * err[16.0]


def test_constant_phase_does_not_change_the_result():
    phi = bumps(4, 0.8, 3.0)
    flat = [[1.0] * N for _ in range(N)]
    a = tie_phase(*defocus_series(flat, phi, 4.0), 4.0, D, WL)
    b = tie_phase(*defocus_series(flat, [[v + 1.3 for v in row] for row in phi], 4.0), 4.0, D, WL)
    assert max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb)) < 1e-9
    assert abs(sum(map(sum, a))) < 1e-9

Exercises

  1. From the paraxial equation ∂zA=i2k∇2A\partial_z A = \frac{i}{2k}\nabla^2 A, derive the transport of intensity equation for A=IeiϕA = \sqrt{I} e^{i\phi}.
  2. For a uniform intensity I0I_0 and a phase ϕ=acos⁡(2πx/p)\phi = a \cos(2\pi x/p), compute ∂zI\partial_z I at the focal plane, and say where the intensity grows after focus.
  3. Show that the FFT solver returns the mean-zero solution of ∇2u=g−gˉ\nabla^2 u = g - \bar g for a band-limited gg, and explain why the mean of the phase is lost.
  4. Show that the noise added to the phase by independent noise in the two images falls as 1/Δz1/\Delta z, and that its spectrum grows as 1/∣f∣41/|f|^4 at low frequency.
  5. Give an intensity II and a phase ϕ\phi on a torus for which I∇ϕI\nabla\phi has a part without divergence, and check that the two-step method does not return ϕ\phi.
  6. A focus series is taken with a lateral drift of one pixel between the two images. Estimate the false phase gradient that this adds.
Proof: Why the TIE solver returns the phase, and where it does notfull

This page derives the transport of intensity equation from the paraxial wave equation, proves that the two Poisson solves of the code return the phase up to a constant when the energy flux is a gradient, and gives the two error terms of a real defocus series: the bias of the finite difference and the noise.

Setting. The field is U(x,y,z)=A(x,y,z)eikzU(x, y, z) = A(x, y, z) e^{ikz} with k=2π/λk = 2\pi/\lambda and the time factor e−iωte^{-i\omega t}. In the paraxial approximation the envelope obeys

∂A∂z=i2k∇2A,\frac{\partial A}{\partial z} = \frac{i}{2k} \nabla^2 A,

where ∇\nabla acts on xx and yy only. In Fourier space this is A^(f,z)=A^(f,0) e−iπλz∣f∣2\hat A(f, z) = \hat A(f, 0)\, e^{-i\pi\lambda z |f|^2}, which is the angular spectrum transfer function e2πiz1/λ2−∣f∣2e^{2\pi i z \sqrt{1/\lambda^2 - |f|^2}} with its square root expanded to first order and the factor eikze^{ikz} removed: i2k(−4π2∣f∣2)=−iπλ∣f∣2\frac{i}{2k}(-4\pi^2|f|^2) = -i\pi\lambda|f|^2. Write A=I eiϕA = \sqrt{I}\, e^{i\phi} where I>0I > 0.

Lemma 1 (the transport of intensity equation). Under the paraxial equation,

−k∂I∂z=∇⋅(I∇ϕ).-k \frac{\partial I}{\partial z} = \nabla \cdot (I \nabla \phi).

Proof. I=AˉAI = \bar A A, so ∂zI=2 Re(Aˉ ∂zA)=2 Re(i2kAˉ∇2A)=−1kIm(Aˉ∇2A)\partial_z I = 2\,\mathrm{Re}(\bar A\, \partial_z A) = 2\,\mathrm{Re}\big(\tfrac{i}{2k} \bar A \nabla^2 A\big) = -\tfrac{1}{k} \mathrm{Im}(\bar A \nabla^2 A). Since ∇⋅(Aˉ∇A)=∣∇A∣2+Aˉ∇2A\nabla \cdot (\bar A \nabla A) = |\nabla A|^2 + \bar A \nabla^2 A and ∣∇A∣2|\nabla A|^2 is real, Im(Aˉ∇2A)=∇⋅Im(Aˉ∇A)\mathrm{Im}(\bar A \nabla^2 A) = \nabla \cdot \mathrm{Im}(\bar A \nabla A). From ∇A=(∇I+iI∇ϕ)eiϕ\nabla A = (\nabla \sqrt{I} + i \sqrt{I} \nabla\phi) e^{i\phi} we get Aˉ∇A=I∇I+iI∇ϕ\bar A \nabla A = \sqrt{I}\nabla\sqrt{I} + i I \nabla\phi, whose imaginary part is I∇ϕI\nabla\phi. □\square

The vector I∇ϕI\nabla\phi is, up to a constant factor, the transverse energy flux. Lemma 1 says that the intensity changes along zz by the divergence of this flux.

The method. Teague's substitution writes I∇ϕ=∇ψI\nabla\phi = \nabla\psi. Then Lemma 1 gives the two Poisson equations

∇2ψ=−k ∂zI,∇2ϕ=∇⋅(∇ψI).\nabla^2 \psi = -k\, \partial_z I, \qquad \nabla^2 \phi = \nabla \cdot \Big(\frac{\nabla\psi}{I}\Big).

The code solves both on a periodic grid with the operator L−1\mathcal{L}^{-1} of line L2 and line L5: take the DFT, divide each coefficient by −4π2∣f∣2-4\pi^2|f|^2, set the zero frequency to 00, and take the inverse DFT. The gradient of line L3 multiplies by 2πif2\pi i f and drops the Nyquist row or column, which has no sign.

Lemma 2 (the spectral solver). Let gg be a real image whose DFT is zero at the Nyquist row and column. Then u=L−1gu = \mathcal{L}^{-1} g is the unique image with mean 00 and the same property such that Δu=g−gˉ\Delta u = g - \bar g, where Δ\Delta is the spectral Laplacian (the divergence of the spectral gradient) and gˉ\bar g is the mean of gg.

Proof. The spectral gradient followed by the spectral divergence multiplies each coefficient with no Nyquist index by (2πifx)2+(2πify)2=−4π2∣f∣2(2\pi i f_x)^2 + (2\pi i f_y)^2 = -4\pi^2|f|^2. This number is nonzero for f≠0f \ne 0, so the coefficient of uu at every f≠0f \ne 0 is fixed by gg and the coefficient at 00 is the mean, which is set to 00. □\square

Theorem (exact recovery). On the periodic grid, let ϕ\phi and I>0I > 0 be given, and suppose that the flux I∇ϕI\nabla\phi (with the spectral gradient) equals ∇χ\nabla\chi for some image χ\chi with no Nyquist content, and that ∇χ/I\nabla\chi / I has none either. If the input satisfies I+−I−2 Δz=−1kΔχ\frac{I_+ - I_-}{2\,\Delta z} = -\frac{1}{k} \Delta\chi exactly and I0=II_0 = I, then lines L1 to L5 return ϕ−ϕˉ\phi - \bar\phi.

Proof. Line L1 gives −1kΔχ-\frac{1}{k}\Delta\chi, and line L2 applies L−1\mathcal{L}^{-1} to Δχ\Delta\chi; by Lemma 2 the result is ψ=χ−χˉ\psi = \chi - \bar\chi, so ∇ψ=∇χ=I∇ϕ\nabla\psi = \nabla\chi = I\nabla\phi. Line L4 gives ∇ϕ\nabla\phi, and line L5 gives L−1(Δϕ)=ϕ−ϕˉ\mathcal{L}^{-1}(\Delta\phi) = \phi - \bar\phi, again by Lemma 2. □\square

For a uniform intensity I0I_0 the hypothesis holds with χ=I0ϕ\chi = I_0 \phi, and the two solves reduce to one: Δϕ=−kI0∂zI\Delta\phi = -\frac{k}{I_0}\partial_z I. The tests check both forms on band-limited data to rounding error, and the varying case with I=e−ψI = e^{-\psi} and ϕ=eψ\phi = e^{\psi}, where I∇ϕ=∇ψI\nabla\phi = \nabla\psi holds in the continuum.

Where the method is not exact.

  1. The flux is not always a gradient. A periodic vector field splits into a gradient, a divergence-free part and a constant vector (the Helmholtz decomposition). Lemma 1 only constrains the divergence of I∇ϕI\nabla\phi, so the data say nothing about the other two parts, and Teague's substitution sets them to zero. If II varies and ∇I\nabla I is not parallel to ∇ϕ\nabla\phi, the flux has a divergence-free part in general, and the result is not ϕ\phi. For the absorbing test object on the page the error from this source is about one percent (a measurement).
  2. The finite difference. If II is smooth in zz, Taylor's theorem gives
I(Δz)−I(−Δz)2 Δz=∂zI(0)+Δz26 ∂z3I(ξ)\frac{I(\Delta z) - I(-\Delta z)}{2\,\Delta z} = \partial_z I(0) + \frac{\Delta z^2}{6}\, \partial_z^3 I(\xi)

at each point, for some ξ\xi in (−Δz,Δz)(-\Delta z, \Delta z). The bias is of order Δz2\Delta z^2. It also includes the error of the paraxial equation when the images come from exact propagation. 3. Noise. The method is linear in the data for uniform intensity. Independent noise e±e_\pm in the two images adds L−1(−kI0e+−e−2 Δz)\mathcal{L}^{-1}\big(-\frac{k}{I_0}\frac{e_+ - e_-}{2\,\Delta z}\big) to the phase. Its DFT coefficient at f≠0f \ne 0 is the coefficient of e+−e−e_+ - e_- times k8π2I0Δz∣f∣2\frac{k}{8\pi^2 I_0 \Delta z |f|^2}. So the noise in the phase falls as 1/Δz1/\Delta z and is largest at the lowest frequencies.

Items 2 and 3 pull Δz\Delta z in opposite directions: a small step amplifies noise, a large step adds bias. Neither the best step nor the size of the divergence-free part follows from the data alone, and the page reports them as measurements.

References

  1. Michael Reed Teague, Deterministic phase retrieval, a Green's function solution, Journal of the Optical Society of America 73(11), 1983, 1434 to 1441, the transport of intensity equation, the substitution of an auxiliary potential and the solution with Green's functions (general locator)
  2. David Paganin and Keith A. Nugent, Noninterferometric phase imaging with partially coherent light, Physical Review Letters 80(12), 1998, 2586 to 2589, the solution of the equation with fast Fourier transforms and its use with partially coherent light (general locator)
  3. David Paganin, Sheridan C. Mayo, Timur E. Gureyev, Peter R. Miller and Stephen W. Wilkins, Simultaneous phase and amplitude extraction from a single defocused image of a homogeneous object, Journal of Microscopy 206(1), 2002, 33 to 40, the single image method for a homogeneous object (general locator)
  4. Joseph W. Goodman, Introduction to Fourier Optics, third edition, Roberts and Company, 2005, the angular spectrum and the Fresnel approximation (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 proofH2 full proof
  • correctness: no review record reviews/5EFCMW/proof-correctness.yaml
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)
WritingW3 standard
  • five exercises