Skip to main content

Custom Misfit Functions

Creating custom objective functions

Misfit functions quantify the difference between synthetic and observed seismic data. DevitoHorizon provides several built-in misfits, but you can easily create your own.

The Misfit Interface

A Misfit describes a single objective term and may include both a data-residual part and a model-space regularization part. The model hooks default to no-op so existing data misfits behave unchanged; pure regularizers (Tikhonov, TV, smoothness) inherit from Regularizer, which fixes the data part to zero.

from abc import ABC, abstractmethod
import numpy as np

class Misfit(ABC):
    """Base class for misfit functions."""

    name: str = "misfit"

    # ---- data-residual part (required) ----
    @abstractmethod
    def value(self, synthetic, observed) -> float: ...

    @abstractmethod
    def gradient(self, synthetic, observed) -> np.ndarray: ...

    # ---- model-space part (optional, defaults to no-op) ----
    def model_value(self, model) -> float:
        """Return scalar regularization value (default: 0.0)."""
        return 0.0

    def model_gradient(self, model) -> dict[str, np.ndarray]:
        """Return {parameter_name: dR/dparam} on the interior grid (default: {})."""
        return {}

    def __add__(self, other): ...     # composes via CompositeMisfit

Calling convention:

  • value / gradient are evaluated per shot during the parallel data-misfit reduction in Physics.objective.
  • model_value / model_gradient are evaluated once per outer iteration in FWIState.objective, after the per-shot reduction — so you do not need to worry about averaging the regularizer across a mini-batch.

Built-in Misfits

from devitohorizon.misfits import (
    L2Misfit,           # Least-squares
    L1Misfit,           # Robust absolute value
    StudentsTMisfit,    # Heavy-tailed distribution
    Envelope1DMisfit,   # 1D Hilbert envelope
    Envelope2DMisfit,   # 2D Hilbert envelope
    PhaseMisfit,        # Normalized adjoint
)

# Usage
physics = DevitoPhysics(misfit=L2Misfit())
physics = DevitoPhysics(misfit='l2')  # Shorthand

Example: Cross-Correlation Misfit

from devitohorizon.misfits import Misfit
import numpy as np

class CrossCorrelationMisfit(Misfit):
    """
    Normalized cross-correlation misfit.

    Measures phase alignment without amplitude sensitivity.
    Useful for cycle-skipping mitigation.

    J(s,o) = 1 - (s . o) / (||s|| ||o||)
    """

    name = "xcorr"

    def __init__(self, eps: float = 1e-12):
        self.eps = eps

    def value(self, synthetic: np.ndarray, observed: np.ndarray) -> float:
        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: np.ndarray, observed: np.ndarray) -> np.ndarray:
        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))

Usage

from devitohorizon.physics import DevitoPhysics

# Use directly in physics
physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    misfit=CrossCorrelationMisfit(),
)

# Run FWI
model_opt, f_opt, result = optimizer.fwi(physics, dataset, model0, bounds)

Using FunctionMisfit Wrapper

For quick prototyping, wrap existing functions:

from devitohorizon.misfits import 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)
physics = DevitoPhysics(misfit=huber)

FunctionMisfit also accepts optional model_value_fn / model_grad_fn callables for an attached regularization term — see Custom Regularizers below.

Regularization

Regularizers are misfits that operate on the model rather than on the data. They share the same Misfit API; you can combine any data misfit with any regularizer using + and the framework will evaluate the data part per-shot and the regularizer part once per outer iteration.

Built-in regularizers

from devitohorizon.misfits import L2Misfit, Tikhonov, TV, GradientL2

#  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)

# Single regularizer
misfit = L2Misfit() + Tikhonov(alpha=1e-4, parameter='m', reference=m0)

# Multiple regularizers compose additively
misfit = L2Misfit() + Tikhonov(alpha=1e-4) + TV(alpha=1e-3, eps=1e-5)

The parameter keyword must match an entry of physics.parameters (e.g. 'm' for slowness-squared inversion or 'vp' for velocity). The framework raises KeyError if the regularizer targets a parameter that is not being inverted, so misconfigurations fail loudly.

