Algorithm Search⌘K

Algorithmcore

Geiger's method

Also called Geiger earthquake location.

Locate an earthquake by Gauss-Newton steps on the hypocenter and origin time that fit the observed arrival times at the stations.

Time
O(k n) worst · averageO(n) best
Space
O(n) extra
Where
k = the number of iterations; n = the number of stations
Properties
deterministiciterative
Origin
Ludwig Geiger, 1910

Geiger's method locates an earthquake from the arrival times of its waves at a network of stations. The unknowns are the hypocenter, three coordinates, and the origin time. The predicted arrival time at a station is the origin time plus the travel time from the source, which depends on the source position in a nonlinear way. The method starts from a trial location, linearizes the travel times around it, and solves the small least-squares problem for a correction; then it repeats. This is the Gauss-Newton algorithm for a nonlinear least-squares problem with four unknowns, and Geiger proposed it for earthquakes in 1910. It is the basic step of earthquake location, and the same linearization, with velocities as further unknowns, leads to traveltime tomography.

In plain words

An earthquake sends waves to many stations, and each station notes when the first wave came. We do not know where or when the quake happened. Guess a place and a time. From the guess, compute when the wave should have reached each station, and compare with what the stations saw. Some stations heard it too early, some too late. Each mismatch hints which way to move the guess: toward the stations that heard it early. The method weighs all the hints at once, picks the move that best explains all the mismatches together, and moves the guess. Then it compares again. Near the right answer each move gets much smaller than the one before, and the guess settles on the place and time that fit the stations best.

The problem

Input: stations si=(ai,bi,ci)s_i = (a_i, b_i, c_i), i=1,…,ni = 1, \ldots, n, with n≥4n \ge 4; observed P arrival times TiT_i; a velocity model, here a constant velocity vv; a starting model m0m_0. Output: the model m=(x,y,z,t0)m = (x, y, z, t_0) that minimizes

Φ(m)=∑i=1n(Ti−t0−Di/v)2,Di=∣h−si∣,h=(x,y,z).\Phi(m) = \sum_{i=1}^{n} \big(T_i - t_0 - D_i/v\big)^2, \qquad D_i = |h - s_i|, \quad h = (x, y, z).

The depth zz is positive down. With a layered or 3D velocity model, the travel time comes from ray tracing or from the eikonal equation, and its derivative with respect to the source position is the slowness vector at the source; the method is the same.

The algorithm

  1. GEIGER(stations s_i, times T_i, v, m₀)
  2. 1m ← m₀
  3. 2repeat until the update is small or the step limit is reached
  4. 3r_i ← T_i - (t₀ + |h - s_i| / v) ▷ residuals
  5. 4G_i ← ((h - s_i)ᵀ / (v |h - s_i|), 1) ▷ Jacobian row
  6. 5solve (Gᵀ G + λ I) δ = Gᵀ r ▷ λ = 0: Gauss-Newton
  7. 6m ← m + δ
  8. 7return m

Row ii of the Jacobian holds the unit vector from station ii to the source divided by vv, and a 1 for the origin time. Line L5 solves the normal equations of the linearized problem; with λ>0\lambda > 0 it is a Levenberg-Marquardt step. The code has two more safeguards, both heuristics and off by default: a limit on the length of the move, and the reflection of a source above the surface back below it.

Example

A good network. Six stations at the surface, at (0,0)(0, 0), (10,0)(10, 0), (0,10)(0, 10), (10,10)(10, 10), (5,12)(5, 12) and (3,4)(3, 4) km, record a source at (4000,3000,5000)(4000, 3000, 5000) m with origin time 0.50.5 s, in a medium with v=6000v = 6000 m/s. The arrival times are 1.67851.6785, 1.89441.8944, 2.08112.0811, 2.24802.2480, 2.22402.2240 and 1.36601.3660 s. Start from (4500,3500,7000)(4500, 3500, 7000) m and 0.40.4 s:

