Algorithm Search⌘K

Algorithmadvanced

Minimum entropy deconvolution

Also called MED.

Find the filter whose output is most spiky, measured by the varimax norm, by a fixed-point iteration. It needs no minimum-phase wavelet and no white reflectivity.

Time
O(k (m n L + L^3)) worst · averageO(m n L + L^3) best
Space
O(m (n + L^2)) extra
Where
L = the number of filter taps; k = the number of iterations; m = the number of traces; n = the number of samples of each trace
Properties
deterministicnot linear in data
Origin
Ralph A. Wiggins, 1978

Minimum entropy deconvolution (MED) designs a deconvolution filter without a model of the wavelet. It assumes only that the reflectivity is sparse, a few strong spikes with small values in between, and looks for the filter that makes the output as spiky as possible. Spikiness is measured by the varimax norm, the sum of fourth powers of the output divided by the square of the sum of squares. The filter comes from a fixed-point iteration: each step solves a Toeplitz system built from the current output. Unlike predictive deconvolution, it does not assume a minimum-phase wavelet or a white reflectivity, so it can compress a mixed-phase wavelet in the convolutional model of a trace.

In plain words

A trace is a list of sharp echoes, smeared by the shape of the sound pulse. Smearing spreads each echo over many samples, so the trace looks busy and even. A good filter undoes the smear and leaves a few big samples among many small ones. The method gives every candidate filter a score: high when a few samples hold most of the energy, low when the energy is spread evenly. It then looks for the filter with the highest score. It starts from a filter that changes nothing, sees which output samples are big, builds a new filter that makes those samples bigger still, and repeats. It does not need to know anything about the shape of the pulse, only that the true echoes are few.

The problem

Input: traces x1,…,xmx_1, \ldots, x_m of nn samples; the filter length LL; the number of iterations. Output: a filter ff of LL taps with ∥f∥=1\|f\| = 1 and the outputs yi=f∗xiy_i = f * x_i (full convolutions). The filter should maximize

Φ(f)=∑i=1mV(yi),V(y)=∑tyt4(∑tyt2)2.\Phi(f) = \sum_{i=1}^{m} V(y_i), \qquad V(y) = \frac{\sum_t y_t^4}{\big(\sum_t y_t^2\big)^2}.

For an output of TT samples, VV lies between 1/T1/T (all samples of equal size) and 11 (one nonzero sample). VV does not change when ff is scaled, so only the direction of ff matters, and the output is fixed only up to a scale, a sign and a time shift. The varimax norm is a fourth moment over the square of a second moment, a kurtosis-like measure, which is why MED is related to independent component analysis, which also maximizes such a contrast.

The algorithm

  1. MED(x_1 … x_m, L, iters)
  2. 1f ← spike at tap ⌊L/2⌋; R_i ← autocorrelation matrix of x_i (L × L, Toeplitz)
  3. 2repeat iters times, or until f stops changing
  4. 3y_i ← f * x_i for every trace
  5. 4E_i ← Σ_t y_it²; F_i ← Σ_t y_it⁴; w_i ← F_i / E_i³
  6. 5A ← Σ_i w_i R_i
  7. 6c ← Σ_i b_i / E_i², where b_ik = Σ_t y_it³ x_i,t-k
  8. 7f ← the solution of A f = c, scaled to unit length
  9. 8return f

The gradient of Φ\Phi is 4∑i(biEi−FiRif)/Ei34\sum_i (b_i E_i - F_i R_i f)/E_i^3, so it is zero exactly when Af=cA f = c with AA and cc taken at ff. Line L7 solves this equation with AA and cc frozen at the current filter, and the next step updates them. The vector bib_i is the cross-correlation of the cubed output with the input: cubing makes the large samples dominate, so each step pulls the filter toward the one that predicts the current large samples. The start at the center tap lets the filter shift the output both ways, which a mixed-phase inverse needs.

Example

