Skip to main content

BP1994 FWI Tutorial - Composable API

Modern workflow built from first-class components: 1. Load SEG-Y data and velocity models directly. 2. Instantiate DevitoPhysics plus helper utilities. 3. Inspect synthetic vs observed data for QC. 4. Compute gradients for a mini-batch of shots. 5. Run an optimizer (SPG) without the legacy FWI wrapper.

import os
os.environ['DEVITO_LOGGING'] = 'ERROR'
os.environ['OMP_NUM_THREADS'] = '8'

import numpy as np
import matplotlib.pyplot as plt
import pysegy

from devitohorizon.data import Dataset
from devitohorizon.misfits import L2Misfit
from devitohorizon.model.grid import get_interior_vp
from devitohorizon.optimization import PQN
from devitohorizon.physics import DevitoPhysics

1. Setup

# Edit these paths

data_path = '/Users/mathiaslouboutin/data/BP1994/allshots_noshift_hdrs_5s.sgy'
model_path = '/Users/mathiaslouboutin/data/BP1994/velocity_smooth.segy'

print(f'Data: {data_path}')
print(f'Model: {model_path}')
Data: /Users/mathiaslouboutin/data/BP1994/allshots_noshift_hdrs_5s.sgy
Model: /Users/mathiaslouboutin/data/BP1994/velocity_smooth.segy

# Make the source intentionally low-frequency to check the source estimation

physics_cfg = {
    'nbl': 40,
    'wavelet': {'type': 'Ricker', 'f0': 7.0},
    'space_order': 8,
    'freesurface': False,
    'parameters': ('m',),
    'misfit': L2Misfit(),
    'model': {'vp': model_path},
    'source_estimation': True,
    'gradient': {'mute': {'type': 'datum'}},
    'target_spacing': (50.0, 50.0),
    'normalization': 'trace',
    'preprocess': {
        'mute': {'type': 'reflections', 'v': 0.8, 't0': 0.0, 'taper': 1000},
        # 'filter': {'type': 'lowpass', 'fcut': 8.0},
    },
}

physics = DevitoPhysics(**physics_cfg)
dataset = Dataset.from_segy(data_path)
model0 = physics.model

print('Physics created!')
print(f'Available shots: {len(dataset)}')
Physics created!
Available shots: 278

2. Initial Model

vp0 = get_interior_vp(model0)

print(f'Model shape: {model0.shape}')
print(f'Velocity range: {vp0.min():.1f} - {vp0.max():.1f} km/s')
Model shape: (502, 201)
Velocity range: 3.8 - 6.0 km/s
plt.figure(figsize=(10, 6))
pysegy.plot_velocity(
    vp0.T,
    origin=model0.origin,
    spacing=model0.spacing,
    cmap='jet',
    cbar=True,
    name='Initial Velocity Model',
    aspect='auto',
    new_fig=False
)
plt.gca().get_images()[0].set_clim(3.8, 6)

# plt.show()

Important: Field data is automatically filtered to match the actual source spectrum for consistent comparison. The system analyzes the generated source wavelet spectrum and automatically sets an appropriate bandpass filter to ensure synthetic and observed data have matching frequency content.

Important: Field data is automatically filtered to match the source spectrum for consistent comparison. For Ricker wavelets with f0=8Hz, this adds a bandpass filter (~2.4-20 Hz) to ensure the synthetic and observed data have matching frequency content.

3. Verify Data

shot_id = 150
shot = dataset[shot_id]
sim = physics.simulate_shot(shot)


processed = physics._misfit_domain(shot, sim)
synthetic = processed['synthetic']
observed = processed['observed']
estimated_wavelet = processed.get('estimated_wavelet')

print(f'Shot {shot_id} QC:')
print(f'  Observed shape: {observed.shape}')
print(f'  Synthetic shape: {synthetic.shape}')
Shot 150 QC:
  Observed shape: (1251, 480)
  Synthetic shape: (1251, 480)
