Algorithm Search⌘K

Algorithmadvanced

Structured illumination microscopy reconstruction

Also called SIM reconstruction.

Separate the three bands mixed by phase-shifted stripe illumination and recombine them in Fourier space. Linear SIM with the stripe frequency at the cutoff about doubles the resolution.

Time
Θ(D N log N) worst · average · best
Space
Θ(N) extra
Where
D = the number of stripe directions; N = the number of pixels in a frame
Properties
deterministicnot iterativelinearneeds known patternoptical method
Origin
Mats G. L. Gustafsson, Rainer Heintzmann, Christoph Cremer, 2000

Structured illumination microscopy (SIM) is an optical method for fluorescence microscopy that sees finer detail than the diffraction limit of the lens allows for a plain image. The microscope lights the sample with a fine pattern of stripes instead of a uniform field. The stripes multiply the sample, and this product moves fine object detail, which the lens cannot pass, to coarse moiré fringes, which it can. The reconstruction is the computation that undoes this mixing: from three images taken with three phases of the stripes it separates three copies of the object spectrum, moves each copy back to its true place in Fourier space, and combines them with a weighted (Wiener-type) filter. The result contains object frequencies up to the sum of the cutoff of the lens and the stripe frequency. With stripes at the cutoff, which is the finest pattern the same lens can make, this is about twice the widefield cutoff; this factor of two holds for linear SIM, where the emission is proportional to the light. The gain comes from the physical illumination, not from image processing; without the stripes the computation can recover nothing beyond the Abbe limit.

In plain words

A lens acts like a sieve for patterns: it passes coarse patterns and blocks fine ones. If you lay a fine striped grid over a fine pattern, you see a coarse moiré pattern, and the moiré is coarse enough to pass the sieve. SIM makes such a moiré on purpose. It lights the sample with a known striped pattern, takes a picture, moves the stripes a little, takes another, and so on. Because the stripes are known, the computer can work out which fine pattern made each moiré, and put the fine detail back where it belongs. Rotating the stripes gives fine detail in every direction.

The problem

The sample is a fluorescent density xx on a periodic grid of N=n1n2N = n_1 n_2 pixels. The microscope has a known optical transfer function HH, real and symmetric, which is 00 above the cutoff kck_c. For each stripe direction d=1,…,Dd = 1, \ldots, D there are three frames, lit with Pj(r)=1+mcos⁡(2πk0,d⋅r/n+φj)P_j(r) = 1 + m\cos(2\pi k_{0,d}\cdot r/n + \varphi_j), with a known integer stripe frequency k0,dk_{0,d}, a known depth mm and three known phases. Frame jj is h⊛(Pjx)h \circledast (P_j x) plus noise. The goal is an estimate of xx with as many object frequencies as the data contain. By the convolution theorem, the DFT of a frame is

d^j(k)=H(k)[X(k)+m2eiφjX(k−k0)+m2e−iφjX(k+k0)],\hat d_j(k) = H(k)\Bigl[X(k) + \tfrac m2 e^{i\varphi_j} X(k - k_0) + \tfrac m2 e^{-i\varphi_j} X(k + k_0)\Bigr],

so each frame mixes three copies of the object spectrum, two of them shifted by ±k0\pm k_0.

The algorithm

Let MM be the 3×33 \times 3 matrix with the rows (1,m2eiφj,m2e−iφj)(1, \frac m2 e^{i\varphi_j}, \frac m2 e^{-i\varphi_j}), and w≥0w \ge 0 the Wiener constant.

  1. SIM-RECONSTRUCT(frames, k0s, phases, m, H, w)
  2. 1num ← 0, den ← w at every frequency k
  3. 2for each direction d with stripe frequency k0
  4. 3(S0, S+, S-) ← M⁻¹ · (DFT of the three frames), at each k
  5. 4T+(k) ← S+(k + k0), H+(k) ← H(k + k0); T-(k) ← S-(k - k0), H-(k) ← H(k - k0)
  6. 5num ← num + H·S0 + H+·T+ + H-·T-; den ← den + H² + H+² + H-²
  7. 6X̂(k) ← num(k) / den(k) if den(k) > 0, else 0
  8. 7return the real part of the inverse DFT of X̂