step (x,y,z)(x, y, z) (m) t0t_0 (s) location error (m) misfit (s²)
1 (3929.563, 2953.062, 4719.685) 0.554 292.8 5.80×10−35.80 \times 10^{-3}
2 (3998.911, 2999.801, 4995.309) 0.501 4.82 1.64×10−61.64 \times 10^{-6}
3 (4000.000, 3000.000, 4999.998) 0.500 1.77×10−31.77 \times 10^{-3} 1.13×10−131.13 \times 10^{-13}
4 (4000.000, 3000.000, 5000.000) 0.500 2.8×10−102.8 \times 10^{-10} 1.9×10−271.9 \times 10^{-27}

From step 1 on, each error is between 5.6×10−55.6 \times 10^{-5} and 8.9×10−58.9 \times 10^{-5} times the square of the one before (in metres), the quadratic convergence of Claim 4 of the proof.

Without the near station. Drop the station at (3,4)(3, 4) km, the one close to the epicenter. From the same start, the first step jumps to the depth z=−1183z = -1183 m, above the surface, and the next to −9617-9617 m; plain Gauss-Newton still reaches the true source, after 10 steps. With all stations at the surface, a source at depth zz and its mirror image at −z-z give the same times, so the data alone cannot rule out a negative depth. From the start (5000,5000,z0)(5000, 5000, z_0) m and 00 s, plain Gauss-Newton diverges for z0=2000z_0 = 2000 m and z0=15000z_0 = 15000 m, and converges to the mirror image (4000,3000,−5000)(4000, 3000, -5000) m for z0=8000z_0 = 8000 m. With a step limit of 2000 m and the reflection of negative depths, it reaches the true source from all three starts, in 16, 12 and 17 steps. These are measurements on this network.

Noisy times. Add Gaussian noise with σ=10\sigma = 10 ms to the six times (seed 2). The method converges in 8 steps to a point 407 m from the true source, where GTr=0G^T r = 0 to rounding; a grid search around that point finds no smaller misfit. The error is caused by the noise, not by the method: 10 ms of time is 60 m of path at 6000 m/s, and the geometry of the network enlarges it, most of all in depth.

Correctness

Each step solves the linearized least-squares problem exactly, when GG has full column rank or λ>0\lambda > 0. The step is zero exactly when the gradient −2GTr-2G^T r of the misfit is zero, so a limit of the iteration is a stationary point. When the data are exact and GG has full rank at the true model, the iteration started close enough converges quadratically. For a fixed hypocenter the best origin time is the mean of Ti−Di/vT_i - D_i/v. With all stations at depth 0, a source and its mirror image fit equally well, and GTGG^T G is singular for a source at the surface. These are theorems, proved in proofs/correctness.md. Convergence from a far start is not guaranteed, and the safeguards that help in the example are heuristics.

Proof: Each step of Geiger's method solves the linearized least-squares problem, its fixed points are the stationary points of the arrival-time misfit, it converges quadratically near an exact location, and stations on a flat surface cannot tell a source from its mirror imagefull

Setting. There are n≥4n \ge 4 stations si∈R3s_i \in \mathbb{R}^3 with observed arrival times TiT_i, and a constant velocity v>0v > 0. The model is m=(h,t0)m = (h, t_0), a hypocenter h∈R3h \in \mathbb{R}^3 and an origin time t0t_0. With Di(h)=∣h−si∣D_i(h) = |h - s_i|, the predicted times are τi(m)=t0+Di(h)/v\tau_i(m) = t_0 + D_i(h)/v, the residuals are ri(m)=Ti−τi(m)r_i(m) = T_i - \tau_i(m), and the misfit is Φ(m)=∑iri(m)2\Phi(m) = \sum_i r_i(m)^2. We assume Di(h)>0D_i(h) > 0 for all ii at the points we consider, so every τi\tau_i is smooth there. G(m)G(m) is the n×4n \times 4 Jacobian of τ\tau. Line L5 solves (GTG+λI) δ=GTr(G^T G + \lambda I)\,\delta = G^T r with the damping λ≥0\lambda \ge 0, and line L6 sets m←m+δm \leftarrow m + \delta.

Claim 1 (the Jacobian). Row ii of G(m)G(m) is ((h−si)T/(vDi), 1)\big((h - s_i)^T/(v D_i),\ 1\big): the unit vector from the station to the source divided by vv, and a 11 for the origin time.

