lib_jsl_interpolation/one_d/
bpoly.rs1#![allow(clippy::neg_cmp_op_on_partial_ord)]
14
15use super::ppoly::PPoly;
16use lib_jsl_core::ErrorsJSL;
17use ndarray::Array2;
18
19fn comb(n: usize, k: usize) -> f64 {
20 if k > n {
21 return 0.0;
22 }
23 let k = k.min(n - k);
24 (0..k).fold(1.0, |acc, i| acc * (n - i) as f64 / (i + 1) as f64)
25}
26
27#[derive(Clone, Debug, PartialEq)]
29pub struct BPoly {
30 pub c: Array2<f64>,
32 pub x: Vec<f64>,
34 pub extrapolate: bool,
36}
37
38impl BPoly {
39 pub fn new(c: Array2<f64>, x: Vec<f64>, extrapolate: bool) -> Result<BPoly, ErrorsJSL> {
42 if c.nrows() == 0 || c.ncols() + 1 != x.len() {
43 return Err(ErrorsJSL::InvalidInputRange("need k + 1 ≥ 1 rows and one column per interval"));
44 }
45 if x.windows(2).any(|w| !(w[1] > w[0])) {
46 return Err(ErrorsJSL::InvalidInputRange("breakpoints must be increasing"));
47 }
48 Ok(BPoly { c, x, extrapolate })
49 }
50
51 pub fn degree(&self) -> usize {
53 self.c.nrows() - 1
54 }
55
56 fn interval(&self, v: f64) -> Option<usize> {
57 let m = self.c.ncols();
58 if !self.extrapolate && (v < self.x[0] || v > self.x[m]) || v.is_nan() {
59 return None;
60 }
61 Some(self.x.partition_point(|&b| b <= v).saturating_sub(1).min(m - 1))
62 }
63
64 pub fn evaluate_derivative(&self, v: f64, nu: usize) -> f64 {
69 let Some(j) = self.interval(v) else { return f64::NAN };
70 let k = self.degree();
71 if nu > k {
72 return 0.0;
73 }
74 let h = self.x[j + 1] - self.x[j];
75 let mut c: Vec<f64> = self.c.column(j).to_vec();
76 for d in 0..nu {
77 let deg = (k - d) as f64;
78 c = c.windows(2).map(|w| deg * (w[1] - w[0]) / h).collect();
79 }
80 let s = (v - self.x[j]) / h;
81 for r in (1..c.len()).rev() {
82 for a in 0..r {
83 c[a] = (1.0 - s) * c[a] + s * c[a + 1];
84 }
85 }
86 c[0]
87 }
88
89 pub fn evaluate(&self, v: f64) -> f64 {
91 self.evaluate_derivative(v, 0)
92 }
93 pub fn derivative(&self, nu: usize) -> BPoly {
97 let (k, m) = (self.degree(), self.c.ncols());
98 if nu > k {
99 return BPoly { c: Array2::zeros((1, m)), x: self.x.clone(), extrapolate: self.extrapolate };
100 }
101 let mut c = self.c.clone();
102 for d in 0..nu {
103 let deg = (k - d) as f64;
104 c = Array2::from_shape_fn((c.nrows() - 1, m), |(a, j)| deg * (c[(a + 1, j)] - c[(a, j)]) / (self.x[j + 1] - self.x[j]));
105 }
106 BPoly { c, x: self.x.clone(), extrapolate: self.extrapolate }
107 }
108
109 pub fn antiderivative(&self, nu: usize) -> BPoly {
115 let mut out = self.clone();
116 for _ in 0..nu {
117 let (k1, m) = (out.c.nrows(), out.c.ncols());
118 let mut c = Array2::zeros((k1 + 1, m));
119 for j in 0..m {
120 let h = out.x[j + 1] - out.x[j];
121 let mut acc = 0.0;
122 for a in 0..k1 {
123 acc += out.c[(a, j)];
124 c[(a + 1, j)] = acc / k1 as f64 * h;
125 }
126 }
127 let last: Vec<f64> = (0..m).map(|j| c[(k1, j)]).collect();
129 let mut carry = 0.0;
130 for j in 1..m {
131 carry += last[j - 1];
132 for a in 0..=k1 {
133 c[(a, j)] += carry;
134 }
135 }
136 out = BPoly { c, x: out.x, extrapolate: out.extrapolate };
137 }
138 out
139 }
140 pub fn integrate(&self, a: f64, b: f64) -> f64 {
144 let anti = BPoly { extrapolate: true, ..self.antiderivative(1) };
145 let (lo, hi) = (self.x[0], self.x[self.x.len() - 1]);
146 let (a, b) = if self.extrapolate { (a, b) } else { (a.clamp(lo, hi), b.clamp(lo, hi)) };
147 anti.evaluate(b) - anti.evaluate(a)
148 }
149
150 pub fn raise_degree(&self, d: usize) -> BPoly {
152 BPoly { c: raise_degree(&self.c, d), x: self.x.clone(), extrapolate: self.extrapolate }
153 }
154
155 pub fn from_power_basis(pp: &PPoly) -> BPoly {
158 let (k1, m) = (pp.c.nrows(), pp.c.ncols());
159 let k = k1 - 1;
160 let mut c = Array2::zeros((k1, m));
161 for j in 0..m {
162 let h = pp.x[j + 1] - pp.x[j];
163 for a in 0..k1 {
164 let factor = pp.c[(a, j)] / comb(k, k - a) * h.powi((k - a) as i32);
165 for q in k - a..k1 {
166 c[(q, j)] += factor * comb(q, k - a);
167 }
168 }
169 }
170 BPoly { c, x: pp.x.clone(), extrapolate: pp.extrapolate }
171 }
172
173 pub fn to_power_basis(&self) -> PPoly {
176 let (k1, m) = (self.c.nrows(), self.c.ncols());
177 let k = k1 - 1;
178 let mut c = Array2::zeros((k1, m));
179 for j in 0..m {
180 let h = self.x[j + 1] - self.x[j];
181 for a in 0..k1 {
182 let factor = if a.is_multiple_of(2) { 1.0 } else { -1.0 } * comb(k, a) * self.c[(a, j)];
183 for s in a..k1 {
184 let val = comb(k - a, s - a) * if s.is_multiple_of(2) { 1.0 } else { -1.0 };
185 c[(k - s, j)] += factor * val / h.powi(s as i32);
186 }
187 }
188 }
189 PPoly { c, x: self.x.clone(), extrapolate: self.extrapolate }
190 }
191
192 pub fn from_derivatives(xi: &[f64], yi: &[Vec<f64>], orders: Option<&[usize]>) -> Result<BPoly, ErrorsJSL> {
201 let m = xi.len().saturating_sub(1);
202 if m == 0 || yi.len() != xi.len() || yi.iter().any(|y| y.is_empty()) {
203 return Err(ErrorsJSL::InvalidInputRange("from_derivatives: need two or more breakpoints, each with at least a value"));
204 }
205 if xi.windows(2).any(|w| !(w[1] > w[0])) {
206 return Err(ErrorsJSL::InvalidInputRange("from_derivatives: breakpoints must be increasing"));
207 }
208 if let Some(o) = orders
209 && o.len() != 1
210 && o.len() != m
211 {
212 return Err(ErrorsJSL::IncompatibleArraySizes((o.len(), m)));
213 }
214 if orders.is_some_and(|o| o.contains(&0)) {
215 return Err(ErrorsJSL::InvalidInputRange("from_derivatives: orders must be positive"));
216 }
217 let mut pieces = Vec::with_capacity(m);
218 for i in 0..m {
219 let (la, lb) = (yi[i].len(), yi[i + 1].len());
220 let (n1, n2) = match orders {
221 None => (la, lb),
222 Some(o) => {
223 let n = o[if o.len() == 1 { 0 } else { i }] + 1;
224 let n1 = (n / 2).min(la);
225 let n2 = (n - n1).min(lb);
226 let n1 = (n - n2).min(la);
227 if n1 + n2 != n {
228 return Err(ErrorsJSL::InvalidInputRange("from_derivatives: not enough derivatives for the requested order"));
229 }
230 (n1, n2)
231 }
232 };
233 pieces.push(construct_from_derivatives(xi[i], xi[i + 1], &yi[i][..n1], &yi[i + 1][..n2]));
234 }
235 let given = (0..m).map(|i| yi[i].len() + yi[i + 1].len()).max().unwrap_or(1);
238 let k1 = given.max(orders.and_then(|o| o.iter().copied().max()).unwrap_or(0));
239 let mut c = Array2::zeros((k1, m));
240 for (j, p) in pieces.iter().enumerate() {
241 let col = Array2::from_shape_vec((p.len(), 1), p.clone()).expect("shape");
242 let raised = raise_degree(&col, k1 - p.len());
243 for a in 0..k1 {
244 c[(a, j)] = raised[(a, 0)];
245 }
246 }
247 Ok(BPoly { c, x: xi.to_vec(), extrapolate: true })
248 }
249 }
251
252fn construct_from_derivatives(xa: f64, xb: f64, ya: &[f64], yb: &[f64]) -> Vec<f64> {
255 let (na, nb) = (ya.len(), yb.len());
256 let n = na + nb;
257 let h = xb - xa;
258 let poch = |a: usize, q: usize| (0..q).map(|r| (a + r) as f64).product::<f64>();
259 let sign = |p: usize| if p.is_multiple_of(2) { 1.0 } else { -1.0 };
260 let mut c = vec![0.0; n];
261 for q in 0..na {
262 c[q] = ya[q] / poch(n - q, q) * h.powi(q as i32);
263 for j in 0..q {
264 c[q] -= sign(j + q) * comb(q, j) * c[j];
265 }
266 }
267 for q in 0..nb {
268 let idx = n - q - 1;
269 c[idx] = yb[q] / poch(n - q, q) * sign(q) * h.powi(q as i32);
270 for j in 0..q {
271 c[idx] -= sign(j + 1) * comb(q, j + 1) * c[n - q + j];
272 }
273 }
274 c
275}
276
277fn raise_degree(c: &Array2<f64>, d: usize) -> Array2<f64> {
278 if d == 0 {
279 return c.clone();
280 }
281 let (k1, m) = (c.nrows(), c.ncols());
282 let k = k1 - 1;
283 let mut out = Array2::zeros((k1 + d, m));
284 for a in 0..k1 {
285 for j in 0..m {
286 let f = c[(a, j)] * comb(k, a);
287 for q in 0..=d {
288 out[(a + q, j)] += f * comb(d, q) / comb(k + d, a + q);
289 }
290 }
291 }
292 out
293}
294
295#[cfg(test)]
296mod tests {
297 use super::*;
298
299 #[test]
300 fn hermite_data_round_trip_and_calculus() {
301 let f = |x: f64| x * x * x - 2.0 * x;
303 let fp = |x: f64| 3.0 * x * x - 2.0;
304 let xi = [0.0, 1.0, 3.0];
305 let yi: Vec<Vec<f64>> = xi.iter().map(|&x| vec![f(x), fp(x)]).collect();
306 let bp = BPoly::from_derivatives(&xi, &yi, None).unwrap();
307 assert_eq!(bp.degree(), 3);
308 for v in [0.0, 0.4, 1.0, 2.2, 3.0] {
309 assert!((bp.evaluate(v) - f(v)).abs() < 1e-13, "{v}");
310 assert!((bp.evaluate_derivative(v, 1) - fp(v)).abs() < 1e-12);
311 assert!((bp.evaluate_derivative(v, 2) - 6.0 * v).abs() < 1e-11);
312 }
313 let exact = |x: f64| x.powi(4) / 4.0 - x * x;
314 assert!((bp.integrate(0.3, 2.7) - (exact(2.7) - exact(0.3))).abs() < 1e-12);
315 let anti = bp.antiderivative(2);
316 assert!((anti.evaluate(2.0) - (2f64.powi(5) / 20.0 - 2f64.powi(3) / 3.0)).abs() < 1e-12);
317 let pp = bp.to_power_basis();
319 let back = BPoly::from_power_basis(&pp);
320 assert!(back.c.iter().zip(bp.c.iter()).all(|(a, b)| (a - b).abs() < 1e-12));
321 assert!((pp.evaluate(2.2) - f(2.2)).abs() < 1e-12);
322 let xi4 = [0.0, 0.5, 1.0, 2.0, 3.0];
324 let yi4: Vec<Vec<f64>> = xi4.iter().map(|&x| vec![f(x), fp(x)]).collect();
325 let b4 = BPoly::from_derivatives(&xi4, &yi4, None).unwrap();
326 assert!((b4.integrate(0.0, 3.0) - exact(3.0)).abs() < 1e-12);
327 assert!((b4.antiderivative(2).evaluate(2.5) - (2.5f64.powi(5) / 20.0 - 2.5f64.powi(3) / 3.0)).abs() < 1e-12);
328 let r = bp.raise_degree(2);
330 assert!((r.evaluate(1.7) - f(1.7)).abs() < 1e-13);
331 }
332}