Algorithm Search⌘K

Algorithmadvanced

Phase-shift migration

Also called Gazdag migration.

Extrapolate the wavefield down in depth steps by a phase shift of each frequency and wavenumber, for velocity that varies only with depth.

Time
O(z t x + t x log(t x)) totalO(z t x) depth_stepsO(t x log(t x)) fft_transform
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
deterministicnot lateral velocitysteep dipsunconditionally stable
Origin
Jeno Gazdag, 1978

Phase-shift migration images a zero-offset section in the frequency-wavenumber domain. It transforms the section in time and in space, and then it steps down in depth. At each step it multiplies every plane wave by the phase factor eikzΔze^{i k_z \Delta z} of the one-way wave equation, and it reads the image row as the field at time zero. In each depth layer the velocity must be the same at all xx. Under that condition the method is exact for the one-way equation, at all dips up to 90 degrees (a theorem). It is slower than Stolt migration, which does the same work for one constant velocity with one change of variables. Split-step Fourier migration adds a correction for lateral changes.

In plain words

Record a line of echoes at the surface. Imagine that every reflector in the ground sent out a pulse at the same moment, and that the pulses travel up at half the true speed. Then the record is a picture of that one upward wave as it reaches the surface. If we could move the receivers down into the ground, the wave would arrive earlier at each depth. At the exact depth of a reflector, its pulse would arrive at time zero. Phase-shift migration moves the receivers down step by step. It splits the record into simple waves of one frequency and one tilt. Each simple wave moves down by one step when you turn its phase by an amount that depends on the speed of the layer. After each step, the value at time zero is the picture at that depth.

The problem

Given a zero-offset section d(t,x)d(t, x) (one trace per surface position, with source and receiver at the same point), sampled at t=kΔtt = k\Delta t and x=jΔxx = j\Delta x, and the velocity viv_i of each depth layer iΔz≤z<(i+1)Δzi\Delta z \le z < (i + 1)\Delta z, find the reflectivity image m(x,z)m(x, z). This is the seismic migration problem for a velocity that changes only with depth. The model is the exploding reflector model: the section is the upgoing field at z=0z = 0 of the wave equation with the half velocity v′=v/2v' = v/2, and the image is the same field at t=0t = 0.

The algorithm

The time transform is U(ω)=∑tu(t)e−iωtU(\omega) = \sum_t u(t) e^{-i\omega t}, and the space transform uses e−ikxxe^{-i k_x x}. With this sign an upgoing wave reaches depth zz a time z/v′z/v' before it reaches the surface, so one step down multiplies its transform by e+ikzΔze^{+i k_z \Delta z} with

