use crate::device::WgpuDevice;
use crate::error::{BarracudaError, Result as BarracudaResult};
use crate::esn_v2::{ESN, ESNConfig};
#[derive(Debug, Clone)]
pub enum TimeSeriesModel {
ESN {
reservoir_size: usize,
spectral_radius: f32,
},
MovingAverage {
window: usize,
},
ExponentialSmoothing {
alpha: f32,
},
WeightedMovingAverage {
weights: Vec<f32>,
},
}
#[derive(Debug, Clone)]
pub struct ForecastConfig {
pub horizon: usize,
pub confidence_level: f32,
pub include_intervals: bool,
}
impl Default for ForecastConfig {
fn default() -> Self {
Self {
horizon: 10,
confidence_level: 0.95,
include_intervals: false,
}
}
}
#[derive(Debug, Clone)]
pub struct Forecast {
pub values: Vec<f32>,
pub lower_bound: Option<Vec<f32>>,
pub upper_bound: Option<Vec<f32>>,
pub horizon: usize,
}
#[derive(Debug, Clone)]
pub struct Anomaly {
pub index: usize,
pub value: f32,
pub expected: f32,
pub score: f32,
}
#[derive(Debug, Clone)]
pub struct Decomposition {
pub trend: Vec<f32>,
pub seasonal: Vec<f32>,
pub residual: Vec<f32>,
}
mod esn_defaults {
pub const CONNECTIVITY: f32 = 0.1;
pub const LEAK_RATE: f32 = 0.3;
pub const REGULARIZATION: f32 = 1e-6;
pub const SEED: u64 = 42;
}
const ANOMALY_WINDOW_FRACTION: usize = 10;
const ANOMALY_MIN_WINDOW: usize = 3;
pub struct TimeSeriesAnalyzer {
device: WgpuDevice,
models: Vec<TimeSeriesModel>,
esn_instance: Option<ESN>,
built: bool,
}
impl TimeSeriesAnalyzer {
#[must_use]
pub fn new(device: &WgpuDevice) -> Self {
Self {
device: device.clone(),
models: Vec::new(),
esn_instance: None,
built: false,
}
}
#[must_use]
pub fn device(&self) -> &WgpuDevice {
&self.device
}
#[must_use]
pub fn add_model(mut self, model: TimeSeriesModel) -> Self {
self.models.push(model);
self
}
pub async fn build(mut self) -> BarracudaResult<Self> {
for model in &self.models {
if let TimeSeriesModel::ESN {
reservoir_size,
spectral_radius,
} = model
{
let config = ESNConfig {
input_size: 1,
reservoir_size: *reservoir_size,
output_size: 1,
spectral_radius: *spectral_radius,
connectivity: esn_defaults::CONNECTIVITY,
leak_rate: esn_defaults::LEAK_RATE,
regularization: esn_defaults::REGULARIZATION,
seed: esn_defaults::SEED,
..Default::default()
};
self.esn_instance = Some(ESN::new(config).await?);
break; }
}
self.built = true;
Ok(self)
}
pub async fn forecast(&mut self, history: &[f32], horizon: usize) -> BarracudaResult<Forecast> {
if !self.built {
return Err(BarracudaError::InvalidInput {
message: "Analyzer not built. Call .build() first.".to_string(),
});
}
if history.is_empty() {
return Err(BarracudaError::InvalidInput {
message: "History cannot be empty".to_string(),
});
}
if self.models.is_empty() {
return Err(BarracudaError::InvalidInput {
message: "No models added. Use .add_model() before building.".to_string(),
});
}
match &self.models[0] {
TimeSeriesModel::ESN { .. } => self.forecast_esn(history, horizon).await,
TimeSeriesModel::MovingAverage { window } => {
self.forecast_moving_average(history, horizon, *window)
}
TimeSeriesModel::ExponentialSmoothing { alpha } => {
self.forecast_exponential_smoothing(history, horizon, *alpha)
}
TimeSeriesModel::WeightedMovingAverage { weights } => {
self.forecast_weighted_moving_average(history, horizon, weights)
}
}
}
pub async fn detect_anomalies(
&mut self,
series: &[f32],
threshold: f32,
) -> BarracudaResult<Vec<Anomaly>> {
if series.len() < 10 {
return Err(BarracudaError::InvalidInput {
message: "Series too short for anomaly detection (need at least 10 points)"
.to_string(),
});
}
let window = (series.len() / ANOMALY_WINDOW_FRACTION).max(ANOMALY_MIN_WINDOW);
let mut anomalies = Vec::new();
for i in window..series.len() {
let window_data = &series[i.saturating_sub(window)..i];
let expected = window_data.iter().sum::<f32>() / window_data.len() as f32;
let actual = series[i];
let variance = window_data
.iter()
.map(|v| (v - expected).powi(2))
.sum::<f32>()
/ window_data.len() as f32;
let std_dev = variance.sqrt();
let score = (actual - expected).abs() / std_dev.max(0.01);
if score > threshold {
anomalies.push(Anomaly {
index: i,
value: actual,
expected,
score,
});
}
}
Ok(anomalies)
}
pub async fn decompose(&self, series: &[f32], period: usize) -> BarracudaResult<Decomposition> {
if series.len() < period * 2 {
return Err(BarracudaError::InvalidInput {
message: format!(
"Series too short for period {} (need at least {})",
period,
period * 2
),
});
}
let mut trend = vec![0.0f32; series.len()];
let window = period;
for i in window / 2..series.len() - window / 2 {
let sum: f32 = series[i - window / 2..i + window / 2].iter().sum();
trend[i] = sum / window as f32;
}
for i in 0..window / 2 {
trend[i] = trend[window / 2];
}
for i in series.len() - window / 2..series.len() {
trend[i] = trend[series.len() - window / 2 - 1];
}
let detrended: Vec<f32> = series
.iter()
.zip(trend.iter())
.map(|(s, t)| s - t)
.collect();
let mut seasonal = vec![0.0f32; series.len()];
for i in 0..period {
let mut sum = 0.0;
let mut count = 0;
for j in (i..series.len()).step_by(period) {
sum += detrended[j];
count += 1;
}
let avg = if count > 0 { sum / count as f32 } else { 0.0 };
for j in (i..series.len()).step_by(period) {
seasonal[j] = avg;
}
}
let residual: Vec<f32> = detrended
.iter()
.zip(seasonal.iter())
.map(|(d, s)| d - s)
.collect();
Ok(Decomposition {
trend,
seasonal,
residual,
})
}
async fn forecast_esn(&mut self, history: &[f32], horizon: usize) -> BarracudaResult<Forecast> {
let esn = self
.esn_instance
.as_mut()
.ok_or_else(|| BarracudaError::InvalidInput {
message: "ESN not initialized".to_string(),
})?;
let sequence: Vec<Vec<f32>> = history.windows(2).map(|w| vec![w[0]]).collect();
let targets: Vec<Vec<f32>> = history.windows(2).map(|w| vec![w[1]]).collect();
let _training_error = esn.train(&sequence, &targets).await?;
let mut forecast_values = Vec::with_capacity(horizon);
let mut current_input = vec![history[history.len() - 1]];
for _ in 0..horizon {
let prediction = esn.predict(¤t_input).await?;
let next_value = prediction[0];
forecast_values.push(next_value);
current_input = vec![next_value];
}
Ok(Forecast {
values: forecast_values,
lower_bound: None,
upper_bound: None,
horizon,
})
}
fn forecast_moving_average(
&self,
history: &[f32],
horizon: usize,
window: usize,
) -> BarracudaResult<Forecast> {
let window = window.min(history.len());
let last_window = &history[history.len() - window..];
let avg = last_window.iter().sum::<f32>() / window as f32;
let values = vec![avg; horizon];
Ok(Forecast {
values,
lower_bound: None,
upper_bound: None,
horizon,
})
}
fn forecast_exponential_smoothing(
&self,
history: &[f32],
horizon: usize,
alpha: f32,
) -> BarracudaResult<Forecast> {
let mut smoothed = history[0];
for &value in &history[1..] {
smoothed = alpha.mul_add(value, (1.0 - alpha) * smoothed);
}
let values = vec![smoothed; horizon];
Ok(Forecast {
values,
lower_bound: None,
upper_bound: None,
horizon,
})
}
fn forecast_weighted_moving_average(
&self,
history: &[f32],
horizon: usize,
weights: &[f32],
) -> BarracudaResult<Forecast> {
if weights.is_empty() {
return Err(BarracudaError::InvalidInput {
message: "Weights cannot be empty".to_string(),
});
}
let window = weights.len().min(history.len());
let last_window = &history[history.len() - window..];
let weighted_sum: f32 = last_window
.iter()
.zip(weights.iter())
.map(|(v, w)| v * w)
.sum();
let weight_sum: f32 = weights.iter().sum();
let forecast_value = weighted_sum / weight_sum;
let values = vec![forecast_value; horizon];
Ok(Forecast {
values,
lower_bound: None,
upper_bound: None,
horizon,
})
}
}
#[cfg(test)]
#[path = "timeseries_tests.rs"]
mod tests;