Algorithm Search⌘K

Algorithmadvanced

Finite-difference migration

Also called 15-degree migration, Claerbout migration.

Downward continue the wavefield with a finite difference solver of a one-way paraxial wave equation, which handles lateral velocity changes.

Time
O(z t x + x t log t) totalO(x) per_step
Space
O(t x + z x) extra
Where
t = the number of time samples; x = the number of traces; z = the number of depth steps
Properties
deterministiclateral velocityunconditionally stable
Origin
Jon F. Claerbout, Stephen M. Doherty, 1972

Finite-difference migration continues the recorded wavefield down into the ground with a finite-difference solver of a one-way paraxial wave equation. For each frequency it replaces the square root 1−(v′kx/ω)2\sqrt{1 - (v' k_x/\omega)^2} of the exact one-way equation by its Taylor polynomial 1−(v′kx/ω)2/21 - (v' k_x/\omega)^2/2, which gives the 15-degree equation ∂zP=i(ω/v′)P+i(v′/(2ω))∂x2P\partial_z P = i(\omega/v')P + i(v'/(2\omega))\partial_x^2 P. Each depth step applies a thin lens eiωΔz/v′e^{i\omega\Delta z/v'} and one Crank-Nicolson step of the second term, a tridiagonal system solved by the Thomas algorithm in O(nx)O(n_x). Because the velocity enters point by point, the method handles lateral velocity changes. The step is unitary for every Δz\Delta z (a theorem), and the error grows with the propagation angle: 0.06 percent at 15 degrees and 6 percent at 45 degrees (a theorem for plane waves in constant velocity).

In plain words

The method moves the recorded wave down into the ground one depth step at a time, one frequency at a time. Each step has two parts. First every point is delayed by the time the wave needs to cross the step at the local speed, as if it went straight down. Then a small correction lets the wave spread sideways, which is how a slanted wave moves. The correction links each point only to its two neighbors, so it is a short chain of equations that a simple elimination solves quickly. The method is cheap and allows the speed to change from point to point, but the sideways correction is an approximation that is good only for waves close to vertical.

The problem

Given a zero-offset section d(t,x)d(t, x) and a velocity v(x,z)v(x, z) on the image grid (vi[j]v_i[j] for the layer iΔz≤z<(i+1)Δzi\Delta z \le z < (i + 1)\Delta z at xjx_j), find the image m(x,z)m(x, z). This is seismic migration in the exploding reflector model, with the half velocity v′=v/2v' = v/2.

The algorithm

The time transform is U(ω)=∑tu(t)e−iωtU(\omega) = \sum_t u(t)e^{-i\omega t}, and T=tridiag⁡(1,−2,1)T = \operatorname{tridiag}(1, -2, 1) is the second difference along xx with P=0P = 0 outside the grid. The Crank-Nicolson step of ∂zP=i(v′/(2ω))∂x2P\partial_z P = i(v'/(2\omega))\partial_x^2 P is (I−i2BT)Pnew=(I+i2BT)P(I - \frac{i}{2}BT)P_{\text{new}} = (I + \frac{i}{2}BT)P with B=diag⁡(bj)B = \operatorname{diag}(b_j).

  1. FINITE-DIFFERENCE-MIGRATION(d, Δt, Δx, Δz, v) ▷ v[i][j]: velocity of layer i at x_j
  2. 1P_k ← DFT in time of every trace, for every frequency index k
  3. 2for every frequency ω = ω_k with 0 < ω_k < the Nyquist frequency do ▷ p ← P_k
  4. 3for i ← 0 to n_z - 1 do
  5. 4image[i] ← image[i] + (2 / n_t) Re p
  6. 5p[j] ← p[j] · exp(i ω Δz / v'[j]) for every j ▷ v' = v[i] / 2, the thin lens
  7. 6b[j] ← v'[j] Δz / (2 ω Δx²) for every j
  8. 7p ← solution of (I - (i/2) B T) p_new = (I + (i/2) B T) p, by the Thomas algorithm
  9. 8return image

Line L1 transforms every trace in time once. For one frequency, pp holds the field along xx at the current depth. Line L4 adds this frequency to the image row; the positive frequencies are enough, because the negative ones are their complex conjugates. Line L5 is the thin lens, the exact step for a vertical wave in the local velocity. Lines L6 and L7 are the diffraction term: one Crank-Nicolson step, which is a tridiagonal system with the diagonal 1+ibj1 + i b_j and the off-diagonal entries −i2bj-\frac{i}{2}b_j.

Example

The angle error by hand. For a plane wave at the angle θ\theta, the exact one-way equation gives kz=(ω/v′)cos⁡θk_z = (\omega/v')\cos\theta and the 15-degree equation gives (ω/v′)(1−sin⁡2θ/2)(\omega/v')(1 - \sin^2\theta/2). At 15 degrees: cos⁡15°=0.965926\cos 15° = 0.965926 against 1−0.066987/2=0.9665061 - 0.066987/2 = 0.966506, a relative error of 6.0×10−46.0 \times 10^{-4}. At 45 degrees: 0.7071070.707107 against 0.750.75, a relative error of 0.0610.061. The 15-degree equation always gives a kzk_z that is too large. A dipping event with the wavenumbers (kx,kz)(k_x, k_z) appears in the image with the dip arctan⁡(kx/kz)\arctan(k_x/k_z), so steep dips come out too small: they are undermigrated.

One coefficient by hand. With f=25f = 25 Hz (ω=157.08\omega = 157.08 rad/s), v′=1500v' = 1500 m/s, Δz=6\Delta z = 6 m and Δx=10\Delta x = 10 m, b=1500⋅6/(2⋅157.08⋅100)=0.286b = 1500 \cdot 6/(2 \cdot 157.08 \cdot 100) = 0.286. The tridiagonal matrix has the diagonal 1+0.286i1 + 0.286i (modulus 1.040) and off-diagonal entries of modulus 0.143, so every row is strictly diagonally dominant.

Tests. In constant velocity 3000 m/s with 32 traces at 10 m, 64 samples at 4 ms and Δz=6\Delta z = 6 m, a point diffractor at row 32 and column 16 focuses within one row of its place, at column 16. A flat event at 0.2 s goes to row 50 (300 m) in the middle columns, because for kx=0k_x = 0 the scheme is the exact phase shift (measurements on these cases).

Correctness

The full proof is in proofs/correctness.md.

  • The 15-degree relation (theorem). kz15k_z^{15} is the Taylor polynomial of degree 2 of kzk_z in sin⁡θ\sin\theta, and kz≤kz15k_z \le k_z^{15} for all angles.
  • The Thomas algorithm succeeds (theorem). Every row of I−i2BTI - \frac{i}{2}BT is strictly diagonally dominant, since 1+bj2>bj\sqrt{1 + b_j^2} > b_j, so no pivot is zero and no pivoting is needed.
  • Unitary step (theorem). The map of line L7 keeps the norm ∑j∣pj∣2/bj\sum_j |p_j|^2/b_j. For constant bb it multiplies the sine mode with the eigenvalue λ\lambda of TT by e2iarctan⁡(bλ/2)e^{2i\arctan(b\lambda/2)} and keeps the plain norm.
  • What the code computes (theorem). Line L8 returns (2/nt)Re⁡∑0<k<nt/2pk(i)(2/n_t)\operatorname{Re}\sum_{0 < k < n_t/2} p_k^{(i)}, where pk(i)p_k^{(i)} is the trace spectrum at index kk after ii lens and diffraction steps.
  • Consistency (theorem). In constant velocity one step multiplies a sine mode by eikzCNΔze^{i k_z^{\text{CN}}\Delta z} with kzCN−kz15=O(Δx2+Δz2)k_z^{\text{CN}} - k_z^{15} = O(\Delta x^2 + \Delta z^2) for fixed ω\omega and kxk_x.
Proof: Correctness of finite-difference migrationfull

Setting. The model is the exploding reflector model with v′=v/2v' = v/2. For one frequency ω>0\omega > 0 the one-way equation of the method is the 15-degree equation

∂P∂z=i ωv′ P+i v′2ω ∂2P∂x2.\frac{\partial P}{\partial z} = i\,\frac{\omega}{v'}\,P + i\,\frac{v'}{2\omega}\,\frac{\partial^2 P}{\partial x^2}.

For a plane wave eikxxe^{i k_x x} in constant v′v' it gives kz15=ω/v′−v′kx2/(2ω)k_z^{15} = \omega/v' - v' k_x^2/(2\omega), while the exact one-way equation gives kz=(ω/v′)1−a2k_z = (\omega/v')\sqrt{1 - a^2} with a=v′kx/ω=sin⁡θa = v' k_x/\omega = \sin\theta, the sine of the propagation angle. The grid has nxn_x points, T=tridiag⁡(1,−2,1)T = \operatorname{tridiag}(1, -2, 1) with P=0P = 0 outside the grid, and B=diag⁡(bj)B = \operatorname{diag}(b_j) with bj=vj′Δz/(2ωΔx2)>0b_j = v'_j \Delta z/(2\omega\Delta x^2) > 0 (line L6).

Lemma 1 (the 15-degree relation). kz15k_z^{15} is the Taylor polynomial of degree 2 in aa of kzk_z, and kz≤kz15k_z \le k_z^{15} for all ∣a∣≤1|a| \le 1. The relative error ((1−a2/2)−1−a2)/1−a2\big((1 - a^2/2) - \sqrt{1 - a^2}\big)/\sqrt{1 - a^2} is 6.0×10−46.0 \times 10^{-4} at θ=15°\theta = 15° and 0.0610.061 at θ=45°\theta = 45°.

Proof. 1−a2=1−a2/2−a4/8−⋯\sqrt{1 - a^2} = 1 - a^2/2 - a^4/8 - \cdots. Also (1−a2/2)2=1−a2+a4/4≥1−a2(1 - a^2/2)^2 = 1 - a^2 + a^4/4 \ge 1 - a^2, and 1−a2/2>01 - a^2/2 > 0, so 1−a2/2≥1−a21 - a^2/2 \ge \sqrt{1 - a^2}. The numbers: cos⁡15°=0.965926\cos 15° = 0.965926 against 1−sin⁡215°/2=0.9665061 - \sin^2 15°/2 = 0.966506; cos⁡45°=0.707107\cos 45° = 0.707107 against 0.750.75. □\square

Lemma 2 (the Thomas algorithm succeeds). For every b∈(0,∞)nxb \in (0, \infty)^{n_x} the matrix I−i2BTI - \frac{i}{2}BT of line L7 has row jj with the diagonal 1+ibj1 + i b_j and the off-diagonal entries −i2bj-\frac{i}{2}b_j. The elimination in thomas_solve never divides by zero, and it returns the exact solution in exact arithmetic.

Proof. Row jj is strictly diagonally dominant: ∣1+ibj∣=1+bj2>bj≥∣ℓj∣+∣uj∣|1 + i b_j| = \sqrt{1 + b_j^2} > b_j \ge |\ell_j| + |u_j|, where ℓj,uj\ell_j, u_j are the off-diagonal entries (∣ℓj∣,∣uj∣≤bj/2|\ell_j|, |u_j| \le b_j/2). We show by induction that the pivots mjm_j satisfy ∣mj∣>∣uj∣|m_j| > |u_j|, so mj≠0m_j \ne 0 and ∣cj∣=∣uj/mj∣<1|c_j| = |u_j/m_j| < 1. For j=0j = 0, m0=1+ib0m_0 = 1 + i b_0 and ∣m0∣>∣u0∣|m_0| > |u_0|. For j≥1j \ge 1, ∣mj∣=∣1+ibj−ℓjcj−1∣≥∣1+ibj∣−∣ℓj∣>∣uj∣|m_j| = |1 + i b_j - \ell_j c_{j-1}| \ge |1 + i b_j| - |\ell_j| > |u_j|, by ∣cj−1∣<1|c_{j-1}| < 1 and the dominance. The forward pass is the factorization of the matrix into a lower bidiagonal factor with the pivots mjm_j and a unit upper bidiagonal factor with the entries cjc_j; the forward and backward passes solve the two triangular systems. □\square

Lemma 3 (the diffraction step is unitary in a weighted norm). Let C=(I−i2BT)−1(I+i2BT)C = (I - \frac{i}{2}BT)^{-1}(I + \frac{i}{2}BT), the map of line L7. Then CC keeps the norm ∥p∥B2=∑j∣pj∣2/bj\|p\|_B^2 = \sum_j |p_j|^2/b_j. If all bj=bb_j = b, CC multiplies the sine mode ψm[j]=sin⁡(mπ(j+1)/(nx+1))\psi_m[j] = \sin(m\pi(j+1)/(n_x+1)) by e2iarctan⁡(bλm/2)e^{2i\arctan(b\lambda_m/2)}, with λm=−4sin⁡2(mπ/(2(nx+1)))\lambda_m = -4\sin^2\big(m\pi/(2(n_x+1))\big), and keeps the plain norm.

Proof. BTBT is self-adjoint in the inner product ⟨p,q⟩B=∑jpˉjqj/bj\langle p, q\rangle_B = \sum_j \bar{p}_j q_j/b_j, because B−1(BT)=TB^{-1}(BT) = T is real symmetric. So BT=VΛV−1BT = V\Lambda V^{-1} with real Λ\Lambda and VV unitary for ⟨⋅,⋅⟩B\langle\cdot,\cdot\rangle_B, and C=V diag⁡((1+iλ/2)/(1−iλ/2))V−1C = V\,\operatorname{diag}\big((1 + i\lambda/2)/(1 - i\lambda/2)\big)V^{-1}. Each factor has modulus 1. For constant bb, Tψm=λmψmT\psi_m = \lambda_m \psi_m (the Dirichlet eigenvectors of TT), and (1+iy)/(1−iy)=e2iarctan⁡y(1 + i y)/(1 - i y) = e^{2i\arctan y} with y=bλm/2y = b\lambda_m/2. □\square

Theorem 1 (what the code computes). Let Lω,iL_{\omega, i} be the thin lens of line L5 (entry jj times eiωΔz/vi,j′e^{i\omega\Delta z/v'_{i,j}}) and Cω,iC_{\omega, i} the step of line L7 for layer ii. With pk(0)p_k^{(0)} the DFT of the traces at index kk (line L1) and pk(i)=Cωk,i−1Lωk,i−1⋯Cωk,0Lωk,0 pk(0)p_k^{(i)} = C_{\omega_k, i-1}L_{\omega_k, i-1}\cdots C_{\omega_k, 0}L_{\omega_k, 0}\, p_k^{(0)}, line L8 returns

m[i][j]=2ntRe⁡∑0<k<nt/2pk(i)[j].m[i][j] = \frac{2}{n_t}\operatorname{Re}\sum_{0 < k < n_t/2} p_k^{(i)}[j].

The algorithm stops after nz⌊(nt−1)/2⌋n_z \lfloor (n_t - 1)/2\rfloor tridiagonal solves.

Proof. As in Theorem 1 of the proof of split-step Fourier migration: line L2 visits 0<k<nt/20 < k < n_t/2, the array pp equals pk(i)p_k^{(i)} at the start of pass ii of line L3, line L4 adds the term to row ii, and lines L5 to L7 apply LL and then CC. Each solve succeeds by Lemma 2. By Lemma 1 of that proof (the positive frequencies are enough), the sum is the field at t=0t = 0 of the continued data without the frequency 0 and the Nyquist frequency, provided the negative frequencies are continued by the conjugate maps. ■\blacksquare

Theorem 2 (consistency for constant velocity). Let v′v' be constant. Then LL is the scalar eiωΔz/v′e^{i\omega\Delta z/v'}, so it commutes with CC, and one depth step multiplies the sine mode ψm\psi_m by eikzCNΔze^{i k_z^{\mathrm{CN}}\Delta z} with

kzCN=ωv′+2Δzarctan⁡(bλ2),λ=−4sin⁡2(kxΔx2),kx=mπ(nx+1)Δx.k_z^{\mathrm{CN}} = \frac{\omega}{v'} + \frac{2}{\Delta z}\arctan\Big(\frac{b\lambda}{2}\Big), \qquad \lambda = -4\sin^2\Big(\frac{k_x\Delta x}{2}\Big), \quad k_x = \frac{m\pi}{(n_x + 1)\Delta x}.

For fixed ω\omega and kxk_x, kzCN−kz15=O(Δx2)+O(Δz2)k_z^{\mathrm{CN}} - k_z^{15} = O(\Delta x^2) + O(\Delta z^2) as Δx,Δz→0\Delta x, \Delta z \to 0.

Proof. The mode factor is Lemma 3, and λm=−4sin⁡2(kxΔx/2)\lambda_m = -4\sin^2(k_x\Delta x/2) with this kxk_x. Put y=bλ/2y = b\lambda/2. Since λ=−kx2Δx2 (1+O(kx2Δx2))\lambda = -k_x^2\Delta x^2\,(1 + O(k_x^2\Delta x^2)), y=−v′kx2Δz4ω (1+O(Δx2))y = -\frac{v' k_x^2\Delta z}{4\omega}\,(1 + O(\Delta x^2)), which is O(Δz)O(\Delta z). Then 2Δzarctan⁡y=2yΔz+O(y3/Δz)=−v′kx22ω(1+O(Δx2))+O(Δz2)\frac{2}{\Delta z}\arctan y = \frac{2y}{\Delta z} + O(y^3/\Delta z) = -\frac{v' k_x^2}{2\omega}(1 + O(\Delta x^2)) + O(\Delta z^2). Add ω/v′\omega/v'. □\square

Together, Lemma 1 and Theorem 2 give the error of the method for constant velocity: the 15-degree error, which is small for angles up to about 15 degrees and grows as a4a^4, and the grid error of order Δx2+Δz2\Delta x^2 + \Delta z^2. The tests measure both. For a velocity that changes along xx the method is a splitting of the 15-degree equation into the lens term and the diffraction term; its splitting error is not bounded here (a heuristic).

Stability. LL has modulus 1 in each entry and CC keeps ∥⋅∥B\|\cdot\|_B (Lemma 3). If the velocity does not change with depth, BB is the same in every step, so ∥pk(i)∥B=∥pk(0)∥B\|p_k^{(i)}\|_B = \|p_k^{(0)}\|_B for all ii, and the plain norm is bounded by max⁡jbj/min⁡jbj\sqrt{\max_j b_j/\min_j b_j} times its first value. There is no step-size condition such as a CFL condition, because the scheme is implicit.

Complexity

  • Real-ram. Line L1 costs O(nxntlog⁡nt)O(n_x n_t \log n_t) with an FFT. Each depth step for one frequency costs O(nx)O(n_x): the lens, the right-hand side and one Thomas solve. With about nt/2n_t/2 frequencies and nzn_z steps the total is O(nzntnx+nxntlog⁡nt)O(n_z n_t n_x + n_x n_t \log n_t).
  • Against split step. Split-step Fourier migration needs two FFTs per step, O(nxlog⁡nx)O(n_x \log n_x), so the finite-difference step is cheaper by a factor log⁡nx\log n_x, at the price of a smaller angle range.
  • Space. One complex vector per frequency, the work arrays of the solver, and the image.

Properties

  • Lateral velocity. Both the lens and the coefficients bjb_j use the local velocity, so lateral changes need no extra work.
  • Unconditionally stable. The Crank-Nicolson step is unitary for every Δz\Delta z, so there is no CFL condition, unlike the explicit time stepping of reverse-time migration.
  • Angle limit. Accurate for waves within about 15 degrees of vertical; at 45 degrees the vertical wavenumber is 6 percent too large.
  • Numerical dispersion. The second difference replaces −kx2-k_x^2 by −4sin⁡2(kxΔx/2)/Δx2-4\sin^2(k_x\Delta x/2)/\Delta x^2, which reduces the effective angle further at coarse Δx\Delta x.
  • Edge reflections. The Dirichlet ends (P=0P = 0 outside the grid) reflect waves that reach the sides; production codes add absorbing boundary terms or tapers.

Variants and improvements

  • 45-degree and higher-order equations. Replace the Taylor polynomial by a continued-fraction (Pade) approximation of the square root. The 45-degree equation has a rational symbol and still leads to tridiagonal systems per step.
  • Splitting in 3D. Apply the diffraction term along xx and then along yy, each with tridiagonal solves (operator splitting). This adds an error that depends on the azimuth, which correction terms reduce.
  • Fourier finite difference. Combine a phase shift with a reference velocity and a finite-difference correction for the difference, which widens the angle range in lateral velocity.
  • Time-domain form. Claerbout's original schemes worked in the time and space domain with a retarded time; the frequency-domain form here is simpler for variable velocity.
  • Implicit weights above one half. Using a weight a little above the Crank-Nicolson value 1/21/2 on the new field damps high-wavenumber noise, at the cost of a step that is no longer unitary (a heuristic trade).

When to use it

Use finite-difference migration when the velocity changes laterally and the dips are moderate, or when a cheap per-step cost matters. It is the classical method of the 1970s. For steep dips use the 45-degree or higher-order equations, split-step Fourier migration with corrections, or reverse-time migration, which has no angle limit. For velocity that changes only with depth, phase-shift migration is exact.

Pitfalls

  • An explicit step. Solving the diffraction term with forward Euler instead of line L7 is unstable for every Δz\Delta z, because the operator is purely imaginary. Use the implicit Crank-Nicolson step of line L7.
  • The full velocity. Using vv instead of v′=v/2v' = v/2 in lines L5 and L6 doubles every depth. Zero-offset data need the half velocity.
  • Pivoting in the solver. The Thomas algorithm needs no pivoting here, because the matrix is strictly diagonally dominant; a general solver with O(nx3)O(n_x^3) cost throws away the tridiagonal structure.
  • Steep events. Trusting the image of steep dips: at 45 degrees the vertical wavenumber is 6 percent too large, so the imaged dip is too small. This is a systematic error, not noise.

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.

finite_difference_migration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-difference-migration/. The authors are listed in prov/BK5R80.jsonl.
"""Finite-difference (Claerbout) migration of a zero-offset section, 15 degree equation.

Conventions (the imaging and inverse problems pages):
- data[k][j] is the zero-offset sample at the two-way time t = k * dt and the
  surface position x = j * dx. vel[i][j] is the velocity (m/s) between the
  depths i dz and (i + 1) dz at x = j dx. image[i][j] is the image at depth i dz.
- U(omega) = sum u(t) exp(-i omega t). Exploding reflector model: the field
  travels with v' = v / 2. Downward continuation by dz multiplies a plane wave
  by exp(+i kz dz), kz = (omega / v') sqrt(1 - (v' kx / omega)^2).
- The 15 degree equation replaces the square root by 1 - (v' kx / omega)^2 / 2:
      dP/dz = i (omega / v') P + i (v' / (2 omega)) d2P/dx2.
  Each depth step applies the thin lens exp(i omega dz / v') and then one
  Crank-Nicolson step of the second term:
      (I - i (b / 2) T) P_new = (I + i (b / 2) T) P,  b = v' dz / (2 omega dx^2),
  with T = tridiag(1, -2, 1) and P = 0 outside the grid (Dirichlet ends).
- Only 0 < omega < the Nyquist frequency are continued; the image is
  (2 / nt) Re of the sum over these frequencies.

Cost: O(nt log nt) per trace for the time FFT, then O(nx) per frequency and
depth step (one tridiagonal solve), so O(nz * nt * nx) in total.
"""

import cmath
import math

from imgkit import dft


def thomas_solve(lower, diag, upper, rhs):
    """Solve a tridiagonal system with the Thomas algorithm (no pivoting).

    lower[j] multiplies x[j - 1] in row j (lower[0] is unused), upper[j]
    multiplies x[j + 1] (upper[-1] is unused). Works for complex entries. It is
    stable for strictly diagonally dominant matrices, which is the case here.
    """
    n = len(diag)
    c = [0j] * n
    d = [0j] * n
    c[0] = upper[0] / diag[0]
    d[0] = rhs[0] / diag[0]
    for j in range(1, n):
        m = diag[j] - lower[j] * c[j - 1]
        c[j] = upper[j] / m if j < n - 1 else 0j
        d[j] = (rhs[j] - lower[j] * d[j - 1]) / m
    x = [0j] * n
    x[n - 1] = d[n - 1]
    for j in range(n - 2, -1, -1):
        x[j] = d[j] - c[j] * x[j + 1]
    return x


def apply_t(p):
    """(T p)_j = p_{j-1} - 2 p_j + p_{j+1}, with p = 0 outside the grid."""
    n = len(p)
    return [(p[j - 1] if j > 0 else 0j) - 2.0 * p[j] + (p[j + 1] if j < n - 1 else 0j) for j in range(n)]


def diffraction_step(p, b):
    """One Crank-Nicolson step (I - i (b / 2) T) p_new = (I + i (b / 2) T) p.

    b is a list of the values b_j = v'_j dz / (2 omega dx^2), one per point.
    """
    n = len(p)
    tp = apply_t(p)
    rhs = [p[j] + 0.5j * b[j] * tp[j] for j in range(n)]
    off = [-0.5j * b[j] for j in range(n)]
    diag = [1.0 + 1j * b[j] for j in range(n)]
    return thomas_solve(off, diag, off, rhs)


def finite_difference_migration(data, dt, dx, dz, vel):
    """Migrate a zero-offset section with the 15 degree finite-difference method.

    data: nt x nx real samples; vel: nz x nx velocities. Returns the nz x nx
    image. Precondition: dt, dx, dz > 0 and every velocity > 0.
    """
    nt, nx = len(data), len(data[0])
    nz = len(vel)
    spectra = [dft([data[k][j] for k in range(nt)]) for j in range(nx)]  # @line L1
    image = [[0.0] * nx for _ in range(nz)]
    for k in range(1, (nt + 1) // 2):  # @line L2
        omega = 2.0 * math.pi * k / (nt * dt)
        p = [spectra[j][k] for j in range(nx)]
        for i in range(nz):  # @line L3
            for j in range(nx):
                image[i][j] += 2.0 * p[j].real / nt  # @line L4
            vhalf = [v / 2.0 for v in vel[i]]
            p = [p[j] * cmath.exp(1j * omega * dz / vhalf[j]) for j in range(nx)]  # @line L5
            b = [vh * dz / (2.0 * omega * dx * dx) for vh in vhalf]  # @line L6
            p = diffraction_step(p, b)  # @line L7
    return image  # @line L8


def kz_15_degree(omega, kx, vhalf):
    """The vertical wavenumber of the continuous 15 degree equation."""
    return omega / vhalf - vhalf * kx * kx / (2.0 * omega)


def kz_crank_nicolson(omega, kx, vhalf, dx, dz):
    """The phase per unit depth of one discrete step (thin lens plus Crank-Nicolson) for exp(i kx x).

    The eigenvalue of T for this wave is lam = -4 sin^2(kx dx / 2), and the
    Crank-Nicolson factor is exp(2 i atan(b lam / 2)).
    """
    b = vhalf * dz / (2.0 * omega * dx * dx)
    lam = -4.0 * math.sin(kx * dx / 2.0) ** 2
    return omega / vhalf + 2.0 * math.atan(b * lam / 2.0) / dz
imgkit.py 322 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/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
test_finite_difference_migration.py 105 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-difference-migration/. The authors are listed in prov/BK5R80.jsonl.
import math
import random
import unittest

from finite_difference_migration import (
    apply_t,
    diffraction_step,
    finite_difference_migration,
    kz_15_degree,
    kz_crank_nicolson,
    thomas_solve,
)

NT, NX, DT, DX = 64, 32, 0.004, 10.0
VEL = 3000.0
DZ = VEL * DT / 2.0


def ricker(t, f0):
    a = (math.pi * f0 * t) ** 2
    return (1.0 - 2.0 * a) * math.exp(-a)


def diffractor(x0, z0):
    out = [[0.0] * NX for _ in range(NT)]
    for j in range(NX):
        t0 = 2.0 * math.hypot(z0, j * DX - x0) / VEL
        for k in range(NT):
            out[k][j] = ricker(k * DT - t0, 25.0)
    return out


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


class TestFiniteDifferenceMigration(unittest.TestCase):
    def test_thomas_solve(self):
        rng = random.Random(11)
        n = 9
        lower = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
        upper = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
        diag = [complex(5.0 + rng.random(), rng.uniform(-1, 1)) for _ in range(n)]
        rhs = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
        x = thomas_solve(lower, diag, upper, rhs)
        for j in range(n):
            s = diag[j] * x[j]
            if j > 0:
                s += lower[j] * x[j - 1]
            if j < n - 1:
                s += upper[j] * x[j + 1]
            self.assertLess(abs(s - rhs[j]), 1e-12)

    def test_step_keeps_the_norm(self):
        # For a constant b the step is a Cayley transform of a real symmetric
        # matrix, so it is unitary.
        rng = random.Random(5)
        p = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(20)]
        q = diffraction_step(p, [0.7] * 20)
        self.assertAlmostEqual(norm(q), norm(p), delta=1e-12)

    def test_step_solves_the_scheme(self):
        rng = random.Random(6)
        p = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(12)]
        b = [rng.uniform(0.1, 2.0) for _ in range(12)]
        q = diffraction_step(p, b)
        tp, tq = apply_t(p), apply_t(q)
        for j in range(12):
            self.assertLess(abs((q[j] - 0.5j * b[j] * tq[j]) - (p[j] + 0.5j * b[j] * tp[j])), 1e-12)

    def test_point_diffractor_focuses(self):
        img = finite_difference_migration(diffractor(160.0, 192.0), DT, DX, DZ, [[VEL] * NX for _ in range(48)])
        best = max((img[i][j], i, j) for i in range(48) for j in range(NX))
        self.assertLessEqual(abs(best[1] - 32), 1)
        self.assertEqual(best[2], 16)

    def test_flat_event_is_a_time_to_depth_map(self):
        # For kx = 0 the scheme is the exact phase shift: a flat event at
        # t0 = 0.2 s goes to z = v' t0 = 300 m, row 50. The Dirichlet ends
        # disturb the columns near the edges, so check the middle ones.
        data = [[ricker(k * DT - 0.2, 25.0)] * NX for k in range(NT)]
        img = finite_difference_migration(data, DT, DX, DZ, [[VEL] * NX for _ in range(60)])
        for j in range(12, 20):
            self.assertEqual(max(range(60), key=lambda i: img[i][j]), 50)

    def test_dispersion(self):
        w, vh = 2.0 * math.pi * 25.0, 1500.0
        self.assertAlmostEqual(kz_crank_nicolson(w, 0.0, vh, DX, DZ), w / vh, places=12)
        self.assertAlmostEqual(kz_15_degree(w, 0.0, vh), w / vh, places=12)
        # The 15 degree relation is the second-order Taylor polynomial of the
        # exact one, and the discrete one tends to it for small steps.
        kx = 0.1 * w / vh
        exact = math.sqrt((w / vh) ** 2 - kx * kx)
        self.assertLess(abs(kz_15_degree(w, kx, vh) - exact), 1e-4 * exact)
        self.assertLess(abs(kz_crank_nicolson(w, kx, vh, 0.1, 0.1) - kz_15_degree(w, kx, vh)), 1e-4 * exact)
        # The error grows with the angle.
        kx2 = 0.7 * w / vh
        exact2 = math.sqrt((w / vh) ** 2 - kx2 * kx2)
        self.assertGreater(abs(kz_15_degree(w, kx2, vh) - exact2), 0.05 * exact2)


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

History

Claerbout (1971) proposed migration by finite differences of a one-way wave equation, and Claerbout and Doherty (1972) gave the downward continuation of zero-offset data with the 15-degree equation. The method was the first wave-equation migration in industry use, and Claerbout's book (1985) explained it with the Crank-Nicolson scheme and its dispersion. The angle limit motivated the 45-degree and higher-order equations, and later the phase-shift, Stolt and split-step methods in the frequency-wavenumber domain.

References

  1. Jon F. Claerbout and Stephen M. Doherty, Downward continuation of moveout-corrected seismograms, Geophysics 37(5), 1972, 741 to 768, the finite-difference downward continuation of the 15-degree equation
  2. Jon F. Claerbout, Toward a unified theory of reflector mapping, Geophysics 36(3), 1971, 467 to 481, the one-way wave equation and the imaging principle
  3. Jon F. Claerbout, Imaging the Earth's Interior, Blackwell Scientific, 1985, the chapters on the 15-degree equation, its Crank-Nicolson solution and its dispersion
  4. Oz Yilmaz, Seismic Data Analysis, Society of Exploration Geophysicists, 2001, Chapter 4 (migration), finite-difference migration and its angle limits

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_step
  • 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