Skip to main content

lib_jsl_interpolation/two_d/
rect_bivariate_spline.rs

1//! Tensor-product interpolating splines on a rectangular grid (SciPy's `RectBivariateSpline`
2//! with `s = 0`): `s(x, y) = Σᵢ Σⱼ cᵢⱼ Bᵢ,ₖₓ(x) Bⱼ,ₖᵧ(y)`, with values, partial derivatives and
3//! integrals over rectangles.
4//!
5//! See the book entry [Piecewise polynomials, Hermite data and scattered interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/piecewise-scattered.html#tensor-product-splines).
6
7use crate::one_d::b_spline::{BSpline, BoundaryCondition, make_interp_spline, nonzero_basis, nonzero_basis_derivatives};
8use lib_jsl_core::ErrorsJSL;
9use ndarray::Array2;
10
11/// An interpolating spline of degrees `kx` and `ky` (odd: 1, 3 or 5) through `z[i][j] = f(xᵢ, yⱼ)`.
12#[derive(Clone, Debug, PartialEq)]
13pub struct RectBivariateSpline {
14    tx: Vec<f64>,
15    ty: Vec<f64>,
16    kx: usize,
17    ky: usize,
18    /// Coefficients, shape `(nx, ny)`.
19    c: Array2<f64>,
20}
21
22fn interval(t: &[f64], k: usize, n: usize, v: f64) -> usize {
23    match t[k..=n].partition_point(|&a| a <= v) {
24        0 => k,
25        p => (k + p - 1).min(n - 1),
26    }
27}
28
29impl RectBivariateSpline {
30    // ANCHOR: rect_bivariate
31    /// Fits the spline. With `s = 0` FITPACK places the interior knots at the data points except
32    /// `(k + 1)/2` at each end, which for odd `k` is the not-a-knot spline; the separable system
33    /// `Aₓ C Aᵧᵀ = Z` is solved one axis at a time: interpolate every column of `Z` along `x`,
34    /// then every row of the result along `y`.
35    pub fn new(x: &[f64], y: &[f64], z: &Array2<f64>, kx: usize, ky: usize) -> Result<RectBivariateSpline, ErrorsJSL> {
36        if z.dim() != (x.len(), y.len()) {
37            return Err(ErrorsJSL::InvalidInputRange("z must have shape (len(x), len(y))"));
38        }
39        for k in [kx, ky] {
40            if k % 2 == 0 || k > 5 {
41                return Err(ErrorsJSL::InvalidInputRange("degrees must be 1, 3 or 5 (FITPACK places even-degree knots differently)"));
42            }
43        }
44        if x.len() <= kx || y.len() <= ky {
45            return Err(ErrorsJSL::InvalidInputRange("need more than k points along each axis"));
46        }
47        let (nx, ny) = (x.len(), y.len());
48        let mut along_x = Array2::zeros((nx, ny));
49        let mut tx = Vec::new();
50        for j in 0..ny {
51            let col: Vec<f64> = z.column(j).to_vec();
52            let s = make_interp_spline(x, &col, kx, &BoundaryCondition::NotAKnot)?;
53            for i in 0..nx {
54                along_x[(i, j)] = s.c[i];
55            }
56            tx = s.t;
57        }
58        let mut c = Array2::zeros((nx, ny));
59        let mut ty = Vec::new();
60        for i in 0..nx {
61            let row: Vec<f64> = along_x.row(i).to_vec();
62            let s = make_interp_spline(y, &row, ky, &BoundaryCondition::NotAKnot)?;
63            for j in 0..ny {
64                c[(i, j)] = s.c[j];
65            }
66            ty = s.t;
67        }
68        Ok(RectBivariateSpline { tx, ty, kx, ky, c })
69    }
70    // ANCHOR_END: rect_bivariate
71
72    /// The value or partial derivative `∂^{dx+dy} s / ∂x^{dx} ∂y^{dy}` at `(x, y)`. Points outside
73    /// the grid are clamped to its edge, as FITPACK's `bispev` does.
74    pub fn evaluate(&self, x: f64, y: f64, dx: usize, dy: usize) -> f64 {
75        let (nx, ny) = self.c.dim();
76        let x = x.clamp(self.tx[self.kx], self.tx[nx]);
77        let y = y.clamp(self.ty[self.ky], self.ty[ny]);
78        let lx = interval(&self.tx, self.kx, nx, x);
79        let ly = interval(&self.ty, self.ky, ny, y);
80        let bx = if dx == 0 { nonzero_basis(&self.tx, self.kx, lx, x) } else { nonzero_basis_derivatives(&self.tx, self.kx, lx, x, dx) };
81        let by = if dy == 0 { nonzero_basis(&self.ty, self.ky, ly, y) } else { nonzero_basis_derivatives(&self.ty, self.ky, ly, y, dy) };
82        let mut sum = 0.0;
83        for (a, wx) in bx.iter().enumerate() {
84            let i = lx - self.kx + a;
85            for (b, wy) in by.iter().enumerate() {
86                sum += wx * wy * self.c[(i, ly - self.ky + b)];
87            }
88        }
89        sum
90    }
91
92    /// `∫_{xa}^{xb} ∫_{ya}^{yb} s(x, y) dy dx` (SciPy's `integral`), as `Σ cᵢⱼ Iᵢ Jⱼ` with the
93    /// integrals `Iᵢ`, `Jⱼ` of the one-dimensional basis functions.
94    pub fn integral(&self, xa: f64, xb: f64, ya: f64, yb: f64) -> f64 {
95        let (nx, ny) = self.c.dim();
96        let basis_integrals = |t: &[f64], k: usize, n: usize, a: f64, b: f64| -> Vec<f64> {
97            (0..n)
98                .map(|i| {
99                    let mut e = vec![0.0; n];
100                    e[i] = 1.0;
101                    BSpline::new(t.to_vec(), e, k).expect("valid knots").integrate(a, b)
102                })
103                .collect()
104        };
105        let ix = basis_integrals(&self.tx, self.kx, nx, xa, xb);
106        let iy = basis_integrals(&self.ty, self.ky, ny, ya, yb);
107        self.c.indexed_iter().map(|((i, j), c)| c * ix[i] * iy[j]).sum()
108    }
109
110    /// The knots along `x` and `y`.
111    pub fn knots(&self) -> (&[f64], &[f64]) {
112        (&self.tx, &self.ty)
113    }
114
115    /// The coefficients `cᵢⱼ`.
116    pub fn coefficients(&self) -> &Array2<f64> {
117        &self.c
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn reproduces_a_bicubic_polynomial() {
127        let f = |x: f64, y: f64| x * x * y - 2.0 * x * y * y * y + 0.5 * x + 1.0;
128        let x: Vec<f64> = (0..7).map(|i| i as f64 * 0.4).collect();
129        let y: Vec<f64> = (0..6).map(|j| -1.0 + j as f64 * 0.5).collect();
130        let z = Array2::from_shape_fn((7, 6), |(i, j)| f(x[i], y[j]));
131        let s = RectBivariateSpline::new(&x, &y, &z, 3, 3).unwrap();
132        for (a, b) in [(0.3, 0.2), (1.7, -0.9), (2.2, 1.4)] {
133            assert!((s.evaluate(a, b, 0, 0) - f(a, b)).abs() < 1e-12);
134            assert!((s.evaluate(a, b, 1, 0) - (2.0 * a * b - 2.0 * b.powi(3) + 0.5)).abs() < 1e-11);
135            assert!((s.evaluate(a, b, 0, 1) - (a * a - 6.0 * a * b * b)).abs() < 1e-11);
136        }
137        // ∫₀^{2.4} ∫_{−1}^{1.5} f dy dx.
138        let exact = {
139            let fx = |x: f64| x * x * (1.5f64.powi(2) - 1.0) / 2.0 - 2.0 * x * (1.5f64.powi(4) - 1.0) / 4.0 + (0.5 * x + 1.0) * 2.5;
140            // Integrate the cubic fx exactly by Simpson's rule (exact for cubics).
141            let (a, b) = (0.0, 2.4);
142            (b - a) / 6.0 * (fx(a) + 4.0 * fx(0.5 * (a + b)) + fx(b))
143        };
144        assert!((s.integral(0.0, 2.4, -1.0, 1.5) - exact).abs() < 1e-11);
145    }
146}