Exercise: fitting decays with few photons

Goal

By the end of this exercise you should be able to:

  • explain why decays are fitted through the forward model (reconvolution),
  • choose a cost for photon counts, and say why χ² with 1/y weights fails with few photons,
  • predict the precision of a lifetime from the number of photons, and what binning buys,
  • convert between amplitude and photon fractions, and compute \bar\tau_a and \bar\tau_f,
  • set up global analysis as a linear unmixing problem in time,
  • (math) derive the maximum-likelihood lifetime, the Cramér–Rao bound and the weights of a Poisson fit.

Background

Idea What it means
Reconvolution model ∗ IRF + background is compared with the raw counts
Levenberg–Marquardt repeat: linearise the model, solve a (damped) least-squares step
Costs least squares; χ² with 1/y_j weights (Neyman); Poisson deviance (maximum likelihood, weights 1/\mu_j)
Precision at best \sigma_\tau/\tau = 1/\sqrt N for one lifetime; F = (\sigma_\tau/\tau)\sqrt N \ge 1
Fractions photon fraction f_i = \alpha_i\tau_i/\sum_j\alpha_j\tau_j; amplitude fraction \alpha_i ∝ molecules
Mean lifetimes \bar\tau_a = \sum\alpha_i\tau_i, \bar\tau_f = \sum f_i\tau_i
Global analysis lifetimes fitted once for all pixels; per pixel, amplitudes by (non-negative) linear least squares

By hand

B1. Empty bins. (a) A bin expects 4 counts. What is the probability that it is empty? (b) A histogram’s tail has 256 bins whose expected counts fall smoothly from 4 to 0.5. The expected number of empty bins is \sum_j e^{-\mu_j}. Without computing exactly: is it closer to 5, 70 or 200? (Hint: what is e^{-\mu} for the many bins with μ around 1?) (c) Why is this a problem for χ² with weights 1/y_j, and not for the Poisson likelihood?

B2. Photon budget. (a) Best possible relative precision of τ with 100, 400 and 10 000 photons? (b) How many photons for ±5 %, ideally, and with an instrument whose F-value is 1.2? (c) A pixel holds 150 photons. What precision do you expect, and after 3 × 3 and 5 × 5 binning (ideal instrument)? What do you give up?

B3. Two numbers for two lifetimes. A pixel holds two species with amplitude fractions α = (0.7, 0.3) and τ = (1.0, 4.0) ns. (a) Compute the photon fractions. (b) Compute \bar\tau_a and \bar\tau_f. (c) The long species binds a drug and its lifetime shortens from 4.0 to 3.0 ns, with the same molecules. Which of the two means changes more, in percent?

B4. Global analysis by hand. The lifetimes are known from a global fit: 1 ns and 3 ns. A pixel’s photons are counted in three gates, 0–2, 2–4 and 4–8 ns (no IRF; ignore wrap-around). The fraction of each species’ photons in each gate is

gate τ = 1 ns τ = 3 ns
0–2 ns 0.865 0.487
2–4 ns 0.117 0.250
4–8 ns 0.018 0.194

and the counts are y = (612, 203, 148). (a) Write the model y \approx M\mathbf a with \mathbf a = (a_1, a_2) the photons of each species. (b) Solve it by least squares (normal equations M^\top M\mathbf a = M^\top y). (c) Which fraction of the pixel’s photons comes from the long species? Compute the residuals: do they look like Poisson noise?

B5. Read the residuals. For each residual pattern (weighted residuals against time), say what is wrong with the fit: (a) noise of about ±1, no structure; (b) positive early, negative in the middle, positive late; (c) positive at every late time, by a similar amount; (d) a sharp positive–negative pair right at the rising edge.

B6. Predict. You have 200 photons per pixel, a flat background of 10 % of the photons, and one lifetime. Rank the mean arrival time, two gates, least squares, χ² with 1/y and the Poisson fit (with a background term) by the bias you expect, and say why.

