packages

ode

On this page

Ordinary differential equations on core's Array: adaptive initial value solvers (explicit Runge-Kutta, Radau IIA, BDF, automatic stiff switching) with dense output and events, fixed-step and symplectic integrators, and boundary value problems by collocation.

Modules

  • ops Flows: one-step maps phi_h composed the way splitting and composition methods are written (Hairer, Lubich and Wanner, Geometric Numerical Integration, II.4-5), behind the ops feature: a ∘ b a after b (core's ∘) c * a the same map with step c h a ** n n steps of a a ⊳ y a applied to the state y (binds like *) so Strang splitting is (0.5 * a) ∘ b ∘ (0.5 * a) and a step of Yoshida's method (w1 * v) ∘ (w0 * v) ∘ (w1 * v).
  • problems Standard test problems with their exact Jacobians and reference values: the stiff ones from Hairer and Wanner (Solving ODEs II, IV.10) and the IVP test set of Mazzia and Magherini, plus Lorenz, the Kepler problem and an N-body cluster for the non-stiff and symplectic integrators.

Structs

BvpSource

pub struct Bvp

The result of solve_bvp.

sol is the C1 cubic spline (sol.at(x)), x the final mesh, y and yp the solution and its derivative there ([n, x.len()]), p the fitted parameters, rms_residuals the relative residual per interval.

nabi
use core::array::{Array, Matrix, Vector};

// y'' = -y, y(0) = 0, y(pi / 2) = 1: y = sin x.
let x: Vector<f64> = [0.0, 0.5, 1.0, 1.5707963267948966];
let y: Matrix<f64> = Array::zeros([2, 4]);
let r = try ode::solve_bvp(|x: f64, y: Vector<f64>| -> Vector<f64> { [y[1], -y[0]] }, |a: Vector<f64>, b: Vector<f64>| -> Vector<f64> { [a[0], b[0] - 1.0] }, x, y, tol: 1e-6);
assert(r.success() && (r.sol.at(1.0)[0] - 1.0f64.sin()).abs() < 1e-6);
  • pub sol: Dense§

    Source

    The spline solution.

  • pub x: Vector<f64>§

    Source

    The final mesh.

  • pub y: Matrix<f64>§

    Source

    The solution at the mesh, [n, m].

  • pub yp: Matrix<f64>§

    Source

    f(x, y, p) at the mesh, [n, m].

  • pub p: Vector<f64>§

    Source

    The parameters (empty without any).

  • pub rms_residuals: Vector<f64>§

    Source

    RMS relative residual per interval.

  • pub iterations: usize§

    Source

    Newton / refinement rounds.

  • pub status: BvpStatus§

    Source

    How it ended.

  • pub nfev: usize§

    Source

    Evaluations of f.

  • pub fn success(self) -> bool§

    Source

    Whether the tolerances were met (status.success()).

    nabi
    use core::array::{Array, Vector};
    
    let x: Vector<f64> = [0.0, 1.0];
    let r = try ode::solve_bvp(|x: f64, y: Vector<f64>| -> Vector<f64> { [y[1], 0.0] }, |a: Vector<f64>, b: Vector<f64>| -> Vector<f64> { [a[0], b[0] - 2.0] }, x, Array::zeros([2, 2]));
    assert(r.success() && (r.sol.at(0.25)[0] - 0.5).abs() < 1e-12);
    

DenseSource

pub struct Dense

The continuous solution of an initial value problem: sol(t) (or sol.at(t)) reads it anywhere on the span, between steps too, and sol(ts) at every time of a vector, to the accuracy of the method's own interpolant (order 3 for RK23, 4 for RK45, 7 for DOP853, 3 for Radau, the current order for BDF). Outside the span it extends the first or last step's polynomial. Each lookup is a binary search over the steps, O(log steps + n).

nabi
use core::array::Vector;

let y0: Vector<f64> = [1.0];
let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { -y }, 0.0..2.0, y0, rtol: 1e-8, atol: 1e-10);
assert(((r.sol)(0.7)[0] - (-0.7f64).exp()).abs() < 1e-7);
let sol = r.sol;
assert(sol([0.5, 0.7])[0, 1] == sol(0.7)[0]);
assert(sol.span().start == 0.0 && sol.span().end == 2.0);
  • pub fn at(self, t: f64) -> Vector<f64>§

    Source

    The solution at t.

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [0.0, 1.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { [y[1], -y[0]] }, 0.0..3.0, y0, method: ode::Method::Dop853, rtol: 1e-10, atol: 1e-12);
    let y = r.sol.at(1.0);
    assert((y[0] - 1.0f64.sin()).abs() < 1e-9 && (y[1] - 1.0f64.cos()).abs() < 1e-9);
    
  • pub fn eval(self, ts: Vector<f64>) -> Matrix<f64>§

    Source

    The solution at every time of ts, as columns: shape [n, ts.len()], like Solution.y.

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0, rtol: 1e-9, atol: 1e-12);
    let ys = r.sol.eval([0.25, 0.5, 1.0]);
    assert(ys.shape() == [1, 3] && (ys[0, 1] - 0.5f64.exp()).abs() < 1e-8);
    
  • pub fn component(self, i: usize) -> fn(f64) -> f64§

    Source

    Component i as a function of time, for quadrature or root finding: sol.component(0)(t) == sol.at(t)[0].

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [0.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { [2.0 * t] }, 0.0..1.0, y0);
    let g = r.sol.component(0);
    assert((g(0.5) - 0.25).abs() < 1e-12);
    

    An i past the last component gives NaN everywhere.

  • pub fn span(self) -> Range<f64>§

    Source

    The time span covered, from the start to the last step's end.

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0);
    assert(r.sol.span().start == 0.0 && r.sol.span().end == 1.0);
    
  • pub fn steps(self) -> usize§

    Source

    The number of steps (interpolants).

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0);
    assert(r.sol.steps() == r.steps);
    
  • pub fn breakpoints(self) -> Vector<f64>§

    Source

    The step ends, from the start: steps() + 1 times.

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0);
    assert(r.sol.breakpoints() == r.t);
    
