Algorithm Search⌘K

Algorithmadvanced

Maximum likelihood emitter localization

Also called MLE single-molecule fitting.

Fit a pixel-integrated Gaussian PSF to the photon counts of one emitter by Newton steps on the Poisson likelihood. For large photon counts and a correct PSF it nears the Cramer-Rao bound.

Time
Θ(K P) worst · averageΘ(P) best
Space
Θ(P) extra
Where
K = the number of iterations; P = the number of pixels in the fitting window
Properties
deterministiciterativemodel basedmonotone likelihoodreturns uncertainty
Origin
Carlas S. Smith, Nikolai Joseph, Bernd Rieger, Keith A. Lidke, Kim I. Mortensen, L. Stirling Churchman, James A. Spudich, Henrik Flyvbjerg, 2010

Maximum likelihood localization estimates the position of one fluorescent emitter from a small camera image to a precision far below the width of the point spread function (PSF). It models the expected photon count of each pixel as a Gaussian PSF integrated over the pixel, times the photon count of the emitter, plus a constant background, and treats the counts as independent Poisson values. It then finds the center, the photon count and the background that make the observed counts most likely, by Newton steps on the negative log likelihood with a line search. It also returns the inverse Fisher information at the estimate, the Cramer-Rao bound, as an estimate of the uncertainty. For large photon counts and a correct PSF model, the variance of the estimate comes close to this bound, which no unbiased estimator can beat; for small counts or a wrong PSF it does not. It is the fitting step of single-molecule localization microscopy.

In plain words

A single glowing molecule shows up on a camera as a small blurred spot a few pixels wide. Each pixel counts the photons that hit it, and the counts are random. The method guesses where the spot's center is, how bright it is and how bright the background is, and predicts the count of each pixel. It then asks how likely the real counts are under that guess, and improves the guess until the likelihood cannot get higher. Because many photons together pin down the center, the center can be found to a few nanometers, even though the spot is hundreds of nanometers wide.

The problem

The input is a window of PP pixels with photon counts cc around one emitter, and the known PSF width ss in pixels. The model is μ(u,v)=NEx(u)Ey(v)+b\mu(u, v) = N E_x(u) E_y(v) + b, where pixel (v,u)(v, u) covers a unit square, Ex(u)=12[erf⁡((u−x0+12)/(2s))−erf⁡((u−x0−12)/(2s))]E_x(u) = \frac12[\operatorname{erf}((u - x_0 + \frac12)/(\sqrt2 s)) - \operatorname{erf}((u - x_0 - \frac12)/(\sqrt2 s))] is the share of the PSF in column uu, and EyE_y is the same for the rows. The counts are independent Poisson with the means μ\mu. The goal is the maximum likelihood estimate of θ=(x0,y0,N,b)\theta = (x_0, y_0, N, b), that is the minimizer of L(θ)=∑(μ−clog⁡μ)L(\theta) = \sum(\mu - c\log\mu), and its uncertainty.

The algorithm

  1. MLE-LOCALIZE(c, s)
  2. 1θ ← (centroid of c - b₀, total of c - b₀, b₀), with b₀ the mean of the border pixels
  3. 2repeat at most max_iter times
  4. 3compute L, ∇L, ∇²L and the Fisher information I(θ) = Σ ∇μ ∇μᵀ / μ
  5. 4if ∇²L is positive definite: δ ← -(∇²L)⁻¹ ∇L ▷ Newton step, by Cholesky
  6. 5else δ ← -I(θ)⁻¹ ∇L ▷ Fisher scoring step
  7. 6halve t from min(1, 1/|δ_center|) until N > 0, the center is in the window and L(θ + tδ) ≤ L(θ) + 10⁻⁴ t ∇Lᵀδ
  8. 7θ ← θ + tδ; stop when the step is below the tolerance
  9. 8crb ← I(θ)⁻¹
  10. 9return θ, crb