Line L3 separates the bands S0=HXS_0 = HX, S+=HX(⋅−k0)S_+ = H X(\cdot - k_0) and S−=HX(⋅+k0)S_- = HX(\cdot + k_0). Line L4 moves them back, so that T±(k)=H(k±k0)X(k)T_\pm(k) = H(k \pm k_0) X(k): each is the object seen through a shifted OTF. Line L5 is the generalized Wiener filter for several measurements of the same X(k)X(k) through different transfer functions. The code uses the incoherent OTF of a circular pupil, H(k)=2π(arccos⁡ρ−ρ1−ρ2)H(k) = \frac2\pi(\arccos\rho - \rho\sqrt{1 - \rho^2}) with ρ=∣k∣/kc\rho = |k|/k_c, and periodic indices, so kc+∣k0∣k_c + |k_0| must stay below half the image size.

Example

Take 32×3232 \times 32 pixels, the cutoff kc=6k_c = 6 (in DFT index units), the stripes k0=(0,5)k_0 = (0, 5), m=1m = 1 and the phases 0,2π/3,4π/30, 2\pi/3, 4\pi/3. The OTF along the stripes is H(0)=1H(0) = 1, H(4)=0.2191H(4) = 0.2191, H(5)=0.0796H(5) = 0.0796 and H(k)=0H(k) = 0 for ∣k∣≥6|k| \ge 6. The sample is the grating x=1+cos⁡(2π⋅9c/32)x = 1 + \cos(2\pi\cdot 9c/32), with the frequency 99 beyond the cutoff.

  • Widefield. The mean of the three frames is h⊛xh \circledast x. Since H(9)=0H(9) = 0, it is the constant 11: the grating is invisible.
  • Raw frame. Each frame contains a moiré fringe at the frequency 9−5=49 - 5 = 4, inside the passband. Its DFT coefficient, divided by NN, has the modulus m2⋅12⋅H(4)=0.0548\frac m2 \cdot \frac12 \cdot H(4) = 0.0548. Each frame also shows the stripes, at the frequency 55, with the modulus m2H(5)=0.0398\frac m2 H(5) = 0.0398.
  • Reconstruction. Without noise and with w=0w = 0, the output equals xx to 10−910^{-9} (a theorem, Claim 4 of the proof): the grating is fully recovered.
  • Beyond the extended support. The grating at the frequency 1212 has 12−5=7>612 - 5 = 7 > 6. No band contains it, and the output is the constant 11.

A measurement with noise, from the test: an object with every frequency up to radius 88, the cutoff kc=5k_c = 5, four stripe directions (0,4),(4,0),(3,3),(3,−3)(0,4), (4,0), (3,3), (3,-3), Gaussian noise with σ=0.01\sigma = 0.01 and w=10−3w = 10^{-3}. The relative error of the SIM result is 0.0690.069; the Wiener deconvolution of the widefield image with the same ww has 0.2370.237. The extended support has 233233 frequencies, against 6969 for the widefield OTF.

Correctness

The proof is in proofs/correctness.md. The main facts, all theorems:

  1. The DFT of a frame is the sum of three bands, as in the formula of the problem.
  2. The phase matrix MM is invertible if and only if m≠0m \ne 0 and the three phases are distinct modulo 2π2\pi; its determinant is a Vandermonde determinant. For equally spaced phases its columns are orthogonal, so the noise in the side bands is 2/m2/m times the noise in the center band.
  3. After the shift, T±(k)=H(k±k0)X(k)T_\pm(k) = H(k \pm k_0) X(k).
  4. Without noise the result has the DFT Σ(k)Σ(k)+wX(k)\frac{\Sigma(k)}{\Sigma(k) + w}X(k), where Σ\Sigma is the sum of the squared OTFs of all bands; with w=0w = 0 it is xx limited to the extended support {Σ>0}\{\Sigma > 0\}.
  5. For real frames the estimate is real.
  6. The extended support lies inside the disk of radius kc+max⁡d∣k0,d∣k_c + \max_d |k_{0,d}|. If ∣k0,d∣≤kc|k_{0,d}| \le k_c, which holds when the same lens makes the stripes, this radius is at most 2kc2k_c.
Proof: Three phases separate the bands, the shifted bands carry the object spectrum outside the passband, and the noise-free result is the object limited to the extended supportfull

Setting. Images are periodic on n1×n2n_1 \times n_2 pixels. The DFT is X(k)=∑rx(r)e−2πi(k1r1/n1+k2r2/n2)X(k) = \sum_r x(r) e^{-2\pi i (k_1 r_1/n_1 + k_2 r_2/n_2)}, and all frequency indices are taken modulo the image size. The OTF HH is real and symmetric, H(−k)=H(k)H(-k) = H(k), so the PSF hh with h^=H\hat h = H is real. For one stripe direction with the integer frequency k0k_0, the depth mm and the phases φ1,φ2,φ3\varphi_1, \varphi_2, \varphi_3, frame jj is dj=h⊛(Pjx)d_j = h \circledast (P_j x) with Pj(r)=1+mcos⁡(2πk0⋅r/n+φj)P_j(r) = 1 + m\cos(2\pi k_0 \cdot r/n + \varphi_j), where k0⋅r/nk_0 \cdot r/n means k0,1r1/n1+k0,2r2/n2k_{0,1}r_1/n_1 + k_{0,2} r_2/n_2. Write a=m/2a = m/2.

