Skip to main content

DevitoPRO

Compatibility notes

DevitoPRO requires Devito main.

DevitoPRO sets up Devito as a submodule locked onto the latest main commit which is compatible with DevitoPRO (i.e. passes all DevitoPRO tests). The branch of the submodule can be manually changed as desired, although it should be noted that this is discouraged. There is CI workflow which automatically updates the submodule every time a PR is merged into Devito, if the new update passes all the DevitoPRO tests. If necessary, the status of the submodule can also be updated by hand (typically for changes spanning both Devito and DevitoPRO).

Note: DevitoPRO now checks the commit tag of the installed Devito at both installation and runtime.

  • At installation, DevitoPRO will force re-install Devito if the tag is not the compatible one.
  • At runtime, DevitoPRO will raise an error if the tag is not the compatible one.

You can disable the runtime error by setting DEVITO_BYPASS_VERSION_CHECK=1 in your environment. This will only raise a warning instead of an error. This is useful for development purposes but not recommended for production.

Install from Docker

Virtually identical to Devito. The only difference is that the main Dockerfile here is called Dockerfile.devitopro (instead of Dockerfile.devito).

Install with pip

First install

Installing devitopro as a Python package is also supported. This setup is designed to handle all dependencies for the user, including installing devito at the required version. To install devitopro:

  • First, clone your mirror repository:
git clone --recurse-submodules --depth 1 your-devitopro-mirror

This will clone the repository and all the necessary submodules, currently devito and CvxCompress (CPU compression).

  • Then, install devitopro:
./install-devitopro.sh

DevitoPRO can be installed in editable mode with the ./install-devitopro.sh -e commmand.

Additionally MPI installation can be skipped with the --no-mpi option. This is useful if DevitoPRO is to be installed on a machine without MPI support or in a virtual environment.

./install-devitopro.sh --no-mpi

Finally, if a Python installation other than the default system python3 is to be used, the --python option can be supplied with the path to the desired Python executable. This is useful when installing DevitoPRO in a virtual environment or using different Python versions.

./install-devitopro.sh --python /path/to/python

Note: DevitoPRO is installed in a minimal configuration by default, skipping some dependencies to reduce the install size for production. Additional dependencies only used for testing, plotting, and demos are installed with the ./install-devitopro.sh --extras option.

Updating DevitoPRO

We are continuously improving DevitoPRO and updating the submodule to keep it synchronised with the latest Devito version. To update DevitoPRO, simply pull the latest changes from the repository and reinstall DevitoPRO by calling the install-devitopro.sh script with the same options as the original installation:

./install-devitopro.sh

It is extremely important that you include the git submodule update --init --recursive so that devito is updated to the latest version as well. The pip install path/to/devitopro command will then automatically reinstall devito at the correct version if the required version has changed.

Note: By default, install-devitopro.sh automatically calls git submodule update --init --recursive at pip install. However we recommend doing it on the user side to avoid issues with for example git credentials.

Getting started

  • For learning how to use Devito, a range of tutorials and examples can be found here. We recommend beginning with the README, before progressing to the userapi notebooks which detail aspects of the DSL and, subsequently, the seismic/tutorials notebooks.
  • Tutorials for DevitoPRO-specific features are available in demos/tutorials, including ordered CIRE extraction and the Decoupler.
  • API reference
  • Devito FAQs
  • DevitoPRO FAQs: devitopro/FAQ.md

Recipes

Curated solvers for DevitoPRO

Various physics examples available in this repository include:

  • Isotropic Acoustic: Standard acoustic wave propagation. Supports SLS viscosity as well.
  • Isotropic Elastic: Elastic wave propagation using isotropic models.
  • Anisotropic Acoustic: Various variations of the acoustic TTI equation (Fletcher Du Fowler, Zhang, Bube’s self-adjoint)
  • Anisotropic Elastic: Elastic wave propagation using anisotropic models such as TTI (Tilted Transverse Isotropy) and VTI (Vertical Transverse Isotropy).

Usage

To run the examples, navigate to the examples directory and execute the scripts or notebooks as needed. Ensure all dependencies are installed.

CLI

To run the solvers from the command line, use the following command:

