Algorithm Search⌘K

Algorithmresearch

Super-resolution optical fluctuation imaging

Also called SOFI.

Compute the n-th order cumulant of the blinking at each pixel of a movie. This raises the PSF to the n-th power, which narrows a Gaussian PSF by the square root of n.

Time
Θ(n N T) worst · average · best
Space
Θ(N + n T) extra
Where
N = the number of pixels; T = the number of frames; n = the order of the cumulant
Properties
background freedeterministicnot iterativenot linearoptical method
Origin
Thomas Dertinger, Ryan Colyer, Gopal Iyer, Shimon Weiss, Jörg Enderlein, 2009

Super-resolution optical fluctuation imaging (SOFI) is an optical method that makes a sharper image from a movie of fluorescent emitters that blink on and off independently. It does not need special optics or isolated emitters. At each pixel it computes a cumulant of order nn of the intensity over time, with small time lags. Because the emitters blink independently, the cumulants of different emitters add without cross terms, and each emitter contributes the nn-th power of its point spread function (PSF), times the nn-th power of its brightness. A constant background drops out exactly, and noise that is independent from frame to frame drops out when the lags differ. For a Gaussian PSF of width σ\sigma, the nn-th power is a Gaussian of width σ/n\sigma/\sqrt n, so the image gets sharper by n\sqrt n; for other PSFs the narrowing factor is different, but the support of the spectrum grows by nn. The gain comes from the physical blinking, which the computation measures; a movie of emitters that do not fluctuate gives no gain.

In plain words

Many small lamps sit closer together than a microscope can separate. Each lamp flickers on its own. The camera sees one blur. At one pixel, the light goes up and down as the nearby lamps flicker. If you measure how strongly the light at a pixel goes up and down, a pixel near the center of one lamp moves a lot, and a pixel between two lamps moves less, because its two lamps flicker independently and partly cancel in the statistics. Higher order statistics sharpen this effect. A steady glow from the background does not go up and down, so it disappears, and camera noise that is new in every frame disappears when you compare different frames.

The problem

The input is a movie of TT frames of NN pixels. The model is F(r,t)=b(r)+∑kεkU(r−rk)sk(t)+N(r,t)F(r, t) = b(r) + \sum_k \varepsilon_k U(r - r_k) s_k(t) + N(r, t): a background bb, emitters at rkr_k with brightness εk\varepsilon_k and PSF UU, independent stationary blinking processes sk(t)∈{0,1}s_k(t) \in \{0, 1\}, and noise that is independent from frame to frame. The goal is an image of the emitter positions sharper than the time mean of the movie, which is the widefield image b+∑kεkρkU(r−rk)b + \sum_k \varepsilon_k \rho_k U(r - r_k) with the on fractions ρk\rho_k.

The algorithm

Choose the order nn and nn distinct lags τ1,…,τn\tau_1, \ldots, \tau_n, for example 0,1,…,n−10, 1, \ldots, n - 1 frames.

  1. SOFI(movie, n, lags)
  2. 1for each pixel r
  3. 2s ← the series F(r, 0), ..., F(r, T - 1)
  4. 3X_q(t) ← s(t + τ_q) for q = 1, ..., n and t = 0, ..., T - 1 - max τ
  5. 4center each X_q by its mean over the window
  6. 5C(r) ← κ_n(X_1, ..., X_n) by the moment formula
  7. 6return C

The moment formulas on the centered series a,b,c,da, b, c, d are κ2=E[ab]\kappa_2 = \mathbb E[ab], κ3=E[abc]\kappa_3 = \mathbb E[abc] and κ4=E[abcd]−E[ab]E[cd]−E[ac]E[bd]−E[ad]E[bc]\kappa_4 = \mathbb E[abcd] - \mathbb E[ab]\mathbb E[cd] - \mathbb E[ac]\mathbb E[bd] - \mathbb E[ad]\mathbb E[bc], where E\mathbb E is the mean over the window. In expectation the result is

