torsh-series 0.1.2

Time series analysis components for ToRSh - powered by SciRS2
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Frequency domain analysis for time series
//!
//! This module provides comprehensive frequency domain analysis tools:
//! - Fast Fourier Transform (FFT) and inverse FFT
//! - Power Spectral Density (PSD) estimation
//! - Periodogram analysis
//! - Spectral density estimation (Welch's method, multi-taper)
//! - Coherence analysis for multivariate series
//!
//! NOTE: This module provides the structure for frequency analysis.
//! Full implementation will use scirs2-signal when FFT APIs are available.

use crate::TimeSeries;
use torsh_core::error::{Result, TorshError};
use torsh_tensor::Tensor;

/// FFT result containing complex frequency components
#[derive(Debug, Clone)]
pub struct FFTResult {
    /// Real parts of FFT coefficients
    pub real: Vec<f64>,
    /// Imaginary parts of FFT coefficients
    pub imag: Vec<f64>,
    /// Frequencies corresponding to each coefficient
    pub frequencies: Vec<f64>,
    /// Sampling rate used
    pub sampling_rate: f64,
}

impl FFTResult {
    /// Get magnitude spectrum
    pub fn magnitude(&self) -> Vec<f64> {
        self.real
            .iter()
            .zip(self.imag.iter())
            .map(|(r, i)| (r * r + i * i).sqrt())
            .collect()
    }

    /// Get phase spectrum
    pub fn phase(&self) -> Vec<f64> {
        self.real
            .iter()
            .zip(self.imag.iter())
            .map(|(r, i)| i.atan2(*r))
            .collect()
    }

    /// Get power spectrum (magnitude squared)
    pub fn power(&self) -> Vec<f64> {
        self.real
            .iter()
            .zip(self.imag.iter())
            .map(|(r, i)| r * r + i * i)
            .collect()
    }
}

/// Power Spectral Density estimation result
#[derive(Debug, Clone)]
pub struct PSDResult {
    /// Power spectral density values
    pub psd: Vec<f64>,
    /// Frequencies
    pub frequencies: Vec<f64>,
    /// Method used for estimation
    pub method: String,
}

/// Periodogram analysis result
#[derive(Debug, Clone)]
pub struct Periodogram {
    /// Power at each frequency
    pub power: Vec<f64>,
    /// Frequencies
    pub frequencies: Vec<f64>,
    /// Significant peaks (frequency, power)
    pub peaks: Vec<(f64, f64)>,
}

/// FFT analyzer for frequency domain analysis
pub struct FFTAnalyzer {
    sampling_rate: f64,
    window: Option<WindowType>,
}

#[derive(Debug, Clone, Copy)]
pub enum WindowType {
    Hann,
    Hamming,
    Blackman,
    Rectangular,
}

impl FFTAnalyzer {
    /// Create a new FFT analyzer
    pub fn new(sampling_rate: f64) -> Self {
        Self {
            sampling_rate,
            window: None,
        }
    }

    /// Set window function for FFT
    pub fn with_window(mut self, window: WindowType) -> Self {
        self.window = Some(window);
        self
    }

    /// Perform FFT on time series
    pub fn fft(&self, series: &TimeSeries) -> Result<FFTResult> {
        let data = series.values.to_vec()?;
        let n = data.len();

        // Apply window if specified
        let windowed_data = if let Some(window) = self.window {
            self.apply_window(&data, window)
        } else {
            data.clone()
        };

        // TODO: Use scirs2-signal FFT when available
        // For now, implement simplified DFT (slow but functional)
        let (real, imag) = self.naive_dft(&windowed_data);

        // Generate frequency bins
        let frequencies: Vec<f64> = (0..n)
            .map(|k| k as f64 * self.sampling_rate / n as f64)
            .collect();

        Ok(FFTResult {
            real,
            imag,
            frequencies,
            sampling_rate: self.sampling_rate,
        })
    }

    /// Perform inverse FFT
    pub fn ifft(&self, fft_result: &FFTResult) -> Result<TimeSeries> {
        // TODO: Use scirs2-signal IFFT when available
        let n = fft_result.real.len();
        let mut data = vec![0.0f32; n];

        // Simplified inverse DFT
        for t in 0..n {
            let mut sum = 0.0;
            for k in 0..n {
                let angle = 2.0 * std::f64::consts::PI * (k * t) as f64 / n as f64;
                sum += fft_result.real[k] * angle.cos() - fft_result.imag[k] * angle.sin();
            }
            data[t] = (sum / n as f64) as f32;
        }

        let tensor = Tensor::from_vec(data, &[n])?;
        Ok(TimeSeries::new(tensor))
    }

    /// Apply window function
    fn apply_window(&self, data: &[f32], window: WindowType) -> Vec<f32> {
        let n = data.len();
        data.iter()
            .enumerate()
            .map(|(i, &x)| x * self.window_coefficient(i, n, window) as f32)
            .collect()
    }