Proof. ∇h∣h−si∣=(h−si)/∣h−si∣\nabla_h |h - s_i| = (h - s_i)/|h - s_i| for h≠sih \ne s_i, and ∂τi/∂t0=1\partial \tau_i/\partial t_0 = 1. □\square

Claim 2 (one step). If G=G(m)G = G(m) has rank 4, line L5 with λ=0\lambda = 0 returns the unique δ\delta that minimizes ∥r(m)−Gδ∥2\|r(m) - G\delta\|^2, the misfit of the linearized times τ(m)+Gδ\tau(m) + G\delta. With λ>0\lambda > 0 it returns the unique minimizer of ∥r−Gδ∥2+λ∥δ∥2\|r - G\delta\|^2 + \lambda\|\delta\|^2, for every GG.

Proof. ∥r−Gδ∥2\|r - G\delta\|^2 is a convex quadratic in δ\delta with gradient 2(GTGδ−GTr)2(G^T G\delta - G^T r). With rank 4, GTGG^T G is positive definite, so the zero of the gradient is unique and is the minimizer. With λ>0\lambda > 0 the Hessian is 2(GTG+λI)2(G^T G + \lambda I), positive definite for any GG. □\square

Claim 3 (fixed points). ∇Φ(m)=−2 G(m)Tr(m)\nabla\Phi(m) = -2\,G(m)^T r(m). So line L5 returns δ=0\delta = 0 if and only if ∇Φ(m)=0\nabla\Phi(m) = 0, for every λ≥0\lambda \ge 0 for which the system is solvable. A limit of the iteration at which GG has rank 4 (or λ>0\lambda > 0) is a stationary point of Φ\Phi.

Proof. ∇Φ=∑i2ri∇ri=−2∑iri∇τi=−2GTr\nabla\Phi = \sum_i 2 r_i \nabla r_i = -2\sum_i r_i \nabla\tau_i = -2G^T r. The matrix GTG+λIG^T G + \lambda I is invertible in the cases named, so δ=0\delta = 0 exactly when GTr=0G^T r = 0. If mk→m∗m_k \to m^\ast, then δk=mk+1−mk→0\delta_k = m_{k+1} - m_k \to 0, and by continuity of GG, rr and the inverse near m∗m^\ast, δ(m∗)=0\delta(m^\ast) = 0. □\square

A stationary point can be a local minimum, a saddle point, or the global minimum; the claim does not say which. The code does not check that Φ\Phi decreases; the safeguards max_step and keep_below_surface are heuristics, and the tests measure that they help.

Claim 4 (local quadratic convergence for exact data). Let λ=0\lambda = 0. Suppose the data are exact for some m∗m^\ast, that is r(m∗)=0r(m^\ast) = 0, with all Di(h∗)>0D_i(h^\ast) > 0 and G(m∗)G(m^\ast) of rank 4. Then there are ε>0\varepsilon > 0 and KK such that for ∥m−m∗∥<ε\|m - m^\ast\| < \varepsilon the step gives ∥m+δ−m∗∥≤K ∥m−m∗∥2\|m + \delta - m^\ast\| \le K\,\|m - m^\ast\|^2. So the iteration started close enough converges to m∗m^\ast, and the error is squared at each step, up to the factor KK.

Proof. Choose ε\varepsilon so that on the ball BB of radius ε\varepsilon around m∗m^\ast all Di>0D_i > 0, GG has rank 4 and ∥(GTG)−1GT∥≤C1\|(G^T G)^{-1} G^T\| \le C_1; this is possible because these hold at m∗m^\ast and depend continuously on mm. The second derivatives of the τi\tau_i are bounded on BB, so Taylor's theorem gives τ(m∗)=τ(m)+G(m) e+ρ\tau(m^\ast) = \tau(m) + G(m)\,e + \rho with e=m∗−me = m^\ast - m and ∥ρ∥≤C2∥e∥2\|\rho\| \le C_2\|e\|^2. Since T=τ(m∗)T = \tau(m^\ast), r(m)=G(m) e+ρr(m) = G(m)\,e + \rho, and line L5 gives δ=e+(GTG)−1GTρ\delta = e + (G^T G)^{-1} G^T \rho. The new error is e−δ=−(GTG)−1GTρe - \delta = -(G^T G)^{-1}G^T\rho, of norm at most C1C2∥e∥2C_1 C_2 \|e\|^2. With K=C1C2K = C_1 C_2 and ε≤1/(2K)\varepsilon \le 1/(2K) the error halves at least at each step, so the iterates stay in BB and converge. □\square

