Skip to main content

solow_preprocessing/
spline.rs

1//! SplineTransformer — B-spline basis expansion.
2//!
3//! Produces truncated-power basis columns of a given degree over a
4//! set of caller-configured knots (uniform quantiles by default).
5//! sklearn ≥ 1.0 exposes this as `sklearn.preprocessing.SplineTransformer`.
6
7use ndarray::{Array2, ArrayView2};
8use solow_core::{Error, Result};
9
10/// Knot placement.
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub enum KnotStrategy {
13    /// Equally-spaced knots.
14    Uniform,
15    /// Quantile-based knots.
16    Quantile,
17}
18
19/// Fitted SplineTransformer.
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[derive(Clone, Debug, PartialEq)]
22pub struct SplineTransformer {
23    /// Per-column knot vectors (sorted).
24    pub knots: Vec<Vec<f64>>,
25    /// Spline degree.
26    pub degree: usize,
27    /// Whether an intercept (constant column) is included.
28    pub include_bias: bool,
29    /// Column count at fit time.
30    pub n_features_in: usize,
31}
32
33impl SplineTransformer {
34    /// Fit with defaults `n_knots = 5`, `degree = 3`, `include_bias = true`,
35    /// `strategy = Uniform`.
36    pub fn fit(x: ArrayView2<'_, f64>) -> Result<Self> {
37        Self::fit_with(x, 5, 3, KnotStrategy::Uniform, true)
38    }
39
40    /// Full-configuration fit.
41    pub fn fit_with(
42        x: ArrayView2<'_, f64>,
43        n_knots: usize,
44        degree: usize,
45        strategy: KnotStrategy,
46        include_bias: bool,
47    ) -> Result<Self> {
48        if n_knots < 2 {
49            return Err(Error::Value("SplineTransformer: n_knots must be ≥ 2".into()));
50        }
51        if degree == 0 {
52            return Err(Error::Value("SplineTransformer: degree must be ≥ 1".into()));
53        }
54        let d = x.ncols();
55        let mut knots: Vec<Vec<f64>> = Vec::with_capacity(d);
56        for j in 0..d {
57            let mut col: Vec<f64> = (0..x.nrows()).map(|i| x[[i, j]]).collect();
58            col.sort_by(|a, b| a.partial_cmp(b).unwrap());
59            let mut k = Vec::with_capacity(n_knots);
60            for i in 0..n_knots {
61                let q = i as f64 / (n_knots - 1) as f64;
62                let pos = match strategy {
63                    KnotStrategy::Uniform => {
64                        let (lo, hi) = (col[0], col[col.len() - 1]);
65                        lo + q * (hi - lo)
66                    }
67                    KnotStrategy::Quantile => {
68                        let p = (q * (col.len() - 1) as f64) as usize;
69                        col[p]
70                    }
71                };
72                k.push(pos);
73            }
74            knots.push(k);
75        }
76        Ok(Self {
77            knots,
78            degree,
79            include_bias,
80            n_features_in: d,
81        })
82    }
83
84    /// Transform via the truncated-power basis `{1, x, x², …, xᵈ,
85    /// (x − κ₁)ᵈ₊, …, (x − κₘ)ᵈ₊}` per column.
86    pub fn transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
87        if x.ncols() != self.n_features_in {
88            return Err(Error::Shape("SplineTransformer::transform: column count mismatch".into()));
89        }
90        let n = x.nrows();
91        let d = x.ncols();
92        let per_col_basis = self.degree + self.knots[0].len();
93        let stride = if self.include_bias { per_col_basis + 1 } else { per_col_basis };
94        let mut out = Array2::<f64>::zeros((n, d * stride));
95        for i in 0..n {
96            for j in 0..d {
97                let base = j * stride;
98                let xij = x[[i, j]];
99                let mut idx = 0_usize;
100                if self.include_bias {
101                    out[[i, base + idx]] = 1.0;
102                    idx += 1;
103                }
104                let mut p = 1.0_f64;
105                for _ in 0..self.degree {
106                    p *= xij;
107                    out[[i, base + idx]] = p;
108                    idx += 1;
109                }
110                for &k in &self.knots[j] {
111                    let d_val = (xij - k).max(0.0);
112                    out[[i, base + idx]] = d_val.powi(self.degree as i32);
113                    idx += 1;
114                }
115            }
116        }
117        Ok(out)
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124    use ndarray::array;
125
126    #[test]
127    fn spline_transformer_widens_by_the_right_multiplier() {
128        let x = array![[0.0_f64], [1.0], [2.0], [3.0], [4.0], [5.0]];
129        // 5 knots + degree 3 + bias = 3 + 5 + 1 = 9 features per input col.
130        let s = SplineTransformer::fit_with(x.view(), 5, 3, KnotStrategy::Uniform, true).unwrap();
131        let z = s.transform(x.view()).unwrap();
132        assert_eq!(z.shape(), &[6, 9]);
133    }
134}