B1. (a) e^{-4} = 1.8\,\%. (b) About 70 (a direct sum gives 68.5): roughly a quarter of the 256 bins are empty, and 141 hold 0 or 1 count. (c) χ² with 1/y_j needs a patch for every empty bin and gives the largest weights to the bins with 1 count, which are exactly the noisiest: the fit follows the low draws and is biased towards a fast decay. The Poisson likelihood has the term y_j\log\mu_j - \mu_j, perfectly defined for y_j = 0 (it just says “μ should be small here”).

B2. (a) 10 %, 5 %, 1 %. (b) N = 1/0.05^2 = 400; with F = 1.2, (1.2/0.05)^2 = 576. (c) 1/\sqrt{150} = 8.2\,\%; 3 × 3: 1 350 photons, 2.7 %; 5 × 5: 3 750 photons, 1.6 %. The price is resolution: the lifetime is now an average over 9 or 25 pixels, and borders between compartments blur.

B3. (a) \alpha\tau = (0.7, 1.2), sum 1.9: f = (0.37, 0.63). (b) \bar\tau_a = 0.7 + 1.2 = 1.90 ns; \bar\tau_f = (0.7 \cdot 1 + 0.3 \cdot 16)/1.9 = 2.89 ns. (c) \bar\tau_a = 0.7 + 0.9 = 1.60 ns (−16 %); \alpha\tau = (0.7, 0.9), sum 1.6, \bar\tau_f = (0.7 + 0.3 \cdot 9)/1.6 = 2.13 ns (−27 %). The intensity-weighted mean moves more because the long species dominates the photons; but both change, and the size of the change depends on which mean you report.

B4. (a) \begin{pmatrix}612\\203\\148\end{pmatrix} \approx \begin{pmatrix}0.865 & 0.487\\0.117 & 0.250\\0.018 & 0.194\end{pmatrix}\begin{pmatrix}a_1\\a_2\end{pmatrix}. (b) M^\top M = \begin{pmatrix}0.7622 & 0.4540\\0.4540 & 0.3373\end{pmatrix}, M^\top y = (555.8, 377.5), so a_1 = 315, a_2 = 695. (c) 695/(315 + 695) = 0.69 of the photons (of the photons in the 8 ns window). The model gives (611.1, 210.5, 140.5); residuals (0.9, −7.5, 7.5). The Poisson SD of the bins is about 25, 14 and 12: residuals of half an SD, nothing systematic.

B5. (a) A good fit. (b) A missing component: the decay is steeper at first and flatter later than one exponential. (c) A background that the model does not include (or an IRF that wraps round). (d) The IRF is shifted relative to the data (a small timing shift between the IRF measurement and the sample), so the model’s rising edge comes too early or too late.

B6. Mean arrival time and two gates are biased by the background (both make τ too long, as in the last unit); least squares without a background term too. χ² with 1/y is biased short by the low bins (at 200 photons, most tail bins hold 0 to 2 counts). The Poisson fit with a background term is nearly unbiased; its spread is close to \tau/\sqrt{180} or a little more. The photon-budget demo below measures these biases.

Math questions

B7. (math) Maximum likelihood from arrival times. For arrival times t_1, \dots, t_N with density \tau^{-1}e^{-t/\tau} (no IRF, infinite window), write the log-likelihood, show that its maximum is the mean arrival time, and that this estimate is unbiased with variance \tau^2/N.

B8. (math) Cramér–Rao. Compute the Fisher information I(\tau) = -E[\partial^2\ell/\partial\tau^2] for B7 and show that the bound 1/I(\tau) equals the variance of the mean arrival time. What does that say about the mean arrival time as an estimator, in this ideal case?

B9. (math) Weights of a Poisson fit. Write the Poisson deviance D(\theta) for counts y_j and model \mu_j(\theta). Show that \nabla D = -2J^\top W(y - \mu) with W = \mathrm{diag}(1/\mu_j), so the Gauss–Newton step of a weighted least-squares fit with weights 1/\mu_j (re-evaluated every step) moves towards the maximum-likelihood estimate.

