Skip to main content

lib_jsl_integration/
boundary_value_problems.rs

1//! Two-point boundary value problems `y' = f(x, y)` on `[a, b]` with `g(y(a), y(b)) = 0`.
2//!
3//! * [`solve_bvp_shooting`]: single shooting. The unknown initial state is found by Newton's
4//!   method on the boundary residual, each evaluation integrating the initial value problem with
5//!   an adaptive Dormand-Prince 5(4) method. Simple and accurate for well-conditioned problems;
6//!   it fails when the initial value problem is unstable over `[a, b]` (e.g. boundary layers).
7//! * [`solve_bvp_collocation`]: global collocation with the fourth-order Hermite-Simpson
8//!   (Lobatto IIIA) scheme, solved by damped Newton on the whole mesh, with mesh refinement where
9//!   the defect of the cubic interpolant is large (the method of SciPy's `solve_bvp`). Robust for
10//!   stiff and boundary-layer problems.
11//!
12//! See the book entry [Boundary value problems](https://jwkunz.github.io/lib_jsl/book/integration/boundary-value-problems.html).
13
14use crate::stiff_ode::Lu;
15use lib_jsl_core::ErrorsJSL;
16
17/// Options for the boundary value solvers.
18#[derive(Debug, Clone, Copy)]
19pub struct BvpOptions {
20    /// Collocation: bound on the relative defect `|S' − f| / (1 + |f|)` of the interpolant.
21    /// Shooting: bound on the boundary residual.
22    pub tolerance: f64,
23    /// Largest mesh allowed by refinement (collocation).
24    pub max_nodes: usize,
25    /// The largest number of Newton iterations (per mesh, for collocation).
26    pub max_newton_iterations: usize,
27}
28
29impl Default for BvpOptions {
30    fn default() -> Self {
31        BvpOptions { tolerance: 1e-6, max_nodes: 2000, max_newton_iterations: 50 }
32    }
33}
34
35/// A solution on a mesh, with derivatives for cubic Hermite interpolation.
36#[derive(Debug, Clone)]
37pub struct BvpSolution {
38    /// The mesh (collocation) or the accepted integration steps (shooting).
39    pub x: Vec<f64>,
40    /// The state at each point of `x`.
41    pub y: Vec<Vec<f64>>,
42    /// `f(x_i, y_i)` at each mesh point.
43    pub derivative: Vec<Vec<f64>>,
44    /// Whether the tolerance was met.
45    pub converged: bool,
46    /// The largest relative defect (collocation) or boundary residual (shooting).
47    pub max_residual: f64,
48}
49
50/// The cubic Hermite interpolant on one interval at fraction `t`, and its derivative.
51fn hermite(t: f64, h: f64, y0: &[f64], f0: &[f64], y1: &[f64], f1: &[f64]) -> (Vec<f64>, Vec<f64>) {
52    let (t2, t3) = (t * t, t * t * t);
53    let (h00, h10, h01, h11) = (2.0 * t3 - 3.0 * t2 + 1.0, t3 - 2.0 * t2 + t, -2.0 * t3 + 3.0 * t2, t3 - t2);
54    let (d00, d10, d01, d11) = ((6.0 * t2 - 6.0 * t) / h, 3.0 * t2 - 4.0 * t + 1.0, (-6.0 * t2 + 6.0 * t) / h, 3.0 * t2 - 2.0 * t);
55    let value = (0..y0.len()).map(|k| h00 * y0[k] + h * h10 * f0[k] + h01 * y1[k] + h * h11 * f1[k]).collect();
56    let slope = (0..y0.len()).map(|k| d00 * y0[k] + d10 * f0[k] + d01 * y1[k] + d11 * f1[k]).collect();
57    (value, slope)
58}
59
60impl BvpSolution {
61    /// The solution at `x` by cubic Hermite interpolation (clamped to the interval).
62    pub fn evaluate(&self, x: f64) -> Vec<f64> {
63        let ascending = self.x[self.x.len() - 1] >= self.x[0];
64        let i = self
65            .x
66            .windows(2)
67            .position(|w| if ascending { x <= w[1] } else { x >= w[1] })
68            .unwrap_or(self.x.len() - 2);
69        let h = self.x[i + 1] - self.x[i];
70        let t = ((x - self.x[i]) / h).clamp(0.0, 1.0);
71        hermite(t, h, &self.y[i], &self.derivative[i], &self.y[i + 1], &self.derivative[i + 1]).0
72    }
73}
74
75fn eval<F: Fn(f64, &[f64]) -> Vec<f64>>(f: &F, x: f64, y: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
76    let v = f(x, y);
77    if v.len() != y.len() {
78        return Err(ErrorsJSL::IncompatibleArraySizes((v.len(), y.len())));
79    }
80    Ok(v)
81}
82
83fn inf_norm(v: &[f64]) -> f64 {
84    v.iter().fold(0.0, |m, a| m.max(a.abs()))
85}
86
87/// Mesh points and states of an initial value solve.
88type Trajectory = (Vec<f64>, Vec<Vec<f64>>);
89
90/// Integrates `y' = f(x, y)` from `a` to `b` with adaptive Dormand-Prince 5(4), returning every
91/// accepted step.
92fn dormand_prince_system<F: Fn(f64, &[f64]) -> Vec<f64>>(f: &F, a: f64, y0: &[f64], b: f64, rtol: f64, atol: f64) -> Result<Trajectory, ErrorsJSL> {
93    let options = crate::stiff_ode::OdeOptions { relative_tolerance: rtol, absolute_tolerance: atol, initial_step: Some(1e-3 * (b - a).abs()), max_steps: 1_000_000 };
94    let s = crate::dormand_prince::dormand_prince_solve(f, a, y0, b, options)?;
95    Ok((s.t, s.y))
96}
97
98/// Solves the boundary value problem by single shooting from the guess `initial_state` for
99/// `y(a)`. `boundary(y(a), y(b))` must return as many residuals as there are state components.
100pub fn solve_bvp_shooting<F, G>(f: F, boundary: G, a: f64, b: f64, initial_state: Vec<f64>, options: BvpOptions) -> Result<BvpSolution, ErrorsJSL>
101where
102    F: Fn(f64, &[f64]) -> Vec<f64>,
103    G: Fn(&[f64], &[f64]) -> Vec<f64>,
104{
105    let n = initial_state.len();
106    if n == 0 || !a.is_finite() || !b.is_finite() || a == b {
107        return Err(ErrorsJSL::InvalidInputRange("Shooting needs a non-empty state and a finite, non-empty interval."));
108    }
109    let (rtol, atol) = (1e-12, 1e-14);
110    let residual = |s: &[f64]| -> Result<(Vec<f64>, Trajectory), ErrorsJSL> {
111        let trajectory = dormand_prince_system(&f, a, s, b, rtol, atol)?;
112        let g = boundary(s, trajectory.1.last().expect("non-empty"));
113        if g.len() != n {
114            return Err(ErrorsJSL::IncompatibleArraySizes((g.len(), n)));
115        }
116        Ok((g, trajectory))
117    };
118    let mut s = initial_state;
119    let (mut g, mut trajectory) = residual(&s)?;
120    let mut converged = inf_norm(&g) <= options.tolerance;
121    for _ in 0..options.max_newton_iterations {
122        if converged {
123            break;
124        }
125        // ANCHOR: shooting_newton
126        // Finite-difference Jacobian of the boundary residual with respect to y(a).
127        let mut jac = vec![vec![0.0; n]; n];
128        for k in 0..n {
129            let step = 1e-7 * s[k].abs().max(1.0);
130            let mut sk = s.clone();
131            sk[k] += step;
132            let (gk, _) = residual(&sk)?;
133            for i in 0..n {
134                jac[i][k] = (gk[i] - g[i]) / step;
135            }
136        }
137        let delta = Lu::new(jac)?.solve(&g);
138        // Damped update: halve until the residual decreases.
139        let norm = inf_norm(&g);
140        let mut lambda = 1.0;
141        loop {
142            let trial: Vec<f64> = s.iter().zip(&delta).map(|(v, d)| v - lambda * d).collect();
143            if let Ok((gt, tt)) = residual(&trial)
144                && (inf_norm(&gt) < norm || lambda < 1e-3)
145            {
146                s = trial;
147                g = gt;
148                trajectory = tt;
149                break;
150            }
151            lambda *= 0.5;
152            if lambda < 1e-4 {
153                return Err(ErrorsJSL::RuntimeError("Shooting failed: the boundary residual could not be reduced."));
154            }
155        }
156        converged = inf_norm(&g) <= options.tolerance;
157        // ANCHOR_END: shooting_newton
158    }
159    let (x, y) = trajectory;
160    let derivative = x.iter().zip(&y).map(|(&xi, yi)| f(xi, yi)).collect();
161    Ok(BvpSolution { x, y, derivative, converged, max_residual: inf_norm(&g) })
162}
163
164// ANCHOR: hermite_simpson
165/// Hermite-Simpson collocation residual `y₁ − y₀ − h/6 (f₀ + 4 f_m + f₁)` of one interval.
166fn interval_residual<F: Fn(f64, &[f64]) -> Vec<f64>>(f: &F, x0: f64, h: f64, y0: &[f64], f0: &[f64], y1: &[f64], f1: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
167    let n = y0.len();
168    let ym: Vec<f64> = (0..n).map(|k| 0.5 * (y0[k] + y1[k]) + h / 8.0 * (f0[k] - f1[k])).collect();
169    let fm = eval(f, x0 + 0.5 * h, &ym)?;
170    Ok((0..n).map(|k| y1[k] - y0[k] - h / 6.0 * (f0[k] + 4.0 * fm[k] + f1[k])).collect())
171}
172// ANCHOR_END: hermite_simpson
173
174/// Solves the collocation equations on a fixed mesh by damped Newton, from the guess `y`.
175fn newton_on_mesh<F, G>(f: &F, boundary: &G, x: &[f64], y: &mut [Vec<f64>], options: &BvpOptions) -> Result<Vec<Vec<f64>>, ErrorsJSL>
176where
177    F: Fn(f64, &[f64]) -> Vec<f64>,
178    G: Fn(&[f64], &[f64]) -> Vec<f64>,
179{
180    let (m, n) = (x.len() - 1, y[0].len());
181    let size = (m + 1) * n;
182    let residuals = |y: &[Vec<f64>], fy: &[Vec<f64>]| -> Result<Vec<f64>, ErrorsJSL> {
183        let mut r = Vec::with_capacity(size);
184        for i in 0..m {
185            r.extend(interval_residual(f, x[i], x[i + 1] - x[i], &y[i], &fy[i], &y[i + 1], &fy[i + 1])?);
186        }
187        let bc = boundary(&y[0], &y[m]);
188        if bc.len() != n {
189            return Err(ErrorsJSL::IncompatibleArraySizes((bc.len(), n)));
190        }
191        r.extend(bc);
192        Ok(r)
193    };
194    let derivatives = |y: &[Vec<f64>]| -> Result<Vec<Vec<f64>>, ErrorsJSL> { x.iter().zip(y).map(|(&xi, yi)| eval(f, xi, yi)).collect() };
195    let mut fy = derivatives(y)?;
196    let mut r = residuals(y, &fy)?;
197    for _ in 0..options.max_newton_iterations {
198        // Jacobian: perturbing node j touches intervals j−1 and j and, at the ends, the boundary rows.
199        let mut jac = vec![vec![0.0; size]; size];
200        for j in 0..=m {
201            for k in 0..n {
202                let step = 1e-7 * y[j][k].abs().max(1.0);
203                let mut yj = y[j].clone();
204                yj[k] += step;
205                let fj = eval(f, x[j], &yj)?;
206                let column = j * n + k;
207                let mut write = |row0: usize, values: Vec<f64>, base: &[f64]| {
208                    for (i, v) in values.into_iter().enumerate() {
209                        jac[row0 + i][column] = (v - base[row0 + i]) / step;
210                    }
211                };
212                if j > 0 {
213                    let v = interval_residual(f, x[j - 1], x[j] - x[j - 1], &y[j - 1], &fy[j - 1], &yj, &fj)?;
214                    write((j - 1) * n, v, &r);
215                }
216                if j < m {
217                    let v = interval_residual(f, x[j], x[j + 1] - x[j], &yj, &fj, &y[j + 1], &fy[j + 1])?;
218                    write(j * n, v, &r);
219                }
220                if j == 0 {
221                    write(m * n, boundary(&yj, &y[m]), &r);
222                }
223                if j == m {
224                    write(m * n, boundary(&y[0], &yj), &r);
225                }
226            }
227        }
228        let delta = Lu::new(jac)?.solve(&r);
229        let norm = inf_norm(&r);
230        let mut lambda = 1.0;
231        let mut accepted = false;
232        while lambda > 1e-4 {
233            let trial: Vec<Vec<f64>> = (0..=m).map(|j| (0..n).map(|k| y[j][k] - lambda * delta[j * n + k]).collect()).collect();
234            if let Ok(ft) = derivatives(&trial)
235                && let Ok(rt) = residuals(&trial, &ft)
236                && inf_norm(&rt) < norm.max(1e-300)
237            {
238                y.clone_from_slice(&trial);
239                fy = ft;
240                r = rt;
241                accepted = true;
242                break;
243            }
244            lambda *= 0.5;
245        }
246        let step_size = (0..size).map(|i| (lambda * delta[i]).abs() / (1.0 + y[i / n][i % n].abs())).fold(0.0, f64::max);
247        if !accepted || step_size < 1e-11 || inf_norm(&r) < 1e-13 {
248            break;
249        }
250    }
251    Ok(fy)
252}
253
254/// Solves the boundary value problem by Hermite-Simpson collocation, starting from the mesh
255/// `x` (strictly monotonic, at least two points) and the guess `y` at each mesh point. Intervals
256/// whose relative defect exceeds the tolerance are split until it is met everywhere or the mesh
257/// reaches `max_nodes` (then `converged` is false).
258pub fn solve_bvp_collocation<F, G>(f: F, boundary: G, x: Vec<f64>, y: Vec<Vec<f64>>, options: BvpOptions) -> Result<BvpSolution, ErrorsJSL>
259where
260    F: Fn(f64, &[f64]) -> Vec<f64>,
261    G: Fn(&[f64], &[f64]) -> Vec<f64>,
262{
263    if x.len() < 2 || x.len() != y.len() || y[0].is_empty() || y.iter().any(|v| v.len() != y[0].len()) {
264        return Err(ErrorsJSL::InvalidInputRange("The mesh needs at least two points and a guess of consistent size at each."));
265    }
266    let increasing = x[1] > x[0];
267    if x.windows(2).any(|w| if increasing { w[1] <= w[0] } else { w[1] >= w[0] }) {
268        return Err(ErrorsJSL::InvalidInputRange("The mesh must be strictly monotonic."));
269    }
270    let (mut x, mut y) = (x, y);
271    loop {
272        let fy = newton_on_mesh(&f, &boundary, &x, &mut y, &options)?;
273        // Relative defect of the cubic interpolant at the quarter points of each interval (it
274        // vanishes at the nodes and midpoints by construction).
275        let mut defects = Vec::with_capacity(x.len() - 1);
276        for i in 0..x.len() - 1 {
277            let h = x[i + 1] - x[i];
278            let mut worst: f64 = 0.0;
279            for t in [0.25, 0.75] {
280                let (s, ds) = hermite(t, h, &y[i], &fy[i], &y[i + 1], &fy[i + 1]);
281                let fs = eval(&f, x[i] + t * h, &s)?;
282                worst = worst.max((0..s.len()).map(|k| (ds[k] - fs[k]).abs() / (1.0 + fs[k].abs())).fold(0.0, f64::max));
283            }
284            defects.push(if worst.is_finite() { worst } else { f64::INFINITY });
285        }
286        let max_residual = defects.iter().copied().fold(0.0, f64::max);
287        let to_split = defects.iter().filter(|&&d| d > options.tolerance).count();
288        if to_split == 0 || x.len() + to_split > options.max_nodes {
289            let converged = to_split == 0 && boundary(&y[0], &y[y.len() - 1]).iter().all(|v| v.abs() < 1e-6_f64.max(options.tolerance));
290            return Ok(BvpSolution { x, y, derivative: fy, converged, max_residual });
291        }
292        // Split each failing interval in two (three where the defect is very large), seeding the
293        // new nodes from the interpolant.
294        let mut new_x = vec![x[0]];
295        let mut new_y = vec![y[0].clone()];
296        for i in 0..x.len() - 1 {
297            let h = x[i + 1] - x[i];
298            let pieces = if defects[i] > 100.0 * options.tolerance { 3 } else if defects[i] > options.tolerance { 2 } else { 1 };
299            for p in 1..pieces {
300                let t = p as f64 / pieces as f64;
301                new_x.push(x[i] + t * h);
302                new_y.push(hermite(t, h, &y[i], &fy[i], &y[i + 1], &fy[i + 1]).0);
303            }
304            new_x.push(x[i + 1]);
305            new_y.push(y[i + 1].clone());
306        }
307        x = new_x;
308        y = new_y;
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use std::f64::consts::FRAC_PI_2;
316
317    /// The lower Bratu solution u'' + e^u = 0, u(0) = u(1) = 0:
318    /// u = −2 ln(cosh((x − ½)θ/2) / cosh(θ/4)) with θ = √2 cosh(θ/4).
319    fn bratu_exact(x: f64) -> f64 {
320        let mut theta: f64 = 1.0;
321        for _ in 0..100 {
322            theta = 2f64.sqrt() * (theta / 4.0).cosh();
323        }
324        -2.0 * (((x - 0.5) * theta / 2.0).cosh() / (theta / 4.0).cosh()).ln()
325    }
326
327    fn bratu(_: f64, y: &[f64]) -> Vec<f64> {
328        vec![y[1], -y[0].exp()]
329    }
330
331    fn dirichlet_zero(ya: &[f64], yb: &[f64]) -> Vec<f64> {
332        vec![ya[0], yb[0]]
333    }
334
335    #[test]
336    fn shooting_solves_linear_and_bratu_problems() {
337        // u'' = −u, u(0) = 0, u(π/2) = 1 → sin x.
338        let sol = solve_bvp_shooting(|_, y: &[f64]| vec![y[1], -y[0]], |ya: &[f64], yb: &[f64]| vec![ya[0], yb[0] - 1.0], 0.0, FRAC_PI_2, vec![0.0, 0.3], BvpOptions::default()).unwrap();
339        assert!(sol.converged && (sol.y[0][1] - 1.0).abs() < 1e-8, "{:?}", sol.y[0]);
340        assert!((sol.evaluate(0.7)[0] - 0.7f64.sin()).abs() < 1e-8);
341        let sol = solve_bvp_shooting(bratu, dirichlet_zero, 0.0, 1.0, vec![0.0, 0.1], BvpOptions::default()).unwrap();
342        for &x in &[0.1, 0.5, 0.83] {
343            assert!((sol.evaluate(x)[0] - bratu_exact(x)).abs() < 1e-8, "x={x}");
344        }
345    }
346
347    #[test]
348    fn collocation_is_fourth_order_and_refines_to_tolerance() {
349        let guess = |m: usize| -> (Vec<f64>, Vec<Vec<f64>>) { ((0..=m).map(|i| i as f64 / m as f64).collect(), vec![vec![0.0, 0.0]; m + 1]) };
350        // Fixed meshes (refinement disabled): halving h cuts the error about 16×.
351        let fixed = BvpOptions { tolerance: f64::INFINITY, ..Default::default() };
352        let error = |m: usize| {
353            let (x, y) = guess(m);
354            let sol = solve_bvp_collocation(bratu, dirichlet_zero, x, y, fixed).unwrap();
355            sol.x.iter().zip(&sol.y).map(|(&x, y)| (y[0] - bratu_exact(x)).abs()).fold(0.0, f64::max)
356        };
357        let (e1, e2) = (error(5), error(10));
358        assert!(e1 / e2 > 12.0 && e1 / e2 < 20.0, "{e1} {e2}");
359        // With refinement the defect tolerance is met and the solution is accurate.
360        let (x, y) = guess(4);
361        let sol = solve_bvp_collocation(bratu, dirichlet_zero, x, y, BvpOptions { tolerance: 1e-8, ..Default::default() }).unwrap();
362        assert!(sol.converged && sol.max_residual <= 1e-8);
363        assert!((sol.evaluate(0.37)[0] - bratu_exact(0.37)).abs() < 1e-9);
364    }
365
366    #[test]
367    fn collocation_resolves_a_boundary_layer() {
368        // ε y'' + y' = 0, y(0) = 0, y(1) = 1: y = (1 − e^{−x/ε}) / (1 − e^{−1/ε}), a layer at x = 0.
369        let eps = 1e-3;
370        let f = move |_: f64, y: &[f64]| vec![y[1], -y[1] / eps];
371        let bc = |ya: &[f64], yb: &[f64]| vec![ya[0], yb[0] - 1.0];
372        let x: Vec<f64> = (0..=10).map(|i| i as f64 / 10.0).collect();
373        let y: Vec<Vec<f64>> = x.iter().map(|&t| vec![t, 1.0]).collect();
374        let sol = solve_bvp_collocation(f, bc, x, y, BvpOptions { tolerance: 1e-5, ..Default::default() }).unwrap();
375        assert!(sol.converged, "max residual {}", sol.max_residual);
376        let exact = |x: f64| -(-x / eps).exp_m1() / -(-1.0 / eps).exp_m1();
377        for &x in &[0.0005, 0.002, 0.01, 0.5] {
378            assert!((sol.evaluate(x)[0] - exact(x)).abs() < 1e-4, "x={x}: {} vs {}", sol.evaluate(x)[0], exact(x));
379        }
380        // Nodes cluster inside the layer: the first 1% of the interval holds over a fifth of them.
381        let inside = sol.x.iter().filter(|&&x| x < 0.01).count();
382        assert!(inside * 5 > sol.x.len(), "{inside} of {}", sol.x.len());
383        assert!(solve_bvp_collocation(f, bc, vec![0.0], vec![vec![0.0, 0.0]], BvpOptions::default()).is_err());
384    }
385}