In line L6, ∣δcenter∣|\delta_{\text{center}}| is the larger of ∣δx0∣|\delta_{x_0}| and ∣δy0∣|\delta_{y_0}|, so a step moves the center by at most one pixel. The gradient is ∇L=∑(1−c/μ)∇μ\nabla L = \sum (1 - c/\mu)\nabla\mu and the Hessian is ∑(c/μ2)∇μ∇μT+(1−c/μ)∇2μ\sum (c/\mu^2)\nabla\mu\nabla\mu^T + (1 - c/\mu)\nabla^2\mu. The derivatives of ExE_x are differences of the normal density gg: Ex′=g(t2)−g(t1)E_x' = g(t_2) - g(t_1) and Ex′′=(t2g(t2)−t1g(t1))/s2E_x'' = (t_2 g(t_2) - t_1 g(t_1))/s^2, with t1,2=u−x0±12t_{1,2} = u - x_0 \pm \frac12.

Example

Take a 9×99 \times 9 window, s=1.3s = 1.3 pixels and the true θ=(4.3,3.8,500,2)\theta = (4.3, 3.8, 500, 2). One Poisson image (seed 22 in the test file) has 676676 counts. The start from line L1 is (4.400,3.783,515.75,2.31)(4.400, 3.783, 515.75, 2.31). The iterates are:

step x0x_0 y0y_0 NN bb LL
0 4.4000 3.7832 515.75 2.3125 −1118.4983-1118.4983
1 4.4468 3.7881 510.17 2.0370 −1119.4874-1119.4874
2 4.4457 3.7881 509.57 2.0647 −1119.4954-1119.4954
3 4.4457 3.7881 509.56 2.0650 −1119.4954-1119.4954

The returned bound gives the standard deviations 0.0700.070, 0.0700.070, 26.026.0 and 0.2250.225. The error in x0x_0 is 0.1460.146 pixels, about two standard deviations: one image is one random draw. Over 200200 images (seed 1111) the sample variances of x0x_0 and y0y_0 are 1.081.08 and 1.021.02 times the bound (a measurement). Without noise, that is with c=μ(θ)c = \mu(\theta), the fit returns θ\theta to 10−610^{-6} from the centroid start and from three poor starts.

With s=100s = 100 nm, pixels of 100100 nm, N=1000N = 1000 and almost no background, the bound on the standard deviation of x0x_0 is 3.29143.2914 nm, against s/N=3.1623s/\sqrt N = 3.1623 nm for infinitely small pixels.

Correctness

The proof is in proofs/correctness.md. The facts:

  1. Derivatives (theorem). The formulas for Ex′E_x', Ex′′E_x'', ∇L\nabla L and ∇2L\nabla^2 L are exact, and I(θ)=E[∇2L]I(\theta) = \mathbb E[\nabla^2 L].
  2. Descent (theorem). The Newton step, when the Hessian is positive definite, and the scoring step otherwise are descent directions, and the line search ends with a decrease of LL. So LL never increases.
  3. Noise-free data (theorem). For c=μ(θ∗)c = \mu(\theta^*), θ∗\theta^* is a global minimizer of LL, and a strict local minimizer when I(θ∗)I(\theta^*) is positive definite.
  4. The bound (theorem). Every unbiased estimator has a covariance of at least I(θ)−1I(\theta)^{-1}, the Cramer-Rao bound. The maximum likelihood estimate reaches it only asymptotically, for large photon counts and a correct model (a standard theorem). For a finite count the closeness is a measurement.
  5. Convergence. Convergence to a stationary point and the local quadratic rate of Newton steps are standard results for line search methods, not proved in the proof file.
Proof: The derivatives are exact, every step lowers the Poisson negative log likelihood, noise-free data give the true parameters, and the returned matrix is the Cramer-Rao boundfull

Setting. Pixel (v,u)(v, u) covers [u−12,u+12]×[v−12,v+12][u - \frac12, u + \frac12] \times [v - \frac12, v + \frac12]. For θ=(x0,y0,N,b)\theta = (x_0, y_0, N, b) the expected count is μ=NEx(u)Ey(v)+b\mu = N E_x(u) E_y(v) + b with

Ex(u)=∫u−1/2u+1/2g(ξ−x0) dξ=12[erf⁡u−x0+1/22s−erf⁡u−x0−1/22s],E_x(u) = \int_{u - 1/2}^{u + 1/2} g(\xi - x_0)\, d\xi = \tfrac12\Bigl[\operatorname{erf}\tfrac{u - x_0 + 1/2}{\sqrt2 s} - \operatorname{erf}\tfrac{u - x_0 - 1/2}{\sqrt2 s}\Bigr],

