Algorithm Search⌘K

Algorithmadvanced

Richardson-Lucy with total variation regularization

Also called RLTV.

Richardson-Lucy for Poisson data with a total variation penalty added one step late: divide each update by 1 - lam div(grad x/|grad x|) to damp noise and keep edges.

Time
Θ(K n m) worst · average · best
Space
Θ(n) extra
Where
K = the number of iterations; m = the number of nonzero PSF entries; n = the number of pixels
Properties
deterministiciterativenot linearnot monotone objectivenonnegativepoisson noise model
Origin
Nicolas Dey, Laure Blanc Feraud, Christophe Zimmer, Pascal Roux, Zvi Kam, Jean Christophe Olivo Marin, Josiane Zerubia, 2006

Richardson-Lucy with total variation regularization (RLTV) is a deblurring method for photon-count images. It takes the multiplicative update of Richardson-Lucy, which is the EM algorithm for Poisson data, and divides it by a factor that comes from the total variation of the estimate:

x←x1−λdiv⁡ ⁣(∇x/∣∇x∣) (h~∗yh∗x).x \leftarrow \frac{x}{1 - \lambda \operatorname{div}\!\big(\nabla x / |\nabla x|\big)}\, \Big(\tilde h \ast \frac{y}{h \ast x}\Big).

Plain Richardson-Lucy fits the noise when it runs long, and the estimate breaks up into bright specks. The extra factor is larger than 1 at a local maximum of the estimate and smaller than 1 at a local minimum, so isolated peaks and pits are pulled toward their neighbors, while large flat regions and straight edges are left mostly alone. Dey and coauthors (2006) proposed it for 3D confocal microscopy. The step is the one-step-late form of maximum a posteriori estimation with a total variation prior: a positive fixed point minimizes the Poisson negative log-likelihood plus λ\lambda times the total variation. Unlike plain Richardson-Lucy it has no monotonicity theorem.

In plain words

You have a dim, blurred microscope image made of counted photons, and you know the blur. Richardson-Lucy improves a guess by blurring it, comparing it with the data, and multiplying each pixel by how much light is still missing there. If you repeat this many times, the guess starts to copy the random grain of the photon counts, and it turns into sharp specks. RLTV adds one more rule to each round. A pixel that stands above all its neighbors is made a little smaller, and a pixel that sits in a hole is made a little larger. A pixel in a smooth area or on a long straight edge is barely changed. One number sets how strong this rule is. Too weak, and the specks come back. Too strong, and the image turns into flat patches and the rounds can start to swing back and forth.

The problem

The unknown is a nonnegative image xx with nn pixels (2D or 3D). The data are counts yi∼Poisson((h∗x)i)y_i \sim \text{Poisson}((h \ast x)_i), independent across pixels, with a known PSF h≥0h \ge 0, ∑h=1\sum h = 1 (see point spread function and Poisson distribution). The blur is periodic convolution with the PSF centered at index 00; its adjoint is correlation, h~(r)=h(−r)\tilde h(r) = h(-r). The goal is the minimizer over x≥0x \ge 0 of

J(x)=∑i[(h∗x)i−yilog⁡(h∗x)i]+λ∑i∣∇x∣ε,i,J(x) = \sum_i \big[(h \ast x)_i - y_i \log (h \ast x)_i\big] + \lambda \sum_i |\nabla x|_{\varepsilon, i},

the negative log-likelihood plus λ\lambda times the total variation. Here ∇\nabla is the forward difference, ∣g∣ε=g12+g22+ε2|g|_\varepsilon = \sqrt{g_1^2 + g_2^2 + \varepsilon^2}, and the small ε>0\varepsilon > 0 makes the total variation differentiable. In Bayesian terms JJ is the negative log-posterior for the prior exp⁡(−λ TV(x))\exp(-\lambda\, \mathrm{TV}(x)), so its minimizer is a MAP estimate.

The algorithm

  1. RLTV(y, h, lambda, K, x0, eps) ▷ x0 > 0, default the constant mean of y
  2. 1x ← x0
  3. 2repeat K times
  4. 3c ← h~ * (y / (h * x)) ▷ Richardson-Lucy correction, two convolutions
  5. 4kappa ← div(grad x / |grad x|_eps) ▷ curvature of the level lines, in [-4, 4]
  6. 5d ← 1 - lambda · kappa ▷ stop with an error if some d ≤ 0
  7. 6x ← x · c / d ▷ pixel by pixel
  8. 7return x

