Algorithm Search⌘K

Algorithmadvanced

Approximate inverse

Also called mollifier method.

Compute mollified values of the solution as inner products of the data with reconstruction kernels that are precomputed from the adjoint equation.

Time
O(m^2 n + r m n + m^3 + r m^2 + s r m) totalO(r m) per_data_setO(m^2 n + r m n + m^3 + r m^2) precompute
Space
O(m^2 + r m) extra
Where
m = the number of data values; n = the number of unknowns; r = the number of reconstruction points; s = the number of data sets
Properties
deterministicnot iterativekernels precomputedlinear in data
Origin
A. K. Louis, P. Maass, 1990

The approximate inverse computes smoothed values of the solution of Ax=yA x = y directly from the data. Pick a mollifier epe_p: a smooth bump with integral 1 and width γ\gamma, centered at the point pp. The mollified solution xγ(p)=⟨x,ep⟩x_\gamma(p) = \langle x, e_p\rangle is a local average of xx near pp, and it tends to x(p)x(p) as γ→0\gamma \to 0. If the reconstruction kernel ψp\psi_p solves the adjoint equation A∗ψp=epA^* \psi_p = e_p, then

⟨y,ψp⟩=⟨Ax,ψp⟩=⟨x,A∗ψp⟩=⟨x,ep⟩=xγ(p).\langle y, \psi_p\rangle = \langle A x, \psi_p\rangle = \langle x, A^* \psi_p\rangle = \langle x, e_p\rangle = x_\gamma(p).

So one inner product of the data with ψp\psi_p gives the mollified value at pp. The kernels depend only on AA and on the mollifiers, so they are computed once, stored, and used for every data set. The width γ\gamma is the regularization parameter. A wider mollifier gives a kernel with a smaller norm, so less noise amplification, but a larger smoothing error. For filtered back-projection, the convolution filter is an approximate inverse kernel of the Radon transform.

In plain words

You cannot recover the exact value of the solution at a point from noisy data of an ill-posed problem. But you can recover a local average of the solution near that point. Decide first which average you want: its center and its width. Then solve one equation, which does not involve the data, for a weight vector that turns the data into exactly that average. After that, each reconstruction is only a weighted sum of the data. A narrow average shows more detail but lets more noise through. A wide average is stable but blurred.

The problem

Given a bounded linear operator A:X→YA: X \to Y between Hilbert spaces (a real m×nm \times n matrix in the code), one or more data sets yδy^\delta with ∥yδ−Ax∥≤δ\|y^\delta - A x\| \le \delta, and mollifiers e1,…,er∈Xe_1, \dots, e_r \in X (in the code, rows of weights with h∑iei=1h \sum_i e_i = 1 on a grid of step hh), compute approximations of the mollified values ⟨x,ei⟩\langle x, e_i\rangle, i=1,…,ri = 1, \dots, r.

The algorithm

  1. APPROXIMATE-INVERSE(A, e₁…eᵣ, data sets Y, β) ▷ β ≥ 0
  2. 1compute the kernels once, independent of the data:
  3. 2bᵢ ← A eᵢ for i = 1, …, r
  4. 3solve (A Aᵀ + β I) ψᵢ = bᵢ for i = 1, …, r
  5. 4Ψ ← (ψ₁, …, ψᵣ)
  6. 5for each data set y in Y do
  7. 6x̂ᵢ ← ⟨y, ψᵢ⟩ for i = 1, …, r

Line L1 starts the precomputation; it uses only AA, the mollifiers and β\beta. In the discrete setting the adjoint equation A⊤ψ=eA^\top \psi = e can have no exact solution, so lines L2 and L3 compute the minimizer of ∥A⊤ψ−e∥2+β∥ψ∥2\|A^\top \psi - e\|^2 + \beta\|\psi\|^2, which is ψ=(AA⊤+βI)−1Ae\psi = (A A^\top + \beta I)^{-1} A e. With β=0\beta = 0 and AA square and nonsingular this is ψ=A−⊤e\psi = A^{-\top} e, the exact solution of the adjoint equation. Line L3 factors one m×mm \times m matrix and solves for all rr right-hand sides together. Line L4 stores the kernels. Lines L5 and L6 are the whole reconstruction: rr inner products per data set.