Claim 1 (forward model). d^j(k)=H(k)[X(k)+aeiφjX(k−k0)+ae−iφjX(k+k0)]\hat d_j(k) = H(k)\bigl[X(k) + a e^{i\varphi_j} X(k - k_0) + a e^{-i\varphi_j} X(k + k_0)\bigr].

Proof. cos⁡θ=(eiθ+e−iθ)/2\cos\theta = (e^{i\theta} + e^{-i\theta})/2, and the DFT of x(r)e2πik0⋅r/nx(r) e^{2\pi i k_0 \cdot r/n} is X(k−k0)X(k - k_0), by the definition of the DFT. So Pjx^(k)=X(k)+aeiφjX(k−k0)+ae−iφjX(k+k0)\widehat{P_j x}(k) = X(k) + a e^{i\varphi_j}X(k - k_0) + a e^{-i\varphi_j}X(k + k_0). The DFT of a periodic convolution is the product of the DFTs (the convolution theorem). □\square

The test compares the frames, which the code computes with the DFT, with a direct periodic convolution.

Claim 2 (band separation). Let S0(k)=H(k)X(k)S_0(k) = H(k)X(k), S+(k)=H(k)X(k−k0)S_+(k) = H(k)X(k - k_0) and S−(k)=H(k)X(k+k0)S_-(k) = H(k)X(k + k_0). Then d^(k)=M (S0,S+,S−)T(k)\hat d(k) = M\,(S_0, S_+, S_-)^T(k) with the rows Mj=(1,aeiφj,ae−iφj)M_j = (1, a e^{i\varphi_j}, a e^{-i\varphi_j}), and MM is invertible if and only if m≠0m \ne 0 and the three phases are distinct modulo 2π2\pi.

Proof. The first part is Claim 1. Let zj=eiφjz_j = e^{i\varphi_j}. Multiplying row jj by zjz_j gives the rows (zj,azj2,a)(z_j, a z_j^2, a), so det⁡M⋅z1z2z3=a2det⁡[zj,zj2,1]\det M \cdot z_1z_2z_3 = a^2 \det[z_j, z_j^2, 1]. Moving the last column to the front is a cyclic permutation of the columns, which has the sign +1+1, so this is a2a^2 times the Vandermonde determinant ∏i<j(zj−zi)\prod_{i<j}(z_j - z_i). It is 00 if and only if a=0a = 0 or two zjz_j are equal. □\square

So line L3 recovers the three bands exactly at every kk. The code inverts MM once by the adjugate and raises an error when ∣det⁡M∣|\det M| is tiny. For the equally spaced phases 0,2π/3,4π/30, 2\pi/3, 4\pi/3, the columns of MM are orthogonal, because ∑jzj=∑jzj−2=0\sum_j z_j = \sum_j z_j^{-2} = 0, and their norms are 3\sqrt 3, a3a\sqrt 3 and a3a\sqrt 3. So for white noise of the same variance in each frame, the noise of the three bands is uncorrelated, and the noise of S±S_\pm is 1/a=2/m1/a = 2/m times the noise of S0S_0.

Claim 3 (shifted bands). Let T+(k)=S+(k+k0)T_+(k) = S_+(k + k_0) and T−(k)=S−(k−k0)T_-(k) = S_-(k - k_0) (line L4). Then T+(k)=H(k+k0)X(k)T_+(k) = H(k + k_0)X(k) and T−(k)=H(k−k0)X(k)T_-(k) = H(k - k_0)X(k).

Proof. Substitute k+k0k + k_0 and k−k0k - k_0 in the definitions of S+S_+ and S−S_-. □\square

So each band is a copy of XX seen through a shifted OTF. Where H(k)=0H(k) = 0 but H(k+k0)≠0H(k + k_0) \ne 0, the frequency kk of the object, which the widefield image does not contain, is measured.

