Algorithm Search⌘K

Algorithmadvanced

Backus-Gilbert method

Also called method of optimally localized averages.

Estimate local averages of the unknown with averaging kernels that are as narrow as possible under a bound on the noise amplification.

Time
O(r (m^2 q + m^3)) totalO(m^2 q + m^3) per_point
Space
O(m^2) extra
Where
m = the number of data values; q = the number of quadrature nodes; r = the number of estimation points
Properties
deterministicnot iterativelinear in dataweights depend on point
Origin
G. Backus, F. Gilbert, 1967

The Backus-Gilbert method estimates local averages of an unknown function x(t)x(t) from finitely many noisy linear data

di=∫Gi(t) x(t) dt+ni,i=1,…,m,d_i = \int G_i(t)\,x(t)\,dt + n_i, \qquad i = 1, \dots, m,

with noise covariance CC. For each point pp it looks for weights a=a(p)a = a(p) and reports x^(p)=∑iaidi\hat x(p) = \sum_i a_i d_i. For exact data this estimate is ∫Kp(t) x(t) dt\int K_p(t)\,x(t)\,dt, an average of xx with the averaging kernel Kp=∑iaiGiK_p = \sum_i a_i G_i. The method chooses aa so that KpK_p has unit area and is as concentrated near pp as the data allow, while the noise variance a⊤Caa^\top C a of the estimate stays small. With the spread s(a)=12∫(t−p)2Kp(t)2 dts(a) = 12\int (t - p)^2 K_p(t)^2\,dt, which is a quadratic form a⊤S(p) aa^\top S(p)\, a, it solves

min⁡a a⊤(S(p)+μC) asubject toc⊤a=1,ci=∫Gi,\min_a \ a^\top \big(S(p) + \mu C\big)\, a \quad \text{subject to} \quad c^\top a = 1, \qquad c_i = \int G_i ,

and a Lagrange multiplier gives a=W−1c/(c⊤W−1c)a = W^{-1} c / (c^\top W^{-1} c) with W=S(p)+μCW = S(p) + \mu C. The parameter μ≥0\mu \ge 0 trades resolution (a small spread) against stability (a small variance). Unlike most regularization methods, it reports with each estimate the averaging kernel that the estimate really is, so the user sees the resolution at every point.

In plain words

With a finite number of noisy measurements you cannot know the unknown function at a point. You can only know weighted averages of it. The Backus-Gilbert method asks, for each point, which combination of the measurements gives an average that is concentrated as closely as possible around that point. A very sharp average needs large weights of both signs, and these amplify the noise. So the method finds the sharpest average whose noise is still acceptable. It returns both the value and the shape of the average, so you know how much detail the value really contains.

The problem

Given data kernels G1,…,GmG_1, \dots, G_m on an interval (in the code, sampled at quadrature nodes tkt_k with weights wkw_k), data d∈Rmd \in \mathbb{R}^m, a symmetric positive semidefinite noise covariance CC, a parameter μ≥0\mu \ge 0, and points p1,…,prp_1, \dots, p_r, compute for each pp the weights a(p)a(p) that minimize a⊤(S(p)+μC) aa^\top (S(p) + \mu C)\, a under ∑iai∫Gi=1\sum_i a_i \int G_i = 1, and the estimate x^(p)=a(p)⊤d\hat x(p) = a(p)^\top d.

The algorithm

  1. BACKUS-GILBERT(G₁…G_m, d, C, points P, μ) ▷ μ ≥ 0, cᵢ = ∫ Gᵢ
  2. 1for each point p in P do
  3. 2S_ij ← 12 ∫ (t - p)² Gᵢ(t) Gⱼ(t) dt for i, j = 1, …, m
  4. 3W ← S + μ C
  5. 4solve W z = c
  6. 5a ← z / (cᵀ z)
  7. 6x̂(p) ← aᵀ d
  8. 7return (x̂(p) for p in P)

