import os
import numpy as np
import matplotlib.pyplot as plt
os.environ['DEVITO_LOGGING'] = 'INFO'
os.environ['OMP_NUM_THREADS'] = '6'
import pysegy
from devitohorizon.data import Dataset
from devitohorizon.model.grid import get_interior_vp
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysicsImmersed Boundary with BP1994 Data - Composable API
Modern workflow demonstrating immersed boundary support with the BP1994 dataset and signed distance functions (SDF).
- Load SEG-Y data and immersed-boundary velocity models directly
- Instantiate
DevitoPhysicswith SDF-aware models and preprocessing - QC synthetic vs observed data with the immersed surface
- Compute gradients using the composable API
1. Setup
The new API works directly with Physics and Dataset objects—no legacy wrappers required.
Dataset
The synthetic data bp94_ib_synthetic.segy is not the dataset provided with the BP1994 dataset. It is generated by running the bp94_ib_modeling.py script which generates synthetic data using immerse boundary modeling. The dataset provided with the BP1994 dataset was genetated with a simpler modeling approach and therefore cannot be inverted with the immersed boundary approach.
# Edit these paths
data_path = '/Users/mathiaslouboutin/data/BP1994/bp94_ib_synthetic.segy'
vp_path = '/Users/mathiaslouboutin/data/BP1994/Model94-velocity_smooth_dx12_elev.sgy'
sdf_path = '/Users/mathiaslouboutin/data/BP1994/Model94-sdf_dx12_elev.sgy'
print(f'Data: {data_path}')
print(f'Velocity model: {vp_path}')
print(f'SDF: {sdf_path}')Data: /Users/mathiaslouboutin/data/BP1994/bp94_ib_synthetic.segy
Velocity model: /Users/mathiaslouboutin/data/BP1994/Model94-velocity_smooth_dx12_elev.sgy
SDF: /Users/mathiaslouboutin/data/BP1994/Model94-sdf_dx12_elev.sgy
preprocess_cfg = {
'mute': {'type': 'reflections', 'v': 1.5, 't0': 0.1, 'taper': 500},
}
physics = DevitoPhysics(
model={'vp': vp_path, 'sdf': sdf_path},
nbl=80,
wavelet={'type': 'Ricker', 'f0': 8.0},
space_order=8,
freesurface=False,
parameters=('m',),
misfit='l2',
gradient={'mute': {'type': 'datum'}},
target_spacing=(50.0, 50.0),
preprocess=preprocess_cfg,
normalization='trace'
)
dataset = Dataset.from_segy(data_path)
model0 = physics.model
print('Physics created!')
print(f'Available shots: {len(dataset)}')
print(f'Model shape: {model0.shape}')
if hasattr(model0, 'sdf'):
print('SDF loaded - immersed boundary enabled!')Physics created!
Available shots: 278
Model shape: (502, 201)
SDF loaded - immersed boundary enabled!
2. Initial Model
vp0 = get_interior_vp(model0)
print(f'Model shape: {model0.shape}')
print(f'Velocity range: {vp0.min():.1f}'
f' - {vp0.max():.1f} km/s')
if hasattr(model0, 'sdf'):
sdf_min = model0.sdf.data.min()
sdf_max = model0.sdf.data.max()
print(f'SDF statistics: min={sdf_min:.2f} max={sdf_max:.2f}')Model shape: (502, 201)
Velocity range: 3.8 - 6.0 km/s
SDF statistics: min=-60.03 max=59.96
plt.figure(figsize=(10, 6))
pysegy.plot_velocity(
vp0.T,
origin=model0.origin,
spacing=model0.spacing,
cmap='gist_ncar',
cbar=True,
name='Velocity with Topography',
aspect='auto',
new_fig=False
)
plt.contour(model0.sdf.data.T, levels=[0], colors='red', linewidths=1.5,
extent=(model0.origin[0],
model0.origin[0] + model0.shape[0] * model0.spacing[0],
model0.origin[1],
model0.origin[1] + model0.shape[1] * model0.spacing[1]))
# plt.show()
Important: Field data is automatically filtered to match the immersed boundary source spectrum so synthetic and observed gathers share the same bandwidth.
Immersed boundary: The signed-distance field (SDF) enforces topography without manual padding or custom operators.
from distributed import LocalCluster
from dask.distributed import Client
from devitohorizon.scheduler import create_scheduler
cluster = LocalCluster(n_workers=2, threads_per_worker=1, death_timeout=600)
client = Client(cluster)
scheduler = create_scheduler(client)
print(f"Dashboard: {client.dashboard_link}")Dashboard: http://127.0.0.1:8787/status
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}')Generating stencils for Derivative(u(t, x, y), (x, 2))
Generating stencils for Derivative(u(t, x, y), (y, 2))
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} (Immersed)')
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'
f' (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 (Immersed Boundary)')
plt.xlabel('Samples')
plt.ylabel('Amplitude')
plt.tight_layout()
# plt.show()plt.plot(observed[:, 200], label='Observed Trace 200')
plt.plot(synthetic[:, 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 Objective Function and Gradient
Use the proper user API: physics.objective(dataset, model)
# Compute objective and gradient for first shot
indices = np.random.choice(len(dataset), size=28, replace=False)
shot_batch = dataset[indices]
f_val, grad_dict = physics.objective(shot_batch, model0, scheduler=scheduler)
gradient = grad_dict['m']
print(f'Objective value: {f_val:.6e}')
print(f'Gradient norm: {np.linalg.norm(gradient):.4e}')Objective value: 3.361709e+04
Gradient norm: 1.3105e+01
pysegy.plot_simage(
gradient.T,
origin=physics.model.origin,
spacing=physics.model.spacing[::-1],
cmap='seismic',
cbar=True,
name='Gradient from Single Shot'
)
plt.title(f'Gradient - {len(indices)} Shots')
plt.show()
5. Run FWI with the Optimizer API
print('Starting FWI optimization...')
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,
scheduler=scheduler
)
print('Optimization complete!')
print(f'Final misfit: {f_opt:.6e}')
print(f'Iterations: {result.nit}')
print(f'Improvement: {((f_val - f_opt)/f_val*100):.1f}%')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()client.close()
cluster.close()