rustkernel_temporal/
types.rs

1//! Temporal analysis types and data structures.
2
3use serde::{Deserialize, Serialize};
4
5// ============================================================================
6// Time Series Types
7// ============================================================================
8
9/// A time series data structure.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct TimeSeries {
12    /// Values in the series.
13    pub values: Vec<f64>,
14    /// Timestamps (optional, defaults to sequential indices).
15    pub timestamps: Option<Vec<u64>>,
16    /// Frequency in seconds (optional).
17    pub frequency: Option<u64>,
18}
19
20impl TimeSeries {
21    /// Create a new time series from values.
22    pub fn new(values: Vec<f64>) -> Self {
23        Self {
24            values,
25            timestamps: None,
26            frequency: None,
27        }
28    }
29
30    /// Create a time series with timestamps.
31    pub fn with_timestamps(values: Vec<f64>, timestamps: Vec<u64>) -> Self {
32        Self {
33            values,
34            timestamps: Some(timestamps),
35            frequency: None,
36        }
37    }
38
39    /// Get the length of the series.
40    pub fn len(&self) -> usize {
41        self.values.len()
42    }
43
44    /// Check if the series is empty.
45    pub fn is_empty(&self) -> bool {
46        self.values.is_empty()
47    }
48
49    /// Get the mean of the series.
50    pub fn mean(&self) -> f64 {
51        if self.values.is_empty() {
52            return 0.0;
53        }
54        self.values.iter().sum::<f64>() / self.values.len() as f64
55    }
56
57    /// Get the variance of the series.
58    pub fn variance(&self) -> f64 {
59        if self.values.len() < 2 {
60            return 0.0;
61        }
62        let mean = self.mean();
63        self.values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (self.values.len() - 1) as f64
64    }
65
66    /// Get the standard deviation.
67    pub fn std_dev(&self) -> f64 {
68        self.variance().sqrt()
69    }
70}
71
72// ============================================================================
73// Forecasting Types
74// ============================================================================
75
76/// ARIMA model parameters.
77#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
78pub struct ARIMAParams {
79    /// AR order (p).
80    pub p: usize,
81    /// Differencing order (d).
82    pub d: usize,
83    /// MA order (q).
84    pub q: usize,
85}
86
87impl ARIMAParams {
88    /// Create new ARIMA parameters.
89    pub fn new(p: usize, d: usize, q: usize) -> Self {
90        Self { p, d, q }
91    }
92}
93
94/// Result of ARIMA fitting and forecasting.
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct ARIMAResult {
97    /// AR coefficients.
98    pub ar_coefficients: Vec<f64>,
99    /// MA coefficients.
100    pub ma_coefficients: Vec<f64>,
101    /// Intercept/constant term.
102    pub intercept: f64,
103    /// Fitted values.
104    pub fitted: Vec<f64>,
105    /// Residuals.
106    pub residuals: Vec<f64>,
107    /// Forecasted values.
108    pub forecast: Vec<f64>,
109    /// AIC (Akaike Information Criterion).
110    pub aic: f64,
111}
112
113/// Prophet-style decomposition result.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct ProphetResult {
116    /// Trend component.
117    pub trend: Vec<f64>,
118    /// Seasonal component (if present).
119    pub seasonal: Option<Vec<f64>>,
120    /// Holiday/event effects (if present).
121    pub holidays: Option<Vec<f64>>,
122    /// Residuals.
123    pub residuals: Vec<f64>,
124    /// Forecast values.
125    pub forecast: Vec<f64>,
126}
127
128// ============================================================================
129// Decomposition Types
130// ============================================================================
131
132/// Seasonal decomposition result (STL-like).
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct DecompositionResult {
135    /// Trend component.
136    pub trend: Vec<f64>,
137    /// Seasonal component.
138    pub seasonal: Vec<f64>,
139    /// Residual component.
140    pub residual: Vec<f64>,
141    /// Original series length.
142    pub n: usize,
143    /// Seasonal period used.
144    pub period: usize,
145}
146
147/// Type of trend extraction method.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
149pub enum TrendMethod {
150    /// Simple moving average.
151    SimpleMovingAverage,
152    /// Exponential moving average.
153    ExponentialMovingAverage,
154    /// Centered moving average.
155    CenteredMovingAverage,
156    /// Lowess smoothing.
157    Lowess,
158}
159
160/// Trend extraction result.
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct TrendResult {
163    /// Extracted trend.
164    pub trend: Vec<f64>,
165    /// Detrended series.
166    pub detrended: Vec<f64>,
167    /// Method used.
168    pub method: TrendMethod,
169}
170
171// ============================================================================
172// Detection Types
173// ============================================================================
174
175/// Change point detection result.
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct ChangePointResult {
178    /// Indices of detected change points.
179    pub change_points: Vec<usize>,
180    /// Confidence scores for each change point (0-1).
181    pub confidence: Vec<f64>,
182    /// Segment means.
183    pub segment_means: Vec<f64>,
184    /// Segment variances.
185    pub segment_variances: Vec<f64>,
186    /// Total cost (for PELT).
187    pub cost: f64,
188}
189
190/// Change point detection method.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
192pub enum ChangePointMethod {
193    /// PELT (Pruned Exact Linear Time).
194    PELT,
195    /// Binary segmentation.
196    BinarySegmentation,
197    /// CUSUM (Cumulative Sum).
198    CUSUM,
199}
200
201/// Anomaly detection result for time series.
202#[derive(Debug, Clone, Serialize, Deserialize)]
203pub struct TimeSeriesAnomalyResult {
204    /// Anomaly scores per point.
205    pub scores: Vec<f64>,
206    /// Indices of detected anomalies.
207    pub anomaly_indices: Vec<usize>,
208    /// Expected values (for context).
209    pub expected: Vec<f64>,
210    /// Threshold used for detection.
211    pub threshold: f64,
212}
213
214/// Method for time series anomaly detection.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
216pub enum AnomalyMethod {
217    /// Z-score based.
218    ZScore,
219    /// IQR (Interquartile Range) based.
220    IQR,
221    /// Moving average deviation.
222    MovingAverageDeviation,
223    /// Seasonal hybrid ESD (Twitter's algorithm).
224    SeasonalESD,
225}
226
227// ============================================================================
228// Volatility Types
229// ============================================================================
230
231/// GARCH model parameters.
232#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
233pub struct GARCHParams {
234    /// ARCH order (p).
235    pub p: usize,
236    /// GARCH order (q).
237    pub q: usize,
238}
239
240impl GARCHParams {
241    /// Create new GARCH parameters.
242    pub fn new(p: usize, q: usize) -> Self {
243        Self { p, q }
244    }
245}
246
247/// Volatility analysis result.
248#[derive(Debug, Clone, Serialize, Deserialize)]
249pub struct VolatilityResult {
250    /// Estimated conditional variance series.
251    pub variance: Vec<f64>,
252    /// Estimated volatility (sqrt of variance).
253    pub volatility: Vec<f64>,
254    /// GARCH coefficients (omega, alpha, beta).
255    pub coefficients: GARCHCoefficients,
256    /// Forecasted volatility.
257    pub forecast: Vec<f64>,
258}
259
260/// GARCH model coefficients.
261#[derive(Debug, Clone, Default, Serialize, Deserialize)]
262pub struct GARCHCoefficients {
263    /// Omega (constant term).
264    pub omega: f64,
265    /// Alpha coefficients (ARCH terms).
266    pub alpha: Vec<f64>,
267    /// Beta coefficients (GARCH terms).
268    pub beta: Vec<f64>,
269}