Line L1 treats each point on its own; the weights depend on pp through the spread matrix. Line L2 computes the spread matrix by the quadrature rule. The factor 12 is chosen so that a box of width ww centered at pp (height 1/w1/w) has spread exactly ww, so the spread reads as a width. Line L3 adds the weighted noise covariance. Lines L4 and L5 solve the constrained problem in closed form: aa is proportional to W−1cW^{-1} c, scaled to unit area. Line L6 applies the weights to the data, and line L7 returns all estimates. The averaging kernel Kp=∑iaiGiK_p = \sum_i a_i G_i and the variance a⊤Caa^\top C a come with no extra solve and should be reported too.

Example

Ten data kernels. Take m=10m = 10 Gaussian kernels Gi(t)=exp⁡(−12((t−ti)/0.08)2)/(0.082π)G_i(t) = \exp(-\tfrac12((t - t_i)/0.08)^2)/(0.08\sqrt{2\pi}) on [0,1][0, 1] with centers ti=(i−0.5)/10t_i = (i - 0.5)/10, white noise (C=IC = I), and the midpoint rule with 400400 nodes. One kernel alone, used at its own center, has spread 3⋅0.08/π=0.13543 \cdot 0.08/\sqrt\pi = 0.1354. At p=0.5p = 0.5, halfway between two centers, with μ=10−2\mu = 10^{-2}, the method gives the weights

a=(0.030,−0.054,0.153,−0.272,0.648,0.648,−0.272,0.153,−0.054,0.030)a = (0.030, -0.054, 0.153, -0.272, 0.648, 0.648, -0.272, 0.153, -0.054, 0.030)

and spread 0.13000.1300. The weights alternate in sign: the negative sidelobes of the neighbors make the kernel narrower than one data kernel, at the price of a noise factor a⊤a=1.02\sqrt{a^\top a} = 1.02.

The trade-off. Now take m=20m = 20 such kernels (centers (i−0.5)/20(i - 0.5)/20, the same width), so neighbors overlap strongly and the problem is ill-conditioned. Let x(t)=sin⁡(πt)+0.5tx(t) = \sin(\pi t) + 0.5t, with x(0.5)=1.25x(0.5) = 1.25, add white noise with standard deviation σ=0.001\sigma = 0.001 (random.Random(7)), keep C=IC = I, and estimate at p=0.5p = 0.5. The noise column is the standard deviation σa⊤a\sigma\sqrt{a^\top a} of the estimate.

μ\mu spread noise std of x^\hat x x^\hat x, exact data x^\hat x, noisy data error
10−1210^{-12} 0.0655 0.380 1.2249 0.6995 0.5505
10−810^{-8} 0.0657 0.326 1.2244 0.7705 0.4795
10−610^{-6} 0.0733 0.0472 1.2209 1.1653 0.0847
10−410^{-4} 0.0859 0.0067 1.2153 1.2161 0.0339
10−210^{-2} 0.1108 0.0011 1.2028 1.2038 0.0462
11 0.2055 0.00037 1.1402 1.1404 0.1096

As μ\mu grows the spread grows and the noise falls, at every step. With exact data the estimate is exactly the average ∫Kpx\int K_p x; it differs from x(0.5)=1.25x(0.5) = 1.25 because xx is curved on the scale of the spread. The best total error here is near μ=10−4\mu = 10^{-4}, where the kernel is 0.0860.086 wide and the noise is 0.00670.0067. Twenty kernels resolve 0.0660.066 at best, compared with 0.1290.129 for ten; more data buy resolution, but only with more noise amplification.

Correctness

The proofs are in proofs/correctness.md, in exact arithmetic and with the same quadrature rule for every integral.

  • Optimal weights (theorem). If W=S(p)+μCW = S(p) + \mu C is positive definite and c≠0c \ne 0, lines L4 and L5 give the unique minimizer of a⊤Waa^\top W a under c⊤a=1c^\top a = 1.
  • Unit area and exact averages (theorem). The averaging kernel has ∫Kp=1\int K_p = 1, and for exact data x^(p)=∫Kp x\hat x(p) = \int K_p\, x. So constants are reproduced exactly.
  • Spread identity (lemma). a⊤S(p) a=12∫(t−p)2Kp(t)2 dta^\top S(p)\,a = 12 \int (t - p)^2 K_p(t)^2\,dt.
  • Monotone trade-off (theorem). As μ\mu increases, the spread a⊤Saa^\top S a does not decrease and the variance a⊤Caa^\top C a does not increase.
  • Termination. One linear solve per point; no data-dependent loop.