When AA commutes with a group of shifts or rotations (convolution, the Radon transform), a shifted mollifier has the shifted kernel, so only one kernel has to be computed (Louis 1996). The code tests this for a circulant blur.

Example

A small discrete case. Let AA be the 10×1010 \times 10 matrix of cumulative sums (Ax)i=h∑j≤ixj(A x)_i = h\sum_{j \le i} x_j with h=0.1h = 0.1, the discrete form of (Ax)(s)=∫0sx(t) dt(A x)(s) = \int_0^s x(t)\,dt. Take the mollifier weights e=(0,0,0,18,38,38,18,0,0,0)e = (0, 0, 0, \tfrac18, \tfrac38, \tfrac38, \tfrac18, 0, 0, 0), a hat of half width 0.20.2 centered at p=0.5p = 0.5, with sum 1. The adjoint equation A⊤ψ=eA^\top \psi = e reads h∑i≥jψi=ejh \sum_{i \ge j} \psi_i = e_j, so ψj=(ej−ej+1)/h\psi_j = (e_j - e_{j+1})/h:

ψ=(0,0,−1.25,−2.5,0,2.5,1.25,0,0,0).\psi = (0, 0, -1.25, -2.5, 0, 2.5, 1.25, 0, 0, 0).

The kernel is a scaled difference of the mollifier, so ⟨y,ψ⟩\langle y, \psi\rangle is a smoothed second difference of the data: numerical differentiation, which is what inverting integration means. For xj=sin⁡(πtj)x_j = \sin(\pi t_j) at the cell centers tj=(j−0.5)ht_j = (j - 0.5)h, the estimate is ⟨Ax,ψ⟩=0.96352\langle A x, \psi\rangle = 0.96352. This is exactly the average 18x4+38x5+38x6+18x7=14(0.89101)+34(0.98769)\tfrac18 x_4 + \tfrac38 x_5 + \tfrac38 x_6 + \tfrac18 x_7 = \tfrac14(0.89101) + \tfrac34(0.98769), not the point value x(0.5)=1x(0.5) = 1.

The width as the regularization parameter. In the continuous case, with the hat ep(t)=γ−1max⁡(0,1−∣t−p∣/γ)e_p(t) = \gamma^{-1}\max(0, 1 - |t - p|/\gamma), the kernel is ψp=−ep′\psi_p = -e_p', which is 1/γ21/\gamma^2 on (p,p+γ)(p, p + \gamma) and −1/γ2-1/\gamma^2 on (p−γ,p)(p - \gamma, p). So

xγ(p)=1γ2(∫pp+γy−∫p−γpy),∥ψp∥=2 γ−3/2.x_\gamma(p) = \frac{1}{\gamma^2}\Big(\int_p^{p+\gamma} y - \int_{p-\gamma}^{p} y\Big), \qquad \|\psi_p\| = \sqrt2\,\gamma^{-3/2}.

Two errors compete. The smoothing error for x(t)=sin⁡(πt)x(t) = \sin(\pi t) at p=1/2p = 1/2 is about ∣x′′(p)∣γ2/12=π2γ2/12|x''(p)|\gamma^2/12 = \pi^2\gamma^2/12. The noise error is at most δ∥ψp∥=2 δγ−3/2\delta\|\psi_p\| = \sqrt 2\,\delta\gamma^{-3/2}. The code computes the integrals on a grid with N=4000N = 4000; the smoothing error is measured, and the noise bound is the worst case. For δ=10−3\delta = 10^{-3}:

γ\gamma smoothing error noise bound 2 δγ−3/2\sqrt2\,\delta\gamma^{-3/2} sum
0.05 0.00205 0.1265 0.1285
0.1 0.00820 0.0447 0.0529
0.139 0.0158 0.0273 0.0431
0.2 0.0325 0.0158 0.0483
0.3 0.0719 0.0086 0.0805