With noisy data, r(m∗)≠0r(m^\ast) \ne 0 at the minimizer, and Gauss-Newton converges only linearly in general, at a rate that depends on the size of the residuals; it can fail when they are large. Then Claim 3 still applies.

Claim 5 (the best origin time). For a fixed hypocenter hh, the t0t_0 that minimizes Φ\Phi is the mean of Ti−Di(h)/vT_i - D_i(h)/v, which the function best_origin_time returns.

Proof. Φ=∑i(ci−t0)2\Phi = \sum_i (c_i - t_0)^2 with ci=Ti−Di(h)/vc_i = T_i - D_i(h)/v, a quadratic in t0t_0 with derivative −2∑i(ci−t0)-2\sum_i (c_i - t_0), which is zero at the mean. □\square

Claim 6 (the mirror ambiguity). If every station has depth 00, then τ(x,y,−z,t0)=τ(x,y,z,t0)\tau(x, y, -z, t_0) = \tau(x, y, z, t_0), so Φ\Phi takes the same value at a source and at its mirror image above the surface. For a source at depth z=0z = 0, the depth column of GG is zero, so GTGG^T G is singular.

Proof. With si=(ai,bi,0)s_i = (a_i, b_i, 0), Di2=(x−ai)2+(y−bi)2+z2D_i^2 = (x - a_i)^2 + (y - b_i)^2 + z^2 does not change when zz changes sign. By Claim 1 the depth entry of row ii is (z−0)/(vDi)=0(z - 0)/(v D_i) = 0 at z=0z = 0. □\square

So with stations on a flat surface the data cannot decide between zz and −z-z, the iteration may converge to the mirror image, and replacing z<0z < 0 by −z-z, as keep_below_surface does, does not change Φ\Phi. In practice stations at different elevations, or a velocity that changes with depth, remove the exact symmetry, but the problem stays poorly conditioned near it.

Claim 7 (cost). One step costs O(n)O(n): O(n)O(n) for the times, the residuals and the Jacobian, O(16n)O(16 n) for GTGG^T G and GTrG^T r, and O(1)O(1) for the 4×44 \times 4 solve. kk steps cost O(kn)O(k n), with O(n)O(n) extra space.

Proof. Each of the nn rows needs one distance. GTGG^T G has 16 entries, each a sum of nn products. A dense solve of fixed size 4 costs a fixed number of operations. □\square

Complexity

In the real-RAM model each step costs O(n)O(n): nn distances, nn Jacobian rows, the 4×44 \times 4 matrix GTGG^T G in O(16n)O(16 n), and a solve of fixed size. With kk steps the total is O(kn)O(k n), and the extra space is O(n)O(n). Near the solution with exact data, the number of steps to reach a precision ϵ\epsilon grows like log⁡log⁡(1/ϵ)\log\log(1/\epsilon). With a 3D velocity model the cost is dominated by the travel time computation.

Properties

  • Gauss-Newton: quadratic convergence near an exact fit (a theorem, Claim 4), linear or no convergence with large residuals.
  • The depth and the origin time trade off: for a source deep below a small network, the depth and time columns of GG are nearly parallel. For five stations around a source at 10 km depth, the condition number of the scaled GTGG^T G is 2.4×1082.4 \times 10^8 for an aperture of 2 km and 1.3×1061.3 \times 10^6 for 30 km (a measurement; the network has all stations at about the same distance from the epicenter, which makes both large).
  • A station near the epicenter constrains the depth best, since its ray is close to vertical (a heuristic).
  • The result is only as good as the velocity model: an error in vv moves the location systematically, which noise analysis does not show.

Variants and improvements

  • Damped steps (Levenberg-Marquardt) and step limits, for a far start.
  • Weighted least squares with the pick uncertainties, and robust norms, such as ℓ1\ell_1, against wrong picks.
  • Grid search or global search over the hypocenter with the best origin time at each point, which avoids local minima at a higher cost.
  • Joint hypocenter determination: locate many events together with station corrections.
  • Simultaneous inversion for hypocenters and velocity structure, as in Aki and Lee (1976), which leads to local earthquake tomography.
  • Relative location of nearby events from time differences, which cancels most of the velocity model error.