pysegy.plot_sdata(observed, name=f'Observed Shot {shot.shot_id}', new_fig=True)
plt.title(f'Observed Shot {shot.shot_id} (Processed)')

pysegy.plot_sdata(synthetic, name=f'Synthetic Shot {shot.shot_id}', new_fig=True)
plt.title(f'Synthetic Shot {shot.shot_id} (Initial Model)')

pysegy.compare_shots(
    synthetic[:2500, :], observed[:2500, :],
    cbar=True, name='Difference',
)
plt.title(f'Difference: Synthetic - Observed (shot {shot_id})')
# plt.show()

if estimated_wavelet is not None:
    plt.figure(figsize=(8, 3))
    plt.plot(estimated_wavelet)
    plt.title('Estimated Source Wavelet')
    plt.xlabel('Samples')
    plt.ylabel('Amplitude')
    plt.tight_layout()
    # plt.show()

plt.plot(observed[:500, 200], label='Observed Trace 200')
plt.plot(synthetic[:500, 200], label='Synthetic Trace 200')
plt.title(f'Trace Comparison (shot {shot_id}, trace 200)')
plt.xlabel('Time Samples')
plt.ylabel('Amplitude')
plt.legend()
# plt.show()

4. Compute Gradient

rng = np.random.default_rng(0)
sample_indices = rng.choice(len(dataset), size=28, replace=False)
sample_shots = dataset.subset(sample_indices)  # .tolist())

f_initial, gradients = physics.objective(sample_shots)
gradient = gradients['m']

print(f'Initial misfit ({len(sample_indices)} shots): {f_initial:.6e}')
print(f'Gradient norm: {np.linalg.norm(gradient):.4e}')
Initial misfit (28 shots): 1.624907e-01
Gradient norm: 7.0641e+01
plt.figure(figsize=(15, 6))
pysegy.plot_simage(
    gradient.T,
    origin=physics.model.origin,
    spacing=physics.model.spacing[::-1],
    cmap='seismic',
    cbar=True,
    name='Initial Gradient',
    new_fig=False
)
plt.title('Initial Gradient (RTM)')
plt.show()

rtm = physics.image(sample_shots)
plt.figure(figsize=(15, 6))
pysegy.plot_simage(
    rtm.T,
    origin=physics.model.origin,
    spacing=physics.model.spacing[::-1],
    cmap='PuOr',
    cbar=True,
    name='ISIC image',
    new_fig=False
)

5. Run FWI with the Optimizer API

print('Starting FWI optimization...')
optimizer = PQN(
    maxiter=20, ftol=1e-6, gtol=1e-16,
    verbose=True, shot_fraction=0.2,
    nm_memory=1, corrections=5,
)
# optimizer = SPG(
#     maxiter=20, ftol=1e-6, gtol=1e-16,
#     verbose=True, shot_fraction=0.2, nm_memory=3,
# )
model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=physics.model,
    bounds={'vp': (3.8, 6.2)},
    rtm=True
)
print('Optimization complete!')
print(f'Final misfit: {f_opt:.6e}')
print(f'Iterations: {result.nit}')
print(f'Improvement: {((f_initial - f_opt)/f_initial*100):.1f}%')
Starting FWI optimization...
Starting FWI optimization...
  Algorithm      : PQN
  Run name       : fwi_run
  Max iterations : 20
  Shots          : 278 total, fraction=20.00% (batch size 56)
  Misfit         : l2 (trace-normalized, norm=l2)
  Parameters     : m
  Output dir     : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/fwi_run
  Save models    : every 1 iteration(s)
  Bounds [vp]    : (3.8, 6.2)
  Check shot     : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/fwi_run/fwi_run_checkshot_139_initial.png
