import tempfile
import matplotlib.pyplot as plt
import numpy as np
import pysegy
from recipes import WaveModel, layered_model
from scipy.ndimage import gaussian_filter
from devitohorizon.config import SeismicData
from devitohorizon.model.grid import get_interior_vp
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics
from devitohorizon.preprocess import (apply_preprocessing, available_preprocess_steps,
preprocess_step)
plt.rcParams["figure.dpi"] = 70
%matplotlib inline
run_dir = tempfile.mkdtemp(prefix="preprocess_tutorial_")
def show_gathers(gathers, titles, dt_ms, dx):
"""Plot a row of shot gathers with pysegy."""
fig, axes = plt.subplots(1, len(gathers), figsize=(3.6 * len(gathers), 4))
for ax, gather, title in zip(np.atleast_1d(axes), gathers, titles, strict=True):
plt.sca(ax)
pysegy.plot_sdata(gather, (dt_ms / 1000.0, dx), new_fig=False, name=title)
plt.tight_layout()
plt.show()
def show_models(models, titles, spacing, vmin, vmax):
"""Plot a row of interior velocity models on one color scale."""
fig, axes = plt.subplots(1, len(models), figsize=(4.2 * len(models), 3.2))
for ax, vp, title in zip(np.atleast_1d(axes), models, titles, strict=True):
plt.sca(ax)
image = pysegy.plot_velocity(vp.T, (spacing[1], spacing[0]), new_fig=False,
name=title)
image.set_clim(vmin, vmax)
plt.tight_layout()
plt.show()Custom Data Preprocessing
Every shot goes through the preprocess config before the misfit compares it with the synthetic. The config is a dict of named sections, applied to the observed and the synthetic alike:
| Section | What it does |
|---|---|
filter |
Butterworth low/high/band-pass (also applied to the source wavelet) |
differentiate / integrate |
fractional time derivative or integral |
mute |
direct-arrival or reflection mute, or a list of them |
offset |
keep a range of source-receiver offsets |
gain |
time-power gain or AGC |
Without further instructions the configured sections run in that order. A steps list lets you choose the order and add your own steps, without subclassing or editing the package.
This tutorial adds a despiking step for observed data contaminated by noise bursts, shows why its position in the chain matters, and runs it through a real inversion with SPG.fwi.
1. A small survey with noise bursts
A three-layer model is the truth and a smoothed copy of it is the starting model. Five shots are modeled on the true model, then each observed gather gets 60 isolated spikes, 3 to 8 times the strongest arrival, the kind of burst noise a land recording picks up from traffic or a bad channel.
shape, spacing = (151, 81), (10.0, 10.0) # (nx, nz), metres
nbl, space_order, tn, f0 = 20, 8, 1.0, 10.0 # tn in s, f0 in Hz
nt, dt_ms = 251, 4.0
true_model = layered_model("iso-acoustic", nlayers=3, shape=shape, spacing=spacing,
nbl=nbl, space_order=space_order)
vp_true = get_interior_vp(true_model)
init_model = WaveModel(true_model.origin, spacing, shape, space_order, nbl=nbl,
bcs="damp", vp=gaussian_filter(vp_true, 10.0, mode="nearest"))
rec_pos = np.array([[i * spacing[0], 10.0] for i in range(shape[0])], dtype=np.float32)
true_physics = DevitoPhysics(nbl=nbl, space_order=space_order, tn=tn, parameters=("m",),
wavelet={"type": "ricker", "f0": f0},
run_name=f"{run_dir}/true")
true_physics.model = true_model
rng = np.random.default_rng(42)
shots = []
for shot_id, source_x in enumerate([150.0, 450.0, 750.0, 1050.0, 1350.0]):
src_pos = np.array([[source_x, 10.0]], dtype=np.float32)
empty = SeismicData(shot_id=shot_id, data=np.zeros((nt, shape[0]), np.float32),
src_pos=src_pos, rec_pos=rec_pos, dt=dt_ms)
observed = true_physics.simulate_shot(empty)["synthetic"]
n_spikes = 60
spike_t = rng.integers(0, observed.shape[0], n_spikes)
spike_r = rng.integers(0, observed.shape[1], n_spikes)
observed[spike_t, spike_r] += (np.abs(observed).max() * rng.uniform(3, 8, n_spikes)
* rng.choice([-1, 1], n_spikes))
shots.append(SeismicData(shot_id=shot_id, data=observed.astype(np.float32),
src_pos=src_pos, rec_pos=rec_pos, dt=dt_ms))
show_models([vp_true, get_interior_vp(init_model)], ["True vp [km/s]", "Initial vp"],
spacing, vp_true.min(), vp_true.max())
show_gathers([shots[2].data], ["Observed, shot 2"], dt_ms, spacing[0])

