Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Demo: 1-D ray tracing notebook

Colab note: This notebook is designed to run on Google Colab. The first code cell installs dependencies. Open In Colab

This notebook provides several examples of travel time curves and plots for each a rows of four panels showing:

  1. Velocity model: depth on the y-axis, velocity on the x-axis

  2. Ray paths: depth on the y-axis, distance on the x-axis

  3. Range curve X(p)X(p): slowness / ray parameter on the x-axis, distance on the y-axis

  4. Delay-time curve τ(p)\tau(p): slowness / ray parameter on the x-axis, delay time on the y-axis

It also includes widgets so you can interactively adjust:

  • which model types are shown

  • the number of rays

  • overall depth

  • velocity scaling

  • whether to show a travel-time check plot

Source
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, IntSlider, FloatSlider, Checkbox, Dropdown
Source
def compute_turning_depth(z, u, p):
    """
    Estimate the turning depth for a ray with ray parameter p.

    Parameters
    ----------
    z : array-like
        Depth samples.
    u : array-like
        Slowness values u(z) at the same depths.
    p : float
        Ray parameter (horizontal slowness).

    Returns
    -------
    float or None
        Estimated turning depth z_t where u(z_t) = p.
        Returns None if the model never satisfies u >= p.
    """

    # A ray can only propagate where u >= p.
    # If this is never true, there is no turning point in the model.
    valid = u >= p
    if not np.any(valid):
        return None

    # Find the deepest depth where propagation is still allowed.
    # This is the last sampled point with u >= p.
    idx = np.where(valid)[0][-1]

    # If that point is the bottom of the model, then the ray has not turned
    # within the sampled depth range, so return the model bottom.
    if idx == len(z) - 1:
        return z[-1]

    # Bracket the turning point between the last valid point and the next point.
    z1, z2 = z[idx], z[idx + 1]
    u1, u2 = u[idx], u[idx + 1]

    # If the sampled slowness already matches p at z1, that is the turning depth.
    if np.isclose(u1, p):
        return z1

    # If u - p changes sign between adjacent samples, then the turning point
    # lies between them. Use linear interpolation to estimate where u(z) = p.
    if (u1 - p) * (u2 - p) < 0 and not np.isclose(u1, u2):
        return z1 + (p - u1) * (z2 - z1) / (u2 - u1)

    # Otherwise, just return the deepest valid sampled depth as an approximation.
    return z[idx]


