use crate::gradient_boosting::{GradientBoostingRegressor, TrainedGradientBoostingRegressor};
use scirs2_core::ndarray::{s, Array1, Array2};
use sklears_core::{
error::Result as SklResult,
prelude::SklearsError,
traits::{Estimator, Fit, Predict},
};
use std::f64;
#[derive(Debug, Clone)]
pub struct TimeSeriesEnsembleConfig {
pub window_size: usize,
pub n_estimators: usize,
pub temporal_overlap: f64,
pub use_seasonal_decomposition: bool,
pub seasonal_periods: Vec<usize>,
pub temporal_decay: f64,
pub drift_adaptation: DriftAdaptationStrategy,
pub cv_strategy: TimeSeriesCVStrategy,
pub aggregation_method: TemporalAggregationMethod,
}
impl Default for TimeSeriesEnsembleConfig {
fn default() -> Self {
Self {
window_size: 24,
n_estimators: 10,
temporal_overlap: 0.5,
use_seasonal_decomposition: true,
seasonal_periods: vec![7, 30, 365], temporal_decay: 0.95,
drift_adaptation: DriftAdaptationStrategy::SlidingWindow,
cv_strategy: TimeSeriesCVStrategy::TimeSeriesSplit,
aggregation_method: TemporalAggregationMethod::WeightedAverage,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum DriftAdaptationStrategy {
SlidingWindow,
ExponentialForgetting,
DynamicEnsemble,
OnlineWeightUpdate,
SeasonalAdaptation,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TimeSeriesCVStrategy {
TimeSeriesSplit,
BlockedCV,
PurgedTimeSeriesSplit,
WalkForward,
SlidingWindow,
}
#[derive(Debug, Clone, PartialEq)]
pub enum TemporalAggregationMethod {
SimpleAverage,
WeightedAverage,
MedianAggregation,
ExponentialSmoothing,
KalmanFilter,
BayesianTemporal,
}
#[allow(dead_code)] pub struct TimeSeriesEnsembleClassifier {
config: TimeSeriesEnsembleConfig,
base_models: Vec<TrainedGradientBoostingRegressor>,
temporal_weights: Vec<f64>,
seasonal_components: Option<SeasonalComponents>,
drift_detector: Option<Box<dyn ConceptDriftDetector>>,
is_fitted: bool,
}
pub struct TimeSeriesEnsembleRegressor {
config: TimeSeriesEnsembleConfig,
base_models: Vec<TrainedGradientBoostingRegressor>,
temporal_weights: Vec<f64>,
seasonal_components: Option<SeasonalComponents>,
drift_detector: Option<Box<dyn ConceptDriftDetector>>,
is_fitted: bool,
}
#[derive(Debug, Clone)]
pub struct SeasonalComponents {
pub trend: Vec<f64>,
pub seasonal: Vec<Vec<f64>>,
pub residual: Vec<f64>,
}
pub trait ConceptDriftDetector: Send + Sync {
fn detect_drift(&mut self, observations: &[f64]) -> bool;
fn reset(&mut self);
fn get_statistics(&self) -> DriftStatistics;
}
#[derive(Debug, Clone)]
pub struct DriftStatistics {
pub drift_points: usize,
pub avg_drift_interval: f64,
pub drift_confidence: f64,
pub time_since_drift: usize,
}
pub struct AdwinDriftDetector {
window: Vec<f64>,
max_window_size: usize,
delta: f64, min_window_size: usize,
drift_count: usize,
last_drift_time: usize,
current_time: usize,
}
impl AdwinDriftDetector {
pub fn new(delta: f64, max_window_size: usize, min_window_size: usize) -> Self {
Self {
window: Vec::new(),
max_window_size,
delta,
min_window_size,
drift_count: 0,
last_drift_time: 0,
current_time: 0,
}
}
fn cut_expression(&self, n0: f64, n1: f64, _u0: f64, _u1: f64) -> f64 {
let n = n0 + n1;
let delta_prime = self.delta / n;
let m = 1.0 / (2.0 * n0) + 1.0 / (2.0 * n1);
let log_term = (-delta_prime.ln()).max(0.0);
(2.0 * log_term / m).sqrt() + (2.0 * log_term / (3.0 * m)) / n
}
}
impl ConceptDriftDetector for AdwinDriftDetector {
fn detect_drift(&mut self, observations: &[f64]) -> bool {
for &obs in observations {
self.window.push(obs);
self.current_time += 1;
if self.window.len() > self.max_window_size {
self.window.remove(0);
}
if self.window.len() < self.min_window_size {
continue;
}
let n = self.window.len();
for i in 1..n {
let w0 = &self.window[0..i];
let w1 = &self.window[i..];
if w0.len() < self.min_window_size || w1.len() < self.min_window_size {
continue;
}
let u0: f64 = w0.iter().sum::<f64>() / w0.len() as f64;
let u1: f64 = w1.iter().sum::<f64>() / w1.len() as f64;
let cut_val = self.cut_expression(w0.len() as f64, w1.len() as f64, u0, u1);
if (u0 - u1).abs() > cut_val {
self.window.drain(0..i);
self.drift_count += 1;
self.last_drift_time = self.current_time;
return true;
}
}
}
false
}
fn reset(&mut self) {
self.window.clear();
self.drift_count = 0;
self.last_drift_time = 0;
self.current_time = 0;
}
fn get_statistics(&self) -> DriftStatistics {
let avg_drift_interval = if self.drift_count > 0 {
self.current_time as f64 / self.drift_count as f64
} else {
0.0
};
DriftStatistics {
drift_points: self.drift_count,
avg_drift_interval,
drift_confidence: if self.window.len() >= self.min_window_size {
0.95
} else {
0.0
},
time_since_drift: self.current_time - self.last_drift_time,
}
}
}
impl TimeSeriesEnsembleConfig {
pub fn builder() -> TimeSeriesEnsembleConfigBuilder {
TimeSeriesEnsembleConfigBuilder::default()
}
}
#[derive(Default)]
pub struct TimeSeriesEnsembleConfigBuilder {
config: TimeSeriesEnsembleConfig,
}
impl TimeSeriesEnsembleConfigBuilder {
pub fn window_size(mut self, window_size: usize) -> Self {
self.config.window_size = window_size;
self
}
pub fn n_estimators(mut self, n_estimators: usize) -> Self {
self.config.n_estimators = n_estimators;
self
}
pub fn temporal_overlap(mut self, temporal_overlap: f64) -> Self {
self.config.temporal_overlap = temporal_overlap;
self
}
pub fn seasonal_periods(mut self, periods: Vec<usize>) -> Self {
self.config.seasonal_periods = periods;
self
}
pub fn temporal_decay(mut self, decay: f64) -> Self {
self.config.temporal_decay = decay;
self
}
pub fn drift_adaptation(mut self, strategy: DriftAdaptationStrategy) -> Self {
self.config.drift_adaptation = strategy;
self
}
pub fn cv_strategy(mut self, strategy: TimeSeriesCVStrategy) -> Self {
self.config.cv_strategy = strategy;
self
}
pub fn aggregation_method(mut self, method: TemporalAggregationMethod) -> Self {
self.config.aggregation_method = method;
self
}
pub fn use_seasonal_decomposition(mut self, use_seasonal: bool) -> Self {
self.config.use_seasonal_decomposition = use_seasonal;
self
}
pub fn build(self) -> TimeSeriesEnsembleConfig {
self.config
}
}
impl TimeSeriesEnsembleRegressor {
pub fn new(config: TimeSeriesEnsembleConfig) -> Self {
Self {
config,
base_models: Vec::new(),
temporal_weights: Vec::new(),
seasonal_components: None,
drift_detector: None,
is_fitted: false,
}
}
pub fn builder() -> TimeSeriesEnsembleRegressorBuilder {
TimeSeriesEnsembleRegressorBuilder::new()
}
fn create_time_features(&self, data: &Array2<f64>) -> SklResult<Array2<f64>> {
let shape = data.shape();
let (n_samples, n_features) = (shape[0], shape[1]);
let window_size = self.config.window_size;
if n_samples < window_size {
return Err(SklearsError::InvalidInput(format!(
"Not enough samples ({}) for window size ({})",
n_samples, window_size
)));
}
let n_output_samples = n_samples - window_size + 1;
let n_output_features = n_features * window_size;
let mut features = Array2::zeros((n_output_samples, n_output_features));
for i in 0..n_output_samples {
for j in 0..window_size {
for k in 0..n_features {
features[[i, j * n_features + k]] = data[[i + j, k]];
}
}
}
Ok(features)
}
fn extract_seasonal_components(&mut self, y: &[f64]) -> SklResult<()> {
if !self.config.use_seasonal_decomposition {
return Ok(());
}
let n = y.len();
let mut trend = vec![0.0; n];
let mut seasonal = Vec::new();
let mut residual = vec![0.0; n];
let ma_window = 12.min(n / 4);
for i in ma_window / 2..n - ma_window / 2 {
let sum: f64 = y[i - ma_window / 2..i + ma_window / 2 + 1].iter().sum();
trend[i] = sum / (ma_window + 1) as f64;
}
for &period in &self.config.seasonal_periods {
if period > n {
continue;
}
let mut period_seasonal = vec![0.0; period];
let mut counts = vec![0; period];
for i in 0..n {
let seasonal_idx = i % period;
period_seasonal[seasonal_idx] += y[i] - trend[i];
counts[seasonal_idx] += 1;
}
for i in 0..period {
if counts[i] > 0 {
period_seasonal[i] /= counts[i] as f64;
}
}
seasonal.push(period_seasonal);
}
for i in 0..n {
residual[i] = y[i] - trend[i];
for (idx, &period) in self.config.seasonal_periods.iter().enumerate() {
if idx < seasonal.len() && period <= n {
residual[i] -= seasonal[idx][i % period];
}
}
}
self.seasonal_components = Some(SeasonalComponents {
trend,
seasonal,
residual,
});
Ok(())
}
#[allow(dead_code, clippy::needless_range_loop)] fn update_temporal_weights(&mut self, recent_errors: &[f64]) {
let n_models = self.base_models.len();
if n_models == 0 {
return;
}
self.temporal_weights = vec![1.0 / n_models as f64; n_models];
if recent_errors.len() != n_models {
return;
}
let total_error: f64 = recent_errors.iter().sum();
if total_error > 0.0 {
for i in 0..n_models {
let inv_error = 1.0 / (recent_errors[i] + 1e-8);
let temporal_factor = self.config.temporal_decay.powi(i as i32);
self.temporal_weights[i] = inv_error * temporal_factor;
}
let sum_weights: f64 = self.temporal_weights.iter().sum();
if sum_weights > 0.0 {
for weight in &mut self.temporal_weights {
*weight /= sum_weights;
}
}
}
}
#[allow(clippy::needless_range_loop)] fn aggregate_predictions(&self, predictions: &[Vec<f64>]) -> SklResult<Vec<f64>> {
if predictions.is_empty() {
return Err(SklearsError::InvalidInput(
"No predictions to aggregate".to_string(),
));
}
let n_samples = predictions[0].len();
let mut result = vec![0.0; n_samples];
match self.config.aggregation_method {
TemporalAggregationMethod::SimpleAverage => {
for pred in predictions {
for (i, &p) in pred.iter().enumerate() {
result[i] += p;
}
}
for r in &mut result {
*r /= predictions.len() as f64;
}
}
TemporalAggregationMethod::WeightedAverage => {
for (j, pred) in predictions.iter().enumerate() {
let weight = if j < self.temporal_weights.len() {
self.temporal_weights[j]
} else {
1.0 / predictions.len() as f64
};
for (i, &p) in pred.iter().enumerate() {
result[i] += p * weight;
}
}
}
TemporalAggregationMethod::MedianAggregation => {
for i in 0..n_samples {
let mut values: Vec<f64> = predictions.iter().map(|p| p[i]).collect();
values.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
result[i] = if values.len().is_multiple_of(2) {
(values[values.len() / 2 - 1] + values[values.len() / 2]) / 2.0
} else {
values[values.len() / 2]
};
}
}
TemporalAggregationMethod::ExponentialSmoothing => {
let alpha = 0.3; for i in 0..n_samples {
result[i] = predictions[0][i];
for j in 1..predictions.len() {
result[i] = alpha * predictions[j][i] + (1.0 - alpha) * result[i];
}
}
}
_ => {
for pred in predictions {
for (i, &p) in pred.iter().enumerate() {
result[i] += p;
}
}
for r in &mut result {
*r /= predictions.len() as f64;
}
}
}
Ok(result)
}
}
pub struct TimeSeriesEnsembleRegressorBuilder {
config: TimeSeriesEnsembleConfig,
}
impl Default for TimeSeriesEnsembleRegressorBuilder {
fn default() -> Self {
Self::new()
}
}
impl TimeSeriesEnsembleRegressorBuilder {
pub fn new() -> Self {
Self {
config: TimeSeriesEnsembleConfig::default(),
}
}
pub fn config(mut self, config: TimeSeriesEnsembleConfig) -> Self {
self.config = config;
self
}
pub fn window_size(mut self, window_size: usize) -> Self {
self.config.window_size = window_size;
self
}
pub fn n_estimators(mut self, n_estimators: usize) -> Self {
self.config.n_estimators = n_estimators;
self
}
pub fn temporal_decay(mut self, decay: f64) -> Self {
self.config.temporal_decay = decay;
self
}
pub fn drift_adaptation(mut self, strategy: DriftAdaptationStrategy) -> Self {
self.config.drift_adaptation = strategy;
self
}
pub fn build(self) -> TimeSeriesEnsembleRegressor {
TimeSeriesEnsembleRegressor::new(self.config)
}
}
impl Estimator for TimeSeriesEnsembleRegressor {
type Config = TimeSeriesEnsembleConfig;
type Error = SklearsError;
type Float = f64;
fn config(&self) -> &Self::Config {
&self.config
}
}
impl Fit<Array2<f64>, Vec<f64>> for TimeSeriesEnsembleRegressor {
type Fitted = Self;
#[allow(non_snake_case)]
fn fit(mut self, X: &Array2<f64>, y: &Vec<f64>) -> SklResult<Self::Fitted> {
if X.shape()[0] != y.len() {
return Err(SklearsError::ShapeMismatch {
expected: format!("X and y must have same number of samples: {}", y.len()),
actual: format!(
"X has {} samples but y has {} samples",
X.shape()[0],
y.len()
),
});
}
self.extract_seasonal_components(y)?;
let time_features = self.create_time_features(X)?;
let n_time_samples = time_features.shape()[0];
let y_time = &y[self.config.window_size - 1..];
if matches!(
self.config.drift_adaptation,
DriftAdaptationStrategy::SlidingWindow
) {
self.drift_detector = Some(Box::new(AdwinDriftDetector::new(0.002, 1000, 30)));
}
self.base_models.clear();
let overlap_size = (n_time_samples as f64 * self.config.temporal_overlap) as usize;
let step_size = (n_time_samples - overlap_size) / self.config.n_estimators.max(1);
for i in 0..self.config.n_estimators {
let start_idx = i * step_size;
let end_idx = (start_idx + overlap_size + step_size).min(n_time_samples);
if end_idx <= start_idx {
break;
}
let X_subset = time_features.slice(s![start_idx..end_idx, ..]);
let y_subset = &y_time[start_idx..end_idx];
let X_subset_owned = X_subset.to_owned();
let y_subset_owned = Array1::from_vec(y_subset.to_vec());
let model = GradientBoostingRegressor::builder()
.n_estimators(50)
.learning_rate(0.1)
.max_depth(6)
.build()
.fit(&X_subset_owned, &y_subset_owned)?;
self.base_models.push(model);
}
self.temporal_weights = vec![1.0 / self.base_models.len() as f64; self.base_models.len()];
self.is_fitted = true;
Ok(self)
}
}
impl Predict<Array2<f64>, Vec<f64>> for TimeSeriesEnsembleRegressor {
#[allow(non_snake_case)] fn predict(&self, X: &Array2<f64>) -> SklResult<Vec<f64>> {
if !self.is_fitted {
return Err(SklearsError::NotFitted {
operation: "prediction".to_string(),
});
}
let time_features = self.create_time_features(X)?;
let mut predictions = Vec::new();
for model in &self.base_models {
let pred = model.predict(&time_features)?;
let pred_vec: Vec<f64> = pred.to_vec();
predictions.push(pred_vec);
}
self.aggregate_predictions(&predictions)
}
}
#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
use super::*;
use scirs2_core::ndarray::Array2;
#[test]
fn test_time_series_ensemble_config() {
let config = TimeSeriesEnsembleConfig::builder()
.window_size(12)
.n_estimators(5)
.temporal_decay(0.9)
.build();
assert_eq!(config.window_size, 12);
assert_eq!(config.n_estimators, 5);
assert_eq!(config.temporal_decay, 0.9);
}
#[test]
fn test_adwin_drift_detector() {
let mut detector = AdwinDriftDetector::new(0.01, 1000, 30);
let stable_data = vec![1.0; 50];
assert!(!detector.detect_drift(&stable_data));
let mut drift_data = vec![1.0; 30];
drift_data.extend(vec![100.0; 30]);
let drift_detected = detector.detect_drift(&drift_data);
assert!(
drift_detected,
"ADWIN should detect significant drift from 1.0 to 100.0"
);
}
#[test]
#[allow(non_snake_case)]
fn test_time_series_ensemble_basic() {
let config = TimeSeriesEnsembleConfig::builder()
.window_size(3)
.n_estimators(3)
.build();
let ensemble = TimeSeriesEnsembleRegressor::new(config);
let data = vec![1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 6.0];
let _X = Array2::from_shape_vec((5, 2), data).expect("shape and data length should match");
let _y: Vec<f64> = vec![1.0, 2.0, 3.0, 4.0, 5.0];
assert_eq!(ensemble.config.window_size, 3);
assert_eq!(ensemble.config.n_estimators, 3);
}
#[test]
fn test_seasonal_decomposition() {
let config = TimeSeriesEnsembleConfig::builder()
.window_size(4)
.use_seasonal_decomposition(true)
.seasonal_periods(vec![7])
.build();
let mut ensemble = TimeSeriesEnsembleRegressor::new(config);
let y: Vec<f64> = (0..28)
.map(|i| (i as f64 / 7.0 * 2.0 * std::f64::consts::PI).sin())
.collect();
ensemble
.extract_seasonal_components(&y)
.expect("operation should succeed");
assert!(ensemble.seasonal_components.is_some());
let components = ensemble
.seasonal_components
.expect("operation should succeed");
assert_eq!(components.trend.len(), 28);
assert_eq!(components.seasonal.len(), 1);
assert_eq!(components.seasonal[0].len(), 7);
assert_eq!(components.residual.len(), 28);
}
}