kz=sgn⁡(ω)ω2v′2−kx2.k_z = \operatorname{sgn}(\omega)\sqrt{\frac{\omega^2}{v'^2} - k_x^2}.
  1. PHASE-SHIFT-MIGRATION(d, Δt, Δx, Δz, v) ▷ d: n_t × n_x section, v[i]: velocity of layer i
  2. 1P ← DFT2(d) ▷ P[k][j] belongs to (ω_k, k_x,j)
  3. 2for i ← 0 to n_z - 1 do
  4. 3row[j] ← (1 / n_t) Σ_k P[k][j] for every j ▷ inverse time transform at t = 0
  5. 4image[i] ← Re IDFT(row)
  6. 5v' ← v[i] / 2
  7. 6for every pair (k, j) do
  8. 7if ω_k ≠ 0 and ω_k² / v'² > k_x,j² then k_z ← sgn(ω_k) sqrt(ω_k² / v'² - k_x,j²)
  9. 8else P[k][j] ← 0 and go to the next pair ▷ evanescent or zero frequency
  10. 9P[k][j] ← P[k][j] · exp(i k_z Δz)
  11. 10return image

Line L1 takes the 2D discrete Fourier transform of the section once. The signed frequencies are ωk=2πk/(ntΔt)\omega_k = 2\pi k/(n_t\Delta t) for 2k<nt2k < n_t and 2π(k−nt)/(ntΔt)2\pi(k - n_t)/(n_t\Delta t) otherwise, and kx,jk_{x,j} is defined in the same way. Lines L3 and L4 form the image row of the current depth: the inverse transform in time at t=0t = 0 is the plain average over the frequencies, because eiω⋅0=1e^{i\omega \cdot 0} = 1, and then an inverse DFT in xx gives the row. Lines L5 to L9 move the whole field one layer down. Line L8 removes the evanescent waves, whose amplitude would grow without bound if they were continued, and the zero frequency, which carries no image. Line L9 is the phase shift of the layer. A field that is real stays real, because the factor at (−ω,−kx)(-\omega, -k_x) is the complex conjugate of the factor at (ω,kx)(\omega, k_x).

Example

A flat reflector in two layers (by hand). Take v=2000v = 2000 m/s from the surface down to 100 m and v=3000v = 3000 m/s below, with Δz=10\Delta z = 10 m. A section that is the same on every trace holds only the wavenumber kx=0k_x = 0. Then kz=ω/v′k_z = \omega/v' and line L9 multiplies by eiω Δz/v′e^{i\omega\,\Delta z/v'}: each row shifts the trace earlier by the vertical two-way time 2Δz/v2\Delta z/v of its layer. Rows 0 to 9 take 2⋅10/2000=0.012 \cdot 10/2000 = 0.01 s each, so row 10 is at 0.1 s. Each later row takes 2⋅10/3000=0.006672 \cdot 10/3000 = 0.00667 s. An event at t=0.2t = 0.2 s therefore lands at row 10+0.1/0.00667=2510 + 0.1/0.00667 = 25, at depth 250 m. The test runs this case with a Ricker wavelet of peak value 1 at 0.2 s. The image peaks at row 25 with the value 0.9999999975 (a measurement; the small loss is the zero frequency and the band edge removed by line L8).

A point diffractor. A point at x0=160x_0 = 160 m, z0=192z_0 = 192 m in the constant velocity 3000 m/s gives a hyperbola t(x)=(2/v)z02+(x−x0)2t(x) = (2/v)\sqrt{z_0^2 + (x - x_0)^2} in the section (nt=64n_t = 64, Δt=4\Delta t = 4 ms, nx=32n_x = 32, Δx=10\Delta x = 10 m). With Δz=6\Delta z = 6 m the image collapses the hyperbola to one spot at row 192/6=32192/6 = 32, column 160/10=16160/10 = 16, and the values far from the spot are below a quarter of the peak. In 2D the migrated pulse is not symmetric, so its peak can move by a sample. In the test, the raw data peak within one sample of (32,16)(32, 16), and data whose traces are first filtered by (iω)1/2(i\omega)^{1/2} peak exactly at (32,16)(32, 16) (measurements).

Correctness

The full proof is in proofs/correctness.md.

  • One layer (theorem). In a layer of constant velocity, every non-evanescent plane wave satisfies Pzz+kz2P=0P_{zz} + k_z^2 P = 0, and the upgoing solution is P(z+Δz)=P(z) eikzΔzP(z + \Delta z) = P(z)\,e^{i k_z \Delta z} with the sign of kzk_z equal to the sign of ω\omega.
  • Loop invariant (theorem). At the start of pass ii of line L2, PP is the transform of the section continued through layers 0,…,i−10, \ldots, i - 1, with the evanescent parts removed. Lines L3 and L4 store the real part of that field at t=0t = 0.
  • Exactness for v(z)v(z) (theorem). If the true field is a finite sum of DFT plane waves without evanescent parts, the image is exactly the field p(0,xj,zi)p(0, x_j, z_i) of the model. For vertical waves the row ii is the trace at the two-way vertical time τi=∑l<i2Δz/vl\tau_i = \sum_{l < i} 2\Delta z/v_l.

The exactness is a statement about the one-way model on a periodic grid. Real sections are not periodic, and the exploding reflector model ignores multiples.

Proof: Correctness of phase-shift migrationfull