Line L3 is the Richardson-Lucy correction; a ratio y/(h∗x)y/(h \ast x) with yi=0y_i = 0 counts as 00. Line L4 uses forward differences for ∇\nabla and backward differences for div⁡\operatorname{div}, so that div⁡\operatorname{div} is the negative adjoint of ∇\nabla. Line L5 is the one-step-late term: the derivative of the total variation is taken at the current estimate. With λ=0\lambda = 0 the method is Richardson-Lucy.

Example

The effect of L4 to L6 is easiest to see with a delta PSF, where c=y/xc = y/x. Take a 5×55 \times 5 periodic image of ones with one pixel of value 2 at the center, y=x0y = x_0, λ=0.1\lambda = 0.1 and ε=10−3\varepsilon = 10^{-3}. Then c=1c = 1, and the step only divides by dd. The curvature κ\kappa is, to four places:

pixel κ\kappa d=1−0.1 κd = 1 - 0.1\,\kappa x1x_1
center (value 2) −2−2=−3.4142-2 - \sqrt 2 = -3.4142 1.3414 1.4910
above and left of it 1.0000 0.9000 1.1111
below and right of it 0.7071 0.9293 1.0761
all others 0 1 1

The peak is pulled down and its neighbors go up. The asymmetry between the neighbors comes from the one-sided differences. The next step has c=y/x1≠1c = y/x_1 \ne 1, which pulls the estimate back toward the data, and the two forces fight. In this case the iteration does not settle: a measurement over 500 steps shows a period-2 checkerboard around the center for λ=0.02\lambda = 0.02, 0.050.05 and 0.10.1, and it converges only for λ=0.01\lambda = 0.01 with ε=0.1\varepsilon = 0.1.

With a real blur the method works as intended. A measurement on one seed: a 16×1616 \times 16 image with background 20 and a 7×77 \times 7 square of value 80, a 5×55 \times 5 Gaussian PSF with σ=1\sigma = 1 pixel, Poisson counts, x0x_0 the constant mean and ε=10−2\varepsilon = 10^{-2}. The error ∥xK−x†∥\lVert x_K - x^\dagger\rVert of the raw data is 165.7.

KK RL (λ=0\lambda = 0) RLTV, λ=0.005\lambda = 0.005 RLTV, λ=0.02\lambda = 0.02 RLTV, λ=0.05\lambda = 0.05
10 143.2 135.0 121.9 119.2
20 160.8 138.6 110.2 111.0
40 196.9 147.7 103.1 104.5
80 259.5 159.1 100.7 102.8
200 391.5 172.0 101.5 108.1

Plain Richardson-Lucy is best near 10 steps and then fits the noise (semi-convergence). With λ=0.02\lambda = 0.02 the error keeps falling to about 100 and stays there. In the same runs, JJ decreased in every step for λ=0\lambda = 0, as the EM theorem says, but not for any of the three positive values.

Correctness

The full proof is in proofs/correctness.md. With cc and κ\kappa as in lines L3 and L4:

  1. Gradients. ∇L=1−c\nabla L = 1 - c for the Poisson term LL (because ∑h=1\sum h = 1), and the gradient of the smoothed total variation is −κ-\kappa.
  2. A scaled gradient step. x+−x=−x1−λκ ∇J(x)x^+ - x = -\dfrac{x}{1 - \lambda\kappa}\, \nabla J(x) pixel by pixel.
  3. Fixed points. A positive xx with d>0d > 0 is a fixed point if and only if ∇J(x)=0\nabla J(x) = 0. JJ is convex, so such a point is a global minimizer of JJ over x≥0x \ge 0.
  4. Positivity. ∣κ∣≤4|\kappa| \le 4 in 2D (2⋅2 \cdot dimension in general). So for λ<1/4\lambda < 1/4 (in 3D, λ<1/6\lambda < 1/6) the denominator is at least 1−4λ>01 - 4\lambda > 0, and a positive start stays nonnegative without clipping.
  5. Reduction. For λ=0\lambda = 0 the step is the EM step of Richardson-Lucy, which never increases the likelihood term and keeps the total flux.

The proof does not show that JJ decreases or that the iterates converge for λ>0\lambda > 0, and the measurements above show that neither holds in general.