When to use it

Use it for routine location of local and regional earthquakes, and of induced events in mines and reservoirs, when a velocity model is available and a reasonable start exists, for example the station with the earliest arrival. Use a grid search first when the network is sparse or the start is poor.

Pitfalls

  • Stations all on one side of the source, or far from it compared with its depth, make GTGG^T G nearly singular, and the step is long and unreliable.
  • A start too far away can give a step to a negative depth, a mirror solution, or divergence, as in the example.
  • With fewer than four stations, or with stations on a line, the problem is underdetermined.
  • A wrong velocity model gives a precise but wrong location; the formal error from (GTG)−1(G^T G)^{-1} does not include it.
  • Mixing P and S picks needs separate velocities; using one velocity for both gives systematic errors.

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.

geiger_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geiger-method/. The authors are listed in prov/9PWX4B.jsonl.
"""Geiger's method: earthquake location by Gauss-Newton on arrival times.

Stations s_i = (x, y, z) in m (z positive down) record P arrival times T_i
in s. In a medium with the constant velocity v, the predicted time from a
source at h = (x, y, z) with origin time t0 is t0 + |h - s_i| / v. Each step
linearizes the times around the current guess and solves the normal
equations G^T G dm = G^T r for the update dm = (dx, dy, dz, dt0).
"""

import math

import imgla as la


def distance(h, s):
    return math.sqrt(sum((a - b) ** 2 for a, b in zip(h, s)))


def predicted_times(m, stations, v):
    """t0 + |h - s_i| / v for the model m = (x, y, z, t0)."""
    h, t0 = m[:3], m[3]
    return [t0 + distance(h, s) / v for s in stations]


def jacobian(m, stations, v):
    """Rows ((x - s_x) / (v D), (y - s_y) / (v D), (z - s_z) / (v D), 1), D = |h - s_i|."""
    h = m[:3]
    rows = []
    for s in stations:
        d = distance(h, s)
        rows.append([(h[0] - s[0]) / (v * d), (h[1] - s[1]) / (v * d), (h[2] - s[2]) / (v * d), 1.0])
    return rows


def misfit(m, stations, times, v):
    """The sum of squared residuals sum_i (T_i - predicted_i)^2."""
    return sum((t - p) ** 2 for t, p in zip(times, predicted_times(m, stations, v)))


def geiger(stations, times, v, m0, iters=20, damping=0.0, tol=1e-10,
           max_step=None, keep_below_surface=False):
    """Locate a source. Returns (m, history of misfits).

    With the defaults this is plain Gauss-Newton, as Geiger proposed. Three
    safeguards are heuristics and are off by default: damping > 0 adds
    damping * I to G^T G (a Levenberg step); max_step (in m) scales the
    update down so that the hypocenter moves at most that far; and
    keep_below_surface replaces a negative depth z by -z, which gives the
    same times when every station is at z = 0. The loop stops when the
    update is shorter than tol (in m and s) or after iters steps.
    """
    m = list(m0)  # @line L1
    history = [misfit(m, stations, times, v)]
    for _ in range(iters):  # @line L2
        pred = predicted_times(m, stations, v)
        r = [t - p for t, p in zip(times, pred)]  # @line L3
        g = jacobian(m, stations, v)  # @line L4
        gt = la.transpose(g)
        normal = la.matmul(gt, g)
        for i in range(4):
            normal[i][i] += damping
        dm = la.solve(normal, la.matvec(gt, r))  # @line L5
        if max_step is not None:
            size = math.sqrt(dm[0] ** 2 + dm[1] ** 2 + dm[2] ** 2)
            if size > max_step:
                dm = [c * max_step / size for c in dm]
        m = [a + b for a, b in zip(m, dm)]  # @line L6
        if keep_below_surface and m[2] < 0.0:
            m[2] = -m[2]
        history.append(misfit(m, stations, times, v))
        if max(abs(dm[0]), abs(dm[1]), abs(dm[2])) < tol and abs(dm[3]) < tol:
            break
    return m, history  # @line L7


