anofox-ml-core 0.1.0

Core traits and types for the anofox-ml machine learning library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::any::Any;

use ndarray::{Array1, Array2};

use crate::error::{Result, RustMlError};
use crate::float::Float;
use crate::traits::{Fit, Predict, Transform};

/// A transformer that can be fit on data and then transform it.
pub trait FitTransform<F: Float>: Send + Sync {
    fn fit_transform(&self, x: &Array2<F>) -> Result<(Box<dyn TransformStep<F>>, Array2<F>)>;
}

/// A fitted transformer step that can transform new data.
pub trait TransformStep<F: Float>: Send + Sync {
    fn transform(&self, x: &Array2<F>) -> Result<Array2<F>>;
    fn as_any(&self) -> &dyn Any;
}

/// A supervised estimator that can be fit and then predict.
pub trait FitPredict<F: Float>: Send + Sync {
    fn fit_predict_step(&self, x: &Array2<F>, y: &Array1<F>) -> Result<Box<dyn PredictStep<F>>>;
}

/// A fitted estimator step that can predict.
pub trait PredictStep<F: Float>: Send + Sync {
    fn predict(&self, x: &Array2<F>) -> Result<Array1<F>>;
    fn as_any(&self) -> &dyn Any;
}

// --- Blanket implementations ---

/// Blanket impl: any type implementing FitUnsupervised + Transform can be a pipeline transformer.
impl<F, T> FitTransform<F> for T
where
    F: Float,
    T: crate::traits::FitUnsupervised<F> + Send + Sync,
    T::Fitted: Transform<F> + Send + Sync + 'static,
{
    fn fit_transform(&self, x: &Array2<F>) -> Result<(Box<dyn TransformStep<F>>, Array2<F>)> {
        let fitted = crate::traits::FitUnsupervised::fit(self, x)?;
        let transformed = fitted.transform(x)?;
        Ok((Box::new(FittedTransformWrapper(fitted)), transformed))
    }
}

struct FittedTransformWrapper<T>(T);

// Safety: T is already Send + Sync via trait bounds
unsafe impl<T: Send> Send for FittedTransformWrapper<T> {}
unsafe impl<T: Sync> Sync for FittedTransformWrapper<T> {}

impl<F: Float, T: Transform<F> + Send + Sync + 'static> TransformStep<F>
    for FittedTransformWrapper<T>
{
    fn transform(&self, x: &Array2<F>) -> Result<Array2<F>> {
        self.0.transform(x)
    }
    fn as_any(&self) -> &dyn Any {
        &self.0
    }
}

/// Blanket impl: any type implementing Fit + Predict can be a pipeline estimator.
impl<F, T> FitPredict<F> for T
where
    F: Float,
    T: Fit<F> + Send + Sync,
    T::Fitted: Predict<F> + Send + Sync + 'static,
{
    fn fit_predict_step(&self, x: &Array2<F>, y: &Array1<F>) -> Result<Box<dyn PredictStep<F>>> {
        let fitted = Fit::fit(self, x, y)?;
        Ok(Box::new(FittedPredictWrapper(fitted)))
    }
}

struct FittedPredictWrapper<T>(T);

unsafe impl<T: Send> Send for FittedPredictWrapper<T> {}
unsafe impl<T: Sync> Sync for FittedPredictWrapper<T> {}

impl<F: Float, T: Predict<F> + Send + Sync + 'static> PredictStep<F> for FittedPredictWrapper<T> {
    fn predict(&self, x: &Array2<F>) -> Result<Array1<F>> {
        self.0.predict(x)
    }
    fn as_any(&self) -> &dyn Any {
        &self.0
    }
}

/// An unfitted pipeline that chains transformers and a final estimator.
///
/// Follows sklearn's Pipeline pattern: chain transformers in sequence,
/// then optionally fit/predict with a final estimator.
///
/// # Example
/// ```ignore
/// use anofox_ml::prelude::*;
///
/// let pipeline = Pipeline::new()
///     .push_transformer("scaler", StandardScaler::new())
///     .set_estimator("knn", KnnClassifier::new(5));
///
/// let fitted = pipeline.fit(&x_train, &y_train)?;
/// let preds = fitted.predict(&x_test)?;
/// ```
pub struct Pipeline<F: Float> {
    transformers: Vec<(String, Box<dyn FitTransform<F>>)>,
    estimator: Option<(String, Box<dyn FitPredict<F>>)>,
}