Balancing γ2\gamma^2 against δγ−3/2\delta\gamma^{-3/2} gives γ∼δ2/7\gamma \sim \delta^{2/7} and a total error of order δ4/7\delta^{4/7}. With γ=δ2/7\gamma = \delta^{2/7} the sums are 0.1600.160, 0.04310.0431, 0.01160.0116 and 0.00310.0031 for δ=10−2,10−3,10−4,10−5\delta = 10^{-2}, 10^{-3}, 10^{-4}, 10^{-5}. Each step divides the error by about 3.723.72, and 104/7=3.7310^{4/7} = 3.73. A random noise vector of norm δ\delta does much less harm than the worst case: for δ=10−3\delta = 10^{-3} and γ=0.139\gamma = 0.139, the Gaussian noise of the test (seed 64) changed the estimate by only 6.4⋅10−56.4 \cdot 10^{-5}.

Correctness

The proofs are in proofs/correctness.md, in exact arithmetic.

  • Exact recovery of mollified values (theorem). If A⊤ψ=eA^\top \psi = e, then ⟨Ax,ψ⟩=⟨x,e⟩\langle A x, \psi\rangle = \langle x, e\rangle for every xx. With β=0\beta = 0 and AA square and nonsingular, lines L2 and L3 give such a ψ\psi, so line L6 returns the mollified values of xx from exact data.
  • The kernel minimizes the adjoint residual (theorem). For β>0\beta > 0, line L3 gives the unique minimizer of ∥A⊤ψ−e∥2+β∥ψ∥2\|A^\top \psi - e\|^2 + \beta\|\psi\|^2. For β=0\beta = 0 and AA⊤A A^\top invertible, it gives the unique minimizer of ∥A⊤ψ−e∥\|A^\top \psi - e\|.
  • Noise bound (theorem). ∣⟨yδ,ψ⟩−⟨y,ψ⟩∣≤δ∥ψ∥|\langle y^\delta, \psi\rangle - \langle y, \psi\rangle| \le \delta\|\psi\|, with equality for the worst noise.
  • Invariance (theorem). If SS is orthogonal and commutes with AA, then the kernel of SeS e is SψS\psi.
  • Termination. The algorithm has no loop with a data-dependent length.

The convergence of xγ(p)x_\gamma(p) to x(p)x(p) as δ→0\delta \to 0 with a suitable γ(δ)\gamma(\delta) follows from these bounds and the smoothing error of the mollifier, as in the example. General convergence results under conditions on AA and the mollifier are in Louis and Maass (1990) and Schuster (2007).

Proof: Correctness of the approximate inversefull

Exact arithmetic. AA is a real m×nm \times n matrix, ⟨⋅,⋅⟩\langle \cdot, \cdot\rangle is the Euclidean inner product, e1,…,er∈Rne_1, \dots, e_r \in \mathbb{R}^n are the mollifiers, and β≥0\beta \ge 0. Lines L2 and L3 define the kernels by

(AA⊤+βI) ψi=Aei,i=1,…,r,(1)(A A^\top + \beta I)\,\psi_i = A e_i, \qquad i = 1, \dots, r, \tag{1}

whenever AA⊤+βIA A^\top + \beta I is invertible, and line L6 returns x^i=⟨y,ψi⟩\hat x_i = \langle y, \psi_i\rangle.

Lemma 1 (the system of line L3). If β>0\beta > 0, or if β=0\beta = 0 and AA has rank mm, then AA⊤+βIA A^\top + \beta I is symmetric positive definite, so (1) has exactly one solution.

Proof. For z≠0z \ne 0, z⊤(AA⊤+βI)z=∥A⊤z∥2+β∥z∥2z^\top (A A^\top + \beta I) z = \|A^\top z\|^2 + \beta\|z\|^2. If β>0\beta > 0 this is at least β∥z∥2>0\beta \|z\|^2 > 0. If β=0\beta = 0 and AA has rank mm, then A⊤A^\top is injective, so ∥A⊤z∥>0\|A^\top z\| > 0. A symmetric positive definite matrix is invertible. □\square