def best_origin_time(h, stations, times, v):
    """For a fixed hypocenter h the least-squares origin time is the mean of T_i - D_i / v."""
    return sum(t - distance(h, s) / v for t, s in zip(times, stations)) / len(times)
imgla.py 259 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/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).

A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""

import math


def _flat(x):
    """Flatten a list of rows (an image) into one list; a vector is returned as is."""
    if x and isinstance(x[0], (list, tuple)):
        return [v for row in x for v in row]
    return x


def zeros(m, n):
    """The m x n zero matrix."""
    return [[0.0] * n for _ in range(m)]


def eye(n):
    """The n x n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1.0
    return out


def transpose(a):
    """A^T."""
    return [list(col) for col in zip(*a)]


def conj_transpose(a):
    """A^H, the conjugate transpose."""
    return [[v.conjugate() for v in col] for col in zip(*a)]


def matmul(a, b):
    """The product A B."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """The product A x."""
    return [sum(v * w for v, w in zip(row, x)) for row in a]


def rmatvec(a, y):
    """The product A^H y."""
    n = len(a[0]) if a else 0
    out = [0.0] * n
    for row, yi in zip(a, y):
        if yi == 0:
            continue
        for j, v in enumerate(row):
            out[j] += v.conjugate() * yi
    return out


def dot(u, v):
    """<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
    return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))


def norm2(x):
    """The Euclidean norm. Images (lists of rows) are flattened."""
    return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))