Claim 4 (noise-free result). Let the directions k0,1,…,k0,Dk_{0,1}, \ldots, k_{0,D} each give three frames without noise, and let Σ(k)=∑d[H(k)2+H(k+k0,d)2+H(k−k0,d)2]\Sigma(k) = \sum_d \bigl[H(k)^2 + H(k + k_{0,d})^2 + H(k - k_{0,d})^2\bigr]. Lines L5 to L7 give the image with the DFT Σ(k)Σ(k)+wX(k)\frac{\Sigma(k)}{\Sigma(k) + w} X(k) where Σ(k)+w>0\Sigma(k) + w > 0, and 00 elsewhere. With w=0w = 0 it is xx with every frequency outside the extended support E={k:Σ(k)>0}E = \{k : \Sigma(k) > 0\} set to 00.

Proof. By Claims 2 and 3, the sum of line L5 is ∑d∑bHb(k)⋅Hb(k)X(k)=Σ(k)X(k)\sum_d \sum_b H_b(k) \cdot H_b(k) X(k) = \Sigma(k) X(k), with the three OTFs Hb∈{H(k),H(k+k0,d),H(k−k0,d)}H_b \in \{H(k), H(k + k_{0,d}), H(k - k_{0,d})\}, and the denominator is Σ(k)+w\Sigma(k) + w. □\square

The test checks this for three directions against the projection computed directly from the DFT of xx, and checks that a grating outside the widefield passband is recovered exactly.

Claim 5 (real output). For real frames, the DFT of the estimate is Hermitian, x^(−k)=x^(k)‾\hat x(-k) = \overline{\hat x(k)}, so the estimate is real and the real part in line L7 removes only rounding.

Proof. The frames are real, so d^j(−k)=d^j(k)‾\hat d_j(-k) = \overline{\hat d_j(k)}. The conjugate of row MjM_j is MjM_j with its last two entries swapped. Let Π\Pi swap the last two components. Then d^(k)‾=M‾ S(k)‾=MΠS(k)‾\overline{\hat d(k)} = \overline M\, \overline{S(k)} = M \Pi \overline{S(k)}, and also d^(−k)=MS(−k)\hat d(-k) = M S(-k). Since MM is invertible, S(−k)=ΠS(k)‾S(-k) = \Pi \overline{S(k)}: S0(−k)=S0(k)‾S_0(-k) = \overline{S_0(k)} and S±(−k)=S∓(k)‾S_\pm(-k) = \overline{S_\mp(k)}. Hence T+(−k)=S+(−k+k0)=S−(k−k0)‾=T−(k)‾T_+(-k) = S_+(-k + k_0) = \overline{S_-(k - k_0)} = \overline{T_-(k)}, and the OTF paired with T+T_+ at −k-k is H(−k+k0)=H(k−k0)H(-k + k_0) = H(k - k_0), the one paired with T−T_- at kk. So the numerator at −k-k is the conjugate of the numerator at kk, and the denominator is symmetric. □\square

Claim 6 (the support and the factor of two). If H(k)=0H(k) = 0 for ∣k∣≥kc|k| \ge k_c, then E⊆{∣k∣<kc+max⁡d∣k0,d∣}E \subseteq \{|k| < k_c + \max_d |k_{0,d}|\}, and EE contains every k=k0+tk = k_0 + t with ∣t∣<kc|t| < k_c and H(t)≠0H(t) \ne 0. If the stripes are made by the same optics, so that ∣k0,d∣≤kc|k_{0,d}| \le k_c, the extended support lies inside the disk of radius 2kc2k_c, and it reaches 2kc2k_c along k0,dk_{0,d} only when ∣k0,d∣|k_{0,d}| is at the cutoff.

Proof. k∈Ek \in E means ∣k∣<kc|k| < k_c or ∣k±k0,d∣<kc|k \pm k_{0,d}| < k_c for some dd, and in the last case ∣k∣<kc+∣k0,d∣|k| < k_c + |k_{0,d}| by the triangle inequality. For k=k0+tk = k_0 + t, H(k−k0)=H(t)≠0H(k - k_0) = H(t) \ne 0. The last statement follows from the first with ∣k0,d∣≤kc|k_{0,d}| \le k_c. □\square

That the stripe frequency is limited by the cutoff of the same objective is a fact about the optics, not about the computation: in a real microscope the stripes are made with the excitation light and the image with the emission light, whose cutoffs differ a little, so the gain is close to, not exactly, a factor of two.

Claim 7 (widefield frame). For the phases 0,2π/3,4π/30, 2\pi/3, 4\pi/3, the mean of the three frames is h⊛xh \circledast x.

Proof. ∑je±iφj=0\sum_j e^{\pm i\varphi_j} = 0 for three equally spaced phases, so the side terms of Claim 1 cancel in the mean. □\square ■\blacksquare

Complexity

