Skip to main content

Gradient Processing

Configuring and extending gradient muting and preconditioning

Gradient processing transforms raw FWI gradients to improve convergence and remove artifacts. DevitoHorizon ships with water-bottom muting, datum muting, cone muting, and global Gaussian smoothing, all configured through GradientProcessingConfig.

Processing is organised as an ordered pipeline of steps, mirroring the data preprocessing pipeline. You can keep the simple flat configuration shown below, or take full control by listing the steps explicitly — picking, reordering, and adding your own custom steps without subclassing anything.

Quick start (flat configuration)

Pass a GradientProcessingConfig (or an equivalent dict) to DevitoPhysics via the gradient keyword argument:

from devitohorizon.config import GradientProcessingConfig
from devitohorizon.physics import DevitoPhysics

config = GradientProcessingConfig(
    mute_type='water',
    mute_threshold=1.59,
    mute_taper_width=4.0,
)

physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    gradient=config,
)

A plain dict is also accepted:

physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    gradient={'mute_type': 'water', 'mute_threshold': 1.59},
)

When no explicit steps are given (see below), the flat fields are translated into the default pipeline, so existing configurations behave exactly as before.

Flat options

Field Type Default Description
mute_type str or None None 'water' (velocity threshold) or 'datum' (surface from dataset geometry)
mute_threshold float 1.59 Velocity threshold in km/s for water-bottom muting
mute_taper_width float 0.0 Taper width in metres below the mute boundary
cone_mute bool False Apply per-shot cone muting (geometry-based)
cone_angle float 60.0 Cone half-angle in degrees (used when cone_mute=True)
global_smoothing bool or None None Smoothing after gradient reduction. None means enabled for FWI, disabled for RTM
smoothing_factor float 0.3 Lateral smoothing strength: the Gaussian σ as a fraction of the local wavelength. See How the smoothing kernel is sized. Same knob as the continuation smoothing_factor
smoothing_depth_ratio float 0.5 Depth σ relative to the lateral σ (1.0 = isotropic, < 1 smooths depth less). See How the smoothing kernel is sized
structure_oriented bool False Smooth along the structure of vp instead of with a Gaussian. See Structure-oriented smoothing
steps tuple of dict or None None Explicit, ordered step list (see The step pipeline). When None, the steps are derived from the flat fields above

The step pipeline

A step is a dict {'kind': name, ...params}. Steps run in the order given and each receives the output of the previous one. Every step runs at one of two stages:

  • 'shot' — applied per shot, before the gradients are summed (used for geometry-dependent operations such as cone muting).
  • 'reduced' — applied once on the summed gradient (used for muting and global smoothing).

The built-in steps are:

Step Stage Parameters (default ← config) Description
cone_mute shot cone_angle ← config.cone_angle Attenuate gradients outside the per-shot illumination cone
surface_mute reduced mute_type, mute_threshold, mute_taper_width ← config Zero gradients in the water column / above the datum
global_smoothing reduced enabled, smoothing_factor, depth_ratio, structure_oriented, sigma (one fixed Gaussian; local wavelength when omitted), parameters (all when omitted) Smooth the reduced gradient arrays, or only the named ones

Provide a steps tuple to pick and order them yourself:

config = GradientProcessingConfig(
    steps=(
        {'kind': 'global_smoothing', 'enabled': True},
        {'kind': 'surface_mute', 'mute_type': 'datum'},
    ),
)

Each step’s parameters override the corresponding flat field for that step only, so a single config can, for example, mute with one threshold and smooth with an explicit sigma. Steps whose stage does not match the current call are skipped automatically (a cone_mute entry is ignored during the reduced-stage finalisation, and vice versa).

A mute set in the flat fields (mute_type) applies to explicit steps too: when they hold no surface_mute of their own, the reduced stage runs as [surface_mute, *steps, surface_mute], the default’s order. List a surface_mute yourself to place it.

Note

Order matters. [global_smoothing, surface_mute] smooths first and then mutes (the historical default); [surface_mute, global_smoothing] mutes first, which lets the smoother blur across the mute boundary. Prefer the former unless you have a specific reason.

Custom steps

A custom step is a callable with the signature:

def my_step(gradients, model, **params):
    """gradients: {name: ndarray}; model: WaveModel; returns {name: ndarray}."""
    ...

gradients is the {parameter_name: array} dict on the interior grid, and model is the working WaveModel (grid, spacing, velocities) — the same model argument passed to misfit and model-smoother callables. Read grid metadata or velocities from it, e.g. get_interior_vp(model). The remaining keys of the step dict arrive as **params.

The geometry/surface/frequency context needed by the built-in steps is handled inside the processor; custom steps receive the model and their own parameters.

There are three ways to use one.

1. Register by name

Registering attaches the step to a stage so it can be referenced by a plain string — the safest option, because the config stays a serialisable dict of strings (it survives YAML round-trips and pickling to Dask workers).

import numpy as np
from devitohorizon.processing import register_gradient_step

def clip_gradient(gradients, model, *, vmax=1.0):
    return {k: np.clip(v, -vmax, vmax) for k, v in gradients.items()}