def trace_model(z, v, n_p=400):
    """
    Trace a family of rays through a 1-D velocity model and compute
    X(p), T(p), tau(p), and approximate ray paths.

    Parameters
    ----------
    z : array-like
        Depth samples.
    v : array-like
        Velocity values v(z) at the same depths.
    n_p : int, optional
        Number of ray-parameter samples to evaluate.

    Returns
    -------
    dict
        Dictionary containing:
        - z        : depth samples
        - v        : velocity model
        - u        : slowness model
        - p        : sampled ray parameters
        - X        : surface-to-surface range for each p
        - T        : surface-to-surface travel time for each p
        - tau      : delay time for each p
        - z_turn   : turning depth for each p
        - ray_paths: list of (x,z) arrays for plotting rays
    """

    # Convert inputs to NumPy arrays so array math works consistently.
    z = np.asarray(z, dtype=float)
    v = np.asarray(v, dtype=float)

    # Convert velocity to slowness: u = 1 / v
    u = 1.0 / v

    # Choose a range of ray parameters.
    # The largest possible p is just below the maximum slowness in the model,
    # so that rays are close to horizontal but still propagating.
    p_max = np.max(u) * 0.995

    # The smallest p is chosen just above the minimum slowness.
    # This avoids exactly hitting singular cases at the model minimum.
    p_min = np.min(u) * 1.001

    # If the model is nearly constant velocity, the above choice may fail.
    # In that case, choose a smaller minimum p so the range is usable.
    if p_min >= p_max:
        p_min = np.min(u) * 0.9

    # Sample ray parameters from large p (shallow rays) to small p (deeper rays).
    p_vals = np.linspace(p_max, p_min, n_p)

    # Allocate arrays for results.
    X = np.full_like(p_vals, np.nan)       # surface-to-surface distance
    T = np.full_like(p_vals, np.nan)       # travel time
    tau = np.full_like(p_vals, np.nan)     # delay time
    z_turn = np.full_like(p_vals, np.nan)  # turning depth
    ray_paths = []                         # full x-z paths for plotting

    # Loop over all ray parameters.
    for j, p in enumerate(p_vals):
        # Find the turning depth where u(z) = p.
        zt = compute_turning_depth(z, u, p)

        # If no valid turning depth exists, skip this ray.
        if zt is None or np.isnan(zt):
            ray_paths.append(None)
            continue

        # Keep only the portion of the model above the turning depth.
        mask = z <= zt
        z_seg = z[mask]
        u_seg = u[mask]

        # If nothing survives, skip this ray.
        if len(z_seg) == 0:
            ray_paths.append(None)
            continue

        # If the turning depth falls between sampled depths,
        # append it explicitly so the integrals go right to the turn.
        if z_seg[-1] < zt:
            z_seg = np.r_[z_seg, zt]
            u_seg = np.r_[u_seg, p]

        # Vertical slowness:
        # eta = sqrt(u^2 - p^2)
        # This becomes zero at the turning point.
        eta = np.sqrt(np.maximum(u_seg**2 - p**2, 0.0))

        # Exclude points too close to the turning point because the integrands
        # become nearly singular there and can create numerical spikes.
        keep = eta > 1e-5

        # Need at least two points to integrate.
        if np.sum(keep) < 2:
            ray_paths.append(None)
            continue

        z_num = z_seg[keep]
        u_num = u_seg[keep]
        eta_num = eta[keep]

        # Compute half-path integrals (surface to turning point):
        #
        # X_half   = integral p / eta dz
        # T_half   = integral u^2 / eta dz
        # tau_half = integral eta dz
        #
        # Then double them because the full ray is symmetric about the turning point.
        x_half = np.trapezoid(p / eta_num, z_num)
        t_half = np.trapezoid((u_num**2) / eta_num, z_num)
        tau_half = np.trapezoid(eta_num, z_num)

        X[j] = 2.0 * x_half
        T[j] = 2.0 * t_half
        tau[j] = 2.0 * tau_half
        z_turn[j] = zt

        # Build an approximate ray path for plotting.
        # dx/dz = p / eta, so integrate that downward to get horizontal position.
        dx_dz = p / eta_num

        # Cumulative trapezoidal integration for x(z) along the downgoing branch.
        x_down = np.r_[
            0.0,
            np.cumsum(np.diff(z_num) * 0.5 * (dx_dz[:-1] + dx_dz[1:]))
        ]

        # Reflect the downgoing branch about the turning point to create
        # the upgoing branch and form a full symmetric ray path.
        x_full = np.r_[x_down, X[j] - x_down[::-1]]
        z_full = np.r_[z_num, z_num[::-1]]

        ray_paths.append((x_full, z_full))

    # Return all computed quantities in a dictionary for easy plotting and reuse.
    return {
        "z": z,
        "v": v,
        "u": u,
        "p": p_vals,
        "X": X,
        "T": T,
        "tau": tau,
        "z_turn": z_turn,
        "ray_paths": ray_paths,
    }


def first_arrivals(X, T):
    """
    Extract the first-arrival (minimum travel time) branch from T(X).

    Parameters
    ----------
    X : array-like
        Source–receiver distances.
    T : array-like
        Travel times corresponding to X.

    Returns
    -------
    X_first : ndarray
        Distances for first arrivals.
    T_first : ndarray
        Corresponding minimum travel times.

    Notes
    -----
    Because T(X) is generally multivalued, multiple travel times may exist
    at the same distance. The first arrival corresponds to the minimum
    travel time at each distance (the lower envelope of T(X)).
    """

    # Keep only finite values (exclude NaNs from invalid rays).
    valid = np.isfinite(X) & np.isfinite(T)
    Xv = X[valid]
    Tv = T[valid]

    # If no valid points exist, return empty arrays.
    if len(Xv) == 0:
        return np.array([]), np.array([])

    # Sort by distance so we can walk along the T(X) curve.
    order = np.argsort(Xv)
    Xs = Xv[order]
    Ts = Tv[order]

    # Initialize a mask for points that belong to the first-arrival branch.
    keep = np.zeros_like(Xs, dtype=bool)

    # Track the smallest travel time encountered so far.
    best = np.inf

    # Loop through distances in increasing order.
    # Keep a point only if it improves (reduces) the travel time.
    for i, t in enumerate(Ts):
        if t < best:
            keep[i] = True
            best = t

    # Return the subset of points forming the lower envelope (first arrivals).
    return Xs[keep], Ts[keep]
