Skip to main content

lib_jsl_interpolation/two_d/
smooth_bivariate.rs

1//! Smoothing spline surfaces for scattered data (SciPy's `bisplrep` / `bisplev` and
2//! `SmoothBivariateSpline`, `LSQBivariateSpline`).
3//!
4//! See the book entry [FITPACK smoothing splines](https://jwkunz.github.io/lib_jsl/book/interpolation/fitpack.html#periodic-splines-and-smoothing-surfaces).
5
6use crate::one_d::b_spline::nonzero_basis;
7use crate::one_d::fitpack::{discontinuity_jumps, fprati};
8use lib_jsl_core::ErrorsJSL;
9
10/// A tensor-product spline surface `s(x, y) = Σᵢⱼ c[i][j] Bᵢ(x) Bⱼ(y)` (SciPy's `tck` from
11/// `bisplrep`), with the weighted sum of squared residuals of its fit.
12#[derive(Clone, Debug)]
13#[non_exhaustive]
14pub struct SmoothBivariateSpline {
15    pub tx: Vec<f64>,
16    pub ty: Vec<f64>,
17    pub kx: usize,
18    pub ky: usize,
19    /// `c[i][j]` for `i < nx − kx − 1`, `j < ny − ky − 1`.
20    pub c: Vec<Vec<f64>>,
21    pub fp: f64,
22}
23
24fn interval(t: &[f64], k: usize, v: f64) -> usize {
25    let n = t.len();
26    let mut l = k;
27    while l < n - k - 2 && v >= t[l + 1] {
28        l += 1;
29    }
30    l
31}
32
33impl SmoothBivariateSpline {
34    /// The surface's value (SciPy's `bisplev` at one point). Outside the knot span the
35    /// arguments are clamped to it, as FITPACK's `fpbisp` does.
36    pub fn evaluate(&self, x: f64, y: f64) -> f64 {
37        let (nx, ny) = (self.tx.len(), self.ty.len());
38        let x = x.clamp(self.tx[self.kx], self.tx[nx - self.kx - 1]);
39        let y = y.clamp(self.ty[self.ky], self.ty[ny - self.ky - 1]);
40        let (lx, ly) = (interval(&self.tx, self.kx, x), interval(&self.ty, self.ky, y));
41        let bx = nonzero_basis(&self.tx, self.kx, lx, x);
42        let by = nonzero_basis(&self.ty, self.ky, ly, y);
43        let mut s = 0.0;
44        for (a, u) in bx.iter().enumerate() {
45            for (b, v) in by.iter().enumerate() {
46                s += u * v * self.c[lx - self.kx + a][ly - self.ky + b];
47            }
48        }
49        s
50    }
51
52    /// Values on the grid `x × y` (SciPy's `bisplev` with arrays): `out[i][j] = s(xᵢ, yⱼ)`.
53    pub fn evaluate_grid(&self, x: &[f64], y: &[f64]) -> Vec<Vec<f64>> {
54        x.iter().map(|&a| y.iter().map(|&b| self.evaluate(a, b)).collect()).collect()
55    }
56}
57
58/// Dense Householder least squares (the problem sizes are a few hundred unknowns).
59#[allow(clippy::needless_range_loop)]
60fn dense_lsq(mut a: Vec<Vec<f64>>, mut b: Vec<f64>, nc: usize) -> (Vec<f64>, f64) {
61    let m = a.len();
62    for j in 0..nc.min(m) {
63        let norm: f64 = (j..m).map(|i| a[i][j] * a[i][j]).sum::<f64>().sqrt();
64        if norm == 0.0 {
65            continue;
66        }
67        let alpha = if a[j][j] > 0.0 { -norm } else { norm };
68        let mut v: Vec<f64> = (j..m).map(|i| a[i][j]).collect();
69        v[0] -= alpha;
70        let vn: f64 = v.iter().map(|x| x * x).sum();
71        if vn == 0.0 {
72            continue;
73        }
74        for col in j..nc {
75            let s: f64 = (j..m).map(|i| v[i - j] * a[i][col]).sum::<f64>() * 2.0 / vn;
76            if s != 0.0 {
77                for i in j..m {
78                    a[i][col] -= s * v[i - j];
79                }
80            }
81        }
82        let s: f64 = (j..m).map(|i| v[i - j] * b[i]).sum::<f64>() * 2.0 / vn;
83        for i in j..m {
84            b[i] -= s * v[i - j];
85        }
86    }
87    let scale = (0..nc.min(m)).map(|i| a[i][i].abs()).fold(0.0f64, f64::max);
88    let mut c = vec![0.0; nc];
89    for i in (0..nc.min(m)).rev() {
90        // Rank deficiency (a panel without data): leave that coefficient at zero, as FITPACK's
91        // minimum-norm treatment does for negligible pivots.
92        if a[i][i].abs() <= 1e-12 * scale {
93            continue;
94        }
95        let s: f64 = (i + 1..nc).map(|j| a[i][j] * c[j]).sum();
96        c[i] = (b[i] - s) / a[i][i];
97    }
98    // The sum of the diagonal of R: FITPACK's scale for the first smoothing weight.
99    let diag = (0..nc.min(m)).map(|i| a[i][i].abs()).sum();
100    (c, diag)
101}
102
103struct Scattered<'a> {
104    x: &'a [f64],
105    y: &'a [f64],
106    z: &'a [f64],
107    w: Vec<f64>,
108    kx: usize,
109    ky: usize,
110}
111
112/// The fit on knots `tx`, `ty` with the jump penalty weighted by `1/p` (`None`: least squares).
113fn fit(d: &Scattered, tx: &[f64], ty: &[f64], p: Option<f64>) -> (SmoothBivariateSpline, Vec<f64>, f64) {
114    let (kx, ky) = (d.kx, d.ky);
115    let (ncx, ncy) = (tx.len() - kx - 1, ty.len() - ky - 1);
116    let nc = ncx * ncy;
117    let mut rows = Vec::with_capacity(d.x.len());
118    let mut rhs = Vec::new();
119    for i in 0..d.x.len() {
120        let (lx, ly) = (interval(tx, kx, d.x[i]), interval(ty, ky, d.y[i]));
121        let bx = nonzero_basis(tx, kx, lx, d.x[i]);
122        let by = nonzero_basis(ty, ky, ly, d.y[i]);
123        let mut row = vec![0.0; nc];
124        for (a, u) in bx.iter().enumerate() {
125            for (b, v) in by.iter().enumerate() {
126                row[(lx - kx + a) * ncy + ly - ky + b] = u * v * d.w[i];
127            }
128        }
129        rows.push(row);
130        rhs.push(d.z[i] * d.w[i]);
131    }
132    if let Some(p) = p {
133        // Jumps of the kx-th x-derivative across interior x knots, for every y coefficient, and
134        // likewise in y (FITPACK's surfit penalty).
135        if tx.len() > 2 * kx + 2 {
136            for jump in discontinuity_jumps(tx, kx).iter().enumerate() {
137                for j in 0..ncy {
138                    let mut row = vec![0.0; nc];
139                    for (r, v) in jump.1.iter().enumerate() {
140                        row[(jump.0 + r) * ncy + j] = v / p;
141                    }
142                    rows.push(row);
143                    rhs.push(0.0);
144                }
145            }
146        }
147        if ty.len() > 2 * ky + 2 {
148            for jump in discontinuity_jumps(ty, ky).iter().enumerate() {
149                for i in 0..ncx {
150                    let mut row = vec![0.0; nc];
151                    for (r, v) in jump.1.iter().enumerate() {
152                        row[i * ncy + jump.0 + r] = v / p;
153                    }
154                    rows.push(row);
155                    rhs.push(0.0);
156                }
157            }
158        }
159    }
160    let (flat, diag) = dense_lsq(rows, rhs, nc);
161    let c: Vec<Vec<f64>> = flat.chunks(ncy).map(|r| r.to_vec()).collect();
162    let mut spl = SmoothBivariateSpline { tx: tx.to_vec(), ty: ty.to_vec(), kx, ky, c, fp: 0.0 };
163    let res: Vec<f64> = (0..d.x.len()).map(|i| (d.w[i] * (d.z[i] - spl.evaluate(d.x[i], d.y[i]))).powi(2)).collect();
164    spl.fp = res.iter().sum();
165    (spl, res, diag)
166}
167
168fn validate<'a>(x: &'a [f64], y: &'a [f64], z: &'a [f64], w: Option<&[f64]>, kx: usize, ky: usize) -> Result<Scattered<'a>, ErrorsJSL> {
169    let m = x.len();
170    if y.len() != m || z.len() != m {
171        return Err(ErrorsJSL::IncompatibleArraySizes((y.len().min(z.len()), m)));
172    }
173    if !(1..=5).contains(&kx) || !(1..=5).contains(&ky) || m < (kx + 1) * (ky + 1) {
174        return Err(ErrorsJSL::InvalidInputRange("bisplrep: need 1 ≤ kx, ky ≤ 5 and at least (kx+1)(ky+1) points"));
175    }
176    let w = match w {
177        Some(w) if w.len() != m => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), m))),
178        Some(w) => w.to_vec(),
179        None => vec![1.0; m],
180    };
181    Ok(Scattered { x, y, z, w, kx, ky })
182}
183
184// ANCHOR: bisplrep_lsq
185/// The weighted least-squares spline surface on given knots (SciPy's `bisplrep(task=-1)` and
186/// `LSQBivariateSpline`). As in FITPACK, only the interior knots of `tx` and `ty` are used: the
187/// `k + 1` boundary knots at each end are placed at the data's range (SciPy's default `xb`, `xe`,
188/// `yb`, `ye`). Coefficients that no data point influences are set to zero.
189#[allow(clippy::too_many_arguments)]
190pub fn bisplrep_lsq(x: &[f64], y: &[f64], z: &[f64], w: Option<&[f64]>, tx: &[f64], ty: &[f64], kx: usize, ky: usize) -> Result<SmoothBivariateSpline, ErrorsJSL> {
191    let d = validate(x, y, z, w, kx, ky)?;
192    if tx.len() < 2 * kx + 2 || ty.len() < 2 * ky + 2 {
193        return Err(ErrorsJSL::InvalidInputRange("bisplrep_lsq: need at least 2k + 2 knots in each direction"));
194    }
195    let ends = |t: &[f64], k: usize, v: &[f64]| -> Vec<f64> {
196        let (b, e) = (v.iter().copied().fold(f64::INFINITY, f64::min), v.iter().copied().fold(f64::NEG_INFINITY, f64::max));
197        std::iter::repeat_n(b, k + 1).chain(t[k + 1..t.len() - k - 1].iter().copied()).chain(std::iter::repeat_n(e, k + 1)).collect()
198    };
199    Ok(fit(&d, &ends(tx, kx, x), &ends(ty, ky, y), None).0)
200}
201// ANCHOR_END: bisplrep_lsq
202
203// ANCHOR: bisplrep
204/// A smoothing spline surface through scattered data with automatically placed knots (SciPy's
205/// `bisplrep` / `SmoothBivariateSpline`, after FITPACK's `surfit`): of the splines with
206/// `Σ (wᵢ (zᵢ − s(xᵢ, yᵢ)))² ≤ smoothing`, the one whose `kx`-th x- and `ky`-th y-derivatives
207/// jump least across the knots. `smoothing = None` gives SciPy's default `m − √(2m)`.
208///
209/// Starting from a single polynomial patch, one knot at a time is added in the direction (x or y)
210/// whose largest interval residual sum is the larger, at the residual-weighted mean coordinate of the
211/// points in that interval (FITPACK's rule, which SciPy follows to the digit), until the
212/// least-squares surface reaches the smoothing target or `nxest`, `nyest` knots (SciPy's
213/// defaults); then the penalty weight `p` is found by FITPACK's rational iteration so that the
214/// residual sum equals the target.
215#[allow(clippy::too_many_arguments)]
216pub fn bisplrep(x: &[f64], y: &[f64], z: &[f64], w: Option<&[f64]>, kx: usize, ky: usize, smoothing: Option<f64>) -> Result<SmoothBivariateSpline, ErrorsJSL> {
217    let d = validate(x, y, z, w, kx, ky)?;
218    let m = x.len() as f64;
219    let s = smoothing.unwrap_or(m - (2.0 * m).sqrt());
220    let acc = 0.001 * s;
221    let (xb, xe) = (x.iter().copied().fold(f64::INFINITY, f64::min), x.iter().copied().fold(f64::NEG_INFINITY, f64::max));
222    let (yb, ye) = (y.iter().copied().fold(f64::INFINITY, f64::min), y.iter().copied().fold(f64::NEG_INFINITY, f64::max));
223    let nxest = ((kx as f64 + (m / 2.0).sqrt()) as usize).max(2 * kx + 3);
224    let nyest = ((ky as f64 + (m / 2.0).sqrt()) as usize).max(2 * ky + 3);
225    let ends = |b: f64, e: f64, k: usize| -> Vec<f64> { std::iter::repeat_n(b, k + 1).chain(std::iter::repeat_n(e, k + 1)).collect() };
226    let (mut tx, mut ty) = (ends(xb, xe, kx), ends(yb, ye, ky));
227    let (mut spl, mut res, mut rdiag) = fit(&d, &tx, &ty, None);
228    let poly_fp = spl.fp;
229    while spl.fp > s + acc && (tx.len() < nxest || ty.len() < nyest) {
230        // FITPACK's `fpsurf`: the sum of squared residuals in every x-interval and every y-interval
231        // (a point on a knot belongs to the interval to its right); the direction whose largest
232        // interval sum is the larger gets the next knot (x on a tie, and whichever has room), and the
233        // knot goes to the residual-weighted mean coordinate of the points in that interval.
234        let (px, py) = (tx.len() - 2 * kx - 1, ty.len() - 2 * ky - 1);
235        let (mut sx, mut sy) = (vec![0.0; px], vec![0.0; py]);
236        let (mut mx, mut my) = (vec![0.0; px], vec![0.0; py]);
237        for i in 0..x.len() {
238            let (lx, ly) = (interval(&tx, kx, x[i]) - kx, interval(&ty, ky, y[i]) - ky);
239            sx[lx] += res[i];
240            sy[ly] += res[i];
241            mx[lx] += res[i] * x[i];
242            my[ly] += res[i] * y[i];
243        }
244        let argmax = |v: &[f64]| (0..v.len()).fold(0, |b, i| if v[i] > v[b] { i } else { b });
245        let (jx, jy) = (argmax(&sx), argmax(&sy));
246        let (can_x, can_y) = (tx.len() < nxest, ty.len() < nyest);
247        let in_x = match (can_x, can_y) {
248            (true, true) => sx[jx] >= sy[jy],
249            (true, false) => true,
250            _ => false,
251        };
252        let (t, k, j, sums, moments) = if in_x { (&mut tx, kx, jx, &sx, &mx) } else { (&mut ty, ky, jy, &sy, &my) };
253        let (lo, hi) = (t[j + k], t[j + k + 1]);
254        let knot = if sums[j] > 0.0 { moments[j] / sums[j] } else { 0.5 * (lo + hi) };
255        if !(knot > lo && knot < hi) {
256            break;
257        }
258        t.insert(j + k + 1, knot);
259        (spl, res, rdiag) = fit(&d, &tx, &ty, None);
260    }
261    // A single polynomial patch, a fit already at the target, or a least-squares surface that
262    // cannot reach it: nothing to smooth.
263    if (spl.fp - s).abs() < acc || (tx.len() == 2 * kx + 2 && ty.len() == 2 * ky + 2) || spl.fp > s {
264        return Ok(spl);
265    }
266    // Rational iteration on p for fp(p) = s, between the polynomial (p = 0) and the
267    // least-squares surface (p = ∞).
268    let (mut p1, mut f1) = (0.0, poly_fp - s);
269    let (mut p3, mut f3) = (f64::INFINITY, spl.fp - s);
270    // FITPACK's first weight: the number of coefficients over the sum of the diagonal of R.
271    let mut p = ((tx.len() - kx - 1) * (ty.len() - ky - 1)) as f64 / rdiag;
272    let (con1, con4, con9) = (0.1, 0.04, 0.9);
273    let (mut ich1, mut ich3) = (false, false);
274    let mut best = spl;
275    for _ in 0..40 {
276        let (cand, _, _) = fit(&d, &tx, &ty, Some(p));
277        let (p2, f2) = (p, cand.fp - s);
278        best = cand;
279        if f2.abs() < acc {
280            break;
281        }
282        if !ich3 {
283            if f2 - f3 <= acc {
284                (p3, f3) = (p2, f2);
285                p *= con4;
286                if p <= p1 {
287                    p = p1 * con9 + p2 * con1;
288                }
289                continue;
290            }
291            if f2 < 0.0 {
292                ich3 = true;
293            }
294        }
295        if !ich1 {
296            if f1 - f2 <= acc {
297                (p1, f1) = (p2, f2);
298                p /= con4;
299                if p3.is_finite() && p <= p3 {
300                    p = p2 * con1 + p3 * con9;
301                }
302                continue;
303            }
304            if f2 > 0.0 {
305                ich1 = true;
306            }
307        }
308        if f1 <= f2 || f2 <= f3 {
309            break;
310        }
311        p = fprati(p1, f1, p2, f2, p3, f3);
312        if f2 < 0.0 {
313            (p3, f3) = (p2, f2);
314        } else {
315            (p1, f1) = (p2, f2);
316        }
317    }
318    Ok(best)
319}
320// ANCHOR_END: bisplrep
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn reproduces_a_bicubic_and_smooths_noise() {
328        let mut s = 3u64;
329        let mut next = || {
330            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
331            (s >> 11) as f64 / (1u64 << 53) as f64
332        };
333        let n = 300;
334        let x: Vec<f64> = (0..n).map(|_| next()).collect();
335        let y: Vec<f64> = (0..n).map(|_| next()).collect();
336        let cubic = |a: f64, b: f64| 1.0 + a - 2.0 * b + a * a * b - 0.5 * b.powi(3) + a.powi(3) * b * b;
337        let z: Vec<f64> = x.iter().zip(&y).map(|(&a, &b)| cubic(a, b)).collect();
338        let t = vec![0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0];
339        let spl = bisplrep_lsq(&x, &y, &z, None, &t, &t, 3, 3).unwrap();
340        assert!(spl.fp < 1e-20 && (spl.evaluate(0.3, 0.7) - cubic(0.3, 0.7)).abs() < 1e-12, "{}", spl.fp);
341        let zn: Vec<f64> = x.iter().zip(&y).map(|(&a, &b)| (6.0 * a).sin() * (4.0 * b).cos() + 0.05 * (next() - 0.5)).collect();
342        let target = n as f64 * 0.05f64.powi(2) / 12.0;
343        let spl = bisplrep(&x, &y, &zn, None, 3, 3, Some(target)).unwrap();
344        assert!((spl.fp - target).abs() <= 0.002 * target + 1e-12, "{} {}", spl.fp, target);
345        assert!(((spl.evaluate(0.5, 0.5) - (3.0f64).sin() * (2.0f64).cos()).abs()) < 0.05);
346    }
347
348    /// Data from a generator that SciPy's reference was computed on (an LCG: 200 points of
349    /// sin 5x cos 3y plus noise of width 0.05).
350    fn lcg_surface() -> (Vec<f64>, Vec<f64>, Vec<f64>) {
351        let mut s = 7u64;
352        let mut next = || {
353            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
354            (s >> 11) as f64 / (1u64 << 53) as f64
355        };
356        let n = 200;
357        let x: Vec<f64> = (0..n).map(|_| next()).collect();
358        let y: Vec<f64> = (0..n).map(|_| next()).collect();
359        let z: Vec<f64> = x.iter().zip(&y).map(|(&a, &b)| (5.0 * a).sin() * (3.0 * b).cos() + 0.05 * (next() - 0.5)).collect();
360        (x, y, z)
361    }
362
363    #[test]
364    fn knots_and_surface_follow_fitpack_as_scipy_does() {
365        let (x, y, z) = lcg_surface();
366        // s = 0.02 is below what the 9 × 9 knot limit reaches: SciPy stops there (ier = 1).
367        let spl = bisplrep(&x, &y, &z, None, 3, 3, Some(0.02)).unwrap();
368        let (tx, ty) = (&spl.tx[4..spl.tx.len() - 4], &spl.ty[4..spl.ty.len() - 4]);
369        let want_x = [0.19917084743330554, 0.3417052585308804, 0.5173093370615343, 0.6641207370914128, 0.8385316530076271];
370        let want_y = [0.29303659466163023, 0.3918309983390825, 0.5102358397728622, 0.6515560362828349, 0.754806417992293];
371        assert_eq!((tx.len(), ty.len()), (5, 5));
372        for (a, b) in tx.iter().zip(want_x).chain(ty.iter().zip(want_y)) {
373            assert!((a - b).abs() < 1e-12, "{a} {b}");
374        }
375        assert!((spl.fp - 0.02283291320245356).abs() < 1e-10, "{}", spl.fp);
376        assert!((spl.evaluate(0.3, 0.6) + 0.22400545921059226).abs() < 1e-9 && (spl.evaluate(0.8, 0.2) + 0.6072041685894835).abs() < 1e-9);
377        // Smoothing targets above the 1 × 0 knot fit's: one x knot, and the penalty weight solved for.
378        for (target, v1, v2) in [(0.04, -0.22275695099777734, -0.6213830675469628), (0.06, -0.22350270349140217, -0.611438006040347)] {
379            let spl = bisplrep(&x, &y, &z, None, 3, 3, Some(target)).unwrap();
380            assert_eq!((spl.tx.len(), spl.ty.len()), (9, 8), "{target}");
381            assert!((spl.tx[4] - 0.3417052585308804).abs() < 1e-12);
382            assert!((spl.fp - target).abs() <= 0.001 * target + 1e-9, "{} {}", spl.fp, target);
383            assert!((spl.evaluate(0.3, 0.6) - v1).abs() < 1e-4 && (spl.evaluate(0.8, 0.2) - v2).abs() < 1e-4, "{target}");
384        }
385    }
386}