Skip to main content

Crate differential_equations

Crate differential_equations 

Source
Expand description

Numerical ordinary differential equation solvers with a compact Rust API.

The crate provides in-place first-order ODE problems, solver options, callbacks (including vector event conditions and exact preset-time effects), retained dense output, and ordered ensemble execution. Concrete algorithms are grouped by family below solvers; core problem, solution, and driver types remain at the crate root.

§Quickstart

use differential_equations::solvers::explicit::Tsit5;
use differential_equations::{OdeProblem, SaveMode, SolveOptions, solve};

let problem = OdeProblem::new(
    |derivative: &mut [f64], state: &[f64], rate: &f64, _time: f64| {
        derivative[0] = rate * state[0];
    },
    [1.0],
    (0.0, 1.0),
    -2.0,
);
let options = SolveOptions::new()
    .with_tolerances(1.0e-9, 1.0e-9)
    .with_save(SaveMode::Endpoints);

let solution = solve(&problem, Tsit5, &options)?;
assert!(solution.last_state()[0] < 0.14);

§API organization

  • OdeProblem describes a first-order initial-value problem and optional Jacobian or callback behavior. OdeProblem::with_preset_time_callback schedules effects at exact integration times without duplicating them in SolveOptions::time_stops, while CallbackSave selects whether the callback’s left limit, affected state, both, or neither are retained. CallbackSet composes callback policies before attaching them to a first-order or split problem and provides initialization/finalization hooks around successful integration. Vector continuous callbacks group several root functions; they are separate from ndarray state shape. callbacks::DomainGuard rejects out-of-domain candidate states before callback effects or trajectory saving. callbacks::PositiveDomain cheaply restricts upcoming steps and clamps accepted states to preserve componentwise non-negativity. callbacks::ManifoldProjection enforces implicit conservation laws with rectangular residuals and typed nonlinear failure. callbacks::GeneralDomain couples that projection engine with predictive step control for a user-defined domain residual. CallbackAction::ContinueWithStepSize overrides the next proposed step; Rust interior-mutability types such as std::cell::Cell let sequential callback effects update parameters without imposing mutable problem ownership on every solve.
  • callbacks contains reusable integration-time policies. Its periodic and iterative schedulers use constant memory; callbacks::IterativeCallback chooses each next event from the state after the previous effect. callbacks::TerminateSteadyState stops when the problem’s derivatives satisfy independent componentwise tolerances. Its function-calling policy marks read-only observations explicitly, and its step-size limiter applies dynamic stability bounds without interfering with smaller adaptive steps.
  • SolveOptions controls tolerances, step sizes, exact time stops, saved output, and dense output retention; solve runs an OdeAlgorithm.
  • solvers::explicit is a good starting point for non-stiff problems, solvers::rosenbrock contains linearly implicit stiff methods, and solvers::automatic contains in-flight non-stiff/stiff composites with configurable hysteresis and observable branch statistics.
  • tableau exposes the extension surface for defining explicit Runge–Kutta and Runge–Kutta–Nyström methods from compile-time-validated JSON resources, plus typed data for specialized solver families.
  • OdeProblem::builder names the initial state, time span, parameters, and ndarray evaluation style. OdeProblem::from_array remains the compact constructor for scalar, vector, and matrix states while numerical kernels retain contiguous flat workspaces. OdeProblem::from_array_out_of_place accepts functions returning arrays; OdeFunction unifies them with in-place closures and propagates errors. solvers::second_order::SecondOrderOdeProblem provides matching ndarray constructors while keeping velocity and position partitions separate.
  • solve_ensemble and solve_batch preserve input order. The default parallel feature also enables their Rayon-backed variants.

§Features

The public Cargo feature surface is intentionally small:

  • parallel is enabled by default and adds Rayon-backed independent solves.
  • serde adds validated, versioned serialization of solutions and portable dense segments. It is independent of parallel execution.
  • allocation-metrics enables repository benchmark instrumentation and is not needed by ordinary users.

Disabling default features selects sequential ensemble execution. State shape is part of the core API, not a feature: ndarray scalar, vector, and matrix adapters remain available with default-features = false. There are no vector, matrix, or ndarray feature flags.

§Errors and panics