where g(t)=e−t2/(2s2)/(2πs)g(t) = e^{-t^2/(2s^2)}/(\sqrt{2\pi}s) is the normal density, and the same for EyE_y. The counts cc are independent Poisson with the means μ\mu. The negative log likelihood, without the constant ∑log⁡c!\sum \log c!, is L(θ)=∑(μ−clog⁡μ)L(\theta) = \sum (\mu - c\log\mu).

Claim 1 (pixel derivatives). With t1=u−x0+12t_1 = u - x_0 + \frac12 and t2=u−x0−12t_2 = u - x_0 - \frac12,

∂Ex∂x0=g(t2)−g(t1),∂2Ex∂x02=t2s2g(t2)−t1s2g(t1).\frac{\partial E_x}{\partial x_0} = g(t_2) - g(t_1), \qquad \frac{\partial^2 E_x}{\partial x_0^2} = \frac{t_2}{s^2} g(t_2) - \frac{t_1}{s^2} g(t_1).

Proof. Ex=G(t1)−G(t2)E_x = G(t_1) - G(t_2) with GG the normal distribution function, G′=gG' = g, and ∂ti/∂x0=−1\partial t_i/\partial x_0 = -1. So ∂Ex/∂x0=−g(t1)+g(t2)\partial E_x/\partial x_0 = -g(t_1) + g(t_2). Then g′(t)=−(t/s2)g(t)g'(t) = -(t/s^2)g(t), so ∂g(ti)/∂x0=(ti/s2)g(ti)\partial g(t_i)/\partial x_0 = (t_i/s^2)g(t_i). □\square

Claim 2 (gradient, Hessian, Fisher information).

∇L=∑(1−cμ)∇μ,∇2L=∑cμ2∇μ ∇μT+(1−cμ)∇2μ,\nabla L = \sum \Bigl(1 - \frac c\mu\Bigr)\nabla\mu, \qquad \nabla^2 L = \sum \frac{c}{\mu^2}\nabla\mu\,\nabla\mu^T + \Bigl(1 - \frac c\mu\Bigr)\nabla^2\mu,

and the Fisher information is I(θ)=E[∇2L]=∑∇μ ∇μT/μI(\theta) = \mathbb E[\nabla^2 L] = \sum \nabla\mu\,\nabla\mu^T/\mu. Here ∇μ=(NEx′Ey, NExEy′, ExEy, 1)\nabla\mu = (N E_x' E_y,\ N E_x E_y',\ E_x E_y,\ 1), and the nonzero entries of ∇2μ\nabla^2\mu are NEx′′EyN E_x''E_y, NExEy′′N E_x E_y'', NEx′Ey′N E_x'E_y', Ex′EyE_x'E_y and ExEy′E_xE_y' in the obvious places.

Proof. Differentiate μ−clog⁡μ\mu - c\log\mu once and twice by the chain rule, and μ\mu by the product rule with Claim 1. Taking the expectation with E[c]=μ\mathbb E[c] = \mu removes the second term of the Hessian. □\square

The test compares the gradient and the Hessian with central differences, and checks that the Hessian at c=μc = \mu equals II.

Claim 3 (descent). Let μ>0\mu > 0 at all pixels. If ∇2L\nabla^2 L is positive definite, the Newton step δ=−(∇2L)−1∇L\delta = -(\nabla^2 L)^{-1}\nabla L satisfies ∇LTδ<0\nabla L^T\delta < 0 unless ∇L=0\nabla L = 0. If not, and the four vectors (∂iμ)(\partial_i\mu) over the pixels are linearly independent, I(θ)I(\theta) is positive definite and the scoring step δ=−I−1∇L\delta = -I^{-1}\nabla L has the same property. Then the backtracking of line L6 ends with a t>0t > 0 for which L(θ+tδ)≤L(θ)+10−4t ∇LTδ<L(θ)L(\theta + t\delta) \le L(\theta) + 10^{-4} t\,\nabla L^T\delta < L(\theta).