PQN initial : f = 1.738021e-01  max|g| = 1.820e+00  (gradient at the starting model)
PQN iter   1: f = 1.683460e-01  optCond = 4.322e-02  step = 1.00e+00  m =   0  feval =     2  geval =     2  time = 8.88e+01s
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In[16], line 11
      2 optimizer = PQN(
      3     maxiter=20, ftol=1e-6, gtol=1e-16,
      4     verbose=True, shot_fraction=0.2,
      5     nm_memory=1, corrections=5,
      6 )
      7 # optimizer = SPG(
      8 #     maxiter=20, ftol=1e-6, gtol=1e-16,
      9 #     verbose=True, shot_fraction=0.2, nm_memory=3,
     10 # )
---> 11 model_opt, f_opt, result = optimizer.fwi(
     12     physics=physics,
     13     dataset=dataset,
     14     model0=physics.model,
     15     bounds={'vp': (3.8, 6.2)},
     16     rtm=True
     17 )
     18 print('Optimization complete!')
     19 print(f'Final misfit: {f_opt:.6e}')

File ~/Devitos/devitohorizon/devitohorizon/optimization/base.py:1058, in Optimizer.fwi(self, physics, dataset, model0, bounds, callback, scheduler, sampling, rtm, rtm_preprocess, rtm_model0, scales, rtm_physics)
   1055 # Run optimization, passing cheap variants explicitly so algorithms
   1056 # can build consistent (f, g) pairs without batch resampling.
   1057 try:
-> 1058     result = self.minimize(
   1059         self.state.objective,
   1060         x0,
   1061         bounds_list,
   1062         self.state.callback,
   1063         fun_value_fn=self.state.objective_value,
   1064     )
   1065 finally:
   1066     self.state.restore_misfit()

File ~/Devitos/devitohorizon/devitohorizon/optimization/optimizers.py:279, in PQN.minimize(self, fun_and_grad, x0, bounds, callback, fun_value_fn)
    276 if bounds is None:
    277     raise ValueError("PQN requires box constraints")
--> 279 x_opt, f_opt, info = pqn(
    280     fun_grad=fun_and_grad,
    281     x0=x0,
    282     bounds=bounds,
    283     callback=callback,
    284     maxiter=self.maxiter,
    285     maxfev=self.maxfev,
    286     ftol=self.ftol,
    287     gtol=self.gtol,
    288     m=self.memory,
    289     verbose=self.verbose,
    290     nm_memory=self.nm_memory,
    291     max_backtracks=self.max_backtracks,
    292     decrease=self.decrease,
    293     max_step_frac=self.max_step_frac,
    294     step_percentile=self.step_percentile,
    295     fun_value_fn=fun_value_fn,
    296     log_scale=self.state.log_scale if self.state is not None else None,
    297     projection=self.state.projection if self.state is not None else None,
    298     resampled=self.state is not None and self.state.objective_changes,
    299 )
    301 return OptimizationResult(
    302     x=x_opt,
    303     fun=f_opt,
   (...)    309     fhist=info.get("fhist", []),
    310 )

File ~/Devitos/devitohorizon/devitohorizon/optimization/algorithms/pqn.py:521, in pqn(fun_grad, x0, bounds, callback, maxiter, maxfev, m, ftol, gtol, verbose, first_order_ls, nm_memory, max_backtracks, fun_value_fn, adjust_step, bb_init, spg_opt_tol, spg_prog_tol, spg_iters, spg_test_opt, decrease, max_step_frac, step_percentile, log_scale, projection, resampled)
    514 elif full_step_accepted:
    515     # Take the full step with a gradient and let its objective
    516     # be the Armijo trial: this iteration wants the gradient
    517     # wherever it lands, and testing the point with a forward
    518     # first would evaluate it twice.  The trial sequence is
    519     # unchanged -- 1, then 1/2, 1/4 -- so the iterates are.
    520     x_try = proj(x + d)