B10. (math) Linear amplitudes. For fixed lifetimes, the model of one pixel is \mu = B\mathbf a + b\mathbf 1 with a known b. Show that minimising \sum_j w_j(y_j - \mu_j)^2 over \mathbf a gives \mathbf a = (B^\top WB)^{-1}B^\top W(y - b\mathbf 1). Why does this make the cost a function of the lifetimes alone?

B7. \ell(\tau) = \sum_i(-\log\tau - t_i/\tau) = -N\log\tau - S/\tau with S = \sum t_i. \ell'(\tau) = -N/\tau + S/\tau^2 = 0 gives \hat\tau = S/N (and \ell'' < 0 there: a maximum). Each t_i has mean τ and variance τ², so E[\hat\tau] = \tau and \operatorname{Var}\hat\tau = \tau^2/N.

B8. \ell''(\tau) = N/\tau^2 - 2S/\tau^3, with E[S] = N\tau: I(\tau) = -N/\tau^2 + 2N/\tau^2 = N/\tau^2. The bound is \tau^2/N, exactly the variance from B7: in the ideal case the mean arrival time is efficient, no unbiased estimator does better. With an IRF, a finite window and background, the mean arrival time is biased and a fit through the forward model is needed to approach the (now larger) bound.

B9. D = 2\sum_j[y_j\log(y_j/\mu_j) - (y_j - \mu_j)]. \partial D/\partial\theta_k = 2\sum_j(-y_j/\mu_j + 1)\,\partial\mu_j/\partial\theta_k = -2\sum_j\frac{y_j - \mu_j}{\mu_j}J_{jk}, i.e. \nabla D = -2J^\top W(y - \mu). The weighted least-squares cost \sum_j w_j(y_j - \mu_j)^2 with fixed w_j = 1/\mu_j has the same gradient at the current point, so its Gauss–Newton step (J^\top WJ)\delta = J^\top W(y - \mu) is a step on D (Fisher scoring: J^\top WJ is the expected Hessian of D/2). Re-evaluating W each step converges to the point where \nabla D = 0, the ML estimate.

B10. The cost is (y - b\mathbf 1 - B\mathbf a)^\top W(y - b\mathbf 1 - B\mathbf a); setting the gradient in \mathbf a to zero gives B^\top W(y - b\mathbf 1 - B\mathbf a) = 0, the normal equations, with the solution above (B4 is the case W = I, b = 0). Substituting this best \mathbf a for every set of lifetimes leaves a cost that depends on the lifetimes alone (“variable projection”): the nonlinear search runs over 2 numbers instead of 2 per pixel. If some amplitude comes out negative, non-negative least squares replaces the formula.

Explore: fit a decay

One simulated histogram (128 bins over 12.5 ns, IRF σ adjustable at 1 ns delay, fixed seed; new noise draws the next one). The model is fitted by Levenberg–Marquardt with the chosen cost; the landscape shows the cost (bright = low) over (τ, photons) for one lifetime, or over (τ₁, τ₂) with the amplitudes profiled out. Start over and step replay the fit; the white path is the optimiser’s.

E1. Preset 10 000 photons: costs agree. Switch between the three costs and note τ ± its error each time. Do they agree within their error bars? Look at the landscape: what shape is it?

E2. Preset 200 photons: 1/y goes wrong. Again compare the three costs. Press new noise a few times with χ² with 1/y: in which direction is it usually off? (One draw proves little; E7 measures it properly.)

E3. Preset ignore the IRF: the model pretends the IRF is a spike. Read τ and the reduced χ², and look at the residuals near the peak. Now tick reconvolution.

E4. Preset two τ, 1 000 photons: a valley (true 0.8 and 3.0 ns, 60 % of the photons in the long one). Read the fitted lifetimes and their errors, and describe the landscape. Press new noise three times. What stays stable from draw to draw, and what does not?

E5. Preset two τ, 100 000 photons. How do the errors compare with E4? Now preset one τ fitted to two: read the lifetime and the reduced χ², and describe the residuals. Which of the true \bar\tau_a and \bar\tau_f is the one-lifetime answer closer to?

E6. Preset background left out (15 % background). Read τ with fit background off, then on.

