Skip to main content

Physics API

Forward modeling and gradient computation

DevitoHorizon provides a physics engine built on Devito for wave-equation forward modeling, adjoint-state gradients, and source estimation.

Module: devitohorizon.physics

from devitohorizon.physics import (
    DevitoPhysics,   # Main physics engine
    Physics,         # Abstract base class
    ForwardResult,   # Forward modeling result
    GradientResult,  # Adjoint gradient result
)

DevitoPhysics

The main physics engine for wave-equation modeling.

Constructor

from devitohorizon.physics import DevitoPhysics

physics = DevitoPhysics(
    nbl: int = 40,                        # Absorbing boundary layer points
    space_order: int = 8,                 # Spatial discretization order
    t0: float | str | None = None,        # Inversion-window start (s, or "20ms"…)
    tn: float | str | None = None,        # Inversion-window end (s, or "2000ms"…)
    freesurface: bool = False,            # Free surface boundary
    parameters: tuple = ('m',),           # Parameters to invert
    illumination: bool = True,            # Apply illumination preconditioning
    misfit: str | Misfit = 'l2',          # Misfit function
    misfit_fn: callable = None,           # Custom misfit value function
    misfit_grad_fn: callable = None,      # Custom misfit gradient function
    model: WaveModel = None,              # Optional: build model immediately
    preprocess: dict = None,              # Preprocessing pipeline (FWI + imaging)
    wavelet: dict = None,                 # Source wavelet config
    gradient: GradientProcessingConfig = None,  # Gradient processing config
    source_estimation: bool | str = False, # Use True for averaged or 'shot' for per-shot
    run_name: str = 'fwi_run',            # Name for logging/output
    normalization: bool | str = False,    # Data normalization mode
    target_spacing: float | tuple = None, # Resample model to this spacing
    continuation: dict = None,            # Frequency continuation config
)
Note

There is a single preprocess knob. It conditions the FWI data (misfit and gradient) and is also the default preprocessing for RTM imaging. The RTM adjoint-source preprocessing is supplied per call (image, objective, compute_shot_gradient, optimizer fwi) via rtm_preprocess, not on the constructor.

Parameters

Parameter Type Default Description
nbl int 40 Number of absorbing boundary points
space_order int 8 Spatial derivative order (higher = more accurate)
t0 float/str/None None Inversion-window start. Bare numbers are seconds; strings carry units ("20ms", "500us"). Mutes residuals before this time so early arrivals are excluded from misfit/gradient. The forward wavefield still propagates from t = 0. The shot itself is not modified.
tn float/str/None None Inversion-window end. Same unit handling as t0. Caps the simulated recording length, regardless of how long the dataset is. None = use the full recording.
freesurface bool False Use free surface at top
parameters tuple None Parameters to invert ('mZ', 'm', 'vp', 'Z', 'b', 'r', 'epsilon', 'delta'). None takes the physics’ default, 'mZ' for the acoustic physics. See Parameterizations
vector_reflectivity bool/str False Propagate the augmented wave equation of reflection FWI: True for the vector reflectivity, 'scalar' for one field. Inverted with ('mZ', 'Z') or ('m', 'r'). See Reflection FWI
t_sub int 5 Time subsampling of the saved forward wavefield; the gradient is summed on the saved samples only
illumination bool True Apply illumination-based preconditioning
misfit str/Misfit 'l2' Misfit function name or object
source_estimation bool/str False Enable estimation. Use True for averaged or 'shot' to keep one per shot.
normalization bool/str False Data normalization: False, True/'shot', or 'trace'
target_spacing float/tuple None Resample model to this grid spacing (m)
continuation dict None Frequency continuation schedule config

Properties

# Current model
model = physics.model  # WaveModel instance

# Estimated source wavelet (if source_estimation is enabled)
wavelet = physics.estimated_source          # Averaged over shots
shot_wavelet = physics.estimated_source_for_shot(shot_id)
source_dataset = physics.estimated_source_dataset()