--> 521     f_try, g_try = counted(x_try)
    522     if f_try <= acceptance_bound(f, g, x_try - x, rule=decrease):
    523         x_new, f_new, g_new, step = x_try, f_try, g_try, 1.0

File ~/Devitos/devitohorizon/devitohorizon/optimization/algorithms/common.py:176, in _CountedFunGrad.__call__(self, x)
    174 self.nfev += 1
    175 self.ngev += 1
--> 176 return self._fg(x)

File ~/Devitos/devitohorizon/devitohorizon/optimization/base.py:401, in FWIState.objective(self, x)
    399 model = self._param_manager.vector_to_model(x)
    400 self._physics.model = model
--> 401 f, g_dict = self._physics.objective(
    402     self.get_current_batch(),
    403     model=model,
    404     scheduler=self._scheduler,
    405 )
    406 g = self._param_manager.direction_to_vector(g_dict, model)
    407 fitted = getattr(self._physics, 'source_filters', None)

File ~/Devitos/devitohorizon/devitohorizon/physics/base.py:2085, in Physics.objective(self, dataset, model, scheduler, params, rtm, physics, rtm_preprocess)
   2083     # None where the shot is to be loaded on the worker.
   2084     payloads = shots if shots is not None else [None] * len(shot_ids)
-> 2085     accumulator = scheduler.map_reduce(
   2086         _compute_shot_gradient_from_context,
   2087         [ShotTask(shot, shot_wavelets.get(shot_id), position)
   2088          for position, (shot_id, shot) in enumerate(
   2089              zip(shot_ids, payloads, strict=True))],
   2090         fold_result, accumulator, shared=run_context,
   2091         combine=combine,
   2092     )
   2094 if surface_future is not None:
   2095     dataset_surface = surface_future.result()

File ~/Devitos/devitohorizon/devitohorizon/scheduler/base.py:315, in Scheduler.map_reduce(self, func, tasks, folder, initial, shared, max_retries, combine, fan_in)
    309     return self.map(
    310         func, [task_list[i] for i in indices],
    311         shared=payload, indices=indices,
    312     )
    314 try:
--> 315     return self.reduce_with_retry(
    316         _submit, list(range(len(task_list))), folder, initial,
    317         shared_context=distributed, max_retries=max_retries,
    318         combine=combine, fan_in=fan_in,
    319     )
    320 finally:
    321     if distributed is not None:

File ~/Devitos/devitohorizon/devitohorizon/scheduler/base.py:421, in Scheduler.reduce_with_retry(self, submit_fn, indices, folder, initial, shared_context, max_retries, combine, fan_in)
    414 try:
    415     # `reduce` is a documented extension point, and an
    416     # implementation of it takes the three arguments the guide
    417     # asks for.  Only a scheduler that says it can fold on its
    418     # workers is handed the other two; every other one keeps
    419     # working untouched, folding on the driver as it always has.
    420     if combine is None ore not self.folds_on_workers:
--> 421         acc = self.reduce(futures, folder, acc)
    422     else:
    423         acc = self.reduce(futures, folder, acc, combine, fan_in)

File ~/Devitos/devitohorizon/devitohorizon/scheduler/serial.py:137, in SerialScheduler.reduce(self, futures, folder, initial, combine, fan_in)
    135 acc = initial
    136 for f in futures:
--> 137     acc = folder(acc, f.result())
    138 return acc

File ~/Devitos/devitohorizon/devitohorizon/scheduler/serial.py:40, in SerialFuture.result(self)
     38 """Compute (on first call) and return the result."""
     39 if self._value is _MISSING:
---> 40     self._value = self._func(self._task)
     41 return self._value

File ~/Devitos/devitohorizon/devitohorizon/physics/base.py:334, in _compute_shot_gradient_from_context(task, shot_task)
    330 """
    331 Worker entrypoint using an explicit physics task specification.
    332 """
    333 engine = _build_physics_from_worker_config(task['physics_cfg'])