Proof. For a positive definite AA, ∇LTδ=−∇LTA−1∇L<0\nabla L^T\delta = -\nabla L^T A^{-1}\nabla L < 0 when ∇L≠0\nabla L \ne 0. zTIz=∑(zT∇μ)2/μz^T I z = \sum (z^T\nabla\mu)^2/\mu is 00 only if zT∇μ=0z^T\nabla\mu = 0 at every pixel, which the linear independence excludes for z≠0z \ne 0. The set where N>0N > 0, the center lies in the image and all μ>0\mu > 0 is open and contains θ\theta, and LL is differentiable there, so L(θ+tδ)=L(θ)+t∇LTδ+o(t)L(\theta + t\delta) = L(\theta) + t\nabla L^T\delta + o(t); for small tt the point is in the set and the inequality holds because 10−4<110^{-4} < 1. Halving tt reaches such a tt. □\square

So the sequence L(θk)L(\theta_k) never increases, which the test checks. The loop stops when a step is below the tolerance. With steps from matrices whose eigenvalues stay in a fixed positive range, the standard theory of line search methods gives ∇L(θk)→0\nabla L(\theta_k) \to 0; near a minimizer with a positive definite Hessian the full Newton step is accepted and the convergence is quadratic. These two facts are standard results and are not proved here. The limit on the move of the center (one pixel per step) only shortens steps, so it keeps the descent property.

Claim 4 (noise-free data). If c=μ(θ∗)c = \mu(\theta^*), then θ∗\theta^* is a global minimizer of LL, and a strict local minimizer if I(θ∗)I(\theta^*) is positive definite.

Proof. With μ∗=μ(θ∗)\mu^* = \mu(\theta^*) and r=μ/μ∗r = \mu/\mu^* at each pixel, L(θ)−L(θ∗)=∑μ∗(r−1−log⁡r)≥0L(\theta) - L(\theta^*) = \sum \mu^*(r - 1 - \log r) \ge 0, since r−1−log⁡r≥0r - 1 - \log r \ge 0 for r>0r > 0. At θ∗\theta^* the gradient is 00, since 1−c/μ=01 - c/\mu = 0 at every pixel, and the Hessian is I(θ∗)I(\theta^*) by Claim 2. A zero gradient and a positive definite Hessian give a strict local minimizer. □\square

The test starts from the centroid guess and from three poor starts, and all four runs return θ∗\theta^* to 10−610^{-6}.

Claim 5 (the bound). For any unbiased estimator θ^\hat\theta of θ\theta from the counts, Cov⁡θ^⪰I(θ)−1\operatorname{Cov}\hat\theta \succeq I(\theta)^{-1}. The code returns I(θ^)−1I(\hat\theta)^{-1}.

Proof. This is the Cramer-Rao bound for the product of Poisson laws, whose Fisher information is the II of Claim 2. □\square

The maximum likelihood estimate reaches the bound only asymptotically, as the photon count grows and when the PSF model is correct; for small counts it can be biased and its variance can differ from the bound. The test measures the variance over 200200 Poisson images with about 500500 signal photons and finds it within 3030 percent of I−1I^{-1} (a measurement, not a theorem).

Claim 6 (no pixels, no background). If the pixels are infinitely small and b=0b = 0, the information about x0x_0 is N/s2N/s^2, so the bound on the standard deviation is s/Ns/\sqrt N.

Proof. The photon positions then form a Poisson process with the intensity Ng(ξ−x0)N g(\xi - x_0) (times the same in yy), and the information about x0x_0 is N∫g′(t)2/g(t) dt=N E[(t/s2)2]=N/s2N\int g'(t)^2/g(t)\,dt = N\,\mathbb E[(t/s^2)^2] = N/s^2 for a normal tt with variance s2s^2. □\square

With unit pixels of side aa the information is smaller. The test computes the bound for s=a=100s = a = 100 nm, N=1000N = 1000 and a background of 10−610^{-6} on a 15×1515 \times 15 grid and finds 3.29143.2914 nm. This agrees to 10−310^{-3} nm with (s2+a2/12)/N\sqrt{(s^2 + a^2/12)/N}, which is a numerical observation for this case, not an identity. ■\blacksquare