python devitopro/recipes/run.py -physics <physics_name> -so <space_order> -d nx ny nz -nt <time_steps> ...

You can get all the available options by running:

python devitopro/recipes/run.py -h

When running on accelerators (GPUs) and/or with the DevitoPRO decoupler (DEVITO_DECOUPLER=1), all model initializations (e.g., vp, vs, etc.) are performed serially on the host to avoid unnecessary data transfers and communication overhead. A utility function, host_config, is available and can be imported with from recipes.utils import host_config for use in external codebases. Note that this function will be moved directly into DevitoPRO in the future.

Additional examples

Elastic Accuracy

This example demonstrates the accuracy of elastic solvers.

  • Script: elastic-accuracy.py
  • Description: The script compares different elastic solvers, including isotropic and anisotropic models, and visualizes their results.
  • Sections:
    • Elas vs Acou: Comparison between elastic and acoustic solvers.
    • AnisoElas vs Elas: Comparison between anisotropic elastic and isotropic elastic solvers.
    • VTI vs TTI: Comparison between vertical transverse isotropy (VTI) and tilted transverse isotropy (TTI) solvers.
    • SSG vs RSG: Stability comparison with respect to theta and vs parameters.

Distributed (MPI) modeling

  • Script: mpi_modeling.py
  • Run: DEVITO_MPI=diag2 mpiexec -n 4 python demos/tutorials/recipes/mpi_modeling.py
  • Description: forward modeling on the SEG/Chevron 2014 2D benchmark velocity model, read straight from its SEG-Y file. Each rank reads only the window of the model covering the slab of the grid it owns, so the model is never read in full nor held in memory. See the MPI page of the documentation (docs/mpi.qmd).

Imaging conditions

This notebook shows what each imaging condition keeps, on one source-receiver pair.

  • Notebook: imaging_conditions.ipynb
  • Description: the three sensitivity kernels a recipe accumulates – the cross-correlation (m), the inverse-scattering condition (Z) and its transmission complement (mZ) – plotted for a pure transmission experiment and for a reflection, with the scattering-angle argument for why the sum and the difference each annihilate one of the two.
  • Sections:
    • A pure transmission experiment: Z cancels the “banana”, mZ keeps it.
    • A reflection: Z images the reflector without the rabbit ears.
    • Choosing: RTM/LSRTM, conventional FWI, reflection FWI.

Immersed Boundary for Acoustic Solvers

This notebook demonstrates the use of immersed boundary support for implementing a topographic free surface.

  • Notebook: immersed_boundary.ipynb
  • Description: It showcases how to read the Signed Distance Function (SDF) and implement immersed boundary conditions using the Schism library.
  • Sections:
    • Read the SDF: Explanation of the boundary geometry and material properties continuation through the surface.

Installation

The recipes should not be installed by themselves but should be automatically installed as part of the devitopro installation.

Customizing the imaging condition

The recipes/solver.py module defines the solvers base class and the public interface. All the recipes are subclasses of this class and, regardless of whether you have access to the open or the obfuscated version of the repository, you can always subclass the solver class and define your own imaging condition.

The tests/test_gradient.py::TestCustomization::test_dummy test shows how to subclass the solver class and define a dummy imaging condition. Below, we show a slightly modified fragment of said test:


class AcousticIsotropicDummy(AcousticIsotropic):

    def sensitivity(self, params='m'):
        """
        Define a custom imaging condition for our solver.
        """
        # `m`, `vp`, ...
        params = as_tuple(params)
        assert len(params) == 1
        param = params[0]

        u = self.saved_state['u_save']
        v = self.state['u']

        b, damp = self.model.b, self.model.damp  # noqa

        dm = self.perturbation(param=param)

        eqns = [Eq(dm, u.dx*v.dx)]

        return eqns

In short, to customize the imaging condition, you need to:

  • Subclass a solver class (full list available in recipes/__init__.py).
  • Override the sensitivity method to define your imaging condition.
    • Inside this method you can access the wavefield at the current time step (via self.state) as well as the wavefield snapshots saved during the forward run (via self.saved_state). You may also access the overarching model object (via self.model) as well as the inverted objects (via the params variable).
    • Write the Eq’s defining the imaging condition. For this part, you need to be familiar with the Devito API.
    • Return the list of Eq’s defining the imaging condition.

