Skip to main content

sim_core/
integrate.rs

1//! Fixed-step integration. The core never looks at the wall clock.
2//!
3//! Classical Runge-Kutta 4 with sub-steps. The plan's default was a semi-implicit scheme; the
4//! convergence and energy checks of the standard suite decide, and RK4 with 4 sub-steps passes them
5//! without the core having to know which states are positions and which are velocities.
6
7use crate::Machine;
8
9pub struct Rk4 {
10    k: [Vec<f64>; 4],
11    tmp: Vec<f64>,
12}
13
14impl Rk4 {
15    pub fn new(n: usize) -> Self {
16        Self { k: std::array::from_fn(|_| vec![0.0; n]), tmp: vec![0.0; n] }
17    }
18
19    pub fn step(&mut self, mut f: impl FnMut(&[f64], &mut [f64]), y: &mut [f64], h: f64) {
20        let [k1, k2, k3, k4] = &mut self.k;
21        let tmp = &mut self.tmp;
22        f(y, k1);
23        for i in 0..y.len() {
24            tmp[i] = y[i] + 0.5 * h * k1[i];
25        }
26        f(tmp, k2);
27        for i in 0..y.len() {
28            tmp[i] = y[i] + 0.5 * h * k2[i];
29        }
30        f(tmp, k3);
31        for i in 0..y.len() {
32            tmp[i] = y[i] + h * k3[i];
33        }
34        f(tmp, k4);
35        for i in 0..y.len() {
36            y[i] += h / 6.0 * (k1[i] + 2.0 * k2[i] + 2.0 * k3[i] + k4[i]);
37        }
38    }
39}
40
41/// Advances a machine by one base step `dt` with the torques held constant, as a drive would.
42pub fn advance(machine: &dyn Machine, rk: &mut Rk4, state: &mut [f64], torque: &[f64], dt: f64, substeps: u32) {
43    let h = dt / substeps as f64;
44    for _ in 0..substeps {
45        rk.step(|y, dy| machine.derivatives(y, torque, dy), state, h);
46    }
47}
48
49/// The most parts a base step's sub-steps are cut into for the machine (`Machine::substeps_wanted`): a bound on what a
50/// step can cost.
51pub const MOST_CUTS: u32 = 256;
52
53/// `advance` with each sub-step cut as the machine asks from the step's start (`Machine::substeps_wanted`, at most
54/// `MOST_CUTS`); the cuts it took.
55pub fn advance_refined(
56    machine: &dyn Machine,
57    rk: &mut Rk4,
58    state: &mut [f64],
59    torque: &[f64],
60    dt: f64,
61    substeps: u32,
62) -> u32 {
63    let cuts = machine.substeps_wanted(state, torque, dt, substeps).clamp(1, MOST_CUTS);
64    advance(machine, rk, state, torque, dt, substeps * cuts);
65    cuts
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn harmonic_oscillator_matches_closed_form() {
74        let mut rk = Rk4::new(2);
75        let mut y = [1.0, 0.0];
76        for _ in 0..1000 {
77            rk.step(
78                |y, dy| {
79                    dy[0] = y[1];
80                    dy[1] = -y[0];
81                },
82                &mut y,
83                1e-3,
84            );
85        }
86        assert!((y[0] - 1f64.cos()).abs() < 1e-12);
87        assert!((y[1] + 1f64.sin()).abs() < 1e-12);
88    }
89
90    #[test]
91    fn error_falls_with_fourth_order() {
92        let err = |n: usize| {
93            let mut rk = Rk4::new(1);
94            let mut y = [1.0];
95            for _ in 0..n {
96                rk.step(|y, dy| dy[0] = -y[0], &mut y, 1.0 / n as f64);
97            }
98            (y[0] - (-1f64).exp()).abs()
99        };
100        let ratio = err(10) / err(20);
101        assert!(ratio > 14.0 && ratio < 18.0, "ratio {ratio}");
102    }
103}