Complexity

One iteration evaluates two error functions and two exponentials per row and per column, then sums 4×44 \times 4 outer products over the PP pixels: Θ(P)\Theta(P) time. The 4×44 \times 4 Cholesky factorization costs O(1)O(1), and each trial of the line search costs Θ(P)\Theta(P). With KK iterations and a bounded number of halvings per iteration, a fit costs Θ(KP)\Theta(KP), and KK is usually below 1010. The extra space is Θ(P)\Theta(P) for the derivatives of the pixels. In a localization movie the fits of different spots are independent, so they run in parallel; Smith and coworkers ran them on a graphics processor.

Properties

  • Uses the right noise model. Photon counts are Poisson, so pixels with more light have more noise. Least squares weights all pixels the same and loses precision; Mortensen and coworkers found that its variance is larger than the bound.
  • Monotone. The negative log likelihood never increases (Claim 3 of the proof).
  • Gives an uncertainty. The bound at the estimate is a cheap estimate of the precision of each spot, useful for filtering and for rendering.
  • Model dependent. The Gaussian PSF is an approximation of the real PSF. A wrong PSF width, a tilted dipole or defocus bias the result.
  • Local. Like every Newton method, it needs a start in the basin of the true minimum. The centroid start is good for one isolated spot.

Variants and improvements

  • Exact PSF models. Replace the Gaussian by an Airy or vectorial PSF, or by a measured PSF, at a higher cost per pixel.
  • Free width. Fit ss too, as a fifth parameter, to catch out-of-focus spots and overlapping emitters.
  • 3D by astigmatism. With a cylindrical lens the widths sxs_x and sys_y depend on the depth zz, and fitting both gives zz.
  • Camera noise. For EMCCD cameras the excess noise factor doubles the variance at high gain; for sCMOS cameras each pixel has its own read noise and gain, which can be added to the likelihood.
  • Several emitters. Fit two or more emitters in one window when spots overlap, and choose the number by a likelihood ratio test.
  • Other optimizers. Levenberg-Marquardt on the Poisson likelihood, or Fisher scoring at every step, which needs no second derivatives.

When to use it

Use maximum likelihood fitting for each spot in PALM, STORM and single-particle tracking, when the precision matters and the PSF is known well. Least squares fitting is simpler and close in precision at high background. A centroid is fastest but biased by the background and far from the bound. When the emitters are too dense for isolated spots, use a multi-emitter fit, a sparse recovery method, or SOFI.

Pitfalls

  • Wrong pixel units. The counts must be photons, not camera units. Convert with the gain and the offset first, or the Poisson model and the bound are wrong.
  • Reading the bound as the error. The bound is the precision of an ideal unbiased estimator under the model. Drift, a wrong PSF and too few photons make the real error larger.
  • Bad starts. A start far from the spot can make the photon count go to 00, and then the position is not defined. The code limits each move of the center to one pixel and keeps it inside the window.
  • Overlapping spots. Two emitters in one window bias a single emitter fit toward their middle.

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
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
maximum_likelihood_localization.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-localization/. The authors are listed in prov/XKDP82.jsonl.
"""Maximum likelihood localization of one emitter in a small image of photon counts.

Model: pixel (v, u) (row v, column u) covers [u - 1/2, u + 1/2] x [v - 1/2, v + 1/2],
in pixel units. The emitter at (x0, y0) sends N photons (expected) through a
symmetric Gaussian PSF of known standard deviation s, and every pixel gets
the expected background b. The expected count is

    mu(u, v) = N Ex(u) Ey(v) + b,
    Ex(u) = (1/2) [erf((u - x0 + 1/2) / (sqrt2 s)) - erf((u - x0 - 1/2) / (sqrt2 s))],

and the counts are independent Poisson. The negative log likelihood, up to
a constant, is L = sum (mu - c log mu). The parameters are
theta = (x0, y0, N, b).
"""

import math

from imgkit import poisson_sample
from imgla import cho_solve, cholesky, solve

_SQRT2 = math.sqrt(2.0)
_SQRT2PI = math.sqrt(2.0 * math.pi)