Trait implementations 2
  • impl ops::Call<f64> for Dense
  • impl ops::Call<Vector<f64>> for Dense

EventSource

pub struct Event

A function of (t, y) whose zeros solve_ivp locates. A terminal event stops the integration at its first zero.

nabi
use ode::{Direction, Event};
use core::array::Vector;

// A ball thrown up at 10 m/s lands after 2 v / g.
let ground = Event { f: |t: f64, y: Vector<f64>| -> f64 { y[0] }, terminal: true, direction: Direction::Falling };
let y0: Vector<f64> = [0.0, 10.0];
let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { [y[1], -9.81] }, 0.0..5.0, y0, events: [ground]);
assert(r.status == ode::Status::Event);
assert((r.t_events[0][0] - 20.0 / 9.81).abs() < 1e-10);
  • pub f: fn(f64, Vector<f64>) -> f64§

    Source

    The event function; an event is a zero of it.

  • pub terminal: bool = false§

    Source

    Stop at the first zero.

  • pub direction: Direction = Direction::Both§

    Source

    Which crossings count.

SolutionSource

pub struct Solution

The result of solve_ivp.

t and y hold every step end (or the t_eval times), the state as columns: y[i, j] is component i at t[j]. sol is the dense output. t_events[k] and y_events[k] hold the zeros of event k (y_events[k] is hits x n).

nabi
use core::array::Vector;

let y0: Vector<f64> = [2.0];
let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y .* -0.5 }, 0.0..10.0, y0, t_eval: [0.0, 5.0, 10.0]);
assert(r.status.success() && r.t.len() == 3 && r.y.shape() == [1, 3]);
assert((r.y[0, 2] - 2.0 * (-5.0f64).exp()).abs() < 1e-3);
assert(r.nfev > 0 && r.njev == 0);
  • pub t: Vector<f64>§

    Source

    Output times.

  • pub y: Matrix<f64>§

    Source

    The state at t, shape [n, t.len()].

  • pub status: Status§

    Source

    Why the run stopped.

  • pub nfev: usize§

    Source

    Evaluations of the right-hand side, finite-difference Jacobians included.

  • pub njev: usize§

    Source

    Jacobian evaluations.

  • pub nlu: usize§

    Source

    LU factorizations.

  • pub steps: usize§

    Source

    Accepted steps.

  • pub sol: Dense§

    Source

    The dense output (empty with dense: false).

  • pub t_events: List<Vector<f64>>§

    Source

    The times of each event's zeros.

  • pub y_events: List<Matrix<f64>>§

    Source

    The states at each event's zeros, hits x n.

  • pub switches: List<f64>§

    Source

    Method::Auto only: the times it changed method, the first to the stiff one, alternating after.

  • pub fn success(self) -> bool§

    Source

    Whether the run ended as asked (status.success()).

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0];
    assert((try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0)).success());
    
  • pub fn last(self) -> Vector<f64>§

    Source

    The state at the last output time.

    nabi
    use core::array::Vector;
    
    let y0: Vector<f64> = [1.0, 0.0];
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { [0.0, 1.0] }, 0.0..2.0, y0);
    let y = r.last();
    assert(y[0] == 1.0 && (y[1] - 2.0).abs() < 1e-14);
    