impl<F: Float> Pipeline<F> {
    /// Create an empty pipeline.
    pub fn new() -> Self {
        Pipeline {
            transformers: Vec::new(),
            estimator: None,
        }
    }

    /// Add a transformer step to the pipeline.
    pub fn push_transformer(
        mut self,
        name: impl Into<String>,
        transformer: impl FitTransform<F> + 'static,
    ) -> Self {
        self.transformers.push((name.into(), Box::new(transformer)));
        self
    }

    /// Set the final estimator of the pipeline.
    pub fn set_estimator(
        mut self,
        name: impl Into<String>,
        estimator: impl FitPredict<F> + 'static,
    ) -> Self {
        self.estimator = Some((name.into(), Box::new(estimator)));
        self
    }

    /// Fit the pipeline: fit each transformer sequentially, transforming
    /// X at each step, then fit the final estimator on the transformed X.
    pub fn fit(self, x: &Array2<F>, y: &Array1<F>) -> Result<FittedPipeline<F>> {
        let mut current_x_owned: Option<Array2<F>> = None;
        let mut fitted_transformers = Vec::with_capacity(self.transformers.len());

        for (name, transformer) in self.transformers {
            let x_ref = current_x_owned.as_ref().unwrap_or(x);
            let (fitted, transformed) = transformer.fit_transform(x_ref)?;
            fitted_transformers.push((name, fitted));
            current_x_owned = Some(transformed);
        }

        let x_final = current_x_owned.as_ref().unwrap_or(x);
        let fitted_estimator = match self.estimator {
            Some((name, estimator)) => {
                let fitted = estimator.fit_predict_step(x_final, y)?;
                Some((name, fitted))
            }
            None => None,
        };

        Ok(FittedPipeline {
            transformers: fitted_transformers,
            estimator: fitted_estimator,
        })
    }
}

impl<F: Float> Default for Pipeline<F> {
    fn default() -> Self {
        Self::new()
    }
}

/// A fitted pipeline that can transform and predict on new data.
pub struct FittedPipeline<F: Float> {
    transformers: Vec<(String, Box<dyn TransformStep<F>>)>,
    estimator: Option<(String, Box<dyn PredictStep<F>>)>,
}

impl<F: Float> FittedPipeline<F> {
    /// Transform new data through all transformer steps.
    pub fn transform(&self, x: &Array2<F>) -> Result<Array2<F>> {
        let mut current_x_owned: Option<Array2<F>> = None;
        for (_, transformer) in &self.transformers {
            let x_ref = current_x_owned.as_ref().unwrap_or(x);
            current_x_owned = Some(transformer.transform(x_ref)?);
        }
        Ok(current_x_owned.unwrap_or_else(|| x.clone()))
    }

    /// Transform new data through all steps, then predict with the final estimator.
    pub fn predict(&self, x: &Array2<F>) -> Result<Array1<F>> {
        let transformed = self.transform(x)?;
        match &self.estimator {
            Some((_, estimator)) => estimator.predict(&transformed),
            None => Err(RustMlError::NotFitted(
                "Pipeline has no estimator set".into(),
            )),
        }
    }