2. Choosing the order of the built-in steps
steps names the sections in the order they should run. A built-in step’s parameters always stay in its section, so the list contains only names. Listing the default order explicitly gives exactly the default result.
bandpass = {"filter": {"type": "bandpass", "fmin": 2.0, "fmax": 12.0}}
gain = {"gain": {"type": "time", "power": 1.0}}
default = apply_preprocessing(shots[2].data, dt_ms, {**bandpass, **gain})
listed = apply_preprocessing(shots[2].data, dt_ms,
{**bandpass, **gain, "steps": ["filter", "gain"]})
print("default order == steps ['filter', 'gain']:", np.array_equal(default, listed))default order == steps ['filter', 'gain']: True
3. A custom despiking step
A step is a function of the gather data (nt x nrec), the sample interval dt in seconds, and the source and receiver coordinates (None when the caller has none). It returns a gather of the same shape. Any other keys of the step dict arrive as keyword arguments.
@preprocess_step(name) registers it under a name, so a config (including a JSON one) can refer to it. This one clips every sample to a multiple of its trace’s robust amplitude, the median absolute value scaled to a standard deviation.
@preprocess_step("despike")
def despike(data, dt, src_pos, rec_pos, *, threshold=4.0):
"""Clip samples beyond `threshold` robust standard deviations of their trace."""
scale = np.median(np.abs(data), axis=0, keepdims=True) / 0.6745 + 1e-30
return np.clip(data, -threshold * scale, threshold * scale)
available_preprocess_steps()['filter',
'differentiate',
'integrate',
'mute',
'offset',
'gain',
'despike']
Order matters
A spike is broadband. Band-pass it and it becomes a long, smooth wavelet that a clip can no longer tell apart from signal. Run the despike before the filter and the spikes are gone; run it after and the stripes stay.
raw = shots[2].data
filtered = apply_preprocessing(raw, dt_ms, bandpass)
despike_first = apply_preprocessing(raw, dt_ms,
{**bandpass, "steps": ["despike", "filter"]})
filter_first = apply_preprocessing(raw, dt_ms,
{**bandpass, "steps": ["filter", "despike"]})
show_gathers([raw, filtered, despike_first, filter_first],
["Raw", "Filter only", "Despike, then filter", "Filter, then despike"],
dt_ms, spacing[0])
4. In the physics: observed only
In DevitoPhysics the preprocessing runs on both the observed and the synthetic. The synthetic has no spikes to remove, so the step says "target": "obs", exactly as a section can. A step dict carries its own parameters (threshold here); only built-in steps take theirs from a section.
compute_shot_misfit returns the pair the misfit compares.
despiked = {**bandpass,
"steps": [{"kind": "despike", "threshold": 4.0, "target": "obs"}, "filter"]}
def make_physics(preprocess, tag):
"""Physics on the starting model with the given preprocessing."""
physics = DevitoPhysics(nbl=nbl, space_order=space_order, tn=tn, parameters=("m",),
wavelet={"type": "ricker", "f0": f0},
run_name=f"{run_dir}/{tag}", preprocess=preprocess)
physics.model = init_model
return physics
pair = make_physics(despiked, "pair").compute_shot_misfit(shots[2])
show_gathers([pair["observed"], pair["synthetic"]],
["Observed (despiked + filtered)", "Synthetic (filtered)"],
dt_ms, spacing[0])
5. Through the inversion
The same configs go straight to the top-level SPG.fwi. First the gradient at the starting model, then eight iterations, with and without the despike step.
_, gradient_plain = make_physics(bandpass, "grad_plain").objective(shots)
_, gradient_despiked = make_physics(despiked, "grad_despiked").objective(shots)
fig, axes = plt.subplots(1, 2, figsize=(8, 3))
for ax, gradient, title in zip(axes, [gradient_plain["m"], gradient_despiked["m"]],
["Gradient, filter only", "Gradient, despike + filter"],
strict=True):
plt.sca(ax)
pysegy.plot_simage(gradient.T, (spacing[1], spacing[0]), new_fig=False, name=title,
cmap="seismic")
plt.tight_layout()
plt.show()
inverted = {}
for tag, preprocess in [("filter only", bandpass), ("despike + filter", despiked)]:
model, _, _ = SPG(maxiter=8, verbose=False).fwi(
physics=make_physics(preprocess, tag.replace(" ", "_")), dataset=shots,
model0=init_model, bounds={"vp": (1.4, 4.0)},
)
inverted[tag] = get_interior_vp(model)
show_models([get_interior_vp(init_model), inverted["filter only"],
inverted["despike + filter"], vp_true],
["Initial", "FWI, filter only", "FWI, despike + filter", "True"],
spacing, vp_true.min(), vp_true.max())Starting FWI optimization...
Algorithm : SPG
Run name : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/filter_only
Max iterations : 8
Shots : 5 (all shots)
Misfit : l2
Parameters : m
Output dir : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/filter_only
Save models : every 1 iteration(s)
Bounds [vp] : (1.4, 4)
Check shot : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/filter_only/filter_only_checkshot_2_initial.png
Check shot : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/filter_only/filter_only_checkshot_2_final.png
Starting FWI optimization...
Algorithm : SPG
Run name : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/despike_+_filter
Max iterations : 8
Shots : 5 (all shots)
Misfit : l2
Parameters : m
Output dir : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/despike_+_filter
Save models : every 1 iteration(s)
Bounds [vp] : (1.4, 4)
Check shot : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/despike_+_filter/despike_+_filter_checkshot_2_initial.png
Check shot : /var/folders/5k/328zp6912nd1h1bqnylt0wph0000gp/T/preprocess_tutorial_b7gw_yxs/despike_+_filter/despike_+_filter_checkshot_2_final.png