Theorem 1 (the kernel minimizes the adjoint residual). Under the hypothesis of Lemma 1, ψi\psi_i is the unique minimizer of

G(ψ)=∥A⊤ψ−ei∥2+β∥ψ∥2.G(\psi) = \|A^\top \psi - e_i\|^2 + \beta\|\psi\|^2 .

Proof. For every gg,

G(ψi+g)=G(ψi)+2⟨(AA⊤+βI)ψi−Aei, g⟩+∥A⊤g∥2+β∥g∥2.G(\psi_i + g) = G(\psi_i) + 2\big\langle (A A^\top + \beta I)\psi_i - A e_i,\ g\big\rangle + \|A^\top g\|^2 + \beta\|g\|^2 .

By (1) the middle term is zero, and by Lemma 1 the last two terms sum to g⊤(AA⊤+βI)g>0g^\top (A A^\top + \beta I) g > 0 for g≠0g \ne 0. So G(ψi+g)>G(ψi)G(\psi_i + g) > G(\psi_i) for every g≠0g \ne 0. □\square

Theorem 2 (exact recovery of mollified values). (a) If A⊤ψ=eA^\top \psi = e, then ⟨Ax,ψ⟩=⟨x,e⟩\langle A x, \psi\rangle = \langle x, e\rangle for every x∈Rnx \in \mathbb{R}^n.

(b) If eie_i is in the range of A⊤A^\top and the hypothesis of Lemma 1 holds with β=0\beta = 0, then A⊤ψi=eiA^\top \psi_i = e_i. In particular this holds when AA is square and nonsingular, and then ψi=A−⊤ei\psi_i = A^{-\top} e_i.

(c) In the case of (b), for exact data y=Axy = A x, line L6 returns x^i=⟨x,ei⟩\hat x_i = \langle x, e_i\rangle, the mollified value.

Proof. (a) ⟨Ax,ψ⟩=(Ax)⊤ψ=x⊤A⊤ψ=⟨x,e⟩\langle A x, \psi\rangle = (A x)^\top \psi = x^\top A^\top \psi = \langle x, e\rangle.

(b) If ei=A⊤ze_i = A^\top z for some zz, then G(z)=0G(z) = 0 with β=0\beta = 0, so the minimum of GG is 00. By Theorem 1 the unique minimizer is ψi\psi_i, so G(ψi)=0G(\psi_i) = 0, which means A⊤ψi=eiA^\top \psi_i = e_i. If AA is square and nonsingular, the range of A⊤A^\top is Rn\mathbb{R}^n and AA has rank m=nm = n; then A⊤ψi=eiA^\top \psi_i = e_i gives ψi=A−⊤ei\psi_i = A^{-\top} e_i.

(c) Apply (a) with ψ=ψi\psi = \psi_i and e=eie = e_i. □\square

Theorem 3 (error with inexact kernels and noisy data). Let y=Axy = A x and ∥yδ−y∥≤δ\|y^\delta - y\| \le \delta. Then

∣⟨yδ,ψi⟩−⟨x,ei⟩∣≤δ ∥ψi∥+∥x∥ ∥A⊤ψi−ei∥,\big|\langle y^\delta, \psi_i\rangle - \langle x, e_i\rangle\big| \le \delta\,\|\psi_i\| + \|x\|\,\|A^\top \psi_i - e_i\|,

and the bound δ∥ψi∥\delta\|\psi_i\| on the noise part is attained by the noise yδ−y=δ ψi/∥ψi∥y^\delta - y = \delta\,\psi_i/\|\psi_i\| if ψi≠0\psi_i \ne 0.

Proof. Write ⟨yδ,ψi⟩−⟨x,ei⟩=⟨yδ−y,ψi⟩+⟨x,A⊤ψi−ei⟩\langle y^\delta, \psi_i\rangle - \langle x, e_i\rangle = \langle y^\delta - y, \psi_i\rangle + \langle x, A^\top \psi_i - e_i\rangle, using ⟨Ax,ψi⟩=⟨x,A⊤ψi⟩\langle A x, \psi_i\rangle = \langle x, A^\top \psi_i\rangle. Apply the Cauchy-Schwarz inequality to each term. For the given noise vector, ⟨yδ−y,ψi⟩=δ∥ψi∥\langle y^\delta - y, \psi_i\rangle = \delta\|\psi_i\|. □\square

