solow_preprocessing/
function_transformer.rs1use ndarray::{Array2, ArrayView2};
5use solow_core::{Error, Result};
6
7pub struct FunctionTransformer {
9 pub func: Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>>,
11 pub inverse_func: Option<Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>>>,
13 pub n_features_in: usize,
15 pub validate: bool,
17}
18
19impl FunctionTransformer {
20 pub fn fit(
22 x: ArrayView2<'_, f64>,
23 func: Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>>,
24 inverse_func: Option<Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>>>,
25 ) -> Result<Self> {
26 if x.ncols() == 0 {
27 return Err(Error::Value("FunctionTransformer: no columns".into()));
28 }
29 Ok(Self {
30 func,
31 inverse_func,
32 n_features_in: x.ncols(),
33 validate: true,
34 })
35 }
36
37 pub fn transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
39 if self.validate && x.ncols() != self.n_features_in {
40 return Err(Error::Shape(
41 "FunctionTransformer::transform: column count mismatch".into(),
42 ));
43 }
44 (self.func)(x)
45 }
46
47 pub fn inverse_transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
49 match &self.inverse_func {
50 None => Err(Error::Value(
51 "FunctionTransformer::inverse_transform: no inverse function provided".into(),
52 )),
53 Some(f) => f(x),
54 }
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61 use ndarray::array;
62
63 #[test]
64 fn function_transformer_applies_log_and_inverses_it() {
65 let x = array![[1.0_f64, 2.0], [3.0, 4.0]];
66 let forward: Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>> =
67 Box::new(|arr| {
68 let mut out = arr.to_owned();
69 for v in out.iter_mut() {
70 *v = (*v).ln();
71 }
72 Ok(out)
73 });
74 let inverse: Box<dyn Fn(ArrayView2<'_, f64>) -> Result<Array2<f64>>> =
75 Box::new(|arr| {
76 let mut out = arr.to_owned();
77 for v in out.iter_mut() {
78 *v = (*v).exp();
79 }
80 Ok(out)
81 });
82 let ft = FunctionTransformer::fit(x.view(), forward, Some(inverse)).unwrap();
83 let z = ft.transform(x.view()).unwrap();
84 let back = ft.inverse_transform(z.view()).unwrap();
85 for i in 0..2 {
86 for j in 0..2 {
87 assert!((back[[i, j]] - x[[i, j]]).abs() < 1e-10);
88 }
89 }
90 }
91}