Proof: Correctness of the Backus-Gilbert methodfull

Exact arithmetic. Every integral is the same quadrature rule ∫f=∑kwkf(tk)\int f = \sum_k w_k f(t_k) with weights wk>0w_k > 0, as in the code; the statements also hold for exact integrals. G1,…,GmG_1, \dots, G_m are the data kernels, ci=∫Gic_i = \int G_i, CC is a symmetric positive semidefinite m×mm \times m matrix, μ≥0\mu \ge 0, and for a point pp

S(p)ij=12∫(t−p)2Gi(t)Gj(t) dt,W=S(p)+μC.S(p)_{ij} = 12 \int (t - p)^2 G_i(t) G_j(t)\,dt, \qquad W = S(p) + \mu C .

For weights a∈Rma \in \mathbb{R}^m the averaging kernel is Kp=∑iaiGiK_p = \sum_i a_i G_i. Lines L4 and L5 compute z=W−1cz = W^{-1} c and a=z/(c⊤z)a = z / (c^\top z).

Lemma 1 (spread identity). For every aa, a⊤S(p) a=12∫(t−p)2Kp(t)2 dt≥0a^\top S(p)\, a = 12 \int (t - p)^2 K_p(t)^2\,dt \ge 0. So S(p)S(p) is symmetric positive semidefinite, and WW is too.

Proof. ∑i,jaiaj∫12(t−p)2GiGj=∫12(t−p)2(∑iaiGi)2\sum_{i,j} a_i a_j \int 12 (t - p)^2 G_i G_j = \int 12 (t - p)^2 \big(\sum_i a_i G_i\big)^2, by linearity of the quadrature. The integrand is nonnegative and the weights are positive. WW is a sum of positive semidefinite matrices with μ≥0\mu \ge 0. □\square

WW is positive definite, for example, if μ>0\mu > 0 and CC is positive definite, or if the vectors ((tk−p)Gi(tk))k\big((t_k - p) G_i(t_k)\big)_k, i=1,…,mi = 1, \dots, m, are linearly independent. We assume this and c≠0c \ne 0 below.

Theorem 1 (optimal weights). If WW is positive definite and c≠0c \ne 0, then c⊤z>0c^\top z > 0, the vector aa of line L5 satisfies c⊤a=1c^\top a = 1, and it is the unique minimizer of a⊤Waa^\top W a over {a:c⊤a=1}\{a : c^\top a = 1\}. The minimum value is 1/(c⊤W−1c)1/(c^\top W^{-1} c).

Proof. W−1W^{-1} is positive definite, so c⊤z=c⊤W−1c>0c^\top z = c^\top W^{-1} c > 0, and c⊤a=c⊤z/c⊤z=1c^\top a = c^\top z / c^\top z = 1. Let b=a+gb = a + g with c⊤g=0c^\top g = 0. Then

b⊤Wb=a⊤Wa+2a⊤Wg+g⊤Wg.b^\top W b = a^\top W a + 2 a^\top W g + g^\top W g .

Since Wa=c/(c⊤z)W a = c / (c^\top z), a⊤Wg=c⊤g/(c⊤z)=0a^\top W g = c^\top g / (c^\top z) = 0. So b⊤Wb=a⊤Wa+g⊤Wg>a⊤Wab^\top W b = a^\top W a + g^\top W g > a^\top W a for g≠0g \ne 0. Finally a⊤Wa=z⊤Wz/(c⊤z)2=c⊤z/(c⊤z)2=1/(c⊤W−1c)a^\top W a = z^\top W z / (c^\top z)^2 = c^\top z/(c^\top z)^2 = 1/(c^\top W^{-1} c). □\square

Theorem 2 (unit area and exact averages). For the weights of Theorem 1, ∫Kp=1\int K_p = 1. If di=∫Gi xd_i = \int G_i\, x for a function xx, then line L6 gives x^(p)=∫Kp x\hat x(p) = \int K_p\, x. In particular, if xx is the constant κ\kappa, then x^(p)=κ\hat x(p) = \kappa.

