differential_equations/lib.rs
1//! Numerical ordinary differential equation solvers with a compact Rust API.
2//!
3//! The crate provides in-place first-order ODE problems, solver options,
4//! callbacks (including vector event conditions and exact preset-time effects),
5//! retained dense output, and
6//! ordered ensemble execution. Concrete
7//! algorithms are grouped by family below [`solvers`]; core problem, solution,
8//! and driver types remain at the crate root.
9//!
10//! # Quickstart
11//!
12//! ```
13//! use differential_equations::solvers::explicit::Tsit5;
14//! use differential_equations::{OdeProblem, SaveMode, SolveOptions, solve};
15//!
16//! let problem = OdeProblem::new(
17//! |derivative: &mut [f64], state: &[f64], rate: &f64, _time: f64| {
18//! derivative[0] = rate * state[0];
19//! },
20//! [1.0],
21//! (0.0, 1.0),
22//! -2.0,
23//! );
24//! let options = SolveOptions::new()
25//! .with_tolerances(1.0e-9, 1.0e-9)
26//! .with_save(SaveMode::Endpoints);
27//!
28//! let solution = solve(&problem, Tsit5, &options)?;
29//! assert!(solution.last_state()[0] < 0.14);
30//! # Ok::<(), differential_equations::SolveError>(())
31//! ```
32//!
33//! # API organization
34//!
35//! - [`OdeProblem`] describes a first-order initial-value problem and optional
36//! Jacobian or callback behavior. [`OdeProblem::with_preset_time_callback`]
37//! schedules effects at exact integration times without duplicating them in
38//! [`SolveOptions::time_stops`], while [`CallbackSave`] selects whether the
39//! callback's left limit, affected state, both, or neither are retained.
40//! [`CallbackSet`] composes callback policies before attaching them to a
41//! first-order or split problem and provides initialization/finalization
42//! hooks around successful integration. Vector continuous callbacks group
43//! several root functions; they are separate from ndarray state shape.
44//! [`callbacks::DomainGuard`] rejects out-of-domain candidate states before
45//! callback effects or trajectory saving.
46//! [`callbacks::PositiveDomain`] cheaply restricts upcoming steps and clamps
47//! accepted states to preserve componentwise non-negativity.
48//! [`callbacks::ManifoldProjection`] enforces implicit conservation laws
49//! with rectangular residuals and typed nonlinear failure.
50//! [`callbacks::GeneralDomain`] couples that projection engine with
51//! predictive step control for a user-defined domain residual.
52//! [`CallbackAction::ContinueWithStepSize`] overrides the next proposed step;
53//! Rust interior-mutability types such as [`std::cell::Cell`] let sequential
54//! callback effects update parameters without imposing mutable problem
55//! ownership on every solve.
56//! - [`callbacks`] contains reusable integration-time policies. Its periodic
57//! and iterative schedulers use constant memory; [`callbacks::IterativeCallback`]
58//! chooses each next event from the state after the previous effect.
59//! [`callbacks::TerminateSteadyState`] stops when the problem's derivatives
60//! satisfy independent componentwise tolerances.
61//! Its function-calling policy marks
62//! read-only observations explicitly, and its step-size limiter applies
63//! dynamic stability bounds without interfering with smaller adaptive steps.
64//! - [`SolveOptions`] controls tolerances, step sizes, exact time stops, saved
65//! output, and dense output retention; [`solve`] runs an [`OdeAlgorithm`].
66//! - [`solvers::explicit`] is a good starting point for non-stiff problems,
67//! [`solvers::rosenbrock`] contains linearly implicit stiff methods, and
68//! [`solvers::automatic`] contains in-flight non-stiff/stiff composites with
69//! configurable hysteresis and observable branch statistics.
70//! - [`tableau`] exposes the extension surface for defining explicit
71//! Runge--Kutta and Runge--Kutta--Nyström methods from compile-time-validated
72//! JSON resources, plus typed data for specialized solver families.
73//! - [`OdeProblem::builder`] names the initial state, time span, parameters,
74//! and ndarray evaluation style. [`OdeProblem::from_array`] remains the
75//! compact constructor for scalar, vector, and matrix states while numerical
76//! kernels retain contiguous flat workspaces.
77//! [`OdeProblem::from_array_out_of_place`] accepts functions returning arrays;
78//! [`OdeFunction`] unifies them with in-place closures and propagates errors.
79//! [`solvers::second_order::SecondOrderOdeProblem`] provides matching ndarray
80//! constructors while keeping velocity and position partitions separate.
81//! - [`solve_ensemble`] and [`solve_batch`] preserve input order. The default
82//! `parallel` feature also enables their Rayon-backed variants.
83//!
84//! # Features
85//!
86//! The public Cargo feature surface is intentionally small:
87//!
88//! - `parallel` is enabled by default and adds Rayon-backed independent solves.
89//! - `serde` adds validated, versioned serialization of solutions and portable
90//! dense segments. It is independent of parallel execution.
91//! - `allocation-metrics` enables repository benchmark instrumentation and is
92//! not needed by ordinary users.
93//!
94//! Disabling default features selects sequential ensemble execution. State
95//! shape is part of the core API, not a feature: ndarray scalar, vector, and
96//! matrix adapters remain available with `default-features = false`. There are
97//! no `vector`, `matrix`, or `ndarray` feature flags.
98//!
99//! # Errors and panics
100//!
101//! Public solve functions return [`SolveError`] for invalid dimensions,
102//! non-finite inputs, unsupported option/algorithm combinations, and numerical
103//! failure. Problem right-hand sides, Jacobians, and callbacks are user code;
104//! a panic in one of them is not caught by the solver. In-place right-hand
105//! sides and Jacobians must fill their complete output buffers, and callback
106//! effects must preserve the problem's state dimension.
107//!
108//! # Further reading
109//!
110//! The packaged repository documentation includes the solver-selection and
111//! scope guide in the [README] and the [compile-time tableau resource guide].
112//! Contributors can use the
113//! [performance regression guide] to compare stable benchmark IDs locally.
114//!
115//! [README]: https://github.com/Wouittone/differential-equations-rs/blob/main/README.md
116//! [compile-time tableau resource guide]: https://github.com/Wouittone/differential-equations-rs/blob/main/docs/TABLEAU_RESOURCES.md
117//! [performance regression guide]: https://github.com/Wouittone/differential-equations-rs/blob/main/docs/BENCHMARKING.md
118
119#![forbid(unsafe_code)]
120#![warn(missing_docs, rustdoc::broken_intra_doc_links)]
121
122mod callback;
123pub mod callbacks;
124mod ensemble;
125mod error;
126mod event;
127pub mod gauss_jackson;
128mod integrator;
129mod linear;
130mod operator_problem;
131mod problem;
132pub mod scoped_problem;
133mod semilinear;
134mod solution;
135mod solver;
136pub mod solvers;
137pub mod state_layout;
138pub mod stepping;
139pub mod tableau;
140pub mod tolerances;
141
142pub use callback::{CallbackAction, CallbackSave, CallbackSet, EventCrossing, EventDirection};
143pub use ensemble::{
144 CaseOutcome, ExecutionPolicy, solve_batch, solve_batch_sequential, solve_ensemble,
145 solve_ensemble_sequential,
146};
147#[cfg(feature = "parallel")]
148pub use ensemble::{solve_batch_parallel, solve_ensemble_parallel};
149pub use error::ConfigurationError;
150pub use event::DEFAULT_EVENT_TOLERANCE;
151pub use gauss_jackson::{
152 GaussJackson8, GaussJacksonConfig, GaussJacksonError, GaussJacksonStatistics, GaussJacksonStep,
153};
154/// The ndarray version used by shape-aware ODE states.
155pub use ndarray;
156pub use operator_problem::{LieGroupProblem, LinearOperatorProblem};
157pub use problem::{MutableFunction, OdeFunction, OdeProblem, OdeProblemBuilder, SplitOdeProblem};
158pub use scoped_problem::{ScopedOdeProblem, ScopedSecondOrderProblem};
159pub use semilinear::SemilinearOdeProblem;
160pub use solution::{
161 DenseSegmentData, InterpolationError, InterpolationQuality, PortableDenseSegment, Solution,
162 SolutionConstructionError, SolutionData, SolverStats,
163};
164pub use solver::{
165 AutomaticPairIncompatibility, OdeAlgorithm, SaveMode, SolveError, SolveOptions, solve,
166};