Cn(r)=∑kεkn U(r−rk)n κn[sk](τ).C_n(r) = \sum_k \varepsilon_k^n\, U(r - r_k)^n\, \kappa_n[s_k](\tau).

Example

Two emitters of equal brightness sit 2σ2\sigma apart under a Gaussian PSF of width σ\sigma. In units of the peak of one PSF:

image at an emitter midway dip?
widefield, U(r−r1)+U(r−r2)U(r - r_1) + U(r - r_2) 1+e−2=1.13531 + e^{-2} = 1.1353 2e−1/2=1.21312e^{-1/2} = 1.2131 no
SOFI order 2, U2(r−r1)+U2(r−r2)U^2(r - r_1) + U^2(r - r_2) 1+e−4=1.01831 + e^{-4} = 1.0183 2e−1=0.73582e^{-1} = 0.7358 yes, ratio 0.72250.7225

The widefield image has its maximum midway, so it shows one blob. The second order image has a dip of about 2828 percent between the emitters. The test simulates this case with 40004000 frames, a background of 22, Gaussian noise and Markov blinking with a=b=0.3a = b = 0.3; the measured ratio is 0.7460.746, close to the expected 0.72250.7225 (a measurement, with the error of a finite movie).

For σ=100\sigma = 100 nm, the width of UnU^n is σ/n=70.7\sigma/\sqrt n = 70.7, 57.757.7 and 5050 nm for n=2,3,4n = 2, 3, 4, and the full width at half maximum, 2.3548 σ/n2.3548\,\sigma/\sqrt n, falls from 235.5235.5 nm for the widefield PSF to 166.5166.5, 136.0136.0 and 117.7117.7 nm.

Correctness

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

  1. Algebra (theorems). The moment formulas equal the partition formula for the joint cumulant. Cumulants of order n≥2n \ge 2 ignore added constants, scale with the product of the factors, add over independent sums, and vanish when the variables split into two independent groups.
  2. SOFI formula (theorem, under the model). With independent stationary emitters, a constant background, noise independent between frames and distinct lags, Cn(r)=∑kεknU(r−rk)nκn[sk](τ)C_n(r) = \sum_k \varepsilon_k^n U(r - r_k)^n \kappa_n[s_k](\tau). With equal lags, white noise adds its own cumulant, for example its variance at n=2n = 2.
  3. One emitter (theorem, exact). For a single emitter and a constant background the computed image is exactly εnUn\varepsilon^n U^n times the sample cumulant of the blinking.
  4. Narrowing (theorem). For a Gaussian PSF, UnU^n is a Gaussian of width σ/n\sigma/\sqrt n. For a PSF whose OTF has the cutoff kck_c, the spectrum of UnU^n has the cutoff nkcn k_c.
  5. Blinking cumulants (theorem). For a two-state Markov chain with on fraction ρ\rho, the zero-lag cumulants are those of a Bernoulli law, κ4=ρ(1−ρ)(1−6ρ(1−ρ))\kappa_4 = \rho(1 - \rho)(1 - 6\rho(1 - \rho)) is negative for 0.211<ρ<0.7890.211 < \rho < 0.789, and the lag-1 covariance is ρ(1−ρ)(1−a−b)\rho(1 - \rho)(1 - a - b).

The computed values are cumulants of the sample, which tend to the cumulants of the model as the movie grows (a standard fact for ergodic processes, not proved here).

Proof: The SOFI cumulant removes the background and the white noise and keeps the n-th power of the PSF of each independent emitterfull

Setting. The intensity at pixel rr and frame tt is

F(r,t)=b(r)+∑kεk U(r−rk) sk(t)+N(r,t),F(r, t) = b(r) + \sum_{k} \varepsilon_k\, U(r - r_k)\, s_k(t) + N(r, t),

with a constant background bb, emitters at rkr_k with brightness εk\varepsilon_k, a PSF UU, blinking processes sks_k and noise NN. The model assumptions are: the processes s1,s2,…s_1, s_2, \ldots and NN are mutually independent and stationary, and the noise values at different frames are independent (white in time). For the lags τ1,…,τn\tau_1, \ldots, \tau_n, the SOFI value of order nn is the joint cumulant