register_gradient_step('clip', clip_gradient, stage='reduced')

config = GradientProcessingConfig(
    steps=(
        {'kind': 'surface_mute', 'mute_type': 'water'},
        {'kind': 'clip', 'vmax': 0.5},
    ),
)

The decorator form is equivalent:

from devitohorizon.processing import gradient_step

@gradient_step('clip', stage='reduced')
def clip_gradient(gradients, model, *, vmax=1.0):
    return {k: np.clip(v, -vmax, vmax) for k, v in gradients.items()}
Tip

For distributed (Dask) runs, register your custom steps in a module that is imported on the workers (e.g. via the cluster’s preload), so the string name resolves there too.

2. Inline callable

For a one-off step you can pass the callable directly. Because the name cannot be looked up, give the step an explicit stage:

def scale(gradients, model, *, factor=1.0):
    return {k: v * factor for k, v in gradients.items()}

config = GradientProcessingConfig(
    steps=({'kind': scale, 'stage': 'reduced', 'factor': 0.8},),
)

You can also keep a readable name and attach the callable via fn:

config = GradientProcessingConfig(
    steps=({'kind': 'taper', 'fn': scale, 'stage': 'reduced', 'factor': 0.8},),
)

Inline callables are convenient but do not serialise — prefer registration for configs that are saved to disk or sent to remote workers.

Inspecting available steps

from devitohorizon.processing import available_gradient_steps

available_gradient_steps()
# {'cone_mute': 'shot', 'surface_mute': 'reduced',
#  'global_smoothing': 'reduced', 'clip': 'reduced'}

How the smoothing kernel is sized

The global_smoothing step is a Gaussian filter whose width follows the local wavelength of the current model, so the same smoothing_factor produces comparable smoothing across models, grids, frequency bands and depths. Two knobs control it: smoothing_factor (overall strength) and smoothing_depth_ratio (depth-vs-lateral anisotropy).

The per-axis standard deviation σ in each cell, in grid samples, is:

\[ \lambda(\mathbf{x}) = \frac{v(\mathbf{x})}{f_\text{max}}, \qquad \sigma_\text{lateral} = \texttt{smoothing\_factor}\cdot\frac{\lambda(\mathbf{x})}{\Delta_\text{lateral}}, \qquad \sigma_\text{depth} = \texttt{smoothing\_factor}\cdot\texttt{smoothing\_depth\_ratio}\cdot\frac{\lambda(\mathbf{x})}{\Delta_\text{depth}} \]

where

  • \(v(\mathbf{x})\) is the current vp, held at or above the slowest unmuted velocity (a muted water or air column does not shrink the kernel) and smoothed by the kernel of that slowest velocity,
  • \(f_\text{max}\) is resolved by the framework per band — the band’s upper cutoff during frequency continuation, otherwise 2.5·f0,
  • \(\Delta\) is the grid spacing along each axis.

A kernel sized by the global minimum velocity alone is sized for the slowest near surface everywhere: at 4 Hz with a 1.56 km/s near surface it is 0.15 of the wavelength in 5.5 km/s salt. The variable kernel is applied as the blend, per cell, of the two Gaussians of a velocity ladder that bracket the cell’s velocity.

In words:

  • smoothing_factor sets the kernel width as a fraction of the local wavelength. 0.3 (default) smooths features finer than ~⅓ of a wavelength; larger values smooth more, 0.0 disables smoothing. This is the same knob the between-band model smoother uses (continuation smoothing_factor), so smoothing strength is named and scaled consistently across the framework.
  • smoothing_depth_ratio scales the depth σ relative to the lateral σ. The default 0.5 smooths depth half as much as the lateral axes (FWI gradients are usually better resolved in depth than laterally); 1.0 gives isotropic smoothing.

Both can be set as flat fields or overridden per step:

# Flat fields
config = GradientProcessingConfig(smoothing_factor=0.5, smoothing_depth_ratio=1.0)

# Or per step (note: the step key for the depth knob is `depth_ratio`)
config = GradientProcessingConfig(
    steps=({'kind': 'global_smoothing',
            'smoothing_factor': 0.5, 'depth_ratio': 1.0},),
)

Structure-oriented smoothing

structure_oriented=True replaces the Gaussian by a diffusion along the structure of the current vp: the lateral length above along interfaces and layering, \(\sqrt{0.05}\approx 0.22\) of it across them, and the Gaussian’s lateral and depth lengths (smoothing_depth_ratio) where vp is uniform. The structure is read from the structure tensor of \(\lambda(\mathbf{x})\,\nabla\log v\), the relative change of vp over one local wavelength; a 10% change counts as half-coherent. It smooths the gradient along the model’s layers without blurring it across them, at the cost of explicit diffusion steps (about \((\sigma_\text{max}/\Delta)^2 / 0.3\) of them).

config = GradientProcessingConfig(mute_type='datum', structure_oriented=True)

Reusing the built-in smoothing kernel

