Optimizers API
Optimization algorithms for FWI
DevitoHorizon provides several optimization algorithms for Full Waveform Inversion, all ported from the MATLAB minConf package by Mark Schmidt. All optimizers inherit from the abstract Optimizer base class and provide both low-level minimize() and high-level fwi() methods.
Module: devitohorizon.optimization
from devitohorizon.optimization import (
Optimizer, # Abstract base class
SPG, # Spectral Projected Gradient
PQN, # Projected Quasi-Newton
TMP, # Two-Metric Projection
BREGMAN, # Split Bregman
)Base Class: Optimizer
All optimizers inherit from this abstract base class.
Constructor
Optimizer(
maxiter: int = 50, # Maximum iterations
ftol: float = 1e-6, # Function tolerance
gtol: float = 1e-8, # Gradient tolerance
verbose: bool = True, # Print progress
output_dir: str = None, # Save directory
save_models: bool = True, # Save model checkpoints
plot: bool = True, # Generate plots
save_every: int = 1, # Save frequency
batch_size: int = None, # Shot batch size (stochastic)
shot_fraction: float = None, # Fraction of shots per batch
shot_pool: list = None, # Restrict to specific shots
seed: int = None, # Random seed for reproducibility
)Methods
minimize(fun_and_grad, x0, bounds, callback)
Low-level optimization interface.
Parameters:
| Parameter | Type | Description |
|---|---|---|
fun_and_grad |
callable | Function returning (f, g) tuple |
x0 |
ndarray | Initial parameter vector |
bounds |
list of tuple | Box constraints [(lower, upper), ...] |
callback |
callable | Called after each iteration with x |
Returns:
OptimizationResultwith fields:x,fun,nit,feval,success,message
Example:
def rosenbrock(x):
f = sum(100*(x[1:]-x[:-1]**2)**2 + (1-x[:-1])**2)
g = np.zeros_like(x)
g[:-1] = -400*x[:-1]*(x[1:]-x[:-1]**2) - 2*(1-x[:-1])
g[1:] += 200*(x[1:]-x[:-1]**2)
return f, g
optimizer = SPG(maxiter=100)
result = optimizer.minimize(
rosenbrock,
x0=np.zeros(10),
bounds=[(-5, 5)] * 10,
)
print(f"Optimal value: {result.fun}")fwi(physics, dataset, model0, bounds, callback, scheduler, sampling, rtm)
High-level FWI interface.
Parameters:
| Parameter | Type | Description |
|---|---|---|
physics |
Physics | Forward/adjoint modeling engine |
dataset |
Dataset or list | Seismic shot data |
model0 |
WaveModel | Initial velocity model |
bounds |
dict | Parameter bounds, e.g., {'vp': (1.5, 5.0)} |
callback |
callable | Called after each iteration with model |
scheduler |
Scheduler | Parallel scheduler (optional) |
sampling |
SamplingConfig | Shot sampling configuration (optional) |
rtm |
bool | Compute RTM image at optimal model (default: False) |
Returns:
(model_opt, f_opt, result)tuple
Example:
from devitohorizon.data import Dataset
from devitohorizon.physics import DevitoPhysics
from devitohorizon.optimization import SPG
dataset = Dataset.from_segy("shots.segy")
physics = DevitoPhysics(nbl=40, space_order=8)
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)},
)SPG: Spectral Projected Gradient
Nonlinear optimization using spectral gradient method with projection onto box constraints. Port of MATLAB minConf_SPG.
Constructor
SPG(
maxiter: int = 50,
ftol: float = 1e-6,
gtol: float = 1e-8,
verbose: bool = True,
alpha0: float = None, # Initial spectral step (from init_step_frac if None)
init_step_frac: float = 0.05, # First update: at most 5% of each cell's value
max_step_frac: float = 0.2, # Later updates: at most 20% (None: uncapped)
step_percentile: float = 100.0, # Percentile of |g|/|x| the fractions use
first_order_ls: bool = True, # Cheap line search for FWI
nm_memory: int = 3, # Non-monotone memory
max_backtracks: int = 10, # Max backtracks (first-order LS)
decrease: str = 'relative', # Sufficient-decrease rule: 'relative' or 'armijo'
**kwargs,
)Algorithm details
- Spectral step size: Barzilai-Borwein formula
alpha = s'*s / s'*y, clipped to(1e-10, 1e10] - Line search: Non-monotone Armijo with cubic polynomial interpolation (
polyinterp). Reference value ismax(f_{i-M}, ..., f_i)with memorynm_memory. - Convergence: Projected optimality
max(|P(x - g) - x|) < gtol, progress tolerance|f_{k} - f_{k-1}| < ftol, step sizemax(|t*d|) < ftol. - First-order LS: When
first_order_ls=Trueand a cheap misfit-only evaluation is available (FWI mode), backtracking uses only forward solves, avoiding adjoint solves on rejected steps. - Sufficient decrease: both rules test a trial against the non-monotone reference above, the max of the misfit history, also when the mini-batch is redrawn every iteration.
decrease='relative'(the default of SPG, PQN and TMP) asks it to fall below that reference by a fractionc1of it and never readsg.d, since an FWI gradient is rarely on the scale of its objective;'armijo'is the classical rule. - Log slowness:
mZis always inverted aslog m, so a step is a relative change of every cell; the bounds and the relative step caps still apply to the parameter itself.
MATLAB parameter mapping
MATLAB (minConf_SPG) |
Python (spg()) |
Default |
|---|---|---|
maxIter |
maxiter |
500 |
optTol |
gtol |
1e-5 |
progTol |
ftol |
1e-9 |
memory |
nm_memory |
3 (MATLAB: 10) |
suffDec |
(hardcoded) | 1e-4 |
interp |
interp |
2 (cubic) |
bbType |
bb_type |
1 |
Example
optimizer = SPG(
maxiter=30,
ftol=1e-7,
gtol=1e-9,
alpha0=1.0,
first_order_ls=True,
output_dir='/tmp/fwi',
save_every=5,
)
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
)PQN: Projected Quasi-Newton
Limited-memory BFGS with projected sub-problem solver. Port of MATLAB minConf_PQN.
Constructor
PQN(
maxiter: int = 50,
ftol: float = 1e-6,
gtol: float = 1e-8,
verbose: bool = True,
memory: int = 3, # Number of L-BFGS correction pairs
nm_memory: int = 3, # Non-monotone memory (first-order LS)
max_backtracks: int = 10,
max_step_frac: float = None, # Cap on every update (None: uncapped)
step_percentile: float = 100.0, # Percentile of |d|/|x| the cap uses
**kwargs,
)Algorithm details
- L-BFGS: Compact representation using
lbfgs_updateandlbfgs_hv_funcfor Hessian-vector products. Curvature pairs accepted wheny'*s > 1e-10. - Sub-problem: The quasi-Newton direction is found by solving
min g'(p-x) + 0.5*(p-x)'*H*(p-x) s.t. p in Cusing an embedded SPG solver (matching MATLABsolveSubProblem). - Line search: Monotone Armijo with cubic polynomial interpolation. Uses
sum(|t*d|) < progTolfor step size check. - BB initialization: Optional Barzilai-Borwein initialization of the sub-problem (
bb_init=True).
MATLAB parameter mapping
MATLAB (minConf_PQN) |
Python (pqn()) |
Default |
|---|---|---|
maxIter |
maxiter |
500 |
optTol |
gtol |
1e-5 |
progTol |
ftol |
1e-9 |
corrections |
m |
10 |
bbInit |
bb_init |
False |
SPGoptTol |
spg_opt_tol |
1e-6 |
SPGiters |
spg_iters |
10 |
Example
optimizer = PQN(
maxiter=20,
memory=5,
verbose=True,
)
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
)Limiting the step
Both optimizers measure a step per cell, as a fraction of that cell’s own value, so the same number means the same thing in slow and fast parts of the model. The first update moves no cell by more than 5% (SPG, init_step_frac) or 1% (PQN). max_step_frac caps every later update:
SPG(maxiter=20, max_step_frac=0.05) # default 0.2
PQN(maxiter=20, max_step_frac=0.05) # default None, uncappedPQN needs the cap more than SPG does. Its direction minimizes a quadratic model of the misfit, and where the measured curvature is small for the gradient’s scale that minimizer sits on the bounds: uncapped, a single iteration can move cells by many times their value. In a JSON config the same keys go under optimizer, e.g. {"method": "PQN", "max_step_frac": 0.05}.
With step_percentile below 100 the bound is read at that percentile of the per-cell ratio, so the few cells above it (next to sources, typically) may move further; the box bounds still hold them.
When to Use
- When you need faster convergence than SPG
- When the problem is well-conditioned
- When memory allows storing correction pairs
TMP: Two-Metric Projection
Box-constrained optimization with working-set management. Port of MATLAB minConf_TMP.
Constructor
TMP(
maxiter: int = 500,
ftol: float = 1e-6,
gtol: float = 1e-6,
verbose: bool = True,
method: str = "lbfgs", # 'lbfgs' or 'sd'
corrections: int = 100, # L-BFGS corrections
**kwargs,
)Algorithm details
- Working set: At each iteration, variables at their bounds with non-improving gradients are frozen. The search direction is computed only on the free (working) variables.
- L-BFGS: Applied to the working set with curvature pair filtering. Pairs with insufficient curvature on the current working set are skipped.
- Line search: Armijo with cubic interpolation. Trial points are projected onto bounds.
- Convergence: Working-set optimality
||g_working|| <= gtol, step size, and function change checks.
MATLAB parameter mapping
MATLAB (minConf_TMP) |
Python (tmp()) |
Default |
|---|---|---|
maxIter |
maxiter |
500 |
optTol |
gtol |
1e-6 |
method |
method |
‘lbfgs’ |
corrections |
corrections |
100 |
interp |
interp |
1 (cubic) |
Example
optimizer = TMP(
maxiter=30,
method="lbfgs",
verbose=True,
)
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
)When to Use
- When many bound constraints are expected to be active
- As an alternative to PQN for box-constrained problems
- When you want working-set identification
BREGMAN: Split Bregman
Iterative shrinkage/thresholding for L1-regularized problems.
Constructor
BREGMAN(
maxiter: int = 50,
ftol: float = 1e-6,
gtol: float = 1e-8,
verbose: bool = True,
tau: float = 1.0, # Shrinkage threshold
**kwargs,
)Features
- L1 regularization: Promotes sparse solutions
- Split Bregman iteration: Efficient for constrained problems
- Shrinkage operator: Soft thresholding for sparsity
Example
optimizer = BREGMAN(
maxiter=30,
tau=0.5, # Lower = more sparsity
verbose=True,
)
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
)When to Use
- When you want to promote sharp boundaries
- For denoising or image reconstruction
- When prior knowledge suggests sparse model updates
OptimizationResult
Result container returned by all optimizers.
Fields
| Field | Type | Description |
|---|---|---|
x |
ndarray | Optimal parameter vector |
fun |
float | Optimal objective value |
nit |
int | Number of iterations |
feval |
int | Number of function evaluations |
geval |
int | Number of gradient evaluations |
success |
bool | Whether optimization converged |
message |
str | Convergence message |
rtm_image |
ndarray or None | RTM image (when rtm=True) |
Example
result = optimizer.minimize(fun_and_grad, x0, bounds)
print(f"Converged: {result.success}")
print(f"Iterations: {result.nit}")
print(f"Function evaluations: {result.feval}")
print(f"Gradient evaluations: {result.geval}")
print(f"Final objective: {result.fun:.6e}")
print(f"Message: {result.message}")Stochastic/Mini-Batch FWI
Configure shot sampling for stochastic optimization:
from devitohorizon.config import SamplingConfig
# Option 1: Constructor parameters
optimizer = SPG(
maxiter=50,
batch_size=8, # Shots per iteration
seed=42, # Reproducibility
)
# Option 2: SamplingConfig
sampling = SamplingConfig(
batch_size=8,
shot_fraction=0.1, # Alternative: use 10% of shots
shot_pool=[0, 5, 10], # Restrict to specific shots
seed=42,
)
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
sampling=sampling,
)Parallel Execution
Use a scheduler for parallel shot computation:
from dask.distributed import Client
from devitohorizon.scheduler import create_scheduler
# Start Dask cluster
client = Client(n_workers=4, threads_per_worker=2)
scheduler = create_scheduler(client)
# Pass to fwi
model_opt, f_opt, result = optimizer.fwi(
physics, dataset, model0,
bounds={'vp': (1.5, 5.0)},
scheduler=scheduler,
)Custom Optimizers
Implement custom algorithms by subclassing Optimizer:
from devitohorizon.optimization import Optimizer
from devitohorizon.config import OptimizationResult
class MyOptimizer(Optimizer):
def minimize(self, fun_and_grad, x0, bounds=None,
callback=None):
x = x0.copy()
for it in range(self.maxiter):
f, g = fun_and_grad(x)
x = x - 0.01 * g
if bounds:
lower = np.array([b[0] for b in bounds])
upper = np.array([b[1] for b in bounds])
x = np.clip(x, lower, upper)
if callback:
callback(x)
return OptimizationResult(
x=x, fun=f, nit=self.maxiter, success=True,
)See Custom Optimizers Guide for detailed examples.