Algorithm Search⌘K

Algorithmadvanced

Nearest neighbor deconvolution

Also called neighboring plane deblurring.

Sharpen each plane of a widefield focal series by subtracting a fraction of the two adjacent observed planes, blurred by the one-plane defocus PSF. Fast, linear and approximate.

Time
Θ(p n m) worst · average · best
Space
Θ(n) extra
Where
m = the number of nonzero entries of a defocused PSF; n = the number of pixels per plane; p = the number of planes (n_z in the text)
Properties
deterministicnot exactnot iterativelinearnot nonnegative
Origin
David A. Agard, John W. Sedat, 1983

Nearest neighbor deconvolution removes out-of-focus light from a focal series taken with a widefield fluorescence microscope. Each plane yjy_j of the stack contains the in-focus image of plane jj of the object plus blurred light from all other planes. The method assumes that most of this haze comes from the two adjacent planes, and that the observed neighbors yj±1y_{j \pm 1} are good stand-ins for the unknown neighbors of the object. It subtracts them, blurred by the PSF of a source one plane away:

x^j=yj−c (h+1∗yj−1+h−1∗yj+1),\hat x_j = y_j - c\,\big(h_{+1} \ast y_{j-1} + h_{-1} \ast y_{j+1}\big),

with a constant cc chosen by eye; the analysis below suggests values at or below 1/21/2. Agard and Sedat used it in the early 1980s as a fast alternative to full 3D deconvolution. It costs two 2D convolutions per plane and no iterations. It is linear and is the first-order term of the Neumann series of the inverse, so it removes the fine detail of out-of-focus objects well. It cannot put the mean intensity back in the right plane, it creates negative values that must be clipped, and it adds the noise of three planes.

In plain words

A microscope that takes a stack of pictures at different focus depths sees each thing sharply in one picture and as a blurred glow in the pictures above and below. To clean one picture, take the picture just above and the one just below, blur them by the amount that one step of focus causes, and subtract a part of that from the picture. The glow from things in the neighbor slices goes away, and things in the slice itself stay sharp. The trick is a guess: the neighbor pictures are themselves glowing copies, not clean slices, and things two or more slices away are ignored. So the result is only approximately right, some pixels come out negative and are set to zero, and the total brightness of each slice is not correct. In return it is very fast.

The problem

The object is a stack x0,…,xnz−1x_0, \dots, x_{n_z - 1} of planes, each an image of nn pixels, recorded at equal focus steps. The data stack is

yj=∑khj−k∗xk+ej,y_j = \sum_k h_{j-k} \ast x_k + e_j,

where hdh_d is the 2D PSF of a point source dd planes away from focus (a slice of the 3D PSF, for example from the Gibson-Lanni model), ∗\ast is periodic 2D convolution with the PSF centered at index 00, and planes outside the stack are empty. The goal is a fast estimate of the in-focus content of each plane. A complete answer would solve the 3D deconvolution problem for the whole stack; this method gives up exactness to work one plane at a time.

The algorithm

  1. NEAREST-NEIGHBOR(y, h_prev, h_next, c, h0, alpha, clip) ▷ h_prev = h_{+1}, h_next = h_{-1}
  2. 1for j ← 0 to n_z - 1
  3. 2b ← 0
  4. 3if j > 0: b ← h_prev * y[j - 1] ▷ blurred plane below
  5. 4if j < n_z - 1: b ← b + h_next * y[j + 1] ▷ blurred plane above
  6. 5x[j] ← y[j] - c · b
  7. 6if h0 is given: x[j] ← Wiener(x[j], h0, alpha) ▷ optional in-focus filter
  8. 7if clip: x[j] ← max(x[j], 0)
  9. 8return x

Line L6 is the optional second step of Agard's scheme: a 2D filter that undoes the in-focus blur h0h_0, here H0‾ x^j/(∣H0∣2+α)\overline{H_0}\,\hat x_j/(|H_0|^2 + \alpha) in the Fourier domain (a Wiener filter with a constant noise-to-signal ratio α\alpha). Line L7 sets negative values to zero. End planes have one neighbor only.

