Algorithm Search⌘K

Algorithmcore

Predictive deconvolution

Also called spiking deconvolution, gapped deconvolution.

Design a Wiener prediction error filter from the trace autocorrelation. With white reflectivity and a minimum-phase wavelet it compresses the wavelet and removes short-period multiples.

Time
O(n (p + g) + p^2) worst · average · best
Space
O(n + p + g) extra
Where
g = the prediction gap; n = the number of samples of the trace; p = the number of prediction taps
Properties
deterministicleast squaresnot linear in data
Origin
Kenneth L. Peacock, Sven Treitel, 1969

Predictive deconvolution sharpens a seismic trace and removes periodic multiples with one least-squares filter. It treats the trace as a signal that can be partly predicted from its past: the predictable part is the long tail of the source wavelet and the repeats of reverberations, and the part that cannot be predicted is the reflectivity of the earth. The filter predicts the trace a gap of α\alpha samples ahead and subtracts the prediction. With α=1\alpha = 1 it is spiking deconvolution. The filter comes from the autocorrelation of the trace through Toeplitz normal equations, which the Levinson-Durbin recursion solves. It is linear prediction applied to the convolutional model of a seismic trace, a special case of the Wiener filter.

In plain words

A seismic trace is the earth's list of echoes, blurred by the shape of the sound pulse. The pulse rings for a while, so each sample of the trace says something about the next few samples. The echoes of the earth come at random, so they cannot be guessed from the past. The method learns, from the trace itself, the best rule to guess each sample from the samples before it. Then it subtracts the guess. What is left is the part that no rule could guess: the sharp echoes. If the guess looks further ahead, the method keeps the start of the pulse and removes only what repeats later, such as the ringing of sound trapped in a water layer.

The problem

Input: a trace d0,…,dn−1d_0, \ldots, d_{n-1}; the number of taps pp; the gap α≥1\alpha \ge 1; the prewhitening ε≥0\varepsilon \ge 0; optionally a design window. Output: the prediction error filter ff and the output trace e=f∗de = f * d. The filter taps aa minimize the energy of the prediction error

E(a)=∑t(dt+α−∑j=0p−1ajdt−j)2,E(a) = \sum_t \Big(d_{t+\alpha} - \sum_{j=0}^{p-1} a_j d_{t-j}\Big)^2,

which leads to the normal equations ∑jajr∣i−j∣=rα+i\sum_{j} a_j r_{|i-j|} = r_{\alpha+i}, i=0,…,p−1i = 0, \ldots, p - 1, where rk=∑tdtdt+kr_k = \sum_t d_t d_{t+k}. The model behind it is the convolutional model d=w∗ρd = w * \rho with a white reflectivity ρ\rho and a minimum-phase wavelet ww. The whiteness makes the autocorrelation of the trace a multiple of the autocorrelation of the wavelet, so the trace alone tells the filter what the wavelet is, up to its phase, which the minimum-phase assumption fixes.

The algorithm

  1. PREDICTIVE-DECON(d, p, α, ε, window)
  2. 1r_k ← Σ_t d_t d_{t+k} for k = 0 … p + α - 1, over the design window
  3. 2r'_0 ← (1 + ε) r_0; r'_k ← r_k for k ≥ 1 ▷ prewhitening
  4. 3solve Σ_j a_j r'_|i-j| = r_{α+i}, i = 0 … p - 1, by Levinson recursion
  5. 4f ← (1, 0, …, 0, -a_0, …, -a_{p-1}) ▷ α - 1 zeros after the 1
  6. 5e_t ← Σ_k f_k d_{t-k} for every t ▷ apply to the whole trace
  7. 6return (e, f)

The filter of line L4 has length p+αp + \alpha. For α=1\alpha = 1 it is the spiking filter, whose output is as close to white as pp taps allow. For a larger gap the first α\alpha samples of the wavelet pass unchanged and only the later, predictable part is removed. Prewhitening adds εr0\varepsilon r_0 to the diagonal, as if white noise were added to the trace; it keeps the system well conditioned and limits the boost at frequencies where the trace has little energy. A value of ε\varepsilon between 0.1 and 1 percent is common; it is a tuning choice.

Example