Cn(r)=κ(F(r,t+τ1),…,F(r,t+τn)).C_n(r) = \kappa\bigl(F(r, t + \tau_1), \ldots, F(r, t + \tau_n)\bigr).

The joint cumulant of X1,…,XnX_1, \ldots, X_n is κ=∑π(−1)∣π∣−1(∣π∣−1)!∏B∈πE[∏q∈BXq]\kappa = \sum_\pi (-1)^{|\pi| - 1}(|\pi| - 1)! \prod_{B \in \pi} \mathbb E\bigl[\prod_{q \in B} X_q\bigr], summed over the partitions π\pi of {1,…,n}\{1, \ldots, n\}. Equivalently, it is the coefficient of t1⋯tnt_1 \cdots t_n in the cumulant generating function K(t)=log⁡E e∑qtqXqK(t) = \log \mathbb E\, e^{\sum_q t_q X_q}, when this function exists, as it does for bounded variables. The code computes the cumulant of the empirical law, which puts the mass 1/L1/L on each of the LL vectors (X1(t),…,Xn(t))(X_1(t), \ldots, X_n(t)) in the window. All the algebraic claims below hold for any law, so they hold exactly for the empirical one too.

Claim 1 (moment formulas). For n=2,3,4n = 2, 3, 4 the code's formulas on the centered series equal the partition formula: κ2=E[ab]\kappa_2 = \mathbb E[ab], κ3=E[abc]\kappa_3 = \mathbb E[abc], κ4=E[abcd]−E[ab]E[cd]−E[ac]E[bd]−E[ad]E[bc]\kappa_4 = \mathbb E[abcd] - \mathbb E[ab]\mathbb E[cd] - \mathbb E[ac]\mathbb E[bd] - \mathbb E[ad]\mathbb E[bc].

Proof. By Claim 2, adding constants does not change κ\kappa for n≥2n \ge 2, so we may center. For centered variables every partition with a block of one element contributes 00. For n=2,3n = 2, 3 only the partition with one block is left. For n=4n = 4 the one block gives E[abcd]\mathbb E[abcd] and the three partitions into two pairs have the coefficient (−1)11!=−1(-1)^1 1! = -1. □\square

The test checks the identity in exact rational arithmetic against a direct sum over all partitions.

Claim 2 (constants and scaling). For n≥2n \ge 2, κ(X1+c1,…,Xn+cn)=κ(X1,…,Xn)\kappa(X_1 + c_1, \ldots, X_n + c_n) = \kappa(X_1, \ldots, X_n), and κ(a1X1,…,anXn)=a1⋯an κ(X1,…,Xn)\kappa(a_1 X_1, \ldots, a_n X_n) = a_1 \cdots a_n\, \kappa(X_1, \ldots, X_n).

Proof. KK of the shifted variables is K(t)+∑qcqtqK(t) + \sum_q c_q t_q, which has no term in t1⋯tnt_1 \cdots t_n when n≥2n \ge 2. Scaling XqX_q by aqa_q replaces tqt_q by aqtqa_q t_q in KK. □\square

Claim 3 (independent sums). If Xq=Yq+ZqX_q = Y_q + Z_q and the families (Yq)(Y_q) and (Zq)(Z_q) are independent, then κ(X)=κ(Y)+κ(Z)\kappa(X) = \kappa(Y) + \kappa(Z).

Proof. By independence, E e∑tq(Yq+Zq)=E e∑tqYq E e∑tqZq\mathbb E\, e^{\sum t_q (Y_q + Z_q)} = \mathbb E\, e^{\sum t_q Y_q}\, \mathbb E\, e^{\sum t_q Z_q}, so the cumulant generating functions add. □\square

Claim 4 (independent groups). If {1,…,n}\{1, \ldots, n\} splits into two nonempty groups AA and BB such that (Xq)q∈A(X_q)_{q \in A} is independent of (Xq)q∈B(X_q)_{q \in B}, then κ(X1,…,Xn)=0\kappa(X_1, \ldots, X_n) = 0.

