Misfits API
Misfit Classes and Gradients
Misfit classes quantify the difference between synthetic and observed data. DevitoHorizon provides class-based misfits with a consistent interface.
Module: devitohorizon.misfits
from devitohorizon.misfits import (
# Base classes
Misfit, # Abstract base class
FunctionMisfit, # Wrap custom functions as Misfit
NormalizedMisfit, # Normalization decorator
CompositeMisfit, # Sum of misfits (data + regularizers)
Regularizer, # Base for model-space-only misfits
# Built-in data misfits
L2Misfit, # Least-squares
L1Misfit, # Robust absolute value
StudentsTMisfit, # Heavy-tailed distribution
Envelope1DMisfit, # 1D Hilbert envelope
Envelope2DMisfit, # 2D Hilbert envelope
PhaseMisfit, # Normalized adjoint
# Built-in regularizers (model-space penalties)
Tikhonov, # alpha/2 * h^d * sum (m - m_ref)^2
GradientL2, # alpha/2 * h^d * sum |grad m|^2 (smoothness)
TV, # alpha * h^d * sum sqrt(|grad m|^2 + eps^2)
)Base Class: Misfit
A Misfit describes a single objective term and may include both a data-residual part (compared per shot against observed data) and an optional model-space part (a regularizer evaluated on the current WaveModel). The model hooks default to no-op so existing data misfits behave unchanged.
from abc import ABC, abstractmethod
import numpy as np
class Misfit(ABC):
"""Abstract base class for misfit functions."""
name: str = "misfit"
# ---- data-residual part (required) ----
@abstractmethod
def value(self, synthetic: np.ndarray, observed: np.ndarray) -> float:
"""Compute scalar data-misfit value."""
@abstractmethod
def gradient(self, synthetic: np.ndarray, observed: np.ndarray) -> np.ndarray:
"""Compute adjoint source (gradient w.r.t. synthetic)."""
# ---- model-space (regularization) part — optional, defaults to 0 / {} ----
def model_value(self, model) -> float:
"""Scalar regularization value (default: 0.0)."""
return 0.0
def model_gradient(self, model) -> dict[str, np.ndarray]:
"""{parameter_name: dR/dparam} on the interior grid (default: {})."""
return {}
# ---- composition ----
def __add__(self, other: "Misfit") -> "Misfit":
"""Sum two misfits — produces a CompositeMisfit."""
def __call__(self, synthetic, observed):
return self.value(synthetic, observed)How the parts are combined
Per outer optimization iteration, the framework evaluates:
\[ J(m) \;=\; \frac{1}{N_s}\sum_{s\in\text{batch}} \varphi\bigl(d_{\text{syn}}(m,s),\,d_{\text{obs}}(s)\bigr) \;+\; \sum_{r}\, R_r(m) \]
The data sum is reduced across shots in parallel (via Physics.objective); the regularizer sum is added once after the reduction by FWIState.objective, so each model_value / model_gradient is evaluated exactly once per iteration regardless of batch size.
Built-in Misfits
L2Misfit (Least-Squares)
Standard least-squares misfit: J = 0.5 * ||s - o||²
from devitohorizon.misfits import L2Misfit
misfit = L2Misfit()
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed)
# Use in physics
physics = DevitoPhysics(misfit=L2Misfit())
physics = DevitoPhysics(misfit='l2') # ShorthandProperties: - Smooth, second-order differentiable - Amplitude preserving - Sensitive to cycle skipping
L1Misfit (Robust)
Absolute value misfit: J = ||s - o||₁
from devitohorizon.misfits import L1Misfit
misfit = L1Misfit()
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed) # Subgradient: sign(s - o)Properties: - More robust to outliers than L2 - Non-smooth at zero - Good for noisy data
StudentsTMisfit
Robust misfit using Student’s t distribution.
from devitohorizon.misfits import StudentsTMisfit
misfit = StudentsTMisfit(k=1.0) # Degrees of freedom
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed)Parameters: - k (float): Degrees of freedom. Lower = heavier tails, more robust.
Properties: - Very robust to outliers - Smooth everywhere - Good for highly contaminated data
Envelope1DMisfit
Envelope misfit using 1D Hilbert transform along time axis.
from devitohorizon.misfits import Envelope1DMisfit
misfit = Envelope1DMisfit()
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed)Properties: - Less sensitive to phase errors - Good for initial model building - Reduces cycle skipping risk
Envelope2DMisfit
Envelope misfit using 2D Hilbert transform.
from devitohorizon.misfits import Envelope2DMisfit
misfit = Envelope2DMisfit()
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed)Properties: - Smoother than 1D envelope - Captures cross-receiver coherence - Best for poor initial models
PhaseMisfit
Amplitude-insensitive phase misfit using normalized adjoint.
from devitohorizon.misfits import PhaseMisfit
misfit = PhaseMisfit()
f = misfit.value(synthetic, observed)
g = misfit.gradient(synthetic, observed)Properties: - Ignores amplitude differences - Focuses on phase alignment - Good when amplitude is unreliable
Normalization Decorator
Apply shot- or trace-level normalization to any misfit.
from devitohorizon.misfits import L2Misfit, NormalizedMisfit
# Shot normalization (entire gather)
shot_norm = NormalizedMisfit(L2Misfit(), normalization='shot')
# Trace normalization (per trace)
trace_norm = NormalizedMisfit(L2Misfit(), normalization='trace')
# Use in physics
physics = DevitoPhysics(misfit=trace_norm)Either way the recorded gather is first divided by its own magnitude n(obs): the relative amplitudes inside the gather count, the energy recorded for the shot does not, so every shot weighs the same. 'shot' then compares syn / n(syn) with obs / n(obs); 'trace' rescales each synthetic trace to its scaled recorded trace, so the offset decay still weighs the traces against each other.
Parameters: - base (Misfit): Base misfit to wrap - normalization (str): 'shot' or 'trace' - norm (str): the magnitude n: 'l2' (default), 'inf', 'rms' or 'l1' - eps (float): Regularization for zero-norm traces (default: 1e-12)
Function Wrapper
Wrap custom functions as a Misfit object. Optional model_value_fn / model_grad_fn callables let you attach a regularization term without subclassing.
from devitohorizon.misfits import FunctionMisfit
def my_value(s, o):
return np.sum((s - o)**2)
def my_grad(s, o):
return 2 * (s - o)
# Data-only custom misfit
misfit = FunctionMisfit(name="my_misfit", value_fn=my_value, grad_fn=my_grad)
# With a custom Tikhonov-style regularizer attached:
def reg_value(model):
vp = np.asarray(model.vp.data[model.padsizes[0][0]:-model.padsizes[0][1],
model.padsizes[1][0]:-model.padsizes[1][1]])
return 1e-4 * 0.5 * float(np.sum(vp ** 2))
def reg_grad(model):
vp = np.asarray(model.vp.data[model.padsizes[0][0]:-model.padsizes[0][1],
model.padsizes[1][0]:-model.padsizes[1][1]])
return {"vp": 1e-4 * vp}
misfit = FunctionMisfit(
name="my_misfit",
value_fn=my_value,
grad_fn=my_grad,
model_value_fn=reg_value,
model_grad_fn=reg_grad,
)
physics = DevitoPhysics(misfit=misfit)Regularizers (Model-Space Penalties)
A regularizer is a Misfit whose data-residual part is identically zero; its contribution comes entirely from model_value / model_gradient. Regularizers compose with any data misfit via +:
from devitohorizon.misfits import L2Misfit, Tikhonov, TV, GradientL2
# Single regularizer
misfit = L2Misfit() + Tikhonov(alpha=1e-4, parameter='m', reference=m_init)
# Multiple regularizers compose additively
misfit = L2Misfit() + Tikhonov(alpha=1e-4) + TV(alpha=1e-3)The parameter keyword must match an entry of physics.parameters so the regularizer’s gradient lands in the right slot of the optimizer’s gradient dictionary; the framework raises KeyError otherwise (loud-failure contract: a regularizer targeting a non-inverted parameter is a configuration bug, not silently dropped).
Tikhonov
\[ R(m) \;=\; \frac{\alpha}{2}\, h^d \sum_i (m_i - m^{\text{ref}}_i)^2 \qquad \nabla R(m) \;=\; \alpha\, h^d\, (m - m^{\text{ref}}) \]
The cell-volume factor \(h^d\) (product of grid spacings) turns the discrete sum into a Riemann approximation of the continuous integral, so alpha keeps the same physical meaning across grids of different resolution.
from devitohorizon.misfits import Tikhonov
from devitohorizon.model import load_model
# Penalize departures from the initial model
m0 = load_model({'model': 'init.zarr'})
reg = Tikhonov(alpha=1e-4, parameter='m', reference=m0)
# Or supply a numpy array on the interior grid:
import numpy as np
ref = np.full((nx, nz), 1.0 / 2.5**2) # uniform vp = 2.5 km/s in 'm' space
reg = Tikhonov(alpha=1e-4, parameter='m', reference=ref)
# Or omit reference entirely for a pure ||m||^2 penalty:
reg = Tikhonov(alpha=1e-4, parameter='m')Parameters:
alpha(float, ≥ 0): Regularization weight.parameter(str, default'm'): Model parameter to penalize (must match an entry ofphysics.parameters).reference(np.ndarray,WaveModel, orNone): Target \(m^{\text{ref}}\). AWaveModelextractsparameterautomatically; a numpy array must match the interior shape;Noneis treated as zero.
GradientL2 (Smoothness)
\[ R(m) \;=\; \frac{\alpha}{2}\, h^d \sum_i |\nabla m|_i^2 \]
Penalizes spatial roughness; equivalent to a discrete Dirichlet energy. Useful for crosshole / tomography problems where the true model is expected to vary smoothly.
from devitohorizon.misfits import GradientL2
reg = GradientL2(alpha=1e-3, parameter='m')TV (Total Variation, Huber-Smoothed)
\[ R(m) \;=\; \alpha\, h^d \sum_i \sqrt{|\nabla m|_i^2 + \varepsilon^2} \]
Edge-preserving regularization that suppresses small oscillations while allowing sharp interfaces. The Huber smoothing parameter \(\varepsilon\) keeps the gradient differentiable at \(|\nabla m| = 0\).
from devitohorizon.misfits import TV
reg = TV(alpha=1e-3, parameter='m', eps=1e-6)Parameters:
alpha(float, ≥ 0): Regularization weight.parameter(str, default'm'): Parameter to penalize.eps(float, > 0, default1e-6): Huber smoothing parameter. Smaller values produce sharper edges but stiffer optimization.
Regularizer Base Class
All built-in regularizers inherit from Regularizer, which is a Misfit subclass with the data-residual part fixed to zero. Use this when writing a custom regularizer:
from devitohorizon.misfits import Regularizer
class MyReg(Regularizer):
def model_value(self, model): ...
def model_gradient(self, model): ...
# value() and gradient() inherited as no-op data partSee Custom Misfits Guide for worked examples.
Specifying Misfit + Regularization
Three equivalent input forms — pick whichever fits your workflow best.
1. String shorthand
'+'-separated terms; first token is the data misfit, later tokens are regularizers. Each token has the form name[:alpha][@parameter]:
physics = DevitoPhysics(misfit='l2 + tikhonov:1e-4')
physics = DevitoPhysics(misfit='l2 + tikhonov:1e-4 + tv:1e-3@m')
physics = DevitoPhysics(misfit='envelope_1d + smooth:1e-2')Available regularizer keys: tikhonov, tv, smooth (alias gradient_l2, smoothness). Note that the string form cannot supply a reference array — use the dict or instance form for Tikhonov with a non-zero reference.
2. Dict form
Useful when configuring from a YAML/JSON file:
param = {
"misfit": {
"misfit": "l2",
"normalization": "shot",
"regularization": [
{"type": "tikhonov", "alpha": 1e-4, "parameter": "m"},
{"type": "tv", "alpha": 1e-3, "parameter": "m"},
],
},
# ... rest of FWIObjective config
}A single regularizer can be passed without the list wrapper:
"regularization": {"type": "tikhonov", "alpha": 1e-4}3. Instance form
from devitohorizon.misfits import L2Misfit, NormalizedMisfit, Tikhonov, TV
misfit = (
NormalizedMisfit(L2Misfit(), 'shot') # data part with normalization
+ Tikhonov(alpha=1e-4, parameter='m', reference=m0)
+ TV(alpha=1e-3, parameter='m', eps=1e-6)
)
physics = DevitoPhysics(misfit=misfit)Composition order
resolve_misfit always builds the chain in the order data misfit → normalization wrapper → regularizers so that normalization affects only the data residual (regularizers see the raw model), regardless of which input form you used.
Comparison Table
| Misfit | Class | Robustness | Amplitude | Phase | Use Case |
|---|---|---|---|---|---|
| L2 | L2Misfit |
Low | Yes | High | Good initial model |
| L1 | L1Misfit |
Medium | No | High | Noisy data |
| Student’s t | StudentsTMisfit |
High | No | High | Heavy outliers |
| Envelope 1D | Envelope1DMisfit |
High | No | Low | Poor initial model |
| Envelope 2D | Envelope2DMisfit |
High | No | Low | Very poor initial model |
| Phase | PhaseMisfit |
Medium | No | Medium | Unreliable amplitudes |
Custom Misfits
Method 1: Subclass Misfit
from devitohorizon.misfits import Misfit
import numpy as np
class CrossCorrelationMisfit(Misfit):
"""Normalized cross-correlation misfit."""
name = "xcorr"
def __init__(self, eps=1e-12):
self.eps = eps
def value(self, synthetic, observed):
num = np.sum(synthetic * observed)
denom = np.linalg.norm(synthetic) * np.linalg.norm(observed) + self.eps
return 1.0 - num / denom
def gradient(self, synthetic, observed):
norm_s = np.linalg.norm(synthetic) + self.eps
norm_o = np.linalg.norm(observed) + self.eps
corr = np.sum(synthetic * observed) / (norm_s * norm_o)
return -(observed / (norm_s * norm_o) - corr * synthetic / (norm_s**2))Method 2: Use FunctionMisfit
def huber_value(s, o, delta=1.0):
r = s - o
mask = np.abs(r) <= delta
return np.sum(np.where(mask, 0.5*r**2, delta*(np.abs(r)-0.5*delta)))
def huber_grad(s, o, delta=1.0):
r = s - o
return np.where(np.abs(r) <= delta, r, delta * np.sign(r))
huber = FunctionMisfit("huber", huber_value, huber_grad)See Custom Misfits Guide for more examples.
Usage in Physics
By Name
physics = DevitoPhysics(misfit='l2')
physics = DevitoPhysics(misfit='l1')
physics = DevitoPhysics(misfit='envelope_1d')By Object
physics = DevitoPhysics(misfit=L2Misfit())
physics = DevitoPhysics(misfit=Envelope1DMisfit())
physics = DevitoPhysics(misfit=CrossCorrelationMisfit())Custom Functions
physics = DevitoPhysics(
misfit_fn=my_value_fn,
misfit_grad_fn=my_grad_fn,
)Gradient Testing
Verify custom gradient implementations:
def taylor_test(misfit, shape=(500, 100)):
"""Taylor series convergence test."""
np.random.seed(42)
x = np.random.randn(*shape).astype(np.float32)
y = np.random.randn(*shape).astype(np.float32)
f0 = misfit.value(x, y)
g = misfit.gradient(x, y)
dx = np.random.randn(*shape)
dx /= np.linalg.norm(dx)
errors = []
for h in [1e-3, 5e-4, 2.5e-4, 1.25e-4]:
f1 = misfit.value(x + h * dx, y)
linear = f0 + h * np.sum(g * dx)
errors.append(abs(f1 - linear))
ratios = [errors[i]/errors[i+1] for i in range(len(errors)-1)]
print(f"Ratios (should be ~4): {ratios}")
return all(r > 3.5 for r in ratios)
# Test
my_misfit = CrossCorrelationMisfit()
assert taylor_test(my_misfit), "Gradient test failed!"References
Envelope misfit: Bozdag, E., Trampert, J., & Tromp, J. (2011). Misfit functions for full waveform inversion based on instantaneous phase and envelope measurements. Geophysical Journal International, 185(2), 845-870.
Robust misfits: Bube, K. P., & Langan, R. T. (1997). Hybrid l1/l2 minimization with applications to tomography. Geophysics, 62(4), 1183-1195.
See Also
- Custom Misfits Guide - Create custom objectives
- API Overview - Complete API reference
- Envelope Demo - Interactive notebook