Without the step the spikes are fit as if they were reflections, and the update is a field of blobs. With it the inversion recovers the layering.
6. Unregistered steps and distributed runs
Instead of a name, kind can be the function itself. Nothing needs registering, and the function travels with the config, which is what a Dask run needs: the registry lives in each process, so a step registered in this notebook is unknown to the workers. Use a name only for steps registered in a module the workers import.
def kill_loud_traces(data, dt, src_pos, rec_pos, *, factor=5.0):
"""Zero traces whose RMS exceeds `factor` times the median trace RMS."""
rms = np.sqrt(np.mean(data**2, axis=0))
return np.where(rms > factor * np.median(rms), 0.0, data)
shipped = {**bandpass,
"steps": [{"kind": kill_loud_traces, "factor": 5.0, "target": "obs"},
{"kind": despike, "target": "obs"}, "filter"]}
pair = make_physics(shipped, "shipped").compute_shot_misfit(shots[2])
print("misfit pair shape:", pair["observed"].shape)misfit pair shape: (251, 151)
7. The two rules
The filter section also filters the source wavelet, and a frequency continuation writes each band into it. Data and wavelet stay filtered alike only if that section is the one place the filter is defined and can never be dropped by accident. So:
- a built-in step in
stepscarries no parameters; they live in its section; - every configured section must be listed in
steps. Listing a built-in that has no section does nothing, so list"filter"whenever a continuation is used.
Both mistakes raise an error that says what to change.
for config in [{**bandpass, **gain, "steps": ["despike", "filter"]},
{"steps": [{"kind": "filter", "type": "lowpass", "fcut": 8.0}]}]:
try:
apply_preprocessing(shots[2].data, dt_ms, config)
except ValueError as error:
print(f"ValueError: {error}\n")ValueError: preprocess sections ['gain'] are configured but not listed in 'steps'; add them where they should run (a continuation schedule adds a 'filter' section, so list 'filter' whenever one is used)
ValueError: built-in step 'filter' takes its parameters from config['filter'], not from the step; move ['fcut', 'type'] there
8. From a run config
In a JSON run config for FWIObjective, steps are referred to by name. Here the continuation writes each band into filter, which is why it is listed:
"preprocess": {
"mute": {"type": "direct", "v": 1.5},
"steps": [{"kind": "despike", "threshold": 4.0, "target": "obs"}, "mute", "filter"]
},
"continuation": {"fmax": [4.0, 8.0, 12.0]}The despike step must then be registered on the client and on every worker, for instance in a module imported by both.
Summary
preprocess["steps"]sets the order of the built-in sections and inserts custom steps; without it the sections run in their default order.- A custom step is
fn(data, dt, src_pos, rec_pos, **params) -> ndarray, registered with@preprocess_step(name)or passed directly askind. - In the misfit,
"target": "obs"or"syn"limits a step to one side. - Built-in parameters live only in their section, and every configured section is listed.
See the Data Preprocessing guide for the reference, and Custom Gradient Processing for the matching pipeline on the gradient side.