oxigdal-temporal 0.1.4

Multi-temporal raster analysis for OxiGDAL - Time series, change detection, phenology, and data cube operations
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
//! Temporal Aggregation Module
//!
//! This module provides methods for aggregating time series data over various temporal windows,
//! including daily, weekly, monthly, yearly, and rolling aggregations.

use crate::error::{Result, TemporalError};
use crate::timeseries::{TemporalMetadata, TimeSeriesRaster};
use chrono::{DateTime, Datelike, Duration, Utc};
use scirs2_core::ndarray::Array3;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info};

/// Type alias for temporal groups
type TemporalGroups<'a> = HashMap<String, Vec<(DateTime<Utc>, &'a Array3<f64>)>>;

/// Temporal window for aggregation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TemporalWindow {
    /// Daily aggregation
    Daily,
    /// Weekly aggregation (7 days)
    Weekly,
    /// Monthly aggregation
    Monthly,
    /// Yearly aggregation
    Yearly,
    /// Custom number of days
    CustomDays(i64),
    /// Rolling window (number of observations)
    Rolling(usize),
}

/// Aggregation statistic
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AggregationStatistic {
    /// Mean value
    Mean,
    /// Median value
    Median,
    /// Minimum value
    Min,
    /// Maximum value
    Max,
    /// Sum
    Sum,
    /// Standard deviation
    StdDev,
    /// Count of valid observations
    Count,
    /// First value
    First,
    /// Last value
    Last,
}

/// Aggregation configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AggregationConfig {
    /// Temporal window
    pub window: TemporalWindow,
    /// Statistics to compute
    pub statistics: Vec<AggregationStatistic>,
    /// NoData value to ignore
    pub nodata: Option<f64>,
    /// Minimum number of valid observations required
    pub min_observations: usize,
}

impl Default for AggregationConfig {
    fn default() -> Self {
        Self {
            window: TemporalWindow::Monthly,
            statistics: vec![AggregationStatistic::Mean],
            nodata: Some(f64::NAN),
            min_observations: 1,
        }
    }
}

/// Result of temporal aggregation
#[derive(Debug, Clone)]
pub struct AggregationResult {
    /// Aggregated time series (one entry per window)
    pub time_series: HashMap<String, TimeSeriesRaster>,
    /// Window start times
    pub window_starts: Vec<DateTime<Utc>>,
    /// Window end times
    pub window_ends: Vec<DateTime<Utc>>,
}

impl AggregationResult {
    /// Create new aggregation result
    #[must_use]
    pub fn new() -> Self {
        Self {
            time_series: HashMap::new(),
            window_starts: Vec::new(),
            window_ends: Vec::new(),
        }
    }

    /// Get time series for specific statistic
    #[must_use]
    pub fn get(&self, stat: &str) -> Option<&TimeSeriesRaster> {
        self.time_series.get(stat)
    }

    /// Add time series for statistic
    pub fn add(&mut self, stat: String, ts: TimeSeriesRaster) {
        self.time_series.insert(stat, ts);
    }
}

impl Default for AggregationResult {
    fn default() -> Self {
        Self::new()
    }
}

/// Temporal aggregator
pub struct TemporalAggregator;

impl TemporalAggregator {
    /// Aggregate time series data
    ///
    /// # Errors
    /// Returns error if aggregation fails
    pub fn aggregate(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
    ) -> Result<AggregationResult> {
        match config.window {
            TemporalWindow::Daily => Self::aggregate_daily(ts, config),
            TemporalWindow::Weekly => Self::aggregate_weekly(ts, config),
            TemporalWindow::Monthly => Self::aggregate_monthly(ts, config),
            TemporalWindow::Yearly => Self::aggregate_yearly(ts, config),
            TemporalWindow::CustomDays(days) => Self::aggregate_custom_days(ts, config, days),
            TemporalWindow::Rolling(size) => Self::aggregate_rolling(ts, config, size),
        }
    }

    /// Aggregate to daily intervals
    fn aggregate_daily(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
    ) -> Result<AggregationResult> {
        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        // Group by day
        let mut daily_groups: TemporalGroups = HashMap::new();

        for (_, entry) in ts.iter() {
            let date_key = entry.metadata.acquisition_date.to_string();
            if let Some(data) = entry.data.as_ref() {
                daily_groups
                    .entry(date_key)
                    .or_default()
                    .push((entry.metadata.timestamp, data));
            }
        }

        Self::compute_statistics(&daily_groups, config, height, width, n_bands)
    }