Proof. ∫Kp=∑iai∫Gi=c⊤a=1\int K_p = \sum_i a_i \int G_i = c^\top a = 1. Next, a⊤d=∑iai∫Gi x=∫(∑iaiGi)x=∫Kp xa^\top d = \sum_i a_i \int G_i\, x = \int \big(\sum_i a_i G_i\big) x = \int K_p\, x. For x=κx = \kappa this is κ∫Kp=κ\kappa \int K_p = \kappa. □\square

Corollary (noise). If d=d0+nd = d^0 + n with di0=∫Gixd^0_i = \int G_i x, E n=0E\,n = 0 and Cov(n)=C\mathrm{Cov}(n) = C, then E x^(p)=∫Kp xE\,\hat x(p) = \int K_p\, x and Var x^(p)=a⊤Ca\mathrm{Var}\,\hat x(p) = a^\top C a.

Proof. x^(p)=a⊤d0+a⊤n\hat x(p) = a^\top d^0 + a^\top n. Apply Theorem 2 to the first term. The second term has mean a⊤En=0a^\top E n = 0 and variance a⊤Caa^\top C a. □\square

Theorem 3 (monotone trade-off). Let 0≤μ1<μ20 \le \mu_1 < \mu_2, let W1=S+μ1CW_1 = S + \mu_1 C and W2=S+μ2CW_2 = S + \mu_2 C be positive definite, and let a1a_1 and a2a_2 be the weights of Theorem 1 for μ1\mu_1 and μ2\mu_2. With sk=ak⊤Saks_k = a_k^\top S a_k and vk=ak⊤Cakv_k = a_k^\top C a_k, we have s1≤s2s_1 \le s_2 and v1≥v2v_1 \ge v_2.

Proof. Both a1a_1 and a2a_2 satisfy the constraint. Since a1a_1 minimizes the objective for μ1\mu_1 and a2a_2 minimizes it for μ2\mu_2,

s1+μ1v1≤s2+μ1v2,s2+μ2v2≤s1+μ2v1.s_1 + \mu_1 v_1 \le s_2 + \mu_1 v_2, \qquad s_2 + \mu_2 v_2 \le s_1 + \mu_2 v_1 .

Adding the two inequalities gives μ1v1+μ2v2≤μ1v2+μ2v1\mu_1 v_1 + \mu_2 v_2 \le \mu_1 v_2 + \mu_2 v_1, that is (μ2−μ1)(v2−v1)≤0(\mu_2 - \mu_1)(v_2 - v_1) \le 0, so v2≤v1v_2 \le v_1. Then the first inequality gives s1−s2≤μ1(v2−v1)≤0s_1 - s_2 \le \mu_1 (v_2 - v_1) \le 0, so s1≤s2s_1 \le s_2. □\square

Theorem 4 (termination). If WW is positive definite and c≠0c \ne 0 for every point pp in PP, the algorithm performs, for each of the finitely many points, one spread matrix, one linear solve and one inner product, and then returns at line L7.

Proof. The only loop is over the finite set PP (line L1). Each pass is well defined: the solve at line L4 succeeds because WW is invertible, and the division at line L5 is by c⊤z>0c^\top z > 0 (Theorem 1). □\square

Complexity

  • Per point. Line L2 costs O(m2q)O(m^2 q) with qq quadrature nodes, and the solve at line L4 costs O(m3)O(m^3). Lines L5 and L6 cost O(m)O(m).
  • Total. O(r(m2q+m3))O(r (m^2 q + m^3)) for rr points, and O(m2)O(m^2) extra space. The products GiGjG_i G_j can be computed once, so that each new pp needs only a weighted sum.
  • Comparison. Tikhonov regularization solves one system for all points; Backus-Gilbert solves one per point. This is why it is used for problems with a modest number of data, as in geophysics and helioseismology, and why faster variants exist.