def _pixel_factor(u, x0, s):
    """(E, dE/dx0, d2E/dx0^2) for the pixel at u and the center x0."""
    t1 = u - x0 + 0.5
    t2 = u - x0 - 0.5
    e = 0.5 * (math.erf(t1 / (_SQRT2 * s)) - math.erf(t2 / (_SQRT2 * s)))
    g1 = math.exp(-t1 * t1 / (2 * s * s)) / (_SQRT2PI * s)
    g2 = math.exp(-t2 * t2 / (2 * s * s)) / (_SQRT2PI * s)
    de = g2 - g1
    d2e = (t2 * g2 - t1 * g1) / (s * s)
    return e, de, d2e


def model(theta, shape, s):
    """The image of expected counts mu for theta = (x0, y0, N, b)."""
    x0, y0, n_ph, b = theta
    n1, n2 = shape
    ex = [_pixel_factor(u, x0, s)[0] for u in range(n2)]
    ey = [_pixel_factor(v, y0, s)[0] for v in range(n1)]
    return [[n_ph * ex[u] * ey[v] + b for u in range(n2)] for v in range(n1)]


def _pixels(theta, shape, s):
    """For each pixel: (mu, the gradient of mu, the Hessian of mu) in theta."""
    x0, y0, n_ph, _ = theta
    n1, n2 = shape
    fx = [_pixel_factor(u, x0, s) for u in range(n2)]
    fy = [_pixel_factor(v, y0, s) for v in range(n1)]
    out = []
    for v in range(n1):
        ey, dey, d2ey = fy[v]
        for u in range(n2):
            ex, dex, d2ex = fx[u]
            mu = n_ph * ex * ey + theta[3]
            grad = [n_ph * dex * ey, n_ph * ex * dey, ex * ey, 1.0]
            hess = [[n_ph * d2ex * ey, n_ph * dex * dey, dex * ey, 0.0],
                    [n_ph * dex * dey, n_ph * ex * d2ey, ex * dey, 0.0],
                    [dex * ey, ex * dey, 0.0, 0.0],
                    [0.0, 0.0, 0.0, 0.0]]
            out.append((v, u, mu, grad, hess))
    return out


def nll(theta, counts, s):
    """L(theta) = sum (mu - c log mu); infinity if some mu <= 0."""
    shape = (len(counts), len(counts[0]))
    total = 0.0
    for row_mu, row_c in zip(model(theta, shape, s), counts):
        for mu, c in zip(row_mu, row_c):
            if mu <= 0:
                return math.inf
            total += mu - c * math.log(mu)
    return total


def derivatives(theta, counts, s):
    """(L, the gradient of L, the Hessian of L, the Fisher information) at theta."""
    shape = (len(counts), len(counts[0]))
    val = 0.0
    g = [0.0] * 4
    h = [[0.0] * 4 for _ in range(4)]
    fi = [[0.0] * 4 for _ in range(4)]
    for v, u, mu, dmu, d2mu in _pixels(theta, shape, s):
        c = counts[v][u]
        val += mu - c * math.log(mu)
        r = 1.0 - c / mu
        w = c / (mu * mu)
        for i in range(4):
            g[i] += r * dmu[i]
            for j in range(4):
                h[i][j] += w * dmu[i] * dmu[j] + r * d2mu[i][j]
                fi[i][j] += dmu[i] * dmu[j] / mu
    return val, g, h, fi


def fisher_information(theta, shape, s):
    """I(theta) = sum dmu dmu^T / mu over the pixels."""
    fi = [[0.0] * 4 for _ in range(4)]
    for _, _, mu, dmu, _ in _pixels(theta, shape, s):
        for i in range(4):
            for j in range(4):
                fi[i][j] += dmu[i] * dmu[j] / mu
    return fi


def crb(theta, shape, s):
    """The Cramer-Rao bound I(theta)^{-1}, a 4 x 4 matrix."""
    fi = fisher_information(theta, shape, s)
    eye = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
    return solve(fi, eye)


