solow_preprocessing/
spline.rs1use ndarray::{Array2, ArrayView2};
8use solow_core::{Error, Result};
9
10#[derive(Clone, Copy, Debug, PartialEq)]
12pub enum KnotStrategy {
13 Uniform,
15 Quantile,
17}
18
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21#[derive(Clone, Debug, PartialEq)]
22pub struct SplineTransformer {
23 pub knots: Vec<Vec<f64>>,
25 pub degree: usize,
27 pub include_bias: bool,
29 pub n_features_in: usize,
31}
32
33impl SplineTransformer {
34 pub fn fit(x: ArrayView2<'_, f64>) -> Result<Self> {
37 Self::fit_with(x, 5, 3, KnotStrategy::Uniform, true)
38 }
39
40 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 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 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}