use super::simd_operations as simd_tree;
use super::streaming_infrastructure::{
ConceptDriftDetector, IncrementalTreeConfig, StreamingBuffer,
};
use crate::{Trained, Untrained};
use scirs2_core::ndarray::{Array1, Array2};
use sklears_core::error::{Result, SklearsError};
use std::marker::PhantomData;
pub struct IncrementalDecisionTree<State = Untrained> {
config: IncrementalTreeConfig,
tree: Option<Box<dyn StreamingTreeModel>>,
buffer: StreamingBuffer,
drift_detector: ConceptDriftDetector,
samples_processed: usize,
state: PhantomData<State>,
}
pub trait StreamingTreeModel: Send + Sync {
fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>>;
fn update(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()>;
fn get_accuracy(&self, x: &Array2<f64>, y: &Array1<f64>) -> Result<f64>;
fn rebuild(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()>;
}
#[derive(Debug, Clone)]
pub struct SimpleIncrementalTree {
nodes: Vec<IncrementalTreeNode>,
}
#[derive(Debug, Clone)]
pub struct IncrementalTreeNode {
pub id: usize,
pub feature_idx: Option<usize>,
pub threshold: Option<f64>,
pub prediction: f64,
pub n_samples: usize,
pub sum_y: f64,
pub sum_y_squared: f64,
pub left_child: Option<usize>,
pub right_child: Option<usize>,
pub is_leaf: bool,
pub depth: usize,
}
impl IncrementalTreeNode {
pub fn new_leaf(id: usize, depth: usize) -> Self {
Self {
id,
feature_idx: None,
threshold: None,
prediction: 0.0,
n_samples: 0,
sum_y: 0.0,
sum_y_squared: 0.0,
left_child: None,
right_child: None,
is_leaf: true,
depth,
}
}
pub fn update_stats(&mut self, y: f64, weight: f64) {
self.n_samples += 1;
self.sum_y += y * weight;
self.sum_y_squared += y * y * weight;
if self.n_samples > 0 {
self.prediction = self.sum_y / self.n_samples as f64;
}
}
pub fn calculate_impurity(&self) -> f64 {
if self.n_samples <= 1 {
return 0.0;
}
let mean = self.sum_y / self.n_samples as f64;
let variance = (self.sum_y_squared / self.n_samples as f64) - (mean * mean);
variance.max(0.0)
}
}
impl StreamingTreeModel for SimpleIncrementalTree {
fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
let n_samples = x.nrows();
let mut predictions = Array1::zeros(n_samples);
for sample_idx in 0..n_samples {
let mut node_id = 0;
loop {
if node_id >= self.nodes.len() {
return Err(SklearsError::PredictError("Invalid node ID".to_string()));
}
let node = &self.nodes[node_id];
if node.is_leaf {
predictions[sample_idx] = node.prediction;
break;
}
if let (Some(feature_idx), Some(threshold)) = (node.feature_idx, node.threshold) {
if feature_idx >= x.ncols() {
return Err(SklearsError::PredictError(
"Invalid feature index".to_string(),
));
}
let feature_value = x[[sample_idx, feature_idx]];
if feature_value <= threshold {
node_id = node.left_child.unwrap_or(node_id);
} else {
node_id = node.right_child.unwrap_or(node_id);
}
} else {
predictions[sample_idx] = node.prediction;
break;
}
}
}
Ok(predictions)
}
fn update(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()> {
for sample_idx in 0..x.nrows() {
let mut node_id = 0;
loop {
if node_id >= self.nodes.len() {
break;
}
let node = &self.nodes[node_id];
if node.is_leaf {
let node = &mut self.nodes[node_id];
node.update_stats(y[sample_idx], weights[sample_idx]);
break;
}
if let (Some(feature_idx), Some(threshold)) = (node.feature_idx, node.threshold) {
let feature_value = x[[sample_idx, feature_idx]];
if feature_value <= threshold {
node_id = node.left_child.unwrap_or(node_id);
} else {
node_id = node.right_child.unwrap_or(node_id);
}
} else {
break;
}
}
}
Ok(())
}
fn get_accuracy(&self, x: &Array2<f64>, y: &Array1<f64>) -> Result<f64> {
let predictions = self.predict(x)?;
let pred_slice: Vec<f64> = predictions.iter().cloned().collect();
let target_slice: Vec<f64> = y.iter().cloned().collect();
let mse = simd_tree::simd_mse_evaluation(&pred_slice, &target_slice);
let y_mean = y.mean().unwrap_or(0.0);
let y_variance = y.iter().map(|&val| (val - y_mean).powi(2)).sum::<f64>() / y.len() as f64;
if y_variance == 0.0 {
Ok(1.0)
} else {
Ok((1.0 - mse / y_variance).max(0.0))
}
}
fn rebuild(&mut self, x: &Array2<f64>, y: &Array1<f64>, weights: &Array1<f64>) -> Result<()> {
self.nodes.clear();
let mut root = IncrementalTreeNode::new_leaf(0, 0);
for i in 0..x.nrows() {
root.update_stats(y[i], weights[i]);
}
self.nodes.push(root);
Ok(())
}
}
impl IncrementalDecisionTree<Untrained> {
pub fn new(config: IncrementalTreeConfig) -> Self {
let buffer = StreamingBuffer::new(config.buffer_size);
let drift_detector = ConceptDriftDetector::new(config.window_size, config.drift_threshold);
Self {
config,
tree: None,
buffer,
drift_detector,
samples_processed: 0,
state: PhantomData,
}
}
pub fn add_sample(
&mut self,
x: Vec<f64>,
y: f64,
weight: Option<f64>,
timestamp: Option<u64>,
) -> Result<()> {
let weight = weight.unwrap_or(1.0);
let timestamp = timestamp.unwrap_or_else(|| {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("operation should succeed")
.as_secs()
});
self.buffer.add_sample(x, y, weight, timestamp);
self.samples_processed += 1;
if self
.samples_processed
.is_multiple_of(self.config.update_frequency)
{
self.update_tree()?;
}
Ok(())
}
fn update_tree(&mut self) -> Result<()> {
if self.buffer.len() < self.config.min_samples_before_build {
return Ok(());
}
let (x_data, y_data, weights) = self.buffer.to_arrays()?;
if let Some(ref mut tree) = self.tree {
tree.update(&x_data, &y_data, &weights)?;
if self.config.enable_drift_detection {
let accuracy = tree.get_accuracy(&x_data, &y_data)?;
if self.drift_detector.update(accuracy) {
tree.rebuild(&x_data, &y_data, &weights)?;
}
}
} else {
let mut new_tree = SimpleIncrementalTree { nodes: Vec::new() };
new_tree.rebuild(&x_data, &y_data, &weights)?;
self.tree = Some(Box::new(new_tree));
}
Ok(())
}
pub fn get_performance_stats(&self) -> Result<IncrementalTreeStats> {
if let Some(ref tree) = self.tree {
let (x_data, y_data, _) = self.buffer.to_arrays()?;
let accuracy = tree.get_accuracy(&x_data, &y_data)?;
Ok(IncrementalTreeStats {
samples_processed: self.samples_processed,
buffer_size: self.buffer.len(),
current_accuracy: accuracy,
drift_detections: 0, tree_updates: self.samples_processed / self.config.update_frequency,
})
} else {
Ok(IncrementalTreeStats {
samples_processed: self.samples_processed,
buffer_size: self.buffer.len(),
current_accuracy: 0.0,
drift_detections: 0,
tree_updates: 0,
})
}
}
}
impl IncrementalDecisionTree<Trained> {
pub fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
if let Some(ref tree) = self.tree {
tree.predict(x)
} else {
Err(SklearsError::PredictError("Tree not trained".to_string()))
}
}
}
#[derive(Debug, Clone)]
pub struct IncrementalTreeStats {
pub samples_processed: usize,
pub buffer_size: usize,
pub current_accuracy: f64,
pub drift_detections: usize,
pub tree_updates: usize,
}