Theorem 4 (invariance). Let SS be an orthogonal n×nn \times n matrix, let AA be n×nn \times n with AS=SAA S = S A, and let the hypothesis of Lemma 1 hold. If ψ\psi is the kernel of the mollifier ee, then SψS\psi is the kernel of the mollifier SeS e.

Proof. From AS=SAA S = S A and S−1=S⊤S^{-1} = S^\top we get S⊤A=AS⊤S^\top A = A S^\top, and by transposition A⊤S=SA⊤A^\top S = S A^\top. So SS commutes with AA⊤+βIA A^\top + \beta I, and

(AA⊤+βI) Sψ=S (AA⊤+βI) ψ=SAe=ASe.(A A^\top + \beta I)\, S\psi = S\,(A A^\top + \beta I)\,\psi = S A e = A S e .

So SψS\psi solves (1) for the mollifier SeS e, and by Lemma 1 it is the only solution. □\square

For a circulant matrix AA and the cyclic shift SS, Theorem 4 says that the kernels of all shifted mollifiers are shifts of one kernel, which is what the shift invariance test checks.

Theorem 5 (termination). Under the hypothesis of Lemma 1, the algorithm performs rr matrix-vector products at line L2, one factorization with rr solves at line L3, and rr inner products per data set at line L6, and then stops. Each step is well defined by Lemma 1.

Proof. Lines L2, L3 and L6 are loops of fixed length rr, line L5 runs once for each of the finitely many data sets, and there are no other loops. □\square

Complexity

  • Precomputation. Forming AA⊤A A^\top costs O(m2n)O(m^2 n), the right-hand sides AeiA e_i cost O(rmn)O(r m n), and the solve costs O(m3+rm2)O(m^3 + r m^2).
  • Per data set. rr inner products of length mm, so O(rm)O(r m). This is the point of the method: in imaging with many data sets of the same geometry, each reconstruction is as cheap as one matrix-vector product.
  • With invariance. If the kernels are shifts of one kernel, line L6 is a convolution, which the FFT computes in O(mlog⁡m)O(m \log m) (see the convolution theorem), and only one kernel is stored.
  • Space. O(m2+rm)O(m^2 + r m), or O(m)O(m) with invariance and a matrix-free solver.

Properties

  • Linear in the data. The reconstruction is x^=Ψ⊤y\hat x = \Psi^\top y for a fixed matrix Ψ\Psi.
  • Known resolution. Exact data give exactly the chosen averages, so the averaging kernels (the rows of the resolution matrix) are the mollifiers themselves, chosen in advance. Compare the Backus-Gilbert method, which computes the best averaging kernel instead.
  • Data independent cost. All the expensive work is done before any data are measured.
  • Regularization by the width. γ\gamma plays the role of α\alpha in Tikhonov regularization. With β>0\beta > 0 there is a second parameter, needed when the adjoint equation is not solvable.

Variants and improvements

  • Invariant kernels. For the Radon transform with rotation and translation invariant mollifiers, one kernel gives filtered back-projection with a filter determined by the mollifier (Louis 1996).
  • Lambda tomography. Choosing a mollifier that also applies a differential operator gives local reconstructions of edges (see lambda tomography).
  • Kernels by singular value expansion. If the singular system of AA is known, ψ=∑jσj−1⟨e,vj⟩uj\psi = \sum_j \sigma_j^{-1} \langle e, v_j\rangle u_j, truncated or filtered.
  • Nonlinear problems and Banach spaces. Louis (1996) and Schuster (2007) describe extensions, including the use of approximate inverse kernels inside iterations.

When to use it