That’s about it. The only remaining step is to ensure that your custom solver is accessible by the runtime. You can do it either programmatically (as in the test above) or by adding your new class to the recipes_registry dictionary in recipes/__init__.py. If you choose the latter, you can then run your custom solver directly from the CLI, e.g.:

python devitopro/recipes/run.py -physics iso-acoustic-dummy ...

Where iso-acoustic-dummy is the name of your custom solver that you used as a key in the recipes_registry dictionary.

While here we only showed how to customize the imaging condition, you can customize any part of the solver by subclassing the solver class and overriding the relevant methods. The base solver class was designed to be easily extensible and customizable. ## SchismPRO

CI-Core DOI

Schism is a set of utilities used for the implementation of immersed boundaries in Devito. SchismPRO is an enhanced version of this software package. # Warper

Warper tunes the CPU or CUDA settings of a named Devito Operator in your existing Python application. It builds alternatives, checks numerical correctness, measures complete Operators, and uses profiler evidence to guide the search. The result is a measured configuration you can reuse, together with a durable session you can inspect in the browser dashboard.

The CPU guide covers C/OpenMP, cache blocks, the min-storage/cire-rotate screen, and single-node MPI scaling over NUMA domains.

Start with installation, then follow the CLI and dashboard tutorial. The tutorial includes a walkthrough you can run without a GPU and screenshots of the actual interface. The documentation index separates user guides from maintainer references.

Install

Warper is installed automatically with DevitoPRO, just like recipes. Use your application’s Python environment; the installation guide covers CPU and CUDA requirements and dashboard setup.

The dashboard runs separately on a laptop using Python’s standard library, without Devito or a GPU.

Tune your application

For an application app.py that invokes an Operator named Forward:

export WARPER_SESSION_ROOT="$PWD/warper-results"
python3 -m warper Forward \
  --optimize-for 15m --max-workers 3 --scenario first-run -- \
  app.py

Replace Forward and app.py with your Operator name and application command; put application arguments after --. Use your normal CUDA environment. The GPU architecture is detected automatically. --max-workers limits parallel compilation; Operator execution remains serial on one GPU. The search budget includes compilation and profiling; final validation and reporting can finish after that budget.

The terminal prints the session ID and result paths. Interrupted sessions can be resumed from their original environment and session root:

python3 -m warper --resume SESSION_ID --optimize-for 15m

An incomplete resume adds this search time. A completed resume validates the saved result without rerunning tuning. To start another search from a prior configuration, use --seed; see the tutorial.

Inspect results

For local sessions, from your DevitoPRO repository:

python3 warper-warper-gui/server --sessions-root "$WARPER_SESSION_ROOT"

Open the printed browser URL. For cluster results, run the dashboard on your laptop and configure SSH collection as described in the GUI reference. It imports completed sessions into a local archive. The dashboard inspects results; tuning starts from the CLI.

Further reading

The contributor entry point links to the architecture and runtime contracts. The retired V2 plan, phase reports and acceptance records remain available through Git history. # DevitoHorizon

DevitoHorizon is a lightweight toolbox for seismic modeling, migration, and full‑waveform inversion (FWI) built on Devito, with optional Dask/Azure scaling. It focuses on clarity and hackability: small, composable modules, runnable demos, and explicit control over misfit and optimization.

What’s Inside

DevitoHorizon uses a component-based architecture with clear separation of concerns:

Core Components (devitohorizon/)

  • config/: Configuration dataclasses for all FWI components
  • data/: Data managers (SEGY, Zarr) for shot loading and discovery
  • physics/: Physics engines for forward modeling and adjoint computation
  • optimization/: Optimization algorithms (SPG, PQN, BREGMAN) and wrappers
  • parameters/: Parameter management (vector/model conversions, bounds)
  • processing/: Gradient processing (muting, cone mute, preconditioning)
  • scheduler/: Task schedulers (Serial, Dask) for parallel execution
  • sampling/: Shot sampling strategies for stochastic FWI
  • results/: Result collection and visualization
  • inversion/: Main FWI orchestrator class
  • misfits/: Misfit functions (L2, L1, Student’s-t, envelope, custom)
  • preprocess/: Data preprocessing (filters, mutes, gains, normalization)
  • model/: Model utilities (load/save/resample, grid operations, masks)
  • io/: Low-level I/O utilities (filesystem, wavelet generation)
  • optim/: Legacy re-exports (use optimization/ for new code)

