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
- Model
- Real RAM
- Properties
- deterministicnot iterativelinearneeds known patternoptical method
- Evidence
- Proof sketchCode in 1 languages
- 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 on a periodic grid of pixels. The microscope has a known optical transfer function , real and symmetric, which is above the cutoff . For each stripe direction there are three frames, lit with , with a known integer stripe frequency , a known depth and three known phases. Frame is plus noise. The goal is an estimate of with as many object frequencies as the data contain. By the convolution theorem, the DFT of a frame is
so each frame mixes three copies of the object spectrum, two of them shifted by .
The algorithm
Let be the matrix with the rows , and the Wiener constant.
SIM-RECONSTRUCT(frames, k0s, phases, m, H, w)- 1
num ← 0, den ← w at every frequency k - 2
for each direction d with stripe frequency k0 - 3
(S0, S+, S-) ← M⁻¹ · (DFT of the three frames), at each k - 4
T+(k) ← S+(k + k0), H+(k) ← H(k + k0); T-(k) ← S-(k - k0), H-(k) ← H(k - k0) - 5
num ← num + H·S0 + H+·T+ + H-·T-; den ← den + H² + H+² + H-² - 6
X̂(k) ← num(k) / den(k) if den(k) > 0, else 0 - 7
return the real part of the inverse DFT of X̂
Line L3 separates the bands , and . Line L4 moves them back, so that : each is the object seen through a shifted OTF. Line L5 is the generalized Wiener filter for several measurements of the same through different transfer functions. The code uses the incoherent OTF of a circular pupil, with , and periodic indices, so must stay below half the image size.
Example
Take pixels, the cutoff (in DFT index units), the stripes , and the phases . The OTF along the stripes is , , and for . The sample is the grating , with the frequency beyond the cutoff.
- Widefield. The mean of the three frames is . Since , it is the constant : the grating is invisible.
- Raw frame. Each frame contains a moiré fringe at the frequency , inside the passband. Its DFT coefficient, divided by , has the modulus . Each frame also shows the stripes, at the frequency , with the modulus .
- Reconstruction. Without noise and with , the output equals to (a theorem, Claim 4 of the proof): the grating is fully recovered.
- Beyond the extended support. The grating at the frequency has . No band contains it, and the output is the constant .
A measurement with noise, from the test: an object with every frequency up to radius , the cutoff , four stripe directions , Gaussian noise with and . The relative error of the SIM result is ; the Wiener deconvolution of the widefield image with the same has . The extended support has frequencies, against for the widefield OTF.
Correctness
The proof is in proofs/correctness.md. The main facts, all theorems:
- The DFT of a frame is the sum of three bands, as in the formula of the problem.
- The phase matrix is invertible if and only if and the three phases are distinct modulo ; its determinant is a Vandermonde determinant. For equally spaced phases its columns are orthogonal, so the noise in the side bands is times the noise in the center band.
- After the shift, .
- Without noise the result has the DFT , where is the sum of the squared OTFs of all bands; with it is limited to the extended support .
- For real frames the estimate is real.
- The extended support lies inside the disk of radius . If , which holds when the same lens makes the stripes, this radius is at most .
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 pixels. The DFT is , and all frequency indices are taken modulo the image size. The OTF is real and symmetric, , so the PSF with is real. For one stripe direction with the integer frequency , the depth and the phases , frame is with , where means . Write .
Claim 1 (forward model). .
Proof. , and the DFT of is , by the definition of the DFT. So . The DFT of a periodic convolution is the product of the DFTs (the convolution theorem).
The test compares the frames, which the code computes with the DFT, with a direct periodic convolution.
Claim 2 (band separation). Let , and . Then with the rows , and is invertible if and only if and the three phases are distinct modulo .
Proof. The first part is Claim 1. Let . Multiplying row by gives the rows , so . Moving the last column to the front is a cyclic permutation of the columns, which has the sign , so this is times the Vandermonde determinant . It is if and only if or two are equal.
So line L3 recovers the three bands exactly at every . The code inverts once by the adjugate and raises an error when is tiny. For the equally spaced phases , the columns of are orthogonal, because , and their norms are , and . So for white noise of the same variance in each frame, the noise of the three bands is uncorrelated, and the noise of is times the noise of .
Claim 3 (shifted bands). Let and (line L4). Then and .
Proof. Substitute and in the definitions of and .
So each band is a copy of seen through a shifted OTF. Where but , the frequency of the object, which the widefield image does not contain, is measured.
Claim 4 (noise-free result). Let the directions each give three frames without noise, and let . Lines L5 to L7 give the image with the DFT where , and elsewhere. With it is with every frequency outside the extended support set to .
Proof. By Claims 2 and 3, the sum of line L5 is , with the three OTFs , and the denominator is .
The test checks this for three directions against the projection computed directly from the DFT of , 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, , so the estimate is real and the real part in line L7 removes only rounding.
Proof. The frames are real, so . The conjugate of row is with its last two entries swapped. Let swap the last two components. Then , and also . Since is invertible, : and . Hence , and the OTF paired with at is , the one paired with at . So the numerator at is the conjugate of the numerator at , and the denominator is symmetric.
Claim 6 (the support and the factor of two). If for , then , and contains every with and . If the stripes are made by the same optics, so that , the extended support lies inside the disk of radius , and it reaches along only when is at the cutoff.
Proof. means or for some , and in the last case by the triangle inequality. For , . The last statement follows from the first with .
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 , the mean of the three frames is .
Proof. for three equally spaced phases, so the side terms of Claim 1 cancel in the mean.
Complexity
Each direction needs three 2D DFTs of pixels, 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 time for directions. The extra space is 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 the extended cutoff is at most . 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 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 trades noise against resolution.
- Needs several frames. Three phases for each of directions, often , 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 , the phases and 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 , 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 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 singular. The code raises an error.
- Too small a Wiener constant. With near , frequencies where all OTFs are small get a large gain and the noise grows. Too large a smooths the result.
- Periodic wrap. The code works modulo the image size. If reaches half the size, the shifted bands wrap around.
- Reading the result as more than double. Linear SIM cannot pass frequencies beyond , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag BKPK9D Edit this page History Report an error Markdown