Proof: The RLTV step is a scaled gradient step, its positive fixed points minimize the regularized Poisson objective, and it keeps the estimate nonnegative for lam < 1/4full

Setting. Images have nn pixels on a periodic grid. The blur is periodic convolution Ax=h∗xAx = h \ast x with h≥0h \ge 0 and ∑h=1\sum h = 1, and the adjoint A∗A^\ast is correlation, A∗v=h~∗vA^\ast v = \tilde h \ast v with h~(r)=h(−r)\tilde h(r) = h(-r). The data y≥0y \ge 0 are counts. For x>0x > 0 with Ax>0Ax > 0 define

L(x)=∑i[(Ax)i−yilog⁡(Ax)i],Tε(x)=∑i(∇1x)i2+(∇2x)i2+ε2,J(x)=L(x)+λTε(x),L(x) = \sum_i \big[(Ax)_i - y_i \log (Ax)_i\big], \qquad T_\varepsilon(x) = \sum_i \sqrt{(\nabla_1 x)_i^2 + (\nabla_2 x)_i^2 + \varepsilon^2}, \qquad J(x) = L(x) + \lambda T_\varepsilon(x),

with forward differences (∇1x)i,j=xi+1,j−xi,j(\nabla_1 x)_{i,j} = x_{i+1,j} - x_{i,j} and (∇2x)i,j=xi,j+1−xi,j(\nabla_2 x)_{i,j} = x_{i,j+1} - x_{i,j}, and div⁡\operatorname{div} the backward difference operator, so that ⟨∇x,p⟩=−⟨x,div⁡p⟩\langle \nabla x, p\rangle = -\langle x, \operatorname{div} p\rangle. Write

c=A∗ ⁣(yAx),κ=div⁡ ⁣(∇x∣∇x∣ε),∣g∣ε=g12+g22+ε2.c = A^\ast\!\left(\frac{y}{Ax}\right), \qquad \kappa = \operatorname{div}\!\left(\frac{\nabla x}{|\nabla x|_\varepsilon}\right), \qquad |g|_\varepsilon = \sqrt{g_1^2 + g_2^2 + \varepsilon^2}.

Lines L3 to L6 compute x+=x c/(1−λκ)x^+ = x\, c / (1 - \lambda\kappa), entry by entry, with λ≥0\lambda \ge 0 and ε>0\varepsilon > 0.

Claim 1 (gradients). ∇L(x)=1−c\nabla L(x) = \mathbf 1 - c and ∇Tε(x)=−κ\nabla T_\varepsilon(x) = -\kappa.

Proof. ∂L/∂xj=∑iAij(1−yi/(Ax)i)=(A∗1)j−cj\partial L/\partial x_j = \sum_i A_{ij}(1 - y_i/(Ax)_i) = (A^\ast \mathbf 1)_j - c_j, and A∗1=∑h=1A^\ast \mathbf 1 = \sum h = 1 at every pixel. For TεT_\varepsilon, the derivative of ∣g∣2+ε2\sqrt{|g|^2 + \varepsilon^2} in gg is g/∣g∣εg/|g|_\varepsilon, so by the chain rule ∇Tε=∇∗(∇x/∣∇x∣ε)=−div⁡(∇x/∣∇x∣ε)=−κ\nabla T_\varepsilon = \nabla^\ast(\nabla x / |\nabla x|_\varepsilon) = -\operatorname{div}(\nabla x/|\nabla x|_\varepsilon) = -\kappa. □\square

Claim 2 (a scaled gradient step). If 1−λκ>01 - \lambda\kappa > 0 at every pixel, then

x+−x=−x1−λκ ∇J(x).x^+ - x = -\frac{x}{1 - \lambda\kappa}\, \nabla J(x).

Proof. By Claim 1, ∇J=1−c−λκ\nabla J = \mathbf 1 - c - \lambda\kappa. So x c/(1−λκ)−x=x (c−1+λκ)/(1−λκ)=−x∇J/(1−λκ)x\,c/(1 - \lambda\kappa) - x = x\,(c - 1 + \lambda\kappa)/(1 - \lambda\kappa) = -x \nabla J/(1 - \lambda\kappa). □\square

This is the one-step-late form of Green (1990): the derivative of the prior is taken at the current estimate and placed in the denominator of the EM step.