Proof. K(t)K(t) is then the sum of a function of (tq)q∈A(t_q)_{q \in A} and a function of (tq)q∈B(t_q)_{q \in B}, and neither has a term with all of t1,…,tnt_1, \ldots, t_n. □\square

Claim 5 (the SOFI formula). Under the model assumptions, if the lags are distinct,

Cn(r)=∑kεkn U(r−rk)n κn[sk](τ),κn[sk](τ)=κ(sk(t+τ1),…,sk(t+τn)).C_n(r) = \sum_k \varepsilon_k^n\, U(r - r_k)^n\, \kappa_n[s_k](\tau), \qquad \kappa_n[s_k](\tau) = \kappa\bigl(s_k(t + \tau_1), \ldots, s_k(t + \tau_n)\bigr).

Proof. The background is a constant, which Claim 2 removes. The emitters and the noise are independent, so by Claim 3 the cumulant is the sum of one cumulant per emitter and one for the noise. The noise values at the nn distinct frames are independent, so by Claim 4 the noise cumulant is 00. For emitter kk, Claim 2 with aq=εkU(r−rk)a_q = \varepsilon_k U(r - r_k) gives the factor εknU(r−rk)n\varepsilon_k^n U(r - r_k)^n. □\square

With equal lags, the noise cumulant is the nn-th cumulant of the noise at one frame, for example its variance σ2\sigma^2 when n=2n = 2. The test measures this bias for n=2n = 2 and checks that the lag 11 removes it.

Claim 6 (single emitter, exact). For one emitter and a constant background, the empirical SOFI image is exactly εnU(r−r1)n\varepsilon^n U(r - r_1)^n times the empirical cumulant of the lagged blinking series, for any lags, at every pixel.

Proof. Without noise, F(r,t)=b(r)+εU(r−r1)s(t)F(r, t) = b(r) + \varepsilon U(r - r_1) s(t) for every tt. Apply Claim 2 to the empirical law. □\square

The test checks this in exact rational arithmetic for n=2,3,4n = 2, 3, 4.

Claim 7 (narrowing). If U(r)=e−∣r∣2/(2σ2)U(r) = e^{-|r|^2/(2\sigma^2)}, then Un(r)=e−∣r∣2/(2σ2/n)U^n(r) = e^{-|r|^2/(2\sigma^2/n)}, a Gaussian of width σ/n\sigma/\sqrt n. For any PSF whose OTF vanishes outside a disk of radius kck_c, the Fourier transform of UnU^n vanishes outside the disk of radius nkcn k_c.

Proof. The first part is algebra. The Fourier transform of UnU^n is the nn-fold convolution of the OTF with itself, whose support lies in the nn-fold sum of the disk, the disk of radius nkcn k_c. □\square

So the n\sqrt n narrowing is a statement about a Gaussian PSF. For another PSF, UnU^n is narrower too, but by a different factor, and the support of its spectrum grows by nn; a later deconvolution can use the larger support.

Claim 8 (blinking cumulants). For a stationary two-state process with P(off→on)=aP(\text{off} \to \text{on}) = a, P(on→off)=bP(\text{on} \to \text{off}) = b and the on fraction ρ=a/(a+b)\rho = a/(a + b):

  • with all lags equal, κ2=ρ(1−ρ)\kappa_2 = \rho(1 - \rho), κ3=ρ(1−ρ)(1−2ρ)\kappa_3 = \rho(1 - \rho)(1 - 2\rho) and κ4=ρ(1−ρ)(1−6ρ(1−ρ))\kappa_4 = \rho(1 - \rho)(1 - 6\rho(1 - \rho)), the cumulants of a Bernoulli law;
  • with the lags 00 and 11, κ2=ρ(1−ρ)(1−a−b)\kappa_2 = \rho(1 - \rho)(1 - a - b).

