Algorithm Search⌘K

Algorithmcore

Kirchhoff migration

Also called diffraction summation migration.

Image each subsurface point by a weighted sum of the data along the diffraction traveltime curve of that point.

Time
O(x t log t + z x a) totalO(x t log t) filterO(z x a) sum
Space
O(x t + z x) extra
Where
a = the number of traces in the aperture; t = the number of time samples; x = the number of traces (and of image columns); z = the number of image depths
Properties
deterministichigh frequency approximationirregular geometrylinear in datatarget oriented
Origin
William A. Schneider, 1978

Kirchhoff migration builds the image one point at a time. For each image point it sums the data along the diffraction curve of that point, the curve of times at which a small scatterer at the point would appear in the record. Each sample in the sum gets an obliquity and spreading weight, and the traces are first filtered by a half derivative. In constant velocity the zero-offset curve is t=(2/v)z2+(x−xr)2t = (2/v)\sqrt{z^2 + (x - x_r)^2}. The method is a high-frequency (ray) approximation of the exact downward continuation of phase-shift migration, and it is the adjoint of a ray-based modeling operator, not its inverse (theorems). Because it needs only traveltimes and weights, it works for any acquisition geometry and for any velocity for which the traveltimes can be computed, for example with the eikonal equation.

In plain words

A small scatterer in the ground sends an echo to every receiver, and the echo arrives later at receivers that are farther away. On the record the echo draws a curve shaped like an upside-down bowl. To test whether a point in the ground scatters, compute its bowl, go along that bowl on the record, and add up the values. If a scatterer is really there, the values line up and the sum is large. If not, positive and negative values cancel. Do this for every point and you get a picture. Two small corrections make the strengths right: echoes that arrive at a steep angle or from far away get less weight, and each trace gets a fixed filter that sharpens it before the sums.

The problem

Given a zero-offset section d(t,xr)d(t, x_r) on traces xr=rΔxx_r = r\Delta x with the time step Δt\Delta t, and a constant velocity vv, compute the image m(x,z)m(x, z) at x=jΔxx = j\Delta x, z=iΔzz = i\Delta z. This is seismic migration in the exploding reflector model, where waves travel up with v′=v/2v' = v/2, so the traveltime from the image point to the trace is ρ/v′\rho/v' with ρ=z2+(x−xr)2\rho = \sqrt{z^2 + (x - x_r)^2}.

The algorithm

The 2D zero-offset formula (Schneider 1978; Yilmaz 2001, Chapter 4) is

m(x,z)=Δx∑rcos⁡θ2πv′ρ  hr(ρv′),cos⁡θ=zρ,m(x, z) = \Delta x \sum_r \frac{\cos\theta}{\sqrt{2\pi v'\rho}}\; h_r\Big(\frac{\rho}{v'}\Big), \qquad \cos\theta = \frac{z}{\rho},

