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
- Model
- Real RAM
- Properties
- deterministiciterativemodel basedmonotone likelihoodreturns uncertainty
- Evidence
- Proof sketchCode in 1 languages
- 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 pixels with photon counts around one emitter, and the known PSF width in pixels. The model is , where pixel covers a unit square, is the share of the PSF in column , and is the same for the rows. The counts are independent Poisson with the means . The goal is the maximum likelihood estimate of , that is the minimizer of , and its uncertainty.
The algorithm
MLE-LOCALIZE(c, s)- 1
θ ← (centroid of c - b₀, total of c - b₀, b₀), with b₀ the mean of the border pixels - 2
repeat at most max_iter times - 3
compute L, ∇L, ∇²L and the Fisher information I(θ) = Σ ∇μ ∇μᵀ / μ - 4
if ∇²L is positive definite: δ ← -(∇²L)⁻¹ ∇L ▷ Newton step, by Cholesky - 5
else δ ← -I(θ)⁻¹ ∇L ▷ Fisher scoring step - 6
halve t from min(1, 1/|δ_center|) until N > 0, the center is in the window and L(θ + tδ) ≤ L(θ) + 10⁻⁴ t ∇Lᵀδ - 7
θ ← θ + tδ; stop when the step is below the tolerance - 8
crb ← I(θ)⁻¹ - 9
return θ, crb
In line L6, is the larger of and , so a step moves the center by at most one pixel. The gradient is and the Hessian is . The derivatives of are differences of the normal density : and , with .
Example
Take a window, pixels and the true . One Poisson image (seed in the test file) has counts. The start from line L1 is . The iterates are:
| step | |||||
|---|---|---|---|---|---|
| 0 | 4.4000 | 3.7832 | 515.75 | 2.3125 | |
| 1 | 4.4468 | 3.7881 | 510.17 | 2.0370 | |
| 2 | 4.4457 | 3.7881 | 509.57 | 2.0647 | |
| 3 | 4.4457 | 3.7881 | 509.56 | 2.0650 |
The returned bound gives the standard deviations , , and . The error in is pixels, about two standard deviations: one image is one random draw. Over images (seed ) the sample variances of and are and times the bound (a measurement). Without noise, that is with , the fit returns to from the centroid start and from three poor starts.
With nm, pixels of nm, and almost no background, the bound on the standard deviation of is nm, against nm for infinitely small pixels.
Correctness
The proof is in proofs/correctness.md. The facts:
- Derivatives (theorem). The formulas for , , and are exact, and .
- 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 . So never increases.
- Noise-free data (theorem). For , is a global minimizer of , and a strict local minimizer when is positive definite.
- The bound (theorem). Every unbiased estimator has a covariance of at least , 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.
- 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 covers . For the expected count is with
where is the normal density, and the same for . The counts are independent Poisson with the means . The negative log likelihood, without the constant , is .
Claim 1 (pixel derivatives). With and ,
Proof. with the normal distribution function, , and . So . Then , so .
Claim 2 (gradient, Hessian, Fisher information).
and the Fisher information is . Here , and the nonzero entries of are , , , and in the obvious places.
Proof. Differentiate once and twice by the chain rule, and by the product rule with Claim 1. Taking the expectation with removes the second term of the Hessian.
The test compares the gradient and the Hessian with central differences, and checks that the Hessian at equals .
Claim 3 (descent). Let at all pixels. If is positive definite, the Newton step satisfies unless . If not, and the four vectors over the pixels are linearly independent, is positive definite and the scoring step has the same property. Then the backtracking of line L6 ends with a for which .
Proof. For a positive definite , when . is only if at every pixel, which the linear independence excludes for . The set where , the center lies in the image and all is open and contains , and is differentiable there, so ; for small the point is in the set and the inequality holds because . Halving reaches such a .
So the sequence 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 ; 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 , then is a global minimizer of , and a strict local minimizer if is positive definite.
Proof. With and at each pixel, , since for . At the gradient is , since at every pixel, and the Hessian is by Claim 2. A zero gradient and a positive definite Hessian give a strict local minimizer.
The test starts from the centroid guess and from three poor starts, and all four runs return to .
Claim 5 (the bound). For any unbiased estimator of from the counts, . The code returns .
Proof. This is the Cramer-Rao bound for the product of Poisson laws, whose Fisher information is the of Claim 2.
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 Poisson images with about signal photons and finds it within percent of (a measurement, not a theorem).
Claim 6 (no pixels, no background). If the pixels are infinitely small and , the information about is , so the bound on the standard deviation is .
Proof. The photon positions then form a Poisson process with the intensity (times the same in ), and the information about is for a normal with variance .
With unit pixels of side the information is smaller. The test computes the bound for nm, and a background of on a grid and finds nm. This agrees to nm with , which is a numerical observation for this case, not an identity.
Complexity
One iteration evaluates two error functions and two exponentials per row and per column, then sums outer products over the pixels: time. The Cholesky factorization costs , and each trial of the line search costs . With iterations and a bounded number of halvings per iteration, a fit costs , and is usually below . The extra space is 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 too, as a fifth parameter, to catch out-of-focus spots and overlapping emitters.
- 3D by astigmatism. With a cylindrical lens the widths and depend on the depth , and fitting both gives .
- 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 , 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.
# 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
- 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
- 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
- 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.
| 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 XKDP82 Edit this page History Report an error Markdown