Claim 3 (fixed points). Let x>0x > 0 at every pixel with 1−λκ>01 - \lambda\kappa > 0. Then x+=xx^+ = x if and only if ∇J(x)=0\nabla J(x) = 0, and then xx is a global minimizer of JJ over the set {x≥0, Ax>0}\{x \ge 0,\ Ax > 0\}.

Proof. The scale x/(1−λκ)x/(1 - \lambda\kappa) in Claim 2 is positive, so x+=xx^+ = x exactly when ∇J(x)=0\nabla J(x) = 0. LL is convex, because −log⁡-\log is convex and AxAx is linear in xx. TεT_\varepsilon is convex, because g↦∣g∣εg \mapsto |g|_\varepsilon is a norm of (g1,g2,ε)(g_1, g_2, \varepsilon) composed with an affine map. So JJ is convex, and a point where its gradient is zero is a global minimizer on the convex domain where JJ is defined. □\square

Claim 4 (the denominator is positive for lam < 1/4). Every entry of κ\kappa lies in [−4,4][-4, 4]. So for 0≤λ<1/40 \le \lambda < 1/4, 1−λκ≥1−4λ>01 - \lambda\kappa \ge 1 - 4\lambda > 0 at every pixel and every xx.

Proof. Let p=∇x/∣∇x∣εp = \nabla x / |\nabla x|_\varepsilon. Then ∣p1∣≤1|p_1| \le 1 and ∣p2∣≤1|p_2| \le 1, because ∣g1∣≤∣g∣ε|g_1| \le |g|_\varepsilon. The entry κi,j=p1;i,j−p1;i−1,j+p2;i,j−p2;i,j−1\kappa_{i,j} = p_{1;i,j} - p_{1;i-1,j} + p_{2;i,j} - p_{2;i,j-1} is a sum of four terms of modulus at most 11. □\square

In dd dimensions the same argument gives ∣κ∣≤2d|\kappa| \le 2d, so λ<1/(2d)\lambda < 1/(2d); for 3D stacks, λ<1/6\lambda < 1/6.

Claim 5 (nonnegativity). If x≥0x \ge 0, Ax>0Ax > 0 where y>0y > 0, and 1−λκ>01 - \lambda\kappa > 0, then x+≥0x^+ \ge 0. A pixel with xj=0x_j = 0 stays 00.

Proof. c=A∗(y/Ax)c = A^\ast(y/Ax) is a sum of nonnegative terms, so c≥0c \ge 0. The factors xx, cc and 1/(1−λκ)1/(1 - \lambda\kappa) are nonnegative. □\square

With Claim 4, the iteration started from a positive image never leaves the nonnegative orthant when λ<1/4\lambda < 1/4, without any clipping. For larger λ\lambda the denominator can become zero or negative at a local minimum of xx, where κ>0\kappa > 0; the code raises an error then.

Claim 6 (lam = 0 is Richardson-Lucy). For λ=0\lambda = 0, x+=x A∗(y/Ax)x^+ = x\, A^\ast(y/Ax), the EM step for Poisson data with A∗1=1A^\ast\mathbf 1 = \mathbf 1. Then L(x+)≤L(x)L(x^+) \le L(x) (the EM monotonicity theorem), and ∑jxj+=∑i: yi>0yi\sum_j x^+_j = \sum_{i:\,y_i > 0} y_i.

Proof. The first part is the EM update with column sums 11. For the sum, ∑jxjcj=∑jxj∑ihi−j yi/(Ax)i=∑i: yi>0yi (Ax)i/(Ax)i\sum_j x_j c_j = \sum_j x_j \sum_i h_{i-j}\, y_i/(Ax)_i = \sum_{i:\, y_i > 0} y_i\, (Ax)_i/(Ax)_i. □\square

What is not claimed. For λ>0\lambda > 0 the step is not an EM step, and Claim 2 does not give a descent: the scaled gradient step has no step size control. JJ need not decrease, and the iterates need not converge. A measurement in the page shows both effects. ■\blacksquare

Complexity

In the real-RAM model one iteration costs two convolutions for L3 and Θ(n)\Theta(n) for L4 to L6. A direct convolution with mm nonzero PSF entries costs Θ(nm)\Theta(nm); with the FFT and the OTF computed once, Θ(nlog⁡n)\Theta(n \log n). So KK iterations cost Θ(Knm)\Theta(Knm) or Θ(Knlog⁡n)\Theta(Kn\log n). The extra space is Θ(n)\Theta(n) for the ratio, the correction and the two gradient images. The total variation term adds about the cost of a few vector operations per step, so RLTV costs about the same per iteration as Richardson-Lucy. It usually needs more iterations, since the regularized result is the limit and not an early-stopped iterate.