where hrh_r is trace rr filtered by the half derivative with the symbol (−iω)1/2(-i\omega)^{1/2} in the sign convention U(ω)=∫u(t)e−iωt dtU(\omega) = \int u(t) e^{-i\omega t}\,dt. Texts that use the opposite sign write the same filter as (iω)1/2(i\omega)^{1/2}.

  1. KIRCHHOFF-MIGRATION(d, Δt, Δx, Δz, n_z, v) ▷ constant velocity v, v' = v / 2
  2. 1h_r ← trace r filtered by (-iω)^(1/2), for every trace r
  3. 2for every image point (i, j) with i ≥ 1 do ▷ z = iΔz, x = jΔx
  4. 3s ← 0
  5. 4for every trace r do ▷ x_r = rΔx
  6. 5ρ ← sqrt(z² + (x - x_r)²); w ← (z / ρ) / sqrt(2π v' ρ)
  7. 6s ← s + w · h_r(ρ / v') ▷ linear interpolation in time, 0 outside the record
  8. 7image[i][j] ← Δx · s
  9. 8return image

Line L1 applies the half-derivative filter to every trace with one FFT and one inverse FFT per trace. Lines L2 to L7 are the diffraction sum. Line L5 computes the distance to the trace, the obliquity factor cos⁡θ=z/ρ\cos\theta = z/\rho and the 2D spreading factor 1/ρ1/\sqrt{\rho}. Line L6 reads the filtered trace at the diffraction time ρ/v′=2ρ/v\rho/v' = 2\rho/v; the time almost never falls on a sample, so the code interpolates linearly. Row 0 (z=0z = 0) is left at zero, because the weight needs z>0z > 0. The sum over rr can be limited to an aperture of aa traces around xx, which saves time and removes noise from far traces.

Example

One weight by hand. For v=2000v = 2000 m/s (v′=1000v' = 1000 m/s), the image point (x,z)=(0,300)(x, z) = (0, 300) m and the trace at xr=400x_r = 400 m, ρ=500\rho = 500 m. The diffraction time is 500/1000=0.5500/1000 = 0.5 s, and the weight is (300/500)/2π⋅1000⋅500=0.6/1772.45=3.385×10−4(300/500)/\sqrt{2\pi \cdot 1000 \cdot 500} = 0.6/1772.45 = 3.385 \times 10^{-4}.

A point diffractor. The test uses the case of phase-shift migration: v=3000v = 3000 m/s, a point at x0=160x_0 = 160 m, z0=192z_0 = 192 m, 32 traces at 10 m, 64 samples at 4 ms, and Δz=6\Delta z = 6 m. The image peaks within one sample of row 32 and column 16. On rows 4 to 47 its relative difference to the phase-shift image is about 0.09 (a measurement); the difference comes from the high-frequency approximation, the finite line of traces and the linear interpolation in time.

Correctness

The full proof is in proofs/correctness.md.

  • What the code computes (theorem). For i≥1i \ge 1, line L8 returns exactly the weighted sum of the formula, with hrh_r read by linear interpolation.
  • The kernel (theorem). For one frequency, the downward continuation of phase shift, written as an integral over the traces, has the kernel G=ik2zρH1(1)(kρ)G = \frac{ik}{2}\frac{z}{\rho}H_1^{(1)}(k\rho) with k=ω/v′k = \omega/v'. This follows from the plane-wave (Weyl) form of the 2D Green's function.
  • High-frequency limit (theorem). As kρ→∞k\rho \to \infty, G=z/ρ2πv′ρ(−iω)1/2eiωρ/v′(1+O(1/(kρ)))G = \frac{z/\rho}{\sqrt{2\pi v'\rho}}(-i\omega)^{1/2}e^{i\omega\rho/v'}(1 + O(1/(k\rho))). Integrated over ω\omega, this gives the formula. So the Kirchhoff sum equals the exact one-way image up to a relative error that goes to zero with the frequency times the distance.
  • Adjoint pair (theorem). The diffraction sum of lines L2 to L8 and the modeling routine that spreads each image value along its curve are exact transposes. The test checks ⟨Sd,m⟩=⟨d,S∗m⟩\langle S d, m\rangle = \langle d, S^* m\rangle to 10−1210^{-12}.

The replacement of the integral over traces by a sum and of hr(t)h_r(t) by an interpolant are discretizations without an error bound here (heuristic steps).

Proof: Correctness of Kirchhoff migrationfull

Setting. The model is the exploding reflector model in the constant velocity vv, with v′=v/2v' = v/2. The zero-offset section d(t,x)d(t, x) is the upgoing field at z=0z = 0, and the exact image is the field at t=0t = 0:

m(x,z)=1(2π)2∬D(ω,kx) eikzz+ikxx dω dkx,D(ω,kx)=∬d(t,x) e−iωt−ikxx dt dx,m(x, z) = \frac{1}{(2\pi)^2} \iint D(\omega, k_x)\, e^{i k_z z + i k_x x}\,d\omega\,dk_x, \qquad D(\omega, k_x) = \iint d(t, x)\, e^{-i\omega t - i k_x x}\,dt\,dx,

with kz=sgn⁡(ω)ω2/v′2−kx2k_z = \operatorname{sgn}(\omega)\sqrt{\omega^2/v'^2 - k_x^2} (this is Step 1 of the proof of Stolt migration). For ∣kx∣>∣ω∣/v′|k_x| > |\omega|/v' we use the decaying branch kz=ikx2−ω2/v′2k_z = i\sqrt{k_x^2 - \omega^2/v'^2}; these parts decay as e−∣kz∣ze^{-|k_z| z} with depth. The phase-shift method sets them to zero instead, so the two images differ by these decaying parts.

The proof has three parts. Theorem 1 says what the code computes, and it is exact. Theorem 2 says that the code's sum is the exact image up to an error that goes to zero at high frequency. Theorem 3 says that the stack and the modeling routine are exact adjoints.

Theorem 1 (what the code computes). Let hrh_r be the trace at xr=rΔxx_r = r\Delta x after line L1, hr=IDFT((−iωk)1/2 DFT(dr))h_r = \mathrm{IDFT}\big((-i\omega_k)^{1/2}\,\mathrm{DFT}(d_r)\big), with the principal square root and the value 0 at ωk=0\omega_k = 0. For i≥1i \ge 1 the output of line L8 is

m[i][j]=Δx∑r=0nx−1zi/ρ2πv′ρ  hrlin(ρ/v′),ρ=zi2+(xj−xr)2,m[i][j] = \Delta x \sum_{r=0}^{n_x - 1} \frac{z_i / \rho}{\sqrt{2\pi v' \rho}}\; h_r^{\mathrm{lin}}(\rho / v'), \qquad \rho = \sqrt{z_i^2 + (x_j - x_r)^2},

where hrlinh_r^{\mathrm{lin}} is the linear interpolant of the samples of hrh_r, set to zero outside the record. Row 0 is zero. The real part kept in line L1 is the whole value except at the Nyquist index: for ωk<0\omega_k < 0 the principal root is the conjugate of the root at −ωk-\omega_k, so the filtered spectrum of a real trace keeps the conjugate symmetry.

Proof. Line L2 visits i=1,…,nz−1i = 1, \ldots, n_z - 1 and every jj. For fixed (i,j)(i, j), line L3 sets s=0s = 0, and lines L4 to L6 add, for every rr, the weight and the sample of kirchhoff_weight and sample, which are the factor (zi/ρ)/2πv′ρ(z_i/\rho)/\sqrt{2\pi v'\rho} and hrlin(ρ/v′)h_r^{\mathrm{lin}}(\rho/v') (note ρ/v′=2ρ/v\rho/v' = 2\rho/v). Line L7 stores Δx s\Delta x\, s. The loops have (nz−1)nxnx(n_z - 1) n_x n_x passes, so the algorithm stops. ■\blacksquare

Lemma (the kernel). Fix ω>0\omega > 0 and put k=ω/v′k = \omega/v', ξ=x−xr\xi = x - x_r, ρ=z2+ξ2\rho = \sqrt{z^2 + \xi^2}, z>0z > 0. Then

G(ω,ξ,z):=12π∫−∞∞eikzz+ikxξ dkx=ik2 zρ H1(1)(kρ).G(\omega, \xi, z) := \frac{1}{2\pi}\int_{-\infty}^{\infty} e^{i k_z z + i k_x \xi}\,dk_x = \frac{i k}{2}\,\frac{z}{\rho}\,H_1^{(1)}(k\rho).

Proof. The Weyl (plane-wave) representation of the 2D outgoing Green's function is H0(1)(kρ)=1π∫eikxξ+ikzz kz−1 dkxH_0^{(1)}(k\rho) = \frac{1}{\pi}\int e^{i k_x \xi + i k_z z}\, k_z^{-1}\,dk_x for z>0z > 0, with kz=k2−kx2k_z = \sqrt{k^2 - k_x^2} on the real branch and kz=ikx2−k2k_z = i\sqrt{k_x^2 - k^2} on the decaying branch. Differentiate in zz under the integral (the factor e−∣kz∣ze^{-|k_z| z} makes this valid for z>0z > 0): ∂zH0(1)(kρ)=iπ∫eikxξ+ikzz dkx=2i G\partial_z H_0^{(1)}(k\rho) = \frac{i}{\pi}\int e^{i k_x \xi + i k_z z}\,dk_x = 2i\,G. On the other side, ∂zH0(1)(kρ)=−k H1(1)(kρ) ∂zρ=−k (z/ρ) H1(1)(kρ)\partial_z H_0^{(1)}(k\rho) = -k\,H_1^{(1)}(k\rho)\,\partial_z \rho = -k\,(z/\rho)\,H_1^{(1)}(k\rho). Divide by 2i2i. □\square

Theorem 2 (the high-frequency limit). Write dr(ω)d_r(\omega) for the time transform of the trace at xrx_r. The exact image is

m(x,z)=∫dxr 12π∫dω  dr(ω) G(ω,x−xr,z),m(x, z) = \int dx_r\, \frac{1}{2\pi}\int d\omega\; d_r(\omega)\, G(\omega, x - x_r, z),

with G(−ω)=G(ω)‾G(-\omega) = \overline{G(\omega)}. As kρ→∞k\rho \to \infty,

G(ω,ξ,z)=z/ρ2πv′ρ (−iω)1/2 eiωρ/v′ (1+O(1/(kρ))).G(\omega, \xi, z) = \frac{z/\rho}{\sqrt{2\pi v' \rho}}\,(-i\omega)^{1/2}\, e^{i\omega\rho/v'}\,\big(1 + O(1/(k\rho))\big).

So, up to this relative error at each frequency, m(x,z)=∫dxr z/ρ2πv′ρ hr(ρ/v′)m(x, z) = \int dx_r\, \frac{z/\rho}{\sqrt{2\pi v'\rho}}\, h_r(\rho/v'), where hrh_r is the trace filtered by (−iω)1/2(-i\omega)^{1/2}. This is the continuous form of the sum in Theorem 1.

Proof. Put D(ω,kx)=∫dr(ω) e−ikxxr dxrD(\omega, k_x) = \int d_r(\omega)\, e^{-i k_x x_r}\,dx_r into the exact image and integrate over kxk_x first; the inner integral is 2π G(ω,x−xr,z)2\pi\,G(\omega, x - x_r, z) by the lemma. For the asymptotic form use H1(1)(y)=2/(πy) ei(y−3π/4) (1+O(1/y))H_1^{(1)}(y) = \sqrt{2/(\pi y)}\, e^{i(y - 3\pi/4)}\,(1 + O(1/y)):

G=ik2 zρ 2πkρ eikρ e−3iπ/4 (1+O(1/(kρ)))=zρ k2πρ  e−iπ/4 eikρ (1+O(1/(kρ))),G = \frac{ik}{2}\,\frac{z}{\rho}\,\sqrt{\frac{2}{\pi k\rho}}\, e^{ik\rho}\, e^{-3i\pi/4}\,(1 + O(1/(k\rho))) = \frac{z}{\rho}\,\sqrt{\frac{k}{2\pi\rho}}\; e^{-i\pi/4}\, e^{ik\rho}\,(1 + O(1/(k\rho))),

since i e−3iπ/4=e−iπ/4i\,e^{-3i\pi/4} = e^{-i\pi/4}. For ω>0\omega > 0, k e−iπ/4=ω/v′ e−iπ/4=(−iω)1/2/v′\sqrt{k}\,e^{-i\pi/4} = \sqrt{\omega/v'}\,e^{-i\pi/4} = (-i\omega)^{1/2}/\sqrt{v'} with the principal root. The negative frequencies follow by conjugation. Finally 12π∫(−iω)1/2 dr(ω) eiωρ/v′ dω=hr(ρ/v′)\frac{1}{2\pi}\int (-i\omega)^{1/2}\, d_r(\omega)\, e^{i\omega\rho/v'}\,d\omega = h_r(\rho/v') by the inverse time transform at t=ρ/v′t = \rho/v'. □\square

The code replaces the integral over xrx_r by the sum with the step Δx\Delta x and hr(t)h_r(t) by the linear interpolant of its samples. These two steps are discretizations, and their errors are not bounded here (a heuristic step; the tests measure a relative difference of about 0.09 to phase-shift migration for a point diffractor). The traces end at the edges of the line, so dips whose diffraction curves leave the line are lost.

Theorem 3 (adjointness). Let SS be the map of lines L2 to L8 (diffraction_stack) and S∗S^* the map of kirchhoff_modeling. For all data dd and images mm, ⟨Sd,m⟩=⟨d,S∗m⟩\langle S d, m\rangle = \langle d, S^* m\rangle in the plain dot products of the arrays.

Proof. For i≥1i \ge 1 let w=wijrw = w_{ijr} be the weight, ρ/v′=u Δt\rho/v' = u\,\Delta t the time, k=⌊u⌋k = \lfloor u\rfloor and f=u−kf = u - k, and let χijr=1\chi_{ijr} = 1 if 0≤k0 \le k and k+1<ntk + 1 < n_t, else 0. Then

⟨Sd,m⟩=∑i≥1,jm[i][j] Δx∑rw χijr ((1−f) d[k][r]+f d[k+1][r]).\langle S d, m\rangle = \sum_{i \ge 1, j} m[i][j]\,\Delta x \sum_r w\,\chi_{ijr}\,\big((1 - f)\,d[k][r] + f\,d[k + 1][r]\big).

All sums are finite, so they can be exchanged. Collecting the coefficient of each d[k′][r]d[k'][r] gives ∑i≥1,jΔx w χijr m[i][j]\sum_{i \ge 1, j} \Delta x\, w\, \chi_{ijr}\, m[i][j] times (1−f)(1 - f) where k=k′k = k' and times ff where k+1=k′k + 1 = k'. That is exactly the value that kirchhoff_modeling adds into out[k'][r] (an image value of 0 adds nothing, so skipping it changes nothing). ■\blacksquare

What is not claimed. The diffraction sum is not the inverse of the modeling operator S∗S^*; it is the adjoint, up to the half-derivative filter. Amplitudes are correct only in the high-frequency limit of Theorem 2, for constant velocity, and with a dense and long enough line of traces.

Complexity

  • Real-ram. Line L1 costs O(ntlog⁡nt)O(n_t \log n_t) per trace with an FFT, O(nxntlog⁡nt)O(n_x n_t \log n_t) in total. The sum costs O(1)O(1) per image point and trace: O(nznxa)O(n_z n_x a) with an aperture of aa traces, or O(nznx2)O(n_z n_x^2) with the whole line.
  • 3D. For a 3D image of NN points and TT traces, the cost is O(NT)O(N T), which is why production codes limit the aperture and compute the traveltimes on a coarse grid.
  • Space. The filtered traces and the image, O(nxnt+nznx)O(n_x n_t + n_z n_x).

Properties

  • Any geometry. The sum needs only the traveltime and the weight from each image point to each trace. Irregular, sparse or 3D acquisition is no harder than a regular line.
  • Target oriented. Any subset of image points can be computed alone, for example one region of interest.
  • Linear in the data. The image is a linear function of the section, and the method is the adjoint of the matching modeling operator.
  • High-frequency approximation. Amplitudes are right only when the wavelength is small compared with the distance and with the scale of velocity changes. Caustics and multiple arrivals break the single-traveltime form.
  • Aliasing. When the diffraction curve is steep and the traces are far apart, the sum picks up aliased energy; anti-alias filters that depend on the local slope are a common addition.

Variants and improvements

  • Variable velocity. Replace ρ/v′\rho/v' by the traveltime from a ray tracer or an eikonal equation solver such as the fast marching method, and the weights by the ray amplitudes.
  • Prestack Kirchhoff migration. For data with offset, the time is the sum of the source-to-point and point-to-receiver traveltimes, and the sum runs over all source and receiver pairs.
  • True-amplitude migration. Bleistein (1987) gave weights that make the sum an asymptotic inverse of the Born modeling, so the image amplitude is the reflection coefficient.
  • Least-squares migration. Use the sum as the adjoint in a conjugate gradient loop to correct amplitudes and the effect of the finite line.
  • Beam migration. Sum along local plane-wave beams instead of single curves, which handles multiple arrivals.

When to use it

Use Kirchhoff migration when the geometry is irregular, when only part of the image is needed, or when a fast image with ray traveltimes is enough, as in velocity analysis by migration. It is the standard prestack depth migration in many workflows. Prefer wave-equation methods (phase-shift, split-step Fourier or reverse-time migration) under complex velocity, such as below salt, where the ray approximation fails. The same idea, with other weights, is delay-and-sum beamforming in ultrasound and backprojection in radar.

Pitfalls

  • No half-derivative filter. Leaving out line L1 gives an image whose wavelet is too smooth and shifted in phase by 45 degrees. Filter every trace first, as in line L1.
  • The wrong filter sign. With the transform e−iωte^{-i\omega t}, the filter is (−iω)1/2(-i\omega)^{1/2}. Using (iω)1/2(i\omega)^{1/2} in line L1 turns the phase the wrong way. Check the sign with a point diffractor.
  • The two-way time. Reading the trace at ρ/v\rho/v in line L6 puts every point at twice its depth. Zero-offset data need ρ/v′=2ρ/v\rho/v' = 2\rho/v, as in line L6.
  • Nearest sample. Rounding ρ/v′\rho/v' to the nearest sample in line L6 adds a time error of up to half a sample, which is noise at high frequencies. Interpolate, as in line L6.

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.

imgkit.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/.
"""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
kirchhoff_migration.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kirchhoff-migration/. The authors are listed in prov/ZFVWK9.jsonl.
"""Kirchhoff (diffraction summation) migration of a 2D zero-offset section.

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 = j * dx. image[i][j] is the image at depth z_i = i * dz
  and position x_j. The velocity vel is constant (m/s).
- U(omega) = sum u(t) exp(-i omega t). With this sign the time derivative has
  the symbol i omega. The filter of the 2D formula is the half derivative with
  the symbol (-i omega)^(1/2) = |omega|^(1/2) exp(-i pi sgn(omega) / 4)
  (principal branch), which keeps real traces real. With the opposite
  transform sign it reads (i omega)^(1/2).
- Exploding reflector model: v' = vel / 2 and the traveltime from the image
  point (x, z) to the trace at x_r is t = r / v' = 2 r / vel, with
  r = sqrt(z^2 + (x - x_r)^2).

The 2D zero-offset formula (Schneider 1978, Yilmaz 2001 chapter 4) is
    I(x, z) = dx * sum_r cos(theta) / sqrt(2 pi v' r) * h(x_r, 2 r / vel),
with cos(theta) = z / r and h the half derivative of the trace. It is a high
frequency (stationary phase) approximation of the exact downward continuation.

Cost: O(nt log nt) per trace for the half derivative (radix-2 FFT when nt is a
power of 2), then O(nz * nx * n_traces) for the sums.
"""

import math

from imgkit import dft, idft


def half_derivative(trace, dt):
    """The half-derivative filter of a trace: multiply its DFT by (-i omega)^(1/2)."""
    n = len(trace)
    spec = dft(trace)
    out = []
    for k in range(n):
        f = k if 2 * k < n else k - n
        omega = 2.0 * math.pi * f / (n * dt)
        out.append(spec[k] * (-1j * omega) ** 0.5 if omega != 0.0 else 0j)
    return [v.real for v in idft(out)]


def sample(trace, t, dt):
    """Linear interpolation of a trace at time t; zero outside the record."""
    u = t / dt
    k = math.floor(u)
    if k < 0 or k + 1 >= len(trace):
        return 0.0
    frac = u - k
    return (1.0 - frac) * trace[k] + frac * trace[k + 1]


def kirchhoff_weight(x, z, xr, vel):
    """cos(theta) / sqrt(2 pi v' r) and the traveltime 2 r / vel, for z > 0."""
    r = math.hypot(z, x - xr)
    vhalf = vel / 2.0
    return (z / r) / math.sqrt(2.0 * math.pi * vhalf * r), r / vhalf


def kirchhoff_migration(data, dt, dx, dz, nz, vel):
    """Migrate a zero-offset section in constant velocity by diffraction summation.

    data: nt x nx real samples. Returns the nz x nx image; row 0 (z = 0) is
    left zero, since the formula needs z > 0. Precondition: dt, dx, dz, vel > 0.
    """
    nt, nx = len(data), len(data[0])
    cols = [half_derivative([data[k][j] for k in range(nt)], dt) for j in range(nx)]  # @line L1
    filtered = [[cols[j][k] for j in range(nx)] for k in range(nt)]
    return diffraction_stack(filtered, dt, dx, dz, nz, vel)


def diffraction_stack(data, dt, dx, dz, nz, vel):
    """Lines L2 to L7: the weighted sum along the diffraction curve of each image point.

    It is a linear map from data to image; kirchhoff_modeling is its exact adjoint.
    """
    nt, nx = len(data), len(data[0])
    cols = [[data[k][j] for k in range(nt)] for j in range(nx)]
    image = [[0.0] * nx for _ in range(nz)]
    for i in range(1, nz):  # @line L2
        z = i * dz
        for j in range(nx):
            x = j * dx
            s = 0.0  # @line L3
            for r in range(nx):  # @line L4
                w, t = kirchhoff_weight(x, z, r * dx, vel)  # @line L5
                s += w * sample(cols[r], t, dt)  # @line L6
            image[i][j] = dx * s  # @line L7
    return image  # @line L8


def kirchhoff_modeling(image, dt, nt, dx, dz, vel):
    """The exact adjoint of kirchhoff_migration without its half derivative.

    It spreads each image value w * I(x, z) * dx onto the trace at x_r along the
    diffraction curve t = 2 r / vel, with the transpose of the linear
    interpolation. Returns nt x nx data (before any half-derivative filter).
    """
    nz, nx = len(image), len(image[0])
    out = [[0.0] * nx for _ in range(nt)]
    for i in range(1, nz):
        z = i * dz
        for j in range(nx):
            val = image[i][j]
            if val == 0.0:
                continue
            for r in range(nx):
                w, t = kirchhoff_weight(j * dx, z, r * dx, vel)
                u = t / dt
                k = math.floor(u)
                if k < 0 or k + 1 >= nt:
                    continue
                frac = u - k
                out[k][r] += dx * w * (1.0 - frac) * val
                out[k + 1][r] += dx * w * frac * val
    return out
test_kirchhoff_migration.py 108 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kirchhoff-migration/. The authors are listed in prov/ZFVWK9.jsonl.
import cmath
import math
import random
import unittest

from imgkit import dft2, idft
from kirchhoff_migration import (
    diffraction_stack,
    half_derivative,
    kirchhoff_migration,
    kirchhoff_modeling,
    kirchhoff_weight,
)

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 signed(k, n):
    return k if 2 * k < n else k - n


def phase_shift_oracle(data, dt, dx, dz, nz, vel):
    """Constant velocity phase-shift migration, an independent reference."""
    nt, nx = len(data), len(data[0])
    p = dft2(data)
    vh = vel / 2.0
    img = []
    for _ in range(nz):
        row = [sum(p[k][j] for k in range(nt)) / nt for j in range(nx)]
        img.append([v.real for v in idft(row)])
        for k in range(nt):
            w = 2.0 * math.pi * signed(k, nt) / (nt * dt)
            for j in range(nx):
                kx = 2.0 * math.pi * signed(j, nx) / (nx * dx)
                a = (w / vh) ** 2 - kx * kx
                if w == 0.0 or a <= 0.0:
                    p[k][j] = 0j
                else:
                    p[k][j] *= cmath.exp(1j * math.copysign(math.sqrt(a), w) * dz)
    return img


def argmax2(img):
    return max((img[i][j], i, j) for i in range(len(img)) for j in range(len(img[0])))[1:]


class TestKirchhoffMigration(unittest.TestCase):
    def test_point_diffractor_focuses(self):
        img = kirchhoff_migration(diffractor(160.0, 192.0), DT, DX, DZ, 48, VEL)
        i, j = argmax2(img)
        self.assertLessEqual(abs(i - 32), 1)
        self.assertEqual(j, 16)

    def test_agrees_with_phase_shift(self):
        data = diffractor(160.0, 192.0)
        a = kirchhoff_migration(data, DT, DX, DZ, 48, VEL)
        b = phase_shift_oracle(data, DT, DX, DZ, 48, VEL)
        rows = range(4, 48)  # the formula is a high frequency approximation; skip z near 0
        num = sum((a[i][j] - b[i][j]) ** 2 for i in rows for j in range(NX))
        den = sum(b[i][j] ** 2 for i in rows for j in range(NX))
        self.assertLess(math.sqrt(num / den), 0.15)

    def test_stack_and_modeling_are_adjoint(self):
        rng = random.Random(7)
        nt, nx, nz = 40, 12, 10
        d = [[rng.gauss(0.0, 1.0) for _ in range(nx)] for _ in range(nt)]
        m = [[rng.gauss(0.0, 1.0) for _ in range(nx)] for _ in range(nz)]
        lt_d = diffraction_stack(d, DT, DX, DZ, nz, VEL)
        l_m = kirchhoff_modeling(m, DT, nt, DX, DZ, VEL)
        left = sum(l_m[k][j] * d[k][j] for k in range(nt) for j in range(nx))
        right = sum(m[i][j] * lt_d[i][j] for i in range(nz) for j in range(nx))
        self.assertLess(abs(left - right), 1e-12 * max(abs(left), 1.0))

    def test_half_derivative_twice_is_minus_derivative(self):
        # (-i omega)^(1/2) applied twice is -i omega, the symbol of -d/dt here.
        n, dt = 64, 0.004
        f = 5.0 / (n * dt)
        trace = [math.sin(2.0 * math.pi * f * k * dt) for k in range(n)]
        twice = half_derivative(half_derivative(trace, dt), dt)
        for k in range(n):
            self.assertAlmostEqual(twice[k], -2.0 * math.pi * f * math.cos(2.0 * math.pi * f * k * dt), delta=1e-9)

    def test_weight_and_traveltime(self):
        w, t = kirchhoff_weight(0.0, 300.0, 400.0, 2000.0)
        self.assertAlmostEqual(t, 0.5, places=12)  # r = 500 m, t = 2 r / v
        self.assertAlmostEqual(w, 0.6 / math.sqrt(2.0 * math.pi * 1000.0 * 500.0), places=15)


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

History

Diffraction stacking began as a graphical method before computers: interpreters summed the data along hyperbolas drawn on the record. Schneider (1978) derived the sum from the Kirchhoff integral of the wave equation, with the obliquity and spreading weights and the half-derivative filter in 2D and the derivative in 3D. Bleistein (1987) and his coworkers derived weights that make the sum an asymptotic inverse of the Born modeling operator, which gave true-amplitude migration. Kirchhoff prestack depth migration then became a standard imaging tool of the industry.

References

  1. William A. Schneider, Integral formulation for migration in two and three dimensions, Geophysics 43(1), 1978, 49 to 76, the Kirchhoff integral for migration with its weights and filter
  2. Norman Bleistein, On the imaging of reflectors in the earth, Geophysics 52(7), 1987, 931 to 942, the asymptotic inversion weights for true-amplitude Kirchhoff migration
  3. Oz Yilmaz, Seismic Data Analysis, Society of Exploration Geophysicists, 2001, Chapter 4 (migration), Kirchhoff migration and its 2D and 3D filters

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.filter
  • a full proof of time.sum
  • 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