Properties

  • Linear in the data. For fixed pp and μ\mu, x^(p)=a(p)⊤d\hat x(p) = a(p)^\top d.
  • Self-describing resolution. The output includes the averaging kernel KpK_p and its spread, which are the rows of the resolution matrix in the continuous setting.
  • Unbiased for the average. E x^(p)=∫Kp xE\,\hat x(p) = \int K_p\, x for zero-mean noise, whatever xx is. The bias with respect to x(p)x(p) depends on how much xx varies over the width of KpK_p.
  • No prior on xx. The method uses no smoothness assumption on xx to compute the weights; it only describes what the data can resolve.
  • Trade-off curve. Plotting spread against variance for all μ\mu gives a monotone curve, the standard picture of the conflict between resolution and stability.

Variants and improvements

  • Other spread functions. Use (t−p)2(t - p)^2 in higher dimensions as ∥t−p∥2\|t - p\|^2, or another weight that grows away from pp; the algorithm is unchanged.
  • Subtractive optimally localized averages (SOLA). Fit KpK_p to a chosen target kernel (for example a Gaussian of a given width) in least squares, instead of minimizing the spread. The matrix of the system then does not depend on pp, so it is factored once. Pijpers and Thompson introduced it for helioseismology.
  • Choice of μ\mu. Pick μ\mu so that the noise standard deviation reaches a target, or use the discrepancy principle on the misfit of a model built from the estimates.
  • Fixed averaging kernels. If the averaging kernel is chosen in advance and the weights are computed for it, the method becomes the approximate inverse.

When to use it

Use the Backus-Gilbert method when there are tens to a few hundred data, when the question is what the data can say about the unknown at each point, and when each estimate needs its own resolution and error bar. This is the typical situation in seismology, in helioseismic rotation inversions, and in other problems with sparse, integral data. When you need a full reconstruction on a fine grid from many data, Tikhonov regularization or truncated SVD is much cheaper, and you can compute their averaging kernels afterwards from the resolution matrix.

Pitfalls

  • μ=0\mu = 0 with close data kernels. S(p)S(p) is then nearly singular, the weights are huge with alternating signs, and the noise standard deviation reaches 0.3800.380 in the table, about fifteen times the smoothing error 0.0250.025. Always use μ>0\mu > 0 with noisy data.
  • Reading x^(p)\hat x(p) as a point value. It is an average over a width of about the spread. Report the spread with the estimate.
  • Wrong noise covariance. The trade-off uses CC; a wrong scale of CC only rescales μ\mu, but a wrong correlation structure gives wrong error bars.
  • Points near the edge of the data coverage. The averaging kernel cannot be centered there; it is lopsided and wider. Check KpK_p, not only the spread number.
  • Quadrature too coarse. Line L2 needs a quadrature that resolves the products GiGjG_i G_j; otherwise the spread and the unit area are wrong.

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.

backus_gilbert_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backus-gilbert-method/. The authors are listed in prov/GT011W.jsonl.
"""The Backus-Gilbert method of optimally localized averages.

The data are d_i = int G_i(t) x(t) dt + n_i for i = 1, ..., m, with noise
covariance C. For a point p the method looks for weights a with

    estimate x_hat(p) = sum_i a_i d_i,   averaging kernel K_p(t) = sum_i a_i G_i(t),

so that K_p has unit area (c^T a = 1 with c_i = int G_i) and is concentrated
near p. The spread is s(a) = 12 int (t - p)^2 K_p(t)^2 dt = a^T S(p) a, the
noise variance is a^T C a, and the method minimizes a^T (S(p) + mu C) a
subject to c^T a = 1. A Lagrange multiplier gives

    a = W^(-1) c / (c^T W^(-1) c),   W = S(p) + mu C.

The factor 12 makes a box of width w around p have spread w. The integrals
are computed by a quadrature rule on a fine grid: nodes ts and weights ws.
"""

from imgla import solve


def spread_matrix(kernels, ts, ws, p):
    """S(p)_ij = 12 int (t - p)^2 G_i(t) G_j(t) dt by the quadrature (ts, ws)."""
    m = len(kernels)
    wt = [12.0 * w * (t - p) ** 2 for t, w in zip(ts, ws)]
    return [[sum(f * gi * gj for f, gi, gj in zip(wt, kernels[i], kernels[j]))
             for j in range(m)] for i in range(m)]