Example

A measurement: 7 planes of 16×1616 \times 16 pixels with point sources of brightness 50, 100 and 100 in planes 2, 3 and 4, at different lateral positions. The PSF of a source dd planes away is a normalized Gaussian of width 0.7+1.5∣d∣0.7 + 1.5|d| pixels; each hdh_d sums to 1, as for a widefield microscope, where every plane receives all the light of every source. The target for each plane is h0∗xjh_0 \ast x_j, the in-focus image without haze. Error norms over the whole stack:

method stack error
raw data 44.0
c=0.3c = 0.3, clipped 24.3
c=0.45c = 0.45 20.5
c=0.45c = 0.45, clipped 17.1
c=0.5c = 0.5, clipped 15.4
c=0.6c = 0.6, clipped 13.5

The haze around each source in its neighbor planes is mostly gone, and clipping helps because the subtraction overshoots. The plane sums tell the other half of the story. In the data every plane sums to 250, the total brightness, whatever plane the sources are in. After the method with c=0.45c = 0.45 the interior planes sum to 25=(1−2⋅0.45)⋅25025 = (1 - 2 \cdot 0.45) \cdot 250 and the end planes to 137.5137.5, while the true plane sums are 0,0,50,100,100,0,00, 0, 50, 100, 100, 0, 0. The method has no way to tell which plane the mean light came from (Claim 4 of the proof). In this example a larger cc gives a smaller error, but the best cc depends on the object and the PSF.

Correctness

The full proof is in proofs/correctness.md. Write the blur as A=A0+E+R\mathcal A = \mathcal A_0 + \mathcal E + \mathcal R: the in-focus part, the two neighbor terms and the rest. Lines L1 to L5 compute (I−cE) y(\mathcal I - c\mathcal E)\,y.

  1. Error formula. For y=Axy = \mathcal A x, x^=(I−cE)Ax\hat x = (\mathcal I - c\mathcal E)\mathcal A x. In the ideal case h0=δh_0 = \delta and no light from planes two or more away, x^=x+(1−c)Ex−c E2x\hat x = x + (1 - c)\mathcal E x - c\,\mathcal E^2 x, which the test checks in exact rational arithmetic.
  2. Neumann series. In that case, with c=1c = 1 and ∥E∥<1\|\mathcal E\| < 1, the method is the Neumann series of (I+E)−1(\mathcal I + \mathcal E)^{-1} cut after the linear term, and the error is −E2x-\mathcal E^2 x, at most ∥E∥2∥x∥\|\mathcal E\|^2\|x\|.
  3. The mean is not restored. If the defocused PSFs sum to 1, an interior plane of a constant stack becomes (1−2c)(1 - 2c) times the constant. At low lateral frequencies E\mathcal E is not small, and the method only rescales; at high lateral frequencies the defocused OTFs are small and the method is accurate.
  4. No positivity. The output can be negative, so clipping is needed, and clipping makes the method nonlinear.
Proof: Nearest neighbor deconvolution is the first-order Neumann approximation of the inverse, exact up to second-order terms, and it cannot restore the axial position of the mean intensityfull

Setting. A stack has planes j=0,…,nz−1j = 0, \dots, n_z - 1, each an image with a periodic border. The imaging model is

yj=∑khj−k∗xk,y_j = \sum_k h_{j-k} \ast x_k,

with ∗\ast the periodic 2D convolution and hdh_d the PSF of a source dd planes away; planes outside the stack are empty. Write the blur as A=A0+E+R\mathcal A = \mathcal A_0 + \mathcal E + \mathcal R, where (A0x)j=h0∗xj(\mathcal A_0 x)_j = h_0 \ast x_j, (Ex)j=h+1∗xj−1+h−1∗xj+1(\mathcal E x)_j = h_{+1} \ast x_{j-1} + h_{-1} \ast x_{j+1} (terms outside the stack are 00), and R\mathcal R holds the offsets ∣d∣≥2|d| \ge 2. Lines L1 to L5 compute