Demos and Documentation

  • demos/: Example notebooks and scripts (BP1994, Overthrust, Marmousi)
  • docker/: Dockerfiles for development and Dask environments
  • Documentation: Quarto documentation website with guides and API reference

Requirements and Environment

  • Python 3.10+; install in editable mode:
    • python -m pip install -e .
  • Devito runtime (Apple M‑series example):
    • DEVITO_ARCH=clang
    • DEVITO_LANGUAGE=openmp
    • DEVITO_PLATFORM=m1
    • OMP_NUM_THREADS=4
  • System toolchain (Homebrew layout):
    • PATH="/opt/homebrew/bin:/opt/homebrew/opt/llvm/bin:$PATH"
    • LD_LIBRARY_PATH="/opt/homebrew/opt/llvm/lib:$LD_LIBRARY_PATH"

Documentation

DevitoHorizon includes comprehensive documentation built with Quarto.

Viewing the Documentation

Option 1: Build and preview locally

Install Quarto: Install instructions

# Then build and preview the docs
cd docs
quarto preview

This will open the documentation in your browser at http://localhost:XXXX.

Option 2: Read markdown directly

The Quarto source files live in docs/: - Home and overview: docs/index.qmd - Tutorials and examples: docs/examples.qmd and docs/examples/ - Customization guides: docs/guides/ - API reference: docs/api.qmd and docs/api/ - Immersed-boundary guide: docs/immersed_boundary.md

Documentation Contents

The documentation includes: - Home: Core concepts, composable workflow, and architecture - Examples: - Basic FWI: Simple full-batch FWI - Stochastic FWI: Mini-batch with shot sampling - Multi-Parameter: VTI inversion - Frequency Continuation: Multi-scale inversion - Immersed Boundary Guide: Topography-aware modeling with signed-distance fields - Customization Guides: Extend misfits, optimizers, I/O, gradient processing, and schedulers - API Reference: Class and function documentation - Architecture: Internal package structure and extension points - Troubleshooting: Common issues and solutions

Quick Start: Run an FWI Demo

  1. SPG (box‑constrained) with L2 misfit
python demos/fwi_marmousi.py \
  --method SPG --misfit l2 --maxiter 5 --batch-size 2 --n-workers 1
  1. Switch misfit to L1 or Student’s‑t
python demos/fwi_marmousi.py --method SPG --misfit l1
python demos/fwi_marmousi.py --method SPG --misfit students
  1. SciPy L‑BFGS variant
python demos/fwi_marmousi.py --method L-BFGS-B --misfit l2 --maxiter 5

Controlling the Data Misfit

  • Choose a built‑in misfit by name: param['misfit'] = 'l2'|'l1'|'students'.
  • Provide a custom pair (phi, dphi):
def phi(x, y):
    return float(np.sum((x - y)**4))
def dphi(x, y):
    return 4.0*(x - y)**3
param['misfit'] = (phi, dphi)
  • Or pass separate entries: param['misfit_fun'], param['misfit_grad'].

Optimizers

  • Select in demos via options['method']:
    • Internal: "SPG", "PQN", "BREGMAN".
    • Any SciPy method string recognized by scipy.optimize.minimize (e.g., "L-BFGS-B", "CG", "TNC", "SLSQP", …).
  • Notes:
    • SPG: projected line search; good for box constraints in m.
    • PQN: L‑BFGS direction + projection; faster local convergence.
    • Bregman: dual iteration with optional transform sparsity (TD/TD_adj).

Optimizer Method Compatibility (SciPy)