An exact case. The wavelet wk=(1/2)kw_k = (1/2)^k has the autocorrelation (4/3)(1/2)k(4/3)(1/2)^k. With exact fractions, the spiking filter with p=5p = 5 gets the taps a=(1/2,0,0,0,0)a = (1/2, 0, 0, 0, 0), so f=(1,−1/2,0,…)f = (1, -1/2, 0, \ldots), and f∗w=(1,0,0,…)f * w = (1, 0, 0, \ldots): the wavelet becomes a spike. With the gap α=3\alpha = 3 the taps are (1/8,0,0,0)(1/8, 0, 0, 0), and the output keeps (1,1/2,1/4)(1, 1/2, 1/4) and is zero after.

A water-layer reverberation. A spike under a water layer with the sea floor reflection c=1/2c = 1/2 and the two-way water time τ=6\tau = 6 samples gives dt=(−1/2)md_t = (-1/2)^m at t=6mt = 6m and zero elsewhere, an endless ringing. The autocorrelation is nonzero only at multiples of 6. With the gap α=6\alpha = 6 and p=8p = 8, line L3 returns a=(−1/2,0,…,0)a = (-1/2, 0, \ldots, 0), so ff is 1 at lag 0 and +1/2+1/2 at lag 6. The output is a single spike: the filter removed all the multiples and kept the primary.

A synthetic trace. A reflectivity of 1500 samples has a Gaussian value with probability 0.1 and zero otherwise (seed 5). It is convolved with the decaying wavelet 0.8k0.8^k, k<60k < 60. The correlation between the trace and the reflectivity is 0.60. Spiking deconvolution with p=12p = 12 and ε=0.1\varepsilon = 0.1 percent gives the filter (1,−0.795,0.049,−0.086,0.022,…)(1, -0.795, 0.049, -0.086, 0.022, \ldots), close to the ideal (1,−0.8)(1, -0.8), and the correlation of the output with the reflectivity rises to 0.997. The filter is not exact because the sample autocorrelation of the reflectivity is only close to white: its lags 1 to 3 are −0.004-0.004, −0.055-0.055 and 0.0460.046 of lag 0. These numbers are measurements on one seed.

Correctness

The normal equations have exactly one solution, because the Toeplitz matrix is the Gram matrix of shifted copies of a nonzero trace and so is positive definite; prewhitening adds a ridge term and keeps it so. The Levinson recursion solves the system: it grows a forward and a backward solution one order at a time, and each reflection coefficient has ∣k∣<1|k| < 1. From ∣k∣<1|k| < 1 and Rouché's theorem, the spiking filter has all its zeros outside the unit circle, so it is minimum phase and has a stable causal inverse. Under the ideal model (white reflectivity, an autoregressive minimum-phase wavelet of order at most pp, the expected autocorrelation) the output is the reflectivity convolved with the first α\alpha wavelet samples, and for α=1\alpha = 1 it is the reflectivity. The proofs are in proofs/correctness.md.

Proof: The prediction filter is the unique least-squares predictor, Levinson recursion solves its Toeplitz equations, the spiking filter is minimum phase, and for an autoregressive wavelet under white reflectivity the output is the reflectivity convolved with the first alpha wavelet samplesfull

Setting. A trace d0,…,dN−1d_0, \ldots, d_{N-1} is real and not all zero; dt=0d_t = 0 outside this range. Its autocorrelation is rk=∑tdtdt+kr_k = \sum_t d_t d_{t+k}, so r−k=rkr_{-k} = r_k. The filter has pp taps a0,…,ap−1a_0, \ldots, a_{p-1} and the gap is α≥1\alpha \ge 1. The prediction of dt+αd_{t+\alpha} is d^t+α=∑j=0p−1ajdt−j\hat d_{t+\alpha} = \sum_{j=0}^{p-1} a_j d_{t-j}, and the prediction error filter (PEF) is f=(1,0,…,0,−a0,…,−ap−1)f = (1, 0, \ldots, 0, -a_0, \ldots, -a_{p-1}) with α−1\alpha - 1 zeros, so that et+α=(f∗d)t+α=dt+α−d^t+αe_{t+\alpha} = (f * d)_{t+\alpha} = d_{t+\alpha} - \hat d_{t+\alpha}. RR is the p×pp \times p Toeplitz matrix Rij=r∣i−j∣R_{ij} = r_{|i-j|} and gi=rα+ig_i = r_{\alpha+i}. We write zz for the unit delay and A(z)=∑jcjzjA(z) = \sum_j c_j z^j for the zz-transform of a filter cc.