def areas(kernels, ws):
    """c_i = int G_i by the quadrature weights."""
    return [sum(w * g for w, g in zip(ws, gk)) for gk in kernels]


def weights(kernels, ts, ws, p, mu, cov):
    """The Backus-Gilbert coefficients a for the point p and trade-off parameter mu."""
    m = len(kernels)
    s = spread_matrix(kernels, ts, ws, p)  # @line L2
    w = [[s[i][j] + mu * cov[i][j] for j in range(m)] for i in range(m)]  # @line L3
    c = areas(kernels, ws)
    z = solve(w, c)  # @line L4
    cz = sum(ci * zi for ci, zi in zip(c, z))
    return [zi / cz for zi in z]  # @line L5


def backus_gilbert(kernels, ts, ws, data, points, mu, cov):
    """Estimates x_hat(p) = a(p)^T d for every point p."""
    out = []
    for p in points:  # @line L1
        a = weights(kernels, ts, ws, p, mu, cov)
        out.append(sum(ai * di for ai, di in zip(a, data)))  # @line L6
    return out  # @line L7


def averaging_kernel(kernels, a):
    """K_p(t) = sum_i a_i G_i(t) on the grid."""
    return [sum(ai * gk[t] for ai, gk in zip(a, kernels)) for t in range(len(kernels[0]))]


def spread(kernel_values, ts, ws, p):
    """12 int (t - p)^2 K(t)^2 dt for a function given on the grid."""
    return 12.0 * sum(w * (t - p) ** 2 * k * k for t, w, k in zip(ts, ws, kernel_values))


def noise_variance(a, cov):
    """a^T C a."""
    return sum(a[i] * cov[i][j] * a[j] for i in range(len(a)) for j in range(len(a)))
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_backus_gilbert_method.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/backus-gilbert-method/. The authors are listed in prov/GT011W.jsonl.
import math
import random
import unittest

from backus_gilbert_method import (areas, averaging_kernel, backus_gilbert, noise_variance,
                                   spread, spread_matrix, weights)
from imgla import solve


def setup(m=10, width=0.08, n=400):
    ts = [(i + 0.5) / n for i in range(n)]
    ws = [1.0 / n] * n
    g = [[math.exp(-0.5 * ((t - (i + 0.5) / m) / width) ** 2) / (width * math.sqrt(2.0 * math.pi))
          for t in ts] for i in range(m)]
    cov = [[1.0 if i == j else 0.0 for j in range(m)] for i in range(m)]
    return ts, ws, g, cov


def objective(a, s, cov, mu):
    m = len(a)
    return sum(a[i] * (s[i][j] + mu * cov[i][j]) * a[j] for i in range(m) for j in range(m))