Key Methods

simulate_shot(shot, ...) / simulate_shots(shots, ...)

Pure forward modeling. Returns the raw synthetic data — no mute, normalization, filtering, source estimation or window muting is applied. This is the entry point for generating a synthetic dataset.

simulate_shots returns populated SeismicData, ready to hand straight to image() or objective(); simulate_shot returns the raw payload dict for a single shot.

shots = physics.simulate_shots(acquisition)   # list of SeismicData
shots[0].data                                 # raw traces, (nt, nrec)

sim = physics.simulate_shot(acquisition[0])   # a dict, for one shot
sim['synthetic']

Pass output= to write each gather on the node that modeled it, rather than bringing it back to the client to be written:

dataset = physics.simulate_shots(acquisition, scheduler=scheduler,
                                 output=f'{container}/shots')

Each shot is written to {output}/shot_XXXX.segy with its geometry in the standard trace headers, and a lazy Dataset over the folder is returned in place of the gathers. Credentials default to the ones the model specification carries.

Warning

Preprocessing belongs to imaging, not forward modeling. simulate_shot’s result has no 'misfit' key. To evaluate the misfit in the preprocessed (imaging) domain, use compute_shot_misfit(shot, model_path=None), which returns the preprocessed 'synthetic'/'observed' and 'misfit'.

compute_shot_gradient(shot, model_path=None, params=None, rtm=False, rtm_preprocess=None)

Compute misfit and gradient for a single shot.

Parameters:

Parameter Type Description
shot SeismicData Shot data to process
model_path str or dict Optional model to load instead of the physics’ own — a path, or a specification carrying credentials
params tuple of str Parameters to compute gradients for (default: physics.parameters)
rtm bool Use RTM mode (raw field data adjoint source) instead of the FWI residual
rtm_preprocess dict Imaging preprocessing for the RTM adjoint source (only when rtm=True). None defaults to a reflection mute (direct-arrival mute that keeps reflections)

Returns:

  • dict with keys: 'misfit' (float), 'gradients' (dict of ndarray), 'illumination' (ndarray or None), 'wavelet' (SeismicData or None), 'origin' (ndarray), 'spacing' (ndarray)

Example:

shot = dataset[0]
result = physics.compute_shot_gradient(shot)

print(f"Misfit: {result['misfit']:.3e}")
print(f"Gradient shape: {result['gradients']['m'].shape}")

objective(dataset, model=None, scheduler=None)

Compute total misfit and accumulated gradient.

Parameters:

Parameter Type Description
dataset Dataset or list Shot data
model WaveModel Optional model override
scheduler Scheduler Optional parallel scheduler

Returns:

  • (total_misfit, gradient_dict) tuple

Example:

# Serial execution
f, g_dict = physics.objective(dataset, model)
print(f"Total misfit: {f:.6e}")
print(f"Gradient norm: {np.linalg.norm(g_dict['m']):.3e}")

# Parallel execution
from devitohorizon.scheduler import create_scheduler
from dask.distributed import Client

client = Client(n_workers=4)
scheduler = create_scheduler(client)

f, g_dict = physics.objective(dataset, model, scheduler=scheduler)

misfit_value(dataset, model=None, scheduler=None)

Compute misfit only (no gradients). Faster for line searches.

Parameters:

Same as objective().

Returns:

  • float total misfit value

Example:

f = physics.misfit_value(dataset, model)
print(f"Misfit: {f:.6e}")

image(dataset, scheduler=None, params=('Z',), rtm_preprocess=None)

Compute RTM/migration image (stacked gradient without model update).

Parameters:

Parameter Type Description
dataset Dataset Shot data
scheduler Scheduler Optional parallel scheduler
params tuple of str Imaging parameters (default: ('Z',) for RTM)
rtm_preprocess dict Imaging preprocessing for the adjoint source. None (default) uses the physics preprocess; pass a dict to image with separate preprocessing