    /// Downcast a named transformer step to its concrete fitted type.
    pub fn get_transformer<T: 'static>(&self, name: &str) -> Result<&T> {
        let step = self
            .transformers
            .iter()
            .find(|(n, _)| n == name)
            .ok_or_else(|| RustMlError::NotFitted(format!("No transformer step named '{name}'")))?;
        step.1.as_any().downcast_ref::<T>().ok_or_else(|| {
            RustMlError::NotFitted(format!(
                "Transformer '{name}' could not be downcast to the requested type"
            ))
        })
    }

    /// Downcast the final estimator to its concrete fitted type.
    pub fn get_estimator<T: 'static>(&self) -> Result<&T> {
        let (_, estimator) = self
            .estimator
            .as_ref()
            .ok_or_else(|| RustMlError::NotFitted("Pipeline has no estimator set".into()))?;
        estimator.as_any().downcast_ref::<T>().ok_or_else(|| {
            RustMlError::NotFitted("Estimator could not be downcast to the requested type".into())
        })
    }

    /// Get the names of all steps in the pipeline.
    pub fn step_names(&self) -> Vec<&str> {
        let mut names: Vec<&str> = self
            .transformers
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        if let Some((name, _)) = &self.estimator {
            names.push(name.as_str());
        }
        names
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ndarray::array;

    // A simple test transformer that doubles all values
    struct Doubler;
    struct FittedDoubler;

    impl FitTransform<f64> for Doubler {
        fn fit_transform(
            &self,
            x: &Array2<f64>,
        ) -> Result<(Box<dyn TransformStep<f64>>, Array2<f64>)> {
            let transformed = x.mapv(|v| v * 2.0);
            Ok((Box::new(FittedDoubler), transformed))
        }
    }

    impl TransformStep<f64> for FittedDoubler {
        fn transform(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
            Ok(x.mapv(|v| v * 2.0))
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    // A simple test estimator that predicts the mean of features
    struct MeanPredictor;
    struct FittedMeanPredictor;

    impl FitPredict<f64> for MeanPredictor {
        fn fit_predict_step(
            &self,
            _x: &Array2<f64>,
            _y: &Array1<f64>,
        ) -> Result<Box<dyn PredictStep<f64>>> {
            Ok(Box::new(FittedMeanPredictor))
        }
    }

    impl PredictStep<f64> for FittedMeanPredictor {
        fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
            Ok(x.mean_axis(ndarray::Axis(1)).unwrap())
        }
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }
    }

    #[test]
    fn test_pipeline_transform_only() {
        let pipeline = Pipeline::<f64>::new().push_transformer("doubler", Doubler);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];

        let fitted = pipeline.fit(&x, &y).unwrap();
        let result = fitted.transform(&array![[1.0, 1.0]]).unwrap();
        assert_eq!(result, array![[2.0, 2.0]]);
    }

    #[test]
    fn test_pipeline_with_estimator() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("doubler", Doubler)
            .set_estimator("mean", MeanPredictor);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];

        let fitted = pipeline.fit(&x, &y).unwrap();

        // Input [1, 2] -> doubled to [2, 4] -> mean = 3.0
        let preds = fitted.predict(&array![[1.0, 2.0]]).unwrap();
        assert!((preds[0] - 3.0).abs() < 1e-10);
    }

    #[test]
    fn test_pipeline_step_names() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("step1", Doubler)
            .push_transformer("step2", Doubler)
            .set_estimator("classifier", MeanPredictor);

        let x = array![[1.0], [2.0]];
        let y = array![0.0, 1.0];

        let fitted = pipeline.fit(&x, &y).unwrap();
        assert_eq!(fitted.step_names(), vec!["step1", "step2", "classifier"]);
    }

    #[test]
    fn test_get_transformer_success() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("doubler", Doubler)
            .set_estimator("mean", MeanPredictor);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];
        let fitted = pipeline.fit(&x, &y).unwrap();

        let _doubler: &FittedDoubler = fitted.get_transformer("doubler").unwrap();
    }

    #[test]
    fn test_get_transformer_wrong_name() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("doubler", Doubler)
            .set_estimator("mean", MeanPredictor);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];
        let fitted = pipeline.fit(&x, &y).unwrap();

        assert!(fitted
            .get_transformer::<FittedDoubler>("wrong_name")
            .is_err());
    }

    #[test]
    fn test_get_transformer_wrong_type() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("doubler", Doubler)
            .set_estimator("mean", MeanPredictor);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];
        let fitted = pipeline.fit(&x, &y).unwrap();

        // FittedMeanPredictor is the wrong type for a transformer step
        assert!(fitted
            .get_transformer::<FittedMeanPredictor>("doubler")
            .is_err());
    }

    #[test]
    fn test_get_estimator_success() {
        let pipeline = Pipeline::<f64>::new()
            .push_transformer("doubler", Doubler)
            .set_estimator("mean", MeanPredictor);

        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![0.0, 1.0];
        let fitted = pipeline.fit(&x, &y).unwrap();

        let _estimator: &FittedMeanPredictor = fitted.get_estimator().unwrap();
    }

    #[test]
    fn test_pipeline_no_estimator_predict_errors() {
        let pipeline = Pipeline::<f64>::new().push_transformer("doubler", Doubler);

        let x = array![[1.0], [2.0]];
        let y = array![0.0, 1.0];

        let fitted = pipeline.fit(&x, &y).unwrap();
        assert!(fitted.predict(&x).is_err());
    }
}