Skip to main content

Marmousi2 reflection FWI with the scalar reflectivity

Reflection FWI after 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 . \]

With vector_reflectivity='scalar' the reflectivity is one field \(Z\), the log impedance \(\log(v_p \rho)\), and the equation above is the variable-density wave equation with the density free of the velocity. parameters=('mZ', 'Z') inverts squared slowness at fixed impedance and \(Z\) at fixed slowness, so the mZ gradient keeps the migration isochrones out of the velocity (see docs/augmented_rfwi.qmd).

Dataset. The AGL elastic Marmousi (Marmousi2; Martin, Wiley and Marfurt, 2006), CC BY 4.0, from the SEG wiki. It has a true density as well as a true velocity, so the inverted \(Z\) can be checked against the true log impedance, and its 17 km spread records diving waves for the velocity to fit.

Data. Modeled with the standard variable-density acoustic equation, \(m\,u_{tt} - \rho \nabla\cdot(\rho^{-1}\nabla u) = \rho s\), under a free surface on a 6.25 m grid, with an Ormsby source shaped on the Chevron SEG 2014 benchmark’s marine wavelet (2-8-24-42.5 Hz: little energy below 3 Hz). The inversion runs the augmented equation on a 50 m grid, so it is not handed its own forward model.

1. Setup

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

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

from devitohorizon.data import Dataset
from devitohorizon.model.grid import get_interior_buoyancy, get_interior_vp
from devitohorizon.model.io import load_model
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics
from marmousi2_data import prepare_marmousi2

2. Models and data

marmousi2_data.py, next to this notebook, makes what is missing from work_dir and returns the paths: it downloads the model from the AGL, takes it every fifth sample onto 6.25 m, smooths the true slowness over 400 m into the starting velocity (the water layer kept), writes the Ormsby wavelet, and models 673 shots every 25 m into a fixed spread of 681 receivers every 25 m, all 12.5 m below the free surface, 6 s at 4 ms. Modeling takes hours on a laptop: run python marmousi2_data.py --directory <work_dir> ahead of time (an interrupted run picks up the missing shots).

# Edit this path: where the models and shots are kept.
work_dir = os.path.expanduser('~/data/Marmousi/rfwi')
paths = prepare_marmousi2(work_dir)
paths

3. Physics and initial model

'vector_reflectivity': 'scalar' adds a zero \(Z\) to the starting model, so the model needs no density file. The inversion runs on 50 m, with the data and the wavelet band-passed to 3-6 Hz. Only the velocity gradient is smoothed: the reflectivity has to stay sharp. The gradients are muted in the water.

preprocess_cfg = {
# Remove high freqs
    'filter': {'type': 'bandpass', 'fmin': 3.0, 'fmax': 6.0},
}

physics_cfg = {
    'nbl': 40,
    'wavelet': {'path': paths['wavelet']},
    'space_order': 8,
    'freesurface': True,
    'parameters': ('mZ', 'Z'),
    'vector_reflectivity': 'scalar',
    'misfit': 'phase',
    'model': {'vp': paths['vp_start']},
    'source_estimation': False,
    'gradient': {
        'mute': {'type': 'water', 'threshold': 1.5},
        'steps': [
            {'kind': 'global_smoothing', 'parameters': ['mZ']},
        ],
    },
    'target_spacing': (50.0, 50.0),
    'normalization': 'trace',
    'preprocess': preprocess_cfg,
    'run_name': f'{work_dir}/marmousi2_rfwi',
}

physics = DevitoPhysics(**physics_cfg)
dataset = Dataset.from_segy(paths['shots'])
model0 = physics.model
print(f'Model shape: {model0.shape}, spacing: {tuple(model0.spacing)}')
print(f'Available shots: {len(dataset)}')
def show(field, model, title, velocity=False, **kwargs):
    """A model-sized field, velocity in km/s on a fixed scale or an image."""
    # 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, 4.7)


# The true model on the inversion grid, for comparison.
true_model = load_model({'model': {'vp': paths['vp_true'], 'rho': paths['rho_true']},
                         'target_spacing': tuple(float(h) for h in model0.spacing)})
vp_true_inv = np.asarray(get_interior_vp(true_model))
log_impedance = np.log(vp_true_inv / get_interior_buoyancy(true_model, vp_true_inv))
vp0 = np.asarray(get_interior_vp(model0))

plt.figure(figsize=(15, 10))
plt.subplot(2, 1, 1)
show(vp_true_inv, model0, 'True velocity (km/s)', velocity=True)
plt.subplot(2, 1, 2)
show(vp0, model0, 'Initial velocity (km/s)', velocity=True)
plt.tight_layout()

4. Verify Data

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

processed = physics._misfit_domain(shot, sim)
pysegy.compare_shots(processed['synthetic'], processed['observed'],
                     cbar=True, name='Difference', perc=95, cmap="seismic")
plt.title(f'Difference: Synthetic - Observed (shot {shot_id})')
plt.plot(processed['observed'][:1000, 500], label='Observed Trace 200')
plt.plot(processed['synthetic'][:1000, 500], 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()

5. Compute Gradient

The velocity gradient mZ and the reflectivity gradient Z, on a tenth of the shots.

rng = np.random.default_rng(0)
sample_shots = dataset.subset(rng.choice(len(dataset), size=68, replace=False))

f_initial, gradients = physics.objective(sample_shots)
print(f'Initial misfit (68 shots): {f_initial:.6e}')

plt.figure(figsize=(15, 10))
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()

6. Run FWI with the Optimizer API

SPG with a tenth of the shots per iteration. Each step is capped at a fraction of the model, and each parameter gets its own spectral step.

optimizer = SPG(
    maxiter=10, ftol=1e-6, gtol=1e-16,
    verbose=True, shot_fraction=0.1, nm_memory=2,
)
model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=physics.model,
    bounds={'vp': (1.0, 4.8)},
)
print(f'Final misfit: {f_opt:.6e}, iterations: {result.nit}')

7. Results

\(Z\) enters the equation only through its gradient, so it is compared with the true log impedance after removing the mean of each.

vp_opt = np.asarray(get_interior_vp(model_opt))
# The scalar reflectivity the optimizer inverted, the log impedance: its one
# component.
Z_opt = np.asarray(result.parameters['Z'][0])

plt.figure(figsize=(15, 20))
for k, (field, title, velocity) in enumerate((
        (vp_opt, 'Inverted velocity (km/s)', True),
        (vp_true_inv, 'True velocity (km/s)', True),
        (Z_opt - Z_opt.mean(), 'Inverted reflectivity Z', False),
        (log_impedance - log_impedance.mean(), 'True log impedance', False))):
    plt.subplot(4, 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 = 60 + i * 70
    plt.plot(vp_true_inv[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')
Back to top