    /// Get window coefficient
    fn window_coefficient(&self, i: usize, n: usize, window: WindowType) -> f64 {
        use std::f64::consts::PI;
        match window {
            WindowType::Hann => 0.5 * (1.0 - (2.0 * PI * i as f64 / (n - 1) as f64).cos()),
            WindowType::Hamming => 0.54 - 0.46 * (2.0 * PI * i as f64 / (n - 1) as f64).cos(),
            WindowType::Blackman => {
                0.42 - 0.5 * (2.0 * PI * i as f64 / (n - 1) as f64).cos()
                    + 0.08 * (4.0 * PI * i as f64 / (n - 1) as f64).cos()
            }
            WindowType::Rectangular => 1.0,
        }
    }

    /// Naive DFT implementation (placeholder for scirs2-signal FFT)
    fn naive_dft(&self, data: &[f32]) -> (Vec<f64>, Vec<f64>) {
        let n = data.len();
        let mut real = vec![0.0; n];
        let mut imag = vec![0.0; n];

        for k in 0..n {
            for t in 0..n {
                let angle = -2.0 * std::f64::consts::PI * (k * t) as f64 / n as f64;
                real[k] += data[t] as f64 * angle.cos();
                imag[k] += data[t] as f64 * angle.sin();
            }
        }

        (real, imag)
    }
}

/// Power Spectral Density estimator
pub struct PSDEstimator {
    method: PSDMethod,
    sampling_rate: f64,
}

#[derive(Debug, Clone, Copy)]
pub enum PSDMethod {
    Periodogram,
    Welch,
    MultitaperThomson,
}

impl PSDEstimator {
    /// Create a new PSD estimator
    pub fn new(method: PSDMethod, sampling_rate: f64) -> Self {
        Self {
            method,
            sampling_rate,
        }
    }

    /// Estimate power spectral density
    pub fn estimate(&self, series: &TimeSeries) -> Result<PSDResult> {
        match self.method {
            PSDMethod::Periodogram => self.periodogram_psd(series),
            PSDMethod::Welch => self.welch_psd(series),
            PSDMethod::MultitaperThomson => self.multitaper_psd(series),
        }
    }

    /// Periodogram-based PSD estimation
    fn periodogram_psd(&self, series: &TimeSeries) -> Result<PSDResult> {
        let fft = FFTAnalyzer::new(self.sampling_rate).fft(series)?;
        let power = fft.power();
        let n = power.len();

        // Normalize by length
        let psd: Vec<f64> = power.iter().map(|&p| p / n as f64).collect();

        Ok(PSDResult {
            psd,
            frequencies: fft.frequencies,
            method: "Periodogram".to_string(),
        })
    }

    /// Welch's method for PSD estimation
    fn welch_psd(&self, series: &TimeSeries) -> Result<PSDResult> {
        // TODO: Implement Welch's method with overlapping segments when scirs2-signal available
        // For now, fallback to periodogram
        self.periodogram_psd(series)
    }

    /// Thomson's multitaper method
    fn multitaper_psd(&self, series: &TimeSeries) -> Result<PSDResult> {
        // TODO: Implement multitaper method when scirs2-signal available
        // For now, fallback to periodogram
        self.periodogram_psd(series)
    }
}

/// Periodogram analyzer
pub struct PeriodogramAnalyzer {
    sampling_rate: f64,
    peak_threshold: f64,
}

impl PeriodogramAnalyzer {
    /// Create a new periodogram analyzer
    pub fn new(sampling_rate: f64) -> Self {
        Self {
            sampling_rate,
            peak_threshold: 0.1,
        }
    }

    /// Set threshold for peak detection (relative to max power)
    pub fn with_threshold(mut self, threshold: f64) -> Self {
        self.peak_threshold = threshold;
        self
    }

    /// Compute periodogram
    pub fn analyze(&self, series: &TimeSeries) -> Result<Periodogram> {
        let fft = FFTAnalyzer::new(self.sampling_rate).fft(series)?;
        let power = fft.power();

        // Find peaks
        let max_power = power.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        let threshold = max_power * self.peak_threshold;

        let mut peaks = Vec::new();
        for i in 1..power.len() - 1 {
            if power[i] > power[i - 1] && power[i] > power[i + 1] && power[i] > threshold {
                peaks.push((fft.frequencies[i], power[i]));
            }
        }

        Ok(Periodogram {
            power,
            frequencies: fft.frequencies,
            peaks,
        })
    }

    /// Find dominant frequency
    pub fn dominant_frequency(&self, series: &TimeSeries) -> Result<f64> {
        let periodogram = self.analyze(series)?;

        if periodogram.peaks.is_empty() {
            // Return frequency with max power
            let max_idx = periodogram
                .power
                .iter()
                .enumerate()
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .map(|(idx, _)| idx)
                .unwrap_or(0);
            Ok(periodogram.frequencies[max_idx])
        } else {
            // Return peak with highest power
            Ok(periodogram
                .peaks
                .iter()
                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                .map(|(freq, _)| *freq)
                .unwrap_or(0.0))
        }
    }
}

/// Spectral coherence analyzer for multivariate time series
pub struct CoherenceAnalyzer {
    sampling_rate: f64,
}

impl CoherenceAnalyzer {
    /// Create a new coherence analyzer
    pub fn new(sampling_rate: f64) -> Self {
        Self { sampling_rate }
    }