Public solve functions return SolveError for invalid dimensions, non-finite inputs, unsupported option/algorithm combinations, and numerical failure. Problem right-hand sides, Jacobians, and callbacks are user code; a panic in one of them is not caught by the solver. In-place right-hand sides and Jacobians must fill their complete output buffers, and callback effects must preserve the problem’s state dimension.

§Further reading

The packaged repository documentation includes the solver-selection and scope guide in the README and the compile-time tableau resource guide. Contributors can use the performance regression guide to compare stable benchmark IDs locally.

Re-exports§

pub use gauss_jackson::GaussJackson8;
pub use gauss_jackson::GaussJacksonConfig;
pub use gauss_jackson::GaussJacksonError;
pub use gauss_jackson::GaussJacksonStatistics;
pub use gauss_jackson::GaussJacksonStep;
pub use scoped_problem::ScopedOdeProblem;
pub use scoped_problem::ScopedSecondOrderProblem;
pub use ndarray;

Modules§

callbacks
Reusable callback policies built on crate::CallbackSet.
gauss_jackson
Fixed-step eighth-order Gauss–Jackson integration of q'' = a(t, q, v).
scoped_problem
Borrowed and thread-eligible problem storage for reusable solvers.
solvers
Numerical algorithms organized by solver family.
state_layout
Explicit matrix-to-state layout adapters.
stepping
Reusable, output-free numerical stepping with explicit commit/reject lifecycle.
tableau
Lazily parsed, resource-backed solver tableaus.
tolerances
Component and block error control for reusable solver attempts.

Structs§

CallbackSet
An ordered collection of callbacks that can be attached to an ODE problem.
CaseOutcome
The indexed result of one independent case.
DenseSegmentData
Version-one polynomial representation for interchange.
LieGroupProblem
A homogeneous-space or matrix Lie-group problem driven by a dense Lie algebra generator.
LinearOperatorProblem
A vector problem driven by a dense, possibly state- and time-dependent linear operator: u' = A(u, p, t) u.
MutableFunction
Sequential adapter for a mutable, fallible in-place right-hand side.
OdeProblem
An initial-value ordinary differential equation problem.
OdeProblemBuilder
A type-state builder for an ndarray-backed OdeProblem.
PortableDenseSegment
Validated immutable polynomial segment, safe to move or share across threads.
SemilinearOdeProblem
A semilinear initial-value problem u' = A u + g(u, p, t).
Solution
A saved ODE trajectory.
SolutionData
Versioned trajectory interchange including logical state shape and dense output. Work statistics describe the original integration and are preserved.
SolveOptions
Common options for adaptive ODE solvers.
SolverStats
Work performed by an ODE solver.
SplitOdeProblem
A split/IMEX ODE representation retaining explicit and implicit components.

Enums§

AutomaticPairIncompatibility
Explains why two components cannot be used as an automatic solver pair.
CallbackAction
The action requested after an ODE callback runs.
CallbackSave
Selects which states a callback forces into the saved trajectory.
ConfigurationError
Invalid data supplied while constructing a problem or algorithm.
EventCrossing
Describes whether and how one vector callback condition crossed zero.
EventDirection
Selects which zero crossings trigger a continuous callback.
ExecutionPolicy
Selects how independent cases are executed.
InterpolationError
A dense-output query or retained interpolation segment is invalid.
InterpolationQuality
Quality available for an interpolation query.
SaveMode
Controls which accepted states are retained in a Solution.
SolutionConstructionError
Invalid saved trajectory data supplied when constructing a Solution.
SolveError
A failure to configure or complete an ODE solve.

Constants§

DEFAULT_EVENT_TOLERANCE
Default requested absolute tolerance for continuous-event localization.

Traits§

OdeAlgorithm
An ODE integration algorithm.
OdeFunction
A statically dispatched, fallible ODE right-hand side.

Functions§

solve
Solves an ODE problem with a selected algorithm.
solve_batch
Runs independent fallible cases as an ordered batch.
solve_batch_parallel
Runs independent fallible cases on Rayon’s global thread pool.
solve_batch_sequential
Runs independent fallible cases sequentially without thread-safety bounds.
solve_ensemble
Solves an ensemble of independently constructed ODE problems.
solve_ensemble_parallel
Solves an ODE ensemble on Rayon’s global thread pool.
solve_ensemble_sequential
Solves an ODE ensemble sequentially without requiring transferable problems.