OrbitSource

pub struct Orbit

A trajectory from symplectic: positions q and momenta p as columns ([d, t.len()]) at the saved times t.

nabi
use core::array::Vector;

let q0: Vector<f64> = [1.0];
let v0: Vector<f64> = [0.0];
let o = try ode::verlet(|q: Vector<f64>| -> Vector<f64> { -q }, q0, v0, 0.0..10.0, 1000);
let e = o.energy(|q: Vector<f64>, p: Vector<f64>| -> f64 { 0.5 * (q[0] * q[0] + p[0] * p[0]) });
assert(o.q.shape() == [1, 1001] && (e[1000] - 0.5).abs() < 1e-5);
  • pub t: Vector<f64>§

    Source

    Saved times.

  • pub q: Matrix<f64>§

    Source

    Positions, [d, t.len()].

  • pub p: Matrix<f64>§

    Source

    Momenta (velocities for verlet and friends), [d, t.len()].

  • pub nfev: usize§

    Source

    Force evaluations.

  • pub fn energy(self, h: fn(Vector<f64>, Vector<f64>) -> f64) -> Vector<f64>§

    Source

    h(q, p) at every saved time: the energy for a Hamiltonian h.

    nabi
    use core::array::Vector;
    
    let q0: Vector<f64> = [1.0];
    let v0: Vector<f64> = [0.0];
    let o = try ode::verlet(|q: Vector<f64>| -> Vector<f64> { -q }, q0, v0, 0.0..1.0, 100);
    let e = o.energy(|q: Vector<f64>, p: Vector<f64>| -> f64 { 0.5 * (q[0] * q[0] + p[0] * p[0]) });
    assert(e.len() == 101 && e[0] == 0.5);
    
  • pub fn last_q(self) -> Vector<f64>§

    Source

    The final positions.

    nabi
    use core::array::Vector;
    
    let q0: Vector<f64> = [1.0];
    let v0: Vector<f64> = [0.0];
    let o = try ode::verlet(|q: Vector<f64>| -> Vector<f64> { -q }, q0, v0, 0.0..1.0, 100);
    assert((o.last_q()[0] - 1.0f64.cos()).abs() < 1e-4);
    
  • pub fn last_p(self) -> Vector<f64>§

    Source

    The final momenta.

    nabi
    use core::array::Vector;
    
    let q0: Vector<f64> = [1.0];
    let v0: Vector<f64> = [0.0];
    let o = try ode::verlet(|q: Vector<f64>| -> Vector<f64> { -q }, q0, v0, 0.0..1.0, 100);
    assert((o.last_p()[0] + 1.0f64.sin()).abs() < 1e-4);
    

Enums

BvpStatusSource

pub enum BvpStatus

How solve_bvp ended.

nabi
use ode::BvpStatus;

assert(BvpStatus::Converged.success() && !BvpStatus::MaxNodes.success());
assert(f"{BvpStatus::MaxNodes}".contains("max_nodes"));
  • Converged§

    Source

    The residuals and boundary conditions meet their tolerances.

  • MaxNodes§

    Source

    Refining the mesh further would pass max_nodes.

  • Singular§

    Source

    The Newton system was singular.

  • BcTolerance§

    Source

    The residual is small but the boundary conditions miss bc_tol after 10 iterations.

  • pub fn success(self) -> bool§

    Source

    Whether the tolerances were met.

    nabi
    assert(ode::BvpStatus::Converged.success());
    