E1. Poisson 2.51 ± 0.05, χ² with 1/y 2.50 ± 0.04, least squares 2.42 ± 0.05 ns (true 2.50). Poisson and 1/y agree; least squares is 1.6 error bars low, because it trades a little τ for a larger background (2.63 instead of 0.91 counts per bin): it weights the big early bins most and the tail least. The landscape is a single bowl, slightly tilted (τ and the photon count are a little correlated).

E2. χ² with 1/y: 3.10 ± 0.80; least squares 2.58 ± 0.42; Poisson 2.74 ± 0.38 ns. This draw happens to push all three up. Over many draws χ² with 1/y comes out too short on average (E7: −3.9 % at 100 photons, −7.5 % at 1 000 with no background), while the Poisson fit stays unbiased and has the smallest spread.

E3. Without reconvolution: τ = 0.87 ns, reduced χ² = 1 571: a terrible fit. The residuals show a large wave around the peak: a spike model cannot follow the blurred rise, so the fit compromises with a longer τ and a large background (151 counts per bin). With reconvolution: 0.80 ns, reduced χ² 0.99.

E4. First draw: τ₁ = 0.36 ± 0.13, τ₂ = 2.02 ± 0.22 ns. The landscape has a long curved valley (two of them, mirror images: swapping τ₁ and τ₂ gives the same model). New draws: (0.75, 3.06), (0.90, 3.63 ± 2.03), (0.66, 3.35) ns. The lifetimes jump around by tens of percent, yet every fit has a reduced χ² near 1 (0.87 to 1.03): each is as good as the truth. \bar\tau_f stays between 1.7 and 2.3 ns (true 2.12): the data pin down an average much better than the two lifetimes.

E5. τ₁ = 0.83 ± 0.02, τ₂ = 3.13 ± 0.12 ns: errors about 10 times smaller with 100 times the photons. One lifetime: τ = 1.58 ± 0.01 ns with reduced χ² = 14.3 and a wavy residual: precise and wrong. It lies between the true \bar\tau_a = 1.43 and \bar\tau_f = 2.12 ns, nearer to \bar\tau_a here, helped by a large fitted background that soaks up the long tail.

E6. Background off: τ = 3.29 ± 0.04 ns, reduced χ² 2.26: the flat background makes the tail look slow. On: 2.52 ± 0.06 ns, background 12.2 counts per bin, reduced χ² 0.90.

Explore: the photon budget

A Monte Carlo of five estimators: for the current settings, 400 seeded histograms (64 bins, IRF σ = 0.15 ns) are analysed by the mean arrival time, two gates (1.5–4 and 4–6.5 ns), least squares, χ² with 1/y and the Poisson fit (the fits include a background term when there is background). Left: every estimate (one row per method), mean ± SD, the true τ. Right (error vs N): the relative RMS error against N, with the 1/\sqrt N line.

E7. Preset the 1/√N line (1 000 photons). Read the table. Which methods are biased, and why? Which has the smallest spread? Compare the Poisson fit’s spread with the ideal \tau/\sqrt N: what is the F-value of this simulated instrument?

E8. On the right, read the Poisson fit’s relative error at 100, 1 000 and 10 000 photons. Does it follow the 1/\sqrt N line? Which methods leave it, and why?

E9. Preset few photons (100) and preset background (10 %, 10 000 photons). For each, which methods are biased and by how much?

E10. Preset two lifetimes (0.8 and 3 ns, 60 % of the photons in the long one, Poisson fits). Describe the scatter of (τ₁, τ₂). How many photons do two lifetimes need for 10 % precision, compared with one?

E7. Mean arrival 2.37 ± 0.07 (−5.2 %: the finite window wraps the tail round); χ² with 1/y 2.31 ± 0.10 (−7.5 %); two gates 2.51 ± 0.22, least squares 2.50 ± 0.13, Poisson 2.50 ± 0.09 (unbiased). The mean arrival has the smallest spread but is biased; among unbiased methods the Poisson fit is best. Ideal: 2.5/√1000 = 0.079; the Poisson fit’s SD of 0.09 gives F \approx 0.09/0.079 = 1.1 (the error-vs-N table gives 3.8 % at 1 000 photons, F = 0.038\sqrt{1000} = 1.2).