Proof. At one time ss is Bernoulli with mean ρ\rho. Since sj=ss^j = s, all raw moments are ρ\rho, and the centered moments are μ2=ρ(1−ρ)\mu_2 = \rho(1 - \rho), μ3=ρ(1−ρ)(1−2ρ)\mu_3 = \rho(1 - \rho)(1 - 2\rho) and μ4=ρ(1−ρ)(1−3ρ+3ρ2)\mu_4 = \rho(1 - \rho)(1 - 3\rho + 3\rho^2). Claim 1 gives κ4=μ4−3μ22=ρ(1−ρ)(1−3ρ(1−ρ)−3ρ(1−ρ))\kappa_4 = \mu_4 - 3\mu_2^2 = \rho(1 - \rho)(1 - 3\rho(1 - \rho) - 3\rho(1 - \rho)). For the lag 11, E[s(t)s(t+1)]=ρ(1−b)\mathbb E[s(t)s(t + 1)] = \rho(1 - b), so κ2=ρ(1−b)−ρ2=ρ(1−b−ρ)\kappa_2 = \rho(1 - b) - \rho^2 = \rho(1 - b - \rho), and (a+b)(1−b)−a=b(1−a−b)(a + b)(1 - b) - a = b(1 - a - b) gives 1−b−ρ=(1−ρ)(1−a−b)1 - b - \rho = (1 - \rho)(1 - a - b). □\square

So κ4<0\kappa_4 < 0 when ρ(1−ρ)>1/6\rho(1 - \rho) > 1/6, that is for 0.211<ρ<0.7890.211 < \rho < 0.789: the fourth order image can change sign between emitters with different on fractions. The test checks the Bernoulli values exactly for ρ=3/10\rho = 3/10, where they are 0.210.21, 0.0840.084 and −0.0546-0.0546.

Remark (estimation). The claims about CnC_n are about the cumulant of the process. The code computes the cumulant of the empirical law of a finite window, which is a biased but consistent estimate for ergodic blinking and noise: the cross terms between emitters and the noise terms are 00 only in the limit of long movies. This is the role of the measurement tests with long series. ■\blacksquare

Complexity

Each pixel needs nn lagged copies of its series, of length at most TT, and the moment formulas cost Θ(T)\Theta(T) per product, with a number of products that depends only on nn. Over NN pixels this is Θ(nNT)\Theta(n N T) time for the orders 22 to 44, and Θ(N+nT)\Theta(N + nT) extra space for the output and the series of one pixel. The partition formula for a general order has a number of terms that grows like the Bell number of nn, which is why codes use explicit formulas for small nn.

Properties

  • Background-free. A constant background has no fluctuations and drops out exactly.
  • Noise-free in expectation with distinct lags. Noise independent between frames has zero cumulant across different frames.
  • Nonlinear in brightness. Emitter kk enters with εknκn[sk]\varepsilon_k^n \kappa_n[s_k]. Bright or strongly blinking emitters dominate, and dim ones vanish as nn grows.
  • Sign changes. Odd and higher cumulants can be negative. For n=4n = 4 and on fractions between 0.2110.211 and 0.7890.789 the factor κ4\kappa_4 is negative, so emitters with different blinking can give values of opposite sign.
  • Needs many frames. The cumulant estimates have a variance that grows quickly with nn, so higher orders need longer movies.

Variants and improvements

  • Cross-cumulants. Use different pixels for the nn factors. For a Gaussian PSF, the cross-cumulant of pixels r1,…,rnr_1, \ldots, r_n is UnU^n centered at the mean of the pixel positions, times a factor that depends only on the distances between the pixels. So it adds new virtual pixels between the real ones and removes the noise even at zero lag, as the noise of different pixels is independent.
  • Deconvolution after SOFI. Since the spectrum of UnU^n reaches nkcn k_c, a deconvolution of the cumulant image can push the resolution gain from n\sqrt n toward nn.
  • Balanced SOFI. Combine cumulants of several orders to cancel the brightness and the blinking factor, and so estimate the brightness, the on fraction and the positions.
  • Lags in time. Longer lags reduce the effect of slow drifts but need blinking that stays correlated over the lag.

