Skip to main content

lib_jsl_interpolation/one_d/
smoothing_spline.rs

1//! The cubic smoothing spline (SciPy's `make_smoothing_spline`): the function `g` minimising
2//!
3//! `Σ wᵢ (yᵢ − g(xᵢ))² + λ ∫ g''(x)² dx`,
4//!
5//! which is a natural cubic spline with knots at the data. Large `λ` approaches the straight-line
6//! least-squares fit, `λ → 0` the interpolating natural spline. When `λ` is not given, it is
7//! chosen by generalised cross-validation (GCV).
8//!
9//! See the book entry [B-splines and smoothing splines](https://jwkunz.github.io/lib_jsl/book/interpolation/b-splines.html#smoothing-splines).
10
11use lib_jsl_core::ErrorsJSL;
12
13use super::b_spline::{BSpline, nonzero_basis, nonzero_basis_derivatives};
14
15/// The result of [`make_smoothing_spline`]: the spline and the smoothing parameter used.
16#[derive(Clone, Debug)]
17pub struct SmoothingSpline {
18    pub spline: BSpline,
19    /// `λ`, as given or as chosen by GCV.
20    pub lam: f64,
21    /// The trace of the influence matrix `A(λ)` (`ŷ = A y`): the effective number of parameters.
22    pub degrees_of_freedom: f64,
23}
24
25/// A symmetric positive-definite banded matrix with half-bandwidth 3, row `i` storing the
26/// entries `(i, i), (i, i+1), (i, i+2), (i, i+3)`.
27#[derive(Clone)]
28struct Band4 {
29    d: Vec<[f64; 4]>,
30}
31
32impl Band4 {
33    fn zeros(n: usize) -> Self {
34        Band4 { d: vec![[0.0; 4]; n] }
35    }
36    fn add(&mut self, i: usize, j: usize, v: f64) {
37        let (a, b) = if i <= j { (i, j) } else { (j, i) };
38        self.d[a][b - a] += v;
39    }
40    fn get(&self, i: usize, j: usize) -> f64 {
41        let (a, b) = if i <= j { (i, j) } else { (j, i) };
42        if b - a > 3 { 0.0 } else { self.d[a][b - a] }
43    }
44    fn lincomb(&self, lam: f64, other: &Band4) -> Band4 {
45        Band4 { d: self.d.iter().zip(&other.d).map(|(a, b)| std::array::from_fn(|k| a[k] + lam * b[k])).collect() }
46    }
47
48    // ANCHOR: ldl
49    /// `LDLᵀ` factorisation: returns the unit lower factor (`l[i][k]` = `L[i+k+1][i]`) and `D`.
50    fn ldl(&self) -> Result<(Vec<[f64; 3]>, Vec<f64>), ErrorsJSL> {
51        let n = self.d.len();
52        let mut l = vec![[0.0f64; 3]; n];
53        let mut dd = vec![0.0; n];
54        for j in 0..n {
55            let mut djj = self.get(j, j);
56            for k in j.saturating_sub(3)..j {
57                djj -= l[k][j - k - 1].powi(2) * dd[k];
58            }
59            if djj <= 0.0 || !djj.is_finite() {
60                return Err(ErrorsJSL::RuntimeError("the smoothing system is not positive definite"));
61            }
62            dd[j] = djj;
63            for i in j + 1..(j + 4).min(n) {
64                let mut v = self.get(i, j);
65                for k in i.saturating_sub(3)..j {
66                    v -= l[k][i - k - 1] * l[k][j - k - 1] * dd[k];
67                }
68                l[j][i - j - 1] = v / djj;
69            }
70        }
71        Ok((l, dd))
72    }
73    // ANCHOR_END: ldl
74}
75
76fn ldl_solve(l: &[[f64; 3]], d: &[f64], b: &[f64]) -> Vec<f64> {
77    let n = d.len();
78    let mut x = b.to_vec();
79    for i in 0..n {
80        for k in i.saturating_sub(3)..i {
81            x[i] -= l[k][i - k - 1] * x[k];
82        }
83    }
84    for i in 0..n {
85        x[i] /= d[i];
86    }
87    for i in (0..n).rev() {
88        for k in i + 1..(i + 4).min(n) {
89            x[i] -= l[i][k - i - 1] * x[k];
90        }
91    }
92    x
93}
94
95// ANCHOR: band_inverse
96/// The entries of `M⁻¹` within the band, from `M = L D Lᵀ`, by the recurrence of Hutchinson and
97/// de Hoog (1985): `Z = D⁻¹ L⁻¹ + (I − Lᵀ) Z`, run from the last row upwards, needs only entries of
98/// `Z` that are themselves in the band.
99fn band_of_inverse(l: &[[f64; 3]], d: &[f64]) -> Band4 {
100    let n = d.len();
101    let mut z = Band4::zeros(n);
102    for i in (0..n).rev() {
103        let reach = (i + 4).min(n);
104        for j in (i..reach).rev() {
105            let mut s = if i == j { 1.0 / d[i] } else { 0.0 };
106            for k in i + 1..reach {
107                s -= l[i][k - i - 1] * z.get(k, j);
108            }
109            z.d[i][j - i] = s;
110        }
111    }
112    z
113}
114// ANCHOR_END: band_inverse
115
116/// Bounded Brent minimisation, step for step as SciPy's `minimize_scalar(method='bounded')`
117/// (`fminbound`) with `xatol = 1e-5`.
118fn fminbound(f: impl Fn(f64) -> f64, x1: f64, x2: f64) -> f64 {
119    let xatol = 1e-5;
120    let sqrt_eps = 2.2e-16f64.sqrt();
121    let golden_mean = 0.5 * (3.0 - 5f64.sqrt());
122    let (mut a, mut b) = (x1, x2);
123    let mut fulc = a + golden_mean * (b - a);
124    let (mut nfc, mut xf) = (fulc, fulc);
125    let (mut rat, mut e) = (0.0f64, 0.0f64);
126    let mut fx = f(xf);
127    let mut num = 1;
128    let (mut ffulc, mut fnfc) = (fx, fx);
129    let mut xm = 0.5 * (a + b);
130    let mut tol1 = sqrt_eps * xf.abs() + xatol / 3.0;
131    let mut tol2 = 2.0 * tol1;
132    let sign = |v: f64| if v > 0.0 { 1.0 } else if v < 0.0 { -1.0 } else { 0.0 };
133    while (xf - xm).abs() > tol2 - 0.5 * (b - a) {
134        let mut golden = true;
135        if e.abs() > tol1 {
136            golden = false;
137            let mut r = (xf - nfc) * (fx - ffulc);
138            let mut q = (xf - fulc) * (fx - fnfc);
139            let mut p = (xf - fulc) * q - (xf - nfc) * r;
140            q = 2.0 * (q - r);
141            if q > 0.0 {
142                p = -p;
143            }
144            q = q.abs();
145            r = e;
146            e = rat;
147            if p.abs() < (0.5 * q * r).abs() && p > q * (a - xf) && p < q * (b - xf) {
148                rat = p / q;
149                let x = xf + rat;
150                if (x - a) < tol2 || (b - x) < tol2 {
151                    let si = sign(xm - xf) + if xm - xf == 0.0 { 1.0 } else { 0.0 };
152                    rat = tol1 * si;
153                }
154            } else {
155                golden = true;
156            }
157        }
158        if golden {
159            e = if xf >= xm { a - xf } else { b - xf };
160            rat = golden_mean * e;
161        }
162        let si = sign(rat) + if rat == 0.0 { 1.0 } else { 0.0 };
163        let x = xf + si * rat.abs().max(tol1);
164        let fu = f(x);
165        num += 1;
166        if fu <= fx {
167            if x >= xf {
168                a = xf;
169            } else {
170                b = xf;
171            }
172            (fulc, ffulc) = (nfc, fnfc);
173            (nfc, fnfc) = (xf, fx);
174            (xf, fx) = (x, fu);
175        } else {
176            if x < xf {
177                a = x;
178            } else {
179                b = x;
180            }
181            if fu <= fnfc || nfc == xf {
182                (fulc, ffulc) = (nfc, fnfc);
183                (nfc, fnfc) = (x, fu);
184            } else if fu <= ffulc || fulc == xf || fulc == nfc {
185                (fulc, ffulc) = (x, fu);
186            }
187        }
188        xm = 0.5 * (a + b);
189        tol1 = sqrt_eps * xf.abs() + xatol / 3.0;
190        tol2 = 2.0 * tol1;
191        if num >= 500 {
192            break;
193        }
194    }
195    xf
196}
197
198// ANCHOR: smoothing
199/// The cubic smoothing spline of `(x, y)` with weights `w` (default 1) and smoothing parameter
200/// `lam` (SciPy's `make_smoothing_spline`). Without `lam`, the parameter minimising the GCV
201/// score `n ‖y − ŷ‖² / (n − tr A(λ))²` over `0 < λ < n` is used, found by the same bounded Brent
202/// search as SciPy.
203///
204/// In the cubic B-spline basis with knots `x` (ends repeated four times), the coefficients solve
205/// `(Bᵀ W B + λ Ω) c = Bᵀ W y`, where `Bᵢⱼ = Bⱼ(xᵢ)` and `Ωᵢⱼ = ∫ Bᵢ'' Bⱼ''`, restricted to natural
206/// splines by eliminating the two end coefficients. The matrices have half-bandwidth 3, so each
207/// solve costs `O(n)`, as does the trace of the influence matrix, from the band of the inverse.
208pub fn make_smoothing_spline(x: &[f64], y: &[f64], w: Option<&[f64]>, lam: Option<f64>) -> Result<SmoothingSpline, ErrorsJSL> {
209    let n = x.len();
210    if y.len() != n {
211        return Err(ErrorsJSL::IncompatibleArraySizes((y.len(), n)));
212    }
213    if n < 5 {
214        return Err(ErrorsJSL::InvalidInputRange("need at least five points"));
215    }
216    if x.windows(2).any(|p| p[1] <= p[0]) || x.iter().chain(y).any(|v| !v.is_finite()) {
217        return Err(ErrorsJSL::InvalidInputRange("x must be strictly increasing and the data finite"));
218    }
219    let ones = vec![1.0; n];
220    let w = w.unwrap_or(&ones);
221    if w.len() != n || w.iter().any(|&v| v <= 0.0 || !v.is_finite()) {
222        return Err(ErrorsJSL::InvalidInputRange("weights must be positive, one per point"));
223    }
224    if let Some(l) = lam
225        && (l < 0.0 || !l.is_finite())
226    {
227        return Err(ErrorsJSL::InvalidInputRange("the smoothing parameter must be non-negative"));
228    }
229    let mut t = vec![x[0]; 3];
230    t.extend_from_slice(x);
231    t.extend([x[n - 1]; 3]);
232    let m = n + 2;
233    // Bᵀ W B and Bᵀ W y: data point i lies in knot interval l = i + 3 (the last in l = n + 1).
234    let mut btwb = Band4::zeros(m);
235    let mut btwy = vec![0.0; m];
236    let mut rows = Vec::with_capacity(n);
237    for i in 0..n {
238        let l = (i + 3).min(n + 1);
239        let b = nonzero_basis(&t, 3, l, x[i]);
240        for r in 0..4 {
241            btwy[l - 3 + r] += w[i] * b[r] * y[i];
242            for s in r..4 {
243                btwb.add(l - 3 + r, l - 3 + s, w[i] * b[r] * b[s]);
244            }
245        }
246        rows.push((l - 3, b));
247    }
248    // Ω: B'' is linear on each interval, so two-point Gauss-Legendre integrates the products exactly.
249    let mut omega = Band4::zeros(m);
250    let g = 1.0 / 3f64.sqrt();
251    for i in 0..n - 1 {
252        let (a, b) = (x[i], x[i + 1]);
253        let l = i + 3;
254        for s in [-g, g] {
255            let u = 0.5 * (a + b) + 0.5 * s * (b - a);
256            let d2 = nonzero_basis_derivatives(&t, 3, l, u, 2);
257            for r in 0..4 {
258                for q in r..4 {
259                    omega.add(l - 3 + r, l - 3 + q, d2[r] * d2[q] * 0.5 * (b - a));
260                }
261            }
262        }
263    }
264    // The minimiser is a natural spline, s'' = 0 at both ends. Eliminating c₀ and c_{m−1} with
265    // these two conditions, c = T a, leaves n unknowns a = (c₁, …, c_{m−2}) and a system that is
266    // positive definite even for λ = 0.
267    let d0 = nonzero_basis_derivatives(&t, 3, 3, x[0], 2);
268    let dn = nonzero_basis_derivatives(&t, 3, n + 1, x[n - 1], 2);
269    let (alpha1, alpha2) = (-d0[1] / d0[0], -d0[2] / d0[0]);
270    let (beta1, beta2) = (-dn[2] / dn[3], -dn[1] / dn[3]);
271    // Column p of T: (row, value) pairs.
272    let tcol = |p: usize| -> Vec<(usize, f64)> {
273        let mut v = vec![(p + 1, 1.0)];
274        if p == 0 {
275            v.push((0, alpha1));
276        }
277        if p == 1 {
278            v.push((0, alpha2));
279        }
280        if p == n - 1 {
281            v.push((m - 1, beta1));
282        }
283        if p == n - 2 {
284            v.push((m - 1, beta2));
285        }
286        v
287    };
288    let reduce = |xm: &Band4| -> Band4 {
289        let mut r = Band4::zeros(n);
290        for p in 0..n {
291            for q in p..(p + 4).min(n) {
292                let mut v = 0.0;
293                for &(rr, tp) in &tcol(p) {
294                    for &(ss, tq) in &tcol(q) {
295                        v += tp * tq * xm.get(rr, ss);
296                    }
297                }
298                r.d[p][q - p] = v;
299            }
300        }
301        r
302    };
303    let (btwb_r, omega_r) = (reduce(&btwb), reduce(&omega));
304    let btwy_r: Vec<f64> = (0..n).map(|p| tcol(p).iter().map(|&(r, v)| v * btwy[r]).sum()).collect();
305    let expand = |a: &[f64]| -> Vec<f64> {
306        let mut c = vec![0.0; m];
307        c[1..m - 1].copy_from_slice(a);
308        c[0] = alpha1 * a[0] + alpha2 * a[1];
309        c[m - 1] = beta1 * a[n - 1] + beta2 * a[n - 2];
310        c
311    };
312    let solve = |lam: f64| -> Result<(Vec<f64>, f64), ErrorsJSL> {
313        let mat = btwb_r.lincomb(lam, &omega_r);
314        let (l, d) = mat.ldl()?;
315        let c = expand(&ldl_solve(&l, &d, &btwy_r));
316        // tr A = tr(M⁻¹ Tᵀ Bᵀ W B T), using only the band of M⁻¹.
317        let z = band_of_inverse(&l, &d);
318        let mut trace = 0.0;
319        for i in 0..n {
320            for j in i..(i + 4).min(n) {
321                let v = z.get(i, j) * btwb_r.get(j, i);
322                trace += if i == j { v } else { 2.0 * v };
323            }
324        }
325        Ok((c, trace))
326    };
327    let lam = match lam {
328        Some(l) => l,
329        None => {
330            let gcv = |lam: f64| -> f64 {
331                let Ok((c, trace)) = solve(lam) else { return f64::INFINITY };
332                let rss: f64 = rows.iter().zip(y).map(|((c0, b), &yi)| (yi - b.iter().enumerate().map(|(r, v)| c[c0 + r] * v).sum::<f64>()).powi(2)).sum();
333                (rss / n as f64) / (1.0 - trace / n as f64).powi(2)
334            };
335            fminbound(gcv, 0.0, n as f64)
336        }
337    };
338    let (c, trace) = solve(lam)?;
339    Ok(SmoothingSpline { spline: BSpline::new(t, c, 3)?, lam, degrees_of_freedom: trace })
340}
341// ANCHOR_END: smoothing
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    #[test]
348    fn extreme_smoothing_gives_the_regression_line_and_none_interpolates() {
349        let x: Vec<f64> = (0..20).map(|i| i as f64 * 0.3 + (i as f64 * 0.7).sin() * 0.05).collect();
350        let y: Vec<f64> = x.iter().map(|v| v.sin() + 0.5 * v).collect();
351        let interp = make_smoothing_spline(&x, &y, None, Some(0.0)).unwrap();
352        for (xi, yi) in x.iter().zip(&y) {
353            assert!((interp.spline.evaluate(*xi) - yi).abs() < 1e-9);
354        }
355        assert!((interp.degrees_of_freedom - 20.0).abs() < 1e-6);
356        let line = make_smoothing_spline(&x, &y, None, Some(1e8)).unwrap();
357        assert!((line.degrees_of_freedom - 2.0).abs() < 1e-3);
358        assert!(line.spline.evaluate_derivative(1.7, 2).abs() < 1e-6);
359    }
360
361    #[test]
362    #[allow(clippy::needless_range_loop)]
363    fn band_of_inverse_matches_a_dense_inverse() {
364        let n = 9;
365        let mut m = Band4::zeros(n);
366        for i in 0..n {
367            m.add(i, i, 4.0 + i as f64 * 0.1);
368            for k in 1..4 {
369                if i + k < n {
370                    m.add(i, i + k, 0.5 / k as f64);
371                }
372            }
373        }
374        let (l, d) = m.ldl().unwrap();
375        let z = band_of_inverse(&l, &d);
376        // Column j of the inverse by solving with e_j.
377        for j in 0..n {
378            let mut e = vec![0.0; n];
379            e[j] = 1.0;
380            let col = ldl_solve(&l, &d, &e);
381            for i in j.saturating_sub(3)..(j + 4).min(n) {
382                assert!((z.get(i, j) - col[i]).abs() < 1e-14);
383            }
384        }
385    }
386}