Use the approximate inverse when the same operator is applied to many data sets, so that a costly precomputation pays off, as in tomography with a fixed scanner geometry. It is also a good choice when you want to say in advance which local averages you reconstruct, for example to report a known resolution. If AA changes from one problem to the next, or you need only one reconstruction, a Tikhonov or truncated SVD solution is simpler. If you want the averaging kernel with the best trade-off between width and noise at each point, use the Backus-Gilbert method.

Pitfalls

  • No exact solution of the adjoint equation. If ee is not in the range of A⊤A^\top, then ⟨y,ψ⟩\langle y, \psi\rangle is not exactly the mollified value; the error is ⟨x,A⊤ψ−e⟩\langle x, A^\top \psi - e\rangle. Check the residual ∥A⊤ψ−e∥\|A^\top \psi - e\| after line L3.
  • β=0\beta = 0 with a rank deficient AA. Then AA⊤A A^\top is singular and line L3 fails. Use a small β>0\beta > 0.
  • A mollifier too narrow. ∥ψ∥\|\psi\| grows fast as γ→0\gamma \to 0 (like γ−3/2\gamma^{-3/2} for integration), so noise dominates. Pick γ\gamma from the noise level, not from the grid size.
  • Mollifier near the boundary. In the example the closed form needs γ≤p\gamma \le p and p+γ≤1p + \gamma \le 1. Near the edge of the domain the mollifier must be cut and renormalized, and the kernel changes.
  • Discrete and continuous inner products. The code uses plain sums. If the mollifier is normalized so that h∑iei=1h \sum_i e_i = 1, then ⟨x,e⟩\langle x, e\rangle is 1/h1/h times the average, as in the tests.

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.

approximate_inverse.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-inverse/. The authors are listed in prov/7S6RR0.jsonl.
"""The approximate inverse of Louis and Maass for A x = y.

Pick a mollifier e_p (a smooth bump of width gamma centered at the point p,
with integral 1). Solve the adjoint equation A^T psi_p = e_p once for the
reconstruction kernel psi_p. Then for any data y,

    x_gamma(p) = <y, psi_p> = <A x, psi_p> = <x, A^T psi_p> = <x, e_p>,

which is the mollified solution at p. The kernels depend on A and on the
mollifier only, so they are computed once and used for every data set.

In the discrete form the adjoint equation may have no exact solution, so
psi_p minimizes ||A^T psi - e_p||^2 + beta ||psi||^2, which gives
psi_p = (A A^T + beta I)^(-1) A e_p. With beta = 0 and A square and
nonsingular this is psi_p = A^(-T) e_p.
"""

from imgla import matvec, solve


def hat_mollifier(grid, p, gamma, h):
    """Discrete hat e(t) = (1 / gamma) max(0, 1 - |t - p| / gamma), scaled so h sum e = 1."""
    e = [max(0.0, 1.0 - abs(t - p) / gamma) for t in grid]
    s = h * sum(e)
    return [v / s for v in e]


def kernels(a, mollifiers, beta=0.0):
    """The reconstruction kernels psi_p, one per mollifier row e_p."""
    m = len(a)
    aat = [[sum(p * q for p, q in zip(a[i], a[j])) + (beta if i == j else 0.0)
            for j in range(m)] for i in range(m)]
    rhs = [matvec(a, e) for e in mollifiers]  # @line L2
    cols = solve(aat, [list(r) for r in zip(*rhs)])  # @line L3
    return [list(c) for c in zip(*cols)]  # @line L4


def apply_kernels(psis, y):
    """x_gamma(p) = <y, psi_p> for each kernel."""
    return [sum(p * q for p, q in zip(psi, y)) for psi in psis]  # @line L6


def approximate_inverse(a, mollifiers, ys, beta=0.0):
    """Reconstruct every data set in ys with the same kernels."""
    psis = kernels(a, mollifiers, beta)  # @line L1
    return [apply_kernels(psis, y) for y in ys]  # @line L5