When method is not one of our internal optimizers, the driver falls back to scipy.optimize.minimize with jac=True and (optional) bounds= in m‑space. Practical guidance:

  • Common choices
    • L-BFGS-B: supports bounds; good default for smooth problems.
    • CG: ignores bounds; use only if you don’t need box constraints.
    • TNC: supports simple bounds; can be robust but sometimes slower.
    • SLSQP: supports bounds and (non)linear constraints (we only pass bounds).
    • Powell: derivative‑free; ignores bounds unless you pass constraints; slower.
    • trust-constr: supports bounds/constraints; requires Hessian or approximation setup; more verbose to tune.
  • Bounds
    • We pass SciPy bounds derived from either param['vp_bounds'] (converted to m) or a default heuristic if not set.
    • Methods that ignore bounds (e.g., CG) will not enforce them; consider an internal method (SPG/PQN) if you require hard box constraints.
  • Tolerances and iterations
    • The fwi() wrapper forwards maxiter and ftol; some SciPy methods also honor gtol or method‑specific tol options.
    • If convergence is too slow or premature, adjust maxiter, ftol, and consider scaling (e.g., m‑bounds tighter, batch size > 1).
  • Callbacks and logging
    • We provide a callback that can save plots or update batches between iterations.
    • Some SciPy methods may call the callback at different frequencies; monitor the console to verify progress.

Preprocessing (Optional)

  • Build a sequence and apply per‑shot before migration:
from devitohorizon.preprocess import apply_preprocessing
cfg = [
  {"op": "bandpass", "fmin": 5, "fmax": 25},
  {"op": "agc", "window": 1.0},
  {"op": "normalize", "mode": "rms"}
]
rec = apply_preprocessing(rec, dt, cfg, src_pos=src, rec_pos=recpos)

FWI Workflow (High Level)

  1. Load a model and geometry for each shot; preprocess recorded data.
  2. Forward simulate, compute misfit φ(d_syn, d_obs) and adjoint source ∂φ/∂d.
  3. Back‑propagate to accumulate the migration/gradient in m.
  4. Reduce across shots; scale by shot count; project/clip as needed.
  5. Update m with the chosen optimizer; repeat until convergence.

Misfit Demo (Standalone)

  • Explore built‑ins and a custom misfit:
python demos/misfit_demo.py

Cloud/Dask (Optional)

  • Use dask.distributed.LocalCluster locally (--n-workers > 1 in demos).
  • For cloud, see docker/ and devitohorizon/cloud/: azure_vm_cluster on Azure, ec2_cluster on AWS. Both take a credentials file written by scripts/make_azure_creds.sh / scripts/make_aws_creds.sh.
  • Storage follows the same credentials: blob storage when they carry an account name and key, S3 when they say "provider": "s3" or carry access keys.
  • Full setup — registry, IAM/NSG permissions, networking, matching the worker image — is in docs/guides/cloud-setup.qmd.

Testing & Linting

  • Run unit tests: pytest -q
  • Lint: python -m flake8

CLI Example

After installation (python -m pip install -e .), a CLI entry devitohorizon-fwi is available. It is driven entirely by a JSON configuration file:

devitohorizon-fwi --config fwi_config.json

Notes: - The model entry accepts a mapping of parameters (e.g., {"vp": "/path/to/file.h5"} or {"m0": "/path/to/file.h5"}). - data_path is the directory containing shots/, not the shots/ directory itself. - Outputs include per-iteration PNGs and a single fwi_history.h5 with grid and iteration metadata. - SPG enforces strict box constraints and requires bounds; PQN often converges faster locally. - Increase verbosity (e.g., "verbose": 2 under optimizer) to print line-search logs.

JSON Config Example

The CLI is driven by a JSON configuration file.

  1. Create fwi_config.json:
{
  "data_path": "/path/to/shots",
  "model": { "vp": "/path/to/initial_model.h5" },
  "output_dir": "./fwi_out",
  "f0": 0.015,
  "nbl": 40,
  "space_order": 16,
  "misfit": "l2",
  "optimizer": {
    "method": "PQN",
    "batch_size": 4,
    "maxiter": 5,
    "plot": true,
    "save_models": true,
    "verbose": 1
  }
}
  1. Run the CLI with the config:
devitohorizon-fwi --config fwi_config.json

Optional: frequency continuation

