Skip to main content

lib_jsl_interpolation/one_d/
fitpack.rs

1//! Smoothing splines with automatically placed knots, after Dierckx's FITPACK (`curfit` and
2//! `parcur`), following SciPy's `make_splrep`, `make_splprep` and `generate_knots`.
3//!
4//! Given data `(xᵢ, yᵢ)`, weights `wᵢ` and a smoothing factor `s`, the spline `g` of degree `k`
5//! is the smoothest one — the sum of squared jumps of `g⁽ᵏ⁾` at its interior knots is least —
6//! among those with `Σ (wᵢ (yᵢ − g(xᵢ)))² ≤ s`. The knots are found by adding them one interval
7//! at a time where the least-squares spline fits worst, until the least-squares fit is within
8//! `s`; then the weight `p` of the data against smoothness is found by rational interpolation so
9//! that the residual equals `s`.
10//!
11//! See the book entry [Smoothing splines with automatic knots](https://jwkunz.github.io/lib_jsl/book/interpolation/fitpack.html).
12
13// Guards such as `!(s >= 0.0)` also reject NaN; band indices read best as index loops.
14#![allow(clippy::neg_cmp_op_on_partial_ord, clippy::needless_range_loop)]
15
16use super::b_spline::{BSpline, BoundaryCondition, make_interp_spline, nonzero_basis, not_a_knot_knots};
17use lib_jsl_core::ErrorsJSL;
18
19/// FITPACK's relative tolerance on `|fp − s|` and its iteration limit for `p`.
20const TOL: f64 = 0.001;
21const MAXIT: usize = 20;
22
23/// Options for [`make_splrep`], [`make_splprep`] and [`generate_knots`] (SciPy's keyword
24/// arguments; the defaults are SciPy's).
25#[derive(Clone, Debug)]
26pub struct SplrepOptions<'a> {
27    /// Weights, one per point (default all one); the residuals are `wᵢ (yᵢ − g(xᵢ))`.
28    pub w: Option<&'a [f64]>,
29    /// The degree (default 3).
30    pub k: usize,
31    /// The smoothing factor `s ≥ 0` (default 0, interpolation).
32    pub s: f64,
33    /// The ends of the approximation interval (default the first and last `x`).
34    pub xb: Option<f64>,
35    pub xe: Option<f64>,
36    /// Stop adding knots once there are at least this many (default no limit beyond the
37    /// interpolating spline's `m + k + 1`).
38    pub nest: Option<usize>,
39}
40
41impl Default for SplrepOptions<'_> {
42    fn default() -> Self {
43        SplrepOptions { w: None, k: 3, s: 0.0, xb: None, xe: None, nest: None }
44    }
45}
46
47/// Data with `d` right-hand sides per point (one for a function, `d` for a curve), validated.
48struct Data<'a> {
49    x: &'a [f64],
50    /// `y[i][j]`: point `i`, coordinate `j`.
51    y: Vec<Vec<f64>>,
52    w: Vec<f64>,
53    k: usize,
54    s: f64,
55    xb: f64,
56    xe: f64,
57}
58
59impl Data<'_> {
60    fn m(&self) -> usize {
61        self.x.len()
62    }
63}
64
65/// An upper-triangular banded matrix (`r[i][j]` is entry `(i, i + j)`) and its right-hand sides,
66/// built by Givens rotations as FITPACK does (`fpgivs`, `fprota`).
67struct Banded {
68    r: Vec<Vec<f64>>,
69    z: Vec<Vec<f64>>,
70}
71
72impl Banded {
73    fn new(nc: usize, bw: usize, d: usize) -> Self {
74        Banded { r: vec![vec![0.0; bw]; nc], z: vec![vec![0.0; d]; nc] }
75    }
76
77    /// Rotates the row `h` (entries for columns `off, off + 1, …`) with right-hand side `rhs`
78    /// into the triangle. The row is kept in a window of the bandwidth that slides one column
79    /// per rotation, since each rotation can fill it in up to the band's edge.
80    fn rotate_in(&mut self, h: Vec<f64>, off: usize, mut rhs: Vec<f64>) {
81        let (nc, bw) = (self.r.len(), self.r[0].len());
82        let mut win = vec![0.0; bw];
83        win[..h.len().min(bw)].copy_from_slice(&h[..h.len().min(bw)]);
84        let mut extra = h.get(bw..).map(|v| v.to_vec()).unwrap_or_default().into_iter();
85        let mut i = off;
86        while i < nc && win.iter().any(|&v| v != 0.0) {
87            let piv = win[0];
88            if piv != 0.0 {
89                // fpgivs: the rotation that zeroes piv against the diagonal ww.
90                let ww = self.r[i][0];
91                let (a, b) = (piv.abs(), ww.abs());
92                let dd = if a >= b { a * (1.0 + (b / a).powi(2)).sqrt() } else { b * (1.0 + (a / b).powi(2)).sqrt() };
93                let (cos, sin) = (ww / dd, piv / dd);
94                self.r[i][0] = dd;
95                // fprota on the right-hand sides and the rest of the row.
96                for (zv, yv) in self.z[i].iter_mut().zip(rhs.iter_mut()) {
97                    let (s1, s2) = (*yv, *zv);
98                    *zv = cos * s2 + sin * s1;
99                    *yv = cos * s1 - sin * s2;
100                }
101                for l in 1..bw {
102                    let (s1, s2) = (win[l], self.r[i][l]);
103                    self.r[i][l] = cos * s2 + sin * s1;
104                    win[l] = cos * s1 - sin * s2;
105                }
106            }
107            win.rotate_left(1);
108            win[bw - 1] = extra.next().unwrap_or(0.0);
109            i += 1;
110        }
111    }
112
113    /// Back substitution for the coefficients, one column per right-hand side (`fpback`).
114    fn solve(&self) -> Vec<Vec<f64>> {
115        let (nc, bw) = (self.r.len(), self.r[0].len());
116        let d = self.z[0].len();
117        let mut c = vec![vec![0.0; d]; nc];
118        for i in (0..nc).rev() {
119            for q in 0..d {
120                let mut store = self.z[i][q];
121                for l in 1..bw.min(nc - i) {
122                    store -= c[i + l][q] * self.r[i][l];
123                }
124                c[i][q] = store / self.r[i][0];
125            }
126        }
127        c
128    }
129}
130
131/// The interval `l` (`t[l] ≤ x < t[l + 1]`, `k ≤ l ≤ n − k − 2`) of each point.
132fn intervals(x: &[f64], t: &[f64], k: usize) -> Vec<usize> {
133    let nk1 = t.len() - k - 1;
134    let mut l = k;
135    x.iter()
136        .map(|&xi| {
137            while xi >= t[l + 1] && l < nk1 - 1 {
138                l += 1;
139            }
140            l
141        })
142        .collect()
143}
144
145/// The least-squares spline on knots `t`: its triangular factor, coefficients, per-point
146/// residuals `Σⱼ (wᵢ (yᵢⱼ − g(xᵢ)ⱼ))²` and their sum.
147struct Lsq {
148    qr: Banded,
149    c: Vec<Vec<f64>>,
150    residuals: Vec<f64>,
151    fp: f64,
152}
153
154fn residuals(data: &Data, t: &[f64], c: &[Vec<f64>]) -> (Vec<f64>, f64) {
155    let k = data.k;
156    let res: Vec<f64> = intervals(data.x, t, k)
157        .into_iter()
158        .enumerate()
159        .map(|(i, l)| {
160            let b = nonzero_basis(t, k, l, data.x[i]);
161            (0..data.y[i].len())
162                .map(|q| {
163                    let g: f64 = b.iter().enumerate().map(|(r, v)| v * c[l - k + r][q]).sum();
164                    (data.w[i] * (data.y[i][q] - g)).powi(2)
165                })
166                .sum()
167        })
168        .collect();
169    let fp = res.iter().sum();
170    (res, fp)
171}
172
173fn lsq(data: &Data, t: &[f64]) -> Lsq {
174    let k = data.k;
175    let nc = t.len() - k - 1;
176    let mut qr = Banded::new(nc, k + 1, data.y[0].len());
177    for (i, l) in intervals(data.x, t, k).into_iter().enumerate() {
178        let wi = data.w[i];
179        let h: Vec<f64> = nonzero_basis(t, k, l, data.x[i]).into_iter().map(|v| v * wi).collect();
180        qr.rotate_in(h, l - k, data.y[i].iter().map(|v| v * wi).collect());
181    }
182    let c = qr.solve();
183    let (residuals, fp) = residuals(data, t, &c);
184    Lsq { qr, c, residuals, fp }
185}
186
187// ANCHOR: fpknot
188/// FITPACK's `fpknot`: split the residuals into the knot intervals (a point on an interior knot
189/// counts half to each side), pick the interval with the largest sum among those holding more
190/// than one point, and insert a knot at the data point in its middle.
191fn add_knot(x: &[f64], t: &[f64], k: usize, res: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
192    let m = x.len();
193    let bounds = &t[k..t.len() - k];
194    let mut ix: Vec<usize> = bounds.iter().map(|&b| x.partition_point(|&v| v < b)).collect();
195    let last = ix.len() - 1;
196    ix[last] = m - 1;
197    let mut parts: Vec<f64> = ix.windows(2).map(|w| res[w[0]..w[1]].iter().sum()).collect();
198    for i in 1..last {
199        let carry = res[ix[i]] / 2.0;
200        parts[i - 1] += carry;
201        parts[i] -= carry;
202    }
203    parts[last - 1] += res[m - 1];
204    let mut best: Option<usize> = None;
205    for i in 0..parts.len() {
206        if ix[i + 1] - ix[i] > 1 && best.is_none_or(|b| parts[i] > parts[b]) {
207            best = Some(i);
208        }
209    }
210    let b = best.ok_or(ErrorsJSL::RuntimeError("generate_knots: no knot interval has room for another knot"))?;
211    let knot = x[(ix[b] + ix[b + 1]).div_ceil(2)];
212    let pos = t.partition_point(|&v| v < knot);
213    let mut out = t.to_vec();
214    out.insert(pos, knot);
215    Ok(out)
216}
217// ANCHOR_END: fpknot
218
219fn knot_sequence(data: &Data, nest: Option<usize>) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
220    let (k, m, s) = (data.k, data.m(), data.s);
221    let acc = s * TOL;
222    let nest = match nest {
223        None => (m + k + 1).max(2 * k + 3),
224        Some(n) if n < 2 * (k + 1) => return Err(ErrorsJSL::InvalidInputRange("nest must be at least 2(k + 1)")),
225        Some(n) => n,
226    };
227    let (nmin, nmax) = (2 * (k + 1), m + k + 1);
228    let mut t: Vec<f64> = std::iter::repeat_n(data.xb, k + 1).chain(std::iter::repeat_n(data.xe, k + 1)).collect();
229    let mut out = Vec::new();
230    let (mut fp, mut nplus) = (0.0, 1usize);
231    for _ in 0..m {
232        out.push(t.clone());
233        let fpold = fp;
234        let fit = lsq(data, &t);
235        fp = fit.fp;
236        let fpms = fp - s;
237        if fpms.abs() < acc || fpms < 0.0 {
238            return Ok(out);
239        }
240        nplus = if t.len() == nmin {
241            1
242        } else {
243            let delta = fpold - fp;
244            let npl1 = if delta > acc { (nplus as f64 * fpms / delta) as usize } else { nplus * 2 };
245            (nplus * 2).min(npl1.max(nplus / 2).max(1))
246        };
247        let mut res = fit.residuals;
248        for j in 0..nplus {
249            t = add_knot(data.x, &t, k, &res)?;
250            if t.len() >= nmax {
251                out.push(not_a_knot_knots(data.x, k));
252                return Ok(out);
253            }
254            if t.len() >= nest {
255                out.push(t);
256                return Ok(out);
257            }
258            if j + 1 < nplus {
259                res = lsq(data, &t).residuals;
260            }
261        }
262    }
263    Ok(out)
264}
265
266/// FITPACK's `fpdisc`: the jumps of the `k`-th derivatives of the B-splines at the interior
267/// knots `t[k+1], …, t[n−k−2]`, row `j` holding `k + 2` entries from column `j`, scaled by
268/// `(Δ/nrint)^k` with `Δ` the base interval and `nrint` its number of knot intervals.
269pub(crate) fn discontinuity_jumps(t: &[f64], k: usize) -> Vec<Vec<f64>> {
270    let n = t.len();
271    let nrint = n - 2 * k - 1;
272    let scale = ((t[n - k - 1] - t[k]) / nrint as f64).powi(k as i32);
273    (0..nrint - 1)
274        .map(|jj| {
275            let j = jj + k + 1;
276            (0..k + 2)
277                .map(|ii| {
278                    let i = jj + ii;
279                    let prod: f64 = (0..k + 2).filter(|&q| i + q != j).map(|q| t[j] - t[i + q]).product();
280                    (t[i + k + 1] - t[i]) / prod * scale
281                })
282                .collect()
283        })
284        .collect()
285}
286
287/// The smoothing spline for a given `p`: the data rows (already triangularised) with the jump
288/// rows weighted by `1/p` rotated in; returns its coefficients and `fp − s`.
289fn smoothing_for_p(data: &Data, t: &[f64], base: &Banded, jumps: &[Vec<f64>], p: f64) -> (Vec<Vec<f64>>, f64) {
290    let k = data.k;
291    let nc = base.r.len();
292    let mut qr = Banded::new(nc, k + 2, base.z[0].len());
293    for i in 0..nc {
294        qr.r[i][..k + 1].copy_from_slice(&base.r[i]);
295        qr.z[i].clone_from(&base.z[i]);
296    }
297    let d = base.z[0].len();
298    for (j, row) in jumps.iter().enumerate() {
299        qr.rotate_in(row.iter().map(|v| v / p).collect(), j, vec![0.0; d]);
300    }
301    let c = qr.solve();
302    let fp = residuals(data, t, &c).1;
303    (c, fp - data.s)
304}
305
306/// FITPACK's `fprati`: the zero of the rational function `(u p + v)/(p + w)` through three points
307/// (`p₃` may be infinite).
308pub(crate) fn fprati(p1: f64, f1: f64, p2: f64, f2: f64, p3: f64, f3: f64) -> f64 {
309    let h1 = f1 * (f2 - f3);
310    let h2 = f2 * (f3 - f1);
311    let h3 = f3 * (f1 - f2);
312    if p3.is_infinite() {
313        return -(p2 * h1 + p1 * h2) / h3;
314    }
315    -(p1 * p2 * h3 + p2 * p3 * h1 + p1 * p3 * h2) / (p1 * h1 + p2 * h2 + p3 * h3)
316}
317
318/// The result of the smoothing fit: knots and coefficients (one column per coordinate), the
319/// weighted sum of squared residuals, and whether `|fp − s| ≤ 0.001 s` was reached.
320struct Fit {
321    t: Vec<f64>,
322    c: Vec<Vec<f64>>,
323    fp: f64,
324    converged: bool,
325}
326
327// ANCHOR: smoothing
328fn fit_smoothing(data: &Data, t: Option<&[f64]>, nest: Option<usize>) -> Result<Fit, ErrorsJSL> {
329    let (k, s) = (data.k, data.s);
330    let acc = s * TOL;
331    let t: Vec<f64> = match t {
332        Some(t) => t.to_vec(),
333        None => knot_sequence(data, nest)?.pop().expect("at least one knot vector"),
334    };
335    let base = lsq(data, &t);
336    if t.len() == 2 * (k + 1) {
337        return Ok(Fit { t, c: base.c, fp: base.fp, converged: true });
338    }
339    // f(p) = fp(p) − s decreases from the polynomial fit (p = 0) to the least-squares spline
340    // (p = ∞); bracket the root and refine it by rational interpolation.
341    let nc = t.len() - k - 1;
342    let mut p = nc as f64 / base.qr.r.iter().map(|r| r[0]).sum::<f64>();
343    let poly: Vec<f64> = std::iter::repeat_n(data.xb, k + 1).chain(std::iter::repeat_n(data.xe, k + 1)).collect();
344    let (mut p1, mut f1) = (0.0, lsq(data, &poly).fp - s);
345    let (mut p3, mut f3) = (f64::INFINITY, base.fp - s);
346    let jumps = discontinuity_jumps(&t, k);
347    let (con1, con4, con9) = (0.1, 0.04, 0.9);
348    let (mut ich1, mut ich3) = (false, false);
349    let mut last = (base.c.clone(), base.fp);
350    for _ in 0..MAXIT {
351        let (c, f2) = smoothing_for_p(data, &t, &base.qr, &jumps, p);
352        let p2 = p;
353        last = (c, f2 + s);
354        if f2.abs() < acc {
355            return Ok(Fit { t, c: last.0, fp: last.1, converged: true });
356        }
357        if !ich3 {
358            if f2 - f3 <= acc {
359                // p is too large.
360                (p3, f3) = (p2, f2);
361                p *= con4;
362                if p <= p1 {
363                    p = p1 * con9 + p2 * con1;
364                }
365                continue;
366            }
367            if f2 < 0.0 {
368                ich3 = true;
369            }
370        }
371        if !ich1 {
372            if f1 - f2 <= acc {
373                // p is too small.
374                (p1, f1) = (p2, f2);
375                p /= con4;
376                if p3.is_finite() && p <= p3 {
377                    p = p2 * con1 + p3 * con9;
378                }
379                continue;
380            }
381            if f2 > 0.0 {
382                ich1 = true;
383            }
384        }
385        if f1 <= f2 || f2 <= f3 {
386            // f is not decreasing: s is too small for the arithmetic.
387            break;
388        }
389        p = fprati(p1, f1, p2, f2, p3, f3);
390        if f2 < 0.0 {
391            (p3, f3) = (p2, f2);
392        } else {
393            (p1, f1) = (p2, f2);
394        }
395    }
396    Ok(Fit { t, c: last.0, fp: last.1, converged: false })
397}
398// ANCHOR_END: smoothing
399
400fn validate<'a>(x: &'a [f64], y: Vec<Vec<f64>>, options: &SplrepOptions) -> Result<Data<'a>, ErrorsJSL> {
401    let m = x.len();
402    let k = options.k;
403    if y.len() != m {
404        return Err(ErrorsJSL::IncompatibleArraySizes((y.len(), m)));
405    }
406    if k == 0 || m <= k {
407        return Err(ErrorsJSL::InvalidInputRange("make_splrep: need degree k ≥ 1 and more than k points"));
408    }
409    if x.windows(2).any(|p| !(p[1] >= p[0])) || x.iter().any(|v| !v.is_finite()) {
410        return Err(ErrorsJSL::InvalidInputRange("make_splrep: x must be finite and non-decreasing"));
411    }
412    if !(options.s >= 0.0) {
413        return Err(ErrorsJSL::InvalidInputRange("make_splrep: s must be non-negative"));
414    }
415    let w = match options.w {
416        Some(w) if w.len() != m => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), m))),
417        Some(w) if w.iter().any(|v| !(*v >= 0.0)) || w.iter().sum::<f64>() == 0.0 => {
418            return Err(ErrorsJSL::InvalidInputRange("make_splrep: weights must be non-negative and not all zero"));
419        }
420        Some(w) => w.to_vec(),
421        None => vec![1.0; m],
422    };
423    let xb = options.xb.unwrap_or(x[0]);
424    let xe = options.xe.unwrap_or(x[m - 1]);
425    if !(xb <= x[0] && xe >= x[m - 1] && xb < xe) {
426        return Err(ErrorsJSL::InvalidInputRange("make_splrep: need xb ≤ x[0] and xe ≥ x[m − 1]"));
427    }
428    Ok(Data { x, y, w, k, s: options.s, xb, xe })
429}
430
431// ANCHOR: generate_knots
432/// The successive knot vectors FITPACK tries (SciPy's `generate_knots`): from the `2(k + 1)` knots
433/// of a polynomial, knots are added where the least-squares spline fits worst — `1, 2, 4, …` per
434/// round, fewer as the residual nears `s` — until the least-squares residual is at most `s`, the
435/// limit `nest` is reached, or the knots become those of the interpolating spline. The last
436/// vector is the one [`make_splrep`] uses.
437pub fn generate_knots(x: &[f64], y: &[f64], options: &SplrepOptions) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
438    if options.s == 0.0 {
439        if options.w.is_some() || options.nest.is_some() {
440            return Err(ErrorsJSL::InvalidInputRange("generate_knots: s = 0 is interpolation, without weights or nest"));
441        }
442        return Ok(vec![not_a_knot_knots(x, options.k)]);
443    }
444    let data = validate(x, y.iter().map(|&v| vec![v]).collect(), options)?;
445    knot_sequence(&data, options.nest)
446}
447// ANCHOR_END: generate_knots
448
449/// The result of [`make_splrep`] and [`make_splprep`] beyond the spline itself.
450#[derive(Clone, Debug)]
451#[non_exhaustive]
452pub struct SplrepInfo {
453    /// The weighted sum of squared residuals `Σ (wᵢ (yᵢ − g(xᵢ)))²`.
454    pub fp: f64,
455    /// Whether `|fp − s| ≤ 0.001 s` was reached (or the spline is the least-squares spline or
456    /// polynomial with `fp ≤ s`); otherwise SciPy warns and returns the last iterate.
457    pub converged: bool,
458}
459
460// ANCHOR: make_splrep
461/// The smoothing spline of degree `k` with automatically placed knots (SciPy's `make_splrep`,
462/// FITPACK's `curfit`): of all splines with `Σ (wᵢ (yᵢ − g(xᵢ)))² ≤ s`, the one whose `k`-th
463/// derivative jumps least at its interior knots. `s = 0` gives the interpolating spline with
464/// not-a-knot ends; a large `s` gives the least-squares polynomial. With weights `1/σᵢ`, a good
465/// `s` lies in `m ± √(2m)`. `t` fixes the knots instead of generating them.
466pub fn make_splrep(x: &[f64], y: &[f64], t: Option<&[f64]>, options: &SplrepOptions) -> Result<(BSpline, SplrepInfo), ErrorsJSL> {
467    if options.s == 0.0 {
468        if t.is_some() || options.w.is_some() || options.nest.is_some() {
469            return Err(ErrorsJSL::InvalidInputRange("make_splrep: s = 0 is interpolation, without t, weights or nest"));
470        }
471        let spl = make_interp_spline(x, y, options.k, &BoundaryCondition::NotAKnot)?;
472        return Ok((spl, SplrepInfo { fp: 0.0, converged: true }));
473    }
474    if t.is_some() && options.nest.is_some() {
475        return Err(ErrorsJSL::InvalidInputRange("make_splrep: give either t or nest"));
476    }
477    let data = validate(x, y.iter().map(|&v| vec![v]).collect(), options)?;
478    let fit = fit_smoothing(&data, t, options.nest)?;
479    let c = fit.c.iter().map(|r| r[0]).collect();
480    Ok((BSpline::new(fit.t, c, data.k)?, SplrepInfo { fp: fit.fp, converged: fit.converged }))
481}
482// ANCHOR_END: make_splrep
483
484/// A smoothing parametric spline curve through `points` (one row per point, one column per
485/// coordinate) with shared, automatically placed knots (SciPy's `make_splprep`, FITPACK's
486/// `parcur`). The parameter `u` defaults to the cumulative chord length scaled to `[0, 1]`; the
487/// smoothing criterion sums the squared residuals over all coordinates. Returns `u` and one
488/// spline per coordinate, all on the same knots.
489pub fn make_splprep(points: &[Vec<f64>], u: Option<&[f64]>, t: Option<&[f64]>, options: &SplrepOptions) -> Result<(Vec<f64>, Vec<BSpline>, SplrepInfo), ErrorsJSL> {
490    let m = points.len();
491    if m < 2 || points.iter().any(|p| p.len() != points[0].len() || p.is_empty()) {
492        return Err(ErrorsJSL::InvalidInputRange("make_splprep: need at least two points of equal, non-zero dimension"));
493    }
494    let u: Vec<f64> = match u {
495        Some(u) => u.to_vec(),
496        None => {
497            let mut v = vec![0.0; m];
498            for i in 1..m {
499                v[i] = v[i - 1] + points[i].iter().zip(&points[i - 1]).map(|(a, b)| (a - b).powi(2)).sum::<f64>().sqrt();
500            }
501            let total = v[m - 1];
502            if total <= 0.0 {
503                return Err(ErrorsJSL::InvalidInputRange("make_splprep: the points must not all coincide"));
504            }
505            v.iter().map(|a| a / total).collect()
506        }
507    };
508    let d = points[0].len();
509    if options.s == 0.0 {
510        if t.is_some() || options.w.is_some() || options.nest.is_some() {
511            return Err(ErrorsJSL::InvalidInputRange("make_splprep: s = 0 is interpolation, without t, weights or nest"));
512        }
513        let splines = (0..d)
514            .map(|j| make_interp_spline(&u, &points.iter().map(|p| p[j]).collect::<Vec<_>>(), options.k, &BoundaryCondition::NotAKnot))
515            .collect::<Result<Vec<_>, _>>()?;
516        return Ok((u, splines, SplrepInfo { fp: 0.0, converged: true }));
517    }
518    if t.is_some() && options.nest.is_some() {
519        return Err(ErrorsJSL::InvalidInputRange("make_splprep: give either t or nest"));
520    }
521    let data = validate(&u, points.to_vec(), options)?;
522    let fit = fit_smoothing(&data, t, options.nest)?;
523    let splines = (0..d).map(|j| BSpline::new(fit.t.clone(), fit.c.iter().map(|r| r[j]).collect(), data.k)).collect::<Result<Vec<_>, _>>()?;
524    let info = SplrepInfo { fp: fit.fp, converged: fit.converged };
525    Ok((u, splines, info))
526}
527
528/// Least squares `min ‖A c − b‖` by Householder QR (dense); returns `c` and `|diag R|`.
529fn dense_lsq(mut a: Vec<Vec<f64>>, mut b: Vec<f64>, nc: usize) -> (Vec<f64>, Vec<f64>) {
530    let m = a.len();
531    for j in 0..nc.min(m) {
532        let norm: f64 = (j..m).map(|i| a[i][j] * a[i][j]).sum::<f64>().sqrt();
533        if norm == 0.0 {
534            continue;
535        }
536        let alpha = if a[j][j] > 0.0 { -norm } else { norm };
537        let mut v: Vec<f64> = (j..m).map(|i| a[i][j]).collect();
538        v[0] -= alpha;
539        let vn: f64 = v.iter().map(|x| x * x).sum();
540        if vn == 0.0 {
541            continue;
542        }
543        for col in j..nc {
544            let s: f64 = (j..m).map(|i| v[i - j] * a[i][col]).sum::<f64>() * 2.0 / vn;
545            for i in j..m {
546                a[i][col] -= s * v[i - j];
547            }
548        }
549        let s: f64 = (j..m).map(|i| v[i - j] * b[i]).sum::<f64>() * 2.0 / vn;
550        for i in j..m {
551            b[i] -= s * v[i - j];
552        }
553    }
554    let mut c = vec![0.0; nc];
555    for i in (0..nc).rev() {
556        let s: f64 = (i + 1..nc).map(|j| a[i][j] * c[j]).sum();
557        c[i] = if a[i][i] != 0.0 { (b[i] - s) / a[i][i] } else { 0.0 };
558    }
559    (c, (0..nc).map(|i| a[i][i].abs()).collect())
560}
561
562/// The periodic spline's free coefficients: `n − 2k − 1` of them, the last `k` of the full
563/// vector repeating the first `k`.
564fn periodic_full(c: &[f64], k: usize) -> Vec<f64> {
565    (0..c.len() + k).map(|j| c[j % c.len()]).collect()
566}
567
568/// The periodic least-squares (`p = ∞`) or smoothing fit on knots `t`, using the first `m − 1`
569/// points (the last repeats the first): the free coefficients, `|diag R|`, `fp` over those
570/// points, and the residuals of all `m` points (FITPACK's `fpperi`).
571fn periodic_fit(data: &Data, t: &[f64], p: Option<f64>) -> (Vec<f64>, Vec<f64>, f64, Vec<f64>) {
572    let k = data.k;
573    let n = t.len();
574    let n7 = n - 2 * k - 1;
575    let m = data.m();
576    let ls = intervals(data.x, t, k);
577    let mut rows = Vec::new();
578    let mut rhs = Vec::new();
579    for i in 0..m - 1 {
580        let l = ls[i];
581        let mut row = vec![0.0; n7];
582        for (r, v) in nonzero_basis(t, k, l, data.x[i]).into_iter().enumerate() {
583            row[(l - k + r) % n7] += v * data.w[i];
584        }
585        rows.push(row);
586        rhs.push(data.w[i] * data.y[i][0]);
587    }
588    if let Some(p) = p {
589        for (j, jump) in discontinuity_jumps(t, k).iter().enumerate() {
590            let mut row = vec![0.0; n7];
591            for (r, v) in jump.iter().enumerate() {
592                row[(j + r) % n7] += v / p;
593            }
594            rows.push(row);
595            rhs.push(0.0);
596        }
597    }
598    let (c, diag) = dense_lsq(rows, rhs, n7);
599    let full: Vec<Vec<f64>> = periodic_full(&c, k).into_iter().map(|v| vec![v]).collect();
600    let (res, _) = residuals(data, t, &full);
601    let fp = res[..m - 1].iter().sum();
602    (c, diag, fp, res)
603}
604
605/// FITPACK's knot sequence for periodic smoothing (`percur`), SciPy's `generate_knots` with
606/// `bc_type='periodic'`.
607fn periodic_knot_sequence(data: &Data, nest: Option<usize>) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
608    let (k, s, m) = (data.k, data.s, data.m());
609    let acc = s * TOL;
610    let nest = nest.unwrap_or((m + 2 * k).max(2 * k + 3));
611    let (nmin, nmax) = (2 * (k + 1), m + 2 * k);
612    let per = data.xe - data.xb;
613    let mut out = Vec::new();
614    let mut t: Vec<f64> = (0..=k).map(|i| data.x[0] - (k - i) as f64 * per).chain((0..=k).map(|i| data.x[m - 1] + i as f64 * per)).collect();
615    let (_, _, mut fp, _) = periodic_fit(data, &t, None);
616    if fp - s < acc || nmax == nmin {
617        out.push(t);
618        return Ok(out);
619    }
620    t = vec![0.0; 2 * k + 3];
621    t[k + 1] = data.x[m.div_ceil(2) - 1];
622    let mut nplus: usize = 1;
623    for _ in 0..m {
624        let n = t.len();
625        t[k] = data.xb;
626        t[n - k - 1] = data.xe;
627        for j in 1..=k {
628            t[k - j] = t[n - k - j - 1] - per;
629            t[n - k + j - 1] = t[k + j] + per;
630        }
631        out.push(t.clone());
632        let fpold = fp;
633        let (_, _, f, mut res) = periodic_fit(data, &t, None);
634        fp = f;
635        let fpms = fp - s;
636        if fpms.abs() < acc || fpms < 0.0 {
637            return Ok(out);
638        }
639        if n == nmin {
640            nplus = 1;
641        } else {
642            let delta = fpold - fp;
643            let npl1 = if delta > acc { (nplus as f64 * fpms / delta) as usize } else { nplus * 2 };
644            nplus = (nplus * 2).min(npl1.max(nplus / 2).max(1));
645        }
646        for j in 0..nplus {
647            t = add_knot(data.x, &t, k, &res)?;
648            let n = t.len();
649            if n >= nmax {
650                out.push(periodic_interp_knots(data.x, k));
651                return Ok(out);
652            }
653            if n >= nest {
654                out.push(t);
655                return Ok(out);
656            }
657            if j + 1 < nplus {
658                res = periodic_fit(data, &t, None).3;
659            }
660        }
661    }
662    Ok(out)
663}
664
665/// SciPy's `_periodic_knots`: the knots of the periodic interpolating spline.
666fn periodic_interp_knots(x: &[f64], k: usize) -> Vec<f64> {
667    let n = x.len();
668    let mut xc = x.to_vec();
669    if k.is_multiple_of(2) {
670        let dx: Vec<f64> = x.windows(2).map(|w| w[1] - w[0]).collect();
671        for i in 1..n - 1 {
672            xc[i] -= dx[i - 1] / 2.0;
673        }
674    }
675    let dx: Vec<f64> = xc.windows(2).map(|w| w[1] - w[0]).collect();
676    let mut t = vec![0.0; n + 2 * k];
677    t[k..k + n].copy_from_slice(&xc);
678    for i in 0..k {
679        t[k - i - 1] = t[k - i] - dx[n - 2 - (i % (n - 1))];
680        let e = t.len() - k + i;
681        t[e] = t[e - 1] + dx[i % (n - 1)];
682    }
683    t
684}
685
686// ANCHOR: periodic
687/// The periodic smoothing spline with automatically placed knots (SciPy's
688/// `make_splrep(..., bc_type='periodic')`, FITPACK's `percur`): the spline and its first `k − 1`
689/// derivatives match at `xb` and `xe = xb + period`, the last data point stands for the first
690/// one shifted by a period, and otherwise the criterion is [`make_splrep`]'s. The free
691/// coefficients are the first `n − 2k − 1`; the last `k` repeat them.
692pub fn make_splrep_periodic(x: &[f64], y: &[f64], t: Option<&[f64]>, options: &SplrepOptions) -> Result<(BSpline, SplrepInfo), ErrorsJSL> {
693    let data = validate(x, y.iter().map(|&v| vec![v]).collect(), options)?;
694    let (k, s) = (data.k, data.s);
695    if x.len() < 2 * k.max(2) {
696        return Err(ErrorsJSL::InvalidInputRange("make_splrep_periodic: too few points for the degree"));
697    }
698    if s == 0.0 && t.is_none() {
699        let t = periodic_interp_knots(x, k);
700        let (c, _, fp, _) = periodic_fit(&data, &t, None);
701        return Ok((BSpline::new(t, periodic_full(&c, k), k)?, SplrepInfo { fp, converged: true }));
702    }
703    let acc = s * TOL;
704    let t: Vec<f64> = match t {
705        Some(t) => t.to_vec(),
706        None => periodic_knot_sequence(&data, options.nest)?.pop().expect("at least one knot vector"),
707    };
708    let (c0, diag, fpinf, _) = periodic_fit(&data, &t, None);
709    if t.len() == 2 * (k + 1) || fpinf - s >= -acc {
710        return Ok((BSpline::new(t.clone(), periodic_full(&c0, k), k)?, SplrepInfo { fp: fpinf, converged: fpinf <= s + acc }));
711    }
712    let n7 = t.len() - 2 * k - 1;
713    let per = data.xe - data.xb;
714    let m = data.m();
715    let tc: Vec<f64> = (0..=k).map(|i| x[0] - (k - i) as f64 * per).chain((0..=k).map(|i| x[m - 1] + i as f64 * per)).collect();
716    let (mut p1, mut f1) = (0.0, periodic_fit(&data, &tc, None).2 - s);
717    let (mut p3, mut f3) = (f64::INFINITY, fpinf - s);
718    let mut p = n7 as f64 / diag.iter().sum::<f64>();
719    let (con1, con4, con9) = (0.1, 0.04, 0.9);
720    let (mut ich1, mut ich3) = (false, false);
721    let mut last = (c0, fpinf);
722    let mut converged = false;
723    for _ in 0..MAXIT {
724        let (c, _, fp, _) = periodic_fit(&data, &t, Some(p));
725        let (p2, f2) = (p, fp - s);
726        last = (c, fp);
727        if f2.abs() < acc {
728            converged = true;
729            break;
730        }
731        if !ich3 {
732            if f2 - f3 <= acc {
733                (p3, f3) = (p2, f2);
734                p *= con4;
735                if p <= p1 {
736                    p = p1 * con9 + p2 * con1;
737                }
738                continue;
739            }
740            if f2 < 0.0 {
741                ich3 = true;
742            }
743        }
744        if !ich1 {
745            if f1 - f2 <= acc {
746                (p1, f1) = (p2, f2);
747                p /= con4;
748                if p3.is_finite() && p <= p3 {
749                    p = p2 * con1 + p3 * con9;
750                }
751                continue;
752            }
753            if f2 > 0.0 {
754                ich1 = true;
755            }
756        }
757        if f1 <= f2 || f2 <= f3 {
758            break;
759        }
760        p = fprati(p1, f1, p2, f2, p3, f3);
761        if f2 < 0.0 {
762            (p3, f3) = (p2, f2);
763        } else {
764            (p1, f1) = (p2, f2);
765        }
766    }
767    Ok((BSpline::new(t, periodic_full(&last.0, k), k)?, SplrepInfo { fp: last.1, converged }))
768}
769// ANCHOR_END: periodic
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774
775    fn noisy(m: usize) -> (Vec<f64>, Vec<f64>) {
776        // A deterministic pseudo-random sequence.
777        let mut state = 12345u64;
778        let x: Vec<f64> = (0..m).map(|i| -3.0 + 6.0 * i as f64 / (m - 1) as f64).collect();
779        let y = x
780            .iter()
781            .map(|&v| {
782                state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
783                let u = (state >> 11) as f64 / (1u64 << 53) as f64 - 0.5;
784                (-v * v).exp() + 0.2 * u
785            })
786            .collect();
787        (x, y)
788    }
789
790    #[test]
791    fn residual_meets_s_and_limits() {
792        let (x, y) = noisy(60);
793        for s in [0.05, 0.2, 0.5] {
794            let (spl, info) = make_splrep(&x, &y, None, &SplrepOptions { s, ..Default::default() }).unwrap();
795            assert!(info.converged, "s = {s}");
796            let fp: f64 = x.iter().zip(&y).map(|(&a, &b)| (b - spl.evaluate(a)).powi(2)).sum();
797            assert!((fp - s).abs() <= 1e-3 * s, "s = {s}: fp = {fp}");
798            assert!((info.fp - fp).abs() < 1e-12);
799        }
800        // A huge s gives the least-squares cubic polynomial: no interior knots.
801        let (spl, _) = make_splrep(&x, &y, None, &SplrepOptions { s: 1e6, ..Default::default() }).unwrap();
802        assert_eq!(spl.t.len(), 8);
803        // s = 0 interpolates.
804        let (spl, _) = make_splrep(&x, &y, None, &SplrepOptions::default()).unwrap();
805        assert!((spl.evaluate(x[17]) - y[17]).abs() < 1e-12);
806    }
807
808    #[test]
809    fn knot_sequence_grows_and_ends_with_the_used_knots() {
810        let (x, y) = noisy(50);
811        let opts = SplrepOptions { s: 0.1, ..Default::default() };
812        let seq = generate_knots(&x, &y, &opts).unwrap();
813        assert_eq!(seq[0].len(), 8);
814        assert!(seq.windows(2).all(|w| w[1].len() > w[0].len()));
815        let (spl, _) = make_splrep(&x, &y, None, &opts).unwrap();
816        assert_eq!(&spl.t, seq.last().unwrap());
817        // Knots are data points.
818        for v in &spl.t[4..spl.t.len() - 4] {
819            assert!(x.contains(v));
820        }
821    }
822
823    #[test]
824    fn parametric_curve_is_smoothed_jointly() {
825        let m = 40;
826        let pts: Vec<Vec<f64>> = (0..m)
827            .map(|i| {
828                let a = i as f64 * 6.0 / m as f64;
829                vec![a.cos() + 0.01 * (7.0 * a).sin(), a.sin() + 0.01 * (5.0 * a).cos()]
830            })
831            .collect();
832        let s = 0.002;
833        let (u, sp, info) = make_splprep(&pts, None, None, &SplrepOptions { s, ..Default::default() }).unwrap();
834        assert!(info.converged);
835        let fp: f64 = (0..m).map(|i| (0..2).map(|j| (pts[i][j] - sp[j].evaluate(u[i])).powi(2)).sum::<f64>()).sum();
836        assert!((fp - s).abs() <= 1e-3 * s, "{fp}");
837        assert_eq!(sp[0].t, sp[1].t);
838    }
839}
840
841#[cfg(test)]
842mod banded_check {
843    use super::Banded;
844    #[test]
845    fn normal_equations() {
846        let nc = 6;
847        let bw = 5;
848        let rows: Vec<(Vec<f64>, usize)> = vec![
849            (vec![1.0, 2.0, 0.5, 0.3], 0), (vec![0.2, 1.0, 0.7, 0.1], 1), (vec![0.3, 0.4, 1.0, 0.2], 2),
850            (vec![0.9, 0.1, 0.2, 0.6], 2), (vec![0.5, 0.5, 0.5, 0.5], 2), (vec![0.1, 0.3, 0.8, 0.4], 2),
851            (vec![1.0, -2.0, 3.0, -1.0, 0.5], 0), (vec![0.4, -1.0, 2.0, -3.0, 1.5], 1),
852        ];
853        let mut b = Banded::new(nc, bw, 1);
854        let mut ata = vec![vec![0.0; nc]; nc];
855        for (h, off) in &rows {
856            for (a, &u) in h.iter().enumerate() {
857                for (c, &v) in h.iter().enumerate() {
858                    ata[off + a][off + c] += u * v;
859                }
860            }
861            b.rotate_in(h.clone(), *off, vec![1.0]);
862        }
863        for i in 0..nc {
864            for j in 0..nc {
865                let mut s = 0.0;
866                for q in 0..nc {
867                    let rq = |r: usize, c: usize| if c >= r && c - r < bw { b.r[r][c - r] } else { 0.0 };
868                    s += rq(q, i) * rq(q, j);
869                }
870                assert!((s - ata[i][j]).abs() < 1e-12, "{i} {j}: {s} vs {}", ata[i][j]);
871            }
872        }
873    }
874}