x^=(I−c E) y.\hat x = (\mathcal I - c\,\mathcal E)\, y.

Line L6 applies a linear filter W\mathcal W plane by plane, and line L7 clips.

Claim 1 (linearity). Without line L7, y↦x^y \mapsto \hat x is linear.

Proof. Lines L3 to L5 are convolutions and linear combinations of the planes of yy, and W\mathcal W is linear. □\square

Claim 2 (exact error formula). For every stack xx and y=Axy = \mathcal A x,

x^=(I−cE)(A0+E+R) x.\hat x = (\mathcal I - c\mathcal E)(\mathcal A_0 + \mathcal E + \mathcal R)\, x.

In the ideal case h0=δh_0 = \delta and R=0\mathcal R = 0 this is

x^=x+(1−c) Ex−c E2x,\hat x = x + (1 - c)\,\mathcal E x - c\,\mathcal E^2 x,

and for c=1c = 1, x^−x=−E2x\hat x - x = -\mathcal E^2 x.

Proof. Substitute y=Axy = \mathcal A x into x^=(I−cE)y\hat x = (\mathcal I - c\mathcal E)y and expand (I−cE)(I+E)=I+(1−c)E−c E2(\mathcal I - c\mathcal E)(\mathcal I + \mathcal E) = \mathcal I + (1 - c)\mathcal E - c\,\mathcal E^2. □\square

The test checks the second formula in exact rational arithmetic.

Claim 3 (first-order Neumann approximation). In the ideal case, if ∥E∥<1\|\mathcal E\| < 1 in some operator norm, then A=I+E\mathcal A = \mathcal I + \mathcal E is invertible, A−1=∑k≥0(−E)k\mathcal A^{-1} = \sum_{k \ge 0} (-\mathcal E)^k, and the method with c=1c = 1 is this series cut after the linear term. Its error satisfies ∥x^−x∥≤∥E∥2∥x∥\|\hat x - x\| \le \|\mathcal E\|^2 \|x\|.

Proof. The Neumann series converges for ∥E∥<1\|\mathcal E\| < 1, and (I+E)∑k<K(−E)k=I−(−E)K(\mathcal I + \mathcal E)\sum_{k<K} (-\mathcal E)^k = \mathcal I - (-\mathcal E)^K tends to I\mathcal I. The first two terms are I−E\mathcal I - \mathcal E. The bound follows from Claim 2 and ∥E2∥≤∥E∥2\|\mathcal E^2\| \le \|\mathcal E\|^2. □\square

For c≠1c \ne 1 the error has the first-order term (1−c)Ex(1 - c)\mathcal E x, and a value c<1c < 1 trades this term against the second-order term c E2xc\,\mathcal E^2 x.

Claim 4 (the mean intensity). Suppose every hdh_d is nonnegative with ∑h±1=1\sum h_{\pm 1} = 1 (the defocused PSF of a widefield microscope keeps the energy of the source). If yy is a constant vv on every plane, then x^j=(1−2c) v\hat x_j = (1 - 2c)\,v on every interior plane 0<j<nz−10 < j < n_z - 1, and x^j=(1−c) v\hat x_j = (1 - c)\,v on the two end planes (before L6 and L7).

Proof. The convolution of a constant image with a kernel of sum 11 is the same constant. An interior plane has two neighbors, an end plane one. □\square

In Fourier terms, at lateral frequency 00 the operator E\mathcal E multiplies by the neighbor sums of the plane values, with weight 11 on each side, so its norm there is close to 22 for a long stack and Claim 3 does not apply. The method subtracts a fixed fraction of the neighbors and does not find which plane the light came from. At high lateral frequencies the defocused OTFs are small, ∥E∥\|\mathcal E\| is small there, and Claim 3 makes the method accurate. So nearest neighbor deconvolution removes the fine detail of out-of-focus planes and leaves a scaled mean.