Claim 1 (normal equations). The error energy E(a)=∑t(dt+α−d^t+α)2E(a) = \sum_{t} (d_{t+\alpha} - \hat d_{t+\alpha})^2, summed over all tt with the zero extension, is minimized by exactly one aa, the solution of Ra=gR a = g. With prewhitening ε≥0\varepsilon \ge 0, line L2 replaces r0r_0 by (1+ε)r0(1 + \varepsilon) r_0; the solution then minimizes E(a)+εr0∥a∥2E(a) + \varepsilon r_0 \|a\|^2.

Proof. Expand E(a)=∑tdt+α2−2∑jaj∑tdt+αdt−j+∑i,jaiaj∑tdt−idt−jE(a) = \sum_t d_{t+\alpha}^2 - 2\sum_j a_j \sum_t d_{t+\alpha} d_{t-j} + \sum_{i,j} a_i a_j \sum_t d_{t-i} d_{t-j}. With the zero extension, ∑tdt−idt−j=r∣i−j∣\sum_t d_{t-i} d_{t-j} = r_{|i-j|} and ∑tdt+αdt−j=rα+j\sum_t d_{t+\alpha} d_{t-j} = r_{\alpha+j}, so E(a)=r0−2aTg+aTRaE(a) = r_0 - 2 a^T g + a^T R a. RR is the Gram matrix of the shifted copies (dt−j)t(d_{t-j})_t, j=0,…,p−1j = 0, \ldots, p - 1. These copies are linearly independent: in ∑jcjdt−j\sum_j c_j d_{t-j} with c≠0c \ne 0, let j∗j^\ast be the largest index with cj∗≠0c_{j^\ast} \ne 0 and t∗t^\ast the last index with dt∗≠0d_{t^\ast} \ne 0; the term at time t∗+j∗t^\ast + j^\ast is cj∗dt∗≠0c_{j^\ast} d_{t^\ast} \ne 0. So RR is positive definite, EE is strictly convex, and its gradient 2(Ra−g)2(R a - g) is zero at exactly one point. With prewhitening the matrix is R+εr0IR + \varepsilon r_0 I, the Hessian of E(a)+εr0∥a∥2E(a) + \varepsilon r_0\|a\|^2, which is also positive definite. □\square

Claim 2 (Levinson recursion). For a symmetric positive definite Toeplitz matrix, the function levinson (line L3) returns the solution of Rx=gR x = g in O(p2)O(p^2) operations.

Proof. For m=1,…,pm = 1, \ldots, p let RmR_m be the leading m×mm \times m block. The loop keeps two vectors: a(m)a^{(m)} with a0(m)=1a^{(m)}_0 = 1 and Rma(m)=(ϵm,0,…,0)TR_m a^{(m)} = (\epsilon_m, 0, \ldots, 0)^T, and x(m)x^{(m)} with Rmx(m)=(g0,…,gm−1)TR_m x^{(m)} = (g_0, \ldots, g_{m-1})^T. For m=1m = 1 these are a=(1)a = (1), ϵ1=r0\epsilon_1 = r_0 and x=(g0/r0)x = (g_0/r_0), as in the code. Because RmR_m is symmetric and Toeplitz, it commutes with the reversal JJ, so Rm(Ja(m))=(0,…,0,ϵm)TR_m (J a^{(m)}) = (0, \ldots, 0, \epsilon_m)^T. For the step to m+1m + 1, let Δ=∑j<maj(m)rm−j\Delta = \sum_{j<m} a^{(m)}_j r_{m-j}. Then

Rm+1(a(m)0)=(ϵm0Δ),Rm+1(0Ja(m))=(Δ0ϵm),R_{m+1}\begin{pmatrix} a^{(m)} \\ 0 \end{pmatrix} = \begin{pmatrix} \epsilon_m \\ 0 \\ \Delta \end{pmatrix}, \qquad R_{m+1}\begin{pmatrix} 0 \\ J a^{(m)} \end{pmatrix} = \begin{pmatrix} \Delta \\ 0 \\ \epsilon_m \end{pmatrix},

