Skip to main content

lib_jsl_interpolation/one_d/
ppoly.rs

1//! Piecewise polynomials in the power basis, following SciPy's `PPoly`: evaluation, derivatives,
2//! antiderivatives, definite integrals and real roots, with constructors from cubic Hermite data
3//! (`CubicHermiteSpline`) and from B-splines (`PPoly.from_spline`).
4//!
5//! On interval `j`, `[x_j, x_{j+1})`, the polynomial is `Σ_i c[i][j] (x − x_j)^{k−i}`: row 0
6//! holds the highest power, as in SciPy.
7//!
8//! See the book entry [Piecewise polynomials, Hermite data and scattered interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/piecewise-scattered.html).
9
10use super::b_spline::BSpline;
11use lib_jsl_core::ErrorsJSL;
12use lib_jsl_linalg::EigVals;
13use ndarray::Array2;
14
15/// A piecewise polynomial of degree `k` on `m` intervals.
16#[derive(Clone, Debug, PartialEq)]
17pub struct PPoly {
18    /// Coefficients, shape `(k + 1, m)`; row 0 multiplies the highest power.
19    pub c: Array2<f64>,
20    /// The `m + 1` breakpoints, increasing.
21    pub x: Vec<f64>,
22    /// Evaluate outside `[x₀, x_m]` by extending the end pieces (otherwise `NaN`).
23    pub extrapolate: bool,
24}
25
26fn factorial_ratio(n: usize, nu: usize) -> f64 {
27    // n (n − 1) … (n − nu + 1)
28    (0..nu).map(|i| (n - i) as f64).product()
29}
30
31impl PPoly {
32    /// A piecewise polynomial from coefficients (shape `(k + 1, m)`) and `m + 1` breakpoints.
33    pub fn new(c: Array2<f64>, x: Vec<f64>, extrapolate: bool) -> Result<PPoly, ErrorsJSL> {
34        if c.nrows() == 0 || c.ncols() + 1 != x.len() {
35            return Err(ErrorsJSL::InvalidInputRange("need k + 1 ≥ 1 rows and one column per interval"));
36        }
37        if x.windows(2).any(|w| w[1] < w[0] || w[1].is_nan()) {
38            return Err(ErrorsJSL::InvalidInputRange("breakpoints must be non-decreasing"));
39        }
40        Ok(PPoly { c, x, extrapolate })
41    }
42
43    /// The degree `k`.
44    pub fn degree(&self) -> usize {
45        self.c.nrows() - 1
46    }
47
48    /// The interval containing `v`: `j` with `x_j ≤ v < x_{j+1}`, the last interval at the right
49    /// end, and the end intervals outside (when extrapolating).
50    fn interval(&self, v: f64) -> Option<usize> {
51        let m = self.c.ncols();
52        if !self.extrapolate && (v < self.x[0] || v > self.x[m]) || v.is_nan() {
53            return None;
54        }
55        Some(self.x.partition_point(|&b| b <= v).saturating_sub(1).min(m - 1))
56    }
57
58    /// The `nu`-th derivative of piece `j` at offset `s = v − x_j`, by Horner's rule.
59    fn eval_piece(&self, j: usize, s: f64, nu: usize) -> f64 {
60        let k = self.degree();
61        if nu > k {
62            return 0.0;
63        }
64        let mut acc = 0.0;
65        for i in 0..=k - nu {
66            acc = acc * s + self.c[(i, j)] * factorial_ratio(k - i, nu);
67        }
68        acc
69    }
70
71    // ANCHOR: evaluate
72    /// The value at `v`.
73    pub fn evaluate(&self, v: f64) -> f64 {
74        self.evaluate_derivative(v, 0)
75    }
76
77    /// The `nu`-th derivative at `v`.
78    pub fn evaluate_derivative(&self, v: f64, nu: usize) -> f64 {
79        match self.interval(v) {
80            Some(j) => self.eval_piece(j, v - self.x[j], nu),
81            None => f64::NAN,
82        }
83    }
84    // ANCHOR_END: evaluate
85
86    /// The derivative of order `nu` as a piecewise polynomial of degree `k − nu` (degree 0 and
87    /// value 0 if `nu > k`).
88    pub fn derivative(&self, nu: usize) -> PPoly {
89        let k = self.degree();
90        let m = self.c.ncols();
91        if nu > k {
92            return PPoly { c: Array2::zeros((1, m)), x: self.x.clone(), extrapolate: self.extrapolate };
93        }
94        let c = Array2::from_shape_fn((k + 1 - nu, m), |(i, j)| self.c[(i, j)] * factorial_ratio(k - i, nu));
95        PPoly { c, x: self.x.clone(), extrapolate: self.extrapolate }
96    }
97
98    // ANCHOR: antiderivative
99    /// The antiderivative of order `nu`, zero at `x₀` and continuous with its first `nu − 1`
100    /// derivatives (SciPy's `antiderivative`): the coefficients are divided by rising factorials,
101    /// and the new low-order coefficients of each piece are set from the previous piece's values
102    /// at the shared breakpoint.
103    pub fn antiderivative(&self, nu: usize) -> PPoly {
104        let k = self.degree();
105        let m = self.c.ncols();
106        let rows = k + 1 + nu;
107        let mut c = Array2::zeros((rows, m));
108        for i in 0..=k {
109            let factor: f64 = (1..=nu).map(|r| (k - i + r) as f64).product();
110            for j in 0..m {
111                c[(i, j)] = self.c[(i, j)] / factor;
112            }
113        }
114        let mut out = PPoly { c, x: self.x.clone(), extrapolate: self.extrapolate };
115        for j in 1..m {
116            let h = out.x[j] - out.x[j - 1];
117            for dx in (0..nu).rev() {
118                let value = out.eval_piece(j - 1, h, dx) / (1..=dx).map(|r| r as f64).product::<f64>();
119                out.c[(rows - 1 - dx, j)] = value;
120            }
121        }
122        out
123    }
124    // ANCHOR_END: antiderivative
125
126    /// `∫_a^b p(x) dx` (with extrapolation beyond the breakpoints if enabled).
127    pub fn integrate(&self, a: f64, b: f64) -> f64 {
128        let anti = PPoly { extrapolate: true, ..self.antiderivative(1) };
129        if !self.extrapolate {
130            let (lo, hi) = (self.x[0], self.x[self.x.len() - 1]);
131            let (ca, cb) = (a.clamp(lo, hi), b.clamp(lo, hi));
132            return anti.evaluate(cb) - anti.evaluate(ca);
133        }
134        anti.evaluate(b) - anti.evaluate(a)
135    }
136
137    // ANCHOR: roots
138    /// The real `x` with `p(x) = y` (SciPy's `solve`), increasing. Each piece's roots are the
139    /// eigenvalues of the companion matrix of its polynomial, kept when real (to a small
140    /// tolerance) and inside the piece, then polished by Newton steps. With `discontinuity`, a
141    /// breakpoint where the polynomial jumps across `y` is reported too. Pieces that equal `y`
142    /// identically are skipped.
143    pub fn solve(&self, y: f64, discontinuity: bool) -> Vec<f64> {
144        let k = self.degree();
145        let m = self.c.ncols();
146        let mut roots = Vec::new();
147        for j in 0..m {
148            let (lo, hi) = (self.x[j], self.x[j + 1]);
149            if hi == lo {
150                continue;
151            }
152            let h = hi - lo;
153            let (left, right) = if self.extrapolate { (if j == 0 { f64::NEG_INFINITY } else { 0.0 }, if j == m - 1 { f64::INFINITY } else { h }) } else { (0.0, h) };
154            let mut coef: Vec<f64> = (0..=k).map(|i| self.c[(i, j)]).collect();
155            coef[k] -= y;
156            // Drop leading zeros.
157            let lead = coef.iter().position(|&v| v != 0.0);
158            let Some(lead) = lead else { continue };
159            let p = &coef[lead..];
160            let deg = p.len() - 1;
161            if deg == 0 {
162                continue;
163            }
164            let candidates: Vec<f64> = if deg == 1 {
165                vec![-p[1] / p[0]]
166            } else {
167                let comp = Array2::from_shape_fn((deg, deg), |(r, col)| if r == 0 { -p[col + 1] / p[0] } else if r == col + 1 { 1.0 } else { 0.0 });
168                match comp.eigvals() {
169                    Ok(ev) => {
170                        let scale = ev.iter().fold(1.0f64, |a, z| a.max(z.norm()));
171                        ev.iter().filter(|z| z.im.abs() <= 1e-7 * scale).map(|z| z.re).collect()
172                    }
173                    Err(_) => Vec::new(),
174                }
175            };
176            let horner = |s: f64| p.iter().fold(0.0, |a, &c| a * s + c);
177            let dhorner = |s: f64| p.iter().take(deg).enumerate().fold(0.0, |a, (i, &c)| a * s + c * (deg - i) as f64);
178            for mut s in candidates {
179                for _ in 0..3 {
180                    let d = dhorner(s);
181                    if d == 0.0 {
182                        break;
183                    }
184                    let step = horner(s) / d;
185                    s -= step;
186                    if step.abs() <= 4.0 * f64::EPSILON * s.abs().max(h) {
187                        break;
188                    }
189                }
190                let tol = 1e-12 * h;
191                if s >= left - tol && s < right + if j == m - 1 { tol } else { -tol.min(0.0) } {
192                    let s = s.clamp(left.max(-f64::MAX), right.min(f64::MAX));
193                    if s < h || j == m - 1 {
194                        roots.push(lo + s);
195                    }
196                }
197            }
198            if discontinuity && j > 0 {
199                let before = self.eval_piece(j - 1, lo - self.x[j - 1], 0) - y;
200                let after = self.c[(k, j)] - y;
201                if before * after < 0.0 {
202                    roots.push(lo);
203                }
204            }
205        }
206        roots.sort_by(f64::total_cmp);
207        roots.dedup_by(|a, b| (*a - *b).abs() <= 1e-12 * (1.0 + b.abs()));
208        roots
209    }
210    // ANCHOR_END: roots
211
212    /// The real roots, `solve(0, true)` (SciPy's `roots`).
213    pub fn roots(&self) -> Vec<f64> {
214        self.solve(0.0, true)
215    }
216
217    // ANCHOR: cubic_hermite
218    /// The cubic Hermite interpolant with values `y` and slopes `dydx` at the strictly increasing
219    /// `x` (SciPy's `CubicHermiteSpline`). With `h` the interval length and `s` the secant slope,
220    /// the piece is `y₀ + d₀ t + (3s − 2d₀ − d₁)/h · t² + (d₀ + d₁ − 2s)/h² · t³`.
221    pub fn cubic_hermite(x: &[f64], y: &[f64], dydx: &[f64]) -> Result<PPoly, ErrorsJSL> {
222        let n = x.len();
223        if n < 2 || y.len() != n || dydx.len() != n {
224            return Err(ErrorsJSL::InvalidInputRange("need at least two points and equal lengths"));
225        }
226        if x.windows(2).any(|w| w[1] <= w[0] || w[1].is_nan()) {
227            return Err(ErrorsJSL::InvalidInputRange("x must be strictly increasing"));
228        }
229        let mut c = Array2::zeros((4, n - 1));
230        for j in 0..n - 1 {
231            let h = x[j + 1] - x[j];
232            let s = (y[j + 1] - y[j]) / h;
233            let (d0, d1) = (dydx[j], dydx[j + 1]);
234            c[(0, j)] = (d0 + d1 - 2.0 * s) / (h * h);
235            c[(1, j)] = (3.0 * s - 2.0 * d0 - d1) / h;
236            c[(2, j)] = d0;
237            c[(3, j)] = y[j];
238        }
239        Ok(PPoly { c, x: x.to_vec(), extrapolate: true })
240    }
241    // ANCHOR_END: cubic_hermite
242
243    /// The same function as a B-spline, as pieces between its distinct knots in the base interval
244    /// `[t_k, t_n]` (SciPy's `PPoly.from_spline`, which also keeps the empty intervals between
245    /// repeated knots): each piece's coefficients are the spline's Taylor coefficients
246    /// `s⁽ⁱ⁾(x_j)/i!` at the left end.
247    pub fn from_spline(spline: &BSpline) -> PPoly {
248        let k = spline.k;
249        let n = spline.c.len();
250        let mut x: Vec<f64> = spline.t[k..=n].to_vec();
251        x.dedup();
252        let m = x.len() - 1;
253        let mut c = Array2::zeros((k + 1, m));
254        let mut fact = 1.0;
255        for d in 0..=k {
256            if d > 0 {
257                fact *= d as f64;
258            }
259            for j in 0..m {
260                c[(k - d, j)] = spline.evaluate_derivative(x[j], d) / fact;
261            }
262        }
263        PPoly { c, x, extrapolate: true }
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::one_d::b_spline::{BoundaryCondition, make_interp_spline};
271
272    #[test]
273    fn hermite_reproduces_a_cubic() {
274        let f = |v: f64| v * v * v - 2.0 * v + 1.0;
275        let df = |v: f64| 3.0 * v * v - 2.0;
276        let x = [-1.0, 0.0, 0.7, 2.0];
277        let y = x.map(f);
278        let d = x.map(df);
279        let p = PPoly::cubic_hermite(&x, &y, &d).unwrap();
280        for v in [-1.5, -0.3, 0.5, 1.9, 2.5] {
281            assert!((p.evaluate(v) - f(v)).abs() < 1e-12);
282            assert!((p.evaluate_derivative(v, 1) - df(v)).abs() < 1e-11);
283            assert!((p.evaluate_derivative(v, 2) - 6.0 * v).abs() < 1e-10);
284        }
285        // ∫_{-1}^{2} f = [x⁴/4 − x² + x] = (4 − 4 + 2) − (1/4 − 1 − 1) = 3.75
286        assert!((p.integrate(-1.0, 2.0) - 3.75).abs() < 1e-12);
287        let a = p.antiderivative(2);
288        assert!((a.evaluate_derivative(1.3, 2) - f(1.3)).abs() < 1e-11);
289        // f has three real roots.
290        let r = p.roots();
291        assert_eq!(r.len(), 3, "{r:?}");
292        for v in r {
293            assert!(f(v).abs() < 1e-12);
294        }
295    }
296
297    #[test]
298    fn from_spline_matches_the_spline() {
299        let x: Vec<f64> = (0..9).map(|i| i as f64 * 0.5).collect();
300        let y: Vec<f64> = x.iter().map(|v| (v * 1.3).sin()).collect();
301        let s = make_interp_spline(&x, &y, 3, &BoundaryCondition::NotAKnot).unwrap();
302        let p = PPoly::from_spline(&s);
303        for i in 0..40 {
304            let v = -0.2 + i as f64 * 0.11;
305            assert!((p.evaluate(v) - s.evaluate(v)).abs() < 1e-12);
306            assert!((p.evaluate_derivative(v, 1) - s.evaluate_derivative(v, 1)).abs() < 1e-11);
307        }
308        assert!((p.integrate(0.3, 3.7) - s.integrate(0.3, 3.7)).abs() < 1e-12);
309        let r = p.roots();
310        // sin(1.3 x) = 0 at x = π/1.3 ≈ 2.4166 (and x = 0).
311        assert!(r.iter().any(|v| (v - std::f64::consts::PI / 1.3).abs() < 1e-3), "{r:?}");
312    }
313}