use crate::config::DecisionTreeConfig;
use scirs2_core::ndarray::{Array1, Array2};
use sklears_core::{error::Result, error::SklearsError};
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
#[derive(Debug, Clone)]
pub struct CustomSplit {
pub feature_idx: usize,
pub threshold: f64,
pub impurity_decrease: f64,
pub left_count: usize,
pub right_count: usize,
}
#[derive(Debug, Clone)]
pub struct SurrogateSplit {
pub feature_idx: usize,
pub threshold: f64,
pub agreement: f64, pub left_direction: bool, }
#[derive(Debug, Clone)]
pub struct CompactTreeNode {
pub packed_data: u64,
pub value: f32,
pub left_child: u32,
pub right_child: u32,
}
impl CompactTreeNode {
pub fn new_leaf(prediction: f64) -> Self {
Self {
packed_data: 0x8000_0000_0000_0000, value: prediction as f32,
left_child: 0,
right_child: 0,
}
}
pub fn new_split(feature_idx: u16, threshold: f32, impurity: f64) -> Self {
let mut packed_data = 0u64;
packed_data |= feature_idx as u64;
let threshold_bits = threshold.to_bits() as u64;
packed_data |= threshold_bits << 16;
Self {
packed_data,
value: impurity as f32,
left_child: 0,
right_child: 0,
}
}
pub fn is_leaf(&self) -> bool {
(self.packed_data & 0x8000_0000_0000_0000) != 0
}
pub fn feature_idx(&self) -> u16 {
(self.packed_data & 0xFFFF) as u16
}
pub fn threshold(&self) -> f32 {
let threshold_bits = ((self.packed_data >> 16) & 0xFFFFFFFF) as u32;
f32::from_bits(threshold_bits)
}
pub fn prediction(&self) -> f64 {
self.value as f64
}
pub fn impurity(&self) -> f64 {
self.value as f64
}
pub fn set_left_child(&mut self, child_idx: u32) {
self.left_child = child_idx;
}
pub fn set_right_child(&mut self, child_idx: u32) {
self.right_child = child_idx;
}
}
#[derive(Debug, Clone)]
pub struct CompactTree {
pub nodes: Vec<CompactTreeNode>,
pub feature_importances: Vec<f32>,
pub n_features: usize,
pub depth: usize,
}
impl CompactTree {
pub fn new(n_features: usize) -> Self {
Self {
nodes: Vec::new(),
feature_importances: vec![0.0; n_features],
n_features,
depth: 0,
}
}
pub fn add_node(&mut self, node: CompactTreeNode) -> u32 {
let idx = self.nodes.len() as u32;
self.nodes.push(node);
idx
}
pub fn predict_single(&self, sample: &[f64]) -> Result<f64> {
if self.nodes.is_empty() {
return Err(SklearsError::InvalidInput("Empty tree".to_string()));
}
let mut current_idx = 0;
loop {
if current_idx >= self.nodes.len() {
return Err(SklearsError::InvalidInput("Invalid node index".to_string()));
}
let node = &self.nodes[current_idx];
if node.is_leaf() {
return Ok(node.prediction());
}
let feature_idx = node.feature_idx() as usize;
if feature_idx >= sample.len() {
return Err(SklearsError::InvalidInput(
"Feature index out of bounds".to_string(),
));
}
let feature_value = sample[feature_idx];
let threshold = node.threshold() as f64;
if feature_value <= threshold {
current_idx = node.left_child as usize;
} else {
current_idx = node.right_child as usize;
}
if current_idx == 0 {
return Err(SklearsError::InvalidInput("Invalid child node".to_string()));
}
current_idx -= 1; }
}
pub fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
let n_samples = x.nrows();
let mut predictions = Array1::zeros(n_samples);
for i in 0..n_samples {
let sample = x.row(i).to_vec();
predictions[i] = self.predict_single(&sample)?;
}
Ok(predictions)
}
pub fn memory_usage(&self) -> usize {
let node_size = std::mem::size_of::<CompactTreeNode>();
let feature_importance_size = std::mem::size_of::<f32>() * self.feature_importances.len();
let metadata_size = std::mem::size_of::<Self>()
- std::mem::size_of::<Vec<CompactTreeNode>>()
- std::mem::size_of::<Vec<f32>>();
self.nodes.len() * node_size + feature_importance_size + metadata_size
}
pub fn n_nodes(&self) -> usize {
self.nodes.len()
}
pub fn n_leaves(&self) -> usize {
self.nodes.iter().filter(|node| node.is_leaf()).count()
}
}
#[derive(Debug, Clone)]
pub struct BitPackedPath {
pub path_bits: u128,
pub path_length: u8,
pub prediction: f32,
}
impl Default for BitPackedPath {
fn default() -> Self {
Self::new()
}
}
impl BitPackedPath {
pub fn new() -> Self {
Self {
path_bits: 0,
path_length: 0,
prediction: 0.0,
}
}
pub fn add_decision(&mut self, go_right: bool) -> Result<()> {
if self.path_length >= 127 {
return Err(SklearsError::InvalidInput("Path too long".to_string()));
}
if go_right {
self.path_bits |= 1u128 << self.path_length;
}
self.path_length += 1;
Ok(())
}
pub fn get_decision(&self, position: u8) -> bool {
if position >= self.path_length {
return false;
}
(self.path_bits & (1u128 << position)) != 0
}
pub fn set_prediction(&mut self, prediction: f64) {
self.prediction = prediction as f32;
}
pub fn get_prediction(&self) -> f64 {
self.prediction as f64
}
}
#[derive(Debug, Clone)]
pub struct BitPackedTree {
pub paths: Vec<BitPackedPath>,
pub feature_indices: Vec<u16>,
pub thresholds: Vec<f32>,
pub n_features: usize,
}
impl BitPackedTree {
pub fn new(n_features: usize) -> Self {
Self {
paths: Vec::new(),
feature_indices: Vec::new(),
thresholds: Vec::new(),
n_features,
}
}
pub fn add_path(&mut self, path: BitPackedPath) {
self.paths.push(path);
}
pub fn memory_usage(&self) -> usize {
let path_size = std::mem::size_of::<BitPackedPath>() * self.paths.len();
let feature_size = std::mem::size_of::<u16>() * self.feature_indices.len();
let threshold_size = std::mem::size_of::<f32>() * self.thresholds.len();
let metadata_size = std::mem::size_of::<Self>()
- std::mem::size_of::<Vec<BitPackedPath>>()
- std::mem::size_of::<Vec<u16>>()
- std::mem::size_of::<Vec<f32>>();
path_size + feature_size + threshold_size + metadata_size
}
}
#[derive(Debug, Clone)]
pub struct CompactEnsemble {
pub trees: Vec<CompactTree>,
pub global_feature_importances: Vec<f32>,
pub n_features: usize,
pub n_trees: usize,
}
impl CompactEnsemble {
pub fn new(n_features: usize) -> Self {
Self {
trees: Vec::new(),
global_feature_importances: vec![0.0; n_features],
n_features,
n_trees: 0,
}
}
pub fn add_tree(&mut self, tree: CompactTree) {
self.trees.push(tree);
self.n_trees += 1;
}
pub fn total_memory_usage(&self) -> usize {
let trees_memory: usize = self.trees.iter().map(|t| t.memory_usage()).sum();
let importance_memory = std::mem::size_of::<f32>() * self.global_feature_importances.len();
let metadata_memory = std::mem::size_of::<Self>()
- std::mem::size_of::<Vec<CompactTree>>()
- std::mem::size_of::<Vec<f32>>();
trees_memory + importance_memory + metadata_memory
}
}
#[derive(Debug, Clone)]
pub struct TreeNode {
pub id: usize,
pub depth: usize,
pub sample_indices: Vec<usize>,
pub impurity: f64,
pub prediction: f64,
pub potential_decrease: f64,
pub best_split: Option<CustomSplit>,
pub parent_id: Option<usize>,
pub is_leaf: bool,
}
#[derive(Debug, Clone)]
pub struct NodePriority {
pub node_id: usize,
pub priority: f64, }
impl PartialEq for NodePriority {
fn eq(&self, other: &Self) -> bool {
self.priority == other.priority
}
}
impl Eq for NodePriority {}
impl PartialOrd for NodePriority {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NodePriority {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other
.priority
.partial_cmp(&self.priority)
.unwrap_or(std::cmp::Ordering::Equal)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OrderedFloat(pub f64);
impl Eq for OrderedFloat {}
impl PartialOrd for OrderedFloat {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl std::hash::Hash for OrderedFloat {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
impl std::cmp::Ord for OrderedFloat {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.0
.partial_cmp(&other.0)
.unwrap_or(std::cmp::Ordering::Equal)
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct SubtreePattern {
pub depth: usize,
pub min_samples: usize,
pub splits: Vec<(usize, OrderedFloat)>,
}
#[derive(Debug, Clone)]
pub struct SubtreeConfig {
pub min_samples_for_sharing: usize,
pub max_shared_depth: usize,
pub min_pattern_frequency: usize,
pub enabled: bool,
}
impl Default for SubtreeConfig {
fn default() -> Self {
Self {
min_samples_for_sharing: 10,
max_shared_depth: 3,
min_pattern_frequency: 2,
enabled: false,
}
}
}
#[derive(Debug, Clone)]
pub struct SharedTreeNode {
pub id: usize,
pub feature_idx: Option<usize>,
pub threshold: Option<f64>,
pub prediction: f64,
pub n_samples: usize,
pub impurity: f64,
pub left_child: Option<usize>,
pub right_child: Option<usize>,
pub subtree_hash: u64,
}
#[derive(Debug, Clone)]
pub struct SubtreeSharingStats {
pub total_shared_nodes: usize,
pub total_patterns: usize,
pub estimated_memory_saved: usize,
pub sharing_efficiency: f64,
}
#[derive(Debug, Clone)]
pub struct SubtreeReference {
pub shared_id: usize,
pub local_node_id: usize,
pub tree_id: usize,
}
#[derive(Debug, Clone)]
pub struct SharedSubtreeManager {
pub shared_nodes: Arc<RwLock<HashMap<usize, SharedTreeNode>>>,
pub pattern_cache: Arc<RwLock<HashMap<SubtreePattern, usize>>>,
pub next_node_id: Arc<RwLock<usize>>,
pub config: SubtreeConfig,
}
impl SharedSubtreeManager {
pub fn new(config: SubtreeConfig) -> Self {
Self {
shared_nodes: Arc::new(RwLock::new(HashMap::new())),
pattern_cache: Arc::new(RwLock::new(HashMap::new())),
next_node_id: Arc::new(RwLock::new(0)),
config,
}
}
pub fn extract_patterns(&self, tree_nodes: &[TreeNode]) -> Result<Vec<SubtreePattern>> {
if !self.config.enabled {
return Ok(vec![]);
}
let mut patterns = Vec::new();
for node in tree_nodes {
if node.is_leaf || node.sample_indices.len() < self.config.min_samples_for_sharing {
continue;
}
if let Some(pattern) = self.extract_pattern_from_node(tree_nodes, node.id, 0) {
patterns.push(pattern);
}
}
Ok(patterns)
}
fn extract_pattern_from_node(
&self,
tree_nodes: &[TreeNode],
node_id: usize,
current_depth: usize,
) -> Option<SubtreePattern> {
if current_depth >= self.config.max_shared_depth {
return None;
}
if node_id >= tree_nodes.len() {
return None;
}
let node = &tree_nodes[node_id];
if node.is_leaf {
return Some(SubtreePattern {
depth: current_depth,
min_samples: node.sample_indices.len(),
splits: vec![],
});
}
let mut splits = Vec::new();
if let Some(ref split) = node.best_split {
splits.push((split.feature_idx, OrderedFloat(split.threshold)));
}
Some(SubtreePattern {
depth: current_depth,
min_samples: node.sample_indices.len(),
splits,
})
}
pub fn get_or_create_shared_subtree(
&self,
pattern: &SubtreePattern,
tree_nodes: &[TreeNode],
root_node_id: usize,
) -> Result<usize> {
{
let cache = self.pattern_cache.read().expect("operation should succeed");
if let Some(&shared_id) = cache.get(pattern) {
return Ok(shared_id);
}
}
let shared_id = {
let mut next_id = self.next_node_id.write().expect("operation should succeed");
let id = *next_id;
*next_id += 1;
id
};
let shared_node = self.create_shared_node(tree_nodes, root_node_id, shared_id)?;
{
let mut nodes = self.shared_nodes.write().expect("operation should succeed");
nodes.insert(shared_id, shared_node);
}
{
let mut cache = self
.pattern_cache
.write()
.expect("operation should succeed");
cache.insert(pattern.clone(), shared_id);
}
Ok(shared_id)
}
fn create_shared_node(
&self,
tree_nodes: &[TreeNode],
node_id: usize,
shared_id: usize,
) -> Result<SharedTreeNode> {
if node_id >= tree_nodes.len() {
return Err(SklearsError::InvalidInput("Invalid node ID".to_string()));
}
let node = &tree_nodes[node_id];
let subtree_hash = self.calculate_subtree_hash(tree_nodes, node_id);
let (feature_idx, threshold) = if let Some(ref split) = node.best_split {
(Some(split.feature_idx), Some(split.threshold))
} else {
(None, None)
};
Ok(SharedTreeNode {
id: shared_id,
feature_idx,
threshold,
prediction: node.prediction,
n_samples: node.sample_indices.len(),
impurity: node.impurity,
left_child: None, right_child: None, subtree_hash,
})
}
fn calculate_subtree_hash(&self, tree_nodes: &[TreeNode], node_id: usize) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
let mut hasher = DefaultHasher::new();
self.hash_subtree_recursive(tree_nodes, node_id, &mut hasher, 0);
hasher.finish()
}
fn hash_subtree_recursive(
&self,
tree_nodes: &[TreeNode],
node_id: usize,
hasher: &mut dyn std::hash::Hasher,
depth: usize,
) {
if depth >= self.config.max_shared_depth || node_id >= tree_nodes.len() {
return;
}
let node = &tree_nodes[node_id];
hasher.write_u8(if node.is_leaf { 1 } else { 0 });
if let Some(ref split) = node.best_split {
hasher.write_usize(split.feature_idx);
hasher.write(&split.threshold.to_le_bytes());
}
}
pub fn calculate_memory_savings(&self) -> Result<SubtreeSharingStats> {
let shared_nodes = self.shared_nodes.read().expect("operation should succeed");
let pattern_cache = self.pattern_cache.read().expect("operation should succeed");
let total_shared_nodes = shared_nodes.len();
let total_patterns = pattern_cache.len();
let estimated_memory_saved = total_shared_nodes * std::mem::size_of::<SharedTreeNode>();
Ok(SubtreeSharingStats {
total_shared_nodes,
total_patterns,
estimated_memory_saved,
sharing_efficiency: if total_patterns > 0 {
total_shared_nodes as f64 / total_patterns as f64
} else {
0.0
},
})
}
}
#[derive(Debug, Clone)]
pub struct TreeSpecificData {
pub tree_id: usize,
pub sample_weights: Vec<f64>,
pub config: DecisionTreeConfig,
pub local_nodes: Vec<TreeNode>,
}
#[derive(Debug, Clone)]
pub struct SharedTreeEnsemble {
pub subtree_manager: SharedSubtreeManager,
pub tree_specific_data: Vec<TreeSpecificData>,
pub subtree_references: Vec<SubtreeReference>,
}
impl SharedTreeEnsemble {
pub fn new(subtree_config: SubtreeConfig) -> Self {
Self {
subtree_manager: SharedSubtreeManager::new(subtree_config),
tree_specific_data: Vec::new(),
subtree_references: Vec::new(),
}
}
pub fn add_tree(
&mut self,
tree_nodes: Vec<TreeNode>,
config: DecisionTreeConfig,
tree_id: usize,
) -> Result<()> {
let patterns = self.subtree_manager.extract_patterns(&tree_nodes)?;
for pattern in patterns {
if let Ok(shared_id) = self.subtree_manager.get_or_create_shared_subtree(
&pattern,
&tree_nodes,
0, ) {
self.subtree_references.push(SubtreeReference {
shared_id,
local_node_id: 0,
tree_id,
});
}
}
let tree_data = TreeSpecificData {
tree_id,
sample_weights: vec![1.0; tree_nodes.len()], config,
local_nodes: tree_nodes,
};
self.tree_specific_data.push(tree_data);
Ok(())
}
pub fn get_sharing_stats(&self) -> Result<SubtreeSharingStats> {
self.subtree_manager.calculate_memory_savings()
}
}