Setting. The model is the exploding reflector model: the zero-offset section d(t,x)d(t, x) is the upgoing wavefield p(t,x,z)p(t, x, z) at z=0z = 0, where pp solves the scalar wave equation pzz+pxx−ptt/v′2=0p_{zz} + p_{xx} - p_{tt}/v'^2 = 0 with the half velocity v′=v/2v' = v/2, and the image is p(0,x,z)p(0, x, z). The velocity is constant in each layer zi≤z<zi+1z_i \le z < z_{i+1}, zi=i Δzz_i = i\,\Delta z, with the value vi′=vi/2v'_i = v_i/2. Transforms use the sign of the area: P(ω,kx,z)=∬p(t,x,z) e−iωt−ikxx dt dxP(\omega, k_x, z) = \iint p(t, x, z)\, e^{-i\omega t - i k_x x}\,dt\,dx. For ω≠0\omega \ne 0 and ω2/v′2>kx2\omega^2/v'^2 > k_x^2 put kz(ω,kx,v′)=sgn⁡(ω)ω2/v′2−kx2k_z(\omega, k_x, v') = \operatorname{sgn}(\omega)\sqrt{\omega^2/v'^2 - k_x^2}; the other pairs (ω,kx)(\omega, k_x) are called evanescent.

The discrete statements are about the arrays of the pseudocode. Pi[k][j]P_i[k][j] is the value of the array PP at the start of pass ii of the loop at line L2. ωk\omega_k and kx,jk_{x,j} are the signed DFT frequencies of index kk and jj (kk for 2k<n2k < n, else k−nk - n, times 2π/(n Δ)2\pi/(n\,\Delta)).

Lemma 1 (one layer). In a layer of constant v′v', every solution of the wave equation has, for a non-evanescent pair (ω,kx)(\omega, k_x), the form P(z)=Aeikzz+Be−ikzzP(z) = A e^{i k_z z} + B e^{-i k_z z}. The upgoing part is AeikzzA e^{i k_z z}, so the upgoing field at z+Δzz + \Delta z is P(z+Δz)=P(z) eikzΔzP(z + \Delta z) = P(z)\, e^{i k_z \Delta z}.

Proof. The transform turns ∂t\partial_t into iωi\omega and ∂x\partial_x into ikxi k_x, so the wave equation becomes Pzz+(ω2/v′2−kx2)P=Pzz+kz2P=0P_{zz} + (\omega^2/v'^2 - k_x^2) P = P_{zz} + k_z^2 P = 0, a linear ODE in zz with the two solutions e±ikzze^{\pm i k_z z}. For kx=0k_x = 0 the upgoing wave is p(t,x,z)=p(t+z/v′,x,0)p(t, x, z) = p(t + z/v', x, 0), because the wave reaches the depth zz a time z/v′z/v' before it reaches the surface. Its transform is P(ω,0,z)=P(ω,0,0) eiωz/v′P(\omega, 0, z) = P(\omega, 0, 0)\, e^{i\omega z/v'}, which is e+ikzze^{+i k_z z} with kz=ω/v′k_z = \omega/v'. The function kx↦kz(ω,kx,v′)k_x \mapsto k_z(\omega, k_x, v') is continuous and never zero on the non-evanescent interval ∣kx∣<∣ω∣/v′|k_x| < |\omega|/v', so the root with the sign of ω\omega is the upgoing branch on the whole interval. □\square