    /// Aggregate to weekly intervals
    fn aggregate_weekly(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
    ) -> Result<AggregationResult> {
        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        // Group by ISO week
        let mut weekly_groups: TemporalGroups = HashMap::new();

        for (_, entry) in ts.iter() {
            let year = entry.metadata.acquisition_date.year();
            let week = entry.metadata.acquisition_date.iso_week().week();
            let week_key = format!("{}-W{:02}", year, week);

            if let Some(data) = entry.data.as_ref() {
                weekly_groups
                    .entry(week_key)
                    .or_default()
                    .push((entry.metadata.timestamp, data));
            }
        }

        Self::compute_statistics(&weekly_groups, config, height, width, n_bands)
    }

    /// Aggregate to monthly intervals
    fn aggregate_monthly(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
    ) -> Result<AggregationResult> {
        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        // Group by year-month
        let mut monthly_groups: TemporalGroups = HashMap::new();

        for (_, entry) in ts.iter() {
            let year = entry.metadata.acquisition_date.year();
            let month = entry.metadata.acquisition_date.month();
            let month_key = format!("{}-{:02}", year, month);

            if let Some(data) = entry.data.as_ref() {
                monthly_groups
                    .entry(month_key)
                    .or_default()
                    .push((entry.metadata.timestamp, data));
            }
        }

        Self::compute_statistics(&monthly_groups, config, height, width, n_bands)
    }

    /// Aggregate to yearly intervals
    fn aggregate_yearly(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
    ) -> Result<AggregationResult> {
        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        // Group by year
        let mut yearly_groups: TemporalGroups = HashMap::new();

        for (_, entry) in ts.iter() {
            let year = entry.metadata.acquisition_date.year();
            let year_key = format!("{}", year);

            if let Some(data) = entry.data.as_ref() {
                yearly_groups
                    .entry(year_key)
                    .or_default()
                    .push((entry.metadata.timestamp, data));
            }
        }

        Self::compute_statistics(&yearly_groups, config, height, width, n_bands)
    }

    /// Aggregate to custom day intervals
    fn aggregate_custom_days(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
        days: i64,
    ) -> Result<AggregationResult> {
        if days <= 0 {
            return Err(TemporalError::invalid_parameter("days", "must be positive"));
        }

        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        let (start_time, end_time) = ts
            .time_range()
            .ok_or_else(|| TemporalError::insufficient_data("Empty time series"))?;

        // Create windows
        let mut window_groups: TemporalGroups = HashMap::new();
        let mut current = start_time;

        while current < end_time {
            let next = current + Duration::days(days);
            let window_key = format!("{}", current.format("%Y-%m-%d"));

            // Get entries in this window
            let entries = ts.query_range(&current, &next);
            for entry in entries {
                if let Some(data) = entry.data.as_ref() {
                    window_groups
                        .entry(window_key.clone())
                        .or_default()
                        .push((entry.metadata.timestamp, data));
                }
            }

            current = next;
        }

        Self::compute_statistics(&window_groups, config, height, width, n_bands)
    }

    /// Rolling window aggregation
    fn aggregate_rolling(
        ts: &TimeSeriesRaster,
        config: &AggregationConfig,
        window_size: usize,
    ) -> Result<AggregationResult> {
        if window_size == 0 {
            return Err(TemporalError::invalid_parameter(
                "window_size",
                "must be greater than 0",
            ));
        }

        if window_size > ts.len() {
            return Err(TemporalError::invalid_parameter(
                "window_size",
                "exceeds time series length",
            ));
        }

        let (height, width, n_bands) = ts
            .expected_shape()
            .ok_or_else(|| TemporalError::insufficient_data("No shape information"))?;

        let entries: Vec<_> = ts.iter().collect();
        let mut result = AggregationResult::new();

        // Initialize time series for each statistic
        for stat in &config.statistics {
            result.add(format!("{:?}", stat), TimeSeriesRaster::new());
        }

        // Slide window through time series
        for i in 0..=(entries.len().saturating_sub(window_size)) {
            let window_entries: Vec<_> = entries[i..i + window_size]
                .iter()
                .filter_map(|(_, e)| e.data.as_ref().map(|d| (e.metadata.timestamp, d)))
                .collect();

            if window_entries.len() < config.min_observations {
                continue;
            }

            // Get window timestamp (middle of window)
            let mid_timestamp = window_entries[window_entries.len() / 2].0;

            // Compute each statistic
            for stat in &config.statistics {
                let aggregated = Self::compute_statistic(
                    &window_entries,
                    *stat,
                    config,
                    height,
                    width,
                    n_bands,
                )?;

                let metadata = TemporalMetadata::new(mid_timestamp, mid_timestamp.date_naive());
                let stat_key = format!("{:?}", stat);
                if let Some(ts) = result.time_series.get_mut(&stat_key) {
                    ts.add_raster(metadata, aggregated)?;
                }
            }
        }

        info!(
            "Completed rolling aggregation with window size {}",
            window_size
        );
        Ok(result)
    }