Trait implementations 1
  • impl Display for BvpStatus

OdeErrorSource

pub enum OdeError

What went wrong setting up a problem. A run that starts but cannot finish (a step size too small, NaN from the right-hand side) does not throw: it returns its result with a Status that says why.

nabi
use ode::OdeError;
use core::array::Vector;

let y0: Vector<f64> = [1.0];
let e = try {
    _ = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { -y }, 0.0..1.0, y0, rtol: -1.0);
    OdeError::NotFinite { what: "" }
} catch e: OdeError { e };
assert(e == OdeError::BadArgument { what: "rtol must be positive and finite, got -1; pass a relative tolerance such as `rtol: 1e-6`" });
assert(f"{e}".contains("rtol"));
  • BadArgument§

    Source

    An argument is out of its range; what says which and what fits.

  • LengthMismatch§

    Source

    Two inputs that must agree in length or shape do not; what names both.

  • NotFinite§

    Source

    An input, or a value the problem's functions gave at the start, holds NaN or an infinity; what names it.

Trait implementations 2
  • impl Display for OdeError
  • impl Error for OdeError

FixedSource

pub enum Fixed

A fixed-step method for fixed.

methodorderstages
Euler11
Midpoint22
Heun22
Rk444
nabi
use ode::Fixed;

assert(Fixed::Rk4.order() == 4 && Fixed::Euler.order() == 1);
  • Forward Euler.

  • Midpoint§

    Source

    The explicit midpoint rule.

  • Heun's method (explicit trapezoid).

  • The classical 4th order Runge-Kutta method.

  • pub fn order(self) -> usize§

    Source

    The order of accuracy.

    nabi
    assert(ode::Fixed::Heun.order() == 2);
    

DirectionSource

pub enum Direction

Which zero crossings of an event function count.

nabi
use ode::Direction;

assert(Direction::Rising != Direction::Falling);
  • Crossings either way.

  • Rising§

    Source

    From negative to positive only.

  • Falling§

    Source

    From positive to negative only.

JacobianSource

pub enum Jacobian

Where the implicit methods get df/dy.

nabi
use ode::{Jacobian, Method};
use core::array::{Matrix, Vector};

let k = 50.0;
let y0: Vector<f64> = [1.0];
let jac = Jacobian::Exact(|t: f64, y: Vector<f64>| -> Matrix<f64> { [[-k]] });
let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y .* -k }, 0.0..1.0, y0, method: Method::Radau, jac: jac);
assert(r.success() && r.njev >= 1);
  • Approx§

    Source

    Forward differences, n evaluations of f each.

  • Exact(fn(f64, Vector<f64>) -> Matrix<f64>)§

    Source

    A function giving the n x n matrix J[i, j] = df_i / dy_j.

  • Constant(Matrix<f64>)§

    Source

    A constant matrix (a linear problem); never recomputed.

MethodSource

pub enum Method

An integration method for solve_ivp.

methodkindorderuse for
Rk23explicit RK 3(2)3loose tolerances, cheap f
Rk45explicit RK 5(4)5the default for non-stiff problems
Dop853explicit RK 8(5,3)8tight tolerances, smooth non-stiff problems
Radauimplicit RK (IIA)5stiff problems, tight tolerances
Bdfmultistep (NDF)1-5stiff problems, large systems
RodasRosenbrock 4(3)4stiff problems, moderate tolerances, small n
AutoRK45 / BDF switch5/1-5stiffness unknown or changing
nabi
use ode::Method;
use core::array::Vector;

let y0: Vector<f64> = [1.0];
for m in [Method::Rk23, Method::Rk45, Method::Dop853, Method::Radau, Method::Bdf, Method::Rodas, Method::Auto] {
    let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { -y }, 0.0..1.0, y0, method: m, rtol: 1e-8, atol: 1e-10);
    assert((r.last()[0] - (-1.0f64).exp()).abs() < 1e-6);
}
  • Bogacki-Shampine 3(2), cubic dense output.

  • Dormand-Prince 5(4), quartic dense output.

  • Dop853§

    Source

    Hairer's DOP853, 8th order with 7th degree dense output.

  • Radau IIA, 5th order, L-stable; cubic dense output.

  • Variable-order BDF (NDF form), orders 1 to 5.

  • The Rosenbrock method RODAS, order 4, L-stable; cubic dense output. A fresh Jacobian each step, no Newton iteration.

  • RK45 while non-stiff, BDF while stiff, switching on its own.