Returns:

  • ndarray stacked gradient image for params[0]

Example:

image = physics.image(dataset)

import matplotlib.pyplot as plt
plt.imshow(image.T, cmap='gray', aspect='auto')
plt.title('RTM Image')
plt.show()

forward(model, src_pos, rec_pos, src_wavelet, dt, nt, save_wavefields=False)

Low-level forward modeling.

Parameters:

Parameter Type Description
model WaveModel Velocity model
src_pos ndarray Source position(s)
rec_pos ndarray Receiver positions
src_wavelet ndarray Source time function
dt float Time sampling (ms)
nt int Number of time steps
save_wavefields bool Save wavefields for adjoint

Returns:

  • ForwardResult with synthetic, wavefields, illumination

Example:

# Setup source wavelet
from devito import RickerSource
wavelet = RickerSource(name='src', grid=model.grid, f0=0.015, time=time)

result = physics.forward(
    model=model,
    src_pos=np.array([[500.0, 0.0, 10.0]]),
    rec_pos=rec_pos,
    src_wavelet=wavelet.data,
    dt=1.0,
    nt=1501,
    save_wavefields=True,
)

synthetic = result.synthetic  # (nt, nrec)

adjoint(model, forward_result, adjoint_source)

Low-level adjoint computation.

Parameters:

Parameter Type Description
model WaveModel Velocity model
forward_result ForwardResult From forward()
adjoint_source ndarray Adjoint source (residual)

Returns:

  • GradientResult with gradients, illumination

Example:

# Compute adjoint source (residual)
adjoint_source = result.synthetic - observed

grad_result = physics.adjoint(model, result, adjoint_source)
gradient = grad_result.gradients['m']

ForwardResult

Container for forward modeling results.

Fields

Field Type Description
synthetic ndarray Synthetic seismogram (nt, nrec)
wavefields dict or None Saved wavefields keyed by parameter name (if requested)
illumination ndarray or None Source illumination

Example

result = physics.forward(...)

# Access fields
syn = result.synthetic
illum = result.illumination

# Plot
import matplotlib.pyplot as plt
plt.imshow(syn, aspect='auto', cmap='gray')
plt.title('Synthetic Shot')
plt.show()

GradientResult

Container for adjoint computation results.

Fields

Field Type Description
gradients dict Gradient arrays by parameter ('m', 'vp', etc.)
illumination ndarray Receiver illumination

Example

grad_result = physics.adjoint(...)

# Access gradients
grad_m = grad_result.gradients['m']
print(f"Gradient shape: {grad_m.shape}")
print(f"Gradient range: [{grad_m.min():.3e}, {grad_m.max():.3e}]")

Misfit Configuration

Built-in Misfits

# By name (string)
physics = DevitoPhysics(misfit='l2')
physics = DevitoPhysics(misfit='l1')
physics = DevitoPhysics(misfit='envelope_1d')
physics = DevitoPhysics(misfit='envelope_2d')
physics = DevitoPhysics(misfit='students')

# By object
from devitohorizon.misfits import L2Misfit, Envelope1DMisfit

physics = DevitoPhysics(misfit=L2Misfit())
physics = DevitoPhysics(misfit=Envelope1DMisfit())

Custom Misfit Functions

# Option 1: Functions
def my_misfit(synthetic, observed):
    return 0.5 * np.sum((synthetic - observed)**2)

def my_grad(synthetic, observed):
    return synthetic - observed

physics = DevitoPhysics(
    misfit_fn=my_misfit,
    misfit_grad_fn=my_grad,
)

# Option 2: Misfit class
from devitohorizon.misfits import Misfit

class MyMisfit(Misfit):
    name = "custom"

    def value(self, synthetic, observed):
        return 0.5 * np.sum((synthetic - observed)**2)

    def gradient(self, synthetic, observed):
        return synthetic - observed