def _integral(ys, h, a, b):
    """int_a^b of the piecewise linear interpolant of the samples ys[j] = y(j h)."""
    def value(t):
        j = min(int(t / h), len(ys) - 2)
        w = t / h - j
        return (1.0 - w) * ys[j] + w * ys[j + 1]

    knots = [a] + [j * h for j in range(int(a / h) + 1, int(b / h) + 1) if a < j * h < b] + [b]
    return sum(0.5 * (t1 - t0) * (value(t0) + value(t1)) for t0, t1 in zip(knots, knots[1:]))


def integration_estimate(ys, h, p, gamma):
    """Closed-form approximate inverse for (A x)(s) = int_0^s x with the hat mollifier.

    The kernel is psi = -e_p', so x_gamma(p) = (1 / gamma^2) [int_p^{p+gamma} y -
    int_{p-gamma}^p y]. ys holds samples of y at s_j = j h, j = 0, ..., N, and the
    integrals use their piecewise linear interpolant. It needs gamma <= p and
    p + gamma <= 1.
    """
    return (_integral(ys, h, p, p + gamma) - _integral(ys, h, p - gamma, p)) / (gamma * gamma)


def integration_kernel_norm(gamma):
    """||psi||_{L^2} = sqrt(2) gamma^(-3/2) for the hat mollifier."""
    return (2.0 / gamma ** 3) ** 0.5
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
test_approximate_inverse.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/approximate-inverse/. The authors are listed in prov/7S6RR0.jsonl.
import math
import random
import unittest

from approximate_inverse import (apply_kernels, approximate_inverse, hat_mollifier,
                                 integration_estimate, integration_kernel_norm, kernels)
from imgla import adjoint_gap, matvec, norm2, rmatvec, solve, transpose


def cumsum_matrix(n):
    h = 1.0 / n
    return [[h if j <= i else 0.0 for j in range(n)] for i in range(n)]


def pl_norm(e, h):
    """Exact L^2 norm of the piecewise linear function with nodal values e."""
    return math.sqrt(sum(h / 3.0 * (a * a + a * b + b * b) for a, b in zip(e, e[1:])))