where the middle blocks have m−1m - 1 zeros. With k=−Δ/ϵmk = -\Delta/\epsilon_m, the vector a(m+1)=(a(m),0)+k(0,Ja(m))a^{(m+1)} = (a^{(m)}, 0) + k (0, J a^{(m)}) has first entry 11 and gives Rm+1a(m+1)=(ϵm+kΔ,0,…,0)TR_{m+1} a^{(m+1)} = (\epsilon_m + k\Delta, 0, \ldots, 0)^T, with ϵm+1=ϵm+kΔ=ϵm(1−k2)\epsilon_{m+1} = \epsilon_m + k\Delta = \epsilon_m (1 - k^2). Since ϵm+1=a(m+1)TRm+1a(m+1)>0\epsilon_{m+1} = a^{(m+1)T} R_{m+1} a^{(m+1)} > 0 for a positive definite matrix, the check in the code never fails, and ∣k∣<1|k| < 1. For xx, let η=∑j<mxj(m)rm−j\eta = \sum_{j<m} x^{(m)}_j r_{m-j}; then Rm+1(x(m),0)=(g0,…,gm−1,η)R_{m+1}(x^{(m)}, 0) = (g_0, \ldots, g_{m-1}, \eta), and adding μJa(m+1)\mu J a^{(m+1)} with μ=(gm−η)/ϵm+1\mu = (g_m - \eta)/\epsilon_{m+1} changes only the last entry, to gmg_m. These are the lines of the loop. Each step costs O(m)O(m), so the total is O(p2)O(p^2), and the memory is O(p)O(p). □\square

Claim 3 (the spiking filter is minimum phase). For α=1\alpha = 1, the PEF ff has F(z)=∑jfjzjF(z) = \sum_j f_j z^j with all zeros outside the closed unit disk. So 1/F(z)1/F(z) is a causal, stable filter.

Proof. For α=1\alpha = 1, the equations Ra=gR a = g say that (Rp+1f)i=0(R_{p+1} f)_i = 0 for i=1,…,pi = 1, \ldots, p, with (Rp+1f)0>0(R_{p+1} f)_0 > 0. By uniqueness (Claim 1 for Rp+1R_{p+1}) ff is the vector a(p+1)a^{(p+1)} of the Levinson recursion run on r0,…,rpr_0, \ldots, r_p. Let Am(z)A_m(z) be the polynomial of a(m)a^{(m)} (degree at most m−1m - 1) and A~m(z)=zmAm(1/z)\tilde A_m(z) = z^{m} A_m(1/z), the polynomial of the reversed vector shifted by one, so that Am+1(z)=Am(z)+k A~m(z)A_{m+1}(z) = A_m(z) + k\,\tilde A_m(z). On ∣z∣=1|z| = 1 the coefficients are real, so ∣A~m(z)∣=∣Am(zˉ)∣=∣Am(z)∣|\tilde A_m(z)| = |A_m(\bar z)| = |A_m(z)|. A1=1A_1 = 1 has no zeros. If AmA_m has no zeros in ∣z∣≤1|z| \le 1, then on ∣z∣=1|z| = 1 we have ∣kA~m(z)∣=∣k∣ ∣Am(z)∣<∣Am(z)∣|k \tilde A_m(z)| = |k|\,|A_m(z)| < |A_m(z)| because ∣k∣<1|k| < 1 (Claim 2). By Rouché's theorem Am+1A_{m+1} has as many zeros in ∣z∣<1|z| < 1 as AmA_m, that is none, and the strict inequality excludes zeros on ∣z∣=1|z| = 1. By induction F=Ap+1F = A_{p+1} has all zeros in ∣z∣>1|z| > 1. A polynomial with no zeros in the closed unit disk has a reciprocal that is analytic on a disk of radius above 1, so its power series is causal with geometrically decaying coefficients. Prewhitening keeps the matrix positive definite, so the claim holds with it too. □\square