--> 334 return engine.compute_shot_gradient(
    335     _shot_of(task, shot_task),
    336     model_path=task['model_path'],
    337     params=task['params'],
    338     rtm=task['rtm'],
    339     wavelet_override=shot_task.wavelet,
    340     physics=task.get('physics'),
    341     rtm_preprocess=task.get('rtm_preprocess'),
    342 )

File ~/Devitos/devitohorizon/devitohorizon/physics/devito.py:2745, in DevitoPhysics.compute_shot_gradient(self, shot, model_path, params, rtm, wavelet_override, physics, rtm_preprocess)
   2743 active_params = params if params is not None else self.parameters
   2744 arrival = self._surface_arrival(shot, rtm_preprocess if rtm else None)
-> 2745 sim = self.simulate_shot(
   2746     shot,
   2747     model_path=model_path,
   2748     save_wavefields=True,
   2749     wavelet_override=wavelet_override,
   2750     physics=physics,
   2751     rtm=rtm,
   2752     rtm_preprocess=rtm_preprocess,
   2753     tn=None if rtm else self._mute_tn(shot, arrival),
   2754 )
   2755 working_model = sim['model']
   2757 # The two paths differ in what is injected and whether there is a
   2758 # misfit: imaging injects the observed field, inversion injects the
   2759 # residual.  Both estimate the source in the domain their data is
   2760 # preprocessed into.

File ~/Devitos/devitohorizon/devitohorizon/physics/devito.py:2039, in DevitoPhysics.simulate_shot(self, shot, model_path, save_wavefields, wavelet_override, nt, physics, rtm, rtm_preprocess, tn)
   2036     params['nt_sim'] = nt
   2037     params['src_wavelet'] = params['src_wavelet'][:nt + params['lead']]
-> 2039 forward_result = self.forward(
   2040     model=working_model,
   2041     src_pos=shot.src_pos,
   2042     rec_pos=shot.rec_pos,
   2043     src_wavelet=params['src_wavelet'],
   2044     dt=params['dt_sim'],
   2045     nt=params['nt_sim'],
   2046     lead=params['lead'],
   2047     save_wavefields=save_wavefields,
   2048     ib_kw=ib_kw,
   2049     physics=physics,
   2050 )
   2052 # Truncate observed data to effective length (tn limit).  A
   2053 # geometry-only shot (no recorded data) carries zeros — the
   2054 # observed payload is unused when generating a synthetic dataset.
   2055 nt_obs = params['nt_obs']

File ~/Devitos/devitohorizon/devitohorizon/physics/devito.py:1094, in DevitoPhysics.forward(self, model, src_pos, rec_pos, src_wavelet, dt, nt, save_wavefields, ib_kw, physics, lead)
   1090 ib_kw = {**(ib_kw ore {}),
   1091          **self._isotropic_acquisition(model, thomsen_weight)}
   1093 # Run forward simulation
-> 1094 solver.forward(
   1095     save=save_wavefields, src=src, rec=d, illum=Iu,
   1096     **ib_kw,
   1097 )
   1099 # Recorded from the simulation's start, ``lead`` steps before the shot.
   1100 synthetic = d.data[:].copy()

File ~/Devitos/devitohorizon/devitohorizon/physics/solver.py:708, in FWISolverImpl.<locals>._FWISolverImpl.forward(self, save, illum, **kwargs)
    706 if illum is not None and self._accepts_illum():
    707     kwargs['illum'] = illum
--> 708 return super().forward(save=save, **kwargs)

File ~/Devitos/recipes/recipes/solver.py:1079, in Propagator.forward(self, save, measurement, src_field, opt, **kwargs)
   1075 """
   1076 Forward propaqation
   1077 """
   1078 op = self.fwd_op(save=save, measurement=measurement, src_field=src_field, opt=opt)
-> 1079 summary = self.run_propagation(op, **kwargs)
   1080 return summary

