Skip to main content

API Overview

Core Components

DevitoHorizon is built from composable, first-class objects. Each module below provides one piece of the FWI workflow.

Module Purpose Detailed Docs
devitohorizon.data Dataset abstractions (Dataset, SeismicData, data managers) Data API
devitohorizon.model Model I/O (load_model, dump_model_segy, resampling)
devitohorizon.physics Forward/adjoint modeling (DevitoPhysics, ForwardResult, GradientResult) Physics API
devitohorizon.optimization Optimizers (SPG, PQN, BREGMAN) with FWI convenience method Optimizers API
devitohorizon.scheduler Parallel execution (SerialScheduler, DaskScheduler)
devitohorizon.processing Gradient processing, muting, and preconditioning
devitohorizon.misfits Misfit functions (L2, L1, envelope, Student’s-t, custom) Misfits API

Data

from devitohorizon.data import Dataset, SeismicData

Factory methods: - Dataset.from_segy(data_path, preprocess=None, creds=None) — Create dataset from SEG-Y - Dataset.from_zarr(data_path, preprocess=None, creds=None) — Create dataset from Zarr

Dataset operations: - len(dataset) — Number of shots - dataset[idx] — Get shot by index (returns SeismicData) - dataset.subset(indices) — Create subset dataset - dataset.sample(n, seed=None) — Random sample of n shots - dataset.surface — Computed surface from geometry (for datum muting)

SeismicData fields: - shot_id — Shot identifier - rec — Receiver data (nt, nrec) - src_pos — Source coordinates - rec_pos — Receiver coordinates - dt — Time sampling in milliseconds

Lower-level managers (SEGYDataManager, ZarrDataManager) available in devitohorizon.data.* for custom I/O.

Model

from devitohorizon.model import load_model, dump_model_segy

Loading models: - load_model(path, nbl=40, space_order=8, **kwargs) — Load from HDF5, SEG-Y, or Zarr - load_model_h5(path, **kwargs) — Load specifically from HDF5 - load_model_segy(path, **kwargs) — Load from SEG-Y - load_model_zarr(path, **kwargs) — Load from Zarr

Saving models: - dump_model_segy(param, prefix, model) — Save the model as one SEG-Y per physical parameter, returning the specification it reads back from - resample_model(model, spacing=None, shape=None) — Resample to new grid

All loaders return Devito WaveModel instances compatible with recipes.

Physics

from devitohorizon.physics import DevitoPhysics

Constructor:

physics = DevitoPhysics(
    nbl=40,                    # Absorbing boundary layer points
    space_order=8,             # Spatial discretization order
    t0=None,                   # Inversion-window start (s, or "20ms"…); mutes earlier residuals
    tn=None,                   # Inversion-window end (s, or "2s"…); caps simulation length
    freesurface=False,         # Free surface boundary
    parameters=('m',),         # Parameters to invert
    illumination=True,         # Apply illumination preconditioning
    misfit='l2',               # Misfit function name
    model=None,                # Optional: build model immediately
    gradient=None,             # Optional: GradientProcessingConfig
    source_estimation=False,   # Use True for averaged or 'shot' for per-shot estimation
)

t0 and tn define an inversion-only time window — the underlying Dataset/shot is not modified. tn truncates how long the simulation runs; t0 mutes residuals before that time so early arrivals are excluded from the misfit and gradient. Both accept seconds (bare numbers) or unit-tagged strings ("500ms", "2s", "100us").

Key methods: - physics.forward(model, src_pos, rec_pos, src_wavelet, dt, nt, save_wavefields=False) Returns ForwardResult(synthetic, wavefields, illumination)

  • physics.adjoint(model, forward_result, adjoint_source) Returns GradientResult(gradients, illumination)

  • physics.compute_shot_gradient(shot, model_path=None, params=None, rtm=False) Returns dict with keys 'misfit', 'gradients', 'illumination', 'wavelet' (SeismicData or None), 'origin', 'spacing'

  • physics.objective(dataset, model=None, scheduler=None) Returns (total_misfit, accumulated_gradients)

  • physics.image(dataset, scheduler=None, params=('Z',)) RTM/migration image (stacked gradient for params[0])

Properties: - physics.model — Currently loaded WaveModel - physics.estimated_source — Averaged source wavelet from source estimation - physics.estimated_source_for_shot(shot_id) — Stored SeismicData for a particular shot - physics.estimated_source_dataset() — Dataset view of all stored source estimates

Optimization