Claim 4 (the ideal case). Assume the statistical model: d=w∗ρd = w * \rho, where ρ\rho is white with Eρtρs=σ2[t=s]\mathbb{E}\rho_t \rho_s = \sigma^2 [t = s], and the wavelet is autoregressive of order at most pp, that is W(z)=1/A(z)W(z) = 1/A(z) with A(z)=1+∑j=1pAjzjA(z) = 1 + \sum_{j=1}^{p} A_j z^j having all zeros outside the closed unit disk. Replace rkr_k by the expected autocorrelation Edtdt+k\mathbb{E} d_t d_{t+k}. Then the PEF with gap α\alpha and pp taps gives et=∑k=0α−1wkρt−ke_t = \sum_{k=0}^{\alpha-1} w_k \rho_{t-k}: the output is the reflectivity convolved with the first α\alpha samples of the wavelet. For α=1\alpha = 1 the output is w0ρt=ρtw_0 \rho_t = \rho_t.

Proof. Since 1/A1/A is causal and stable, dt=∑k≥0wkρt−kd_t = \sum_{k \ge 0} w_k \rho_{t-k}, and ρt=(A∗d)t\rho_t = (A * d)_t is a function of dt,…,dt−pd_t, \ldots, d_{t-p}. So the past dt,dt−1,…d_t, d_{t-1}, \ldots and the past ρt,ρt−1,…\rho_t, \rho_{t-1}, \ldots span the same space. Split dt+α=∑k<αwkρt+α−k+∑k≥αwkρt+α−kd_{t+\alpha} = \sum_{k<\alpha} w_k \rho_{t+\alpha-k} + \sum_{k \ge \alpha} w_k \rho_{t+\alpha-k}. The first sum is uncorrelated with every dt−jd_{t-j}, j≥0j \ge 0, because it holds only ρ\rho at times after tt. The second sum is a function of the past, and it is a linear function of dt,…,dt−p+1d_t, \ldots, d_{t-p+1} only: apply the recursion ds=ρs−∑j=1pAjds−jd_s = \rho_s - \sum_{j=1}^{p} A_j d_{s-j} for s=t+α,…,t+1s = t + \alpha, \ldots, t + 1 and drop the future ρ\rho terms; what remains is a combination of dt,…,dt−p+1d_t, \ldots, d_{t-p+1}. Call its coefficients a∗a^\ast. Then the error dt+α−∑jaj∗dt−jd_{t+\alpha} - \sum_j a^\ast_j d_{t-j} equals the first sum, which is orthogonal to dt,…,dt−p+1d_t, \ldots, d_{t-p+1}. Orthogonality of the error to the data is exactly the normal equations Ra∗=gR a^\ast = g with the expected autocorrelation, so by Claim 1 the filter of lines L2 and L3 is a∗a^\ast, and the output is the first sum. □\square

For the test cases: the wavelet wk=(1/2)kw_k = (1/2)^k has A(z)=1−z/2A(z) = 1 - z/2, so the spiking taps are (1/2,0,…,0)(1/2, 0, \ldots, 0), the gapped taps are ((1/2)α,0,…)((1/2)^\alpha, 0, \ldots), and the output keeps the first α\alpha samples. A water-layer reverberation W(z)=1/(1+czτ)W(z) = 1/(1 + c z^\tau) has wk=0w_k = 0 for 0<k<τ0 < k < \tau, so with gap τ\tau and p≥1p \ge 1 the output is ρ\rho itself.

Claim 5 (cost). For a trace of NN samples, line L1 costs O(N(p+α))O(N (p + \alpha)), Levinson costs O(p2)O(p^2) and line L5 costs O(N(p+α))O(N (p + \alpha)). □\square

Proof. The autocorrelation computes p+αp + \alpha lags, each a sum of at most NN products. The convolution of line L5 has at most p+αp + \alpha products per output sample. Claim 2 gives the cost of the solve. □\square

Complexity

In the real-RAM model, the autocorrelation costs O(n(p+α))O(n (p + \alpha)), the Levinson recursion O(p2)O(p^2) and the filter application O(n(p+α))O(n (p + \alpha)). A general dense solver would cost O(p3)O(p^3). The autocorrelation and the convolution can use the FFT, at O(nlog⁡n)O(n \log n) each. Extra space is O(n+p+α)O(n + p + \alpha).