def initial_guess(counts):
    """Background from the border mean, photons from the excess sum, center from the centroid."""
    n1, n2 = len(counts), len(counts[0])
    border = [counts[v][u] for v in range(n1) for u in range(n2)
              if v in (0, n1 - 1) or u in (0, n2 - 1)]
    b = max(sum(border) / len(border), 1e-3)
    excess = [[max(counts[v][u] - b, 0.0) for u in range(n2)] for v in range(n1)]
    total = sum(sum(row) for row in excess)
    if total <= 0:
        return [(n2 - 1) / 2, (n1 - 1) / 2, 1.0, b]
    x0 = sum(u * excess[v][u] for v in range(n1) for u in range(n2)) / total
    y0 = sum(v * excess[v][u] for v in range(n1) for u in range(n2)) / total
    return [x0, y0, total, b]


def localize(counts, s, theta0=None, max_iter=50, tol=1e-9, max_shift=1.0, callback=None):
    """Maximum likelihood fit of theta = (x0, y0, N, b) to a Poisson image.

    Newton steps with a backtracking line search; when the Hessian of L is
    not positive definite, a Fisher scoring step. A step moves the center by
    at most max_shift pixels, and the center must stay inside the image.
    Returns (theta, crb), with crb the inverse Fisher information at the
    estimate.
    """
    theta = list(theta0) if theta0 is not None else initial_guess(counts)  # @line L1
    shape = (len(counts), len(counts[0]))
    for _ in range(max_iter):  # @line L2
        val, g, h, fi = derivatives(theta, counts, s)  # @line L3
        if callback is not None:
            callback(theta, val)
        try:  # @line L4
            step = cho_solve(cholesky(h), [-gi for gi in g])  # @line L4
        except ValueError:  # @line L5
            step = cho_solve(cholesky(fi), [-gi for gi in g])  # @line L5
        slope = sum(gi * di for gi, di in zip(g, step))
        t = min(1.0, max_shift / max(abs(step[0]), abs(step[1]), 1e-300))  # @line L6
        while True:  # @line L6
            trial = [a + t * d for a, d in zip(theta, step)]  # @line L6
            if (trial[2] > 0 and -0.5 <= trial[0] <= shape[1] - 0.5  # @line L6
                    and -0.5 <= trial[1] <= shape[0] - 0.5  # @line L6
                    and nll(trial, counts, s) <= val + 1e-4 * t * slope):  # @line L6
                break  # @line L6
            t *= 0.5  # @line L6
            if t < 1e-12:  # @line L6
                break  # @line L6
        if t < 1e-12:
            break
        theta = trial  # @line L7
        if max(abs(t * d) for d in step) < tol:  # @line L7
            break  # @line L7
    return theta, crb(theta, shape, s)  # @line L8 L9


def poisson_image(rng, mu):
    """Independent Poisson counts with the means mu (an image)."""
    return [[poisson_sample(rng, m) for m in row] for row in mu]
test_maximum_likelihood_localization.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/maximum-likelihood-localization/. The authors are listed in prov/XKDP82.jsonl.

import math
import random

from maximum_likelihood_localization import (
    crb,
    derivatives,
    fisher_information,
    localize,
    model,
    nll,
    poisson_image,
)

THETA = [4.3, 3.8, 500.0, 2.0]
SHAPE = (9, 9)
S = 1.3


def test_gradient_and_hessian_match_finite_differences():
    rng = random.Random(1)
    counts = poisson_image(rng, model(THETA, SHAPE, S))
    theta = [4.1, 4.0, 450.0, 2.5]
    _, g, h, _ = derivatives(theta, counts, S)
    steps = [1e-5, 1e-5, 1e-3, 1e-5]
    for i in range(4):
        up = list(theta)
        dn = list(theta)
        up[i] += steps[i]
        dn[i] -= steps[i]
        fd = (nll(up, counts, S) - nll(dn, counts, S)) / (2 * steps[i])
        assert abs(fd - g[i]) < 1e-5 * (1 + abs(g[i]))
        _, gu, _, _ = derivatives(up, counts, S)
        _, gd, _, _ = derivatives(dn, counts, S)
        for j in range(4):
            fd2 = (gu[j] - gd[j]) / (2 * steps[i])
            assert abs(fd2 - h[i][j]) < 1e-4 * (1 + abs(h[i][j]))