Source
def make_models(zmax=220.0, velocity_scale=1.0):
    """
    Construct a set of example 1-D velocity models for ray-tracing.

    Parameters
    ----------
    zmax : float, optional
        Maximum depth of the model (km).
    velocity_scale : float, optional
        Scaling factor applied to all velocities (useful for exploration).

    Returns
    -------
    dict
        Dictionary of named models, each containing (z, v) arrays:
        - z : depth values
        - v : velocity values at those depths
    """

    # ------------------------------------------------------------------
    # 1. Smooth positive gradient
    # ------------------------------------------------------------------
    # Velocity increases linearly with depth.
    # This produces smoothly curving ray paths and no sharp discontinuities.
    z1 = np.linspace(0, zmax, 1200)
    v1 = velocity_scale * (4.0 + 0.020 * z1)

    # ------------------------------------------------------------------
    # 2. Sharp increase / kinked gradient
    # ------------------------------------------------------------------
    # Piecewise-linear model with a strong velocity increase (kink),
    # mimicking a major gradient or transition zone.
    z2_nodes = np.array([0, 40, 70, 90, 130, zmax], dtype=float)
    v2_nodes = velocity_scale * np.array([4.2, 5.0, 5.5, 7.6, 8.0, 8.8], dtype=float)

    # Interpolate onto a fine depth grid for smooth integration.
    z2 = np.linspace(0, zmax, 1200)
    v2 = np.interp(z2, z2_nodes, v2_nodes)

    # ------------------------------------------------------------------
    # 3. Low-velocity zone (LVZ)
    # ------------------------------------------------------------------
    # Velocity decreases with depth over some interval, then increases again.
    # This creates:
    #   - shadow zones
    #   - gaps in allowable ray parameters
    #   - potential waveguide behavior
    z3_nodes = np.array([0, 50, 90, 140, 180, zmax], dtype=float)
    v3_nodes = velocity_scale * np.array([4.4, 5.4, 4.9, 5.2, 6.1, 6.8], dtype=float)

    z3 = np.linspace(0, zmax, 1200)
    v3 = np.interp(z3, z3_nodes, v3_nodes)

    # ------------------------------------------------------------------
    # 4. Staircase layered model
    # ------------------------------------------------------------------
    # Piecewise-constant velocity model with sharp discontinuities.
    # Depth array repeats values to create vertical jumps (step function).
    # This mimics classic layered Earth models and produces reflections
    # and simpler ray behavior.
    z4 = np.array([0, 30, 30, 70, 70, 120, 120, 180, 180, zmax], dtype=float)
    v4 = velocity_scale * np.array([4.0, 4.0, 5.0, 5.0, 6.3, 6.3, 7.5, 7.5, 8.2, 8.2], dtype=float)

    # Return all models in a dictionary for easy selection.
    return {
        "Smooth positive gradient": (z1, v1),
        "Sharp increase / kinked gradient": (z2, v2),
        "Low-velocity zone": (z3, v3),
        "Staircase layered model": (z4, v4),
    }