def solve(a, b):
    """Solve A x = b by Gaussian elimination with partial pivoting.

    b is a vector or a matrix (a list of rows). A must be square and
    nonsingular; a zero pivot raises ValueError. Fractions stay exact.
    """
    n = len(a)
    vec = not (b and isinstance(b[0], (list, tuple)))
    rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
    m = [list(row) + rhs[i] for i, row in enumerate(a)]
    w = len(m[0])
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        piv = m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / piv
            if f != 0:
                mr, mc = m[r], m[c]
                for j in range(c, w):
                    mr[j] -= f * mc[j]
    x = [[0.0] * (w - n) for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(w - n):
            s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def cholesky(a):
    """Lower triangular L with A = L L^H for a Hermitian positive definite A."""
    n = len(a)
    low = zeros(n, n)
    for j in range(n):
        d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
        d = d.real if isinstance(d, complex) else d
        if not d > 0:
            raise ValueError("matrix is not positive definite")
        ljj = math.sqrt(d)
        low[j][j] = ljj
        for i in range(j + 1, n):
            s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
            low[i][j] = s / ljj
    return low


def cho_solve(low, b):
    """Solve (L L^H) x = b, with L from cholesky."""
    n = len(low)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
        x[i] = s / low[i][i].conjugate()
    return x


def _rot_params(app, aqq, apq):
    """c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
    theta = (aqq - app) / (2.0 * apq)
    t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
    c = 1.0 / math.sqrt(1.0 + t * t)
    return c, c * t


def sym_eig(a, tol=1e-15, max_sweeps=100):
    """Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.

    Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
    """
    n = len(a)
    m = [[float(v) for v in row] for row in a]
    q = eye(n)
    for _ in range(max_sweeps):
        off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        scale = sum(m[i][i] ** 2 for i in range(n)) + off
        if off <= (tol * tol) * scale or off == 0.0:
            break
        for p in range(n - 1):
            for r in range(p + 1, n):
                apq = m[p][r]
                if apq == 0.0:
                    continue
                c, s = _rot_params(m[p][p], m[r][r], apq)
                for k in range(n):
                    mkp, mkr = m[k][p], m[k][r]
                    m[k][p] = c * mkp - s * mkr
                    m[k][r] = s * mkp + c * mkr
                mp, mr = m[p], m[r]
                for k in range(n):
                    mpk, mrk = mp[k], mr[k]
                    mp[k] = c * mpk - s * mrk
                    mr[k] = s * mpk + c * mrk
                m[p][r] = m[r][p] = 0.0
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - s * qkr
                    q[k][r] = s * qkp + c * qkr
    order = sorted(range(n), key=lambda i: m[i][i])
    w = [m[i][i] for i in order]
    qs = [[q[k][i] for i in order] for k in range(n)]
    return w, qs


def _complete(cols, m):
    """Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
    for idx, col in enumerate(cols):
        if any(v != 0.0 for v in col):
            continue
        for e in range(m):
            cand = [0.0] * m
            cand[e] = 1.0
            for _ in range(2):
                for jdx, other in enumerate(cols):
                    if jdx == idx or not any(v != 0.0 for v in other):
                        continue
                    h = sum(a * b for a, b in zip(other, cand))
                    cand = [a - h * b for a, b in zip(cand, other)]
            nrm = math.sqrt(sum(v * v for v in cand))
            if nrm > 0.5:
                cols[idx] = [v / nrm for v in cand]
                break
    return cols


def svd(a, tol=1e-15, max_sweeps=100):
    """Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).

    Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
    descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
    """
    m, n = len(a), len(a[0])
    if m < n:
        v, s, u = svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
    vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
    for _ in range(max_sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                cp, cr = cols[p], cols[r]
                alpha = sum(x * x for x in cp)
                beta = sum(x * x for x in cr)
                gamma = sum(x * y for x, y in zip(cp, cr))
                if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                c, s = _rot_params(alpha, beta, gamma)
                cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
                cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
                vp, vr = vcols[p], vcols[r]
                vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
                vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
        if not rotated:
            break
    sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
    # A column below 1e-150 times the largest one is zero to working precision;
    # its squares underflow, so its direction carries no information.
    floor = max(sig) * 1e-150 if sig else 0.0
    sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
    order = sorted(range(n), key=lambda j: -sig[j])
    s_out = [sig[j] for j in order]
    ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
    ucols = _complete(ucols, m)
    u = [[ucols[j][i] for j in range(n)] for i in range(m)]
    v = [[vcols[j][i] for j in order] for i in range(n)]
    return u, s_out, v


def adjoint_gap(apply_a, apply_ah, x, y):
    """|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.

    x and y may be vectors or images (lists of rows). If the denominator is
    zero, the absolute gap is returned.
    """
    ax = apply_a(x)
    gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
    den = norm2(ax) * norm2(y)
    return gap / den if den > 0.0 else gap
test_geiger_method.py 102 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/geiger-method/. The authors are listed in prov/9PWX4B.jsonl.

import random

import imgla as la
from geiger_method import (
    best_origin_time,
    distance,
    geiger,
    jacobian,
    misfit,
    predicted_times,
)

V = 6000.0
NET5 = [(0.0, 0.0, 0.0), (10000.0, 0.0, 0.0), (0.0, 10000.0, 0.0),
        (10000.0, 10000.0, 0.0), (5000.0, 12000.0, 0.0)]
NET6 = NET5 + [(3000.0, 4000.0, 0.0)]
TRUE = [4000.0, 3000.0, 5000.0, 0.5]
START = [4500.0, 3500.0, 7000.0, 0.4]


def test_page_example_converges_quadratically():
    times = predicted_times(TRUE, NET6, V)
    assert [round(t, 4) for t in times] == [1.6785, 1.8944, 2.0811, 2.248, 2.224, 1.366]
    errs = []
    for k in range(5):
        m, _ = geiger(NET6, times, V, START, iters=k)
        errs.append(distance(m[:3], TRUE[:3]))
    assert 290.0 < errs[1] < 295.0
    assert 4.7 < errs[2] < 4.9
    assert errs[3] < 2e-3
    assert errs[4] < 1e-8


def test_without_the_near_station_the_first_step_overshoots():
    times = predicted_times(TRUE, NET5, V)
    m, _ = geiger(NET5, times, V, START, iters=1)
    assert m[2] < 0.0


def test_safeguards_recover_from_a_far_start():
    times = predicted_times(TRUE, NET5, V)
    for z0 in (2000.0, 8000.0, 15000.0):
        m, _ = geiger(NET5, times, V, [5000.0, 5000.0, z0, 0.0], iters=30,
                      max_step=2000.0, keep_below_surface=True)
        assert distance(m[:3], TRUE[:3]) < 1e-6
        assert abs(m[3] - TRUE[3]) < 1e-9


def test_jacobian_matches_finite_differences():
    rng = random.Random(1)
    for _ in range(10):
        m = [rng.uniform(0.0, 10000.0), rng.uniform(0.0, 10000.0), rng.uniform(1000.0, 20000.0),
             rng.uniform(-1.0, 1.0)]
        g = jacobian(m, NET6, V)
        for c, h in ((0, 0.01), (1, 0.01), (2, 0.01), (3, 1e-6)):
            mp, mm = list(m), list(m)
            mp[c] += h
            mm[c] -= h
            fd = [(a - b) / (2 * h) for a, b in zip(predicted_times(mp, NET6, V), predicted_times(mm, NET6, V))]
            assert max(abs(a - row[c]) for a, row in zip(fd, g)) < 1e-9


def test_noisy_times_reach_the_least_squares_minimum():
    rng = random.Random(2)
    times = [t + rng.gauss(0.0, 0.01) for t in predicted_times(TRUE, NET6, V)]
    m, hist = geiger(NET6, times, V, START, iters=30)
    # The gradient G^T r is zero at the solution.
    r = [t - p for t, p in zip(times, predicted_times(m, NET6, V))]
    gtr = la.rmatvec(jacobian(m, NET6, V), r)
    assert max(abs(c) for c in gtr[:3]) < 1e-12
    assert abs(gtr[3]) < 1e-12
    # A grid search over the hypocenter, with the best origin time, never does better.
    best = float("inf")
    for i in range(-5, 6):
        for j in range(-5, 6):
            for k in range(-5, 6):
                h = [m[0] + 40.0 * i, m[1] + 40.0 * j, m[2] + 80.0 * k]
                t0 = best_origin_time(h, NET6, times, V)
                best = min(best, misfit(h + [t0], NET6, times, V))
    assert hist[-1] <= best + 1e-15
    assert distance(m[:3], TRUE[:3]) < 500.0


def test_best_origin_time_is_the_mean():
    times = predicted_times(TRUE, NET6, V)
    assert abs(best_origin_time(TRUE[:3], NET6, times, V) - TRUE[3]) < 1e-12


def test_small_aperture_couples_depth_and_origin_time():
    # A deep source under a small network: the depth and origin-time columns of G
    # are nearly parallel, so G^T G is badly conditioned.
    def cond(aperture):
        st = [(aperture * c, aperture * s, 0.0) for c, s in ((1, 0), (0, 1), (-1, 0), (0, -1), (0.7, 0.7))]
        g = jacobian([0.0, 0.0, 10000.0, 0.0], st, V)
        scaled = [[row[0] * V, row[1] * V, row[2] * V, row[3]] for row in g]
        w, _ = la.sym_eig(la.matmul(la.transpose(scaled), scaled))
        return w[-1] / w[0]

    assert cond(2000.0) > 50.0 * cond(30000.0)

History

Geiger (1910) published the method in the Nachrichten of the Göttingen Society of Sciences, and an English translation appeared in the Bulletin of St. Louis University in 1912. He linearized the travel times around a trial focus and origin time and corrected the trial by least squares, repeating until the corrections were small. Each step needs the solution of a small linear system, which was laborious by hand; with digital computers the same linearized step became the core of many earthquake location programs. Aki and Lee (1976) extended the linearization to the velocity structure, solving for hypocenters and velocities together, an early form of local earthquake tomography.

References

  1. Ludwig Geiger, Herdbestimmung bei Erdbeben aus den Ankunftszeiten, Nachrichten der Gesellschaft der Wissenschaften zu Goettingen, 1910, 331 to 349, the location of the focus and the origin time from arrival times by repeated linearized least-squares corrections
  2. Ludwig Geiger, Probability method for the determination of earthquake epicenters from the arrival time only, Bulletin of St. Louis University 8(1), 1912, 60 to 71, the English translation of the 1910 paper
  3. Peter M. Shearer, Introduction to Seismology, second edition, Cambridge University Press, 2009, Chapter 5 (inversion of travel time data), the section on earthquake location
  4. Keiiti Aki and W. H. K. Lee, Determination of three-dimensional velocity anomalies under a seismic array using first P arrival times from local earthquakes, 1. A homogeneous initial model, Journal of Geophysical Research 81(23), 1976, 4381 to 4399, the joint linearized inversion for hypocenters and velocity structure from local arrival times

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example