When to use it

Use SOFI when the emitters blink independently, as quantum dots and many dyes do, but are too dense for single-molecule localization, or when the frame rate and the photon budget favor a simple pixelwise computation. It works with a plain widefield microscope, removes the background, and needs no fitting. For the highest resolution with sparse emitters, localization methods give tens of nanometers. For samples that do not blink, use SIM or deconvolution.

Pitfalls

  • Correlated blinking or drift. The formula needs independent emitters and a still sample. Drift, bleaching or a common flicker of the lamp add cross terms. Correct the drift and split long movies into blocks.
  • Equal lags. With zero lag, white noise adds to the cumulant. Use distinct lags or cross-cumulants.
  • Short movies. Finite movies leave cross terms between emitters of the order of the statistical error. Check that the image does not change much with half of the frames.
  • Reading values as densities. The value at a pixel scales with εnκn\varepsilon^n\kappa_n, not with the number of emitters. Use balanced SOFI or another method for counting.
  • Expecting n\sqrt n for any PSF. The factor n\sqrt n holds for a Gaussian PSF.

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.

sofi.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sofi/. The authors are listed in prov/70NF24.jsonl.
"""Super-resolution optical fluctuation imaging (SOFI): pixelwise cumulants.

A movie is a list of T frames, each an image movie[t][i][j]. The SOFI image
of order n with the time lags (tau_1, ..., tau_n) is, at each pixel, the
sample joint cumulant of the n series X_q(t) = F(t + tau_q), for
t = 0, ..., T - 1 - max(tau). Sample moments are means over these windows.

With distinct lags, noise that is independent from frame to frame adds
nothing to the cumulant in expectation; a constant background adds nothing
exactly. Works with float and fractions.Fraction values.
"""

import math


def _mean(xs):
    return sum(xs) / len(xs)


def _centered(xs):
    m = _mean(xs)
    return [x - m for x in xs]


def cumulant(series):
    """The sample joint cumulant of 2, 3 or 4 equal-length series.

    On the centered series a, b, c, d:
      order 2: E[ab]
      order 3: E[abc]
      order 4: E[abcd] - E[ab] E[cd] - E[ac] E[bd] - E[ad] E[bc]
    """
    n = len(series)
    if n not in (2, 3, 4):
        raise ValueError("order must be 2, 3 or 4")
    z = [_centered(s) for s in series]
    length = len(z[0])
    if n == 2:
        return _mean([z[0][t] * z[1][t] for t in range(length)])
    if n == 3:
        return _mean([z[0][t] * z[1][t] * z[2][t] for t in range(length)])

    def m2(p, q):
        return _mean([z[p][t] * z[q][t] for t in range(length)])

    m4 = _mean([z[0][t] * z[1][t] * z[2][t] * z[3][t] for t in range(length)])
    return m4 - m2(0, 1) * m2(2, 3) - m2(0, 2) * m2(1, 3) - m2(0, 3) * m2(1, 2)


def set_partitions(items):
    """All partitions of the list items into nonempty blocks."""
    if not items:
        yield []
        return
    first, rest = items[0], items[1:]
    for part in set_partitions(rest):
        yield [[first]] + part
        for i in range(len(part)):
            yield part[:i] + [[first] + part[i]] + part[i + 1:]


def cumulant_by_partitions(series):
    """The sample joint cumulant of any order by the partition formula.

    kappa = sum over partitions pi of (-1)^(|pi| - 1) (|pi| - 1)! prod_B E[prod_{q in B} X_q],
    with raw (not centered) sample moments.
    """
    length = len(series[0])
    total = 0
    for part in set_partitions(list(range(len(series)))):
        k = len(part)
        term = (-1) ** (k - 1) * math.factorial(k - 1)
        for block in part:
            prod = [1] * length
            for q in block:
                prod = [p * v for p, v in zip(prod, series[q])]
            term = term * _mean(prod)
        total += term
    return total