E8. 11 %, 3.8 % and 1.1 %: parallel to the 1/\sqrt N line, a little above it (F ≈ 1.1 to 1.2). The mean arrival time flattens out at about 5 %: its bias does not shrink with more photons. χ² with 1/y joins the Poisson curve only at large N, where every bin holds many counts; two gates stay well above (they use only part of the photons).

E9. 100 photons: mean arrival −5.1 %, two gates +3.7 % (± 0.76!), least squares +1.5 %, χ² with 1/y −3.9 %, Poisson +0.4 % (± 0.27, ideal ± 0.25). Background 10 %: mean arrival +6.5 %, two gates +7.7 %, the three fits with a background term 0.1 to 0.2 %. With background the Poisson fit’s error is 2.1 % at 10 000 photons instead of 1.1 %.

E10. At 10 000 photons: τ₁ = 0.80 ± 0.05 and τ₂ = 3.01 ± 0.12 ns, strongly correlated (0.75): the cloud is stretched along a line (if τ₁ comes out long, τ₂ comes out long too). Error vs N: τ₁ / τ₂ relative errors 20 % / 22 % at 1 000, 14 % / 8.8 % at 3 000, 7.6 % / 4.3 % at 10 000 photons. One lifetime reaches 10 % at about 100 photons, two lifetimes between 3 000 and 10 000: some 30 to 100 times more photons.

Explore: global analysis of an image

The cell with two species (0.6 and 3.5 ns) whose photon fractions vary across it. The lifetimes are fitted once to the summed decay of all unmasked pixels (Poisson, with a background term; the plot shows that summed decay and the fit), then each pixel’s amounts by non-negative least squares. The second image shows the photon fraction of the long species, or the intensity-weighted lifetime.

E11. Preset global analysis: a fraction map. Read the global lifetimes. Describe the fraction map: where is the long species most abundant? Then 50 photons per pixel still work: what changes in the lifetimes and in the map? Try 3 × 3 binning.

E12. Preset global analysis of a FRET cell (a donor of 2.6 ns, partly in a FRET state of 1.3 ns). What does the fraction map show? Why does global analysis suit FRET experiments? (Next-but-one unit.)

E11. 8 041 pixels, 2.3 million photons: τ = 0.60 and 3.50 ns, exactly the truth. The long species’ fraction increases from left to right (and downwards) and is low in the nucleus. With 50 photons in the bright pixels: 289 000 photons in all, τ = 0.59 and 3.45 ns, still close; the fraction map is speckled but shows the same gradient. 3 × 3 binning smooths it (lifetimes 0.59 and 3.45 ns again). Fitting two lifetimes in each pixel separately would be hopeless at 50 photons (E10).

E12. τ = 1.29 and 2.61 ns (true 1.3 and 2.6). The map of the 2.61 ns fraction is high almost everywhere and lower along the mitochondria and the membrane, where donors are in the FRET state. In a FRET experiment the two lifetimes (donor alone, donor with acceptor) are the same in every pixel; only the interacting fraction varies, which is exactly the assumption of global analysis.

Code

Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in flim/src/decayfit/exercise.rs. A histogram has n equal bins over one laser period T; the IRF is a histogram with the same bins that sums to 1.

C1. model(tau, photons, background, irf, period): the expected histogram, by reconvolution:

for every bin i (from a = i·Δt to b = (i+1)·Δt):
    d_i = (exp(−a/τ) − exp(−b/τ)) / (1 − exp(−T/τ))     # periodic decay, area 1
μ = background in every bin
for every IRF bin k, for every bin i:
    μ[(i + k) mod n] += photons · irf[k] · d_i           # circular convolution

The check uses the gate fractions of B4 (τ = 1 and 3 ns), and checks that an IRF in bin 3 shifts the decay by 3 bins.

