import os
os.environ['DEVITO_LOGGING'] = 'ERROR'
os.environ['OMP_NUM_THREADS'] = '6'
import matplotlib.pyplot as plt
import numpy as np
import pysegy
from devitohorizon.data import Dataset
from devitohorizon.model.grid import get_interior_vp
from devitohorizon.model.io import load_model
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysicsBP1994 reflection FWI with the scalar reflectivity
BP94_init.ipynb with the inversion of McLeman et al. (2021), Reflection FWI with an augmented wave equation and quasi-Newton adaptive gradient scheme: velocity and a reflectivity are inverted together, and the wave equation carries the reflectivity as a first-order scattering term,
\[ m\,u_{tt} - \nabla^2 u + \mathbf{w} \cdot \nabla u = \rho\, s, \qquad \mathbf{w} = \nabla Z + \tfrac12 \nabla \log m . \]
What changes from BP94_init.ipynb:
vector_reflectivity='scalar'propagates the equation above, with \(Z\) one field, the log impedance, zero at the start. Its scattering vector \(\nabla Z\) is curl-free by construction. The free vector form (vector_reflectivity=True) is not used here: on this model its first update is about two thirds rotational, and a rotational \(\mathbf{w}\) makes the forward grow without bound.parameters=('mZ', 'Z')inverts squared slowness at fixed \(Z\) and \(Z\) at fixed slowness. ThemZgradient keeps the migration isochrones out of the velocity (seedocs/guides/reflection-fwi.qmd).- Only the velocity gradient is smoothed, and SPG steps
mZandZeach by its own spectral step, so no parameter scales are needed.
1. Setup
# Edit these paths. The shots are modeled on the atan model
# (BP94 with its topography); the inversion starts from its smoothed version.
data_dir = '/Users/mathiaslouboutin/data/BP1994/4Devito_Model94atan'
data_path = f'{data_dir}/m94atan2_shots_ricker8hz_t125.sgy'
model_path = f'{data_dir}/m94atan2-velocity_smooth.sgy'
true_model_path = f'{data_dir}/m94atan2-velocity.sgy'physics_cfg = {
'nbl': 80,
'wavelet': {'type': 'Ricker', 'f0': 8.0},
'space_order': 8,
'freesurface': False,
'parameters': ('mZ', 'Z'),
'vector_reflectivity': 'scalar',
'misfit': 'phase',
'model': {'vp': model_path},
'source_estimation': False,
'gradient': {
'mute': {'type': 'datum', 'taper_width': 100.0},
# Smooth the velocity only: the reflectivity has to stay sharp.
'steps': [
{'kind': 'global_smoothing', 'parameters': ['mZ']},
],
},
'target_spacing': (25, 25),
'run_name': 'bp94_scalar_reflectivity',
}
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
def show(field, model, title, velocity=False, **kwargs):
# pysegy takes (z, x): the (nx, nz) array transposed, spacing and origin reversed.
plot = pysegy.plot_velocity if velocity else pysegy.plot_simage
plot(field.T, spacing=tuple(model.spacing[::-1]), origin=tuple(model.origin[::-1]),
cmap='jet' if velocity else 'seismic', cbar=True, name=title,
new_fig=False, **kwargs)
if velocity:
plt.gca().get_images()[0].set_clim(1.5, 6.0)
vp0 = np.asarray(get_interior_vp(model0))
print(f'Model shape: {model0.shape}, spacing: {tuple(model0.spacing)}')
print(f'Velocity range: {vp0.min():.2f} - {vp0.max():.2f} km/s')
print(f'Reflectivity field: {hasattr(model0, "Z")}')
plt.figure(figsize=(12, 5))
show(vp0, model0, 'Initial velocity (km/s)', velocity=True)Model shape: (1002, 401), spacing: (np.float32(25.0), np.float32(25.0))
Velocity range: 1.92 - 5.88 km/s
Reflectivity field: True

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']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})')
4. Compute Gradient
The velocity gradient mZ and the reflectivity gradient Z, the log-impedance image.
rng = np.random.default_rng(0)
sample_indices = rng.choice(len(dataset), size=28, replace=False)
sample_shots = dataset.subset(sample_indices)
f_initial, gradients = physics.objective(sample_shots)
print(f'Initial misfit ({len(sample_indices)} shots): {f_initial:.6e}')
print({name: gradient.shape for name, gradient in gradients.items()
if name in physics.parameters})Initial misfit (28 shots): 2.388776e+06
{'mZ': (1002, 401), 'Z': (1002, 401)}
plt.figure(figsize=(15, 8))
for k, (field, title) in enumerate((
(gradients['mZ'], 'velocity gradient, mZ'),
(gradients['Z'], 'reflectivity gradient, Z'))):
plt.subplot(2, 1, k + 1)
show(field, model0, title, perc=98)
plt.tight_layout()
5. Run FWI with the Optimizer API
SPG steps mZ and Z each by its own spectral step, so the reflectivity, which starts at zero, needs no scale of its own: its steps are bounded as a fraction of its box, as the velocity’s are of its value.
Each iteration uses half the shots, one from every other patch of neighbouring shots, so each reflectivity update carries the footprint of many shots rather than a few.
The bounds bracket the true model below the topography (1.73 to 5.89 km/s) and the 1.92 km/s fill above it, so the first projection leaves the starting model untouched.
optimizer = SPG(
maxiter=10, ftol=1e-6, gtol=1e-16,
verbose=True, shot_fraction=0.5, nm_memory=3,
init_step_frac=0.05, max_step_frac=0.2,
)
model_opt, f_opt, result = optimizer.fwi(
physics=physics,
dataset=dataset,
model0=physics.model,
bounds={'vp': (1.7, 6.0)},
)
print('Optimization complete!')
print(f'Final misfit: {f_opt:.6e}')
print(f'Iterations: {result.nit}')
# Against the optimizer's own first misfit: `f_initial` above is on another
# subset of shots.
print(f'Improvement: {((result.fhist[0] - f_opt)/result.fhist[0]*100):.1f}%')Starting FWI optimization...
Algorithm : SPG
Run name : bp94_scalar_reflectivity
Max iterations : 10
Shots : 278 total, fraction=50.00% (batch size 139)
Misfit : phase
Parameters : mZ, Z
Output dir : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/bp94_scalar_reflectivity
Save models : every 1 iteration(s)
Bounds [vp] : (1.7, 6)
Check shot : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/bp94_scalar_reflectivity/bp94_scalar_reflectivity_checkshot_139_initial.png
SPG initial : f = 2.610585e+06 max|g| = 9.428e-01 (gradient at the starting model)
SPG iter 1: f = 2.425174e+06 optCond = 7.985e-01 step = 1.00e+00 alpha mZ=5.8863e-02 Z=3.1928e-02 feval = 2 geval = 2 time = 5.93e+02s
SPG iter 2: f = 2.316930e+06 optCond = 9.682e-01 step = 1.00e+00 alpha mZ=1.5315e-01 Z=1.2013e-01 feval = 3 geval = 3 time = 5.77e+02s
SPG iter 3: f = 2.000924e+06 optCond = 1.279e+00 step = 1.00e+00 alpha mZ=1.8337e-01 Z=1.2633e-01 feval = 4 geval = 4 time = 5.82e+02s
SPG iter 4: f = 1.913056e+06 optCond = 1.229e+00 step = 1.00e+00 alpha mZ=1.4346e-01 Z=1.0160e-01 feval = 5 geval = 5 time = 6.02e+02s
SPG iter 5: f = 1.764795e+06 optCond = 1.079e+00 step = 1.00e+00 alpha mZ=9.7376e-02 Z=7.1735e-02 feval = 6 geval = 6 time = 6.10e+02s
SPG iter 6: f = 1.750004e+06 optCond = 6.414e-01 step = 1.00e+00 alpha mZ=7.3865e-02 Z=6.0631e-02 feval = 7 geval = 7 time = 6.08e+02s
SPG iter 7: f = 1.687142e+06 optCond = 6.124e-01 step = 1.00e+00 alpha mZ=7.3391e-02 Z=4.8523e-02 feval = 8 geval = 8 time = 5.99e+02s
SPG iter 8: f = 1.644929e+06 optCond = 6.927e-01 step = 1.00e+00 alpha mZ=1.2007e-01 Z=5.8472e-02 feval = 9 geval = 9 time = 6.16e+02s
SPG iter 9: f = 1.577713e+06 optCond = 1.248e+00 step = 1.00e+00 alpha mZ=1.8295e-01 Z=5.1879e-02 feval = 10 geval = 10 time = 6.03e+02s
SPG iter 10: f = 1.556515e+06 optCond = nan step = 1.00e+00 alpha mZ=1.1085e-01 Z=6.9861e-02 feval = 11 geval = 10 time = 2.81e+02s
SPG: Number of iterations reached maxiter
Check shot : /Users/mathiaslouboutin/Devitos/devitohorizon/demos/bp94_scalar_reflectivity/bp94_scalar_reflectivity_checkshot_139_final.png
Optimization complete!
Final misfit: 1.556515e+06
Iterations: 10
Improvement: 40.4%
6. Results
vp_opt = np.asarray(get_interior_vp(model_opt))
# The log impedance the optimizer inverted, its one component.
Z_opt = result.parameters['Z'][0]
vp_true = np.asarray(get_interior_vp(load_model(
{'model': {'vp': true_model_path},
'target_spacing': tuple(float(h) for h in model_opt.spacing)})))
plt.figure(figsize=(15, 15))
for k, (field, title, velocity) in enumerate((
(vp_opt, 'Optimized velocity (km/s)', True),
(vp_true, 'True velocity (km/s)', True),
(Z_opt, 'Reflectivity Z (log impedance)', False))):
plt.subplot(3, 1, k + 1)
show(field, model_opt, title, velocity=velocity, perc=98)
plt.tight_layout()
depth = (model_opt.origin[1] + np.arange(vp_opt.shape[1]) * model_opt.spacing[1]) / 1e3
plt.figure(figsize=(12, 6))
for i in range(5):
plt.subplot(1, 5, i + 1)
ix = 50 + i * 100
plt.plot(vp_true[ix], depth, label='True')
plt.plot(vp_opt[ix], depth, label='FWI')
plt.plot(vp0[ix], depth, label='Initial', linestyle='--')
plt.gca().invert_yaxis()
plt.title(f'x={ix * model_opt.spacing[0] / 1e3:g} km')
plt.xlabel('Vp (km/s)')
if i > 0:
plt.yticks([])
plt.legend()
plt.figure(figsize=(15, 5))
show(vp_opt - vp0, model_opt, 'Velocity update (km/s)', perc=98)
plt.figure(figsize=(8, 4))
plt.semilogy(result.fhist, marker='o', ms=3)
plt.xlabel('iteration')
plt.ylabel('misfit')
plt.title('Convergence')
