Custom Solvers
Plugging your own wave-equation propagator into DevitoPhysics
DevitoHorizon’s forward and adjoint runs are driven by a solver — a class that builds the time-stepping operators, wires the source/receiver acquisition, and exposes the imaging condition. The default solver (HorizonSolver) wraps the recipe registered for the model’s physics and adds the Devito Horizon FWI imaging condition (ISIC for acoustic, parent sensitivity for elastic, illumination accumulation, damping/impedance handling).
When the default does not match your needs — different stencil, alternate imaging condition, custom wave-equation physics — you can supply your own solver class via the solver= parameter on DevitoPhysics.
Contract
A custom solver must:
- Be a subclass of
recipes.Propagator. - Be instantiable as
solver(model, opt)wheremodelis therecipes.WaveModelto run on andoptis the dict produced byget_fwi_solver_options(plus anoutput_dirkey for the operator cache). - Implement the methods called by
DevitoPhysics:fwd_op,jacobian_adj_op,forward,jacobian_adjoint,src,rec,perturbation,saved_state,state,field_so,_reset. Subclassing an existing recipe (e.g.recipes.AcousticIsotropic) gives you all of these for free.
Gradient contract
solver.perturbation(param=p).data holds the sensitivity kernel for parameter p after jacobian_adjoint runs. Whether that kernel is \(g_p\) (linear) or \(g_{\log p}\) (log-domain) is the solver’s choice and is declared via a class attribute:
class MyAcousticSolver(AcousticIsotropic):
# Omit entirely if your kernel produces g_m directly.
gradient_kind = {'m': 'log'} # kernel accumulates g_{log m}
def sensitivity(self, params=('m',)):
...DevitoPhysics.adjoint reads gradient_kind and applies the \(1/p\) chain rule numerically (using the current model field values) so that the optimizer always sees \(g_p\) for the user’s chosen parameter p.
See Parameterizations and the gradient contract and the ISIC derivation.
DevitoHorizon never adds the HorizonSolver imaging extras on top of a user-supplied class — your solver is responsible for its own imaging condition. The on-disk operator pickling layer (FWISolverImpl) is always added so cached operators survive across shots and Dask workers.
DevitoPhysics.forward / .adjoint always pass an illum= keyword (the source-illumination accumulator). The FWISolverImpl wrapper inspects the compiled operator’s input list and forwards illum only when the operator declares it — so a bare recipes.Propagator subclass that does not produce an illum field works without any extra boilerplate.
Quick start
from recipes import AcousticIsotropic
from devitohorizon.physics import DevitoPhysics
class MySolver(AcousticIsotropic):
"""Acoustic propagator with my own imaging condition."""
def sensitivity(self, params=('m',)):
# Custom imaging condition here
return super().sensitivity(params=params)
physics = DevitoPhysics(
nbl=40,
space_order=8,
parameters=('m',),
solver=MySolver, # <-- plug in your class
)solver= accepts a class, not an instance — DevitoPhysics instantiates it once per shot with the per-shot working model.
Reusing the Horizon imaging condition
HorizonSolver(base_cls) returns a new class layered on top of a recipe with the default Horizon imaging extras (save_expr, extra, sensitivity, _prepare_kw). You can subclass it when you want to keep most of the defaults and only augment one piece:
from recipes import recipes_registry
from devitohorizon.physics import DevitoPhysics, HorizonSolver
HorizonAcoustic = HorizonSolver(recipes_registry['iso-acoustic'])
class MySolver(HorizonAcoustic):
@property
def extra(self):
# Augment Horizon's illumination accumulation with your own term
eqs = list(super().extra)
eqs.append(my_extra_equation())
return eqs
physics = DevitoPhysics(solver=MySolver)Using the factories directly
For one-off scripts or when you want full control over solver construction (no DevitoPhysics wrapper), use create_fwi_solver:
from devitohorizon.physics import create_fwi_solver
from devitohorizon.physics.solver import get_fwi_solver_options
opt = get_fwi_solver_options(model, nt=1000)
opt['output_dir'] = '/tmp/op_cache'
# Default Horizon solver
solver = create_fwi_solver(model, opt, physics_name='iso-acoustic')
# Custom solver — only pickling is added on top
solver = create_fwi_solver(model, opt, solver_cls=MySolver)Factory reference
| Factory | Purpose |
|---|---|
HorizonSolver(base_cls) |
Wraps a Propagator subclass with the default Horizon FWI imaging condition (save_expr, extra, sensitivity, _prepare_kw, Hz→kHz f0 conversion). |
FWISolverImpl(base_cls) |
Wraps a Propagator subclass with operator pickling — fwd_op and jacobian_adj_op are cached under <output_dir>/.operator_cache/. Nothing else is added. |
create_fwi_solver(model, opt, solver_cls=None, physics_name=None) |
Builds and instantiates the final solver. When solver_cls is None, uses HorizonSolver(recipes_registry[physics_name]). Always wraps the result with FWISolverImpl. |
The two factories produce class types, not instances. They are class factories (similar to collections.namedtuple) and can be composed: FWISolverImpl(HorizonSolver(AcousticIsotropic)) is the layering used by default.
What opt contains
get_fwi_solver_options(model, nt, tn=None, physics=...) returns a dict with at least:
| Key | Purpose |
|---|---|
save |
Snapshot mode for the forward wavefield (always 'disk' for FWI) |
nt |
Number of time steps |
t_sub |
Snapshot subsampling factor |
coefficients |
FD coefficients scheme ('lsqr_drp') |
abox |
Use the ABox subdomain (disabled when SDF is present) |
compression |
Snapshot compression scheme (language-dependent) |
space_order |
Spatial discretization order |
factorization |
Stiffness factorization flag (1 for TTI-elastic) |
DevitoPhysics adds:
| Key | Purpose |
|---|---|
output_dir |
Cache root used by FWISolverImpl for pickled_meth. Cache files are written under <output_dir>/.operator_cache/. |
f0 |
Source peak frequency (Hz). HorizonSolver converts to kHz; custom solvers receive the raw Hz value and are responsible for their own unit handling. |
A custom solver may consume or ignore any of these keys. Unknown keys are passed through to the parent Propagator.__init__ unchanged.
Operator pickling and Dask workers
FWISolverImpl is the wrapper that decorates fwd_op and jacobian_adj_op with pickled_meth. The first call compiles and serializes the operator under <output_dir>/.operator_cache/; subsequent calls — including from Dask workers on a shared filesystem — load the cached operator instead of recompiling.
The cache key is built from the method’s structural kwargs, the grid spacing, and the save mode. The output_dir key is intentionally excluded so that operators pre-compiled by the main process match the keys computed by workers, even when their output_dir paths differ.
For models with an SDF (immersed boundary), caching is skipped because operator pickling is not yet supported with cut-cell stencils.
Validating a custom solver
DevitoPhysics validates at construction time:
>>> DevitoPhysics(solver=int)
TypeError: `solver` must be a recipes.Propagator subclass, got <class 'int'>.
>>> DevitoPhysics(solver=MyPropagator()) # instance, not class
TypeError: `solver` must be a recipes.Propagator subclass, ...A useful round-trip test for any custom solver is the Born/adjoint dot product:
def adjoint_dot_test(physics, model, shot):
"""⟨J δm, δd⟩ ≈ ⟨δm, J^T δd⟩."""
import numpy as np
rng = np.random.default_rng(0)
# Forward + Born
sim = physics.simulate_shot(shot, save_wavefields=True)
dm = rng.normal(size=model.shape).astype(np.float32)
# ... apply solver.jacobian(dm) and solver.jacobian_adjoint(dd)
# and compare the two inner products.See Also
- Customization Overview
- Custom Misfits — Custom objective functions
- Custom Gradient Processing
- API Reference: Physics — Full physics API
recipes.Propagator— base class for all wave-equation propagators