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: Tomography Resolution Tests

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 seismic tomography using travel time residuals.

We start by defining the grid, generating our two velocity models - checkerboard vs impulse, generating random seismic rays.

Next, we complete our inversion by defining the G matrix, building a Laplacian operator for smoothing, and defining both the inverse and forward models for our plotting.

The final step combines everything into one workflow/plot.

It also includes widgets so you can interactively adjust:

  • the number of travel time rays

  • random data noise

  • the damping parameter

  • model smoothness

  • the model type (checkerboard versus impulse

Source
# Install dependencies (for Google Colab or missing packages)
import sys
import subprocess

# Detect environment
try:
    import google.colab
    IN_COLAB = True
    print("Running in Google Colab")
except ImportError:
    IN_COLAB = False
    print("Running in local environment")

# Required packages (module_name : pip_name)
required_packages = {
    'numpy': 'numpy',
    'matplotlib': 'matplotlib',
    'ipywidgets': 'ipywidgets',
    'IPython': 'ipython',
    'scipy': 'scipy'
}

missing_packages = []

# Check for missing packages
for module_name, pip_name in required_packages.items():
    try:
        __import__(module_name)
        print(f"✓ {module_name} is already installed")
    except ImportError:
        missing_packages.append(pip_name)
        print(f"✗ {module_name} not found")

# Install if needed
if missing_packages:
    print(f"\nInstalling: {', '.join(missing_packages)}")

    if IN_COLAB:
        subprocess.check_call(["pip", "install", "-q"] + missing_packages)
    else:
        subprocess.check_call([sys.executable, "-m", "pip", "install"] + missing_packages)

    print("✓ Installation complete!")

else:
    print("\n✓ All required packages are installed!")

# Imports (run after install)
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython.display import display, clear_output
from scipy.sparse import lil_matrix, vstack, eye, csr_matrix
from scipy.sparse.linalg import lsqr
from ipywidgets import interact, interactive_output, VBox, HBox

# Matplotlib inline for notebooks
try:
    get_ipython().run_line_magic('matplotlib', 'inline')
except:
    pass

print("\n✓ All imports successful!")
Running in local environment
✓ numpy is already installed
✓ matplotlib is already installed
✓ ipywidgets is already installed
✓ IPython is already installed
✓ scipy is already installed

✓ All required packages are installed!

✓ All imports successful!
"""
Model Definitions
"""

"""
Grid definition
---
We'll hold the tomography grid static over the whole demo.
"""
nx, ny = 20, 20
n_model = nx * ny

def index(ix, iy):
    return iy * nx + ix

"""
Generate velocity models
---
Here we define functions to generate a checkerboard velocity model and an impulse velocity model
"""
def checkerboard(nx, ny, size=4, amp=1.0):
    model = np.zeros((ny, nx))
    for i in range(ny):
        for j in range(nx):
            if ((i // size) + (j // size)) % 2 == 0:
                model[i, j] = amp
            else:
                model[i, j] = -amp
    return model.flatten()

def impulse(nx, ny, ix0=10, iy0=10, amp=1.0):
    model = np.zeros(nx * ny)
    model[index(ix0, iy0)] = amp
    return model

"""
Generate seismic rays
---
Here we define a function that will generate random seismic rays over the tomographic model
"""
def generate_rays(n_rays):
    sources = []
    receivers = []
    
    for _ in range(n_rays):
        side_src = np.random.choice(['left','right','top','bottom'])
        side_rec = np.random.choice(['left','right','top','bottom'])
        
        # Avoid same-side rays (optional but recommended)
        while side_rec == side_src:
            side_rec = np.random.choice(['left','right','top','bottom'])
        
        def random_point(side):
            if side == 'left':
                return [0, np.random.uniform(0, ny)]
            elif side == 'right':
                return [nx, np.random.uniform(0, ny)]
            elif side == 'bottom':
                return [np.random.uniform(0, nx), 0]
            elif side == 'top':
                return [np.random.uniform(0, nx), ny]
        
        sources.append(random_point(side_src))
        receivers.append(random_point(side_rec))
    
    return np.array(sources), np.array(receivers)

"""
Plot the velocity model
"""
def plot_model(ax, m, title):
    vmax = np.max(np.abs(m)) + 1e-10

    im = ax.imshow(
        m.reshape(ny, nx),
        cmap='seismic',
        vmin=-vmax,
        vmax=vmax,
        extent=[0, nx, ny, 0]
    )

    ax.set_title(title)
    ax.set_xlabel("Distance")
    ax.set_ylabel("Depth")
    return im
"""
Generate the G Matrix
---
Here we define a function that calculates the G matrix i.e. the travel time of each ray in each tomographic grid cell
"""
def build_G(sources, receivers, nsteps=100):
    G = lil_matrix((len(sources), n_model))
    
    for i in range(len(sources)):
        x = np.linspace(sources[i][0], receivers[i][0], nsteps)
        y = np.linspace(sources[i][1], receivers[i][1], nsteps)
        
        for j in range(nsteps):
            ix = int(np.clip(x[j], 0, nx-1))
            iy = int(np.clip(y[j], 0, ny-1))
            G[i, index(ix, iy)] += 1
            
    return G.tocsr()

"""
Build a Lapacian Operator
---
Here we define a function that calculates the Lapacian matrix to tests model smoothness
"""
def build_laplacian(nx, ny):
    """
    2D 5-point Laplacian operator on a grid
    """
    N = nx * ny
    L = lil_matrix((N, N))

    def idx(i, j):
        return j * nx + i

    for j in range(ny):
        for i in range(nx):

            k = idx(i, j)

            L[k, k] = -4

            if i > 0:
                L[k, idx(i-1, j)] = 1
            if i < nx-1:
                L[k, idx(i+1, j)] = 1
            if j > 0:
                L[k, idx(i, j-1)] = 1
            if j < ny-1:
                L[k, idx(i, j+1)] = 1

    return L.tocsr()

"""
Define the regularized inversion 
"""
def invert(G, d, nx, ny, damping=0.0, smoothness=0.0):

    N = G.shape[1]

    blocks = [G]
    rhs = [d]

    # --- smoothness term ---
    if smoothness > 0:
        L = build_laplacian(nx, ny)
        blocks.append(np.sqrt(smoothness) * L)
        rhs.append(np.zeros(L.shape[0]))

    # --- damping term (FIXED: sparse identity!) ---
    if damping > 0:
        I = eye(N, format='csr')   # 🔥 critical fix
        blocks.append(np.sqrt(damping) * I)
        rhs.append(np.zeros(N))

    # --- build augmented system safely ---
    G_aug = vstack(blocks)
    d_aug = np.hstack(rhs)

    return lsqr(G_aug, d_aug)[0]

"""
Define the forward model
"""
def forward(G, m, noise_level=0.0, relative=True):
    """
    Forward model: d = G m + noise

    Parameters:
    -----------
    G : (n_rays, n_cells) sparse or dense matrix
        Ray path lengths through each cell
    m : (n_cells,) array
        Model (slowness or velocity perturbation)
    noise_level : float
        Standard deviation of noise (relative or absolute)
    relative : bool
        If True, noise scales with signal strength

    Returns:
    --------
    d : (n_rays,) array
        Synthetic travel-time data
    """

    # --- deterministic forward projection ---
    d_true = G @ m

    # --- noise model ---
    if noise_level> 0:

        if relative:
            sigma = noise_level * np.max(np.abs(d_true))
        else:
            sigma = noise_level

        noise = sigma * np.random.randn(len(d_true))
        d_obs = d_true + noise

    else:
        d_obs = d_true

    return d_obs
def run_demo(n_rays, noise_level, damping, smoothness, model_type):

    fig, axs = plt.subplots(1, 3, figsize=(15,4))

    # --- build model ---
    if model_type == 'checkerboard':
        m_true = checkerboard(nx, ny)
    else:
        m_true = impulse(nx, ny)

    sources, receivers = generate_rays(n_rays)
    G = build_G(sources, receivers)

    d = forward(G, m_true, noise_level, False)
    m_rec = invert(G, d, nx, ny, damping, smoothness)

    # --- plot models ---
    plot_model(axs[1], m_true, "True Model")
    plot_model(axs[2], m_rec, "Recovered Model")

    # --- rays ---
    for i in range(len(sources)):
        axs[0].plot(
            [sources[i,0], receivers[i,0]],
            [sources[i,1], receivers[i,1]],
            color='black',
            alpha=0.2
        )

    axs[0].set_xlim(0, nx)
    axs[0].set_ylim(ny, 0)
    axs[0].set_title("Rays n=%i" % len(sources))
    axs[0].set_xlabel('Distance')
    axs[0].set_ylabel('Depth')
    plt.show()

controls = {
    'n_rays': widgets.IntSlider(min=20, max=500, step=20, value=200,description='No. of Rays'),
    'noise_level': widgets.FloatSlider(min=0.0, max=0.5, step=0.05, value=0.01,description='Noise'),
    'damping': widgets.FloatSlider(min=0.0, max=1.0, step=0.05, value=0.1,description='Damping'),
    'smoothness': widgets.FloatSlider(min=0.0, max=1.0, step=0.05, value=0.1,description='Smoothness'),
    'model_type': widgets.Dropdown(options=['checkerboard', 'impulse'],description='Model type')
}

ui = widgets.VBox([controls['n_rays'], controls['noise_level'], controls['damping'], controls['smoothness'], controls['model_type']])


out = interactive_output(run_demo, controls)
display(ui,out)
#update()
Loading...
Loading...

Now the above seismic ray example is not physically accurate to the Earth conditions.

Typically in seismic inversion, rays will travel upward only. The example below changes this so that seismic receivers can only be located on the Earth surface (i.e. the top of our model).

"""
Generate seismic rays only from bottom to top
---
Here we define a function that will generate random seismic rays over the tomographic model.
"""
def generate_rays(n_rays):
    sources = []
    receivers = []
    
    for _ in range(n_rays):
        side_src = np.random.choice(['bottom','left','right'])
        side_rec = np.random.choice(['top'])
        
        # Avoid same-side rays (optional but recommended)
        while side_rec == side_src:
            side_rec = np.random.choice(['left','right','top','bottom'])
        
        def random_point(side):
            if side == 'left':
                return [0, np.random.uniform(0, ny)]
            elif side == 'right':
                return [nx, np.random.uniform(0, ny)]
            elif side == 'bottom':
                return [np.random.uniform(0, nx), ny]
            elif side == 'top':
                return [np.random.uniform(0, nx), 0]
        
        sources.append(random_point(side_src))
        receivers.append(random_point(side_rec))
    
    return np.array(sources), np.array(receivers)
def run_demo(n_rays, noise_level, damping, smoothness, model_type):

    fig, axs = plt.subplots(1, 3, figsize=(15,4))

    # --- build model ---
    if model_type == 'checkerboard':
        m_true = checkerboard(nx, ny)
    else:
        m_true = impulse(nx, ny)

    sources, receivers = generate_rays(n_rays)
    G = build_G(sources, receivers)

    d = forward(G, m_true, noise_level, False)
    m_rec = invert(G, d, nx, ny, damping, smoothness)

    # --- plot models ---
    plot_model(axs[1], m_true, "True Model")
    plot_model(axs[2], m_rec, "Recovered Model")

    # --- rays ---
    for i in range(len(sources)):
        axs[0].plot(
            [sources[i,0], receivers[i,0]],
            [sources[i,1], receivers[i,1]],
            color='black',
            alpha=0.2
        )

    axs[0].set_xlim(0, nx)
    axs[0].set_ylim(ny, 0)
    axs[0].set_title("Rays n=%i" % len(sources))
    axs[0].set_xlabel('Distance')
    axs[0].set_ylabel('Depth')
    plt.show()

controls = {
    'n_rays': widgets.IntSlider(min=20, max=500, step=20, value=200,description='No. of Rays'),
    'noise_level': widgets.FloatSlider(min=0.0, max=0.5, step=0.05, value=0.01,description='Noise'),
    'damping': widgets.FloatSlider(min=0.0, max=1.0, step=0.05, value=0.1,description='Damping'),
    'smoothness': widgets.FloatSlider(min=0.0, max=1.0, step=0.05, value=0.1,description='Smoothness'),
    'model_type': widgets.Dropdown(options=['checkerboard', 'impulse'],description='Model type')
}

ui = widgets.VBox([controls['n_rays'], controls['noise_level'], controls['damping'], controls['smoothness'], controls['model_type']])


out = interactive_output(run_demo, controls)
display(ui,out)
Loading...
Loading...