Algorithm Search⌘K

Algorithmintro

Van Cittert deconvolution

Also called Van Cittert iteration.

Deblur by x <- x + beta (y - h * x), adding back the residual. It converges where |1 - beta H| < 1, so it is Landweber for a positive OTF and fails where the OTF is negative.

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
deterministiciterativelinearmonotone error for positive otfneeds early stoppingnot nonnegative
Origin
Pieter Hendrik van Cittert, Peter A. Jansson, 1931

Van Cittert deconvolution is the oldest iterative deblurring method. It undoes a known blur hh by adding back the part of the data that the current estimate does not explain: x←x+β (y−h∗x)x \leftarrow x + \beta\,(y - h \ast x). P. H. van Cittert used it in 1931 to remove the effect of the slit width from measured spectral lines. In the language of linear algebra it is the Richardson iteration for the system h∗x=yh \ast x = y. In the Fourier domain each frequency is treated on its own: the error at frequency kk is multiplied by 1−βHk1 - \beta H_k in every step, where HH is the optical transfer function. So the method converges exactly at the frequencies where ∣1−βHk∣<1|1 - \beta H_k| < 1. For a PSF with a positive OTF it is the Landweber iteration in another form, with the same filter factors 1−(1−βHk)K1 - (1 - \beta H_k)^K. For a PSF whose OTF is negative somewhere, such as a box or a defocus blur, it diverges, and the fix is to apply the mirrored PSF to the residual, which is Landweber. Unlike Richardson-Lucy it is linear, does not keep the estimate nonnegative and has no noise model; with noise it must be stopped early.

In plain words

You have a blurred picture and you know the blur. Start with a blank guess, or with the blurred picture itself. Blur your guess the same way the camera did, and compare it with the real picture. The difference shows what your guess still misses. Add that difference, or a fixed fraction of it, to your guess, and repeat. Coarse features are fixed in a few rounds, because the blur keeps them almost intact. Fine detail is weakened a lot by the blur, so it comes back slowly, a little in each round. If the blur turns some patterns upside down, as an out-of-focus lens does, adding the difference pushes those patterns the wrong way, and the guess gets worse. Noise in the picture also comes back with the detail, so you stop after a moderate number of rounds.

The problem

The unknown is a signal or an image xx with nn pixels, and the data are y=h∗x+ey = h \ast x + e with a known PSF hh and noise ee. The blur is periodic convolution, (h∗x)i=∑jhj x(i−j) mod n(h \ast x)_i = \sum_j h_j\, x_{(i - j) \bmod n}, with the PSF stored with its center at index 00, so that a delta PSF gives the identity. This boundary condition makes the blur matrix circulant, and the DFT diagonalizes it: h∗x^k=Hkx^k\widehat{h \ast x}_k = H_k \hat x_k with Hk=∑jhje−2πijk/nH_k = \sum_j h_j e^{-2\pi i jk/n} (see discrete Fourier transform). Usually h≥0h \ge 0 and ∑h=1\sum h = 1, so H0=1H_0 = 1 and ∣Hk∣≤1|H_k| \le 1. The goal is an estimate of xx; without noise, the minimum norm solution of h∗x=yh \ast x = y.

The algorithm

  1. VAN-CITTERT(y, h, beta, K, x0) ▷ beta > 0, default beta = 1, x0 = 0
  2. 1x ← x0
  3. 2repeat K times
  4. 3r ← y - h * x ▷ residual, one periodic convolution
  5. 4x ← x + beta · r
  6. 5return x

Line L3 blurs the estimate and subtracts it from the data. Line L4 adds a fraction β\beta of the residual. The classic form has β=1\beta = 1 and x0=yx_0 = y, which is the same as x0=0x_0 = 0 with one more step.

Example

Take n=6n = 6, the PSF h0=2/3h_0 = 2/3, h±1=1/6h_{\pm 1} = 1/6, and the true signal x†=(0,0,6,0,0,0)x^\dagger = (0, 0, 6, 0, 0, 0). The data are y=h∗x†=(0,1,4,1,0,0)y = h \ast x^\dagger = (0, 1, 4, 1, 0, 0). The OTF is Hk=2/3+(1/3)cos⁡(2πk/6)H_k = 2/3 + (1/3)\cos(2\pi k/6), which is 11, 5/65/6, 1/21/2 and 1/31/3 for k=0,1,2,3k = 0, 1, 2, 3. All values are positive, so with β=1\beta = 1 every error component shrinks by the factor 1−Hk1 - H_k, at worst 2/32/3. With x0=0x_0 = 0 the iterates are, in exact arithmetic:

