Skip to main content

lib_jsl_interpolation/one_d/
b_spline.rs

1//! B-splines of any degree, following `scipy.interpolate`: the [`BSpline`] type (evaluation,
2//! derivatives, antiderivatives and integrals), interpolating splines with a choice of end
3//! conditions ([`make_interp_spline`]), least-squares splines on given knots
4//! ([`make_lsq_spline`]) and parametric interpolating curves ([`make_interp_curve`]).
5//!
6//! A spline of degree `k` with knots `t₀ ≤ t₁ ≤ … ≤ t_{n+k}` is a sum `s(x) = Σ cⱼ Bⱼ,ₖ(x)` of the
7//! B-spline basis functions, each a piecewise polynomial of degree `k` that is non-zero only on
8//! `[tⱼ, tⱼ₊ₖ₊₁)`. They are evaluated by the Cox-de Boor recurrence, and an interpolating spline
9//! is found by solving a banded linear system for the coefficients.
10//!
11//! See the book entry [B-splines and smoothing splines](https://jwkunz.github.io/lib_jsl/book/interpolation/b-splines.html).
12
13use lib_jsl_core::ErrorsJSL;
14use lib_jsl_linalg::{LeastSquaresSvd, Solve};
15use ndarray::{Array1, Array2};
16
17/// What a [`BSpline`] returns outside its base interval `[t_k, t_n]`.
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
19pub enum Extrapolate {
20    /// Continue the first or last polynomial piece (SciPy's default, `extrapolate=True`).
21    Yes,
22    /// Return NaN.
23    No,
24    /// Wrap round periodically (`extrapolate='periodic'`).
25    Periodic,
26}
27
28/// A spline `s(x) = Σ cⱼ Bⱼ,ₖ(x)` of degree `k` in the B-spline basis (SciPy's `BSpline`).
29#[derive(Clone, Debug, PartialEq)]
30pub struct BSpline {
31    /// The knots, non-decreasing; `n + k + 1` of them for `n` coefficients.
32    pub t: Vec<f64>,
33    /// The coefficients.
34    pub c: Vec<f64>,
35    /// The degree.
36    pub k: usize,
37    /// Behaviour outside `[t[k], t[n]]`.
38    pub extrapolate: Extrapolate,
39}
40
41// ANCHOR: basis
42/// The `k + 1` B-splines of degree `k` that are non-zero on the knot interval
43/// `t[l] ≤ x < t[l + 1]`, namely `B_{l−k}, …, B_l`, by the Cox-de Boor recurrence (de Boor's
44/// `bsplvb`). Each degree is built from the previous one; the values are non-negative and sum
45/// to one.
46pub fn nonzero_basis(t: &[f64], k: usize, l: usize, x: f64) -> Vec<f64> {
47    let mut b = vec![0.0; k + 1];
48    let (mut left, mut right) = (vec![0.0; k + 1], vec![0.0; k + 1]);
49    b[0] = 1.0;
50    for j in 1..=k {
51        left[j] = x - t[l + 1 - j];
52        right[j] = t[l + j] - x;
53        let mut saved = 0.0;
54        for r in 0..j {
55            let temp = b[r] / (right[r + 1] + left[j - r]);
56            b[r] = saved + right[r + 1] * temp;
57            saved = left[j - r] * temp;
58        }
59        b[j] = saved;
60    }
61    b
62}
63// ANCHOR_END: basis
64
65/// The `nu`-th derivatives of the `k + 1` B-splines that are non-zero on interval `l`, from the
66/// basis of degree `k − nu` and the derivative formula
67/// `B'ⱼ,ₖ = k (Bⱼ,ₖ₋₁ / (tⱼ₊ₖ − tⱼ) − Bⱼ₊₁,ₖ₋₁ / (tⱼ₊ₖ₊₁ − tⱼ₊₁))`.
68pub fn nonzero_basis_derivatives(t: &[f64], k: usize, l: usize, x: f64, nu: usize) -> Vec<f64> {
69    if nu > k {
70        return vec![0.0; k + 1];
71    }
72    let mut v = nonzero_basis(t, k - nu, l, x);
73    for d in k - nu + 1..=k {
74        // v holds degree d − 1 values for indices l − (d − 1) ..= l.
75        let old = |j: isize| -> f64 {
76            let i = j - (l as isize - (d as isize - 1));
77            if i < 0 || i as usize >= v.len() { 0.0 } else { v[i as usize] }
78        };
79        let mut next = vec![0.0; d + 1];
80        for (i, slot) in next.iter_mut().enumerate() {
81            let j = l as isize - d as isize + i as isize;
82            let ju = j as usize;
83            let a = t[ju + d] - t[ju];
84            let b = t[ju + d + 1] - t[ju + 1];
85            let ta = if a > 0.0 { old(j) / a } else { 0.0 };
86            let tb = if b > 0.0 { old(j + 1) / b } else { 0.0 };
87            *slot = d as f64 * (ta - tb);
88        }
89        v = next;
90    }
91    v
92}
93
94impl BSpline {
95    /// A spline from knots, coefficients and degree; extrapolates by default.
96    pub fn new(t: Vec<f64>, c: Vec<f64>, k: usize) -> Result<Self, ErrorsJSL> {
97        if t.len() < 2 * k + 2 {
98            return Err(ErrorsJSL::InvalidInputRange("a spline of degree k needs at least 2k + 2 knots"));
99        }
100        if t.windows(2).any(|w| w[1] < w[0] || !w[0].is_finite()) {
101            return Err(ErrorsJSL::InvalidInputRange("knots must be finite and non-decreasing"));
102        }
103        let n = t.len() - k - 1;
104        if c.len() != n {
105            return Err(ErrorsJSL::IncompatibleArraySizes((c.len(), n)));
106        }
107        if t[k] >= t[n] {
108            return Err(ErrorsJSL::InvalidInputRange("the base interval [t[k], t[n]] is empty"));
109        }
110        Ok(BSpline { t, c, k, extrapolate: Extrapolate::Yes })
111    }
112
113    /// The number of coefficients `n`.
114    pub fn len(&self) -> usize {
115        self.c.len()
116    }
117
118    /// `true` when the spline has no coefficients (never, for a valid spline).
119    pub fn is_empty(&self) -> bool {
120        self.c.is_empty()
121    }
122
123    /// The knot interval `l` with `t[l] ≤ x < t[l + 1]`, `k ≤ l < n`, after applying the
124    /// extrapolation rule; `None` for NaN, or outside the base interval without extrapolation.
125    fn interval(&self, x: f64) -> Option<(usize, f64)> {
126        let (k, n) = (self.k, self.c.len());
127        let (lo, hi) = (self.t[k], self.t[n]);
128        let mut x = x;
129        if x.is_nan() {
130            return None;
131        }
132        match self.extrapolate {
133            Extrapolate::No if x < lo || x > hi => return None,
134            Extrapolate::Periodic => x = lo + (x - lo).rem_euclid(hi - lo),
135            _ => {}
136        }
137        // Binary search on t[k..=n] for the last t[l] ≤ x, clamped to a non-empty interval.
138        let mut l = match self.t[k..=n].partition_point(|&v| v <= x) {
139            0 => k,
140            p => (k + p - 1).min(n - 1),
141        };
142        while l > k && self.t[l] == self.t[l + 1] {
143            l -= 1;
144        }
145        Some((l, x))
146    }
147
148    // ANCHOR: evaluate
149    /// The value `s(x)` (SciPy's `BSpline.__call__`).
150    pub fn evaluate(&self, x: f64) -> f64 {
151        self.evaluate_derivative(x, 0)
152    }
153
154    /// The `nu`-th derivative `s⁽ⁿᵘ⁾(x)`, zero when `nu > k`.
155    pub fn evaluate_derivative(&self, x: f64, nu: usize) -> f64 {
156        let Some((l, x)) = self.interval(x) else { return f64::NAN };
157        let b = if nu == 0 { nonzero_basis(&self.t, self.k, l, x) } else { nonzero_basis_derivatives(&self.t, self.k, l, x, nu) };
158        b.iter().enumerate().map(|(r, v)| self.c[l - self.k + r] * v).sum()
159    }
160    // ANCHOR_END: evaluate
161
162    /// The values at many points.
163    pub fn evaluate_many(&self, x: &[f64]) -> Vec<f64> {
164        x.iter().map(|&v| self.evaluate(v)).collect()
165    }
166
167    /// The derivative of order `nu` as a spline of degree `k − nu` on the knots with `nu` removed
168    /// from each end (SciPy's `BSpline.derivative`):
169    /// `c'ⱼ = k (cⱼ₊₁ − cⱼ) / (tⱼ₊ₖ₊₁ − tⱼ₊₁)`.
170    pub fn derivative(&self, nu: usize) -> Result<BSpline, ErrorsJSL> {
171        if nu > self.k {
172            return Err(ErrorsJSL::InvalidInputRange("the order of the derivative exceeds the degree"));
173        }
174        let mut s = self.clone();
175        for _ in 0..nu {
176            let k = s.k;
177            let n = s.c.len();
178            let c: Vec<f64> = (0..n - 1)
179                .map(|j| {
180                    let d = s.t[j + k + 1] - s.t[j + 1];
181                    if d > 0.0 { k as f64 * (s.c[j + 1] - s.c[j]) / d } else { 0.0 }
182                })
183                .collect();
184            s = BSpline { t: s.t[1..s.t.len() - 1].to_vec(), c, k: k - 1, extrapolate: s.extrapolate };
185        }
186        Ok(s)
187    }
188
189    /// The antiderivative of order `nu`, a spline of degree `k + nu` that vanishes at `t[0]`
190    /// (SciPy's `BSpline.antiderivative`): one end knot is added at each end and
191    /// `Cⱼ₊₁ = Σᵢ≤ⱼ cᵢ (tᵢ₊ₖ₊₁ − tᵢ) / (k + 1)`.
192    pub fn antiderivative(&self, nu: usize) -> BSpline {
193        let mut s = self.clone();
194        for _ in 0..nu {
195            let k = s.k;
196            let mut c = Vec::with_capacity(s.c.len() + 1);
197            c.push(0.0);
198            let mut acc = 0.0;
199            for (j, &cj) in s.c.iter().enumerate() {
200                acc += cj * (s.t[j + k + 1] - s.t[j]) / (k + 1) as f64;
201                c.push(acc);
202            }
203            let mut t = Vec::with_capacity(s.t.len() + 2);
204            t.push(s.t[0]);
205            t.extend_from_slice(&s.t);
206            t.push(*s.t.last().expect("non-empty"));
207            s = BSpline { t, c, k: k + 1, extrapolate: if s.extrapolate == Extrapolate::Periodic { Extrapolate::Yes } else { s.extrapolate } };
208        }
209        s
210    }
211
212    /// `∫ₐᵇ s(x) dx` (SciPy's `BSpline.integrate`). With [`Extrapolate::No`] the integrand is zero
213    /// outside the base interval; with [`Extrapolate::Periodic`] whole periods are counted.
214    pub fn integrate(&self, a: f64, b: f64) -> f64 {
215        let (k, n) = (self.k, self.c.len());
216        let (lo, hi) = (self.t[k], self.t[n]);
217        let anti = self.antiderivative(1);
218        let f = |x: f64| BSpline { extrapolate: Extrapolate::Yes, ..anti.clone() }.evaluate(x);
219        match self.extrapolate {
220            Extrapolate::Yes => f(b) - f(a),
221            Extrapolate::No => f(b.clamp(lo, hi)) - f(a.clamp(lo, hi)),
222            Extrapolate::Periodic => {
223                let period = hi - lo;
224                let whole = f(hi) - f(lo);
225                let reduce = |x: f64| {
226                    let m = ((x - lo) / period).floor();
227                    m * whole + f(lo + (x - lo) - m * period) - f(lo)
228                };
229                reduce(b) - reduce(a)
230            }
231        }
232    }
233
234    /// The B-spline design matrix `Mᵢⱼ = Bⱼ,ₖ(xᵢ)` for points in the base interval (SciPy's
235    /// `BSpline.design_matrix`, as a dense array).
236    pub fn design_matrix(x: &[f64], t: &[f64], k: usize) -> Result<Array2<f64>, ErrorsJSL> {
237        let n = t.len().checked_sub(k + 1).ok_or(ErrorsJSL::InvalidInputRange("too few knots"))?;
238        let probe = BSpline::new(t.to_vec(), vec![0.0; n], k)?;
239        let mut m = Array2::zeros((x.len(), n));
240        for (i, &xi) in x.iter().enumerate() {
241            if xi < t[k] || xi > t[n] {
242                return Err(ErrorsJSL::InvalidInputRange("design-matrix points must lie in [t[k], t[n]]"));
243            }
244            let (l, _) = probe.interval(xi).expect("finite point");
245            for (r, v) in nonzero_basis(t, k, l, xi).into_iter().enumerate() {
246                m[(i, l - k + r)] = v;
247            }
248        }
249        Ok(m)
250    }
251}
252
253/// End conditions for [`make_interp_spline`] (SciPy's `bc_type`).
254#[derive(Clone, Debug, PartialEq)]
255pub enum BoundaryCondition {
256    /// No derivative conditions; the knots are chosen so that the first and last interior
257    /// polynomial pieces join without a break ("not-a-knot", SciPy's default).
258    NotAKnot,
259    /// Zero second derivative at both ends (cubic splines only).
260    Natural,
261    /// Zero first derivative at both ends (cubic splines only).
262    Clamped,
263    /// Matching derivatives of orders `1..k` at both ends; requires `y[0] == y[n−1]`.
264    Periodic,
265    /// Given derivatives `(order, value)` at the left and right ends; there must be `k − 1` in
266    /// total (for example `[(1, a)]` and `[(1, b)]` for a cubic spline with given slopes).
267    Derivatives { left: Vec<(usize, f64)>, right: Vec<(usize, f64)> },
268}
269
270/// Knots for not-a-knot interpolation (SciPy's `_not_a_knot`): for odd `k` the data points
271/// without the first and last `(k − 1)/2` interior ones; for even `k` the midpoints between data
272/// points, likewise thinned; and `k + 1` copies of each end point.
273pub(crate) fn not_a_knot_knots(x: &[f64], k: usize) -> Vec<f64> {
274    let interior: Vec<f64> = if !k.is_multiple_of(2) { x.to_vec() } else { x.windows(2).map(|w| (w[0] + w[1]) / 2.0).collect() };
275    let k2 = if !k.is_multiple_of(2) { k.div_ceil(2) } else { k / 2 };
276    let mut t = vec![x[0]; k + 1];
277    if interior.len() > 2 * k2 {
278        t.extend_from_slice(&interior[k2..interior.len() - k2]);
279    }
280    t.extend(std::iter::repeat_n(x[x.len() - 1], k + 1));
281    t
282}
283
284/// Knots on a circle for periodic interpolation (SciPy's `_periodic_knots`).
285fn periodic_knots(x: &[f64], k: usize) -> Vec<f64> {
286    let n = x.len();
287    let mut xc = x.to_vec();
288    if k.is_multiple_of(2) {
289        let dx: Vec<f64> = x.windows(2).map(|w| w[1] - w[0]).collect();
290        for i in 1..n - 1 {
291            xc[i] -= dx[i - 1] / 2.0;
292        }
293    }
294    let dx: Vec<f64> = xc.windows(2).map(|w| w[1] - w[0]).collect();
295    let mut t = vec![0.0; n + 2 * k];
296    t[k..k + n].copy_from_slice(&xc);
297    let len = t.len();
298    for i in 0..k {
299        t[k - i - 1] = t[k - i] - dx[n - 2 - (i % (n - 1))];
300        t[len - k + i] = t[len - k + i - 1] + dx[i % (n - 1)];
301    }
302    t
303}
304
305/// Solves a banded system with partial pivoting. `rows[i]` holds the non-zero entries of row
306/// `i` as `(first column, values)`; the band below the diagonal has width at most `kl`.
307fn solve_banded(n: usize, rows: &[(usize, Vec<f64>)], rhs: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
308    let kl = rows.iter().enumerate().map(|(i, (c0, _))| i.saturating_sub(*c0)).max().unwrap_or(0);
309    let ku = rows.iter().enumerate().map(|(i, (c0, v))| (c0 + v.len()).saturating_sub(i + 1)).max().unwrap_or(0);
310    // Row i stores columns i − kl ..= i + kl + ku (the upper band grows by kl through pivoting).
311    let w = 2 * kl + ku + 1;
312    let mut band = vec![0.0; n * w];
313    let at = |i: usize, j: usize| i * w + (j + kl - i);
314    for (i, (c0, vals)) in rows.iter().enumerate() {
315        for (o, &v) in vals.iter().enumerate() {
316            band[at(i, c0 + o)] = v;
317        }
318    }
319    let mut b = rhs.to_vec();
320    let scale = band.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE);
321    for j in 0..n {
322        let last = (j + kl).min(n - 1);
323        let p = (j..=last).max_by(|&a, &c| band[at(a, j)].abs().total_cmp(&band[at(c, j)].abs())).expect("non-empty");
324        if band[at(p, j)].abs() <= f64::EPSILON * scale * 1e-3 {
325            return Err(ErrorsJSL::RuntimeError("the interpolation matrix is singular (are the knots compatible with the data?)"));
326        }
327        let cmax = (j + kl + ku).min(n - 1);
328        if p != j {
329            for c in j..=cmax {
330                band.swap(at(p, c), at(j, c));
331            }
332            b.swap(p, j);
333        }
334        let piv = band[at(j, j)];
335        for i in j + 1..=last {
336            let f = band[at(i, j)] / piv;
337            if f != 0.0 {
338                for c in j..=cmax {
339                    band[at(i, c)] -= f * band[at(j, c)];
340                }
341                b[i] -= f * b[j];
342            }
343        }
344    }
345    for i in (0..n).rev() {
346        let cmax = (i + kl + ku).min(n - 1);
347        let s: f64 = (i + 1..=cmax).map(|c| band[at(i, c)] * b[c]).sum();
348        b[i] = (b[i] - s) / band[at(i, i)];
349    }
350    Ok(b)
351}
352
353fn check_data(x: &[f64], y: &[f64]) -> Result<(), ErrorsJSL> {
354    if x.len() != y.len() {
355        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
356    }
357    if x.windows(2).any(|w| w[1] <= w[0]) || x.iter().chain(y).any(|v| !v.is_finite()) {
358        return Err(ErrorsJSL::InvalidInputRange("x must be strictly increasing and the data finite"));
359    }
360    Ok(())
361}
362
363// ANCHOR: make_interp_spline
364/// The interpolating spline of degree `k` through `(x, y)` (SciPy's `make_interp_spline`).
365///
366/// For `k = 0` and `k = 1` the spline is piecewise constant or linear. Otherwise the knots are
367/// chosen from the data (not-a-knot, or the data points with `k` copies of each end when
368/// derivatives are given), and the `n` interpolation conditions `s(xᵢ) = yᵢ` together with the
369/// end conditions form a banded linear system for the coefficients. Periodic splines solve a
370/// cyclic system for `n − 1` free coefficients.
371pub fn make_interp_spline(x: &[f64], y: &[f64], k: usize, bc: &BoundaryCondition) -> Result<BSpline, ErrorsJSL> {
372    check_data(x, y)?;
373    let n = x.len();
374    if n < k + 1 {
375        return Err(ErrorsJSL::InvalidInputRange("need at least k + 1 data points"));
376    }
377    let derivatives = match bc {
378        BoundaryCondition::NotAKnot => None,
379        BoundaryCondition::Natural => Some((vec![(2, 0.0)], vec![(2, 0.0)])),
380        BoundaryCondition::Clamped => Some((vec![(1, 0.0)], vec![(1, 0.0)])),
381        BoundaryCondition::Derivatives { left, right } => Some((left.clone(), right.clone())),
382        BoundaryCondition::Periodic => return periodic_spline(x, y, k),
383    };
384    if k == 0 || k == 1 {
385        if derivatives.is_some() {
386            return Err(ErrorsJSL::InvalidInputRange("degrees 0 and 1 take no end conditions"));
387        }
388        let mut t = x.to_vec();
389        if k == 0 {
390            t.push(x[n - 1]);
391        } else {
392            t.insert(0, x[0]);
393            t.push(x[n - 1]);
394        }
395        let mut s = BSpline::new(t, y.to_vec(), k)?;
396        s.extrapolate = Extrapolate::Yes;
397        return Ok(s);
398    }
399    let (left, right) = derivatives.unwrap_or_default();
400    let t = if left.is_empty() && right.is_empty() {
401        not_a_knot_knots(x, k)
402    } else {
403        let mut t = vec![x[0]; k];
404        t.extend_from_slice(x);
405        t.extend(std::iter::repeat_n(x[n - 1], k));
406        t
407    };
408    let nt = t.len() - k - 1;
409    if nt != n + left.len() + right.len() {
410        return Err(ErrorsJSL::InvalidInputRange("the number of end conditions must be k − 1 (one at each end for a cubic)"));
411    }
412    if left.iter().chain(&right).any(|&(nu, _)| nu == 0 || nu > k) {
413        return Err(ErrorsJSL::InvalidInputRange("end-condition derivative orders must lie in 1..=k"));
414    }
415    let probe = BSpline::new(t.clone(), vec![0.0; nt], k)?;
416    let mut rows = Vec::with_capacity(nt);
417    let mut rhs = Vec::with_capacity(nt);
418    let (l0, _) = probe.interval(x[0]).expect("finite");
419    for &(nu, v) in &left {
420        rows.push((l0 - k, nonzero_basis_derivatives(&t, k, l0, x[0], nu)));
421        rhs.push(v);
422    }
423    for (&xi, &yi) in x.iter().zip(y) {
424        let (l, _) = probe.interval(xi).expect("finite");
425        rows.push((l - k, nonzero_basis(&t, k, l, xi)));
426        rhs.push(yi);
427    }
428    let (ln, _) = probe.interval(x[n - 1]).expect("finite");
429    for &(nu, v) in &right {
430        rows.push((ln - k, nonzero_basis_derivatives(&t, k, ln, x[n - 1], nu)));
431        rhs.push(v);
432    }
433    let c = solve_banded(nt, &rows, &rhs)?;
434    BSpline::new(t, c, k)
435}
436// ANCHOR_END: make_interp_spline
437
438/// Periodic interpolation: `n − 1` free coefficients, the last `k` repeating the first, so that
439/// every derivative matches across the ends.
440fn periodic_spline(x: &[f64], y: &[f64], k: usize) -> Result<BSpline, ErrorsJSL> {
441    let n = x.len();
442    if (y[0] - y[n - 1]).abs() > 1e-12 * (1.0 + y[0].abs()) {
443        return Err(ErrorsJSL::InvalidInputRange("periodic interpolation needs y[0] == y[n − 1]"));
444    }
445    if n < 2 {
446        return Err(ErrorsJSL::InvalidInputRange("need at least two points"));
447    }
448    let t = periodic_knots(x, k);
449    let nt = t.len() - k - 1; // = n + k − 1
450    let free = n - 1;
451    let probe = BSpline::new(t.clone(), vec![0.0; nt], k)?;
452    let mut a = Array2::<f64>::zeros((free, free));
453    for i in 0..free {
454        let (l, _) = probe.interval(x[i]).expect("finite");
455        for (r, v) in nonzero_basis(&t, k, l, x[i]).into_iter().enumerate() {
456            a[(i, (l - k + r) % free)] += v;
457        }
458    }
459    let sol = a.solve(&Array1::from(y[..free].to_vec())).map_err(|_| ErrorsJSL::RuntimeError("the periodic interpolation matrix is singular"))?;
460    let c: Vec<f64> = (0..nt).map(|j| sol[j % free]).collect();
461    let mut s = BSpline::new(t, c, k)?;
462    s.extrapolate = Extrapolate::Periodic;
463    Ok(s)
464}
465
466/// The least-squares spline of degree `k` on the knots `t`: minimises `Σ (wᵢ (yᵢ − s(xᵢ)))²`
467/// (SciPy's `make_lsq_spline`; note that the weights multiply the residuals, not their squares). The data must satisfy the Schoenberg-Whitney conditions (each
468/// basis function must be non-zero at some data point) for the solution to be unique.
469pub fn make_lsq_spline(x: &[f64], y: &[f64], t: &[f64], k: usize, w: Option<&[f64]>) -> Result<BSpline, ErrorsJSL> {
470    if x.len() != y.len() {
471        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
472    }
473    if x.windows(2).any(|p| p[1] < p[0]) {
474        return Err(ErrorsJSL::InvalidInputRange("x must be non-decreasing"));
475    }
476    let mut m = BSpline::design_matrix(x, t, k)?;
477    let mut rhs = Array1::from(y.to_vec());
478    if let Some(w) = w {
479        if w.len() != x.len() {
480            return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), x.len())));
481        }
482        for (i, &wi) in w.iter().enumerate() {
483            m.row_mut(i).mapv_inplace(|v| v * wi);
484            rhs[i] *= wi;
485        }
486    }
487    let ls = m.least_squares(&rhs).map_err(|_| ErrorsJSL::RuntimeError("least-squares spline failed"))?;
488    if ls.rank < m.ncols() {
489        return Err(ErrorsJSL::InvalidInputRange("the knots and data violate the Schoenberg-Whitney conditions"));
490    }
491    BSpline::new(t.to_vec(), ls.solution.to_vec(), k)
492}
493
494/// An interpolating parametric curve through the rows of `points` (an `n × d` array): the
495/// parameter is the cumulative chord length normalised to `[0, 1]` (as `splprep` chooses it),
496/// and each coordinate is interpolated with [`make_interp_spline`]. Returns the parameter values
497/// and one spline per coordinate.
498pub fn make_interp_curve(points: &Array2<f64>, k: usize, bc: &BoundaryCondition) -> Result<(Vec<f64>, Vec<BSpline>), ErrorsJSL> {
499    let n = points.nrows();
500    let mut u = vec![0.0; n];
501    for i in 1..n {
502        let d = points.row(i).iter().zip(points.row(i - 1).iter()).map(|(a, b)| (a - b) * (a - b)).sum::<f64>().sqrt();
503        u[i] = u[i - 1] + d;
504    }
505    let total = u[n - 1];
506    if total <= 0.0 {
507        return Err(ErrorsJSL::InvalidInputRange("the points must not all coincide"));
508    }
509    u.iter_mut().for_each(|v| *v /= total);
510    let splines = (0..points.ncols()).map(|j| make_interp_spline(&u, &points.column(j).to_vec(), k, bc)).collect::<Result<Vec<_>, _>>()?;
511    Ok((u, splines))
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517
518    #[test]
519    fn basis_is_a_partition_of_unity() {
520        let t = [0.0, 0.0, 0.0, 0.0, 1.0, 2.5, 3.0, 3.0, 3.0, 3.0];
521        for x in [0.0, 0.3, 1.7, 2.9] {
522            let s: f64 = nonzero_basis(&t, 3, BSpline::new(t.to_vec(), vec![0.0; 6], 3).unwrap().interval(x).unwrap().0, x).iter().sum();
523            assert!((s - 1.0).abs() < 1e-14);
524        }
525    }
526
527    #[test]
528    fn interpolating_cubics_reproduce_cubics() {
529        let x: Vec<f64> = (0..9).map(|i| (i as f64 * 0.7).powf(1.3)).collect();
530        let f = |x: f64| 1.0 - 2.0 * x + 0.5 * x * x - 0.1 * x * x * x;
531        let fp = |x: f64| -2.0 + x - 0.3 * x * x;
532        let y: Vec<f64> = x.iter().map(|&v| f(v)).collect();
533        let bcs = [
534            BoundaryCondition::NotAKnot,
535            BoundaryCondition::Derivatives { left: vec![(1, fp(x[0]))], right: vec![(1, fp(x[8]))] },
536        ];
537        for bc in bcs {
538            let s = make_interp_spline(&x, &y, 3, &bc).unwrap();
539            for z in [0.1, 1.3, 2.2, 4.0] {
540                assert!((s.evaluate(z) - f(z)).abs() < 1e-12, "{bc:?} at {z}");
541                assert!((s.evaluate_derivative(z, 1) - fp(z)).abs() < 1e-11);
542            }
543            let exact = |x: f64| x - x * x + x * x * x / 6.0 - 0.025 * x.powi(4);
544            assert!((s.integrate(0.5, 3.0) - (exact(3.0) - exact(0.5))).abs() < 1e-12);
545        }
546    }
547
548    #[test]
549    fn periodic_spline_matches_derivatives_across_the_ends() {
550        let n = 12;
551        let x: Vec<f64> = (0..=n).map(|i| i as f64 * std::f64::consts::TAU / n as f64).collect();
552        let y: Vec<f64> = x.iter().map(|v| v.sin() + 0.3 * (2.0 * v).cos()).collect();
553        let s = make_interp_spline(&x, &y, 3, &BoundaryCondition::Periodic).unwrap();
554        let (a, b) = (x[0], x[n]);
555        for nu in 0..3 {
556            assert!((s.evaluate_derivative(a, nu) - s.evaluate_derivative(b - 1e-12, nu)).abs() < 1e-8, "order {nu}");
557        }
558        assert!((s.evaluate(a + 0.3) - s.evaluate(b + 0.3)).abs() < 1e-14);
559    }
560}