Properties

  • Nonnegative: for λ<1/4\lambda < 1/4 in 2D and a positive start, every iterate is nonnegative (Claim 4 of the proof).
  • Nonlinear in yy, and the noise model is Poisson, as for Richardson-Lucy.
  • The total flux is not kept exactly for λ>0\lambda > 0; in the first example it rises from 26 to about 27.5.
  • A pixel that becomes 00 stays 00, as in Richardson-Lucy.
  • The result depends on λ\lambda and ε\varepsilon. Total variation favors piecewise constant images: edges stay sharp, but smooth ramps turn into steps (staircasing) and small low-contrast details are lost.

Variants and improvements

  • 3D stacks. The original use: the same step with 3D differences, often with a different spacing along the optical axis. The positivity bound becomes λ<1/6\lambda < 1/6.
  • Other priors in the one-step-late form. Any differentiable prior UU gives x←x c/(1+λ∇U(x))x \leftarrow x\,c/(1 + \lambda \nabla U(x)); Green (1990) introduced this form for emission tomography (see the one-step-late algorithm). Tikhonov and entropy priors are common choices.
  • Convergent splittings. To minimize the same JJ with a guarantee, use a primal-dual or splitting method, such as split Bregman or ADMM, with the total variation handled by a proximal step such as Chambolle's projection. These cost more per iteration but do not oscillate.
  • Damped steps. Replace x+x^+ by x+t(x+−x)x + t(x^+ - x) with t∈(0,1]t \in (0, 1] chosen by a line search on JJ; by Claim 2 the direction is a scaled descent direction, so a small enough tt lowers JJ.

When to use it

Use RLTV for fluorescence microscopy, confocal stacks and other photon-limited images when the object is made of regions with sharp borders, the PSF is known and the noise is close to Poisson. It is a small change to an existing Richardson-Lucy code, which makes it popular in practice. Pick λ\lambda well below 1/41/4, relative to the scale of the counts, and watch the result for oscillation. When the object has smooth gradients, such as a diffuse cell body, total variation causes staircasing, and a smoother prior or plain Richardson-Lucy with early stopping may be better. When a guaranteed minimizer of JJ is needed, use a convergent splitting method.

Pitfalls

  • The step is not EM for λ>0\lambda > 0. JJ can rise from one step to the next, and the iterates can oscillate, as in the first example. A large λ\lambda makes this worse.
  • If 1−λκ≤01 - \lambda\kappa \le 0 at a pixel, the step gives a negative or infinite value. For λ<1/4\lambda < 1/4 in 2D this cannot happen.
  • A very small ε\varepsilon makes κ\kappa jump between ±4\pm 4 for tiny changes of the estimate in flat regions, which amplifies the oscillation. A larger ε\varepsilon is safer (a heuristic; in the first example only ε=0.1\varepsilon = 0.1 converged).
  • Total variation depends on the image scale: λ\lambda that works for counts near 100 is far too strong for counts near 1, because the Poisson term scales with the counts and the total variation term with their differences.
  • The periodic boundary links opposite borders. Pad the image, or use another boundary rule, when the object touches the border.
  • The quality depends on the PSF model. A PSF that ignores the depth-dependent aberration of the Gibson-Lanni model gives artifacts deep in the sample, whatever λ\lambda is.

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
richardson_lucy_total_variation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/richardson-lucy-total-variation/. The authors are listed in prov/DC5KCE.jsonl.
"""Richardson-Lucy with total variation regularization (RLTV), after Dey et al. (2006).

Images are lists of rows. The blur is periodic 2D convolution with a PSF h of
the image size, stored with its center at (0, 0), h >= 0 and sum h = 1. The
update is

    x <- x / (1 - lam div(grad x / |grad x|_eps)) * (h~ * (y / (h * x)))

with forward differences for grad, the negative adjoint (backward
differences) for div, a periodic border and |g|_eps = sqrt(g1^2 + g2^2 + eps^2).
"""

import math

from imgkit import circ_conv2