The measure. For T=4T = 4 samples, V(1,0,0,0)=1V(1, 0, 0, 0) = 1, V(1,−1,0,0)=2/4=0.5V(1, -1, 0, 0) = 2/4 = 0.5 and V(1,1,1,1)=4/16=0.25=1/TV(1, 1, 1, 1) = 4/16 = 0.25 = 1/T.

A mixed-phase wavelet. A reflectivity of 300 samples has a Gaussian value with probability 0.05 and zero otherwise (seed 6). It is convolved with the wavelet (0.3,−0.8,1.0,−0.4)(0.3, -0.8, 1.0, -0.4). The polynomial 0.3−0.8z+z2−0.4z30.3 - 0.8z + z^2 - 0.4z^3 has the zero 1.51.5 outside the unit circle and the zeros 0.5±0.5i0.5 \pm 0.5i inside it, so the wavelet is mixed phase and a minimum-phase method would not compress it correctly. MED with L=15L = 15 taps gives:

reflectivity trace MED output
varimax norm VV 0.1948 0.0813 0.2144
best normalized correlation with the reflectivity 1 0.733 0.964

The correlation is the largest over time shifts, with the sign ignored, because MED fixes neither. The values of Φ\Phi over the iterations were 0.08130.0813, 0.14330.1433, 0.20670.2067, 0.21440.2144, and then stayed at 0.21440.2144 to four digits; the iteration stopped after 23 steps, when the change of ff fell below 10−1210^{-12}, with a gradient of size 4.5×10−134.5 \times 10^{-13}. The output has a higher varimax norm than the true reflectivity: the filter found a spikier signal than the earth's own. These numbers are measurements on one seed.

Correctness

The varimax norm lies in [1/T,1][1/T, 1], with 11 for a single spike and 1/T1/T for samples of equal size (a theorem, by the Cauchy-Schwarz inequality). Φ\Phi does not change when ff is scaled. The gradient has the closed form above. The matrix AA is a positive combination of autocorrelation matrices of nonzero traces, so it is symmetric positive definite and line L7 has exactly one solution. A unit filter is a fixed point of lines L3 to L7 if and only if the gradient of Φ\Phi is zero there; so a limit of the iteration is a stationary point of Φ\Phi. These are theorems; the proofs are in proofs/correctness.md. They do not say that the iteration converges, that Φ\Phi grows at each step, or that the stationary point is the global maximum. Fast convergence and a growing Φ\Phi are measurements on test data.

Proof: The varimax norm lies between 1/T and 1, its gradient has a closed form, and the fixed points of Wiggins' iteration are exactly the stationary points of the total varimaxfull

Setting. There are MM traces x1,…,xMx_1, \ldots, x_M, real and not all zero, and a real filter ff of LL taps, f≠0f \ne 0. The output of trace ii is the full convolution yi=f∗xiy_i = f * x_i, yit=∑kfkxi,t−ky_{it} = \sum_k f_k x_{i,t-k}, of length TiT_i. The varimax norm of a nonzero yy is V(y)=∑tyt4/(∑tyt2)2V(y) = \sum_t y_t^4 / (\sum_t y_t^2)^2. We write Ei=∑tyit2E_i = \sum_t y_{it}^2, Fi=∑tyit4F_i = \sum_t y_{it}^4, bik=∑tyit3xi,t−kb_{ik} = \sum_t y_{it}^3 x_{i,t-k}, and RiR_i for the L×LL \times L matrix (Ri)kj=∑txi,t−kxi,t−j(R_i)_{kj} = \sum_t x_{i,t-k} x_{i,t-j}, which is Toeplitz because the convolution is full. The objective is Φ(f)=∑iV(yi)\Phi(f) = \sum_i V(y_i). Lines L3 to L7 form

A(f)=∑iFiEi3Ri,c(f)=∑ibiEi2,A(f) = \sum_i \frac{F_i}{E_i^3} R_i, \qquad c(f) = \sum_i \frac{b_i}{E_i^2},