    /// Compute statistics for grouped data
    fn compute_statistics(
        groups: &TemporalGroups,
        config: &AggregationConfig,
        height: usize,
        width: usize,
        n_bands: usize,
    ) -> Result<AggregationResult> {
        let mut result = AggregationResult::new();

        // Initialize time series for each statistic
        for stat in &config.statistics {
            result.add(format!("{:?}", stat), TimeSeriesRaster::new());
        }

        // Process each group
        let mut sorted_keys: Vec<_> = groups.keys().collect();
        sorted_keys.sort();

        for key in sorted_keys {
            let group = &groups[key];

            if group.len() < config.min_observations {
                debug!(
                    "Skipping group {} with {} observations (min: {})",
                    key,
                    group.len(),
                    config.min_observations
                );
                continue;
            }

            // Get first timestamp as representative
            let timestamp = group[0].0;

            // Compute each statistic
            for stat in &config.statistics {
                let aggregated =
                    Self::compute_statistic(group, *stat, config, height, width, n_bands)?;

                let metadata = TemporalMetadata::new(timestamp, timestamp.date_naive());
                let stat_key = format!("{:?}", stat);
                if let Some(ts) = result.time_series.get_mut(&stat_key) {
                    ts.add_raster(metadata, aggregated)?;
                }
            }
        }

        info!(
            "Aggregated {} groups with {} statistics",
            groups.len(),
            config.statistics.len()
        );
        Ok(result)
    }