Each direction needs three 2D DFTs of NN pixels, Θ(N)\Theta(N) work to separate, shift and add the bands, and one inverse DFT at the end. With power-of-two sizes and the FFT, this is Θ(DNlog⁡N)\Theta(D N \log N) time for DD directions. The extra space is Θ(N)\Theta(N) for the bands of one direction and the two sums. The method has no iteration.

Properties

  • Linear in the data, for known stripe parameters. The noise in each frequency is easy to predict.
  • Optical gain. The new frequencies come from the light pattern; the computation only undoes a known mixing.
  • Factor of two only for linear SIM. With ∣k0∣≤kc|k_0| \le k_c the extended cutoff is at most 2kc2k_c. The stripes are made with the excitation light and the image is formed with the emission light, so in practice the gain is a little less than two.
  • Uneven noise. The side bands carry m/2m/2 of the signal, and the OTF is small near the edge of each band, so the high frequencies of the result are noisy. The Wiener constant ww trades noise against resolution.
  • Needs several frames. Three phases for each of DD directions, often D=3D = 3, so nine frames for a 2D image.

Variants and improvements

  • More phases. Use more than three phases and solve the band equations by least squares.
  • Parameter estimation. In practice k0k_0, the phases and mm are not known exactly. They are estimated from the data, for example from the cross-correlation of the bands in their overlap.
  • Apodization. Multiply the result by a smooth window that falls to zero at the edge of the extended support, to reduce ringing.
  • 3D SIM. Three-beam interference gives stripes that also vary along the optical axis, and the same band separation works in 3D with five bands.
  • Nonlinear (saturated) SIM. If the emission is a nonlinear function of the light, the effective pattern has harmonics 2k0,3k0,…2k_0, 3k_0, \ldots, which bring more bands and, in principle, no fixed limit (Gustafsson 2005). Each harmonic needs more phases.

When to use it

Use SIM for fluorescent samples when a gain of up to two in resolution is enough, when the sample must stay alive, and when a wide field must be imaged fast. It uses ordinary dyes and moderate light. For a larger gain, localization methods such as PALM and STORM go to tens of nanometers but need many more frames and special dyes. SOFI gives a gain from the blinking of the dyes without special optics. If the sample does not fluoresce, or the stripe pattern cannot be projected, SIM does not apply.

Pitfalls

  • Wrong pattern parameters. A small error in k0k_0 or in a phase leaves part of one band in another, and the result shows stripes or a honeycomb pattern. Estimate the parameters from the data.
  • Equal phases. Two equal phases make MM singular. The code raises an error.
  • Too small a Wiener constant. With ww near 00, frequencies where all OTFs are small get a large gain and the noise grows. Too large a ww smooths the result.
  • Periodic wrap. The code works modulo the image size. If kc+∣k0∣k_c + |k_0| reaches half the size, the shifted bands wrap around.
  • Reading the result as more than double. Linear SIM cannot pass frequencies beyond kc+∣k0∣k_c + |k_0|, no matter how the reconstruction is tuned.

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
structured_illumination_microscopy.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structured-illumination-microscopy/. The authors are listed in prov/BKPK9D.jsonl.
"""Linear structured illumination microscopy (SIM) reconstruction in 2D.

Model, periodic on n1 x n2 pixels: the sample x is lit by the stripes

    P(r, c) = 1 + m cos(2 pi (u r / n1 + v c / n2) + phi)

with an integer frequency k0 = (u, v), a modulation depth m and a phase phi.
The camera records the periodic convolution of P x with the PSF whose DFT is
the OTF H (real and symmetric, so the PSF is real). With the DFT of imgkit,
X(k) = sum x exp(-2 pi i k . r / n), one frame is

    D(k) = H(k) [X(k) + (m/2) e^{i phi} X(k - k0) + (m/2) e^{-i phi} X(k + k0)].

Three phases give three linear equations for the three bands H X(k),
H X(k - k0) and H X(k + k0) at each k. All frequency indices are taken
modulo the image size, so k0 plus the OTF cutoff must stay below n / 2.
"""

import cmath
import math

from imgkit import dft2, idft2, new_image


def signed(k, n):
    """The signed frequency of DFT index k: k for k < n / 2, k - n otherwise."""
    return k if k < n - k else k - n


def otf_incoherent(n1, n2, kc):
    """The OTF of an aberration-free circular pupil with the cutoff kc (DFT index units).

    H(k) = (2 / pi) (acos rho - rho sqrt(1 - rho^2)) for rho = |k| / kc < 1, else 0.
    """
    h = new_image(n1, n2)
    for a in range(n1):
        for b in range(n2):
            rho = math.hypot(signed(a, n1), signed(b, n2)) / kc
            if rho < 1:
                h[a][b] = (2 / math.pi) * (math.acos(rho) - rho * math.sqrt(1 - rho * rho))
    return h


