import os
import matplotlib.pyplot as plt
import numpy as np
import pysegy
from devito import configuration
from devitohorizon.data import Dataset
from devitohorizon.model.grid import get_interior_vp
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics
configuration['log-level'] = 'ERROR'Overthrust FWI Tutorial - Clean Composable API
Modern FWI workflow using composable components: 1. Setup model and data 2. Create Physics and Optimizer objects directly (no config objects!) 3. Compute gradient for verification 4. Run FWI 5. Show results
1. Setup
# Edit these paths
home = os.environ['HOME']
data_path = f'{home}/.julia/dev/JUDI/data/overthrust_shot_records.segy'
model_path = f'{home}/.julia/dev/JUDI/data/overthrust_model.h5'
print(f'Data: {data_path}')
print(f'Model: {model_path}')Data: /Users/mathiaslouboutin/.julia/dev/JUDI/data/overthrust_shot_records.segy
Model: /Users/mathiaslouboutin/.julia/dev/JUDI/data/overthrust_model.h5
physics_cfg = {
'nbl': 40,
'space_order': 16,
'freesurface': False,
'parameters': ('m',),
'misfit': 'l2',
# 'normalization': 'trace',
'model': {'m0': model_path},
'gradient': {
'mute': {
'type': 'water',
}
},
'wavelet': {
'type': 'ricker',
'f0': 8.0,
},
'name': 'overthrust_fwi',
'preprocess': {
# 'filter': {
# 'type': 'bandpass',
# 'fmin': 2.0,
# 'fmax': 18.0,
# 'order': 4,
# 'zero_phase': True,
# },
'normalize': {'type': 'shot', 'mode': 'inf'},
},
}
physics = DevitoPhysics(**physics_cfg)
dataset = Dataset.from_segy(
data_path,
)
print('Physics created!')
print(f'Available shots: {len(dataset)}')Physics created!
Available shots: 16
2. Initial Model
# Get and plot initial model
vp0 = get_interior_vp(physics.model)
print(f'Model shape: {physics.model.shape}')
print(f'Velocity range: {vp0.min():.1f} - {vp0.max():.1f} km/s')Model shape: (np.int64(401), np.int64(121))
Velocity range: 1.5 - 5.1 km/s
pysegy.plot_velocity(
vp0.T,
origin=physics.model.origin,
spacing=physics.model.spacing,
cmap='jet',
cbar=True,
name='Initial Velocity Model')
3. Verify Data
shot = dataset[0]
fwd = physics.simulate_shot(shot)
sim = physics._misfit_domain(shot, fwd)
synthetic = sim['synthetic']
observed = sim['observed']
misfit = sim['misfit']
estimated_wavelet = sim.get('estimated_wavelet')
print('Data retrieved for shot 0:')
print(f' Observed shape: {observed.shape}')
print(f' Synthetic shape: {synthetic.shape}')
print(f' Misfit: {misfit:.6e}')Data retrieved for shot 0:
Observed shape: (501, 197)
Synthetic shape: (501, 197)
Misfit: 1.728397e+01
pysegy.plot_sdata(observed, name='Observed Shot 0', new_fig=True, cmap='PuOr')
plt.title('Observed Shot 0')
pysegy.plot_sdata(synthetic, name='Synthetic Shot 0', new_fig=True, cmap='PuOr')
plt.title('Synthetic Shot 0 (Initial Model)')
pysegy.compare_shots(synthetic, observed, cbar=True, name='Difference', cmap='PuOr')
plt.title('Difference: Synthetic - Observed')
if estimated_wavelet is not None:
plt.figure(figsize=(8, 3))
plt.plot(estimated_wavelet, label='Estimated wavelet')
plt.title('Estimated Source Wavelet')
plt.xlabel('Samples')
plt.ylabel('Amplitude')
plt.legend()
plt.tight_layout()
plt.show()4. Compute Gradient
# Compute gradient using a few shots
sample_shots = dataset.subset([0, 4, 8, 12, 15])
f_initial, gradients = physics.objective(sample_shots, physics.model)
print(f'Initial misfit (4 shots): {f_initial:.6e}')
print(f'Gradient norm: {np.linalg.norm(gradients["m"]):.4e}')Initial misfit (4 shots): 2.068495e+01
Gradient norm: 1.4306e+02
gradient = gradients['m']
pysegy.plot_simage(
gradient.T,
origin=physics.model.origin,
spacing=physics.model.spacing,
cmap='seismic',
cbar=True,
name='Initial Gradient'
)
plt.title('Initial Gradient (RTM)')
plt.show()
5. Run FWI
Clean Composable API: - No FWI class—just physics, dataset, and optimizers - No config objects—pass kwargs directly - Simple driver: optimizer.fwi(physics, dataset, physics.model, bounds)
# Create optimizer - just pass kwargs!
optimizer = SPG(maxiter=10, ftol=1e-6, gtol=1e-8, verbose=True, shot_fraction=.5)
# Run FWI - optimizer handles everything
model_opt, f_opt, result = optimizer.fwi(
physics=physics,
dataset=dataset,
model0=physics.model,
bounds={'vp': (1.5, 5.0)},
)
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...
Algorithm : SPG
Run name : overthrust_fwi
Max iterations : 10
Shots : 16 total, fraction=50.00% (batch size 8)
Misfit : l2
Parameters : m
Output dir : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/fwi_run
Save models : every 1 iteration(s)
Bounds [vp] : (1.5, 5)
Check shot : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/fwi_run/overthrust_fwi_checkshot_8_initial.png
SPG initial : f = 2.002895e+01 max|g| = 3.499e+04 (gradient at the starting model)
SPG iter 1: f = 1.744560e+01 optCond = 4.044e-01 step = 1.00e+00 alpha x=1.6067e-07 feval = 2 geval = 2 time = 8.29e+00s
SPG iter 2: f = 1.199269e+01 optCond = 4.044e-01 step = 1.00e+00 alpha x=6.6427e-07 feval = 3 geval = 3 time = 8.52e+00s
SPG iter 3: f = 9.016970e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=6.0361e-07 feval = 4 geval = 4 time = 7.95e+00s
SPG iter 4: f = 8.147998e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=8.2719e-07 feval = 5 geval = 5 time = 7.73e+00s
SPG iter 5: f = 9.850199e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=6.0461e-07 feval = 6 geval = 6 time = 7.98e+00s
SPG iter 6: f = 6.768835e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=2.3855e-07 feval = 7 geval = 7 time = 7.77e+00s
SPG iter 7: f = 4.937608e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=1.7933e-07 feval = 8 geval = 8 time = 8.00e+00s
SPG iter 8: f = 6.066260e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=3.1966e-07 feval = 9 geval = 9 time = 8.18e+00s
SPG iter 9: f = 4.576478e+00 optCond = 4.044e-01 step = 1.00e+00 alpha x=4.2750e-07 feval = 10 geval = 10 time = 8.17e+00s
SPG iter 10: f = 4.703472e+00 optCond = nan step = 1.25e-01 alpha x=7.9188e-07 feval = 14 geval = 10 time = 1.87e+01s
SPG: Number of iterations reached maxiter
Check shot : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/fwi_run/overthrust_fwi_checkshot_8_final.png
Optimization complete!
Final misfit: 4.703472e+00
Iterations: 10
Improvement: 77.3%
Optimization complete!
Final misfit: 4.703472e+00
Iterations: 10
Improvement: 77.3%
# Plot optimized model
vp_opt = get_interior_vp(model_opt)
pysegy.plot_velocity(
vp_opt.T,
origin=model_opt.origin,
spacing=model_opt.spacing,
cmap='jet',
cbar=True,
name='Optimized Velocity Model'
)
plt.title('Optimized Model')
plt.show()
# Plot velocity difference
vp_diff = vp_opt - vp0
pysegy.plot_simage(
vp_diff.T,
origin=physics.model.origin,
spacing=physics.model.spacing,
cmap='seismic',
cbar=True,
name='Velocity Update'
)
plt.title('Model Update (Optimized - Initial)')
plt.show()