StatusSource

pub enum Status

Why a run stopped.

nabi
use ode::Status;

assert(Status::Finished.success() && Status::Event.success());
assert(!Status::StepTooSmall.success());
assert(f"{Status::StepTooSmall}".contains("rtol"));
  • Finished§

    Source

    The end of the span was reached.

  • A terminal event stopped the run.

  • StepTooSmall§

    Source

    The step size the error test asked for fell below the spacing of floats at t.

  • NotFinite§

    Source

    The right-hand side gave NaN or infinity, and no smaller step avoided it.

  • pub fn success(self) -> bool§

    Source

    Whether the run ended as asked (the end of the span or a terminal event).

    nabi
    assert(ode::Status::Finished.success());
    
Trait implementations 1
  • impl Display for Status

SymplecticSource

pub enum Symplectic

A symplectic method for symplectic.

methodorderforce evaluations per step
Euler11
Verlet21 (kick-drift-kick)
Leapfrog21 (drift-kick-drift)
Yoshida443
Yoshida667
nabi
assert(ode::Symplectic::Yoshida4.order() == 4);
  • Symplectic Euler: kick, then drift.

  • Verlet§

    Source

    Velocity Verlet (Stormer-Verlet, kick-drift-kick).

  • Leapfrog§

    Source

    Position Verlet (drift-kick-drift).

  • Yoshida4§

    Source

    Yoshida's 4th order composition (Forest-Ruth).

  • Yoshida6§

    Source

    Yoshida's 6th order composition, solution A.

  • pub fn order(self) -> usize§

    Source

    The order of accuracy.

    nabi
    assert(ode::Symplectic::Leapfrog.order() == 2);
    

Functions

solve_bvpSource

pub fn solve_bvp<X: AsVector<f64>>(
    f: fn(f64, Vector<f64>) -> Vector<f64>,
    bc: fn(Vector<f64>, Vector<f64>) -> Vector<f64>,
    x: X,
    y: Matrix<f64>,
    tol: f64 = 1e-3,
    max_nodes: usize = 1000,
    bc_tol: f64 = 0.0,
) throws (OdeError) -> Bvp

Solves y' = f(x, y) with bc(y(a), y(b)) = 0 (n conditions) on the mesh x (rising, at least 2 nodes), from the guess y ([n, x.len()]). tol bounds the RMS relative residual, bc_tol (tol when left 0) the boundary residuals.

nabi
use core::array::{Array, Matrix, Vector};

// Bratu's problem y'' + e^y = 0, y(0) = y(1) = 0 (the lower branch).
let x: Vector<f64> = [0.0, 0.25, 0.5, 0.75, 1.0];
let y: Matrix<f64> = Array::zeros([2, 5]);
let r = try ode::solve_bvp(|x: f64, y: Vector<f64>| -> Vector<f64> { [y[1], -y[0].exp()] }, |a: Vector<f64>, b: Vector<f64>| -> Vector<f64> { [a[0], b[0]] }, x, y, tol: 1e-8);
assert(r.success() && (r.sol.at(0.5)[0] - 0.1405392144).abs() < 1e-8);

solve_bvp_paramsSource

pub fn solve_bvp_params<X: AsVector<f64>, P: AsVector<f64>>(
    f: fn(f64, Vector<f64>, Vector<f64>) -> Vector<f64>,
    bc: fn(Vector<f64>, Vector<f64>, Vector<f64>) -> Vector<f64>,
    x: X,
    y: Matrix<f64>,
    p: P,
    tol: f64 = 1e-3,
    max_nodes: usize = 1000,
    bc_tol: f64 = 0.0,
) throws (OdeError) -> Bvp

solve_bvp with unknown parameters p (k of them, from the guess p): f(x, y, p) and n + k boundary conditions bc(ya, yb, p), as for eigenvalue problems. Always takes the dense Newton path.

nabi
use core::array::{Array, Matrix, Vector};