class TestApproximateInverse(unittest.TestCase):
    def test_exact_data_gives_mollified_solution(self):
        n = 40
        h = 1.0 / n
        a = cumsum_matrix(n)
        grid = [(i + 0.5) * h for i in range(n)]
        moll = [hat_mollifier(grid, p, 0.1, h) for p in (0.2, 0.35, 0.5, 0.8)]
        rng = random.Random(61)
        x = [rng.gauss(0.0, 1.0) for _ in range(n)]
        est = approximate_inverse(a, moll, [matvec(a, x)])[0]
        for e, v in zip(moll, est):
            self.assertAlmostEqual(v, sum(p * q for p, q in zip(e, x)), places=9)

    def test_kernel_formulas_agree(self):
        rng = random.Random(62)
        a = [[rng.uniform(-1.0, 1.0) for _ in range(6)] for _ in range(4)]
        es = [[rng.uniform(0.0, 1.0) for _ in range(6)] for _ in range(3)]
        beta = 0.05
        psis = kernels(a, es, beta)
        ata = [[sum(a[r][i] * a[r][j] for r in range(4)) + (beta if i == j else 0.0)
                for j in range(6)] for i in range(6)]
        for e, psi in zip(es, psis):
            ref = matvec(a, solve(ata, e))
            for p, q in zip(psi, ref):
                self.assertAlmostEqual(p, q, places=10)
            # psi minimizes ||A^T psi - e||^2 + beta ||psi||^2: the gradient is zero.
            g = matvec(a, [p - q for p, q in zip(rmatvec(a, psi), e)])
            g = [gi + beta * pi for gi, pi in zip(g, psi)]
            self.assertLess(norm2(g), 1e-10)

    def test_kernels_are_reused(self):
        n = 30
        h = 1.0 / n
        a = cumsum_matrix(n)
        grid = [(i + 0.5) * h for i in range(n)]
        moll = [hat_mollifier(grid, p, 0.15, h) for p in (0.3, 0.6)]
        rng = random.Random(63)
        ys = [[rng.gauss(0.0, 1.0) for _ in range(n)] for _ in range(3)]
        psis = kernels(a, moll, 1e-6)
        both = approximate_inverse(a, moll, ys, 1e-6)
        for y, est in zip(ys, both):
            self.assertEqual(est, apply_kernels(psis, y))

    def test_shift_invariance(self):
        # A circulant blur commutes with shifts, so the kernel for a shifted
        # mollifier is the shifted kernel.
        n = 24
        w = [0.5, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
             0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25]
        a = [[w[(i - j) % n] + (0.2 if i == j else 0.0) for j in range(n)] for i in range(n)]
        base = [max(0.0, 1.0 - abs(min(i, n - i)) / 3.0) for i in range(n)]
        moll = [[base[(i - s) % n] for i in range(n)] for s in range(n)]
        psis = kernels(a, moll)
        for s in range(n):
            for i in range(n):
                self.assertAlmostEqual(psis[s][i], psis[0][(i - s) % n], places=10)

    def test_integration_closed_form(self):
        n = 1000
        h = 1.0 / n
        ys = [(j * h) ** 2 / 2.0 for j in range(n + 1)]
        self.assertAlmostEqual(integration_estimate(ys, h, 0.3, 0.1), 0.3, places=12)
        self.assertAlmostEqual(integration_kernel_norm(0.1), math.sqrt(2.0) * 0.1 ** -1.5, places=9)

    def test_noise_bound_and_rate(self):
        n = 4000
        h = 1.0 / n
        ys = [(1.0 - math.cos(math.pi * j * h)) / math.pi for j in range(n + 1)]
        rng = random.Random(64)
        noise = [rng.gauss(0.0, 1.0) for _ in range(n + 1)]
        p, errs, deltas = 0.5, [], [1e-3, 1e-5]
        for delta in deltas:
            gamma = delta ** (2.0 / 7.0)
            scale = delta / pl_norm(noise, h)
            e = [scale * v for v in noise]
            clean = integration_estimate(ys, h, p, gamma)
            dirty = integration_estimate([u + v for u, v in zip(ys, e)], h, p, gamma)
            bound = delta * integration_kernel_norm(gamma)
            self.assertLessEqual(abs(dirty - clean), bound * (1.0 + 1e-9))
            # Worst case: the mollifier error and the full noise bound add up.
            errs.append(abs(clean - 1.0) + bound)
        slope = math.log(errs[0] / errs[1]) / math.log(deltas[0] / deltas[1])
        self.assertLess(abs(slope - 4.0 / 7.0), 0.15)

    def test_adjoint_of_integration(self):
        n = 50
        a = cumsum_matrix(n)
        at = transpose(a)
        rng = random.Random(65)
        x = [rng.gauss(0.0, 1.0) for _ in range(n)]
        z = [rng.gauss(0.0, 1.0) for _ in range(n)]
        self.assertLess(adjoint_gap(lambda v: matvec(a, v), lambda v: matvec(at, v), x, z), 1e-12)


if __name__ == "__main__":
    unittest.main()

History

A. K. Louis and P. Maass introduced the mollifier method for linear equations of the first kind in 1990. Louis developed it into the approximate inverse in 1996, with the invariance properties that make it efficient in tomography and with an interpretation of filtered back-projection as an approximate inverse. T. Schuster wrote a book on the theory and its applications (2007). The idea of reconstructing chosen local averages is close to the Backus-Gilbert method from geophysics (1967 to 1970), which instead optimizes the averaging kernel.

References

  1. A. K. Louis and P. Maass, A mollifier method for linear operator equations of the first kind, Inverse Problems 6(3), 1990, 427 to 440, the mollifier method and its convergence (general locator)
  2. A. K. Louis, Approximate inverse for linear and some nonlinear problems, Inverse Problems 12(2), 1996, 175 to 190, the approximate inverse, invariance properties of the kernels, and applications to tomography (general locator)
  3. T. Schuster, The Method of Approximate Inverse: Theory and Applications, Lecture Notes in Mathematics 1906, Springer, Berlin, 2007, the theory of the method and its use in tomography (general locator)

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.per_data_set
  • a full proof of time.precompute
  • a full proof of time.total
  • 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