def mirror(h):
    """The PSF h(-r) on the same periodic grid."""
    n1, n2 = len(h), len(h[0])
    return [[h[(-i) % n1][(-j) % n2] for j in range(n2)] for i in range(n1)]


def grad(x):
    """Forward differences with a periodic border: (x[i+1][j] - x[i][j], x[i][j+1] - x[i][j])."""
    n1, n2 = len(x), len(x[0])
    g1 = [[x[(i + 1) % n1][j] - x[i][j] for j in range(n2)] for i in range(n1)]
    g2 = [[x[i][(j + 1) % n2] - x[i][j] for j in range(n2)] for i in range(n1)]
    return g1, g2


def div(p1, p2):
    """Backward differences, the negative adjoint of grad: <grad x, p> = -<x, div p>."""
    n1, n2 = len(p1), len(p1[0])
    return [[p1[i][j] - p1[(i - 1) % n1][j] + p2[i][j] - p2[i][(j - 1) % n2] for j in range(n2)] for i in range(n1)]


def tv_curvature(x, eps):
    """div(grad x / |grad x|_eps). Every entry lies in [-4, 4]."""
    g1, g2 = grad(x)
    n1, n2 = len(x), len(x[0])
    p1 = [[0.0] * n2 for _ in range(n1)]
    p2 = [[0.0] * n2 for _ in range(n1)]
    for i in range(n1):
        for j in range(n2):
            m = math.sqrt(g1[i][j] ** 2 + g2[i][j] ** 2 + eps * eps)
            p1[i][j] = g1[i][j] / m
            p2[i][j] = g2[i][j] / m
    return div(p1, p2)


def tv(x, eps):
    """The smoothed total variation sum sqrt(g1^2 + g2^2 + eps^2)."""
    g1, g2 = grad(x)
    return sum(math.sqrt(a * a + b * b + eps * eps) for ra, rb in zip(g1, g2) for a, b in zip(ra, rb))


def neg_log_likelihood(x, y, h):
    """sum (h * x - y log(h * x)), the Poisson negative log-likelihood up to a constant."""
    b = circ_conv2(x, h)
    total = 0.0
    for rb, ry in zip(b, y):
        for bi, yi in zip(rb, ry):
            total += bi - (yi * math.log(bi) if yi > 0 else 0.0)
    return total


def objective(x, y, h, lam, eps):
    """The functional that RLTV is built from: the Poisson term plus lam times TV."""
    return neg_log_likelihood(x, y, h) + lam * tv(x, eps)


def rl_correction(x, y, h, ht=None):
    """c = h~ * (y / (h * x)), the Richardson-Lucy correction factor."""
    if ht is None:
        ht = mirror(h)
    b = circ_conv2(x, h)
    r = [[(yi / bi if yi > 0 else 0.0) for bi, yi in zip(rb, ry)] for rb, ry in zip(b, y)]
    return circ_conv2(r, ht)


def rltv(y, h, lam, iters, x0=None, eps=1e-3, callback=None):
    """Run iters RLTV steps from x0 (default: the constant mean of y). lam = 0 gives Richardson-Lucy."""
    n1, n2 = len(y), len(y[0])
    if x0 is None:
        mean = sum(map(sum, y)) / (n1 * n2)
        x0 = [[mean] * n2 for _ in range(n1)]
    ht = mirror(h)
    x = [list(row) for row in x0]  # @line L1
    for k in range(iters):  # @line L2
        c = rl_correction(x, y, h, ht)  # @line L3
        kappa = tv_curvature(x, eps)  # @line L4
        new = []
        for i in range(n1):
            row = []
            for j in range(n2):
                d = 1.0 - lam * kappa[i][j]  # @line L5
                if d <= 0.0:
                    raise ValueError("1 - lam div(grad x / |grad x|) <= 0; lower lam")
                row.append(x[i][j] * c[i][j] / d)  # @line L6
            new.append(row)
        x = new
        if callback is not None:
            callback(k + 1, x)
    return x  # @line L7
test_richardson_lucy_total_variation.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/richardson-lucy-total-variation/. The authors are listed in prov/DC5KCE.jsonl.

import math
import random

import pytest

from imgkit import circ_conv2, img_norm, poisson_sample
from richardson_lucy_total_variation import (
    div,
    grad,
    neg_log_likelihood,
    objective,
    rl_correction,
    rltv,
    tv,
    tv_curvature,
)