File ~/Devitos/recipes/recipes/solver.py:114, in check_damp.<locals>.wrapper(prop, *args, **kwargs)
    112 if re_init:
    113     prop.model.initialize_damp(abc_type=prop._abc)
--> 114 return func(prop, *args, **kwargs)

File ~/Devitos/recipes/recipes/solver.py:1134, in Propagator.run_propagation(self, op, lin, estimate_memory, **kwargs)
   1132 # Preemptive filter of kwargs
   1133 with switchconfig(ignore_unknowns=True):
-> 1134     summary = run(**kw)
   1135 return summary

File ~/Devitos/devitopro/devitopro/operators/operator.py:510, in ProMixin.apply(self, **kwargs)
    508     return decouple(self, **kwargs)
    509 else:
--> 510     return super().apply(**kwargs)

File ~/Devitos/devito/devito/operator/operator.py:1059, in Operator.apply(self, **kwargs)
   1057 try:
   1058     with self._profiler.timer_on('apply', comm=args.comm):
-> 1059         retval = cfunction(*arg_values)
   1060 except ctypes.ArgumentError as e:
   1061     if e.args[0].startswith("argument "):

KeyboardInterrupt: 
vp_opt = get_interior_vp(model_opt)
model_path = '/Users/mathiaslouboutin/data/BP1994/velocity.segy'
vp_true = pysegy.segy_read(model_path).data / 1e3

plt.figure(figsize=(15, 12))
plt.subplot(211)
pysegy.plot_velocity(
    vp_opt.T,
    origin=model_opt.origin,
    spacing=model_opt.spacing,
    cmap='jet',
    cbar=True,
    name='Optimized Velocity Model',
    new_fig=False
)
plt.gca().get_images()[0].set_clim(3.8, 6)

plt.subplot(212)
pysegy.plot_velocity(
    vp_true,
    origin=model_opt.origin,
    spacing=(10, 15),
    cmap='jet',
    cbar=True,
    name='Optimized Velocity Model',
    new_fig=False
)
plt.gca().get_images()[0].set_clim(3.8, 6)

plt.show()
z0 = np.arange(vp_true.shape[0]) * 10
z1 = np.arange(vp_opt.shape[-1]) * model_opt.spacing[-1] + model_opt.origin[-1]

plt.figure(figsize=(12, 6))

for i in range(5):
    plt.subplot(1, 5, i+1)
    ix = 50 + i * 100
    ix1 = ix * 50 // 15

    plt.plot(vp_true[::-1, ix1], z0, label='True')
    plt.plot(vp_opt[ix, ::-1], z1, label='FWI')
    plt.plot(vp0[ix, ::-1], z1, label='Initial', linestyle='--')
    plt.title(f'x={ix*50} m')
    plt.xlabel('Vp (km/s)')
    if i > 0:
        plt.yticks([])
plt.legend()
# plt.tight_layout()
plt.figure(figsize=(15, 6))
pysegy.plot_simage(
    result.rtm_image.T,
    origin=model_opt.origin,
    spacing=model_opt.spacing,
    cmap='PuOr',
    cbar=True,
    name='ISIC final image',
    new_fig=False
)
plt.figure(figsize=(15, 6))
pysegy.plot_simage(
    np.gradient(vp_opt.T, axis=0),
    origin=model_opt.origin,
    spacing=model_opt.spacing,
    cmap='PuOr',
    cbar=True,
    name='FWI image',
    new_fig=False
)
# Plot velocity difference
vp_diff = vp_opt - vp0

plt.figure(figsize=(15, 6))
pysegy.plot_simage(
    vp_diff.T,
    origin=physics.model.origin,
    spacing=physics.model.spacing[::-1],
    cmap='seismic',
    cbar=True,
    name='Velocity Update',
    new_fig=False
)
plt.title('Model Update (Optimized - Initial)')
plt.show()
Back to top