A custom smoothing step can size a single Gaussian with the built-in rule via gaussian_smoothing_sigma(model, fmax, ...), or call devitohorizon.processing.smoothing.local_gaussian_smoothing for the variable kernel itself. gaussian_smoothing_sigma returns the per-axis sigma (in grid samples) that smooths down to a fraction smoothing_factor of one wavelength λ = vmin / fmax, with the depth axis smoothed by depth_ratio of the lateral width (default half). The smoothing_factor knob is the same one used by the between-band model smoother (Frequency Continuation), so smoothing strength is named and scaled consistently across the framework.

The framework resolves the band-aware maximum frequency to preserve and passes it to any reduced-stage step that declares an fmax parameter (or **kwargs) — it is the band’s upper cutoff during continuation, else 2.5·f0. Steps that don’t declare fmax are unaffected; an explicit fmax in the step config wins.

import numpy as np
from scipy.ndimage import gaussian_filter
from devitohorizon.processing import gradient_step, gaussian_smoothing_sigma

@gradient_step('band_aware_smooth', stage='reduced')
def band_aware_smooth(gradients, model, *, fmax=None, vmin=None):
    sigma = gaussian_smoothing_sigma(model, fmax, vmin=vmin)
    if sigma is None:               # no frequency available -> skip
        return gradients
    return {k: gaussian_filter(v, sigma=sigma, mode='nearest')
            for k, v in gradients.items()}

gaussian_smoothing_sigma accepts an optional vmin (m/s; defaults to the model’s minimum interior velocity), smoothing_factor (fraction of a wavelength; default 0.3), and depth_ratio (depth width relative to lateral; default 0.5, use 1.0 for isotropic). The same factor is configurable directly on the global_smoothing step ({'kind': 'global_smoothing', 'smoothing_factor': 0.5}) or as a flat config field (GradientProcessingConfig(smoothing_factor=0.5)).

Examples

Water-bottom muting

Zeros gradients in the water column using a velocity threshold:

config = GradientProcessingConfig(
    mute_type='water',
    mute_threshold=1.59,   # km/s — water velocity
    mute_taper_width=4.0,  # metres of taper below the mute boundary
)

Datum muting

Mutes above the acquisition surface derived from dataset geometry. Requires Dataset.surface to be populated:

config = GradientProcessingConfig(
    mute_type='datum',
    mute_taper_width=8.0,
)

Cone muting

Per-shot illumination cone mute — attenuates gradients outside the wavefield cone:

config = GradientProcessingConfig(
    cone_mute=True,
    cone_angle=65.0,
)

Combined, with a custom step

@gradient_step('clip', stage='reduced')
def clip_gradient(gradients, model, *, vmax=1.0):
    return {k: np.clip(v, -vmax, vmax) for k, v in gradients.items()}

config = GradientProcessingConfig(
    steps=(
        {'kind': 'cone_mute', 'cone_angle': 60.0},        # per shot
        {'kind': 'global_smoothing'},                      # reduced
        {'kind': 'surface_mute', 'mute_type': 'datum',
         'mute_taper_width': 8.0},                       # reduced
        {'kind': 'clip', 'vmax': 0.5},                     # reduced, custom
    ),
)

Standalone mask utilities

The surface mute the pipeline applies is also available as a standalone function, surface_mask, so you can reuse the exact same mask outside the FWI loop — for example to mask an external gradient, blank the water column of a migrated image, or visualise the mute region.

from devitohorizon import surface_mask

# Velocity-based water-bottom mask (no geometry needed)
mask = surface_mask(model)                      # mute_type='water' by default

# Datum mask from the acquisition geometry of a dataset
mask = surface_mask(model, dataset, mute_type='datum', taper_width=8.0)

# `mask` is a boolean array on the interior grid: True marks muted cells.
gradient[mask] = 0.0

surface_mask(model, dataset=None, *, mute_type='water', threshold=1.59, taper_width=0.0) returns a boolean array shaped like the interior grid ((nx, nz) in 2D, (nx, ny, nz) in 3D) where True marks cells to mute. It mirrors the surface_mute step exactly:

Argument Meaning
model Working WaveModel — provides the interior velocities, origin and spacing
dataset Acquisition geometry for mute_type='datum'. Accepts a Dataset (its .surface is read), a surface dict ({'horizontal', 'depth'}), or a precomputed depth-index array. Ignored for 'water'
mute_type 'water' (velocity threshold, no dataset) or 'datum' (acquisition surface from dataset)
threshold Water velocity threshold in km/s ('water' only)
taper_width Cosine-taper width in metres below the datum ('datum' only)

The function returns the mask but does not apply it — index your array with it (array[mask] = 0) as shown above. Two lower-level helpers are exported alongside it:

  • water_bottom_mask(model, threshold=1.59, geometry=None, taper_width=0.0) — the velocity-based mask, with optional geometry refinement.
  • surface_depth_indices(model, surface) — projects dataset surface samples onto a per-column depth index on the interior grid (the building block behind mute_type='datum').
from devitohorizon.model import (
    surface_mask, water_bottom_mask, surface_depth_indices,
)

See Also

Back to top