Source
def plot_rows(show_model_set="All four",
              n_rays=12,
              zmax=220.0,
              velocity_scale=1.0,
              n_p=350,
              show_travel_time_check=False,
              show_first_arrivals_only=True):
    """
    Plot Shearer-style multi-row summary figures for a set of 1-D velocity models.

    Parameters
    ----------
    show_model_set : str, optional
        Controls which model rows to plot. Options include:
        - "All four"
        - "Gradients only"
        - "LVZ + staircase"
        - or the name of a single model
    n_rays : int, optional
        Number of representative ray paths to draw in each ray-path panel.
    zmax : float, optional
        Maximum depth of the model (km).
    velocity_scale : float, optional
        Multiplicative factor applied to all model velocities.
    n_p : int, optional
        Number of ray-parameter samples used in ray tracing.
    show_travel_time_check : bool, optional
        If True, also plot a separate travel-time figure T(X) below the main summary.
    show_first_arrivals_only : bool, optional
        If True, plot only the first-arrival branch in the travel-time check.
        If False, plot all branches plus the first arrivals.

    Notes
    -----
    The main figure has one row per model and four columns:
        1. z(v): velocity vs depth
        2. ray paths: distance vs depth
        3. X(p): range vs ray parameter
        4. tau(p): delay time vs ray parameter
    """

    # Build the dictionary of available example models.
    models = make_models(zmax=zmax, velocity_scale=velocity_scale)

    # Select which models to include based on the user's choice.
    if show_model_set == "All four":
        names = list(models.keys())
    elif show_model_set == "Gradients only":
        names = ["Smooth positive gradient", "Sharp increase / kinked gradient"]
    elif show_model_set == "LVZ + staircase":
        names = ["Low-velocity zone", "Staircase layered model"]
    else:
        # Assume the input is the name of one specific model.
        names = [show_model_set]

    # Trace rays through each selected model.
    # Each entry contains the model name and the ray-tracing results.
    results = [(name, trace_model(*models[name], n_p=n_p)) for name in names]
    nrows = len(results)

    # Create the main figure:
    # one row per model, four columns per row.
    fig, axes = plt.subplots(nrows, 4, figsize=(17, 3.8 * nrows), squeeze=False)

    # Loop through the selected models and populate one row at a time.
    for i, (name, res) in enumerate(results):
        z = res["z"]
        v = res["v"]
        p = res["p"]
        X = res["X"]
        tau = res["tau"]
        ray_paths = res["ray_paths"]

        # --------------------------------------------------------------
        # Column 1: Velocity model z(v)
        # --------------------------------------------------------------
        ax = axes[i, 0]
        ax.plot(v, z, linewidth=2)
        ax.invert_yaxis()  # depth increases downward
        ax.set_xlabel("Velocity (km/s)")
        ax.set_ylabel("Depth (km)")
        ax.grid(True, alpha=0.3)

        # Add a column title only on the top row.
        if i == 0:
            ax.set_title("z(v)")

        # Label the row with the model name.
        ax.text(
            0.03, 0.10, name,
            transform=ax.transAxes,
            fontsize=10,
            bbox=dict(facecolor="white", alpha=0.85, edgecolor="none")
        )

        # --------------------------------------------------------------
        # Column 2: Ray paths (distance vs depth)
        # --------------------------------------------------------------
        ax = axes[i, 1]

        # Find which ray paths were successfully computed.
        valid_idx = np.where([rp is not None for rp in ray_paths])[0]

        # Plot a subset of ray paths to keep the panel readable.
        if len(valid_idx) > 0:
            select = np.linspace(
                0, len(valid_idx) - 1,
                min(n_rays, len(valid_idx))
            ).astype(int)

            for idx in valid_idx[select]:
                x_path, z_path = ray_paths[idx]
                ax.plot(x_path, z_path, linewidth=1)

        ax.invert_yaxis()
        ax.set_xlabel("Distance (km)")
        ax.set_ylabel("Depth (km)")
        ax.grid(True, alpha=0.3)

        if i == 0:
            ax.set_title("Ray paths")

        # --------------------------------------------------------------
        # Column 3: X(p) curve
        # --------------------------------------------------------------
        ax = axes[i, 2]

        # Only plot finite values (exclude invalid rays).
        mask = np.isfinite(X)
        ax.plot(p[mask], X[mask], linewidth=2)

        ax.set_xlabel("Slowness / p (s/km)")
        ax.set_ylabel("Distance X(p) (km)")
        ax.grid(True, alpha=0.3)

        if i == 0:
            ax.set_title("X(p)")

        # --------------------------------------------------------------
        # Column 4: tau(p) curve
        # --------------------------------------------------------------
        ax = axes[i, 3]

        mask = np.isfinite(tau)
        ax.plot(p[mask], tau[mask], linewidth=2)

        ax.set_xlabel("Slowness / p (s/km)")
        ax.set_ylabel(r"Delay time $\tau(p)$ (s)")
        ax.grid(True, alpha=0.3)

        if i == 0:
            ax.set_title(r"$\tau(p)$")

    # Adjust spacing so labels and titles do not overlap.
    fig.tight_layout()
    plt.show()

    # --------------------------------------------------------------
    # Optional travel-time check plot: T(X)
    # --------------------------------------------------------------
    if show_travel_time_check:
        fig, axes = plt.subplots(
            len(results), 1,
            figsize=(7, 3.2 * len(results)),
            squeeze=False
        )

        for ax, (name, res) in zip(axes[:, 0], results):
            X = res["X"]
            T = res["T"]

            # Keep only valid X,T pairs.
            mask = np.isfinite(X) & np.isfinite(T)

            if show_first_arrivals_only:
                # Plot only the lower envelope (first arrivals).
                Xf, Tf = first_arrivals(X, T)
                ax.plot(Xf, Tf, linewidth=2)
            else:
                # Plot all branches plus the extracted first arrivals.
                ax.plot(X[mask], T[mask], alpha=0.6, label="All branches")
                Xf, Tf = first_arrivals(X, T)
                ax.plot(Xf, Tf, linewidth=2, label="First arrivals")
                ax.legend()

            ax.set_title(name)
            ax.set_xlabel("Distance X (km)")
            ax.set_ylabel("Travel time T (s)")
            ax.grid(True, alpha=0.3)

        fig.tight_layout()
        plt.show()