def gaussian_psf(n, sigma):
    h = [[0.0] * n for _ in range(n)]
    for di in range(-2, 3):
        for dj in range(-2, 3):
            h[di % n][dj % n] = math.exp(-(di * di + dj * dj) / (2 * sigma * sigma))
    s = sum(map(sum, h))
    return [[v / s for v in row] for row in h]


def rand_img(rng, n1, n2, lo=0.5, hi=3.0):
    return [[rng.uniform(lo, hi) for _ in range(n2)] for _ in range(n1)]


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


def diff(a, b):
    return [[p - q for p, q in zip(ra, rb)] for ra, rb in zip(a, b)]


def numeric_grad(f, x, h=1e-6):
    out = []
    for i in range(len(x)):
        row = []
        for j in range(len(x[0])):
            xp = [list(r) for r in x]
            xm = [list(r) for r in x]
            xp[i][j] += h
            xm[i][j] -= h
            row.append((f(xp) - f(xm)) / (2 * h))
        out.append(row)
    return out


def matrix_em_step(x, y, h):
    """The EM update for Poisson data with an explicit blur matrix, as a reference."""
    n1, n2 = len(x), len(x[0])
    n = n1 * n2
    a = [[h[(i1 - j1) % n1][(i2 - j2) % n2] for j1 in range(n1) for j2 in range(n2)]
         for i1 in range(n1) for i2 in range(n2)]
    xv = [v for row in x for v in row]
    yv = [v for row in y for v in row]
    b = [sum(a[i][j] * xv[j] for j in range(n)) for i in range(n)]
    col = [sum(a[i][j] for i in range(n)) for j in range(n)]
    out = [xv[j] / col[j] * sum(a[i][j] * yv[i] / b[i] for i in range(n) if yv[i] > 0) for j in range(n)]
    return [out[i * n2:(i + 1) * n2] for i in range(n1)]


def test_div_is_the_negative_adjoint_of_grad():
    rng = random.Random(1)
    x = rand_img(rng, 5, 7, -1, 1)
    p1, p2 = rand_img(rng, 5, 7, -1, 1), rand_img(rng, 5, 7, -1, 1)
    g1, g2 = grad(x)
    lhs = inner(g1, p1) + inner(g2, p2)
    rhs = -inner(x, div(p1, p2))
    scale = math.sqrt(img_norm(g1) ** 2 + img_norm(g2) ** 2) * math.sqrt(img_norm(p1) ** 2 + img_norm(p2) ** 2)
    assert abs(lhs - rhs) <= 1e-10 * scale


def test_blur_adjoint():
    rng = random.Random(2)
    h = gaussian_psf(8, 1.0)
    x, y = rand_img(rng, 8, 8, -1, 1), rand_img(rng, 8, 8, -1, 1)
    hx = circ_conv2(x, h)
    ht = [[h[(-i) % 8][(-j) % 8] for j in range(8)] for i in range(8)]
    assert abs(inner(hx, y) - inner(x, circ_conv2(y, ht))) <= 1e-10 * img_norm(hx) * img_norm(y)


def test_tv_curvature_is_minus_the_tv_gradient_and_is_bounded():
    rng = random.Random(3)
    x = rand_img(rng, 6, 6)
    eps = 0.1
    num = numeric_grad(lambda z: tv(z, eps), x)
    kappa = tv_curvature(x, eps)
    for rn, rk in zip(num, kappa):
        for a, b in zip(rn, rk):
            assert abs(a + b) < 1e-6
    for _ in range(5):
        z = rand_img(rng, 6, 6, 0, 10)
        assert all(-4 <= v <= 4 for row in tv_curvature(z, 1e-6) for v in row)


def test_poisson_gradient_is_one_minus_the_rl_correction():
    rng = random.Random(4)
    h = gaussian_psf(6, 0.8)
    x = rand_img(rng, 6, 6)
    y = [[float(rng.randint(0, 5)) for _ in range(6)] for _ in range(6)]
    num = numeric_grad(lambda z: neg_log_likelihood(z, y, h), x)
    c = rl_correction(x, y, h)
    for rn, rc in zip(num, c):
        for a, b in zip(rn, rc):
            assert abs(a - (1 - b)) < 1e-6