def psf_of_otf(h):
    """The real PSF, centered at index (0, 0), whose DFT is the real symmetric OTF h."""
    return [[z.real for z in row] for row in idft2(h)]


def pattern(n1, n2, k0, phi, m):
    """The illumination 1 + m cos(2 pi (u r / n1 + v c / n2) + phi)."""
    u, v = k0
    return [[1 + m * math.cos(2 * math.pi * (u * r / n1 + v * c / n2) + phi)
             for c in range(n2)] for r in range(n1)]


def blur(img, h):
    """Periodic convolution of img with the PSF of the OTF h, by the DFT."""
    f = dft2(img)
    g = [[h[a][b] * f[a][b] for b in range(len(f[0]))] for a in range(len(f))]
    return [[z.real for z in row] for row in idft2(g)]


def sim_frames(x, h, k0, phases, m):
    """The raw frames of one stripe direction: blur(P_j x) for each phase phi_j."""
    n1, n2 = len(x), len(x[0])
    frames = []
    for phi in phases:
        p = pattern(n1, n2, k0, phi, m)
        lit = [[p[r][c] * x[r][c] for c in range(n2)] for r in range(n1)]
        frames.append(blur(lit, h))
    return frames


def mixing_matrix(phases, m):
    """Row j is (1, (m/2) e^{i phi_j}, (m/2) e^{-i phi_j})."""
    return [[1, (m / 2) * cmath.exp(1j * phi), (m / 2) * cmath.exp(-1j * phi)]
            for phi in phases]


def _cofactor(a, i, j):
    r = [t for t in range(3) if t != i]
    c = [t for t in range(3) if t != j]
    minor = a[r[0]][c[0]] * a[r[1]][c[1]] - a[r[0]][c[1]] * a[r[1]][c[0]]
    return minor if (i + j) % 2 == 0 else -minor


def inv3(a, tol=1e-12):
    """The inverse of a 3 x 3 complex matrix by the adjugate.

    Raises ValueError when |det| <= tol * max|a_ij|^3 (equal phases, or m = 0).
    """
    det = sum(a[0][j] * _cofactor(a, 0, j) for j in range(3))
    scale = max(abs(z) for row in a for z in row)
    if abs(det) <= tol * scale ** 3:
        raise ValueError("the phases do not separate the three bands")
    return [[_cofactor(a, j, i) / det for j in range(3)] for i in range(3)]


def separate_bands(frames, phases, m):
    """The DFTs of the bands (H X(k), H X(k - k0), H X(k + k0)) from three frames."""
    if len(frames) != 3 or len(phases) != 3:
        raise ValueError("linear SIM needs three phases per direction")
    minv = inv3(mixing_matrix(phases, m))
    f = [dft2(d) for d in frames]
    n1, n2 = len(f[0]), len(f[0][0])
    bands = []
    for b in range(3):
        s = [[sum(minv[b][j] * f[j][r][c] for j in range(3)) for c in range(n2)]
             for r in range(n1)]
        bands.append(s)
    return bands


def shifted(img, k0, sign):
    """T(k) = img(k + sign k0), with the indices modulo the image size."""
    n1, n2 = len(img), len(img[0])
    u, v = k0
    return [[img[(r + sign * u) % n1][(c + sign * v) % n2] for c in range(n2)]
            for r in range(n1)]


def sim_reconstruct(frames_by_dir, k0s, phases, m, h, w=0.0):
    """Linear SIM reconstruction with a generalized Wiener filter.

    frames_by_dir[d] holds the three frames of direction d, lit with the
    frequency k0s[d] and the given phases. Returns the real image whose DFT is
    sum_b conj(H_b) T_b / (sum_b |H_b|^2 + w), set to 0 where the
    denominator is 0. With w = 0 and noise-free frames this is x with every
    frequency outside the extended support removed.
    """
    n1, n2 = len(h), len(h[0])
    num = [[0j] * n2 for _ in range(n1)]  # @line L1
    den = [[float(w)] * n2 for _ in range(n1)]  # @line L1
    for frames, k0 in zip(frames_by_dir, k0s):  # @line L2
        s0, sp, sm = separate_bands(frames, phases, m)  # @line L3
        tp, hp = shifted(sp, k0, 1), shifted(h, k0, 1)  # @line L4
        tm, hm = shifted(sm, k0, -1), shifted(h, k0, -1)  # @line L4
        for r in range(n1):  # @line L5
            for c in range(n2):  # @line L5
                for t, hb in ((s0, h), (tp, hp), (tm, hm)):  # @line L5
                    num[r][c] += hb[r][c] * t[r][c]  # @line L5
                    den[r][c] += hb[r][c] * hb[r][c]  # @line L5
    est = [[num[r][c] / den[r][c] if den[r][c] > 0 else 0j for c in range(n2)]  # @line L6
           for r in range(n1)]  # @line L6
    return [[z.real for z in row] for row in idft2(est)]  # @line L7


