1use super::{Event, IvpSolution, Segment, Stepper, drive};
10use lib_jsl_core::ErrorsJSL;
11
12#[rustfmt::skip]
13mod tables {
14pub(super) const RK45_A: [[f64; 5]; 6] = [[0.0, 0.0, 0.0, 0.0, 0.0], [0.2, 0.0, 0.0, 0.0, 0.0], [0.075, 0.225, 0.0, 0.0, 0.0], [0.9777777777777777, -3.7333333333333334, 3.5555555555555554, 0.0, 0.0], [2.9525986892242035, -11.595793324188385, 9.822892851699436, -0.2908093278463649, 0.0], [2.8462752525252526, -10.757575757575758, 8.906422717743473, 0.2784090909090909, -0.2735313036020583]];
15pub(super) const RK45_B: [f64; 6] = [0.09114583333333333, 0.0, 0.44923629829290207, 0.6510416666666666, -0.322376179245283, 0.13095238095238096];
16pub(super) const RK45_C: [f64; 6] = [0.0, 0.2, 0.3, 0.8, 0.8888888888888888, 1.0];
17pub(super) const RK45_E: [f64; 7] = [-0.0012326388888888888, 0.0, 0.0042527702905061394, -0.03697916666666667, 0.05086379716981132, -0.0419047619047619, 0.025];
18pub(super) const RK45_P: [[f64; 4]; 7] = [[1.0, -2.8535800653862835, 3.0717434641059005, -1.1270175653862835], [0.0, 0.0, 0.0, 0.0], [0.0, 4.023133379230305, -6.249321565289, 2.675424484351598], [0.0, -3.7324019615885042, 10.068970589843675, -5.685526961588504], [0.0, 2.5548038301849423, -6.399112377351017, 3.5219323679207912], [0.0, -1.3744241142186024, 3.272657752246729, -1.7672812570757455], [0.0, 1.3824689317781436, -3.764937863556287, 2.382468931778144]];
19pub(super) const DOP_A: [[f64; 16]; 16] = [[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.05260015195876773, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0197250569845379, 0.0591751709536137, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.02958758547680685, 0.0, 0.08876275643042054, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.2413651341592667, 0.0, -0.8845494793282861, 0.924834003261792, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.037037037037037035, 0.0, 0.0, 0.17082860872947386, 0.12546768756682242, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.037109375, 0.0, 0.0, 0.17025221101954405, 0.06021653898045596, -0.017578125, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.03709200011850479, 0.0, 0.0, 0.17038392571223998, 0.10726203044637328, -0.015319437748624402, 0.008273789163814023, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.6241109587160757, 0.0, 0.0, -3.3608926294469414, -0.868219346841726, 27.59209969944671, 20.154067550477894, -43.48988418106996, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.47766253643826434, 0.0, 0.0, -2.4881146199716677, -0.590290826836843, 21.230051448181193, 15.279233632882423, -33.28821096898486, -0.020331201708508627, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [-0.9371424300859873, 0.0, 0.0, 5.186372428844064, 1.0914373489967295, -8.149787010746927, -18.52006565999696, 22.739487099350505, 2.4936055526796523, -3.0467644718982196, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [2.273310147516538, 0.0, 0.0, -10.53449546673725, -2.0008720582248625, -17.9589318631188, 27.94888452941996, -2.8589982771350235, -8.87285693353063, 12.360567175794303, 0.6433927460157636, 0.0, 0.0, 0.0, 0.0, 0.0], [0.054293734116568765, 0.0, 0.0, 0.0, 0.0, 4.450312892752409, 1.8915178993145003, -5.801203960010585, 0.3111643669578199, -0.1521609496625161, 0.20136540080403034, 0.04471061572777259, 0.0, 0.0, 0.0, 0.0], [0.056167502283047954, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25350021021662483, -0.2462390374708025, -0.12419142326381637, 0.15329179827876568, 0.00820105229563469, 0.007567897660545699, -0.008298, 0.0, 0.0, 0.0], [0.03183464816350214, 0.0, 0.0, 0.0, 0.0, 0.028300909672366776, 0.053541988307438566, -0.05492374857139099, 0.0, 0.0, -0.00010834732869724932, 0.0003825710908356584, -0.00034046500868740456, 0.1413124436746325, 0.0, 0.0], [-0.42889630158379194, 0.0, 0.0, 0.0, 0.0, -4.697621415361164, 7.683421196062599, 4.06898981839711, 0.3567271874552811, 0.0, 0.0, 0.0, -0.0013990241651590145, 2.9475147891527724, -9.15095847217987, 0.0]];
20pub(super) const DOP_B: [f64; 12] = [0.054293734116568765, 0.0, 0.0, 0.0, 0.0, 4.450312892752409, 1.8915178993145003, -5.801203960010585, 0.3111643669578199, -0.1521609496625161, 0.20136540080403034, 0.04471061572777259];
21pub(super) const DOP_C: [f64; 16] = [0.0, 0.05260015195876773, 0.0789002279381516, 0.1183503419072274, 0.2816496580927726, 0.3333333333333333, 0.25, 0.3076923076923077, 0.6512820512820513, 0.6, 0.8571428571428571, 1.0, 1.0, 0.1, 0.2, 0.7777777777777778];
22pub(super) const DOP_E3: [f64; 13] = [-0.18980075407240762, 0.0, 0.0, 0.0, 0.0, 4.450312892752409, 1.8915178993145003, -5.801203960010585, -0.4226823213237919, -0.1521609496625161, 0.20136540080403034, 0.02265179219836082, 0.0];
23pub(super) const DOP_E5: [f64; 13] = [0.01312004499419488, 0.0, 0.0, 0.0, 0.0, -1.2251564463762044, -0.4957589496572502, 1.6643771824549864, -0.35032884874997366, 0.3341791187130175, 0.08192320648511571, -0.022355307863886294, 0.0];
24pub(super) const DOP_D: [[f64; 16]; 4] = [[-8.428938276109013, 0.0, 0.0, 0.0, 0.0, 0.5667149535193777, -3.0689499459498917, 2.38466765651207, 2.117034582445028, -0.871391583777973, 2.2404374302607883, 0.6315787787694688, -0.08899033645133331, 18.148505520854727, -9.194632392478356, -4.436036387594894], [10.427508642579134, 0.0, 0.0, 0.0, 0.0, 242.28349177525817, 165.20045171727028, -374.5467547226902, -22.113666853125306, 7.733432668472264, -30.674084731089398, -9.332130526430229, 15.697238121770845, -31.139403219565178, -9.35292435884448, 35.81684148639408], [19.985053242002433, 0.0, 0.0, 0.0, 0.0, -387.0373087493518, -189.17813819516758, 527.8081592054236, -11.57390253995963, 6.8812326946963, -1.0006050966910838, 0.7777137798053443, -2.778205752353508, -60.19669523126412, 84.32040550667716, 11.99229113618279], [-25.69393346270375, 0.0, 0.0, 0.0, 0.0, -154.18974869023643, -231.5293791760455, 357.6391179106141, 93.40532418362432, -37.45832313645163, 104.0996495089623, 29.8402934266605, -43.53345659001114, 96.32455395918828, -39.17726167561544, -149.72683625798564]];
25}
26use tables::*;
27
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30#[non_exhaustive]
31pub enum ExplicitMethod {
32 Rk45,
34 Dop853,
36}
37
38#[derive(Clone, Debug)]
42pub struct ExplicitOptions {
43 pub rtol: f64,
44 pub atol: f64,
45 pub atol_components: Vec<f64>,
47 pub first_step: Option<f64>,
49 pub max_step: f64,
51 pub max_steps: usize,
53}
54
55impl Default for ExplicitOptions {
56 fn default() -> Self {
58 ExplicitOptions { rtol: 1e-3, atol: 1e-6, atol_components: Vec::new(), first_step: None, max_step: f64::INFINITY, max_steps: 1_000_000 }
59 }
60}
61
62const SAFETY: f64 = 0.9;
63const MIN_FACTOR: f64 = 0.2;
64const MAX_FACTOR: f64 = 10.0;
65
66fn rms(v: &[f64]) -> f64 {
67 (v.iter().map(|x| x * x).sum::<f64>() / v.len() as f64).sqrt()
68}
69
70struct ExplicitRk<'a, F> {
71 f: &'a F,
72 method: ExplicitMethod,
73 t: f64,
74 y: Vec<f64>,
75 fy: Vec<f64>,
76 t_bound: f64,
77 direction: f64,
78 h_abs: f64,
79 rtol: f64,
80 atol: Vec<f64>,
81 max_step: f64,
82 nfev: usize,
83 rejected: usize,
84}
85
86impl<F: Fn(f64, &[f64]) -> Vec<f64>> ExplicitRk<'_, F> {
87 fn eval(&mut self, t: f64, y: &[f64]) -> Vec<f64> {
88 self.nfev += 1;
89 (self.f)(t, y)
90 }
91
92 fn n_stages(&self) -> usize {
93 match self.method {
94 ExplicitMethod::Rk45 => 6,
95 ExplicitMethod::Dop853 => 12,
96 }
97 }
98
99 fn a(&self, s: usize, j: usize) -> f64 {
100 match self.method {
101 ExplicitMethod::Rk45 => RK45_A[s][j],
102 ExplicitMethod::Dop853 => DOP_A[s][j],
103 }
104 }
105
106 fn c(&self, s: usize) -> f64 {
107 match self.method {
108 ExplicitMethod::Rk45 => RK45_C[s],
109 ExplicitMethod::Dop853 => DOP_C[s],
110 }
111 }
112
113 fn b(&self, s: usize) -> f64 {
114 match self.method {
115 ExplicitMethod::Rk45 => RK45_B[s],
116 ExplicitMethod::Dop853 => DOP_B[s],
117 }
118 }
119
120 fn stage_point(&self, k: &[Vec<f64>], s: usize, y: &[f64], h: f64) -> Vec<f64> {
122 let mut out = y.to_vec();
123 for (j, kj) in k.iter().enumerate().take(s) {
124 let a = self.a(s, j) * h;
125 if a != 0.0 {
126 out.iter_mut().zip(kj).for_each(|(o, v)| *o += a * v);
127 }
128 }
129 out
130 }
131
132 fn rk_step(&mut self, h: f64) -> (Vec<f64>, Vec<Vec<f64>>) {
136 let n = self.n_stages();
137 let mut k = vec![self.fy.clone()];
138 for s in 1..n {
139 let p = self.stage_point(&k, s, &self.y, h);
140 let ks = self.eval(self.t + self.c(s) * h, &p);
141 k.push(ks);
142 }
143 let mut y_new = self.y.clone();
144 for (s, ks) in k.iter().enumerate() {
145 let b = self.b(s) * h;
146 y_new.iter_mut().zip(ks).for_each(|(o, v)| *o += b * v);
147 }
148 let f_new = self.eval(self.t + h, &y_new);
149 k.push(f_new);
150 (y_new, k)
151 }
152 fn error_norm(&self, k: &[Vec<f64>], h: f64, scale: &[f64]) -> f64 {
157 let combine = |e: &[f64]| -> Vec<f64> { (0..scale.len()).map(|i| k.iter().zip(e).map(|(ks, w)| w * ks[i]).sum::<f64>() / scale[i]).collect() };
158 match self.method {
159 ExplicitMethod::Rk45 => rms(&combine(&RK45_E).iter().map(|v| v * h).collect::<Vec<_>>()),
160 ExplicitMethod::Dop853 => {
161 let e5: f64 = combine(&DOP_E5).iter().map(|v| v * v).sum();
162 let e3: f64 = combine(&DOP_E3).iter().map(|v| v * v).sum();
163 if e5 == 0.0 && e3 == 0.0 {
164 return 0.0;
165 }
166 h.abs() * e5 / ((e5 + 0.01 * e3) * scale.len() as f64).sqrt()
167 }
168 }
169 }
170
171 fn error_exponent(&self) -> f64 {
172 match self.method {
173 ExplicitMethod::Rk45 => -1.0 / 5.0,
174 ExplicitMethod::Dop853 => -1.0 / 8.0,
175 }
176 }
177
178 fn dense(&mut self, t_old: f64, y_old: &[f64], f_old_new: (&[f64], &[f64]), mut k: Vec<Vec<f64>>, h: f64) -> Vec<Vec<f64>> {
180 let n = y_old.len();
181 match self.method {
182 ExplicitMethod::Rk45 => {
183 (0..4).map(|p| (0..n).map(|i| h * k.iter().enumerate().map(|(s, ks)| RK45_P[s][p] * ks[i]).sum::<f64>()).collect()).collect()
185 }
186 ExplicitMethod::Dop853 => {
187 for s in 13..16 {
189 let p = self.stage_point(&k, s, y_old, h);
190 let ks = self.eval(t_old + DOP_C[s] * h, &p);
191 k.push(ks);
192 }
193 let (f_old, f_new) = f_old_new;
194 let dy: Vec<f64> = self.y.iter().zip(y_old).map(|(a, b)| a - b).collect();
195 let mut f = vec![dy.clone(), (0..n).map(|i| h * f_old[i] - dy[i]).collect(), (0..n).map(|i| 2.0 * dy[i] - h * (f_new[i] + f_old[i])).collect()];
196 for d in DOP_D.iter() {
197 f.push((0..n).map(|i| h * k.iter().enumerate().map(|(s, ks)| d[s] * ks[i]).sum::<f64>()).collect());
198 }
199 let mut poly: Vec<Vec<f64>> = vec![vec![0.0; n]];
202 for (step, row) in f.iter().rev().enumerate() {
203 poly[0].iter_mut().zip(row).for_each(|(a, b)| *a += b);
204 let mut next = vec![vec![0.0; n]; poly.len() + 1];
205 for (d, coef) in poly.iter().enumerate() {
206 for i in 0..n {
207 if step % 2 == 0 {
208 next[d + 1][i] += coef[i];
209 } else {
210 next[d][i] += coef[i];
211 next[d + 1][i] -= coef[i];
212 }
213 }
214 }
215 poly = next;
216 }
217 poly.remove(0); poly
219 }
220 }
221 }
222}
223
224impl<F: Fn(f64, &[f64]) -> Vec<f64>> Stepper for ExplicitRk<'_, F> {
225 fn t(&self) -> f64 {
226 self.t
227 }
228 fn y(&self) -> &[f64] {
229 &self.y
230 }
231 fn counts(&self) -> (usize, usize, usize, usize) {
232 (self.nfev, 0, 0, self.rejected)
233 }
234
235 fn step(&mut self) -> Result<Segment, ErrorsJSL> {
240 let t = self.t;
241 let min_step = 10.0 * ((t + self.direction * t.abs().max(f64::MIN_POSITIVE) * f64::EPSILON) - t).abs().max(f64::MIN_POSITIVE);
242 let mut h_abs = self.h_abs.min(self.max_step).max(min_step);
243 let mut rejected = false;
244 loop {
245 if h_abs < min_step {
246 return Err(ErrorsJSL::RuntimeError("solve_ivp_explicit: the step size became too small"));
247 }
248 let mut t_new = t + self.direction * h_abs;
249 if self.direction * (t_new - self.t_bound) > 0.0 {
250 t_new = self.t_bound;
251 }
252 let h = t_new - t;
253 h_abs = h.abs();
254 let (y_new, k) = self.rk_step(h);
255 let scale: Vec<f64> = (0..y_new.len()).map(|i| self.atol[i] + self.y[i].abs().max(y_new[i].abs()) * self.rtol).collect();
256 let err = self.error_norm(&k, h, &scale);
257 if err < 1.0 {
258 let mut factor = if err == 0.0 { MAX_FACTOR } else { MAX_FACTOR.min(SAFETY * err.powf(self.error_exponent())) };
259 if rejected {
260 factor = factor.min(1.0);
261 }
262 let y_old = std::mem::replace(&mut self.y, y_new);
263 let f_new = k[k.len() - 1].clone();
264 let f_old = std::mem::replace(&mut self.fy, f_new.clone());
265 self.t = t_new;
266 self.h_abs = h_abs * factor;
267 let coeffs = self.dense(t, &y_old, (&f_old, &f_new), k, h);
268 return Ok(Segment { t_start: t.min(t_new), t_end: t.max(t_new), t_ref: t, h, y_ref: y_old, coeffs });
269 }
270 h_abs *= MIN_FACTOR.max(SAFETY * err.powf(self.error_exponent()));
271 self.rejected += 1;
272 rejected = true;
273 }
274 }
275 }
277
278pub fn solve_ivp_explicit<F>(f: F, t_span: (f64, f64), y0: &[f64], method: ExplicitMethod, options: &ExplicitOptions, events: &[Event]) -> Result<IvpSolution, ErrorsJSL>
284where
285 F: Fn(f64, &[f64]) -> Vec<f64>,
286{
287 let (t0, t1) = t_span;
288 let n = y0.len();
289 if n == 0 || !t0.is_finite() || !t1.is_finite() || t0 == t1 {
290 return Err(ErrorsJSL::InvalidInputRange("need a non-empty state and finite t0 ≠ t1"));
291 }
292 let atol = if options.atol_components.is_empty() { vec![options.atol; n] } else { options.atol_components.clone() };
293 if atol.len() != n || atol.iter().any(|a| !(*a >= 0.0)) || !(options.rtol > 0.0) {
294 return Err(ErrorsJSL::InvalidInputRange("need rtol > 0 and one non-negative atol per component"));
295 }
296 if !(options.max_step > 0.0) {
297 return Err(ErrorsJSL::InvalidInputRange("max_step must be positive"));
298 }
299 let direction = if t1 > t0 { 1.0 } else { -1.0 };
300 let mut rk = ExplicitRk { f: &f, method, t: t0, y: y0.to_vec(), fy: Vec::new(), t_bound: t1, direction, h_abs: 0.0, rtol: options.rtol, atol, max_step: options.max_step, nfev: 0, rejected: 0 };
301 rk.fy = rk.eval(t0, y0);
302 rk.h_abs = match options.first_step {
303 Some(h) if h > 0.0 => h,
304 Some(_) => return Err(ErrorsJSL::InvalidInputRange("first_step must be positive")),
305 None => {
306 let order = match method {
308 ExplicitMethod::Rk45 => 4.0,
309 ExplicitMethod::Dop853 => 7.0,
310 };
311 let span = (t1 - t0).abs();
312 let scale: Vec<f64> = (0..n).map(|i| rk.atol[i] + y0[i].abs() * rk.rtol).collect();
313 let d0 = rms(&y0.iter().zip(&scale).map(|(a, s)| a / s).collect::<Vec<_>>());
314 let d1 = rms(&rk.fy.iter().zip(&scale).map(|(a, s)| a / s).collect::<Vec<_>>());
315 let h0 = if d0 < 1e-5 || d1 < 1e-5 { 1e-6 } else { 0.01 * d0 / d1 }.min(span);
316 let y1: Vec<f64> = (0..n).map(|i| y0[i] + h0 * direction * rk.fy[i]).collect();
317 let f1 = rk.eval(t0 + h0 * direction, &y1);
318 let d2 = rms(&(0..n).map(|i| (f1[i] - rk.fy[i]) / scale[i]).collect::<Vec<_>>()) / h0;
319 let h1 = if d1 <= 1e-15 && d2 <= 1e-15 { (h0 * 1e-3).max(1e-6) } else { (0.01 / d1.max(d2)).powf(1.0 / (order + 1.0)) };
320 (100.0 * h0).min(h1).min(span).min(options.max_step)
321 }
322 };
323 let (t, y, status, t_events, y_events, dense) = drive(&mut rk, t0, t1, y0, events, options.max_steps)?;
324 let (nfev, _, _, rejected_steps) = rk.counts();
325 Ok(IvpSolution { t, y, status, t_events, y_events, dense, nfev, njev: 0, nlu: 0, rejected_steps, switches: Vec::new() })
326}
327#[cfg(test)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn both_methods_reach_their_order_on_the_harmonic_oscillator() {
335 let f = |_: f64, y: &[f64]| vec![y[1], -y[0]];
336 for method in [ExplicitMethod::Rk45, ExplicitMethod::Dop853] {
337 let o = ExplicitOptions { rtol: 1e-10, atol: 1e-12, ..Default::default() };
338 let sol = solve_ivp_explicit(f, (0.0, 10.0), &[1.0, 0.0], method, &o, &[]).unwrap();
339 let y = sol.y.last().unwrap();
340 assert!((y[0] - 10f64.cos()).abs() < 1e-8, "{method:?} {y:?}");
341 let d = sol.dense.evaluate(3.3);
343 assert!((d[0] - 3.3f64.cos()).abs() < 1e-8, "{method:?} dense {d:?}");
344 }
345 let o = ExplicitOptions { rtol: 1e-10, atol: 1e-12, ..Default::default() };
347 let a = solve_ivp_explicit(f, (0.0, 10.0), &[1.0, 0.0], ExplicitMethod::Rk45, &o, &[]).unwrap();
348 let b = solve_ivp_explicit(f, (0.0, 10.0), &[1.0, 0.0], ExplicitMethod::Dop853, &o, &[]).unwrap();
349 assert!(b.nfev * 2 < a.nfev, "{} vs {}", b.nfev, a.nfev);
350 }
351
352 #[test]
353 fn backward_integration_and_events() {
354 let cross = Event { function: Box::new(|_, y: &[f64]| y[0] - std::f64::consts::E), direction: 0.0, terminal: None };
356 let o = ExplicitOptions { rtol: 1e-10, atol: 1e-12, ..Default::default() };
357 let sol = solve_ivp_explicit(|_, y: &[f64]| vec![y[0]], (2.0, 0.0), &[2f64.exp()], ExplicitMethod::Dop853, &o, std::slice::from_ref(&cross)).unwrap();
358 assert!((sol.y.last().unwrap()[0] - 1.0).abs() < 1e-9);
359 assert!((sol.t_events[0][0] - 1.0).abs() < 1e-9, "{:?}", sol.t_events);
360 assert!((sol.dense.evaluate(0.5)[0] - 0.5f64.exp()).abs() < 1e-9);
361 let o = ExplicitOptions { atol_components: vec![1e-9, 1e-3], ..Default::default() };
363 assert!(solve_ivp_explicit(|_, y: &[f64]| vec![-y[0], -y[1]], (0.0, 1.0), &[1.0, 1.0], ExplicitMethod::Rk45, &o, &[]).is_ok());
364 }
365}