solve A(f)u=c(f)A(f) u = c(f), and set the new filter to u/∥u∥u / \|u\|.

Claim 1 (bounds of the varimax norm). For a nonzero yy of length TT, 1/T≤V(y)≤11/T \le V(y) \le 1. V=1V = 1 exactly when yy has one nonzero sample, and V=1/TV = 1/T exactly when all ∣yt∣|y_t| are equal.

Proof. For the upper bound, ∑tyt4≤(max⁡tyt2)∑tyt2≤(∑tyt2)2\sum_t y_t^4 \le (\max_t y_t^2) \sum_t y_t^2 \le (\sum_t y_t^2)^2. The second inequality is an equality only if at most one yty_t is nonzero, and then the first is too. For the lower bound, the Cauchy-Schwarz inequality for (yt2)t(y_t^2)_t and (1)t(1)_t gives (∑tyt2)2≤T∑tyt4(\sum_t y_t^2)^2 \le T \sum_t y_t^4, with equality exactly when all yt2y_t^2 are equal. □\square

Claim 2 (scale invariance). Φ(λf)=Φ(f)\Phi(\lambda f) = \Phi(f) for every λ≠0\lambda \ne 0. So the normalization after line L7 does not change Φ\Phi, and the problem is a search over directions of ff.

Proof. yiy_i scales by λ\lambda, the numerator of VV by λ4\lambda^4 and the denominator by λ4\lambda^4. □\square

Claim 3 (the gradient). ∂Φ∂fk=4∑ibikEi−Fi(Rif)kEi3\dfrac{\partial \Phi}{\partial f_k} = 4\sum_i \dfrac{b_{ik} E_i - F_i (R_i f)_k}{E_i^3}.

Proof. Since ∂yit/∂fk=xi,t−k\partial y_{it}/\partial f_k = x_{i,t-k}, we get ∂Fi/∂fk=4∑tyit3xi,t−k=4bik\partial F_i/\partial f_k = 4\sum_t y_{it}^3 x_{i,t-k} = 4 b_{ik} and ∂Ei/∂fk=2∑tyitxi,t−k\partial E_i/\partial f_k = 2\sum_t y_{it} x_{i,t-k}. Further ∑tyitxi,t−k=∑jfj∑txi,t−jxi,t−k=(Rif)k\sum_t y_{it} x_{i,t-k} = \sum_j f_j \sum_t x_{i,t-j} x_{i,t-k} = (R_i f)_k. The quotient rule on Fi/Ei2F_i/E_i^2 gives (4bikEi2−Fi⋅2Ei⋅2(Rif)k)/Ei4(4 b_{ik} E_i^2 - F_i \cdot 2E_i \cdot 2 (R_i f)_k)/E_i^4, which is the term of trace ii. □\square

Claim 4 (the system is solvable). If some yiy_i is not zero, A(f)A(f) is symmetric positive definite, so line L7 has exactly one solution.

Proof. Each RiR_i is the Gram matrix of the shifted copies (xi,t−k)t(x_{i,t-k})_t, k=0,…,L−1k = 0, \ldots, L - 1. For a nonzero xix_i these copies are linearly independent (take the largest kk with a nonzero coefficient and the last nonzero sample of xix_i; that output sample is not cancelled), so RiR_i is positive definite, and it is the zero matrix for xi=0x_i = 0. The weights Fi/Ei3F_i/E_i^3 are positive for every trace with yi≠0y_i \ne 0, and yi≠0y_i \ne 0 whenever xi≠0x_i \ne 0 because convolution by a nonzero ff is injective. So A(f)A(f) is a positive combination of positive definite matrices plus zero matrices. □\square

Claim 5 (fixed points are stationary points). A unit vector ff is a fixed point of the iteration (the new filter equals ff) if and only if ∇Φ(f)=0\nabla \Phi(f) = 0.