def extended_support(h, k0s):
    """The mask of the frequencies k with H(k) != 0, H(k + k0) != 0 or H(k - k0) != 0."""
    n1, n2 = len(h), len(h[0])
    mask = [[h[r][c] != 0 for c in range(n2)] for r in range(n1)]
    for k0 in k0s:
        for sign in (1, -1):
            hs = shifted(h, k0, sign)
            for r in range(n1):
                for c in range(n2):
                    mask[r][c] = mask[r][c] or hs[r][c] != 0
    return mask


def widefield(frames):
    """The mean of the frames; for three equally spaced phases it is blur(x)."""
    k = len(frames)
    n1, n2 = len(frames[0]), len(frames[0][0])
    return [[sum(f[r][c] for f in frames) / k for c in range(n2)] for r in range(n1)]


def wiener_deconvolve(img, h, w):
    """The Wiener estimate conj(H) D / (|H|^2 + w), set to 0 where the denominator is 0."""
    f = dft2(img)
    n1, n2 = len(f), len(f[0])
    g = new_image(n1, n2)
    for r in range(n1):
        for c in range(n2):
            d = h[r][c] * h[r][c] + w
            g[r][c] = h[r][c] * f[r][c] / d if d > 0 else 0j
    return [[z.real for z in row] for row in idft2(g)]
test_structured_illumination_microscopy.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/structured-illumination-microscopy/. The authors are listed in prov/BKPK9D.jsonl.

import math
import random

from imgkit import circ_conv2, dft2, gauss_noise, idft2
from structured_illumination_microscopy import (
    extended_support,
    inv3,
    mixing_matrix,
    otf_incoherent,
    pattern,
    psf_of_otf,
    separate_bands,
    sim_frames,
    sim_reconstruct,
    widefield,
    wiener_deconvolve,
)

PHASES = (0.0, 2 * math.pi / 3, 4 * math.pi / 3)


def rand_image(rng, n):
    return [[rng.random() for _ in range(n)] for _ in range(n)]


def max_diff(a, b):
    return max(abs(a[r][c] - b[r][c]) for r in range(len(a)) for c in range(len(a[0])))


def rel_err(a, b):
    num = sum((a[r][c] - b[r][c]) ** 2 for r in range(len(a)) for c in range(len(a[0])))
    den = sum(b[r][c] ** 2 for r in range(len(a)) for c in range(len(a[0])))
    return math.sqrt(num / den)


def test_forward_model_is_periodic_convolution():
    rng = random.Random(1)
    n = 8
    h = otf_incoherent(n, n, 2.5)
    psf = psf_of_otf(h)
    x = rand_image(rng, n)
    k0 = (1, 2)
    frames = sim_frames(x, h, k0, PHASES, 0.8)
    for phi, d in zip(PHASES, frames):
        p = pattern(n, n, k0, phi, 0.8)
        lit = [[p[r][c] * x[r][c] for c in range(n)] for r in range(n)]
        assert max_diff(d, circ_conv2(lit, psf)) < 1e-12


def test_band_separation_is_exact():
    rng = random.Random(2)
    n = 16
    h = otf_incoherent(n, n, 4)
    x = rand_image(rng, n)
    u, v = 1, 3
    phases = (0.3, 1.9, 4.4)
    s0, sp, sm = separate_bands(sim_frames(x, h, (u, v), phases, 0.7), phases, 0.7)
    big_x = dft2(x)
    for r in range(n):
        for c in range(n):
            assert abs(s0[r][c] - h[r][c] * big_x[r][c]) < 1e-9
            assert abs(sp[r][c] - h[r][c] * big_x[(r - u) % n][(c - v) % n]) < 1e-9
            assert abs(sm[r][c] - h[r][c] * big_x[(r + u) % n][(c + v) % n]) < 1e-9