KK xKx_K ∥xK−x†∥\lVert x_K - x^\dagger \rVert
1 (0,1,4,1,0,0)(0, 1, 4, 1, 0, 0) 2.4495
2 (−1/6,2/3,5,2/3,−1/6,0)(-1/6, 2/3, 5, 2/3, -1/6, 0) 1.3944
3 (−1/6,5/12,49/9,5/12,−1/6,1/18)(-1/6, 5/12, 49/9, 5/12, -1/6, 1/18) 0.8453
4 (−0.1343,0.2593,5.6759,0.2593,−0.1343,0.0741)(-0.1343, 0.2593, 5.6759, 0.2593, -0.1343, 0.0741) 0.5301
6 (−0.0721,0.1034,5.8809,0.1034,−0.0721,0.0566)(-0.0721, 0.1034, 5.8809, 0.1034, -0.0721, 0.0566) 0.2218

The peak grows back toward 6 and the error falls in every step, as Claim 3 of the proof says. The estimate has negative values, although the true signal and the data are nonnegative: this is the ringing of a linear method, and the reason for the bounded variant below.

For a PSF with a negative OTF the picture changes. The box of width 5 on 16 points has H4=−1/5H_4 = -1/5. With β=1\beta = 1 the error at frequency 4 is multiplied by 1.21.2 in every step, so after 10 more steps it is 1.210=6.191.2^{10} = 6.19 times larger. No positive β\beta helps, because ∣1−βH4∣=1+β/5>1|1 - \beta H_4| = 1 + \beta/5 > 1.

Correctness

The full proof is in proofs/correctness.md. The main facts, for periodic convolution and real β>0\beta > 0:

  1. Closed form. From x0=0x_0 = 0, xK=β∑j<K(I−βA)jyx_K = \beta\sum_{j<K}(I - \beta A)^j y, and in the Fourier domain x^K,k=fk y^k/Hk\hat x_{K,k} = f_k\, \hat y_k / H_k with the filter factors fk=1−(1−βHk)Kf_k = 1 - (1 - \beta H_k)^K (for Hk≠0H_k \ne 0). This is the spectral filter form of Landweber, with βHk\beta H_k in place of ωσ2\omega\sigma^2.
  2. Convergence with exact data. If y=h∗x†y = h \ast x^\dagger, the error at frequency kk is −(1−βHk)Kx^k†-(1 - \beta H_k)^K \hat x^\dagger_k. So xKx_K converges to the minimum norm solution for every x†x^\dagger if and only if ∣1−βHk∣<1|1 - \beta H_k| < 1 at every frequency with Hk≠0H_k \ne 0; that is, every nonzero HkH_k lies in the open disk of center 1/β1/\beta and radius 1/β1/\beta. For a symmetric PSF the OTF is real, and the condition is 0<βHk<20 < \beta H_k < 2.
  3. Monotone error. Under that condition the error norm never grows (Parseval).
  4. Divergence. If ∣1−βHk∣>1|1 - \beta H_k| > 1 for some kk, the error at that frequency grows geometrically for any x†x^\dagger that has it.
  5. Noise. With y=h∗x†+ey = h\ast x^\dagger + e, the limit is x†x^\dagger plus the noise term e^k/Hk\hat e_k / H_k, which is large where ∣Hk∣|H_k| is small, and a frequency with Hk=0H_k = 0 and e^k≠0\hat e_k \ne 0 grows like Kβe^kK\beta\hat e_k. The iterates show semi-convergence: the error first falls and then rises.
Proof: The Van Cittert iterate is a spectral filter, and it converges exactly where |1 - beta H| < 1full