def lagged(s, lags):
    """The series X_q(t) = s(t + lags[q]) for t = 0, ..., len(s) - 1 - max(lags)."""
    length = len(s) - max(lags)
    if length < 2:
        raise ValueError("the movie is too short for these lags")
    return [s[tau:tau + length] for tau in lags]


def sofi_image(movie, order=2, lags=None):
    """The SOFI image of the given order: the joint cumulant of lagged series at each pixel.

    lags defaults to (0, 1, ..., order - 1), so all lags are distinct.
    """
    if lags is None:
        lags = tuple(range(order))
    if len(lags) != order:
        raise ValueError("one lag per factor")
    n1, n2 = len(movie[0]), len(movie[0][0])
    out = [[0] * n2 for _ in range(n1)]
    for i in range(n1):  # @line L1
        for j in range(n2):  # @line L1
            s = [frame[i][j] for frame in movie]  # @line L2
            xs = lagged(s, lags)  # @line L3
            out[i][j] = cumulant(xs)  # @line L4 L5
    return out  # @line L6


def mean_image(movie):
    """The widefield image: the time mean of each pixel."""
    n1, n2 = len(movie[0]), len(movie[0][0])
    return [[_mean([f[i][j] for f in movie]) for j in range(n2)] for i in range(n1)]


def markov_blinking(rng, length, a, b, on=None):
    """A two-state blinking series: P(off -> on) = a, P(on -> off) = b.

    The stationary on fraction is rho = a / (a + b), and the lag-1
    covariance is rho (1 - rho) (1 - a - b). The first state is drawn from
    the stationary law unless on is given.
    """
    if on is None:
        on = rng.random() < a / (a + b)
    out = []
    for _ in range(length):
        out.append(1 if on else 0)
        u = rng.random()
        on = (u >= b) if on else (u < a)
    return out


def gaussian_psf(dist2, sigma):
    """exp(-d^2 / (2 sigma^2)) for the squared distance d^2."""
    return math.exp(-dist2 / (2 * sigma * sigma))


def simulate_movie(rng, shape, emitters, sigma, length, a, b, background=0.0, noise=0.0):
    """A movie of blinking emitters with a Gaussian PSF.

    emitters is a list of (row, column, brightness) with real coordinates.
    Each frame is background + sum_k brightness_k s_k(t) U(r - r_k) plus
    independent N(0, noise^2) values.
    """
    n1, n2 = shape
    weights = [[[gaussian_psf((i - r) ** 2 + (j - c) ** 2, sigma) * e for j in range(n2)]
                for i in range(n1)] for r, c, e in emitters]
    states = [markov_blinking(rng, length, a, b) for _ in emitters]
    movie = []
    for t in range(length):
        frame = [[background] * n2 for _ in range(n1)]
        for k, w in enumerate(weights):
            if states[k][t]:
                for i in range(n1):
                    for j in range(n2):
                        frame[i][j] += w[i][j]
        if noise > 0:
            for i in range(n1):
                for j in range(n2):
                    frame[i][j] += rng.gauss(0.0, noise)
        movie.append(frame)
    return movie
test_sofi.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sofi/. The authors are listed in prov/70NF24.jsonl.

import math
import random
from fractions import Fraction as F

from sofi import (
    cumulant,
    cumulant_by_partitions,
    lagged,
    markov_blinking,
    mean_image,
    simulate_movie,
    sofi_image,
)


def test_moment_formulas_match_partition_formula():
    rng = random.Random(1)
    for order in (2, 3, 4):
        xs = [[F(rng.randint(-5, 9)) for _ in range(12)] for _ in range(order)]
        assert cumulant(xs) == cumulant_by_partitions(xs)


def test_bernoulli_cumulants():
    s = [F(1)] * 3 + [F(0)] * 7  # the empirical law is Bernoulli(3/10)
    rho = F(3, 10)
    assert cumulant([s, s]) == rho * (1 - rho) == F(21, 100)
    assert cumulant([s, s, s]) == rho * (1 - rho) * (1 - 2 * rho) == F(84, 1000)
    k4 = rho * (1 - rho) * (1 - 6 * rho * (1 - rho))
    assert cumulant([s, s, s, s]) == k4 == F(-546, 10000)


