lib_jsl_interpolation/one_d/
ppoly.rs1use super::b_spline::BSpline;
11use lib_jsl_core::ErrorsJSL;
12use lib_jsl_linalg::EigVals;
13use ndarray::Array2;
14
15#[derive(Clone, Debug, PartialEq)]
17pub struct PPoly {
18 pub c: Array2<f64>,
20 pub x: Vec<f64>,
22 pub extrapolate: bool,
24}
25
26fn factorial_ratio(n: usize, nu: usize) -> f64 {
27 (0..nu).map(|i| (n - i) as f64).product()
29}
30
31impl PPoly {
32 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 pub fn degree(&self) -> usize {
45 self.c.nrows() - 1
46 }
47
48 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 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 pub fn evaluate(&self, v: f64) -> f64 {
74 self.evaluate_derivative(v, 0)
75 }
76
77 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 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 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 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 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 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 pub fn roots(&self) -> Vec<f64> {
214 self.solve(0.0, true)
215 }
216
217 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 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 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 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 assert!(r.iter().any(|v| (v - std::f64::consts::PI / 1.3).abs() < 1e-3), "{r:?}");
312 }
313}