// y'' + k^2 y = 0, y(0) = y(1) = 0, y'(0) = k: the first eigenvalue is k = pi.
let x: Vector<f64> = [0.0, 0.25, 0.5, 0.75, 1.0];
let y: Matrix<f64> = [[0.0, 0.7, 1.0, 0.7, 0.0], [3.0, 2.0, 0.0, -2.0, -3.0]];
let p0: Vector<f64> = [3.0];
let r = try ode::solve_bvp_params(
    |x: f64, y: Vector<f64>, p: Vector<f64>| -> Vector<f64> { [y[1], -p[0] * p[0] * y[0]] },
    |a: Vector<f64>, b: Vector<f64>, p: Vector<f64>| -> Vector<f64> { [a[0], b[0], a[1] - p[0]] },
    x, y, p0, tol: 1e-8);
assert(r.success() && (r.p[0] - 3.141592653589793).abs() < 1e-6);

eulerSource

pub fn euler<Y: AsVector<f64>>(f: fn(f64, Vector<f64>) -> Vector<f64>, span: Range<f64>, y0: Y, steps: usize) throws (OdeError) -> Solution

fixed with forward Euler.

nabi
use core::array::Vector;

let y0: Vector<f64> = [1.0];
let r = try ode::euler(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 0.0..1.0, y0, 4);
assert(r.last()[0] == 1.25 * 1.25 * 1.25 * 1.25);

fixedSource

pub fn fixed<Y: AsVector<f64>>(f: fn(f64, Vector<f64>) -> Vector<f64>, span: Range<f64>, y0: Y, steps: usize, method: Fixed = Fixed::Rk4) throws (OdeError) -> Solution

Integrates y' = f(t, y) over span in steps equal steps of method (h = (end - start) / steps; the span may run backwards). The result has steps + 1 columns. A NaN or infinity in the state stops the run with Status::NotFinite.

nabi
use ode::Fixed;
use core::array::Vector;

let y0: Vector<f64> = [1.0];
let f = |t: f64, y: Vector<f64>| -> Vector<f64> { y };
let e1 = (try ode::fixed(f, 0.0..1.0, y0, 100, method: Fixed::Rk4)).last()[0] - 1.0f64.exp();
let e2 = (try ode::fixed(f, 0.0..1.0, y0, 200, method: Fixed::Rk4)).last()[0] - 1.0f64.exp();
assert((e1 / e2 - 16.0).abs() < 0.5);   // 4th order: halving h cuts the error 16 times

rk4Source

pub fn rk4<Y: AsVector<f64>>(f: fn(f64, Vector<f64>) -> Vector<f64>, span: Range<f64>, y0: Y, steps: usize) throws (OdeError) -> Solution

fixed with the classical Runge-Kutta method.

nabi
use core::array::Vector;

let y0: Vector<f64> = [0.0, 1.0];
let r = try ode::rk4(|t: f64, y: Vector<f64>| -> Vector<f64> { [y[1], -y[0]] }, 0.0..6.283185307179586, y0, 200);
assert((r.last()[1] - 1.0).abs() < 1e-7);

solve_ivpSource

pub fn solve_ivp<Y: AsVector<f64>>(
    f: fn(f64, Vector<f64>) -> Vector<f64>,
    span: Range<f64>,
    y0: Y,
    method: Method = Method::Rk45,
    rtol: f64 = 1e-3,
    atol: f64 | Vector<f64> = 1e-6,
    t_eval: Vector<f64> | none = none,
    dense: bool = true,
    events: List<Event> = [],
    max_step: f64 = f64::INFINITY,
    first_step: f64 = 0.0,
    jac: Jacobian = Jacobian::Approx,
) throws (OdeError) -> Solution

Solves y' = f(t, y), y(span.start) = y0 over span, which may run backwards (10.0..0.0).

The error test is per component, |err_i| <= atol_i + rtol |y_i|, in the RMS norm: rtol (floored at 100 eps) and atol (one value or one per component) say how many digits to keep and below what size a component counts as zero. Options:

  • t_eval: output only at these times (inside span, ordered along it), read off the dense output; otherwise at every step end.
  • dense: keep the dense output in sol (on by default; false saves memory and DOP853's three extra stages per step).
  • events: functions whose zeros to locate (Event).
  • max_step, first_step: bound the step size, fix the first one (0 lets the method choose).
  • jac: the Jacobian for Radau, Bdf, Rodas and Auto.

A run that cannot finish returns what it has with a failing status; bad input throws OdeError.

nabi
use ode::Method;
use core::array::Vector;

// Logistic growth, y' = y (1 - y): y(t) = 1 / (1 + 9 e^-t) from 0.1.
let r = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y .* (1.0 .- y) }, 0.0..5.0, [0.1], method: Method::Dop853, rtol: 1e-10, atol: 1e-12);
assert((r.last()[0] - 1.0 / (1.0 + 9.0 * (-5.0f64).exp())).abs() < 1e-10);

