Skip to main content

sklears_tree/
decision_tree.rs

1//! Generic, state-typed decision tree building block
2//!
3//! This module provides `DecisionTree<State>`, a low-level generic struct used as a
4//! shared building block (e.g. by the Python bindings in `sklears-python`) and by
5//! basic construction/builder tests in this crate.
6//!
7//! For fully-featured, SmartCore-backed classification and regression estimators
8//! that actually learn from data, use [`crate::classifier::DecisionTreeClassifier`]
9//! and [`crate::regressor::DecisionTreeRegressor`] instead — those are the types
10//! re-exported at the crate root as `DecisionTreeClassifier`/`DecisionTreeRegressor`.
11//!
12//! `DecisionTree<State>`'s own [`Fit`]/[`Predict`] implementations below are
13//! intentionally minimal: `fit` does not build a real tree and `predict` always
14//! returns zeros. Do not use `DecisionTree` directly when you need real
15//! predictions.
16
17use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
18use sklears_core::error::{Result, SklearsError};
19use sklears_core::traits::{Estimator, Fit, Predict, Trained, Untrained};
20use std::marker::PhantomData;
21
22// Re-export types from existing modules
23pub use crate::config::DecisionTreeConfig;
24pub use crate::criteria::{ConditionalTestType, FeatureType, MonotonicConstraint, SplitCriterion};
25pub use crate::node::{CompactTreeNode, CustomSplit, SurrogateSplit, TreeNode};
26pub use crate::splits::{ChaidSplit, HyperplaneSplit};
27
28/// Main Decision Tree structure that can be used for both classification and regression
29#[derive(Debug, Clone)]
30pub struct DecisionTree<State = Untrained> {
31    config: DecisionTreeConfig,
32    root: Option<TreeNode>,
33    feature_importances: Option<Array1<f64>>,
34    n_features: usize,
35    n_samples: usize,
36    state: PhantomData<State>,
37}
38
39impl<State> Default for DecisionTree<State> {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl<State> DecisionTree<State> {
46    /// Create a new DecisionTree with default configuration
47    pub fn new() -> Self {
48        Self {
49            config: DecisionTreeConfig::default(),
50            root: None,
51            feature_importances: None,
52            n_features: 0,
53            n_samples: 0,
54            state: PhantomData,
55        }
56    }
57
58    /// Create a new DecisionTree with custom configuration
59    pub fn with_config(config: DecisionTreeConfig) -> Self {
60        Self {
61            config,
62            root: None,
63            feature_importances: None,
64            n_features: 0,
65            n_samples: 0,
66            state: PhantomData,
67        }
68    }
69
70    /// Create a builder for configuring the decision tree
71    pub fn builder() -> DecisionTreeBuilder<State> {
72        DecisionTreeBuilder::new()
73    }
74
75    /// Get the configuration of the decision tree
76    pub fn config(&self) -> &DecisionTreeConfig {
77        &self.config
78    }
79
80    /// Get the root node of the tree (if fitted)
81    pub fn root(&self) -> Option<&TreeNode> {
82        self.root.as_ref()
83    }
84
85    /// Get feature importances (if available)
86    pub fn feature_importances(&self) -> Option<&Array1<f64>> {
87        self.feature_importances.as_ref()
88    }
89
90    /// Get the number of features the tree was trained on
91    pub fn n_features(&self) -> usize {
92        self.n_features
93    }
94
95    /// Get the number of training samples
96    pub fn n_samples(&self) -> usize {
97        self.n_samples
98    }
99
100    /// Get the depth of the tree (returns root node depth if available)
101    pub fn depth(&self) -> usize {
102        match &self.root {
103            Some(root) => root.depth,
104            None => 0,
105        }
106    }
107
108    /// Set the split criterion (fluent API)
109    pub fn criterion(mut self, criterion: SplitCriterion) -> Self {
110        self.config.criterion = criterion;
111        self
112    }
113
114    /// Set the maximum depth of the tree (fluent API)
115    pub fn max_depth(mut self, max_depth: usize) -> Self {
116        self.config.max_depth = Some(max_depth);
117        self
118    }
119
120    /// Set the minimum samples required to split an internal node (fluent API)
121    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
122        self.config.min_samples_split = min_samples_split;
123        self
124    }
125
126    /// Set the minimum samples required to be at a leaf node (fluent API)
127    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
128        self.config.min_samples_leaf = min_samples_leaf;
129        self
130    }
131
132    /// Set the missing value strategy (fluent API)
133    pub fn missing_values(mut self, strategy: crate::config::MissingValueStrategy) -> Self {
134        self.config.missing_values = strategy;
135        self
136    }
137
138    /// Set the random seed (fluent API)
139    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
140        self.config.random_state = random_state;
141        self
142    }
143}
144
145/// Builder pattern for configuring DecisionTree
146#[derive(Debug)]
147pub struct DecisionTreeBuilder<State> {
148    config: DecisionTreeConfig,
149    _marker: PhantomData<State>,
150}
151
152impl<State> DecisionTreeBuilder<State> {
153    /// Create a new builder
154    pub fn new() -> Self {
155        Self {
156            config: DecisionTreeConfig::default(),
157            _marker: PhantomData,
158        }
159    }
160
161    /// Set the split criterion
162    pub fn criterion(mut self, criterion: SplitCriterion) -> Self {
163        self.config.criterion = criterion;
164        self
165    }
166
167    /// Set the maximum depth of the tree
168    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
169        self.config.max_depth = max_depth;
170        self
171    }
172
173    /// Set the minimum samples required to split an internal node
174    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
175        self.config.min_samples_split = min_samples_split;
176        self
177    }
178
179    /// Set the minimum samples required to be at a leaf node
180    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
181        self.config.min_samples_leaf = min_samples_leaf;
182        self
183    }
184
185    /// Set the minimum impurity decrease required for a split
186    pub fn min_impurity_decrease(mut self, min_impurity_decrease: f64) -> Self {
187        self.config.min_impurity_decrease = min_impurity_decrease;
188        self
189    }
190
191    /// Set the maximum number of features to consider for splitting
192    pub fn max_features(self, _max_features: Option<usize>) -> Self {
193        // Convert between Option<usize> and MaxFeatures type if needed
194        // self.config.max_features = max_features;
195        self
196    }
197
198    /// Set the random seed
199    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
200        self.config.random_state = random_state;
201        self
202    }
203
204    /// Build the DecisionTree with the configured parameters
205    pub fn build(self) -> DecisionTree<State> {
206        DecisionTree::with_config(self.config)
207    }
208}
209
210impl<State> Default for DecisionTreeBuilder<State> {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216// Note: Estimator trait implementation can be added later when all required methods are defined
217
218impl DecisionTree<Untrained> {
219    /// Check if the tree has been fitted (always false for Untrained trees)
220    pub fn is_fitted(&self) -> bool {
221        false
222    }
223
224    /// Get the number of classes (not available for untrained trees)
225    pub fn n_classes(&self) -> usize {
226        0 // Untrained trees don't have class information
227    }
228}
229
230/// Validation functions for decision trees
231pub struct TreeValidator;
232
233impl TreeValidator {
234    /// Validate input data dimensions
235    pub fn validate_input(x: &ArrayView2<'_, f64>, y: &ArrayView1<'_, f64>) -> Result<()> {
236        if x.nrows() != y.len() {
237            return Err(SklearsError::InvalidInput(format!(
238                "Number of samples in X ({}) does not match number of targets in y ({})",
239                x.nrows(),
240                y.len()
241            )));
242        }
243
244        if x.nrows() == 0 {
245            return Err(SklearsError::InvalidInput(
246                "Input arrays must contain at least one sample".to_string(),
247            ));
248        }
249
250        if x.ncols() == 0 {
251            return Err(SklearsError::InvalidInput(
252                "Input arrays must contain at least one feature".to_string(),
253            ));
254        }
255
256        Ok(())
257    }
258
259    /// Validate that the tree has been fitted
260    pub fn validate_fitted(_tree: &DecisionTree<Trained>) -> Result<()> {
261        // Type system ensures tree is fitted
262        Ok(())
263    }
264
265    /// Validate prediction input dimensions
266    pub fn validate_prediction_input(
267        tree: &DecisionTree<Trained>,
268        x: &ArrayView2<'_, f64>,
269    ) -> Result<()> {
270        Self::validate_fitted(tree)?;
271
272        if x.ncols() != tree.n_features() {
273            return Err(SklearsError::InvalidInput(format!(
274                "Number of features in X ({}) does not match number of features seen during fit ({})",
275                x.ncols(),
276                tree.n_features()
277            )));
278        }
279
280        Ok(())
281    }
282}
283
284// Trait implementations
285
286impl Estimator<Untrained> for DecisionTree<Untrained> {
287    type Config = DecisionTreeConfig;
288    type Error = SklearsError;
289    type Float = f64;
290
291    fn config(&self) -> &Self::Config {
292        &self.config
293    }
294}
295
296impl Estimator<Trained> for DecisionTree<Trained> {
297    type Config = DecisionTreeConfig;
298    type Error = SklearsError;
299    type Float = f64;
300
301    fn config(&self) -> &Self::Config {
302        &self.config
303    }
304}
305
306impl Fit<Array2<f64>, Array1<f64>, Untrained> for DecisionTree<Untrained> {
307    type Fitted = DecisionTree<Trained>;
308
309    fn fit(self, x: &Array2<f64>, y: &Array1<f64>) -> Result<Self::Fitted> {
310        // Validate input
311        TreeValidator::validate_input(&x.view(), &y.view())?;
312
313        // Intentionally minimal: `DecisionTree<State>` is a low-level shared
314        // building block, not a real estimator. It does not construct a tree
315        // from `y` at all. For a real, learning implementation use
316        // `crate::classifier::DecisionTreeClassifier` or
317        // `crate::regressor::DecisionTreeRegressor` instead.
318        let fitted_tree = DecisionTree::<Trained> {
319            config: self.config,
320            root: None,
321            feature_importances: None,
322            n_features: x.ncols(),
323            n_samples: x.nrows(),
324            state: PhantomData,
325        };
326
327        Ok(fitted_tree)
328    }
329}
330
331impl Predict<Array2<f64>, Array1<f64>> for DecisionTree<Trained> {
332    fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
333        TreeValidator::validate_prediction_input(self, &x.view())?;
334
335        // Intentionally minimal: there is no tree to traverse (see `fit` above),
336        // so this always returns zeros. Use `crate::classifier::DecisionTreeClassifier`
337        // or `crate::regressor::DecisionTreeRegressor` for real predictions.
338        let predictions = Array1::zeros(x.nrows());
339
340        Ok(predictions)
341    }
342}
343
344impl DecisionTree<Trained> {
345    /// Check if the tree has been fitted (always true for Trained trees)
346    pub fn is_fitted(&self) -> bool {
347        true
348    }
349
350    /// Get the number of classes (always 2; `DecisionTree<State>` never learns
351    /// real class information from training data). For a real class count use
352    /// `crate::classifier::DecisionTreeClassifier::n_classes`, which computes
353    /// it from the actual training labels.
354    pub fn n_classes(&self) -> usize {
355        2
356    }
357}