{
  "data_path": "/path/to/shots",
  "model": { "vp": "/path/to/initial_model.h5" },
  "output_dir": "./fwi_out",
  "misfit": "l2",
  "optimizer": { "method": "PQN", "batch_size": 4, "plot": true, "save_models": true, "verbose": 2 },
  "continuation": {
    "fmax": [5.0, 10.0, 15.0],   // Hz per band
    "iters": [5, 5, 5],          // iterations per band
    "ppw": 10.0,                 // points-per-wavelength for auto grid spacing
    "shot_fraction": 0.5         // use 50% of shots per band
  }
}

Notes: - model can point to {"vp": ...} or {"m0": ...}; velocity is expected in km/s. - If your model is in m/s, set units via: "units": { "vp": { "in": "m/s" } }. - Choose inversion parameters explicitly with optimizer.parameters (e.g., ["vp", "vs"]) or by setting param["grad_params"]; gradients are now tracked per parameter. - Set optimizer.verbose to 2 to include line-search logs with the Armijo reference value.

Running on a Cluster (SLURM / PBS)

A single srun (or mpirun) spreads the run over every node of the allocation — no separate scheduler or worker setup:

#SBATCH -N 4 --ntasks-per-node=1 --cpus-per-task=48
export OMP_NUM_THREADS=$SLURM_CPUS_PER_TASK
srun devitohorizon-fwi --config fwi_config.json

srun inherits the layout from the #SBATCH directives, so one rank per node comes from --ntasks-per-node=1 in the header. That header matters: a job requesting many tasks per node (-n 96) starts one worker per task, each spawning OMP_NUM_THREADS threads on the same node.

Ready-to-edit job scripts live in scripts/fwi_slurm.sbatch and scripts/fwi_pbs.sh (PBS uses pbsdsh, which numbers its tasks through PBS_NODENUM). Ranks launched with mpirun are recognized too, but prefer a non-MPI launcher: mpirun spends MPI_COMM_WORLD on one rank per worker, which is in the way if shots are later decomposed across ranks.

Every rank runs the same program, so the CLI decides per rank what to be: rank 0 starts the Dask scheduler and drives the inversion, every rank (including rank 0) runs a worker, and the workers exit when the inversion finishes. Ranks find each other through a scheduler file written next to output_dir.

output_dir must be on a filesystem shared by every node. Workers load the staged model from it and rendezvous through it; on node-local storage the workers never see the scheduler file and time out with an error saying so.

Use one task per node and give the cores to OpenMP: Devito parallelizes a single shot with OpenMP while each Dask worker runs one shot at a time. Beware that nproc reports OMP_NUM_THREADS rather than the allocation, so set it explicitly.

Optional dask settings in the config:

key default meaning
scheduler_file next to output_dir explicit rendezvous path
address – connect to an already-running scheduler instead
worker_on_driver true also run a worker on rank 0
worker_nthreads 1 Dask threads per worker (leave at 1 for OpenMP)
worker_memory_limit 0 (off) Dask’s monitor otherwise restarts workers mid-shot
worker_local_directory – worker spill directory, e.g. node-local scratch
startup_timeout 300 seconds to wait for rendezvous and workers
workers_per_rank 1 Dask workers started per rank; split a fat node between shots
rendezvous_dir output_dir directory holding the scheduler file
scheduler_port – fix the scheduler port instead of taking a free one
dashboard false serve the Dask dashboard (off by default on batch nodes)
n_workers – single-node local cluster, when not under a launcher
threads_per_worker 1 threads per worker for that local cluster

Chevron GOM Example

  • Tutorial notebook: demos/ChevronGOM/chevron_fwi_tutorial.ipynb
  • Configuration: demos/ChevronGOM/chevron_fwi.json

Follow the instructions in demos/ChevronGOM/FULL_FWI.md to preview the data, compute an initial gradient on four shots, and run the full three-sweep, four-band continuation using devitohorizon-fwi.

Tips

End‑to‑End FWI Example (Code)

Below is a compact example stitching the pieces together without using the CLI scripts. This is helpful if you want to run FWI from a notebook or your own driver.

import os
from distributed import LocalCluster
from dask.distributed import Client

from devitohorizon.data import Dataset
from devitohorizon.optimization import SPG
from devitohorizon.physics import DevitoPhysics
from devitohorizon.scheduler import create_scheduler