Proof. By Claim 3, ∇Φ(f)=4(c(f)−A(f)f)\nabla \Phi(f) = 4(c(f) - A(f) f), so ff is stationary exactly when A(f)f=c(f)A(f) f = c(f). If A(f)f=c(f)A(f) f = c(f), then line L7 returns u=fu = f by Claim 4, and u/∥u∥=fu/\|u\| = f. Conversely, let u/∥u∥=fu/\|u\| = f, so u=μfu = \mu f with μ=∥u∥>0\mu = \|u\| > 0 and c(f)=μA(f)fc(f) = \mu A(f) f. Take the inner product with ff. On one side, fTbi=∑tyit3∑kfkxi,t−k=∑tyit4=Fif^T b_i = \sum_t y_{it}^3 \sum_k f_k x_{i,t-k} = \sum_t y_{it}^4 = F_i, so fTc(f)=∑iFi/Ei2f^T c(f) = \sum_i F_i/E_i^2. On the other side, fTRif=∑tyit2=Eif^T R_i f = \sum_t y_{it}^2 = E_i, so fTA(f)f=∑iFi/Ei2f^T A(f) f = \sum_i F_i/E_i^2. These are equal and positive, so μ=1\mu = 1 and A(f)f=c(f)A(f) f = c(f). □\square

So when the iteration converges to a limit f∗f^\ast and the map is continuous there (it is, since AA is invertible near f∗f^\ast), f∗f^\ast is a stationary point of Φ\Phi: a local maximum, a saddle point or, in principle, a local minimum. The iteration is not proved to increase Φ\Phi at every step, and it is not proved to converge; Wiggins reported that it converges quickly in practice, and the tests and the example on the page measure an increase of Φ\Phi on their data, which is not a theorem. The global maximum of Φ\Phi over ff need not be the inverse of the wavelet: on a finite record the sparsest output can be sparser than the true reflectivity.

Claim 6 (cost). With traces of nn samples, the matrices RiR_i cost O(MnL)O(M n L) once. Each iteration costs O(M(nL+L2))O(M (n L + L^2)) to form A(f)A(f) and c(f)c(f), and O(L3)O(L^3) for the solve by Gaussian elimination, or O(L2)O(L^2) by Levinson recursion, because A(f)A(f) is Toeplitz.

Proof. Line L3 computes MM full convolutions of length n+L−1n + L - 1 with LL taps; line L6 computes LL sums of n+L−1n + L - 1 products per trace; line L5 adds MM matrices of size L×LL \times L. A sum of Toeplitz matrices with scalar weights is Toeplitz, so A(f)A(f) is Toeplitz and symmetric positive definite (Claim 4), and Levinson recursion applies; the code uses the general solver. □\square

Complexity

In the real-RAM model one iteration costs O(mnL)O(m n L) for the convolutions and the cross terms, O(mL2)O(m L^2) to form AA, and O(L3)O(L^3) for a dense solve. AA is a weighted sum of Toeplitz matrices and so is Toeplitz, and the Levinson-Durbin recursion solves it in O(L2)O(L^2). With kk iterations the total is O(k(mnL+L3))O(k (m n L + L^3)), or O(k mnL)O(k\, m n L) with Levinson when L≤nL \le n. The code stores the mm autocorrelation matrices, O(m(n+L2))O(m (n + L^2)) space.

Properties

  • No phase assumption: the filter can be mixed phase, and so can the wavelet (the example above is a measurement).
  • The output is fixed only up to a scale, a sign and a time shift (a theorem: scaling ff or changing its sign does not change Φ\Phi, and moving the taps of ff within the LL taps only shifts the full output, so it does not change Φ\Phi either).
  • Not linear: the filter depends on the data through the fourth powers of the output.
  • One filter for many traces: the sum over traces makes the filter fit the common wavelet and not the details of one trace.
  • Sensitive to noise and to the filter length: a long filter can make a noise burst into a spike (a heuristic, seen in practice).