Properties

  • Least squares: the filter minimizes the prediction error energy on the design window (a theorem, Claim 1).
  • Data adaptive and so not linear: the filter depends on the trace, and the output is not a linear function of the input.
  • The spiking filter is minimum phase (a theorem, Claim 3).
  • Only the amplitude spectrum of the wavelet is estimated, from the autocorrelation. The phase comes from the minimum-phase assumption, not from the data. If the wavelet is not minimum phase, the output has a phase error.
  • Whiteness of the reflectivity is an assumption. Real reflectivity often has more energy at high frequencies than a white series, and the filter then removes part of the earth signal.

Variants and improvements

  • Time-variant deconvolution: design separate filters in several time gates, because the wavelet changes with time as the earth absorbs high frequencies.
  • Surface-consistent deconvolution: split the filter into source, receiver, offset and midpoint terms and estimate them over the whole survey.
  • Multichannel prediction: predict one trace from several, for multiples with moveout.
  • Minimum entropy deconvolution drops the white and minimum-phase assumptions and asks for a sparse output instead.
  • Homomorphic deconvolution works in the cepstrum domain and can handle mixed-phase wavelets.
  • For multiples with long periods and moveout, surface-related multiple elimination and the parabolic Radon transform work better.

When to use it

Use spiking deconvolution early in processing, before stacking, to compress the wavelet and widen the spectrum. Use gapped deconvolution on shallow water data where the reverberation period is short and nearly constant; on zero-offset or near-offset traces, or in the tau-p domain, where the period does not change with offset.

Pitfalls

  • With too little prewhitening, the filter boosts frequencies where the trace holds only noise, and the output is noisy.
  • The design window must hold enough samples, several times the filter length, and must not hold strong coherent noise; the sample autocorrelation is then a poor estimate.
  • A gap that does not match the multiple period leaves part of the multiples; a gap that is too small also shortens the primary wavelet.
  • Multiples are periodic only at zero offset in flat layers. At far offsets their period changes, and a single-channel filter removes them only in part.
  • A wavelet that is not minimum phase, such as the zero-phase wavelet of a processed vibroseis record, is not compressed correctly unless it is first converted to minimum phase.

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.

imgla.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/.
"""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
predictive_deconvolution.py 77 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/predictive-deconvolution/. The authors are listed in prov/R3R43H.jsonl.
"""Predictive deconvolution with a Wiener prediction error filter.