Lemma 2 (the image row). For any array Q[k][j]Q[k][j], line L3 followed by line L4 gives the row Re⁡ q(0,xj)\operatorname{Re}\, q(0, x_j), where q(tℓ,xj)=1ntnx∑k,j′Q[k][j′] eiωktℓ+ikx,j′xjq(t_\ell, x_j) = \frac{1}{n_t n_x}\sum_{k,j'} Q[k][j']\, e^{i\omega_k t_\ell + i k_{x,j'} x_j} is the inverse 2D DFT of QQ.

Proof. At t0=0t_0 = 0 the factor eiωkt0e^{i\omega_k t_0} is 1, so the inverse transform in time at t=0t = 0 is 1nt∑kQ[k][j′]\frac{1}{n_t}\sum_k Q[k][j'], which is line L3. Line L4 applies the inverse DFT in xx (the helper divides by nxn_x) and keeps the real part. □\square

Theorem 1 (loop invariant). At the start of pass ii of the loop at line L2,

Pi[k][j]={D[k][j] exp⁡(i∑l=0i−1kz(ωk,kx,j,vl′) Δz)if (ωk,kx,j) is non-evanescent for v0′,…,vi−1′,0otherwise,P_i[k][j] = \begin{cases} D[k][j]\, \exp\Big(i \sum_{l=0}^{i-1} k_z(\omega_k, k_{x,j}, v'_l)\,\Delta z\Big) & \text{if } (\omega_k, k_{x,j}) \text{ is non-evanescent for } v'_0, \ldots, v'_{i-1}, \\ 0 & \text{otherwise,} \end{cases}

where D=DFT2(d)D = \mathrm{DFT2}(d) is the array of line L1. So PiP_i is the DFT of the field continued to depth ziz_i by Lemma 1 in each layer, with the evanescent parts removed, and row ii of the image is Re⁡\operatorname{Re} of that field at t=0t = 0.

Proof. Induction on ii. Initialization: before pass 0 the sum is empty and P0=DP_0 = D by line L1. Maintenance: assume the claim for ii. Line L3 and line L4 do not change PP, and by Lemma 2 they store the real part of the inverse transform of PiP_i at t=0t = 0 as row ii. Lines L5 to L9 then visit every pair (k,j)(k, j) once (line L6). If the pair is evanescent for vi′v'_i, line L8 sets the entry to 0, which is the second case for i+1i + 1. Otherwise line L7 computes kz(ωk,kx,j,vi′)k_z(\omega_k, k_{x,j}, v'_i) and line L9 multiplies the entry by eikzΔze^{i k_z \Delta z}, which adds the term l=il = i to the sum (an entry that is already 0 stays 0). This is the claim for i+1i + 1. Termination: the loop at line L2 runs nzn_z times and the inner loop ntnxn_t n_x times, so the algorithm stops after nzntnxn_z n_t n_x updates and line L10 returns the nzn_z rows. ■\blacksquare

Theorem 2 (exact for v(z)v(z) in the discrete model). Let the true field in the model be a finite sum of the DFT plane waves ei(ωkt+kx,jx)e^{i(\omega_k t + k_{x,j} x)} restricted to the upgoing branch, periodic in tt and xx with the periods ntΔtn_t \Delta t and nxΔxn_x \Delta x, and with no evanescent components. Then row ii of the image is exactly the field p(0,xj,zi)p(0, x_j, z_i).

Proof. By Lemma 1 each plane wave at depth ziz_i is the plane wave at the surface times ∏leikz(ωk,kx,j,vl′)Δz\prod_l e^{i k_z(\omega_k, k_{x,j}, v'_l)\Delta z}, which is the factor in Theorem 1. The DFT of the sampled sum is the array of coefficients, so PiP_i is the DFT of the samples of p(⋅,⋅,zi)p(\cdot, \cdot, z_i), and by Lemma 2 row ii is Re⁡ p(0,xj,zi)\operatorname{Re}\, p(0, x_j, z_i). A real field has a real value. □\square

Corollary (vertical waves). For kx=0k_x = 0 the factor of Theorem 1 is eiωkτie^{i\omega_k \tau_i} with τi=∑l<iΔz/vl′=∑l<i2Δz/vl\tau_i = \sum_{l<i} \Delta z/v'_l = \sum_{l<i} 2\Delta z/v_l, the two-way vertical time to ziz_i. So a section that is constant in xx is mapped by zi↦z_i \mapsto the trigonometric interpolant of the trace at t=τit = \tau_i (without the frequency ω=0\omega = 0 and with the Nyquist index treated as a negative frequency). When τi\tau_i falls on a sample, the image is that sample. This is the time-to-depth conversion. □\square

What is not claimed. The data of a real experiment are not periodic, the wavelet is not band limited, and the exploding reflector model ignores multiples and ray paths that differ for the down and up legs. Theorem 2 is a statement about the model and the discrete grid. Lateral velocity changes are outside the method: Lemma 1 needs a constant velocity across xx inside each layer.

Complexity

  • Transform (real-ram). Line L1 is one 2D DFT of an nt×nxn_t \times n_x array: O(ntnxlog⁡(ntnx))O(n_t n_x \log(n_t n_x)) with an FFT and O(ntnx(nt+nx))O(n_t n_x (n_t + n_x)) with direct sums.
  • Depth steps. Each pass of line L2 costs O(ntnx)O(n_t n_x) for line L3, O(nxlog⁡nx)O(n_x \log n_x) for line L4 and O(ntnx)O(n_t n_x) for lines L6 to L9. With nzn_z steps the total is O(nzntnx+ntnxlog⁡(ntnx))O(n_z n_t n_x + n_t n_x \log(n_t n_x)).
  • Space. The array PP holds ntnxn_t n_x complex numbers and the image nznxn_z n_x real numbers.

The cost does not depend on the dip of the events. In practice the frequencies outside the band of the source are skipped, which divides the work by the ratio of the Nyquist frequency to the band.

Properties

  • All dips. The phase shift uses the exact square root, so dips up to 90 degrees are imaged correctly (in the one-way model). The 15-degree finite-difference migration uses an approximation of the root.
  • Unconditionally stable. Every factor in line L9 has modulus 1 and line L8 sets the others to 0, so no step increases the energy. Any Δz\Delta z can be used; a large step only samples the image coarsely.
  • Linear in the data. The image is a linear function of the section.
  • Periodic edges. The DFT treats the section as periodic in tt and xx, so energy that leaves one side enters at the other. Pad with zeros to avoid wrap-around.
  • No lateral velocity change. Inside a layer the velocity must be the same at every xx; otherwise the plane waves are not solutions.

Variants and improvements

  • Stolt migration. For one constant velocity, all depth steps can be done at once by a change of variables from ω\omega to kzk_z, with one inverse FFT instead of nzn_z passes.
  • Phase shift plus interpolation (PSPI). Gazdag and Sguazzero (1984) continue the field with a few reference velocities and interpolate between the results at each xx, which handles lateral velocity changes.
  • Split-step Fourier migration. One reference velocity per layer, and a phase correction in the space domain for the local velocity.
  • Prestack depth migration. The same phase shift, applied to sources and receivers together (the double square root equation), migrates data with offset.
  • Time migration. With the vertical time as the depth variable, the steps follow the record time and the velocity is the rms velocity.

When to use it

Use phase-shift migration when the velocity changes only with depth and you want an exact image at all dips. It is a reference method for testing faster or more general methods, as in the tests on this site, where Stolt, Kirchhoff, split-step and finite-difference migration are all checked against it. For one constant velocity, Stolt migration is faster. For strong lateral changes, use split-step Fourier, PSPI or finite-difference migration, and for steep dips with complex velocity use reverse-time migration.

Pitfalls

  • The wrong sign of the phase. With the transform e−iωte^{-i\omega t}, writing line L9 as P⋅e−ikzΔzP \cdot e^{-i k_z \Delta z} continues the field up instead of down, and a diffractor spreads into a wider hyperbola. Use e+ikzΔze^{+i k_z \Delta z} as in line L9. Claerbout and Yilmaz use the other transform sign, so their formula has the other sign too.
  • The full velocity. Using v[i]v[i] in line L5 instead of v[i]/2v[i]/2 puts every reflector at twice its depth. Zero-offset data need the half velocity of the exploding reflector model, as in line L5.
  • Continuing evanescent waves. If line L8 keeps the pairs with ωk2/v′2<kx,j2\omega_k^2/v'^2 < k_{x,j}^2 and uses an imaginary kzk_z of the wrong sign, the factor grows exponentially and the image fills with noise. Set them to zero, as in line L8.
  • Imaging after the step. Moving lines L3 and L4 after line L9 shifts every row down by one step. The image of depth ziz_i is taken before the field is moved to zi+1z_{i+1}.

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
phase_shift_migration.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-shift-migration/. The authors are listed in prov/PNBG5B.jsonl.
"""Phase-shift (Gazdag) migration of a zero-offset section for a velocity v(z).

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. image[i][j] is the image at depth z = i * dz.
- The time transform is U(omega) = sum u(t) exp(-i omega t), the same sign as
  the DFT, and the x transform uses exp(-i kx x). Index k of a DFT of length n
  stands for the frequency k for k < n / 2 and k - n otherwise.
- Exploding reflector model: the zero-offset data is a one-way upgoing field
  in a medium with half the velocity, v / 2.
- With this sign, downward continuation by dz multiplies the transform by
  exp(+i kz dz) with kz = sgn(omega) sqrt(omega^2 / v'^2 - kx^2), v' = v / 2.
  Evanescent components (|kx| > |omega| / v') are set to zero.

Cost: two 2D FFTs of the data, then O(nz * nt * nx) for the phase shifts,
plus one FFT of length nx per depth step.
"""

import cmath
import math

from imgkit import dft2, idft


def signed_freq(k, n, d):
    """The angular frequency 2 pi f of DFT index k for n samples with spacing d."""
    f = k if 2 * k < n else k - n
    return 2.0 * math.pi * f / (n * d)


def vertical_wavenumber(omega, kx, vel):
    """kz = sgn(omega) sqrt(omega^2 / vel^2 - kx^2), or None for an evanescent pair."""
    q = (omega / vel) ** 2 - kx * kx
    if q < 0.0 or omega == 0.0:
        return None
    return math.copysign(math.sqrt(q), omega)


def phase_shift_migration(data, dt, dx, dz, vz):
    """Migrate a zero-offset section with the phase-shift method.

    data: nt x nx real samples. vz: a list of nz velocities (m/s); vz[i] is the
    velocity between the depths i dz and (i + 1) dz. Returns the nz x nx image,
    whose row i is the field at time 0 after continuation to depth i dz.
    Precondition: dt, dx, dz > 0 and every velocity > 0.
    """
    nt, nx = len(data), len(data[0])
    nz = len(vz)
    p = dft2(data)  # @line L1
    omegas = [signed_freq(k, nt, dt) for k in range(nt)]
    kxs = [signed_freq(j, nx, dx) for j in range(nx)]
    image = []
    for i in range(nz):  # @line L2
        row_k = [sum(p[k][j] for k in range(nt)) / nt for j in range(nx)]  # @line L3
        image.append([v.real for v in idft(row_k)])  # @line L4
        vhalf = vz[i] / 2.0  # @line L5
        for k in range(nt):  # @line L6
            for j in range(nx):
                kz = vertical_wavenumber(omegas[k], kxs[j], vhalf)  # @line L7
                if kz is None:
                    p[k][j] = 0j  # @line L8
                else:
                    p[k][j] *= cmath.exp(1j * kz * dz)  # @line L9
    return image  # @line L10


def ricker(t, f0):
    """The Ricker wavelet (1 - 2 a) exp(-a) with a = (pi f0 t)^2, peak frequency f0."""
    a = (math.pi * f0 * t) ** 2
    return (1.0 - 2.0 * a) * math.exp(-a)


def diffractor_section(nt, nx, dt, dx, x0, z0, vel, f0):
    """Zero-offset data of one point diffractor at (x0, z0) in constant velocity.

    The event is a Ricker wavelet along t(x) = (2 / vel) sqrt(z0^2 + (x - x0)^2).
    """
    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, f0)
    return out
test_phase_shift_migration.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-shift-migration/. The authors are listed in prov/PNBG5B.jsonl.
import math
import unittest

from imgkit import dft, idft
from phase_shift_migration import (
    diffractor_section,
    phase_shift_migration,
    ricker,
    signed_freq,
    vertical_wavenumber,
)

NT, NX, DT, DX = 64, 32, 0.004, 10.0
VEL = 3000.0


def half_filter(data, dt):
    """Multiply the time spectrum of every trace by (i omega)^(1/2), zero at omega = 0."""
    nt, nx = len(data), len(data[0])
    cols = []
    for j in range(nx):
        spec = dft([data[k][j] for k in range(nt)])
        out = []
        for k in range(nt):
            w = signed_freq(k, nt, dt)
            out.append(spec[k] * (1j * w) ** 0.5 if w != 0.0 else 0j)
        cols.append([v.real for v in idft(out)])
    return [[cols[j][k] for j in range(nx)] for k in range(nt)]


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 TestPhaseShiftMigration(unittest.TestCase):
    def test_flat_event_in_two_layers(self):
        # Reflector at 250 m under 100 m of 2000 m/s and 3000 m/s below:
        # two-way time 2 (100/2000 + 150/3000) = 0.2 s, sample 50.
        nx = 8
        data = [[ricker(k * DT - 0.2, 25.0)] * nx for k in range(NT)]
        vz = [2000.0] * 10 + [3000.0] * 30
        img = phase_shift_migration(data, DT, DX, 10.0, vz)
        for j in range(nx):
            col = [img[i][j] for i in range(len(vz))]
            self.assertEqual(max(range(len(vz)), key=lambda i: col[i]), 25)
            self.assertAlmostEqual(col[25], 1.0, delta=1e-6)

    def test_point_diffractor_focuses(self):
        # Diffractor at x0 = 160 m (column 16), z0 = 192 m; dz = v dt / 2 = 6 m,
        # so the focus is row 32. The half-derivative prefilter makes the
        # migrated pulse zero phase, so the maximum is exactly there.
        dz = VEL * DT / 2.0
        data = half_filter(diffractor_section(NT, NX, DT, DX, 160.0, 192.0, VEL, 25.0), DT)
        img = phase_shift_migration(data, DT, DX, dz, [VEL] * 48)
        self.assertEqual(argmax2(img), (32, 16))

    def test_raw_diffractor_within_one_sample(self):
        dz = VEL * DT / 2.0
        data = diffractor_section(NT, NX, DT, DX, 160.0, 192.0, VEL, 25.0)
        img = phase_shift_migration(data, DT, DX, dz, [VEL] * 48)
        i, j = argmax2(img)
        self.assertLessEqual(abs(i - 32), 1)
        self.assertEqual(j, 16)

    def test_energy_is_focused(self):
        # Away from the focus the image is small compared with the peak.
        dz = VEL * DT / 2.0
        data = half_filter(diffractor_section(NT, NX, DT, DX, 160.0, 192.0, VEL, 25.0), DT)
        img = phase_shift_migration(data, DT, DX, dz, [VEL] * 48)
        peak = img[32][16]
        far = max(abs(img[i][j]) for i in range(48) for j in range(NX) if abs(i - 32) > 6 or abs(j - 16) > 6)
        self.assertLess(far, 0.25 * peak)

    def test_vertical_wavenumber(self):
        w = 2.0 * math.pi * 20.0
        v = 1500.0
        self.assertAlmostEqual(vertical_wavenumber(w, 0.0, v), w / v, places=12)
        self.assertAlmostEqual(vertical_wavenumber(-w, 0.0, v), -w / v, places=12)
        self.assertIsNone(vertical_wavenumber(w, 1.01 * w / v, v))
        self.assertIsNone(vertical_wavenumber(0.0, 0.0, v))
        kx = 0.6 * w / v
        self.assertAlmostEqual(vertical_wavenumber(w, kx, v), 0.8 * w / v, places=12)

    def test_signed_frequencies(self):
        self.assertEqual([round(signed_freq(k, 8, 1.0) * 8 / (2 * math.pi)) for k in range(8)],
                         [0, 1, 2, 3, -4, -3, -2, -1])


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

History

Claerbout (1971) and Claerbout and Doherty (1972) introduced downward continuation of seismic data with the one-way wave equation, solved by finite differences. Loewenthal, Lu, Roberson and Sherwood (1976) described zero-offset data with the exploding reflector model and the half velocity. In 1978 Gazdag solved the same downward continuation in the frequency-wavenumber domain, where it is exact for a velocity that changes only with depth, and Stolt published the constant-velocity version in the same year. Gazdag and Sguazzero (1984) extended the method to lateral velocity changes with phase shift plus interpolation.

References

  1. Jeno Gazdag, Wave equation migration with the phase-shift method, Geophysics 43(7), 1978, 1342 to 1351, the phase-shift downward continuation and the imaging at t = 0
  2. D. Loewenthal, L. Lu, R. Roberson and J. Sherwood, The wave equation applied to migration, Geophysical Prospecting 24(2), 1976, 380 to 399, the exploding reflector model of zero-offset data
  3. Oz Yilmaz, Seismic Data Analysis, Society of Exploration Geophysicists, 2001, Chapter 4 (migration), frequency-wavenumber migration
  4. Jon F. Claerbout, Imaging the Earth's Interior, Blackwell, 1985, the chapters on downward continuation in the frequency domain

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.depth_steps
  • a full proof of time.fft_transform
  • 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