// Backwards from t = 1.
let y1: Vector<f64> = [1.0f64.exp()];
let b = try ode::solve_ivp(|t: f64, y: Vector<f64>| -> Vector<f64> { y }, 1.0..0.0, y1, rtol: 1e-9, atol: 1e-12);
assert((b.last()[0] - 1.0).abs() < 1e-8);

leapfrogSource

pub fn leapfrog<Q: AsVector<f64>, V: AsVector<f64>>(accel: fn(Vector<f64>) -> Vector<f64>, q0: Q, v0: V, span: Range<f64>, steps: usize, every: usize = 1) throws (OdeError) -> Orbit

Leapfrog (drift-kick-drift) for q'' = accel(q), unit mass.

nabi
use core::array::Vector;

let q0: Vector<f64> = [0.0];
let v0: Vector<f64> = [0.0];
let o = try ode::leapfrog(|q: Vector<f64>| -> Vector<f64> { [-9.81] }, q0, v0, 0.0..1.0, 4);
assert((o.last_q()[0] + 0.5 * 9.81).abs() < 1e-12);   // exact for constant force

symplecticSource

pub fn symplectic(
    velocity: fn(Vector<f64>) -> Vector<f64>,
    force: fn(Vector<f64>) -> Vector<f64>,
    q0: Vector<f64>,
    p0: Vector<f64>,
    span: Range<f64>,
    steps: usize,
    method: Symplectic = Symplectic::Verlet,
    every: usize = 1,
) throws (OdeError) -> Orbit

Integrates the separable Hamiltonian system q' = velocity(p) (dT/dp), p' = force(q) (-dV/dq) over span in steps equal steps, saving every every-th step (and the last).

nabi
use ode::Symplectic;
use core::array::Vector;

// A pendulum, H = p^2 / 2 - cos q.
let q0: Vector<f64> = [1.0];
let p0: Vector<f64> = [0.0];
let o = try ode::symplectic(|p: Vector<f64>| -> Vector<f64> { p }, |q: Vector<f64>| -> Vector<f64> { [-q[0].sin()] }, q0, p0, 0.0..100.0, 2000, method: Symplectic::Yoshida4);
let e = o.energy(|q: Vector<f64>, p: Vector<f64>| -> f64 { 0.5 * p[0] * p[0] - q[0].cos() });
assert((e[e.len() - 1] - e[0]).abs() < 1e-6);

verletSource

pub fn verlet<Q: AsVector<f64>, V: AsVector<f64>>(accel: fn(Vector<f64>) -> Vector<f64>, q0: Q, v0: V, span: Range<f64>, steps: usize, every: usize = 1) throws (OdeError) -> Orbit

Velocity Verlet for q'' = accel(q): symplectic with unit mass, p the velocity.

nabi
use core::array::Vector;

let q0: Vector<f64> = [0.0];
let v0: Vector<f64> = [1.0];
let o = try ode::verlet(|q: Vector<f64>| -> Vector<f64> { [0.0] }, q0, v0, 0.0..2.0, 10);
assert((o.last_q()[0] - 2.0).abs() < 1e-14);

yoshida4Source

pub fn yoshida4<Q: AsVector<f64>, V: AsVector<f64>>(accel: fn(Vector<f64>) -> Vector<f64>, q0: Q, v0: V, span: Range<f64>, steps: usize, every: usize = 1) throws (OdeError) -> Orbit

Yoshida's 4th order method for q'' = accel(q), unit mass.

nabi
use core::array::Vector;

let q0: Vector<f64> = [1.0];
let v0: Vector<f64> = [0.0];
let o = try ode::yoshida4(|q: Vector<f64>| -> Vector<f64> { -q }, q0, v0, 0.0..1.0, 50);
assert((o.last_q()[0] - 1.0f64.cos()).abs() < 1e-8);