def test_fisher_information_is_the_mean_hessian():
    # E[c] = mu makes the second term of the Hessian vanish.
    mu = model(THETA, SHAPE, S)
    _, _, h, fi = derivatives(THETA, mu, S)
    ref = fisher_information(THETA, SHAPE, S)
    for i in range(4):
        for j in range(4):
            assert abs(h[i][j] - fi[i][j]) < 1e-9 * (1 + abs(fi[i][j]))
            assert abs(fi[i][j] - ref[i][j]) < 1e-12 * (1 + abs(ref[i][j]))


def test_noise_free_data_gives_the_true_parameters():
    mu = model(THETA, SHAPE, S)
    for start in (None, [1.0, 7.0, 50.0, 10.0], [2.0, 6.0, 100.0, 5.0], [7.5, 0.5, 2000.0, 0.1]):
        theta, _ = localize(mu, S, theta0=start)
        for a, b in zip(theta, THETA):
            assert abs(a - b) < 1e-6 * (1 + abs(b))


def test_negative_log_likelihood_never_increases():
    rng = random.Random(2)
    counts = poisson_image(rng, model(THETA, SHAPE, S))
    values = []
    localize(counts, S, theta0=[2.0, 6.0, 100.0, 5.0], callback=lambda t, v: values.append(v))
    assert len(values) > 3
    for a, b in zip(values, values[1:]):
        assert b <= a + 1e-9


def test_variance_is_close_to_the_cramer_rao_bound():
    # A measurement: 200 Poisson images, sample variance against I^{-1}.
    rng = random.Random(11)
    mu = model(THETA, SHAPE, S)
    bound = crb(THETA, SHAPE, S)
    fits = [localize(poisson_image(rng, mu), S)[0] for _ in range(200)]
    for k in (0, 1):
        vals = [f[k] for f in fits]
        mean = sum(vals) / len(vals)
        var = sum((v - mean) ** 2 for v in vals) / (len(vals) - 1)
        assert abs(var / bound[k][k] - 1) < 0.3
        assert abs(mean - THETA[k]) < 3 * math.sqrt(bound[k][k] / len(vals))


def test_bound_for_100_nm_pixels_and_1000_photons():
    # s = a = 100 nm, N = 1000, almost no background: about 3.29 nm,
    # which is sqrt((s^2 + a^2 / 12) / N).
    n = 15
    bound = crb([(n - 1) / 2, (n - 1) / 2, 1000.0, 1e-6], (n, n), 1.0)
    nm = 100 * math.sqrt(bound[0][0])
    assert abs(nm - 3.2914) < 1e-3
    assert abs(nm - 100 * math.sqrt((1 + 1 / 12) / 1000)) < 1e-3

History

Thompson, Larson and Webb (2002) gave the precision of least squares fitting, and Ober, Ram and Ward (2004) derived the limit from the Fisher information of the detection process. In 2010 Smith and coworkers fitted the pixel-integrated Gaussian by Newton-Raphson steps on the Poisson likelihood, fast enough on a graphics processor for whole localization movies, and showed variances at the bound. In the same issue of Nature Methods, Mortensen and coworkers compared maximum likelihood and least squares fitting and gave formulas for the precision of both.

References

  1. C. S. Smith, N. Joseph, B. Rieger and K. A. Lidke, Fast, single-molecule localization that achieves theoretically minimum uncertainty, Nature Methods 7(5), 2010, 373 to 375, the pixel-integrated Gaussian model, the Poisson likelihood, its first and second derivatives, the Newton-Raphson iteration and the comparison of the variance with the Cramer-Rao bound
  2. K. I. Mortensen, L. S. Churchman, J. A. Spudich and H. Flyvbjerg, Optimized localization analysis for single-molecule tracking and super-resolution microscopy, Nature Methods 7(5), 2010, 377 to 381, maximum likelihood against least squares fitting, the precision formulas for both, and the comparison with the information limit
  3. R. J. Ober, S. Ram and E. S. Ward, Localization accuracy in single-molecule microscopy, Biophysical Journal 86(2), 2004, 1185 to 1200, the Fisher information of the photon detection process and the resulting limit of the localization accuracy

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