class TestBackusGilbert(unittest.TestCase):
    def test_box_spread(self):
        n = 2000
        ts = [(i + 0.5) / n for i in range(n)]
        ws = [1.0 / n] * n
        for wdt in (0.1, 0.3):
            box = [1.0 / wdt if abs(t - 0.5) < wdt / 2 else 0.0 for t in ts]
            self.assertAlmostEqual(spread(box, ts, ws, 0.5), wdt, places=5)

    def test_unit_area_and_kkt(self):
        ts, ws, g, cov = setup()
        c = areas(g, ws)
        for p, mu in ((0.5, 1e-3), (0.27, 0.1)):
            a = weights(g, ts, ws, p, mu, cov)
            self.assertAlmostEqual(sum(x * y for x, y in zip(a, c)), 1.0, places=12)
            # Brute force: the KKT system [[2 W, c], [c^T, 0]] [a; l] = [0; 1].
            s = spread_matrix(g, ts, ws, p)
            m = len(c)
            kkt = [[2.0 * (s[i][j] + mu * cov[i][j]) for j in range(m)] + [c[i]] for i in range(m)]
            kkt.append(list(c) + [0.0])
            ref = solve(kkt, [0.0] * m + [1.0])[:m]
            for x, y in zip(a, ref):
                self.assertAlmostEqual(x, y, places=6)

    def test_optimal_among_feasible_weights(self):
        ts, ws, g, cov = setup()
        c = areas(g, ws)
        p, mu = 0.6, 0.01
        a = weights(g, ts, ws, p, mu, cov)
        s = spread_matrix(g, ts, ws, p)
        best = objective(a, s, cov, mu)
        rng = random.Random(71)
        cc = sum(x * x for x in c)
        for _ in range(30):
            v = [rng.gauss(0.0, 1.0) for _ in c]
            proj = sum(x * y for x, y in zip(v, c)) / cc
            d = [x - proj * y for x, y in zip(v, c)]
            b = [x + 0.01 * y for x, y in zip(a, d)]
            self.assertGreaterEqual(objective(b, s, cov, mu), best)

    def test_spread_matrix_matches_kernel_spread(self):
        ts, ws, g, cov = setup()
        a = weights(g, ts, ws, 0.4, 0.05, cov)
        s = spread_matrix(g, ts, ws, 0.4)
        direct = spread(averaging_kernel(g, a), ts, ws, 0.4)
        self.assertAlmostEqual(objective(a, s, cov, 0.0), direct, places=10)

    def test_trade_off_is_monotone(self):
        ts, ws, g, cov = setup()
        for p in (0.5, 0.33):
            prev_s, prev_v = -1.0, math.inf
            for mu in (1e-6, 1e-4, 1e-3, 1e-2, 1e-1, 1.0, 10.0):
                a = weights(g, ts, ws, p, mu, cov)
                sp = spread(averaging_kernel(g, a), ts, ws, p)
                nv = noise_variance(a, cov)
                self.assertGreaterEqual(sp, prev_s - 1e-12)
                self.assertLessEqual(nv, prev_v + 1e-12)
                prev_s, prev_v = sp, nv

    def test_constants_are_reproduced(self):
        ts, ws, g, cov = setup()
        data = [3.0 * ci for ci in areas(g, ws)]
        est = backus_gilbert(g, ts, ws, data, [0.2, 0.5, 0.9], 0.01, cov)
        for v in est:
            self.assertAlmostEqual(v, 3.0, places=10)

    def test_estimate_is_local_average(self):
        ts, ws, g, cov = setup()
        # A function that varies slowly on the scale of the spread (about 0.12).
        x = [math.sin(math.pi * t) + 0.5 * t for t in ts]
        data = [sum(w * gi * xi for w, gi, xi in zip(ws, gk, x)) for gk in g]
        for p in (0.3, 0.5, 0.7):
            a = weights(g, ts, ws, p, 1e-4, cov)
            k = averaging_kernel(g, a)
            avg = sum(w * ki * xi for w, ki, xi in zip(ws, k, x))
            est = backus_gilbert(g, ts, ws, data, [p], 1e-4, cov)[0]
            self.assertAlmostEqual(est, avg, places=10)
            self.assertLess(abs(est - (math.sin(math.pi * p) + 0.5 * p)), 0.08)


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

History

George Backus and Freeman Gilbert developed the method between 1967 and 1970 to find out what gross Earth data, such as the frequencies of free oscillations and the mass and moment of inertia of the Earth, can resolve about the density and elastic properties of the interior. Their papers introduced averaging kernels, the spread criterion and the trade-off curve between resolution and error. The method became a standard tool in seismology and helioseismology, and it influenced the later view of regularization in terms of resolution. The approximate inverse of Louis and Maass (1990) reverses the roles: the averaging kernel is fixed in advance and the weights follow from it.

References

  1. G. Backus and F. Gilbert, Numerical applications of a formalism for geophysical inverse problems, Geophysical Journal of the Royal Astronomical Society 13, 1967, 247 to 276, the formalism of averaging kernels for finite data (general locator)
  2. G. Backus and F. Gilbert, The resolving power of gross Earth data, Geophysical Journal of the Royal Astronomical Society 16, 1968, 169 to 205, the spread criterion and optimally localized averaging kernels (general locator)
  3. G. Backus and F. Gilbert, Uniqueness in the inversion of inaccurate gross Earth data, Philosophical Transactions of the Royal Society of London A 266, 1970, 123 to 192, the trade-off between resolution and error for noisy data (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_point
  • 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