def test_noise_free_output_is_projection_on_extended_support():
    rng = random.Random(3)
    n = 16
    h = otf_incoherent(n, n, 3)
    x = rand_image(rng, n)
    k0s = [(0, 3), (3, 0), (2, -2)]
    frames = [sim_frames(x, h, k0, PHASES, 1.0) for k0 in k0s]
    out = sim_reconstruct(frames, k0s, PHASES, 1.0, h, w=0.0)
    mask = extended_support(h, k0s)
    big_x = dft2(x)
    proj = idft2([[big_x[r][c] if mask[r][c] else 0j for c in range(n)] for r in range(n)])
    assert max_diff(out, [[z.real for z in row] for row in proj]) < 1e-9


def test_grating_beyond_cutoff_is_recovered():
    n, kc = 32, 6
    h = otf_incoherent(n, n, kc)
    x = [[1 + math.cos(2 * math.pi * 9 * c / n) for c in range(n)] for _ in range(n)]
    frames = sim_frames(x, h, (0, 5), PHASES, 1.0)
    wf = widefield(frames)
    flat = [v for row in wf for v in row]
    assert max(flat) - min(flat) < 1e-9
    out = sim_reconstruct([frames], [(0, 5)], PHASES, 1.0, h)
    assert max_diff(out, x) < 1e-9
    # A grating at frequency 12 is beyond kc + |k0| = 11 and stays invisible.
    y = [[1 + math.cos(2 * math.pi * 12 * c / n) for c in range(n)] for _ in range(n)]
    out = sim_reconstruct([sim_frames(y, h, (0, 5), PHASES, 1.0)], [(0, 5)], PHASES, 1.0, h)
    assert max_diff(out, [[1.0] * n for _ in range(n)]) < 1e-9


def test_equal_phases_or_zero_depth_raise():
    for phases, m in (((0.0, 0.0, 1.0), 1.0), (PHASES, 0.0)):
        try:
            inv3(mixing_matrix(phases, m))
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")


def test_inverse_of_mixing_matrix():
    a = mixing_matrix((0.1, 2.0, 3.7), 0.9)
    b = inv3(a)
    for i in range(3):
        for j in range(3):
            v = sum(a[i][t] * b[t][j] for t in range(3))
            assert abs(v - (1 if i == j else 0)) < 1e-12


def test_beats_widefield_wiener_with_noise():
    # A random image with every frequency up to radius 8 kept, seen with the
    # cutoff 5 and four stripe directions of length about 4.
    rng = random.Random(7)
    n, kc = 32, 5
    h = otf_incoherent(n, n, kc)
    big = dft2(rand_image(rng, n))
    for r in range(n):
        for c in range(n):
            if math.hypot(min(r, n - r), min(c, n - c)) > 8:
                big[r][c] = 0j
    x = [[z.real for z in row] for row in idft2(big)]
    k0s = [(0, 4), (4, 0), (3, 3), (3, -3)]
    sigma = 1e-2
    frames = []
    for k0 in k0s:
        clean = sim_frames(x, h, k0, PHASES, 1.0)
        frames.append([[[d[r][c] + e[r][c] for c in range(n)] for r in range(n)]
                       for d, e in ((d, gauss_noise(rng, (n, n), sigma)) for d in clean)])
    out = sim_reconstruct(frames, k0s, PHASES, 1.0, h, w=1e-3)
    wf = wiener_deconvolve(widefield(frames[0]), h, 1e-3)
    assert rel_err(out, x) < 0.5 * rel_err(wf, x)

History

Heintzmann and Cremer (1999) proposed lighting a fluorescent sample through a moved diffraction grating to improve the resolution. Gustafsson (2000) described the band separation and recombination for linear SIM and showed a lateral resolution gain of a factor of two. Gustafsson (2005) used the saturation of the dye to make harmonics of the pattern, which in principle gives no fixed limit. SIM is now a standard method for live-cell fluorescence imaging.

References

  1. M. G. L. Gustafsson, Surpassing the lateral resolution limit by a factor of two using structured illumination microscopy, Journal of Microscopy 198(2), 2000, 82 to 87, the frequency mixing by the stripes, the separation of the bands from several phases, the shift and recombination of the bands, and the factor of two
  2. R. Heintzmann and C. Cremer, Laterally modulated excitation microscopy: improvement of resolution by using a diffraction grating, Proceedings of SPIE 3568, 1999, 185 to 196, the excitation with a moved grating pattern and the reconstruction of the higher frequencies
  3. M. G. L. Gustafsson, Nonlinear structured-illumination microscopy: wide-field fluorescence imaging with theoretically unlimited resolution, Proceedings of the National Academy of Sciences 102(37), 2005, 13081 to 13086, saturated excitation, the harmonics of the illumination and the larger number of bands

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.average
  • a full proof of time.best
  • 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