sciart_core/ode.rs
1//! Fixed-step ODE integration for deterministic physics scenes (SPEC-001 CORE-R37,
2//! CORE-R44) and tridiagonal solvers for implicit diffusion (CORE-R59) and complex
3//! Crank–Nicolson steps (CORE-R100).
4//!
5//! RK4 state is a const-generic `[f64; N]` so every stage lives on the stack: no
6//! allocation, no trait objects, and the closure is monomorphised into a tight loop.
7//! Classical RK4 is the sweet spot for a 60 Hz visual simulation: 4th-order accurate
8//! with four evaluations, and far better behaved than Euler on orbits and pendulums.
9//!
10//! Long-lived conservative systems (N-body, choreographies) instead want the symplectic
11//! kick–drift–kick leapfrog ([`verlet_step`]): 2nd order, one force evaluation per step,
12//! time-reversible, and with a bounded energy error where RK4 slowly drifts. It works on
13//! caller-owned slices because N-body state is sized at runtime.
14
15/// Smallest substep `integrate` will use; smaller, zero, negative or NaN `h_max` is
16/// raised to this (CORE-R37).
17pub const MIN_STEP: f64 = 1e-6;
18
19/// Upper bound on substeps per `integrate` call (CORE-R37).
20///
21/// Keeps the per-frame cost bounded (GEN-R8) whatever `dt`/`h_max` a caller passes:
22/// at the 1/60 s sim step this still allows substeps of ~4 µs of simulated time.
23pub const MAX_STEPS: usize = 4096;
24
25/// Relative slack when counting substeps, so that exact multiples such as
26/// `integrate(.., 0.9, 0.3, ..)` take 3 steps rather than `ceil(3.0000000000000004) = 4`.
27/// The resulting step exceeds `h_max` by at most this fraction — irrelevant for accuracy.
28const COUNT_SLACK: f64 = 1e-9;
29
30/// `y + a * k`, element-wise, on the stack.
31///
32/// Plain multiply-add rather than `f64::mul_add`: without a hardware FMA target feature
33/// (baseline x86_64) `mul_add` becomes a libm call, and results would differ by platform.
34#[inline(always)]
35fn axpy<const N: usize>(y: &[f64; N], a: f64, k: &[f64; N]) -> [f64; N] {
36 std::array::from_fn(|i| y[i] + a * k[i])
37}
38
39/// Advance `y' = f(t, y)` by one classical Runge–Kutta 4 step of size `h` (CORE-R37).
40///
41/// Exact for solutions that are polynomials of degree ≤ 4 in `t`; global error
42/// `O(h⁴)` otherwise. Non-finite values produced by `f` propagate into `y` untouched —
43/// detecting blow-up is the caller's policy, not the integrator's.
44#[inline]
45pub fn rk4_step<const N: usize, F>(y: &mut [f64; N], t: f64, h: f64, mut f: F)
46where
47 F: FnMut(f64, &[f64; N]) -> [f64; N],
48{
49 let half = 0.5 * h;
50 let k1 = f(t, y);
51 let k2 = f(t + half, &axpy(y, half, &k1));
52 let k3 = f(t + half, &axpy(y, half, &k2));
53 let k4 = f(t + h, &axpy(y, h, &k3));
54 let sixth = h / 6.0;
55 for i in 0..N {
56 // Pairwise grouping keeps the weighted sum symmetric and reproducible.
57 let slope = (k1[i] + k4[i]) + 2.0 * (k2[i] + k3[i]);
58 y[i] += sixth * slope;
59 }
60}
61
62/// Integrate `y' = f(t, y)` from `t` to `t + dt` in equal RK4 substeps no longer than
63/// `h_max`, returning how many were taken (CORE-R37).
64///
65/// - `dt ≤ 0` or non-finite: nothing happens, `f` is never called, returns 0.
66/// - Steps: `ceil(dt / h_max)` (with a 1e-9 relative slack for exact multiples), at
67/// least 1 and at most [`MAX_STEPS`].
68/// - `h_max` below [`MIN_STEP`] (including 0, negative, NaN) is raised to `MIN_STEP`;
69/// `h_max = +∞` means a single step.
70///
71/// Substep times are computed as `t + i·h`, not accumulated, so they do not drift.
72pub fn integrate<const N: usize, F>(
73 y: &mut [f64; N],
74 t: f64,
75 dt: f64,
76 h_max: f64,
77 mut f: F,
78) -> usize
79where
80 F: FnMut(f64, &[f64; N]) -> [f64; N],
81{
82 let steps = substeps(dt, h_max);
83 let h = dt / steps as f64;
84 for i in 0..steps {
85 rk4_step(y, t + i as f64 * h, h, &mut f);
86 }
87 steps
88}
89
90/// Number of equal substeps covering `dt` with none longer than `h_max`: the count rule
91/// shared by [`integrate`] and [`verlet_integrate`] (CORE-R37, CORE-R44). 0 for `dt ≤ 0`
92/// or non-finite `dt`, otherwise in `1..=MAX_STEPS`.
93fn substeps(dt: f64, h_max: f64) -> usize {
94 if !(dt.is_finite() && dt > 0.0) {
95 return 0;
96 }
97 // `f64::max` returns the non-NaN operand, so NaN also lands on MIN_STEP.
98 let h_max = h_max.max(MIN_STEP);
99 // Saturating float->int cast; the clamp covers both underflow (tiny dt / huge h_max)
100 // and the MAX_STEPS budget.
101 ((dt / h_max - COUNT_SLACK).ceil() as usize).clamp(1, MAX_STEPS)
102}
103
104/// `v += a * k`, element-wise (plain multiply-add like [`axpy`], for determinism).
105#[inline(always)]
106fn add_scaled(v: &mut [f64], a: f64, k: &[f64]) {
107 for (v, k) in v.iter_mut().zip(k) {
108 *v += a * k;
109 }
110}
111
112/// One kick–drift–kick leapfrog (velocity Verlet) step of size `h` for `x'' = a(x)`
113/// (CORE-R44).
114///
115/// `accel(pos, acc_out)` must overwrite `acc_out` with the accelerations at `pos`.
116/// On entry `acc` must hold `a(pos)`; on exit it holds `a` at the new position, so
117/// consecutive steps cost one force evaluation each. Mismatched slice lengths make the
118/// step a no-op (and `accel` is not called).
119#[inline]
120pub fn verlet_step<F>(pos: &mut [f64], vel: &mut [f64], acc: &mut [f64], h: f64, mut accel: F)
121where
122 F: FnMut(&[f64], &mut [f64]),
123{
124 if pos.len() != vel.len() || pos.len() != acc.len() {
125 return;
126 }
127 let half = 0.5 * h;
128 add_scaled(vel, half, acc);
129 add_scaled(pos, h, vel);
130 accel(pos, acc);
131 add_scaled(vel, half, acc);
132}
133
134/// Advance `x'' = a(x)` by `dt` in equal leapfrog substeps no longer than `h_max`,
135/// returning how many were taken (CORE-R44).
136///
137/// Step-count rules are those of [`integrate`] (`MIN_STEP`, `MAX_STEPS`, none for
138/// `dt ≤ 0` or non-finite `dt`); mismatched slice lengths take no steps. The `acc`
139/// contract is that of [`verlet_step`]: prime it once with `accel(pos, acc)` after
140/// building the state, then carry it alongside `pos` and `vel`.
141pub fn verlet_integrate<F>(
142 pos: &mut [f64],
143 vel: &mut [f64],
144 acc: &mut [f64],
145 dt: f64,
146 h_max: f64,
147 mut accel: F,
148) -> usize
149where
150 F: FnMut(&[f64], &mut [f64]),
151{
152 if pos.len() != vel.len() || pos.len() != acc.len() {
153 return 0;
154 }
155 let steps = substeps(dt, h_max);
156 let h = dt / steps as f64;
157 for _ in 0..steps {
158 verlet_step(pos, vel, acc, h, &mut accel);
159 }
160 steps
161}
162
163/// Solve the tridiagonal system `sub[i]·x[i−1] + diag[i]·x[i] + sup[i]·x[i+1] = rhs[i]`
164/// in place into `rhs` by the Thomas algorithm, in O(n) (CORE-R59). `sub[0]` and
165/// `sup[n − 1]` are ignored; `scratch` holds the eliminated super-diagonal.
166///
167/// For implicit (Crank–Nicolson) diffusion steps, which stay stable at any `dt`. All
168/// five slices must have the same length. Mismatched lengths or a zero (or non-finite)
169/// pivot return `false` with `rhs` untouched: the pivots are checked in a first pass
170/// before `rhs` is written. Without pivoting, it is stable for diagonally dominant
171/// matrices, which is what diffusion produces.
172pub fn tridiag_solve(
173 sub: &[f64],
174 diag: &[f64],
175 sup: &[f64],
176 rhs: &mut [f64],
177 scratch: &mut [f64],
178) -> bool {
179 let n = rhs.len();
180 if [sub.len(), diag.len(), sup.len(), scratch.len()] != [n; 4] {
181 return false;
182 }
183 // Pass 1: pivots m_i = diag[i] − sub[i]·c'[i−1], and c'[i] = sup[i] / m_i.
184 let pivot = |i: usize, c_prev: f64| {
185 if i == 0 {
186 diag[0]
187 } else {
188 diag[i] - sub[i] * c_prev
189 }
190 };
191 let mut c_prev = 0.0;
192 for i in 0..n {
193 let m = pivot(i, c_prev);
194 if m == 0.0 || !m.is_finite() {
195 return false;
196 }
197 c_prev = sup[i] / m;
198 scratch[i] = c_prev;
199 }
200 // Pass 2: forward-eliminate rhs with the same pivots, then back-substitute.
201 for i in 0..n {
202 let c_prev = if i == 0 { 0.0 } else { scratch[i - 1] };
203 let d_prev = if i == 0 { 0.0 } else { rhs[i - 1] };
204 rhs[i] = (rhs[i] - sub[i] * d_prev) / pivot(i, c_prev);
205 }
206 for i in (0..n.saturating_sub(1)).rev() {
207 rhs[i] -= scratch[i] * rhs[i + 1];
208 }
209 true
210}
211
212/// A plain complex number for [`tridiag_solve_c`] and its callers (CORE-R100): `Copy`,
213/// two `f64`s, the textbook formulas and nothing else (no dependency).
214#[derive(Debug, Clone, Copy, PartialEq, Default)]
215pub struct C64 {
216 pub re: f64,
217 pub im: f64,
218}
219
220impl C64 {
221 pub const ZERO: C64 = C64 { re: 0.0, im: 0.0 };
222 pub const ONE: C64 = C64 { re: 1.0, im: 0.0 };
223 pub const I: C64 = C64 { re: 0.0, im: 1.0 };
224
225 #[inline]
226 pub const fn new(re: f64, im: f64) -> Self {
227 Self { re, im }
228 }
229
230 #[inline]
231 pub fn conj(self) -> Self {
232 Self::new(self.re, -self.im)
233 }
234
235 /// `|z|²`.
236 #[inline]
237 pub fn norm_sqr(self) -> f64 {
238 self.re * self.re + self.im * self.im
239 }
240
241 /// `k·z` for real `k`.
242 #[inline]
243 pub fn scale(self, k: f64) -> Self {
244 Self::new(self.re * k, self.im * k)
245 }
246
247 /// Whether both parts are finite.
248 #[inline]
249 pub fn is_finite(self) -> bool {
250 self.re.is_finite() && self.im.is_finite()
251 }
252}
253
254impl std::ops::Add for C64 {
255 type Output = C64;
256 #[inline]
257 fn add(self, o: C64) -> C64 {
258 C64::new(self.re + o.re, self.im + o.im)
259 }
260}
261
262impl std::ops::Sub for C64 {
263 type Output = C64;
264 #[inline]
265 fn sub(self, o: C64) -> C64 {
266 C64::new(self.re - o.re, self.im - o.im)
267 }
268}
269
270impl std::ops::Neg for C64 {
271 type Output = C64;
272 #[inline]
273 fn neg(self) -> C64 {
274 C64::new(-self.re, -self.im)
275 }
276}
277
278impl std::ops::Mul for C64 {
279 type Output = C64;
280 #[inline]
281 fn mul(self, o: C64) -> C64 {
282 C64::new(
283 self.re * o.re - self.im * o.im,
284 self.re * o.im + self.im * o.re,
285 )
286 }
287}
288
289impl std::ops::Div for C64 {
290 type Output = C64;
291 /// `a / b = a·conj(b) / |b|²`; a zero `b` gives non-finite parts.
292 #[inline]
293 fn div(self, o: C64) -> C64 {
294 (self * o.conj()).scale(1.0 / o.norm_sqr())
295 }
296}
297
298/// [`tridiag_solve`] over [`C64`] (CORE-R100): solve `sub[i]·x[i−1] + diag[i]·x[i] +
299/// sup[i]·x[i+1] = rhs[i]` in place into `rhs`, `scratch` holding the eliminated
300/// super-diagonal. Mismatched lengths or a zero (or non-finite) pivot return `false`
301/// with `rhs` untouched.
302pub fn tridiag_solve_c(
303 sub: &[C64],
304 diag: &[C64],
305 sup: &[C64],
306 rhs: &mut [C64],
307 scratch: &mut [C64],
308) -> bool {
309 let n = rhs.len();
310 if [sub.len(), diag.len(), sup.len(), scratch.len()] != [n; 4] {
311 return false;
312 }
313 // Pass 1: c'[i] = sup[i] / m_i with m_i = diag[i] − sub[i]·c'[i−1].
314 let mut c_prev = C64::ZERO;
315 for i in 0..n {
316 let m = if i == 0 {
317 diag[0]
318 } else {
319 diag[i] - sub[i] * c_prev
320 };
321 if m.norm_sqr() == 0.0 || !m.is_finite() {
322 return false;
323 }
324 c_prev = sup[i] / m;
325 scratch[i] = c_prev;
326 }
327 for i in 0..n {
328 let (m, d_prev) = if i == 0 {
329 (diag[0], C64::ZERO)
330 } else {
331 (diag[i] - sub[i] * scratch[i - 1], rhs[i - 1])
332 };
333 rhs[i] = (rhs[i] - sub[i] * d_prev) / m;
334 }
335 for i in (0..n.saturating_sub(1)).rev() {
336 rhs[i] = rhs[i] - scratch[i] * rhs[i + 1];
337 }
338 true
339}
340
341/// Factor a complex tridiagonal matrix once for [`tridiag_apply_c`] (CORE-R100):
342/// `inv_pivot[i] = 1/m_i` and `c_prime[i] = sup[i]/m_i`. Mismatched lengths or a zero
343/// (or non-finite) pivot return `false` with both outputs untouched.
344pub fn tridiag_factor_c(
345 sub: &[C64],
346 diag: &[C64],
347 sup: &[C64],
348 inv_pivot: &mut [C64],
349 c_prime: &mut [C64],
350) -> bool {
351 let n = diag.len();
352 if [sub.len(), sup.len(), inv_pivot.len(), c_prime.len()] != [n; 4] {
353 return false;
354 }
355 // Check every pivot before writing, so a failure leaves the outputs as they were.
356 let mut c_prev = C64::ZERO;
357 for i in 0..n {
358 let m = if i == 0 {
359 diag[0]
360 } else {
361 diag[i] - sub[i] * c_prev
362 };
363 if m.norm_sqr() == 0.0 || !m.is_finite() {
364 return false;
365 }
366 c_prev = sup[i] / m;
367 }
368 let mut c_prev = C64::ZERO;
369 for i in 0..n {
370 let m = if i == 0 {
371 diag[0]
372 } else {
373 diag[i] - sub[i] * c_prev
374 };
375 let inv = C64::ONE / m;
376 c_prev = sup[i] * inv;
377 inv_pivot[i] = inv;
378 c_prime[i] = c_prev;
379 }
380 true
381}
382
383/// Solve with a matrix factored by [`tridiag_factor_c`], in place into `rhs`: two
384/// complex multiply-adds per unknown. Mismatched lengths do nothing (CORE-R100).
385#[inline]
386pub fn tridiag_apply_c(sub: &[C64], inv_pivot: &[C64], c_prime: &[C64], rhs: &mut [C64]) {
387 let n = rhs.len();
388 if [sub.len(), inv_pivot.len(), c_prime.len()] != [n; 3] || n == 0 {
389 return;
390 }
391 let mut d_prev = rhs[0] * inv_pivot[0];
392 rhs[0] = d_prev;
393 for i in 1..n {
394 d_prev = (rhs[i] - sub[i] * d_prev) * inv_pivot[i];
395 rhs[i] = d_prev;
396 }
397 for i in (0..n - 1).rev() {
398 rhs[i] = rhs[i] - c_prime[i] * rhs[i + 1];
399 }
400}