physics = DevitoPhysics(misfit=MyMisfit())

Gradient Processing

Configure gradient muting and preconditioning via GradientProcessingConfig:

from devitohorizon.config import GradientProcessingConfig

# Water-bottom muting (velocity threshold)
config = GradientProcessingConfig(
    mute_type='water',
    mute_threshold=1.59,    # km/s cutoff velocity
    mute_taper_width=4.0,   # taper width in metres below the mute boundary
)

# Datum muting (geometry-based surface mute)
config = GradientProcessingConfig(
    mute_type='datum',
    mute_taper_width=8.0,
)

# Cone muting (per-shot illumination cone)
config = GradientProcessingConfig(
    cone_mute=True,
    cone_angle=65.0,        # half-angle in degrees
)

# Combine muting types
config = GradientProcessingConfig(
    mute_type='water',
    mute_threshold=1.59,
    cone_mute=True,
    cone_angle=60.0,
)

physics = DevitoPhysics(gradient=config, ...)

A dict is also accepted and will be normalized automatically:

# Dict form (nested 'mute' key supported)
physics = DevitoPhysics(
    gradient={
        'mute': {'type': 'water', 'threshold': 1.59, 'taper_width': 4.0},
        'cone_angle': 60.0,   # auto-enables cone_mute
    }
)

See the Gradient Processing guide for the full step pipeline, how smoothing_factor/smoothing_depth_ratio size the smoothing kernel, custom steps, and the standalone surface_mask utility for reusing the surface mute outside the FWI loop.


Source Estimation

Automatically estimate source wavelet from data:

physics = DevitoPhysics(
    source_estimation=True,  # Enable
    ...
)

# After running gradient computation (estimated wavelet in result dict)
result = physics.compute_shot_gradient(shot)
wavelet_shot = result['wavelet']  # SeismicData or None
if wavelet_shot is not None:
    trace = wavelet_shot.data[:, 0]
    dt_ms = wavelet_shot.dt

# Averaged wavelet from all shots (updated after each objective call)
avg_wavelet = physics.estimated_source
avg_wavelet_dt = physics.estimated_source_dt
# Per-shot estimates
shot_wavelet = physics.estimated_source_for_shot(shot_id)
wavelet_ds = physics.estimated_source_dataset()

Multi-Parameter Inversion

Invert for multiple parameters (VTI anisotropy):

physics = DevitoPhysics(
    parameters=('m', 'epsilon', 'delta'),  # P-velocity + Thomsen parameters
    nbl=40,
    space_order=8,
)

# Bounds for all parameters
model_opt, f_opt, result = optimizer.fwi(
    physics, dataset, model0,
    bounds={
        'vp': (1.5, 5.0),
        'epsilon': (0.0, 0.3),
        'delta': (-0.1, 0.2),
    },
)

Example: Complete Workflow

from devitohorizon.config import GradientProcessingConfig
from devitohorizon.data import Dataset
from devitohorizon.model import load_model
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics

# Load data and model
dataset = Dataset.from_segy("shots.segy")
model0 = load_model("initial.h5", nbl=40, space_order=8)

# Configure physics
physics = DevitoPhysics(
    nbl=40,
    space_order=8,
    parameters=('m',),
    misfit='l2',
    illumination=True,
    source_estimation=True,
    gradient=GradientProcessingConfig(
        mute_type='water',
        mute_threshold=1.59,
    ),
)

# QC: single shot gradient
shot = dataset[0]
result = physics.compute_shot_gradient(shot)
print(f"Shot 0 misfit: {result['misfit']:.3e}")

# Run FWI
optimizer = SPG(maxiter=20, verbose=True)
model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=model0,
    bounds={'vp': (1.5, 5.0)},
)

print(f"Final misfit: {f_opt:.6e}")
print(f"Converged: {result.success}")

See Also

Back to top