C2. cost(y, mu, kind): least squares \sum (y_j - \mu_j)^2; χ² with data weights \sum (y_j - \mu_j)^2 / y_j (weight 1 for an empty bin); the Poisson deviance 2\sum [y_j \log(y_j/\mu_j) - (y_j - \mu_j)] with 0 \log 0 = 0.

C3. fit(y, irf, period, kind, start_tau): fit τ, the photons and the background:

θ = (start τ, 0.9 · total counts, 0.1 · total / n)
repeat up to 50 times:
    μ = model(θ);  J = the change of μ with each parameter      # τ: a small finite difference
    w_j = 1, 1/y_j or 1/μ_j, depending on the cost
    solve (Jᵀ W J) δ = Jᵀ W (y − μ)                               # 3 equations, 3 unknowns
    if the background would become negative: keep it at 0 and solve for the other two
    try θ + δ, θ + δ/2, θ + δ/4, ... until the cost goes down
    stop if it does not

The checks: a noise-free histogram is fitted exactly from a start of 1.5 ns with all three costs; 200 noisy histograms of 1 000 photons give an unbiased τ with a spread close to the 1/\sqrt N limit (B2).

C4. mean_lifetimes(alpha, tau): \bar\tau_a and \bar\tau_f of a mixture. The checks are B3(b), B3(c) and the lecture’s example.

C5. amplitudes(y, shapes): the least-squares amplitudes of known decay shapes in one pixel (global analysis): a matrix with one row per bin and one column per shape, solved by linear least squares. The check is B4(b).

Then cargo run -p flim -- decayfit and open the pictures in out/decayfit/. The program first fits 300 noisy histograms of a 2.5 ns decay (IRF σ = 0.15 ns, 0.2 background counts per bin) with each cost, at 100, 1 000 and 10 000 photons, and prints the mean, the spread and the relative RMS error. Then it makes a 96 \times 96 FLIM image of nuclei holding two species, 0.6 and 3.5 ns, whose photon fraction changes from left to right. It finds the two lifetimes once from the summed decay of all pixels with at least 80 photons (for every pair on a grid the amplitudes are linear, C5; it keeps the pair with the lowest deviance), then the amplitudes of every pixel with C5. fraction-long.png is the photon fraction of the long species per pixel, fraction-true.png the truth.

C6. Read the table. Which cost is biased, in which direction, and does the bias shrink with more photons? Which cost has the smallest error? Compare the Poisson fit’s spread with the ideal \tau/\sqrt N: what F-value do you get?

C7. Compare fraction-long.png with fraction-true.png, and read the global lifetimes and the printed error of the fractions. Why can a pixel with a few hundred photons give a useful fraction here, when a two-lifetime fit of that pixel alone could not (E10)?

The model solution is flim/src/decayfit/solution.rs in the download.

C6. χ² with 1/y is biased short: 2.18 ns at 100 photons, 2.33 at 1 000 and 2.47 at 10 000 (true 2.5). The bias shrinks as the bins fill up, but slowly. Least squares and the Poisson fit are nearly unbiased (2.48 to 2.53 ns). The Poisson fit has the smallest relative RMS error at every photon count: 19.9 %, 4.7 % and 1.4 %, against 24.8 %, 6.5 % and 2.1 % for least squares. Its spread of 0.11 ns at 1 000 photons against the ideal 0.079 ns gives F \approx 1.4: higher than the demo’s 1.1 to 1.2, because this fit also estimates the background, which trades off against τ and costs some precision.

C7. The global lifetimes come out at 0.60 and 3.50 ns, the truth, from 211 510 photons in 1 032 pixels. The fraction map shows the same left-to-right rise as the truth, speckled: the error per pixel is −0.003 ± 0.089. With the two lifetimes fixed, each pixel is a linear problem with two unknowns, which a few hundred photons can pin down; the hard, nonlinear part (the lifetimes) used the photons of all pixels together. A free two-lifetime fit per pixel would need thousands of photons (E10).

Where this leads

Fits are slow (a nonlinear search per pixel or per region) and need a model. The next unit computes two numbers per pixel with no fit and no model, the phasor, and reads mixtures, lifetimes and calibration directly from a plot.