A prediction filter a_0..a_{n-1} with gap alpha predicts d[t + alpha] from
d[t], d[t - 1], .., d[t - n + 1]. Its least-squares taps solve the Toeplitz
normal equations sum_j a_j r_|i-j| = r_{alpha+i}, i = 0..n-1, with r the
trace autocorrelation. The prediction error filter is
f = (1, 0, .., 0, -a_0, .., -a_{n-1}) with alpha - 1 zeros, and the output is
e = f * d. alpha = 1 is spiking deconvolution. Works with float and with
fractions.Fraction values.
"""


def autocorrelation(d, maxlag):
    """r_k = sum_t d_t d_{t+k} for k = 0..maxlag (zero beyond the trace)."""
    n = len(d)
    return [sum(d[t] * d[t + k] for t in range(n - k)) if k < n else 0 * d[0]
            for k in range(maxlag + 1)]


def levinson(r, g):
    """Solve the symmetric Toeplitz system sum_j x_j r_|i-j| = g_i, i = 0..n-1.

    r has at least n entries and the matrix must be positive definite.
    Levinson recursion: O(n^2) operations and O(n) extra memory.
    """
    n = len(g)
    if r[0] == 0:
        raise ValueError("r_0 must be positive")
    a = [1 + 0 * r[0]]
    err = r[0]
    x = [g[0] / r[0]]
    for m in range(1, n):
        delta = sum(a[j] * r[m - j] for j in range(m))
        k = -delta / err
        ext = a + [0 * r[0]]
        a = [ext[j] + k * ext[m - j] for j in range(m + 1)]
        err = err * (1 - k * k)
        if err <= 0:
            raise ValueError("the Toeplitz matrix is not positive definite")
        eps = sum(x[j] * r[m - j] for j in range(m))
        mu = (g[m] - eps) / err
        x = x + [0 * r[0]]
        x = [x[j] + mu * a[m - j] for j in range(m + 1)]
    return x


def prediction_filter(r, n, gap, prewhitening=0):
    """The n prediction taps for the gap from the autocorrelation r (at least n + gap lags)."""
    rr = [r[0] * (1 + prewhitening)] + list(r[1:n])  # @line L2
    g = [r[gap + i] for i in range(n)]
    return levinson(rr, g)  # @line L3


def prediction_error_filter(a, gap):
    """f = (1, 0 .. 0, -a_0 .. -a_{n-1}) with gap - 1 zeros."""
    one = 1 + 0 * a[0]
    return [one] + [0 * one] * (gap - 1) + [-v for v in a]


def apply_filter(f, d):
    """The causal convolution e_t = sum_k f_k d_{t-k}, t = 0..len(d) - 1."""
    return [sum(f[k] * d[t - k] for k in range(min(len(f), t + 1))) for t in range(len(d))]


def predictive_deconvolution(d, n, gap=1, prewhitening=0, design=None):
    """Design the filter on d[design[0]:design[1]] (default the whole trace) and apply it to d.

    Returns (e, f): the output trace and the prediction error filter.
    """
    lo, hi = (0, len(d)) if design is None else design
    r = autocorrelation(d[lo:hi], n + gap - 1)  # @line L1
    a = prediction_filter(r, n, gap, prewhitening)
    f = prediction_error_filter(a, gap)  # @line L4
    e = apply_filter(f, d)  # @line L5
    return e, f  # @line L6
test_predictive_deconvolution.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/predictive-deconvolution/. The authors are listed in prov/R3R43H.jsonl.

import math
import random
from fractions import Fraction as F

import imgla as la
from predictive_deconvolution import (
    apply_filter,
    autocorrelation,
    levinson,
    prediction_error_filter,
    prediction_filter,
    predictive_deconvolution,
)


def toeplitz(r, n):
    return [[r[abs(i - j)] for j in range(n)] for i in range(n)]


def ar1_autocorrelation(n):
    """Exact autocorrelation of the infinite wavelet w_k = (1/2)^k: r_k = (4/3) (1/2)^k."""
    return [F(4, 3) * F(1, 2) ** k for k in range(n)]


def test_levinson_matches_dense_solve():
    rng = random.Random(1)
    for n in (1, 2, 5, 12):
        d = [rng.gauss(0.0, 1.0) for _ in range(60)]
        r = autocorrelation(d, n)
        g = [rng.gauss(0.0, 1.0) for _ in range(n)]
        x = levinson(r, g)
        y = la.solve(toeplitz(r, n), g)
        assert max(abs(a - b) for a, b in zip(x, y)) < 1e-9


def test_levinson_is_exact_with_fractions():
    rng = random.Random(2)
    d = [F(rng.randint(-5, 5)) for _ in range(20)]
    d[0] = F(7)
    r = autocorrelation(d, 6)
    g = [F(rng.randint(-9, 9)) for _ in range(6)]
    assert levinson(r, g) == la.solve(toeplitz(r, 6), g)


def test_spiking_filter_of_ar1_wavelet():
    r = ar1_autocorrelation(8)
    a = prediction_filter(r, 5, 1)
    assert a == [F(1, 2), 0, 0, 0, 0]
    f = prediction_error_filter(a, 1)
    w = [F(1, 2) ** k for k in range(30)]
    e = apply_filter(f, w)
    assert e == [1] + [0] * 29


def test_gapped_filter_keeps_the_first_alpha_samples():
    for gap in (2, 3, 5):
        r = ar1_autocorrelation(4 + gap + 1)
        a = prediction_filter(r, 4, gap)
        assert a == [F(1, 2) ** gap, 0, 0, 0]
        f = prediction_error_filter(a, gap)
        assert len(f) == gap + 4
        w = [F(1, 2) ** k for k in range(30)]
        e = apply_filter(f, w)
        assert e[:gap] == w[:gap]
        assert e[gap:] == [0] * (30 - gap)


def test_gap_equal_to_reverberation_period_removes_it():
    # d has (-c)^m at t = m tau: a spike under a water-layer reverberation.
    c, tau = F(1, 2), 6
    n = 8
    r = [F(0)] * (n + tau + 1)
    for k in range(len(r)):
        if k % tau == 0:
            r[k] = (-c) ** (k // tau) / (1 - c * c)
    a = prediction_filter(r, n, tau)
    assert a == [-c] + [0] * (n - 1)
    d = [(-c) ** (t // tau) if t % tau == 0 else F(0) for t in range(60)]
    e = apply_filter(prediction_error_filter(a, tau), d)
    assert e == [1] + [0] * 59


def test_prewhitening_adds_to_the_diagonal():
    rng = random.Random(3)
    d = [rng.gauss(0.0, 1.0) for _ in range(80)]
    n, gap, eps = 6, 2, 0.05
    r = autocorrelation(d, n + gap)
    a = prediction_filter(r, n, gap, eps)
    mat = toeplitz(r, n)
    for i in range(n):
        mat[i][i] += eps * r[0]
    b = la.solve(mat, [r[gap + i] for i in range(n)])
    assert max(abs(p - q) for p, q in zip(a, b)) < 1e-10


def test_filter_is_least_squares_prediction():
    # Perturbing the taps never lowers the prediction error energy on the design data.
    rng = random.Random(4)
    d = [rng.gauss(0.0, 1.0) for _ in range(150)]
    d = apply_filter([1.0, 0.9, 0.4], d)
    n, gap = 4, 2

    def energy(a):
        pad = [0.0] * len(d) + d + [0.0] * (n + gap)
        e = apply_filter(prediction_error_filter(a, gap), pad)
        return sum(v * v for v in e)

    r = autocorrelation(d, n + gap)
    a = prediction_filter(r, n, gap)
    base = energy(a)
    for _ in range(20):
        b = [v + rng.gauss(0.0, 0.05) for v in a]
        assert energy(b) >= base - 1e-9


def test_spiking_deconvolution_recovers_sparse_reflectivity():
    rng = random.Random(5)
    nt = 1500
    refl = [rng.gauss(0.0, 1.0) if rng.random() < 0.1 else 0.0 for _ in range(nt)]
    w = [0.8 ** k for k in range(60)]
    d = apply_filter(w, refl)
    e, f = predictive_deconvolution(d, 12, gap=1, prewhitening=0.001)
    assert abs(f[1] + 0.8) < 0.08
    num = sum(p * q for p, q in zip(e, refl))
    den = math.sqrt(sum(p * p for p in e) * sum(q * q for q in refl))
    assert num / den > 0.95


def test_spiking_filter_is_minimum_phase():
    # The inverse of the prediction error filter, run as a recursion, decays.
    rng = random.Random(6)
    d = apply_filter([1.0, -1.2, 0.6, 0.3], [rng.gauss(0.0, 1.0) for _ in range(400)])
    _, f = predictive_deconvolution(d, 10, gap=1, prewhitening=0.01)
    y = []
    for t in range(600):
        v = (1.0 if t == 0 else 0.0) - sum(f[k] * y[t - k] for k in range(1, min(len(f), t + 1)))
        y.append(v)
    assert max(abs(v) for v in y[500:]) < 1e-6

History

Levinson (Journal of Mathematics and Physics, volume 25, dated 1946 and often cited as 1947) gave the recursive solution of the Toeplitz equations of Wiener's least-squares prediction. Robinson (1957) modeled the trace as a wavelet convolved with an uncorrelated series and used the prediction error operator to recover that series. Peacock and Treitel (1969) made predictive deconvolution with a gap a standard tool and showed how the gap length controls the output wavelet and the attenuation of reverberations.

References

  1. Kenneth L. Peacock and Sven Treitel, Predictive deconvolution, theory and practice, Geophysics 34(2), 1969, 155 to 169, the prediction error filter with a prediction distance, its normal equations from the autocorrelation, and the effect of the gap on the wavelet and on reverberations
  2. Enders A. Robinson, Predictive decomposition of seismic traces, Geophysics 22(4), 1957, 767 to 778, the model of a trace as a wavelet convolved with an uncorrelated series, and the prediction error operator that recovers the series
  3. Norman Levinson, The Wiener RMS (root mean square) error criterion in filter design and prediction, Journal of Mathematics and Physics 25(1-4), 1946, 261 to 278, the recursive solution of the Toeplitz normal equations of the Wiener filter
  4. Oz Yilmaz, Seismic Data Analysis, Society of Exploration Geophysicists, 2001, Investigations in Geophysics 10, the chapter on deconvolution (spiking and predictive deconvolution, prewhitening, the design window)

Where this leads

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