import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hilbert
from devitohorizon.misfits import (
Envelope1DMisfit,
L2Misfit,
)
# Instantiate misfits
env_misfit = Envelope1DMisfit()
l2_misfit = L2Misfit()
# Plotting style
plt.style.use('default')
%matplotlib inlineEnvelope Misfit for FWI
This notebook demonstrates envelope misfit functions for Full Waveform Inversion (FWI). Envelope misfits are less sensitive to phase errors (cycle skipping) than standard L2 misfit, making them more robust for building initial velocity models.
Mathematical Background
The envelope is computed using the Hilbert transform:
\[ \begin{align} z(t) &= x(t) + i\mathcal{H}[x(t)] \quad \text{(analytic signal)} \\ E(t) &= |z(t)| = \sqrt{x(t)^2 + \mathcal{H}[x(t)]^2} \quad \text{(envelope)} \end{align} \]
The envelope misfit is:
\[ \phi = \frac{1}{2} \|E_{\text{syn}} - E_{\text{obs}}\|^2 \]
The gradient (adjoint source) is:
\[ \frac{\partial \phi}{\partial x} = \text{Re}\left[\frac{(E_{\text{syn}} - E_{\text{obs}}) \cdot \bar{z}_{\text{syn}}}{E_{\text{syn}} + \epsilon}\right] \]
where \(\bar{z}\) is the complex conjugate and \(\epsilon\) is a small regularization parameter.
Reference
Bozdağ et al. (2011), “Misfit functions for full waveform inversion based on instantaneous phase and envelope measurements”, Geophysical Journal International, 185(2), 845-870.
1D Example: Phase-Shifted Ricker Wavelets
We’ll demonstrate envelope misfit on 1D signals with phase shifts, which is a common problem in FWI (cycle skipping).
# Create a Ricker wavelet
nt = 500
t = np.linspace(0, 1, nt)
f0 = 15.0 # Hz
t0 = 0.3 # seconds
# Observed data: Ricker wavelet
obs = (1 - 2 * (np.pi * f0 * (t - t0))**2) * np.exp(-(np.pi * f0 * (t - t0))**2)
# Synthetic data: Same Ricker but with phase shift (cycle skipping scenario)
t_shift = 0.35
syn = (1 - 2 * (np.pi * f0 * (t - t_shift))**2) * np.exp(-(np.pi * f0 * (t - t_shift))**2)
print("1D Envelope Misfit Comparison")
print("=" * 50)
print(f"L2 misfit: {l2_misfit.value(syn, obs):.6e}")
print(f"Envelope misfit: {env_misfit.value(syn, obs):.6e}")
print()
print(f"L2 gradient norm: {np.linalg.norm(l2_misfit.gradient(syn, obs)):.6e}")
print(f"Envelope gradient norm: {np.linalg.norm(env_misfit.gradient(syn, obs)):.6e}")# Compute envelopes and gradients
env_obs = np.abs(hilbert(obs))
env_syn = np.abs(hilbert(syn))
grad_l2 = l2_misfit.gradient(syn, obs)
grad_env = env_misfit.gradient(syn, obs)
# Plot
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
# Top left: Signals
axes[0, 0].plot(t, obs, 'k-', label='Observed', linewidth=2)
axes[0, 0].plot(t, syn, 'r--', label='Synthetic (phase shifted)', linewidth=2)
axes[0, 0].set_xlabel('Time (s)')
axes[0, 0].set_ylabel('Amplitude')
axes[0, 0].set_title('Waveforms')
axes[0, 0].legend()
axes[0, 0].grid(True, alpha=0.3)
# Top right: Envelopes
axes[0, 1].plot(t, env_obs, 'k-', label='Observed envelope', linewidth=2)
axes[0, 1].plot(t, env_syn, 'r--', label='Synthetic envelope', linewidth=2)
axes[0, 1].set_xlabel('Time (s)')
axes[0, 1].set_ylabel('Envelope')
axes[0, 1].set_title('Envelopes (match despite phase shift)')
axes[0, 1].legend()
axes[0, 1].grid(True, alpha=0.3)
# Bottom left: L2 gradient
axes[1, 0].plot(t, grad_l2, 'b-', linewidth=2)
axes[1, 0].set_xlabel('Time (s)')
axes[1, 0].set_ylabel('Gradient')
axes[1, 0].set_title(f'L2 Gradient (norm={np.linalg.norm(grad_l2):.2e})')
axes[1, 0].grid(True, alpha=0.3)
axes[1, 0].axhline(0, color='k', linestyle=':', alpha=0.5)
# Bottom right: Envelope gradient
axes[1, 1].plot(t, grad_env, 'g-', linewidth=2)
axes[1, 1].set_xlabel('Time (s)')
axes[1, 1].set_ylabel('Gradient')
axes[1, 1].set_title(f'Envelope Gradient (norm={np.linalg.norm(grad_env):.2e})')
axes[1, 1].grid(True, alpha=0.3)
axes[1, 1].axhline(0, color='k', linestyle=':', alpha=0.5)
plt.tight_layout()
plt.show()
print("Key observation: Despite the phase shift, the envelopes are similar,")
print("making envelope misfit more robust to cycle skipping.")2D Example: Receiver Gather
For seismic FWI, we typically work with 2D receiver gathers organized as time × receivers. envelope_1d applies the Hilbert transform along time for each receiver trace independently, while envelope_2d extends the transform to both time and receiver axes for additional smoothing.
# Create a synthetic receiver gather (time x receivers)
nrec = 50
nt = 500
t = np.linspace(0, 1, nt)
# Create a simple moveout pattern (hyperbolic)
obs = np.zeros((nt, nrec))
syn = np.zeros((nt, nrec))
f0 = 15.0 # Hz
v = 2000.0 # m/s
dx = 20.0 # m
for i in range(nrec):
offset = i * dx
# Hyperbolic moveout
t0_obs = 0.3 + np.sqrt(0.1**2 + (offset / v)**2)
t0_syn = 0.32 + np.sqrt(0.1**2 + (offset / v)**2) # Slightly shifted
# Ricker wavelet with moveout
obs[:, i] = (1 - 2 * (np.pi * f0 * (t - t0_obs))**2) * \
np.exp(-(np.pi * f0 * (t - t0_obs))**2)
syn[:, i] = (1 - 2 * (np.pi * f0 * (t - t0_syn))**2) * \
np.exp(-(np.pi * f0 * (t - t0_syn))**2)
print("2D Envelope Misfit Comparison")
print("=" * 50)
print(f"L2 misfit: {l2_misfit.value(syn, obs):.6e}")
print(f"Envelope misfit: {env_misfit.value(syn, obs):.6e}")
print()
print(f"L2 gradient norm: {np.linalg.norm(l2_misfit.gradient(syn, obs)):.6e}")
print(f"Envelope gradient norm: {np.linalg.norm(env_misfit.gradient(syn, obs)):.6e}")# Compute gradients
grad_l2 = l2_misfit.gradient(syn, obs)
grad_env = env_misfit.gradient(syn, obs)
# Plot
fig, axes = plt.subplots(2, 3, figsize=(15, 8))
vmax = 0.1 * np.max(np.abs(obs))
extent = [0, nrec, t[-1], t[0]]
# Top row: Data
im0 = axes[0, 0].imshow(obs, aspect='auto', cmap='seismic',
vmin=-vmax, vmax=vmax, extent=extent)
axes[0, 0].set_xlabel('Receiver')
axes[0, 0].set_ylabel('Time (s)')
axes[0, 0].set_title('Observed Data')
plt.colorbar(im0, ax=axes[0, 0])
im1 = axes[0, 1].imshow(syn, aspect='auto', cmap='seismic',
vmin=-vmax, vmax=vmax, extent=extent)
axes[0, 1].set_xlabel('Receiver')
axes[0, 1].set_ylabel('Time (s)')
axes[0, 1].set_title('Synthetic Data')
plt.colorbar(im1, ax=axes[0, 1])
im2 = axes[0, 2].imshow((syn - obs), aspect='auto', cmap='seismic',
vmin=-vmax, vmax=vmax, extent=extent)
axes[0, 2].set_xlabel('Receiver')
axes[0, 2].set_ylabel('Time (s)')
axes[0, 2].set_title('Residual')
plt.colorbar(im2, ax=axes[0, 2])
# Bottom row: Gradients (adjoint sources)
gmax_l2 = 0.1 * np.max(np.abs(grad_l2))
im3 = axes[1, 0].imshow(grad_l2, aspect='auto', cmap='seismic',
vmin=-gmax_l2, vmax=gmax_l2, extent=extent)
axes[1, 0].set_xlabel('Receiver')
axes[1, 0].set_ylabel('Time (s)')
axes[1, 0].set_title(f'L2 Gradient\n(norm={np.linalg.norm(grad_l2):.2e})')
plt.colorbar(im3, ax=axes[1, 0])
gmax_env = 0.1 * np.max(np.abs(grad_env))
im4 = axes[1, 1].imshow(grad_env, aspect='auto', cmap='seismic',
vmin=-gmax_env, vmax=gmax_env, extent=extent)
axes[1, 1].set_xlabel('Receiver')
axes[1, 1].set_ylabel('Time (s)')
axes[1, 1].set_title(f'Envelope Gradient\n(norm={np.linalg.norm(grad_env):.2e})')
plt.colorbar(im4, ax=axes[1, 1])
# Gradient difference
diff = grad_l2 - grad_env
dmax = 0.1 * np.max(np.abs(diff))
im5 = axes[1, 2].imshow(diff, aspect='auto', cmap='seismic',
vmin=-dmax, vmax=dmax, extent=extent)
axes[1, 2].set_xlabel('Receiver')
axes[1, 2].set_ylabel('Time (s)')
axes[1, 2].set_title('Difference\n(L2 - Envelope)')
plt.colorbar(im5, ax=axes[1, 2])
plt.tight_layout()
plt.show()Using Envelope Misfit in FWI
You can enable envelope misfits directly in the new composable API:
from devitohorizon.data import Dataset
from devitohorizon.model import load_model
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics
model0 = load_model("models/init_model.h5")
dataset = Dataset.from_segy("data/shots.segy")
physics = DevitoPhysics(nbl=40, space_order=8, misfit="envelope_2d")
optimizer = SPG(maxiter=10, ftol=1e-6, gtol=1e-8)
model_opt, f_opt, result = optimizer.fwi(
physics=physics,
dataset=dataset,
model0=model0,
bounds={"vp": (1.5, 5.0)},
)Or mix and match misfits dynamically using resolve_misfit("envelope") when building the physics object.
Summary
Envelope misfit provides a robust alternative to L2 misfit for FWI:
- Less sensitive to phase errors (cycle skipping)
- Good for initial model building (low-frequency inversion)
- Works with unknown source wavelets
- Trades detail for robustness (loses amplitude information)
The gradient is correctly derived using the Hilbert transform and validated with Taylor series tests for 2D signals.