Claim 5 (no positivity). x^\hat x can be negative for a nonnegative yy.

Proof. Take c=1/2c = 1/2, one interior plane jj of zeros and both neighbors constant 11. Then x^j=0−12(1+1)=−1\hat x_j = 0 - \tfrac12 (1 + 1) = -1. □\square

This is why line L7 clips; with clipping the method is no longer linear. ■\blacksquare

Complexity

In the real-RAM model each plane needs two 2D convolutions and a linear combination. With mm nonzero entries in a defocused PSF, a direct convolution costs Θ(nm)\Theta(nm); with the FFT and the two OTFs computed once, Θ(nlog⁡n)\Theta(n \log n). So the whole stack costs Θ(nznm)\Theta(n_z n m) or Θ(nznlog⁡n)\Theta(n_z n \log n), with no iterations. The optional filter of L6 adds Θ(nlog⁡n)\Theta(n \log n) per plane. Beyond the output, the extra space is Θ(n)\Theta(n) for the blurred neighbors. A plane can be processed as soon as it and its two neighbors are recorded, so the method works on a stream of planes.

Properties

  • Linear in yy without clipping, and a fixed 3D filter: a convolution in zz with three taps.
  • Not exact, even without noise. The error is first order in the neighbor PSFs for c≠1c \ne 1 and second order for c=1c = 1.
  • No noise model. The noise of the result is the noise of yjy_j plus cc times the blurred noise of two other planes; the blur smooths the subtracted noise, so the increase is modest, but the L6 filter amplifies high frequencies.
  • Not quantitative: plane sums and the axial position of diffuse objects are wrong.

Variants and improvements

  • No neighbor deconvolution. Use no neighbor planes at all: subtract a blurred copy of the plane itself, x^j=yj−c hblur∗yj\hat x_j = y_j - c\, h_{\mathrm{blur}} \ast y_j, which is unsharp masking with a defocused PSF. It needs only one image per plane and is even more approximate.
  • More neighbors. Subtract planes j±2j \pm 2 with their PSFs as well. This lowers the error from distant planes but adds noise and, by Claim 2 of the proof, more higher-order terms.
  • Fourier domain form. All steps are convolutions, so the method can be written as one 3D filter on the FFT of the stack.
  • Full 3D deconvolution. Constrained iterative methods, such as Richardson-Lucy and RLTV, use the whole 3D PSF and keep the estimate nonnegative. They are quantitative but cost many 3D FFTs.

When to use it

Use it for a quick look at a widefield stack, for a live preview during acquisition, or when only a few planes are recorded. It improves the contrast of small structures, such as chromosomes, vesicles or filaments, near their focal plane. Do not use it for measurements of intensity, volume or axial position, or when objects are large and diffuse. For quantitative work use a constrained iterative 3D method.

Pitfalls

  • The defocused PSF must match the focus step and the optics. A PSF that is too narrow subtracts sharp copies of neighbor features and creates dark ghosts; a PSF that is too wide leaves the haze.
  • Depth-dependent aberration, such as the spherical aberration of the Gibson-Lanni model, changes h±1h_{\pm 1} with depth. A single pair of PSFs is then wrong for part of the stack.
  • A large cc removes too much light from interior planes; for c>1/2c > 1/2 a uniform region becomes negative and is clipped to zero.
  • The end planes have one neighbor and are treated differently, so their brightness does not match the interior planes.
  • The L6 filter with a small α\alpha amplifies the noise at frequencies where ∣H0∣|H_0| is small.

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
nearest_neighbor_deconvolution.py 68 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nearest-neighbor-deconvolution/. The authors are listed in prov/03GAAZ.jsonl.
"""Nearest neighbor deconvolution of a widefield focal series, after Agard (1984).

A stack is a list of planes y[0..nz-1], each an image (a list of rows). The
imaging model is y_j = sum_k h_{j-k} * x_k, with * the periodic 2D convolution
and h_d the 2D PSF of a source d planes away; planes outside the stack are
empty. Nearest neighbor deconvolution keeps only the two neighbors, and uses
the observed neighbors in place of the unknown ones:

    x_j = y_j - c (h_{+1} * y_{j-1} + h_{-1} * y_{j+1}),

optionally followed by a 2D Wiener filter with the in-focus PSF h_0 and by
clipping at zero.
"""