def test_the_step_is_a_scaled_gradient_step():
    # x+ - x = -(x / (1 - lam kappa)) * grad J, so x is a fixed point exactly where grad J = 0.
    rng = random.Random(5)
    h = gaussian_psf(6, 0.8)
    x = rand_img(rng, 6, 6)
    y = [[float(rng.randint(0, 6)) for _ in range(6)] for _ in range(6)]
    lam, eps = 0.05, 0.2
    num = numeric_grad(lambda z: objective(z, y, h, lam, eps), x)
    kappa = tv_curvature(x, eps)
    xp = rltv(y, h, lam, 1, x0=x, eps=eps)
    for i in range(6):
        for j in range(6):
            expect = x[i][j] - x[i][j] / (1 - lam * kappa[i][j]) * num[i][j]
            assert abs(xp[i][j] - expect) < 1e-5


def test_lam_zero_is_richardson_lucy():
    rng = random.Random(6)
    h = gaussian_psf(6, 1.0)
    y = [[float(rng.randint(0, 9)) for _ in range(6)] for _ in range(6)]
    mean =sum(map(sum, y)) / 36
    ref = [[mean] * 6 for _ in range(6)]
    for _ in range(3):
        ref = matrix_em_step(ref, y, h)
    x = rltv(y, h, 0.0, 3)
    assert img_norm(diff(x, ref)) < 1e-10 * img_norm(ref)


def test_delta_psf_gives_the_data_in_one_step():
    rng = random.Random(7)
    delta = [[1.0 if (i, j) == (0, 0) else 0.0 for j in range(5)] for i in range(5)]
    y = rand_img(rng, 5, 5)
    x = rltv(y, delta, 0.0, 1, x0=rand_img(rng, 5, 5))
    assert img_norm(diff(x, y)) < 1e-12 * img_norm(y)


def test_positivity_for_small_lam_and_failure_for_large_lam():
    rng = random.Random(8)
    h = gaussian_psf(8, 1.0)
    y = [[float(rng.randint(0, 20)) for _ in range(8)] for _ in range(8)]
    x = rltv(y, h, 0.24, 20, eps=1e-6)
    assert all(v >= 0 for row in x for v in row)
    pit = [[1.0] * 8 for _ in range(8)]
    pit[3][3] = 0.01
    with pytest.raises(ValueError):
        rltv(y, h, 0.5, 1, x0=pit, eps=1e-6)


def test_tv_term_lowers_the_error_on_noisy_counts():
    # A measurement on one seed: a piecewise constant phantom, Poisson counts, 80 iterations.
    n = 16
    rng = random.Random(9)
    xt = [[20.0 + (60.0 if 4 <= i < 11 and 5 <= j < 12 else 0.0) for j in range(n)] for i in range(n)]
    h = gaussian_psf(n, 1.0)
    b = circ_conv2(xt, h)
    y = [[float(poisson_sample(rng, v)) for v in row] for row in b]
    rl = rltv(y, h, 0.0, 80)
    tvx = rltv(y, h, 0.02, 80, eps=1e-2)
    e_rl = img_norm(diff(rl, xt))
    e_tv = img_norm(diff(tvx, xt))
    assert e_tv < 0.9 * e_rl

History

W. H. Richardson (1972) and L. B. Lucy (1974) introduced the multiplicative iteration, and Shepp and Vardi (1982) showed it is the EM algorithm for Poisson emission data. Rudin, Osher and Fatemi (1992) introduced total variation for noise removal. P. J. Green (1990) proposed the one-step-late modification of EM for MAP estimation with a prior in emission tomography. Dey, Blanc-Feraud, Zimmer, Roux, Kam, Olivo-Marin and Zerubia (2006) put total variation into this form for 3D confocal microscopy.

References

  1. N. Dey, L. Blanc-Feraud, C. Zimmer, P. Roux, Z. Kam, J.-C. Olivo-Marin and J. Zerubia, Richardson-Lucy algorithm with total variation regularization for 3D confocal microscope deconvolution, Microscopy Research and Technique 69(4), 2006, pages 260 to 266
  2. William Hadley Richardson, Bayesian-based iterative method of image restoration, Journal of the Optical Society of America 62(1), 1972, pages 55 to 59
  3. L. B. Lucy, An iterative technique for the rectification of observed distributions, The Astronomical Journal 79, 1974, the article from page 745
  4. Leonid I. Rudin, Stanley Osher and Emad Fatemi, Nonlinear total variation based noise removal algorithms, Physica D 60(1-4), 1992, pages 259 to 268

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