from devitohorizon.optimization import SPG, PQN, BREGMAN

SPG (Spectral Projected Gradient):

optimizer = SPG(
    maxiter=50,
    ftol=1e-6,
    gtol=1e-8,
    verbose=True,
    alpha0=1.0,
    nm_memory=3,
)

PQN (Projected Quasi-Newton):

optimizer = PQN(
    maxiter=50,
    ftol=1e-6,
    gtol=1e-8,
    verbose=True,
    memory=3,
    nm_memory=3,
)

BREGMAN (Split Bregman):

optimizer = BREGMAN(
    maxiter=50,
    ftol=1e-6,
    verbose=True,
    tau=1.0,        # Shrinkage threshold
)

FWI convenience method (all optimizers):

model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=model0,
    bounds={'vp': (1.5, 5.0)},
    callback=None,
    scheduler=None,
)

Custom optimization:

def objective(x):
    model = param_manager.vector_to_model(x, model0)
    f, g_dict = physics.objective(dataset, model)
    g = param_manager.gradients_to_vector(g_dict)
    return f, g

result = optimizer.minimize(objective, x0, bounds)

Scheduler

from devitohorizon.scheduler import create_scheduler, SerialScheduler, DaskScheduler

Factory: - create_scheduler(client=None) — Returns SerialScheduler if client=None, else DaskScheduler

All schedulers share the same interface: - scheduler.map_reduce(func, tasks, folder, initial, shared=None) — Run func over tasks and fold the results. This is the entry point: it distributes shared to the workers once for the whole run, submits, folds in completion order, resubmits the tasks that failed, and releases the payload at the end. - scheduler.map(func, tasks, shared=None, indices=None) — Map function over tasks, returns list of Future - scheduler.reduce(futures, folder, initial) — Fold futures one at a time into accumulator - scheduler.gather(futures) — Collect all future results as a list - scheduler.submit(func, *args, **kwargs) — Submit a single task, returns Future

Usage:

from dask.distributed import Client

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

# Pass to optimizer or physics.objective()
f, g = physics.objective(dataset, model, scheduler=scheduler)

# Direct use
total = scheduler.map_reduce(
    compute_shot, shots, lambda acc, r: acc + r['misfit'], 0.0
)

# State every task reads goes as `shared`, not captured in the callable:
# it is distributed once for the run rather than serialized into each task.
total = scheduler.map_reduce(
    compute_shot_with_context, shots,
    lambda acc, r: acc + r['misfit'], 0.0, shared=run_context,
)

# The lower-level pieces, if you need them
futures = scheduler.map(compute_shot, shots)
results = scheduler.gather(futures)

Results are folded in completion order, so a folder must not depend on the order the tasks were given in. Tasks that fail are resubmitted up to max_retries times; a failure rate at or below failure_threshold is tolerated and those tasks are skipped.

Processing

from devitohorizon.processing import GradientProcessor, estimate_source_and_fix_synthetic

GradientProcessor: - GradientProcessor(model, config) — Handles muting, masking, and preconditioning - processor.process(gradients, geometry=None) — Apply processing pipeline - processor.apply_surface_mute(gradients, surface) — Apply datum/water muting

Source estimation: - estimate_source_and_fix_synthetic(observed, synthetic, dt, src_wavelet) — Returns (estimated_wavelet, corrected_synthetic, source_filter)

Misfits

from devitohorizon.misfits import (
    # Base classes
    Misfit,            # Abstract base class
    FunctionMisfit,    # Wrap custom functions as Misfit
    NormalizedMisfit,  # Normalization decorator

    # Built-in misfits
    L2Misfit,          # Least-squares
    L1Misfit,          # Robust absolute value
    StudentsTMisfit,   # Heavy-tailed distribution
    Envelope1DMisfit,  # 1D Hilbert envelope
    Envelope2DMisfit,  # 2D Hilbert envelope
    PhaseMisfit,       # Normalized adjoint
)

Using built-in misfits:

physics = DevitoPhysics(misfit='l2')              # String name
physics = DevitoPhysics(misfit='envelope_1d')     # Envelope
physics = DevitoPhysics(misfit=L2Misfit())        # Object
physics = DevitoPhysics(misfit=Envelope1DMisfit()) # Object

Custom misfits:

def my_misfit(synthetic, observed):
    return np.linalg.norm(synthetic - observed)

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

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

All misfits implement .value(synthetic, observed) -> float and .gradient(synthetic, observed) -> ndarray. See Misfits API for the full class-based interface.

See Also

Back to top