from imgkit import circ_conv2, dft2, idft2, new_image


def blur_stack(x, psfs):
    """y_j = sum_k psfs[j - k] * x_k over the offsets present in the dict psfs, zero outside the stack."""
    nz = len(x)
    n1, n2 = len(x[0]), len(x[0][0])
    out = []
    for j in range(nz):
        acc = new_image(n1, n2, 0)
        for d, h in psfs.items():
            k = j - d
            if 0 <= k < nz:
                b = circ_conv2(x[k], h)
                acc = [[p + q for p, q in zip(ra, rb)] for ra, rb in zip(acc, b)]
        out.append(acc)
    return out


def wiener_2d(img, h0, alpha):
    """The 2D filter conj(H0) Y / (|H0|^2 + alpha), real part. alpha = 0 is the plain inverse."""
    hf = dft2(h0)
    yf = dft2(img)
    xf = [[hk.conjugate() * yk / (abs(hk) ** 2 + alpha) for hk, yk in zip(rh, ry)] for rh, ry in zip(hf, yf)]
    return [[v.real for v in row] for row in idft2(xf)]


def nearest_neighbor(y, h_prev, h_next, c, h0=None, alpha=0.0, clip=False):
    """Nearest neighbor deconvolution of the stack y.

    h_prev is the PSF h_{+1} that carries plane j - 1 into plane j, h_next the
    PSF h_{-1} that carries plane j + 1 into plane j, and c the subtraction
    constant. With h0 given, each plane is then filtered by wiener_2d(., h0,
    alpha). With clip, negative values are set to 0.
    """
    nz = len(y)
    n1, n2 = len(y[0]), len(y[0][0])
    out = []
    for j in range(nz):  # @line L1
        b = new_image(n1, n2, 0)  # @line L2
        if j > 0:
            b = circ_conv2(y[j - 1], h_prev)  # @line L3
        if j < nz - 1:
            t = circ_conv2(y[j + 1], h_next)  # @line L4
            b = [[p + q for p, q in zip(ra, rb)] for ra, rb in zip(b, t)]
        xj = [[yv - c * bv for yv, bv in zip(ry, rb)] for ry, rb in zip(y[j], b)]  # @line L5
        if h0 is not None:
            xj = wiener_2d(xj, h0, alpha)  # @line L6
        if clip:
            xj = [[max(v, 0) for v in row] for row in xj]  # @line L7
        out.append(xj)
    return out  # @line L8
test_nearest_neighbor_deconvolution.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nearest-neighbor-deconvolution/. The authors are listed in prov/03GAAZ.jsonl.

import math
import random
from fractions import Fraction

from imgkit import circ_conv2, img_norm
from nearest_neighbor_deconvolution import blur_stack, nearest_neighbor, wiener_2d