def test_single_emitter_is_exact_and_background_free():
    rng = random.Random(2)
    blink = [F(rng.randint(0, 1)) for _ in range(40)]
    psf = [F(1, 9), F(1, 2), F(1), F(1, 2), F(1, 9)]
    eps, bg = F(7), F(3)
    movie = [[[bg + eps * u * st for u in psf]] for st in blink]
    for order in (2, 3, 4):
        img = sofi_image(movie, order)
        k = cumulant(lagged(blink, tuple(range(order))))
        for j, u in enumerate(psf):
            assert img[0][j] == u ** order * eps ** order * k


def test_lags_remove_white_noise():
    rng = random.Random(3)
    a, b, sigma = 0.2, 0.2, 0.5
    s = markov_blinking(rng, 40000, a, b)
    noisy = [v + rng.gauss(0.0, sigma) for v in s]
    rho = a / (a + b)
    var = rho * (1 - rho)
    lag1 = var * (1 - a - b)
    c0 = cumulant(lagged(noisy, (0, 0)))
    c1 = cumulant(lagged(noisy, (0, 1)))
    assert abs(c0 - (var + sigma ** 2)) < 0.02
    assert abs(c1 - lag1) < 0.02


def test_markov_lag_covariance():
    rng = random.Random(4)
    a, b = 0.1, 0.2
    s = markov_blinking(rng, 50000, a, b)
    rho = a / (a + b)
    assert abs(sum(s) / len(s) - rho) < 0.02
    assert abs(cumulant(lagged(s, (0, 1))) - rho * (1 - rho) * (1 - a - b)) < 0.015


def test_second_order_resolves_two_emitters():
    # Two emitters 2 sigma apart: the mean image has no dip between them,
    # the second order SOFI image has one.
    rng = random.Random(5)
    sigma = 2.0
    movie = simulate_movie(rng, (1, 15), [(0, 5, 1.0), (0, 9, 1.0)], sigma, 4000,
                           0.3, 0.3, background=2.0, noise=0.05)
    wf = mean_image(movie)[0]
    s2 = sofi_image(movie, 2)[0]
    assert wf[7] > wf[5] and wf[7] > wf[9]
    assert s2[7] < 0.85 * min(s2[5], s2[9])


def test_order_n_narrows_a_gaussian_by_sqrt_n():
    # One emitter: the SOFI image of order n is U^n times a constant, a
    # Gaussian of width sigma / sqrt(n).
    rng = random.Random(6)
    sigma = 1.5
    blink = markov_blinking(rng, 200, 0.3, 0.3)
    psf = [math.exp(-(j - 6) ** 2 / (2 * sigma ** 2)) for j in range(13)]
    movie = [[[u * st for u in psf]] for st in blink]
    for order in (2, 3, 4):
        img = sofi_image(movie, order)[0]
        for j in range(13):
            want = math.exp(-order * (j - 6) ** 2 / (2 * sigma ** 2))
            assert abs(img[j] / img[6] - want) < 1e-9

History

Dertinger and coworkers introduced SOFI in 2009, using blinking quantum dots. They showed that the cumulant image of order nn is the sum of the nn-th powers of the PSFs, free of background, and they also showed 3D images. Later work developed cross-cumulants for extra pixels, deconvolution of the cumulant images, balanced SOFI for the brightness and the on fraction, and SOFI with dyes and fluorescent proteins.

References

  1. T. Dertinger, R. Colyer, G. Iyer, S. Weiss and J. Enderlein, Fast, background-free, 3D super-resolution optical fluctuation imaging (SOFI), Proceedings of the National Academy of Sciences 106(52), 2009, 22287 to 22292, the model of independent blinking emitters, the cumulant of order n as a sum of n-th powers of the PSF, the removal of background and noise, and the narrowing by the square root of n for a Gaussian PSF

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
  • at least three sources
  • a scene preset for the example