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
//! Core ML traits for the ferrolearn framework.
//!
//! This module defines the fundamental traits that all ferrolearn estimators
//! and transformers implement. The key design principle is **compile-time
//! safety**: calling [`Predict::predict`] on an unfitted model is a type
//! error, not a runtime error.
//!
//! # Design
//!
//! The unfitted struct (e.g., `LogisticRegression`) holds hyperparameters
//! and implements [`Fit`]. Calling [`Fit::fit`] consumes the hyperparameters
//! by reference and returns a *new fitted type* (e.g., `FittedLogisticRegression`)
//! that implements [`Predict`]. The unfitted type **never** implements `Predict`,
//! so the compiler rejects invalid usage.
//!
//! ```text
//! [StandardScaler] --fit(&x, &())--> [FittedStandardScaler] --transform(&x)--> Array2<F>
//! [LogisticRegression] --fit(&x, &y) --> [FittedLogisticRegression] --predict(&x) --> Array1<usize>
//! ```
//!
//! # Type-System Safety Guarantees
//!
//! ferrolearn encodes ML workflow correctness in Rust's type system. The [`Fit`]
//! trait returns a distinct `Fitted` associated type, and only that fitted type
//! implements [`Predict`] or [`Transform`]. This means:
//!
//! - **An unfitted model cannot call `predict()` or `transform()`** -- this is a
//! compile-time error, not a runtime check. There is no `is_fitted()` guard
//! that can be forgotten or bypassed.
//! - **`clone()` on a fitted model preserves fitted state** -- unlike frameworks
//! where cloning resets learned parameters, a cloned `FittedLinearRegression`
//! retains its coefficients because the fitted state is part of the type.
//! - **Type mismatches (e.g., fitting on `f32`, predicting on `f64`) are compile
//! errors** -- the generic parameter `F` threads through `Fit`, `Predict`, and
//! `Transform`, so the compiler rejects mixed-precision workflows.
//!
//! This is a formal guarantee carried by Rust's type checker. The compiler serves
//! as the theorem prover: successful compilation is the proof certificate that
//! every `predict()` call is preceded by a `fit()` call on compatible data.
//!
//! # Float Bound
//!
//! All algorithms are generic over `F: num_traits::Float + Send + Sync + 'static`.
/// Train a model on data, producing a fitted model.
///
/// The unfitted struct holds hyperparameters. Calling `fit` returns a new
/// fitted type that holds learned parameters. This is the core mechanism
/// that ensures compile-time enforcement: the unfitted type does not
/// implement [`Predict`], so calling `predict` before `fit` is a type error.
///
/// # Type-System Role
///
/// `Fit` is the entry point of the type-level state machine. It transitions
/// an unfitted configuration struct (which does **not** implement [`Predict`]
/// or [`Transform`]) into a fitted struct (which does). This transition is
/// enforced at compile time -- the compiler will reject any program that
/// calls `predict()` or `transform()` on the unfitted type.
///
/// # Type Parameters
///
/// - `X`: The feature matrix type (typically `ndarray::Array2<F>`).
/// - `Y`: The target type. Use `()` for unsupervised models.
///
/// # Examples
///
/// ```
/// use ferrolearn_core::Fit;
/// use ferrolearn_core::FerroError;
///
/// struct MyRegressor { alpha: f64 }
/// struct FittedMyRegressor { weights: Vec<f64> }
///
/// impl Fit<Vec<Vec<f64>>, Vec<f64>> for MyRegressor {
/// type Fitted = FittedMyRegressor;
/// type Error = FerroError;
///
/// fn fit(&self, _x: &Vec<Vec<f64>>, _y: &Vec<f64>) -> Result<FittedMyRegressor, FerroError> {
/// Ok(FittedMyRegressor { weights: vec![1.0, 2.0] })
/// }
/// }
/// ```
/// Generate predictions from a fitted model.
///
/// Only fitted model types implement this trait. Unfitted configuration
/// structs do **not** implement `Predict`, which means that calling
/// `predict` on an unfitted model is a compile-time error.
///
/// # Type-System Role
///
/// `Predict` is only implemented on fitted types (e.g., `FittedLinearRegression`,
/// `FittedKMeans`). The unfitted counterparts (`LinearRegression`, `KMeans`)
/// never implement `Predict`. This makes "predict before fit" impossible to
/// express in valid Rust -- the compiler rejects it outright.
///
/// # Type Parameters
///
/// - `X`: The feature matrix type (typically `ndarray::Array2<F>`).
/// Transform data (e.g., scaling, encoding).
///
/// Transformers that require fitting first should implement [`Fit`]
/// to produce a fitted type that implements `Transform`. Stateless
/// transformers can implement `Transform` directly.
///
/// # Type-System Role
///
/// For stateful transformers (e.g., `StandardScaler`, `PCA`), `Transform`
/// is only implemented on the fitted type (`FittedStandardScaler`,
/// `FittedPCA`). The unfitted type implements [`Fit`] but not `Transform`,
/// so calling `transform()` before `fit()` is a compile-time error.
///
/// # Type Parameters
///
/// - `X`: The input data type.
/// Combined fit-and-transform in a single pass.
///
/// This trait extends [`Transform`] and provides a convenience method
/// that fits the transformer and transforms the data in one step.
/// This can be more efficient than calling `fit` followed by `transform`
/// separately when the fitting process already computes the transformed
/// output.
///
/// # Type Parameters
///
/// - `X`: The input data type.
/// Incrementally train a model on a batch of data.
///
/// Unlike [`Fit`], `PartialFit` can be called multiple times -- each call
/// updates the model with a new batch. This enables online/streaming learning.
///
/// The trait is implemented by both unfitted models (first call) and fitted
/// models (subsequent calls), enabling chaining:
/// `model.partial_fit(&b1, &y1)?.partial_fit(&b2, &y2)?.predict(&x)?`