    /// Compute coherence between two time series
    pub fn coherence(&self, x: &TimeSeries, y: &TimeSeries) -> Result<Vec<f64>> {
        if x.len() != y.len() {
            return Err(TorshError::InvalidArgument(
                "Time series must have equal length".to_string(),
            ));
        }

        // TODO: Use scirs2-signal cross-spectral density when available
        let fft_x = FFTAnalyzer::new(self.sampling_rate).fft(x)?;
        let fft_y = FFTAnalyzer::new(self.sampling_rate).fft(y)?;

        let n = fft_x.real.len();
        let mut coherence = vec![0.0; n];

        for i in 0..n {
            let pxx = fft_x.real[i] * fft_x.real[i] + fft_x.imag[i] * fft_x.imag[i];
            let pyy = fft_y.real[i] * fft_y.real[i] + fft_y.imag[i] * fft_y.imag[i];
            let pxy = (fft_x.real[i] * fft_y.real[i] + fft_x.imag[i] * fft_y.imag[i]).abs();

            coherence[i] = if pxx > 1e-10 && pyy > 1e-10 {
                (pxy * pxy) / (pxx * pyy)
            } else {
                0.0
            };
        }

        Ok(coherence)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use torsh_tensor::Tensor;

    fn create_test_series() -> TimeSeries {
        // Create a simple sinusoidal signal
        let mut data = Vec::with_capacity(128);
        for i in 0..128 {
            let t = i as f32 * 0.1;
            data.push((2.0 * std::f32::consts::PI * t).sin());
        }
        let tensor = Tensor::from_vec(data, &[128]).expect("Tensor should succeed");
        TimeSeries::new(tensor)
    }

    #[test]
    fn test_fft_analyzer() {
        let series = create_test_series();
        let analyzer = FFTAnalyzer::new(10.0);
        let result = analyzer
            .fft(&series)
            .expect("FFT computation should succeed");

        assert_eq!(result.real.len(), 128);
        assert_eq!(result.imag.len(), 128);
        assert_eq!(result.frequencies.len(), 128);
    }

    #[test]
    fn test_fft_with_window() {
        let series = create_test_series();
        let analyzer = FFTAnalyzer::new(10.0).with_window(WindowType::Hann);
        let result = analyzer
            .fft(&series)
            .expect("FFT computation should succeed");

        assert_eq!(result.real.len(), 128);
    }

    #[test]
    fn test_fft_magnitude() {
        let series = create_test_series();
        let analyzer = FFTAnalyzer::new(10.0);
        let result = analyzer
            .fft(&series)
            .expect("FFT computation should succeed");
        let magnitude = result.magnitude();

        assert_eq!(magnitude.len(), 128);
        assert!(magnitude.iter().all(|&m| m >= 0.0));
    }

    #[test]
    fn test_ifft() {
        let series = create_test_series();
        let analyzer = FFTAnalyzer::new(10.0);
        let fft_result = analyzer
            .fft(&series)
            .expect("FFT computation should succeed");
        let reconstructed = analyzer
            .ifft(&fft_result)
            .expect("IFFT computation should succeed");

        assert_eq!(reconstructed.len(), series.len());
    }

    #[test]
    fn test_psd_periodogram() {
        let series = create_test_series();
        let estimator = PSDEstimator::new(PSDMethod::Periodogram, 10.0);
        let result = estimator
            .estimate(&series)
            .expect("estimation should succeed");

        assert_eq!(result.psd.len(), 128);
        assert_eq!(result.frequencies.len(), 128);
        assert_eq!(result.method, "Periodogram");
    }

    #[test]
    fn test_periodogram_analyzer() {
        let series = create_test_series();
        let analyzer = PeriodogramAnalyzer::new(10.0);
        let periodogram = analyzer.analyze(&series).expect("analysis should succeed");

        assert_eq!(periodogram.power.len(), 128);
        assert_eq!(periodogram.frequencies.len(), 128);
    }

    #[test]
    fn test_dominant_frequency() {
        let series = create_test_series();
        let analyzer = PeriodogramAnalyzer::new(10.0);
        let freq = analyzer
            .dominant_frequency(&series)
            .expect("dominant frequency estimation should succeed");

        assert!(freq >= 0.0);
    }

    #[test]
    fn test_coherence_analyzer() {
        let series1 = create_test_series();
        let series2 = create_test_series();
        let analyzer = CoherenceAnalyzer::new(10.0);
        let coherence = analyzer
            .coherence(&series1, &series2)
            .expect("coherence computation should succeed");

        assert_eq!(coherence.len(), 128);
        assert!(coherence.iter().all(|&c| c >= 0.0 && c <= 1.0));
    }

    #[test]
    fn test_window_types() {
        let series = create_test_series();

        for window in [
            WindowType::Hann,
            WindowType::Hamming,
            WindowType::Blackman,
            WindowType::Rectangular,
        ] {
            let analyzer = FFTAnalyzer::new(10.0).with_window(window);
            let result = analyzer
                .fft(&series)
                .expect("FFT computation should succeed");
            assert_eq!(result.real.len(), 128);
        }
    }
}