Variants and improvements

  • Other simplicity measures: Ooe and Ulrych (1979) apply an exponential transformation to the output; Cabrelli (1985) uses a different norm and an algorithm without iteration.
  • Gradient ascent or Newton steps on Φ\Phi, with a line search that makes each step increase Φ\Phi.
  • Sparse deconvolution with an ℓ1\ell_1 penalty on the output, solved by iteratively reweighted least squares or other methods of sparse signal recovery; it fits a known or estimated wavelet and asks for a sparse reflectivity.
  • Phase estimation: maximize a kurtosis-like measure over a single parameter, a constant phase rotation of the output of another deconvolution, in place of a full filter (a heuristic with far fewer unknowns).

When to use it

Use it when the wavelet is not minimum phase, the reflectivity has a few strong contrasts, and there are several traces with the same wavelet. Prefer predictive deconvolution when the reflectivity is close to white and the wavelet is minimum phase, because it is linear in the autocorrelation, fast and well understood.

Pitfalls

  • The sparsest output is not always the true reflectivity. A long filter can concentrate energy in a few samples that are not reflections, and on a short record the output can be spikier than the reflectivity, as in the example.
  • The iteration can stop at a stationary point that is not the global maximum. Try several starting filters, for example spikes at different taps.
  • The time shift of the output is not fixed: compare outputs with a reference only after an alignment.
  • On a single short trace the result varies a lot from record to record; use as many traces as possible with the same wavelet.
  • Noise bursts and spikes in the input are amplified: edit them out first.

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
minimum_entropy_deconvolution.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-entropy-deconvolution/. The authors are listed in prov/FDWZTR.jsonl.
"""Minimum entropy deconvolution (MED) by Wiggins' fixed-point iteration.

The filter f has L taps. For each trace x_i the output is the full
convolution y_i = f * x_i, of length len(x_i) + L - 1. The varimax norm of
an output is V(y) = sum_t y_t^4 / (sum_t y_t^2)^2, a number in [1/T, 1]
that is large for a spiky output. MED looks for the f that makes
sum_i V(y_i) stationary. With E_i = sum y_it^2, F_i = sum y_it^4,
b_ik = sum_t y_it^3 x_i(t - k) and R_i the autocorrelation matrix of x_i,
the gradient is zero exactly when

    sum_i (F_i / E_i^3) R_i f = sum_i b_i / E_i^2,

and the iteration solves this linear system for f with the right-hand side
and the weights taken from the current output.
"""

import math

import imgla as la


def convolve_full(f, x):
    """The full convolution y_t = sum_k f_k x_{t-k}, t = 0..len(x) + len(f) - 2."""
    n = len(x) + len(f) - 1
    y = [0.0] * n
    for k, fk in enumerate(f):
        if fk == 0:
            continue
        for t, xt in enumerate(x):
            y[t + k] += fk * xt
    return y


def varimax(y):
    """V(y) = sum y^4 / (sum y^2)^2 (0 for a zero signal)."""
    e = sum(v * v for v in y)
    if e == 0:
        return 0.0
    return sum(v ** 4 for v in y) / (e * e)


def total_varimax(f, traces):
    """sum_i V(f * x_i)."""
    return sum(varimax(convolve_full(f, x)) for x in traces)


def autocorrelation_matrix(x, length):
    """R[k][j] = sum_t x_{t-j} x_{t-k} = r_|k-j| (full convolution, so R is Toeplitz)."""
    r = [sum(x[t] * x[t + k] for t in range(len(x) - k)) for k in range(length)]
    return [[r[abs(k - j)] for j in range(length)] for k in range(length)]


def cross_term(y, x, length):
    """b_k = sum_t y_t^3 x_{t-k}, k = 0..length - 1."""
    y3 = [v ** 3 for v in y]
    return [sum(y3[t + k] * x[t] for t in range(len(x))) for k in range(length)]