data_dir = os.path.join("demos", "marmousi")
physics = DevitoPhysics(
    nbl=40,
    space_order=16,
    model={"m0": os.path.join(data_dir, "marmousi_model.h5")},
    misfit="l2",
)
dataset = Dataset.from_segy(os.path.join(data_dir, "shots.segy"))

# Optional Dask client
cluster = LocalCluster(n_workers=2, threads_per_worker=1, dashboard_address=None)
client = Client(cluster)

optimizer = SPG(maxiter=5, ftol=1e-6, batch_size=2)
model_opt, f_opt, result = optimizer.fwi(
    physics=physics,
    dataset=dataset,
    model0=physics.model,
    bounds={'vp': (1.5, 5.0)},
    scheduler=create_scheduler(client),
)

print({"final_objective": f_opt, "iterations": result.nit})

client.close()
cluster.close()

Need continuation? Build per-band datasets/physics and call devitohorizon.inversion.fwi.run_frequency_continuation, which simply loops over bands while calling optimizer.fwi under the hood:

from devitohorizon.inversion.fwi import run_frequency_continuation
from devitohorizon.model import resample_model
from devitohorizon.scheduler import create_scheduler

bands = [
    {
        "dataset": dataset_low,
        "physics_factory": lambda model: DevitoPhysics(..., preprocess=low_pass, model=model),
        "model": start_model_low,
        "maxiter": 5,
        "label": "6 Hz",
    },
    {
        "dataset": dataset_high,
        "physics_factory": lambda model: DevitoPhysics(..., preprocess=mid_band, model=model),
        "model_transform": lambda model: resample_model(model, (25.0, 25.0)),
        "maxiter": 10,
        "label": "10 Hz",
    },
]

model_opt, f_opt, result, history = run_frequency_continuation(
    optimizer,
    bands=bands,
    bounds={'vp': (1.5, 5.0)},
    scheduler=create_scheduler(client),
)

Parameter Reference

For a complete reference of runtime configuration, see docs/api/overview.qmd and the broader API Reference.

Quick Reference

Essential param parameters: - param['model']: Path to model file (e.g., "models/initial.h5") - param['data_path']: Path to observed data directory - param['source']: Source type: 'ricker' or path to wavelet file - param['f0']: Peak frequency in kHz (required for Ricker) - param['nbl']: Absorbing boundary layers (default: 40) - param['space_order']: FD stencil order (default: 8)

Essential options parameters: - options['method']: Optimizer: 'L-BFGS-B', 'SPG', 'PQN', 'BREGMAN' - options['batch_size']: Shots per iteration (default: 8) - options['mute']: Gradient muting: 'water', 'datum', or None - options['parameters']: Parameters to invert (default: ('m',))

Key distinction: param controls physics/modeling, options controls optimization/FWI.

CLI cheatsheet: - SPG: python demos/fwi_marmousi.py --method SPG --misfit l2 --maxiter 5 - L‑BFGS: python demos/fwi_marmousi.py --method L-BFGS-B --misfit l1 --maxiter 5

Troubleshooting

  • Devito/OpenMP on macOS (Apple Silicon): install brew install llvm and set PATH and LD_LIBRARY_PATH per the environment section.
  • Matplotlib cache errors in headless runs: set MPLCONFIGDIR=/tmp/mpl.
  • Gradients look zero/NaN: verify tn/nt are long enough to cover the record; check preprocessing (mute/filters) and that your misfit gradient matches phi.
  • Convergence too slow with SPG: try PQN or increase batch_size.
  • Misfit scaling: we multiply both objective and adjoint source by dt to be consistent with discrete time integration; ensure your custom dphi is gradient w.r.t. the first argument (synthetic data).

Contributing

Issues and PRs are welcome. Please include: - A minimal, runnable snippet or command showing the problem. - Any relevant logs (Devito INFO output helpful for performance/shape issues). - If you propose a new misfit/optimizer, add a short README under the submodule and a small demo. - Keep OMP_NUM_THREADS conservative when using Dask. - Large volumes: prefer external storage with fsspec/adlfs/zarr. - To integrate a new misfit or optimizer, follow the patterns in misfits.py and optim/.

Back to top