def gpsf(n, sigma):
    h = [[0.0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            di = i if i <= n // 2 else i - n
            dj = j if j <= n // 2 else j - n
            h[i][j] = math.exp(-(di * di + dj * dj) / (2 * sigma * sigma))
    s = sum(map(sum, h))
    return [[v / s for v in r] for r in h]


def delta(n):
    return [[1 if (i, j) == (0, 0) else 0 for j in range(n)] for i in range(n)]


def rand_stack(rng, nz, n, lo=-1.0, hi=1.0):
    return [[[rng.uniform(lo, hi) for _ in range(n)] for _ in range(n)] for _ in range(nz)]


def stack_inner(a, b):
    return sum(p * q for pa, pb in zip(a, b) for ra, rb in zip(pa, pb) for p, q in zip(ra, rb))


def stack_norm(a):
    return math.sqrt(stack_inner(a, a))


def stack_lin(alpha, a, beta, b):
    return [[[alpha * p + beta * q for p, q in zip(ra, rb)] for ra, rb in zip(pa, pb)] for pa, pb in zip(a, b)]


def mirror(h):
    n1, n2 = len(h), len(h[0])
    return [[h[(-i) % n1][(-j) % n2] for j in range(n2)] for i in range(n1)]


def test_blur_stack_adjoint():
    # The adjoint of y_j = sum_k h_{j-k} * x_k is x_k = sum_j h~_{j-k} * y_j, the blur with mirrored PSFs and offsets.
    rng = random.Random(1)
    n, nz = 6, 4
    psfs = {d: gpsf(n, 0.6 + abs(d)) for d in (-1, 0, 1)}
    psfs[1] = [[v * (1 + 0.1 * i) for v in row] for i, row in enumerate(psfs[1])]
    adj = {-d: mirror(h) for d, h in psfs.items()}
    x, y = rand_stack(rng, nz, n), rand_stack(rng, nz, n)
    ax = blur_stack(x, psfs)
    gap = abs(stack_inner(ax, y) - stack_inner(x, blur_stack(y, adj)))
    assert gap <= 1e-10 * stack_norm(ax) * stack_norm(y)


def test_formula_on_each_plane():
    rng = random.Random(2)
    n, nz = 5, 4
    hp, hn = gpsf(n, 1.0), gpsf(n, 1.3)
    y = rand_stack(rng, nz, n, 0, 5)
    c = 0.45
    x = nearest_neighbor(y, hp, hn, c)
    for j in range(nz):
        for i in range(n):
            for q in range(n):
                b = 0.0
                if j > 0:
                    b += circ_conv2(y[j - 1], hp)[i][q]
                if j < nz - 1:
                    b += circ_conv2(y[j + 1], hn)[i][q]
                assert abs(x[j][i][q] - (y[j][i][q] - c * b)) < 1e-12


def test_exact_second_order_identity():
    # With h_0 = delta and h_d = 0 for |d| >= 2, y = (I + E) x and the method is I - cE, so
    # x_hat = x + (1 - c) E x - c E^2 x exactly.
    n, nz = 3, 4
    rng = random.Random(3)
    hp = [[Fraction(rng.randint(0, 4), 20) for _ in range(n)] for _ in range(n)]
    hn = [[Fraction(rng.randint(0, 4), 20) for _ in range(n)] for _ in range(n)]
    x = [[[Fraction(rng.randint(0, 9)) for _ in range(n)] for _ in range(n)] for _ in range(nz)]
    e = {1: hp, -1: hn}
    y = blur_stack(x, {0: delta(n), 1: hp, -1: hn})
    ex = blur_stack(x, e)
    eex = blur_stack(ex, e)
    for c in (Fraction(1), Fraction(1, 2), Fraction(9, 20)):
        got = nearest_neighbor(y, hp, hn, c)
        want = [[[xv + (1 - c) * a - c * b for xv, a, b in zip(rx, ra, rb)]
                  for rx, ra, rb in zip(px, pa, pb)] for px, pa, pb in zip(x, ex, eex)]
        assert got == want


def test_zero_neighbor_psfs_give_the_data():
    rng = random.Random(4)
    n = 4
    zero = [[0.0] * n for _ in range(n)]
    y = rand_stack(rng, 3, n, 0, 1)
    assert nearest_neighbor(y, zero, zero, 0.5) == y


def test_linear_without_clipping():
    rng = random.Random(5)
    n, nz = 5, 3
    hp, hn = gpsf(n, 1.0), gpsf(n, 1.0)
    a, b = rand_stack(rng, nz, n), rand_stack(rng, nz, n)
    lhs = nearest_neighbor(stack_lin(2.0, a, -3.0, b), hp, hn, 0.45)
    rhs = stack_lin(2.0, nearest_neighbor(a, hp, hn, 0.45), -3.0, nearest_neighbor(b, hp, hn, 0.45))
    assert stack_norm(stack_lin(1.0, lhs, -1.0, rhs)) < 1e-12 * stack_norm(rhs)


def test_uniform_stack_keeps_one_minus_two_c():
    # Each defocused PSF sums to 1, so an interior plane of a uniform stack becomes (1 - 2c) times its value.
    n, nz = 4, 5
    hp, hn = gpsf(n, 1.5), gpsf(n, 1.5)
    y = [[[7.0] * n for _ in range(n)] for _ in range(nz)]
    for c in (0.3, 0.45, 0.5):
        x = nearest_neighbor(y, hp, hn, c)
        for j in range(1, nz - 1):
            assert all(abs(v - 7.0 * (1 - 2 * c)) < 1e-12 for row in x[j] for v in row)
        assert all(abs(v - 7.0 * (1 - c)) < 1e-12 for row in x[0] for v in row)


def test_wiener_step_inverts_an_invertible_in_focus_psf():
    rng = random.Random(6)
    n = 8
    h0 = [[0.0] * n for _ in range(n)]
    h0[0][0], h0[1][0], h0[n - 1][0], h0[0][1], h0[0][n - 1] = 0.6, 0.1, 0.1, 0.1, 0.1
    x = [[rng.uniform(0, 1) for _ in range(n)] for _ in range(n)]
    back = wiener_2d(circ_conv2(x, h0), h0, 0.0)
    assert img_norm([[p - q for p, q in zip(ra, rb)] for ra, rb in zip(back, x)]) < 1e-10 * img_norm(x)
    y = [[[rng.uniform(0, 1) for _ in range(n)] for _ in range(n)] for _ in range(2)]
    zero = [[0.0] * n for _ in range(n)]
    out = nearest_neighbor(y, zero, zero, 0.5, h0=h0, alpha=0.0, clip=True)
    for j in range(2):
        want = [[max(v, 0) for v in row] for row in wiener_2d(y[j], h0, 0.0)]
        assert img_norm([[p - q for p, q in zip(ra, rb)] for ra, rb in zip(out[j], want)]) < 1e-12


def test_out_of_focus_haze_is_reduced():
    # A measurement: three point sources in a 5-plane stack of 8 x 8 planes, PSF widths 0.7 + 1.5 |d| pixels.
    n, nz = 8, 5
    psfs = {d: gpsf(n, 0.7 + 1.5 * abs(d)) for d in range(-4, 5)}
    x = [[[0.0] * n for _ in range(n)] for _ in range(nz)]
    x[2][2][2] = 100.0
    x[3][5][6] = 100.0
    x[1][4][1] = 50.0
    y = blur_stack(x, psfs)
    target = [circ_conv2(p, psfs[0]) for p in x]
    est = nearest_neighbor(y, psfs[1], psfs[-1], 0.45, clip=True)
    err_raw = stack_norm(stack_lin(1.0, y, -1.0, target))
    err_nn = stack_norm(stack_lin(1.0, est, -1.0, target))
    assert err_nn < 0.6 * err_raw

History

Agard and Sedat (1983) studied the 3D architecture of polytene chromosome nuclei from focal series, and Agard (1984) reviewed optical sectioning microscopy, with the nearest neighbor scheme as the fast option next to constrained iterative 3D deconvolution. McNally, Karpova, Cooper and Conchello (1999) reviewed it next to the no neighbor and the constrained iterative methods.

References

  1. D. A. Agard, Optical sectioning microscopy, cellular architecture in three dimensions, Annual Review of Biophysics and Bioengineering 13, 1984, pages 191 to 219
  2. David A. Agard and John W. Sedat, Three-dimensional architecture of a polytene nucleus, Nature 302(5910), 1983, pages 676 to 681
  3. James G. McNally, Tatiana Karpova, John Cooper and Jose Angel Conchello, Three-dimensional imaging by deconvolution microscopy, Methods 19(3), 1999, pages 373 to 385 (nearest neighbor and no neighbor methods next to the iterative ones)

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