def gradient(f, traces):
    """The gradient of sum_i V(f * x_i) with respect to f."""
    length = len(f)
    g = [0.0] * length
    for x in traces:
        y = convolve_full(f, x)
        e = sum(v * v for v in y)
        fq = sum(v ** 4 for v in y)
        b = cross_term(y, x, length)
        rf = [sum(y[t + k] * x[t] for t in range(len(x))) for k in range(length)]
        for k in range(length):
            g[k] += 4.0 * (b[k] * e - fq * rf[k]) / e ** 3
    return g


def med(traces, length, iters=30, f0=None, tol=1e-12):
    """Run the MED iteration. Returns (f, history of sum_i V)."""
    rs = [autocorrelation_matrix(x, length) for x in traces]
    if f0 is None:  # @line L1
        f = [0.0] * length
        f[length // 2] = 1.0
    else:
        f = list(f0)
    history = [total_varimax(f, traces)]
    for _ in range(iters):  # @line L2
        a = la.zeros(length, length)
        c = [0.0] * length
        for x, r in zip(traces, rs):
            y = convolve_full(f, x)  # @line L3
            e = sum(v * v for v in y)  # @line L4
            fq = sum(v ** 4 for v in y)
            w = fq / e ** 3
            for k in range(length):  # @line L5
                rowa, rowr = a[k], r[k]
                for j in range(length):
                    rowa[j] += w * rowr[j]
            b = cross_term(y, x, length)  # @line L6
            for k in range(length):
                c[k] += b[k] / (e * e)
        new = la.solve(a, c)  # @line L7
        nrm = math.sqrt(sum(v * v for v in new))
        new = [v / nrm for v in new]
        step = min(math.sqrt(sum((p - q) ** 2 for p, q in zip(new, f))),
                   math.sqrt(sum((p + q) ** 2 for p, q in zip(new, f))))
        f = new
        history.append(total_varimax(f, traces))
        if step < tol:
            break
    return f, history  # @line L8
test_minimum_entropy_deconvolution.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-entropy-deconvolution/. The authors are listed in prov/FDWZTR.jsonl.

import math
import random

from minimum_entropy_deconvolution import (
    autocorrelation_matrix,
    convolve_full,
    cross_term,
    gradient,
    med,
    total_varimax,
    varimax,
)


def sparse(rng, n, p=0.05):
    return [rng.gauss(0.0, 1.0) if rng.random() < p else 0.0 for _ in range(n)]


def best_match(y, r, shifts=range(-20, 40)):
    """The largest normalized cross-correlation of y with r over the shifts (sign ignored)."""
    den = math.sqrt(sum(v * v for v in y) * sum(v * v for v in r))
    best = 0.0
    for s in shifts:
        num = sum(y[t + s] * r[t] for t in range(len(r)) if 0 <= t + s < len(y))
        best = max(best, abs(num) / den)
    return best


def test_varimax_bounds_and_extremes():
    rng = random.Random(1)
    for _ in range(100):
        n = rng.randint(1, 40)
        y = [rng.gauss(0.0, 1.0) for _ in range(n)]
        v = varimax(y)
        assert 1.0 / n - 1e-12 <= v <= 1.0 + 1e-12
    assert varimax([0.0, 0.0, -2.5, 0.0]) == 1.0
    assert abs(varimax([0.7] * 25) - 1.0 / 25) < 1e-15
    assert varimax([0.0] * 5) == 0.0


def test_varimax_is_scale_invariant():
    rng = random.Random(2)
    x = [rng.gauss(0.0, 1.0) for _ in range(50)]
    f = [rng.gauss(0.0, 1.0) for _ in range(6)]
    a = total_varimax(f, [x])
    b = total_varimax([-4.0 * v for v in f], [x])
    assert abs(a - b) < 1e-12


def test_autocorrelation_matrix_matches_the_definition():
    rng = random.Random(3)
    x = [rng.gauss(0.0, 1.0) for _ in range(20)]
    length = 5
    r = autocorrelation_matrix(x, length)
    for k in range(length):
        for j in range(length):
            direct = sum(x[t - j] * x[t - k] for t in range(len(x) + length)
                         if 0 <= t - j < len(x) and 0 <= t - k < len(x))
            assert abs(r[k][j] - direct) < 1e-12


def test_gradient_matches_finite_differences():
    rng = random.Random(4)
    traces = [[rng.gauss(0.0, 1.0) for _ in range(40)] for _ in range(2)]
    f = [rng.gauss(0.0, 1.0) for _ in range(5)]
    g = gradient(f, traces)
    h = 1e-6
    for k in range(len(f)):
        fp = list(f)
        fm = list(f)
        fp[k] += h
        fm[k] -= h
        fd = (total_varimax(fp, traces) - total_varimax(fm, traces)) / (2 * h)
        assert abs(fd - g[k]) < 1e-6 * max(1.0, abs(g[k]))


def test_fixed_point_is_a_stationary_point():
    rng = random.Random(5)
    refl = sparse(rng, 300)
    x = convolve_full([1.0, -0.6, 0.2], refl)
    f, hist = med([x], 15, iters=60)
    g = gradient(f, [x])
    assert max(abs(v) for v in g) < 1e-8
    assert hist[-1] > hist[0]


def test_recovers_a_mixed_phase_wavelet():
    # The wavelet (0.3, -0.8, 1.0, -0.4) is not minimum phase; MED needs no phase assumption.
    rng = random.Random(6)
    refl = sparse(rng, 300)
    x = convolve_full([0.3, -0.8, 1.0, -0.4], refl)
    f, _ = med([x], 15, iters=40)
    y = convolve_full(f, x)
    assert varimax(y) > 2.0 * varimax(x)
    assert best_match(y, refl) > 0.95


def test_one_filter_for_several_traces():
    rng = random.Random(7)
    w = [0.4, 1.0, -0.5]
    refls = [sparse(rng, 200) for _ in range(3)]
    traces = [convolve_full(w, r) for r in refls]
    f, hist = med(traces, 13, iters=40)
    for x, r in zip(traces, refls):
        assert best_match(convolve_full(f, x), r) > 0.95
    assert hist[-1] > hist[0]


def test_cross_term_definition():
    rng = random.Random(8)
    x = [rng.gauss(0.0, 1.0) for _ in range(15)]
    f = [rng.gauss(0.0, 1.0) for _ in range(4)]
    y = convolve_full(f, x)
    b = cross_term(y, x, 4)
    for k in range(4):
        direct = sum(y[t] ** 3 * x[t - k] for t in range(len(y)) if 0 <= t - k < len(x))
        assert abs(b[k] - direct) < 1e-12

History

Wiggins (1978) named the method minimum entropy deconvolution, with the idea that a spiky output is simple and has low entropy, and used the varimax norm, a measure taken from factor analysis, to score the output. He maximized the sum of the norms over several traces with an iteration that solves a Toeplitz system at each step. Ooe and Ulrych (1979) changed the measure with an exponential transformation, and Cabrelli (1985) proposed another simplicity norm with an algorithm that needs no iteration.

References

  1. Ralph A. Wiggins, Minimum entropy deconvolution, Geoexploration 16(1-2), 1978, 21 to 35, the varimax norm as a measure of simplicity of the output, and the iterative solution for the filter that maximizes it over several traces
  2. M. Ooe and T. J. Ulrych, Minimum entropy deconvolution with an exponential transformation, Geophysical Prospecting 27(2), 1979, 458 to 473, a change of the simplicity measure by an exponential transformation of the output
  3. Carlos A. Cabrelli, Minimum entropy deconvolution and simplicity, a noniterative algorithm, Geophysics 50(3), 1985, 394 to 413, a different simplicity measure and an algorithm without iteration

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