    /// Compute a single statistic
    fn compute_statistic(
        entries: &[(DateTime<Utc>, &Array3<f64>)],
        stat: AggregationStatistic,
        config: &AggregationConfig,
        height: usize,
        width: usize,
        n_bands: usize,
    ) -> Result<Array3<f64>> {
        let mut result: Array3<f64> = Array3::zeros((height, width, n_bands));

        match stat {
            AggregationStatistic::Mean => {
                let mut sum: Array3<f64> = Array3::zeros((height, width, n_bands));
                let mut count: Array3<f64> = Array3::zeros((height, width, n_bands));

                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    sum[[i, j, k]] += val;
                                    count[[i, j, k]] += 1.0;
                                }
                            }
                        }
                    }
                }

                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            result[[i, j, k]] = if count[[i, j, k]] > 0.0 {
                                sum[[i, j, k]] / count[[i, j, k]]
                            } else {
                                config.nodata.unwrap_or(f64::NAN)
                            };
                        }
                    }
                }
            }
            AggregationStatistic::Min => {
                result.fill(f64::INFINITY);
                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) && val < result[[i, j, k]] {
                                    result[[i, j, k]] = val;
                                }
                            }
                        }
                    }
                }
                // Replace INFINITY with nodata
                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            if result[[i, j, k]].is_infinite() {
                                result[[i, j, k]] = config.nodata.unwrap_or(f64::NAN);
                            }
                        }
                    }
                }
            }
            AggregationStatistic::Max => {
                result.fill(f64::NEG_INFINITY);
                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) && val > result[[i, j, k]] {
                                    result[[i, j, k]] = val;
                                }
                            }
                        }
                    }
                }
                // Replace NEG_INFINITY with nodata
                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            if result[[i, j, k]].is_infinite() {
                                result[[i, j, k]] = config.nodata.unwrap_or(f64::NAN);
                            }
                        }
                    }
                }
            }
            AggregationStatistic::Sum => {
                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    result[[i, j, k]] += val;
                                }
                            }
                        }
                    }
                }
            }
            AggregationStatistic::Count => {
                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    result[[i, j, k]] += 1.0;
                                }
                            }
                        }
                    }
                }
            }
            AggregationStatistic::First => {
                if let Some((_, first_data)) = entries.first() {
                    result = (*first_data).clone();
                }
            }
            AggregationStatistic::Last => {
                if let Some((_, last_data)) = entries.last() {
                    result = (*last_data).clone();
                }
            }
            AggregationStatistic::StdDev => {
                // First pass: compute mean
                let mut mean: Array3<f64> = Array3::zeros((height, width, n_bands));
                let mut count: Array3<f64> = Array3::zeros((height, width, n_bands));

                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    mean[[i, j, k]] += val;
                                    count[[i, j, k]] += 1.0;
                                }
                            }
                        }
                    }
                }

                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            if count[[i, j, k]] > 0.0 {
                                mean[[i, j, k]] /= count[[i, j, k]];
                            }
                        }
                    }
                }

                // Second pass: compute variance
                let mut variance: Array3<f64> = Array3::zeros((height, width, n_bands));

                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    let diff = val - mean[[i, j, k]];
                                    variance[[i, j, k]] += diff * diff;
                                }
                            }
                        }
                    }
                }

                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            result[[i, j, k]] = if count[[i, j, k]] > 1.0 {
                                (variance[[i, j, k]] / count[[i, j, k]]).sqrt()
                            } else {
                                config.nodata.unwrap_or(f64::NAN)
                            };
                        }
                    }
                }
            }
            AggregationStatistic::Median => {
                // Collect values for each pixel
                let mut pixel_values: Vec<Vec<Vec<Vec<f64>>>> =
                    vec![vec![vec![Vec::new(); n_bands]; width]; height];

                for (_, data) in entries {
                    for i in 0..height {
                        for j in 0..width {
                            for k in 0..n_bands {
                                let val = data[[i, j, k]];
                                if Self::is_valid(val, config.nodata) {
                                    pixel_values[i][j][k].push(val);
                                }
                            }
                        }
                    }
                }

                // Compute median for each pixel
                for i in 0..height {
                    for j in 0..width {
                        for k in 0..n_bands {
                            let values = &mut pixel_values[i][j][k];
                            if values.is_empty() {
                                result[[i, j, k]] = config.nodata.unwrap_or(f64::NAN);
                            } else {
                                values.sort_by(|a, b| {
                                    a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal)
                                });
                                let mid = values.len() / 2;
                                result[[i, j, k]] = if values.len() % 2 == 0 {
                                    (values[mid - 1] + values[mid]) / 2.0
                                } else {
                                    values[mid]
                                };
                            }
                        }
                    }
                }
            }
        }

        Ok(result)
    }

    /// Check if value is valid (not nodata)
    fn is_valid(val: f64, nodata: Option<f64>) -> bool {
        if let Some(nd) = nodata {
            if nd.is_nan() {
                !val.is_nan()
            } else {
                (val - nd).abs() > 1e-10
            }
        } else {
            true
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::timeseries::TemporalMetadata;
    use chrono::NaiveDate;

    fn create_test_timeseries() -> TimeSeriesRaster {
        let mut ts = TimeSeriesRaster::new();

        for i in 0..30 {
            let dt = DateTime::from_timestamp(1640995200 + i * 86400, 0).expect("valid");
            let date = NaiveDate::from_ymd_opt(2022, 1, 1 + i as u32).expect("valid");
            let metadata = TemporalMetadata::new(dt, date);
            let data = Array3::from_elem((5, 5, 2), i as f64);
            ts.add_raster(metadata, data).expect("should add");
        }

        ts
    }

    #[test]
    fn test_daily_aggregation() {
        let ts = create_test_timeseries();
        let config = AggregationConfig {
            window: TemporalWindow::Daily,
            statistics: vec![AggregationStatistic::Mean],
            ..Default::default()
        };

        let result = TemporalAggregator::aggregate(&ts, &config).expect("should aggregate");
        assert!(result.get("Mean").is_some());
    }

    #[test]
    fn test_weekly_aggregation() {
        let ts = create_test_timeseries();
        let config = AggregationConfig {
            window: TemporalWindow::Weekly,
            statistics: vec![AggregationStatistic::Mean, AggregationStatistic::Max],
            ..Default::default()
        };

        let result = TemporalAggregator::aggregate(&ts, &config).expect("should aggregate");
        assert!(result.get("Mean").is_some());
        assert!(result.get("Max").is_some());
    }

    #[test]
    fn test_monthly_aggregation() {
        let ts = create_test_timeseries();
        let config = AggregationConfig {
            window: TemporalWindow::Monthly,
            statistics: vec![AggregationStatistic::Mean],
            ..Default::default()
        };

        let result = TemporalAggregator::aggregate(&ts, &config).expect("should aggregate");
        let mean_ts = result.get("Mean").expect("should have mean");
        assert!(!mean_ts.is_empty());
    }

    #[test]
    fn test_rolling_aggregation() {
        let ts = create_test_timeseries();
        let config = AggregationConfig {
            window: TemporalWindow::Rolling(7),
            statistics: vec![AggregationStatistic::Mean],
            min_observations: 5,
            ..Default::default()
        };

        let result = TemporalAggregator::aggregate(&ts, &config).expect("should aggregate");
        let mean_ts = result.get("Mean").expect("should have mean");
        assert!(!mean_ts.is_empty());
    }

    #[test]
    fn test_multiple_statistics() {
        let ts = create_test_timeseries();
        let config = AggregationConfig {
            window: TemporalWindow::Weekly,
            statistics: vec![
                AggregationStatistic::Mean,
                AggregationStatistic::Min,
                AggregationStatistic::Max,
                AggregationStatistic::StdDev,
            ],
            ..Default::default()
        };

        let result = TemporalAggregator::aggregate(&ts, &config).expect("should aggregate");
        assert!(result.get("Mean").is_some());
        assert!(result.get("Min").is_some());
        assert!(result.get("Max").is_some());
        assert!(result.get("StdDev").is_some());
    }
}