Interactive widget view

interact(
    plot_rows,
    show_model_set=Dropdown(
        options=[
            "All four",
            "Gradients only",
            "LVZ + staircase",
            "Smooth positive gradient",
            "Sharp increase / kinked gradient",
            "Low-velocity zone",
            "Staircase layered model",
        ],
        value="All four",
        description="Models",
    ),
    n_rays=IntSlider(value=12, min=4, max=30, step=1, description="Rays"),
    zmax=FloatSlider(value=220.0, min=100.0, max=400.0, step=10.0, description="Depth"),
    velocity_scale=FloatSlider(value=1.0, min=0.7, max=1.4, step=0.05, description="Vel scale"),
    n_p=IntSlider(value=350, min=100, max=700, step=50, description="n_p"),
    show_travel_time_check=Checkbox(value=False, description="show T(X)"),
    show_first_arrivals_only=Checkbox(value=True, description="first arrivals"),
);
Loading...

Static example

plot_rows(
    show_model_set="All four",
    n_rays=12,
    zmax=220.0,
    velocity_scale=1.0,
    n_p=350,
    show_travel_time_check=False,
)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[6], line 1
----> 1 plot_rows(
      2     show_model_set="All four",
      3     n_rays=12,
      4     zmax=220.0,
      5     velocity_scale=1.0,
      6     n_p=350,
      7     show_travel_time_check=False,
      8 )

Cell In[4], line 58, in plot_rows(show_model_set, n_rays, zmax, velocity_scale, n_p, show_travel_time_check, show_first_arrivals_only)
     54     names = [show_model_set]
     56 # Trace rays through each selected model.
     57 # Each entry contains the model name and the ray-tracing results.
---> 58 results = [(name, trace_model(*models[name], n_p=n_p)) for name in names]
     59 nrows = len(results)
     61 # Create the main figure:
     62 # one row per model, four columns per row.

Cell In[2], line 164, in trace_model(z, v, n_p)
    155 eta_num = eta[keep]
    157 # Compute half-path integrals (surface to turning point):
    158 #
    159 # X_half   = integral p / eta dz
   (...)
    162 #
    163 # Then double them because the full ray is symmetric about the turning point.
--> 164 x_half = np.trapezoid(p / eta_num, z_num)
    165 t_half = np.trapezoid((u_num**2) / eta_num, z_num)
    166 tau_half = np.trapezoid(eta_num, z_num)

File ~/anaconda3/lib/python3.12/site-packages/numpy/__init__.py:333, in __getattr__(attr)
    330     "Removed in NumPy 1.25.0"
    331     raise RuntimeError("Tester was removed in NumPy 1.25.")
--> 333 raise AttributeError("module {!r} has no attribute "
    334                      "{!r}".format(__name__, attr))

AttributeError: module 'numpy' has no attribute 'trapezoid'