See Misfits API: Regularizers for parameter-by-parameter docs and worked examples.

Custom regularizers

Method 1: Subclass Regularizer

The cleanest path. Regularizer is a Misfit subclass with the data part fixed to zero, so you only implement the model hooks:

from devitohorizon.misfits import Regularizer
from devitohorizon.model.grid import get_interior_vp
import numpy as np

class LogTikhonov(Regularizer):
    """
    Multiplicative Tikhonov on velocity:
        R(vp) = alpha/2 * h^d * sum (log(vp) - log(vp_ref))^2

    Useful when you want the prior to act on the relative perturbation
    rather than on the absolute amplitude (so penalties are scale-invariant).
    """

    def __init__(self, alpha, vp_ref):
        self.alpha = float(alpha)
        self.vp_ref = np.asarray(vp_ref, dtype=np.float64)
        self.parameter = 'vp'
        self.name = f"log_tikhonov:{self.alpha:g}"

    def model_value(self, model):
        vp = np.asarray(get_interior_vp(model), dtype=np.float64)
        cell_volume = float(np.prod(model.spacing))
        log_diff = np.log(vp) - np.log(self.vp_ref)
        return 0.5 * self.alpha * cell_volume * float(np.sum(log_diff ** 2))

    def model_gradient(self, model):
        vp = np.asarray(get_interior_vp(model), dtype=np.float64)
        cell_volume = float(np.prod(model.spacing))
        # d/dvp [0.5 * (log vp - log vp_ref)^2] = (log vp - log vp_ref) / vp
        grad = (np.log(vp) - np.log(self.vp_ref)) / vp
        return {self.parameter: self.alpha * cell_volume * grad}

Use it the same way as a built-in:

misfit = L2Misfit() + LogTikhonov(alpha=1e-4, vp_ref=vp_initial_interior)
physics = DevitoPhysics(misfit=misfit, parameters=('vp',))

Method 2: FunctionMisfit with model hooks

For one-off regularizers without writing a class:

from devitohorizon.misfits import FunctionMisfit
from devitohorizon.model.grid import get_interior_vp

def reg_value(model):
    vp = np.asarray(get_interior_vp(model), dtype=np.float64)
    return 1e-4 * 0.5 * float(np.sum(vp ** 2))

def reg_grad(model):
    vp = np.asarray(get_interior_vp(model), dtype=np.float64)
    return {"vp": 1e-4 * vp}              # interior-shape array per parameter

misfit = FunctionMisfit(
    name="my_misfit",
    value_fn=lambda s, o: 0.5 * float(np.sum((s - o) ** 2)),
    grad_fn=lambda s, o: s - o,
    model_value_fn=reg_value,
    model_grad_fn=reg_grad,
)

Method 3: Subclass Misfit with both parts

For a custom misfit that intrinsically couples a data term and a model term (e.g. a Bayesian formulation with a parameter-dependent likelihood weight), implement all four methods on a single Misfit subclass:

from devitohorizon.misfits import Misfit

class MyJointMisfit(Misfit):
    name = "joint"

    def value(self, syn, obs): ...        # data part
    def gradient(self, syn, obs): ...     # adjoint source
    def model_value(self, model): ...     # model part
    def model_gradient(self, model): ...  # {param: array}

Contract requirements

model_gradient(model) must:

  1. Return a dict mapping parameter names ('m', 'vp', …) to numpy arrays.
  2. The arrays must be on the interior grid of the WaveModel — i.e. without the absorbing-boundary padding. Use devitohorizon.model.grid.get_interior_vp(model) or interior_array(model.<param>.data, model.padsizes) to extract interior data.
  3. The shape must match ParameterAdapter(model, parameters=(name,)).model_to_vector(model) reshaped to the interior grid — this is the same shape the data gradient uses.
  4. The parameter keys must be a subset of physics.parameters; the framework raises KeyError otherwise.

Returning float64 is preferred — the optimizer’s gradients_to_vector casts to float32 in one place, so leaving the regularizer in float64 keeps the analysis higher-precision.

Gradient Testing

Always verify your gradient implementation:

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!"

See Also

Back to top