Setting. Signals have length nn (an image is the same with a 2D index and the 2D DFT). The blur is periodic convolution Ax=h∗xAx = h \ast x with the PSF stored with its center at index 00. The DFT is x^k=∑jxje−2πijk/n\hat x_k = \sum_j x_j e^{-2\pi i jk/n}, and Hk=h^kH_k = \hat h_k. By the convolution theorem for the DFT, Ax^k=Hkx^k\widehat{Ax}_k = H_k \hat x_k, so AA is diagonal in the Fourier basis. The step size β>0\beta > 0 is real. The iteration is lines L1 to L4:

x0=0,xK+1=xK+β (y−AxK).x_0 = 0, \qquad x_{K+1} = x_K + \beta\,(y - A x_K).

Claim 1 (closed form). For every K≥0K \ge 0,

xK=β∑j=0K−1(I−βA)j y,x^K,k={1−(1−βHk)KHk y^kHk≠0,Kβ y^kHk=0.x_K = \beta \sum_{j=0}^{K-1} (I - \beta A)^j\, y, \qquad \hat x_{K,k} = \begin{cases} \dfrac{1 - (1 - \beta H_k)^K}{H_k}\, \hat y_k & H_k \ne 0, \\[2mm] K \beta\, \hat y_k & H_k = 0. \end{cases}

Proof. By induction on KK. For K=0K = 0 both sides are 00. If the formula holds for KK, then xK+1=(I−βA)xK+βy=β∑j=1K(I−βA)jy+βyx_{K+1} = (I - \beta A) x_K + \beta y = \beta \sum_{j=1}^{K} (I - \beta A)^j y + \beta y, which is the formula for K+1K + 1. In the Fourier basis I−βAI - \beta A is multiplication by 1−βHk1 - \beta H_k, and the geometric sum is β∑j<K(1−βHk)j=(1−(1−βHk)K)/Hk\beta \sum_{j<K} (1 - \beta H_k)^j = (1 - (1 - \beta H_k)^K)/H_k for Hk≠0H_k \ne 0, and KβK\beta for Hk=0H_k = 0. □\square

So xKx_K is a spectral filter of the naive inverse y^k/Hk\hat y_k / H_k with the filter factors fk=1−(1−βHk)Kf_k = 1 - (1 - \beta H_k)^K, the Landweber form with β\beta in place of ω\omega and HkH_k in place of σ2\sigma^2. The identity in Claim 1 is exact in rational arithmetic; the test compares the code with the matrix series.

Claim 2 (exact data). Let y=Ax†y = A x^\dagger, and let PP be the orthogonal projection onto the frequencies with Hk≠0H_k \ne 0, so that Px†Px^\dagger is the minimum norm solution of Ax=yAx = y. Then

(xK−Px†)^k={−(1−βHk)K x^k†Hk≠0,0Hk=0.\widehat{(x_K - P x^\dagger)}_k = \begin{cases} -(1 - \beta H_k)^K\, \hat x^\dagger_k & H_k \ne 0, \\ 0 & H_k = 0. \end{cases}

Hence xK→Px†x_K \to P x^\dagger for every x†x^\dagger if and only if ∣1−βHk∣<1|1 - \beta H_k| < 1 for every kk with Hk≠0H_k \ne 0.

Proof. y^k=Hkx^k†\hat y_k = H_k \hat x^\dagger_k. For Hk≠0H_k \ne 0, Claim 1 gives x^K,k=(1−(1−βHk)K)x^k†\hat x_{K,k} = (1 - (1 - \beta H_k)^K)\hat x^\dagger_k, and (Px†)^k=x^k†\widehat{(Px^\dagger)}_k = \hat x^\dagger_k. For Hk=0H_k = 0, y^k=0\hat y_k = 0, so x^K,k=0=(Px†)^k\hat x_{K,k} = 0 = \widehat{(Px^\dagger)}_k. The sequence (1−βHk)K(1 - \beta H_k)^K tends to 00 if ∣1−βHk∣<1|1 - \beta H_k| < 1. If ∣1−βHk∣≥1|1 - \beta H_k| \ge 1 for some kk with Hk≠0H_k \ne 0, take x†x^\dagger with only the frequency kk (and −k-k for a real signal); then the error has modulus ∣1−βHk∣K∣x^k†∣≥∣x^k†∣>0|1 - \beta H_k|^K |\hat x^\dagger_k| \ge |\hat x^\dagger_k| > 0 at every KK, and it grows geometrically if ∣1−βHk∣>1|1 - \beta H_k| > 1. □\square

Claim 3 (the error never grows). If ∣1−βHk∣≤1|1 - \beta H_k| \le 1 for every kk and y=Ax†y = Ax^\dagger, then ∥xK+1−Px†∥≤∥xK−Px†∥\|x_{K+1} - Px^\dagger\| \le \|x_K - Px^\dagger\|.

Proof. By Claim 2 each Fourier coefficient of the error is multiplied by 1−βHk1 - \beta H_k in each step, or stays 00. Its modulus does not grow. By Parseval, ∥v∥2=1n∑k∣v^k∣2\|v\|^2 = \frac1n \sum_k |\hat v_k|^2, so the norm does not grow. □\square

Claim 4 (real symmetric PSF). If hj=h−jh_j = h_{-j} is real, then every HkH_k is real, and the condition of Claim 2 is 0<βHk<20 < \beta H_k < 2 for every kk with Hk≠0H_k \ne 0. If HH takes values of both signs, no β>0\beta > 0 satisfies it.

Proof. Hk=h0+∑j≥1hj(e−2πijk/n+e2πijk/n)H_k = h_0 + \sum_{j \ge 1} h_j (e^{-2\pi i jk/n} + e^{2\pi i jk/n}) is real. For real t=βHkt = \beta H_k, ∣1−t∣<1|1 - t| < 1 if and only if 0<t<20 < t < 2. A negative HkH_k gives 1−βHk>11 - \beta H_k > 1 for every β>0\beta > 0. □\square

For the box of width 5 on 16 points, H4=−1/5H_4 = -1/5, and the error at frequency 4 is multiplied by 1.21.2 in each step for β=1\beta = 1.

Claim 5 (the Landweber variant). The iteration xK+1=xK+βA∗(y−AxK)x_{K+1} = x_K + \beta A^\ast (y - Ax_K), with A∗A^\ast the correlation with hh, multiplies the error at frequency kk by 1−β∣Hk∣21 - \beta |H_k|^2. For 0<β<2/max⁡k∣Hk∣20 < \beta < 2/\max_k |H_k|^2 it converges to Px†Px^\dagger for every PSF and exact data, and its error never grows.

Proof. A∗v^k=Hk‾ v^k\widehat{A^\ast v}_k = \overline{H_k}\, \hat v_k, because the adjoint of a diagonal operator in an orthogonal basis has the conjugate diagonal. So the step is the one of Claim 2 with Hk‾Hk=∣Hk∣2\overline{H_k} H_k = |H_k|^2 in place of HkH_k, and 0<β∣Hk∣2<20 < \beta |H_k|^2 < 2 for every Hk≠0H_k \ne 0. Claims 2 and 3 apply. □\square

Noisy data. If y=Ax†+ey = Ax^\dagger + e, Claim 1 gives x^K,k=fkx^k†+fke^k/Hk\hat x_{K,k} = f_k \hat x^\dagger_k + f_k \hat e_k / H_k for Hk≠0H_k \ne 0. Under the condition of Claim 2, fk→1f_k \to 1, and xKx_K tends to Px†+A+ePx^\dagger + A^{+} e, whose noise term is e^k/Hk\hat e_k / H_k and is large where ∣Hk∣|H_k| is small. For Hk=0H_k = 0 and e^k≠0\hat e_k \ne 0 the coefficient Kβe^kK\beta\hat e_k grows without bound. So with noise the iteration must be stopped early. ■\blacksquare

Complexity

In the real-RAM model, one iteration is one convolution and two vector operations. A direct periodic convolution with a PSF of mm nonzero entries costs Θ(nm)\Theta(nm); with the FFT and the OTF computed once, it costs Θ(nlog⁡n)\Theta(n \log n) for nn a power of two. So KK iterations cost Θ(Knm)\Theta(Knm) or Θ(Knlog⁡n)\Theta(K n \log n), and the extra space is Θ(n)\Theta(n) for the residual. The number of iterations is the regularization parameter. With exact data the error at frequency kk falls like ∣1−βHk∣K|1 - \beta H_k|^K, so reaching a relative error ε\varepsilon at that frequency takes about log⁡(1/ε)/∣log⁡∣1−βHk∣∣\log(1/\varepsilon)/|\log|1 - \beta H_k|| steps, which is about log⁡(1/ε)/(βHk)\log(1/\varepsilon)/(\beta H_k) for small positive HkH_k. With a periodic boundary and no other constraint the whole run equals one filtered division in the Fourier domain, which costs Θ(nlog⁡n)\Theta(n \log n) in total; the iteration is worth its cost only when a constraint is applied in each step or when the blur is not a convolution.

Properties

  • Linear in yy: xKx_K is a fixed filter applied to the data.
  • No noise model. It is not the maximum likelihood method of any noise law, and it does not keep the estimate nonnegative.
  • The total flux is kept in the limit: x^K,0=(1−(1−β)K) y^0\hat x_{K,0} = (1 - (1 - \beta)^K)\, \hat y_0 for H0=1H_0 = 1, and with β=1\beta = 1 the sum of xKx_K equals the sum of yy from the first step on.
  • The step β\beta trades speed against safety. For a real positive OTF with Hk≤1H_k \le 1, any 0<β<20 < \beta < 2 converges, and β=1\beta = 1 removes the zero frequency error in one step.

Variants and improvements

  • Landweber form. Apply the adjoint of the blur, correlation with hh, to the residual: x←x+β h~∗(y−h∗x)x \leftarrow x + \beta\, \tilde h \ast (y - h \ast x) with h~(r)=h(−r)\tilde h(r) = h(-r). The factor becomes 1−β∣Hk∣21 - \beta |H_k|^2, so it converges for 0<β<2/max⁡∣Hk∣20 < \beta < 2/\max|H_k|^2 for every PSF, at the price of a second convolution and slower progress where ∣Hk∣|H_k| is small. This is the Landweber iteration for the blur.
  • Bounded or constrained Van Cittert. Jansson, Hunt and Plyler (1970) scaled the correction by a relaxation function that falls to zero at the physical bounds of the signal, so the estimate stays between them. A simpler version clips xx to x≥0x \ge 0 after each step, which is projected Landweber when the Landweber form is used. Constraints make the method nonlinear and can bring back some frequencies with small ∣Hk∣|H_k|.
  • Damped form. Add the term −βαx-\beta\alpha x to the Landweber step. The fixed point is then (A∗A+αI)−1A∗y(A^\ast A + \alpha I)^{-1} A^\ast y, the solution of Tikhonov regularization, so the iteration no longer needs early stopping.
  • Multiplicative instead of additive. Richardson-Lucy multiplies by a ratio instead of adding a difference, which keeps the estimate nonnegative and is maximum likelihood for Poisson counts.

When to use it

Use it as a simple first deblurring step, or as a teaching example of a spectral filter, when the PSF is symmetric and has a positive OTF, for example a Gaussian blur, and the noise is low. Stop it early, with the discrepancy principle when the noise level is known. Use the Landweber form for any PSF whose OTF may be negative or complex, such as defocus, motion blur or a box. For photon counts use Richardson-Lucy, and for a fixed linear answer use the Wiener filter, which gets the same kind of result in one FFT pass.

Pitfalls

  • A negative OTF value makes the plain iteration diverge at that frequency, whatever β\beta is. Defocus and box blurs have negative lobes. Check the sign of HH before you use the plain form.
  • An OTF zero with noise in the data makes that frequency grow linearly in KK.
  • The method shows semi-convergence: run long enough, it fits the noise. The number of iterations must be chosen; without a known noise level any stopping rule is a heuristic.
  • With a zero or reflexive boundary the blur matrix is not circulant, the Fourier analysis is only an approximation, and ringing appears at the image border.
  • The estimate can go negative near sharp edges, as in the example. Clip it, or use a constrained variant, if negative values break later steps.
  • A PSF that does not sum to 1 changes the scale of HH; with ∑h=s\sum h = s the condition for β=1\beta = 1 fails when s≥2s \ge 2.

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
van_cittert_deconvolution.py 98 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/van-cittert-deconvolution/. The authors are listed in prov/3D8AWP.jsonl.
"""Van Cittert deconvolution: x <- x + beta (y - h * x).

Signals are lists and images are lists of rows. The blur is periodic
convolution with the PSF h stored with its center at index 0 (wrapped
around), so a delta PSF gives the identity. Works with float and with
fractions.Fraction values.
"""

from imgkit import circ_conv, circ_conv2, dft, dft2


def _is_image(x):
    return bool(x) and isinstance(x[0], (list, tuple))


def blur(x, h):
    """The periodic convolution h * x of a signal or an image."""
    if _is_image(x):
        return circ_conv2(x, h)
    return circ_conv(x, h)


def mirror(h):
    """The PSF h(-r) on the same periodic grid, so that blur(., mirror(h)) is the adjoint of blur(., h)."""
    if _is_image(h):
        n1, n2 = len(h), len(h[0])
        return [[h[(-i) % n1][(-j) % n2] for j in range(n2)] for i in range(n1)]
    n = len(h)
    return [h[(-j) % n] for j in range(n)]


def blur_adjoint(y, h):
    """The adjoint of x -> h * x for real h: correlation with h."""
    return blur(y, mirror(h))


def _zero_like(y):
    if _is_image(y):
        return [[0 * v for v in row] for row in y]
    return [0 * v for v in y]


def _axpy(x, beta, r):
    if _is_image(x):
        return [[a + beta * b for a, b in zip(ra, rb)] for ra, rb in zip(x, r)]
    return [a + beta * b for a, b in zip(x, r)]


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


def van_cittert(y, h, beta=1, iters=10, x0=None, callback=None):
    """Run iters steps of x <- x + beta (y - h * x) from x0 (default 0).

    callback(k, x) is called after each step, if given. Returns the last x.
    """
    x = _zero_like(y) if x0 is None else x0  # @line L1
    for k in range(iters):  # @line L2
        r = _sub(y, blur(x, h))  # @line L3
        x = _axpy(x, beta, r)  # @line L4
        if callback is not None:
            callback(k + 1, x)
    return x  # @line L5


def van_cittert_landweber(y, h, beta=1, iters=10, x0=None):
    """The variant x <- x + beta h~ * (y - h * x), which is Landweber for the blur."""
    x = _zero_like(y) if x0 is None else x0
    for _ in range(iters):
        r = _sub(y, blur(x, h))
        x = _axpy(x, beta, blur_adjoint(r, h))
    return x


def otf(h):
    """The discrete OTF H_k = DFT(h)_k of a PSF stored with its center at index 0."""
    if _is_image(h):
        return dft2(h)
    return dft(h)


def filter_factors(h, beta, iters):
    """f_k = 1 - (1 - beta H_k)^iters, the factor of the Van Cittert iterate from x0 = 0."""
    if _is_image(h):
        return [[1 - (1 - beta * v) ** iters for v in row] for row in otf(h)]
    return [1 - (1 - beta * v) ** iters for v in otf(h)]


def converges(h, beta, tol=1e-12):
    """True when |1 - beta H_k| < 1 at every frequency with H_k != 0."""
    hs = otf(h)
    vals = [v for row in hs for v in row] if _is_image(h) else hs
    return all(abs(1 - beta * v) < 1 - tol for v in vals if abs(v) > tol)
test_van_cittert_deconvolution.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/van-cittert-deconvolution/. The authors are listed in prov/3D8AWP.jsonl.

import math
import random
from fractions import Fraction as F

from imgkit import dft, disk_phantom, gauss_noise, img_norm
from van_cittert_deconvolution import (
    blur,
    blur_adjoint,
    converges,
    filter_factors,
    otf,
    van_cittert,
    van_cittert_landweber,
)


def norm(v):
    return math.sqrt(sum(abs(t) ** 2 for t in v))


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


def psf_1d(n, taps):
    """A PSF of length n with taps[d] at offset d (d may be negative), centered at index 0."""
    h = [0] * n
    for d, v in taps.items():
        h[d % n] += v
    return h


def test_delta_psf_is_the_identity():
    rng = random.Random(1)
    x = [rng.uniform(-1, 1) for _ in range(12)]
    delta = [1] + [0] * 11
    assert blur(x, delta) == x
    assert van_cittert(x, delta, beta=1, iters=1) == x
    img = [[rng.random() for _ in range(5)] for _ in range(4)]
    delta2 = [[1 if (i, j) == (0, 0) else 0 for j in range(5)] for i in range(4)]
    assert blur(img, delta2) == img


def test_adjoint_of_the_blur():
    rng = random.Random(2)
    for n in (8, 13, 16):
        h = [rng.random() for _ in range(n)]
        x = [rng.gauss(0, 1) for _ in range(n)]
        y = [rng.gauss(0, 1) for _ in range(n)]
        ax = blur(x, h)
        gap = abs(sum(a * b for a, b in zip(ax, y)) - sum(a * b for a, b in zip(x, blur_adjoint(y, h))))
        assert gap <= 1e-10 * norm(ax) * norm(y)
    h2 = [[rng.random() for _ in range(6)] for _ in range(5)]
    x2 = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(5)]
    y2 = [[rng.gauss(0, 1) for _ in range(6)] for _ in range(5)]
    ax2 = blur(x2, h2)
    lhs = sum(a * b for ra, rb in zip(ax2, y2) for a, b in zip(ra, rb))
    rhs = sum(a * b for ra, rb in zip(x2, blur_adjoint(y2, h2)) for a, b in zip(ra, rb))
    assert abs(lhs - rhs) <= 1e-10 * img_norm(ax2) * img_norm(y2)


def test_exact_iterates_match_the_matrix_series():
    # x_K = beta sum_{j < K} (I - beta A)^j y with the dense circulant matrix A.
    rng = random.Random(3)
    for _ in range(5):
        n = rng.choice([5, 6, 8])
        raw = [rng.randint(0, 3) for _ in range(n)]
        raw[0] += 1
        h = [F(v, sum(raw)) for v in raw]
        a = [[h[(i - j) % n] for j in range(n)] for i in range(n)]
        beta = F(rng.randint(1, 3), 2)
        y = [F(rng.randint(-5, 5)) for _ in range(n)]
        iters = rng.randint(1, 6)
        term = list(y)
        total = [F(0)] * n
        for _ in range(iters):
            total = [t + beta * s for t, s in zip(total, term)]
            aterm = [sum(a[i][j] * term[j] for j in range(n)) for i in range(n)]
            term = [s - beta * q for s, q in zip(term, aterm)]
        assert van_cittert(y, h, beta=beta, iters=iters) == total


def test_filter_factors_in_the_fourier_domain():
    rng = random.Random(4)
    for _ in range(6):
        n = rng.choice([8, 12, 16])
        h = [rng.random() for _ in range(n)]
        s = sum(h)
        h = [v / s for v in h]
        y = [rng.gauss(0, 1) for _ in range(n)]
        beta = rng.uniform(0.2, 1.5)
        iters = rng.randint(1, 8)
        xk = dft(van_cittert(y, h, beta=beta, iters=iters))
        yk, hk = dft(y), otf(h)
        f = filter_factors(h, beta, iters)
        for k in range(n):
            expect = f[k] / hk[k] * yk[k]
            assert abs(xk[k] - expect) <= 1e-9 * (1 + abs(expect))


def test_check_values_of_the_filter_factor():
    # 1 - 0.99^100 is the Landweber check value of the area.
    h = [F(1)] + [F(0)] * 3
    f = filter_factors([1.0, 0.0, 0.0, 0.0], 0.01, 100)
    assert abs(f[0] - 0.63397) < 1e-5
    assert van_cittert([F(1), F(0), F(0), F(0)], h, beta=F(1, 2), iters=3) == [F(7, 8), 0, 0, 0]


def test_positive_otf_converges_and_the_error_never_grows():
    n = 32
    h = psf_1d(n, {0: F(2, 3), 1: F(1, 6), -1: F(1, 6)})
    hf = [float(v) for v in h]
    assert converges(hf, 1.0)
    rng = random.Random(5)
    xt = [rng.choice([0.0, 0.0, 1.0, 3.0]) for _ in range(n)]
    y = blur(xt, hf)
    errs = []
    van_cittert(y, hf, beta=1.0, iters=70, callback=lambda k, x: errs.append(norm(sub(x, xt))))
    for a, b in zip(errs, errs[1:]):
        assert b <= a * (1 + 1e-12)
    assert errs[-1] < 1e-9 * norm(xt)


def test_negative_otf_diverges():
    # Box of width 5 on 16 points: H_4 = -1/5, so |1 - beta H_4| > 1 for every beta > 0.
    n = 16
    h = psf_1d(n, {d: 0.2 for d in range(-2, 3)})
    assert abs(otf(h)[4] - (-0.2)) < 1e-12
    assert not converges(h, 1.0)
    xt = [math.cos(2 * math.pi * 4 * j / n) for j in range(n)]
    y = blur(xt, h)
    e10 = norm(sub(van_cittert(y, h, iters=10), xt))
    e20 = norm(sub(van_cittert(y, h, iters=20), xt))
    assert abs(e20 / e10 - 1.2 ** 10) < 1e-6 * 1.2 ** 10
    # The Landweber form uses |H|^2 > 0 and its error never grows.
    errs = [norm(sub(van_cittert_landweber(y, h, beta=1.0, iters=k), xt)) for k in (0, 5, 10, 40)]
    for a, b in zip(errs, errs[1:]):
        assert b <= a * (1 + 1e-12)
    assert errs[-1] < 0.5 * errs[0]


def test_noise_gives_semi_convergence():
    n = 32
    h = psf_1d(n, {0: 0.36, 1: 0.24, -1: 0.24, 2: 0.08, -2: 0.08})
    assert converges(h, 1.0)
    rng = random.Random(6)
    xt = [0.0] * n
    for j in range(10, 16):
        xt[j] = 1.0
    y = [a + b for a, b in zip(blur(xt, h), gauss_noise(rng, n, 0.02))]
    errs = []
    van_cittert(y, h, beta=1.0, iters=3000, callback=lambda k, x: errs.append(norm(sub(x, xt))))
    best = min(errs)
    assert errs.index(best) < len(errs) - 1
    assert errs[-1] > 2 * best


def test_image_deblurring_with_a_separable_psf():
    n = 16
    w = {0: 2 / 3, 1: 1 / 6, n - 1: 1 / 6}
    h = [[w.get(i, 0.0) * w.get(j, 0.0) for j in range(n)] for i in range(n)]
    xt = disk_phantom(n, 0.6)
    y = blur(xt, h)
    assert converges(h, 1.0)
    x = van_cittert(y, h, beta=1.0, iters=120)
    err = img_norm([[a - b for a, b in zip(ra, rb)] for ra, rb in zip(x, xt)])
    assert err < 1e-4 * img_norm(xt)

History

P. H. van Cittert (1931) studied how the width of the entrance slit of a spectrometer changes the measured intensity profile of a spectral line, and corrected the profile by repeated addition of the residual. The method was later used for spectra and images, and Jansson, Hunt and Plyler (1970) made it practical for infrared spectra by bounding the estimate. The link with the Landweber iteration (1951) and with spectral filtering came with the theory of ill-posed problems, and Starck, Pantin and Murtagh (2002) review it next to the other iterative methods of astronomical deconvolution.

References

  1. P. H. van Cittert, Zum Einfluss der Spaltbreite auf die Intensitatsverteilung in Spektrallinien. II, Zeitschrift fur Physik 69(5-6), 1931, pages 298 to 308
  2. Peter A. Jansson, Robert H. Hunt and Earle K. Plyler, Resolution enhancement of spectra, Journal of the Optical Society of America 60(5), 1970, the article from page 596 (the Van Cittert step with a relaxation factor that keeps the estimate within physical bounds)
  3. Per Christian Hansen, James G. Nagy and Dianne P. O'Leary, Deblurring Images, Matrices, Spectra, and Filtering, SIAM, 2006, the chapters on structured blurring matrices and on spectral filtering (periodic blur diagonalized by the DFT, filter factors)
  4. J. L. Starck, E. Pantin and F. Murtagh, Deconvolution in astronomy, a review, Publications of the Astronomical Society of the Pacific 114(800), 2002, pages 1051 to 1069 (the Van Cittert, Landweber and Richardson-Lucy iterations side by side)

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