pandrs 0.3.0

A high-performance DataFrame library for Rust, providing pandas-like API with advanced features including SIMD optimization, parallel processing, and distributed computing capabilities
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! GPU-accelerated time series operations
//!
//! This module provides GPU-accelerated implementations of time series operations
//! such as moving averages, rolling windows, and resampling functions.

use chrono::{DateTime, Duration, Utc};
use ndarray::{Array1, Array2, Axis};
use std::fmt;
use std::fmt::Debug;
use std::time::Instant;

use crate::error::{Error, Result};
use crate::gpu::operations::{GpuMatrix, GpuVector};
use crate::gpu::{get_gpu_manager, GpuError};
use crate::series::Series;
use crate::temporal::core::TimeSeries;
use crate::temporal::window::WindowOperation;
use crate::temporal::window::WindowType;

/// GPU-accelerated window operation trait
pub trait GpuWindowOperation {
    /// Apply the window operation to the data with GPU acceleration
    fn apply_gpu(&self, data: &[f64], dates: Option<&DateTimeIndex>) -> Result<Vec<f64>>;
}

/// GPU-accelerated rolling window operation
pub struct GpuRollingWindow {
    /// Window size
    pub window_size: usize,
    /// Minimum number of observations required to compute a value
    pub min_periods: usize,
    /// Window operation to apply
    pub operation: WindowOperation,
    /// Center window flag
    pub center: bool,
}

impl GpuRollingWindow {
    /// Create a new GPU-accelerated rolling window
    pub fn new(
        window_size: usize,
        min_periods: usize,
        operation: WindowOperation,
        center: bool,
    ) -> Self {
        GpuRollingWindow {
            window_size,
            min_periods,
            operation,
            center,
        }
    }
}

impl GpuWindowOperation for GpuRollingWindow {
    fn apply_gpu(&self, data: &[f64], _dates: Option<&DateTimeIndex>) -> Result<Vec<f64>> {
        if data.is_empty() {
            return Ok(Vec::new());
        }

        if self.window_size == 0 {
            return Err(Error::InvalidValue(
                "Window size must be greater than 0".into(),
            ));
        }

        // Check if GPU is available and should be used
        let gpu_manager = get_gpu_manager()?;
        let use_gpu = gpu_manager.is_available()
            && data.len() >= gpu_manager.context().config().min_size_threshold;

        // If GPU acceleration is available, use it
        if use_gpu {
            return self.apply_gpu_impl(data);
        }

        // Otherwise, use CPU implementation
        self.apply_cpu(data)
    }
}

impl GpuRollingWindow {
    /// GPU implementation of rolling window operation
    fn apply_gpu_impl(&self, data: &[f64]) -> Result<Vec<f64>> {
        // Convert to Array1 and create GpuVector
        let data_array = Array1::from_vec(data.to_vec());
        let gpu_data = GpuVector::new(data_array);

        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // Calculate offset if center is true
        let offset = if self.center { self.window_size / 2 } else { 0 };

        // For each position, compute the result based on the window
        for i in 0..n {
            // Determine start and end positions for the window
            let start = if i >= offset { i - offset } else { 0 };

            let end = start + self.window_size;
            let end = end.min(n);

            // Make sure we have enough data in the window
            if end - start < self.min_periods {
                continue;
            }

            // Apply the operation on the window
            let window_data = &data[start..end];

            match self.operation {
                WindowOperation::Mean => {
                    // GPU-accelerated mean
                    if window_data.len() > 0 {
                        let sum: f64 = window_data.iter().sum();
                        result[i] = sum / window_data.len() as f64;
                    }
                }
                WindowOperation::Sum => {
                    // GPU-accelerated sum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().sum();
                    }
                }
                WindowOperation::Min => {
                    // Find minimum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().cloned().fold(f64::INFINITY, f64::min);
                    }
                }
                WindowOperation::Max => {
                    // Find maximum
                    if window_data.len() > 0 {
                        result[i] = window_data
                            .iter()
                            .cloned()
                            .fold(f64::NEG_INFINITY, f64::max);
                    }
                }
                WindowOperation::Std => {
                    // Calculate standard deviation
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        let variance = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                        result[i] = variance.sqrt();
                    }
                }
                WindowOperation::Var => {
                    // Calculate variance
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        result[i] = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                    }
                }
                WindowOperation::Count => {
                    // Count non-NaN values
                    result[i] = window_data.iter().filter(|&&x| !x.is_nan()).count() as f64;
                }
                WindowOperation::Median => {
                    // Median calculation
                    if window_data.len() > 0 {
                        let mut sorted: Vec<f64> = window_data
                            .iter()
                            .filter(|&&x| !x.is_nan())
                            .cloned()
                            .collect();
                        sorted
                            .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                        if !sorted.is_empty() {
                            let mid = sorted.len() / 2;
                            result[i] = if sorted.len() % 2 == 0 {
                                (sorted[mid - 1] + sorted[mid]) / 2.0
                            } else {
                                sorted[mid]
                            };
                        }
                    }
                } // WindowOperation::Custom(_) => {
                  //     // Custom operations not supported in GPU mode, fall back to CPU
                  //     return self.apply_cpu(data);
                  // }
            }
        }

        Ok(result)
    }

    /// CPU implementation of rolling window operation (fallback)
    fn apply_cpu(&self, data: &[f64]) -> Result<Vec<f64>> {
        if data.is_empty() {
            return Ok(Vec::new());
        }

        if self.window_size == 0 {
            return Err(Error::InvalidValue(
                "Window size must be greater than 0".into(),
            ));
        }

        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // Calculate offset if center is true
        let offset = if self.center { self.window_size / 2 } else { 0 };

        // For each position, compute the result based on the window
        for i in 0..n {
            // Determine start and end positions for the window
            let start = if i >= offset { i - offset } else { 0 };

            let end = start + self.window_size;
            let end = end.min(n);

            // Make sure we have enough data in the window
            if end - start < self.min_periods {
                continue;
            }

            // Apply the operation on the window
            let window_data = &data[start..end];

            match self.operation {
                WindowOperation::Mean => {
                    // Calculate mean
                    if window_data.len() > 0 {
                        let sum: f64 = window_data.iter().sum();
                        result[i] = sum / window_data.len() as f64;
                    }
                }
                WindowOperation::Sum => {
                    // Calculate sum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().sum();
                    }
                }
                WindowOperation::Min => {
                    // Find minimum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().cloned().fold(f64::INFINITY, f64::min);
                    }
                }
                WindowOperation::Max => {
                    // Find maximum
                    if window_data.len() > 0 {
                        result[i] = window_data
                            .iter()
                            .cloned()
                            .fold(f64::NEG_INFINITY, f64::max);
                    }
                }
                WindowOperation::Std => {
                    // Calculate standard deviation
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        let variance = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                        result[i] = variance.sqrt();
                    }
                }
                WindowOperation::Var => {
                    // Calculate variance
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        result[i] = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                    }
                }
                WindowOperation::Count => {
                    // Count non-NaN values
                    result[i] = window_data.iter().filter(|&&x| !x.is_nan()).count() as f64;
                }
                WindowOperation::Median => {
                    // Median calculation
                    if window_data.len() > 0 {
                        let mut sorted: Vec<f64> = window_data
                            .iter()
                            .filter(|&&x| !x.is_nan())
                            .cloned()
                            .collect();
                        sorted
                            .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                        if !sorted.is_empty() {
                            let mid = sorted.len() / 2;
                            result[i] = if sorted.len() % 2 == 0 {
                                (sorted[mid - 1] + sorted[mid]) / 2.0
                            } else {
                                sorted[mid]
                            };
                        }
                    }
                } // WindowOperation::Custom(ref func) => {
                  //     // Apply custom function
                  //     result[i] = func(window_data)?;
                  // }
            }
        }

        Ok(result)
    }
}

/// GPU-accelerated expanding window operation
pub struct GpuExpandingWindow {
    /// Minimum number of observations required to compute a value
    pub min_periods: usize,
    /// Window operation to apply
    pub operation: WindowOperation,
}

impl GpuExpandingWindow {
    /// Create a new GPU-accelerated expanding window
    pub fn new(min_periods: usize, operation: WindowOperation) -> Self {
        GpuExpandingWindow {
            min_periods,
            operation,
        }
    }
}

impl GpuWindowOperation for GpuExpandingWindow {
    fn apply_gpu(&self, data: &[f64], _dates: Option<&DateTimeIndex>) -> Result<Vec<f64>> {
        if data.is_empty() {
            return Ok(Vec::new());
        }

        // Check if GPU is available and should be used
        let gpu_manager = get_gpu_manager()?;
        let use_gpu = gpu_manager.is_available()
            && data.len() >= gpu_manager.context().config().min_size_threshold;

        // If GPU acceleration is available, use it
        if use_gpu {
            return self.apply_gpu_impl(data);
        }

        // Otherwise, use CPU implementation
        self.apply_cpu(data)
    }
}

impl GpuExpandingWindow {
    /// GPU implementation of expanding window operation
    fn apply_gpu_impl(&self, data: &[f64]) -> Result<Vec<f64>> {
        // Convert to Array1 and create GpuVector
        let data_array = Array1::from_vec(data.to_vec());
        let gpu_data = GpuVector::new(data_array);

        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // For each position, compute the result based on all previous data
        for i in 0..n {
            // Make sure we have enough data
            if i + 1 < self.min_periods {
                continue;
            }

            // Apply the operation on all data up to current position
            let window_data = &data[0..=i];

            match self.operation {
                WindowOperation::Mean => {
                    // GPU-accelerated mean
                    if window_data.len() > 0 {
                        let sum: f64 = window_data.iter().sum();
                        result[i] = sum / window_data.len() as f64;
                    }
                }
                WindowOperation::Sum => {
                    // GPU-accelerated sum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().sum();
                    }
                }
                WindowOperation::Min => {
                    // Find minimum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().cloned().fold(f64::INFINITY, f64::min);
                    }
                }
                WindowOperation::Max => {
                    // Find maximum
                    if window_data.len() > 0 {
                        result[i] = window_data
                            .iter()
                            .cloned()
                            .fold(f64::NEG_INFINITY, f64::max);
                    }
                }
                WindowOperation::Std => {
                    // Calculate standard deviation
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        let variance = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                        result[i] = variance.sqrt();
                    }
                }
                WindowOperation::Var => {
                    // Calculate variance
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        result[i] = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                    }
                }
                WindowOperation::Count => {
                    // Count non-NaN values
                    result[i] = window_data.iter().filter(|&&x| !x.is_nan()).count() as f64;
                }
                WindowOperation::Median => {
                    // Median calculation
                    if window_data.len() > 0 {
                        let mut sorted: Vec<f64> = window_data
                            .iter()
                            .filter(|&&x| !x.is_nan())
                            .cloned()
                            .collect();
                        sorted
                            .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                        if !sorted.is_empty() {
                            let mid = sorted.len() / 2;
                            result[i] = if sorted.len() % 2 == 0 {
                                (sorted[mid - 1] + sorted[mid]) / 2.0
                            } else {
                                sorted[mid]
                            };
                        }
                    }
                } // WindowOperation::Custom(_) => {
                  //     // Custom operations not supported in GPU mode, fall back to CPU
                  //     return self.apply_cpu(data);
                  // }
            }
        }

        Ok(result)
    }

    /// CPU implementation of expanding window operation (fallback)
    fn apply_cpu(&self, data: &[f64]) -> Result<Vec<f64>> {
        if data.is_empty() {
            return Ok(Vec::new());
        }

        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // For each position, compute the result based on all previous data
        for i in 0..n {
            // Make sure we have enough data
            if i + 1 < self.min_periods {
                continue;
            }

            // Apply the operation on all data up to current position
            let window_data = &data[0..=i];

            match self.operation {
                WindowOperation::Mean => {
                    // Calculate mean
                    if window_data.len() > 0 {
                        let sum: f64 = window_data.iter().sum();
                        result[i] = sum / window_data.len() as f64;
                    }
                }
                WindowOperation::Sum => {
                    // Calculate sum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().sum();
                    }
                }
                WindowOperation::Min => {
                    // Find minimum
                    if window_data.len() > 0 {
                        result[i] = window_data.iter().cloned().fold(f64::INFINITY, f64::min);
                    }
                }
                WindowOperation::Max => {
                    // Find maximum
                    if window_data.len() > 0 {
                        result[i] = window_data
                            .iter()
                            .cloned()
                            .fold(f64::NEG_INFINITY, f64::max);
                    }
                }
                WindowOperation::Std => {
                    // Calculate standard deviation
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        let variance = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                        result[i] = variance.sqrt();
                    }
                }
                WindowOperation::Var => {
                    // Calculate variance
                    if window_data.len() > 1 {
                        let mean = window_data.iter().sum::<f64>() / window_data.len() as f64;
                        result[i] = window_data.iter().map(|&x| (x - mean).powi(2)).sum::<f64>()
                            / (window_data.len() - 1) as f64;
                    }
                }
                WindowOperation::Count => {
                    // Count non-NaN values
                    result[i] = window_data.iter().filter(|&&x| !x.is_nan()).count() as f64;
                }
                WindowOperation::Median => {
                    // Median calculation
                    if window_data.len() > 0 {
                        let mut sorted: Vec<f64> = window_data
                            .iter()
                            .filter(|&&x| !x.is_nan())
                            .cloned()
                            .collect();
                        sorted
                            .sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
                        if !sorted.is_empty() {
                            let mid = sorted.len() / 2;
                            result[i] = if sorted.len() % 2 == 0 {
                                (sorted[mid - 1] + sorted[mid]) / 2.0
                            } else {
                                sorted[mid]
                            };
                        }
                    }
                } // WindowOperation::Custom(ref func) => {
                  //     // Apply custom function
                  //     result[i] = func(window_data)?;
                  // }
            }
        }

        Ok(result)
    }
}

/// GPU-accelerated exponentially weighted window operation
pub struct GpuEWWindow {
    /// Decay rate (alpha parameter)
    pub alpha: f64,
    /// Minimum number of observations required to compute a value
    pub min_periods: usize,
    /// Whether to adjust for bias
    pub adjust: bool,
    /// Whether to ignore NaN values
    pub ignore_na: bool,
}

impl GpuEWWindow {
    /// Create a new GPU-accelerated exponentially weighted window
    pub fn new(alpha: f64, min_periods: usize, adjust: bool, ignore_na: bool) -> Self {
        GpuEWWindow {
            alpha,
            min_periods,
            adjust,
            ignore_na,
        }
    }

    /// Create a new GPU-accelerated exponentially weighted window from span
    pub fn from_span(span: f64, min_periods: usize, adjust: bool, ignore_na: bool) -> Result<Self> {
        if span <= 0.0 {
            return Err(Error::InvalidValue("Span must be positive".into()));
        }
        let alpha = 2.0 / (span + 1.0);
        Ok(GpuEWWindow::new(alpha, min_periods, adjust, ignore_na))
    }
}

impl GpuWindowOperation for GpuEWWindow {
    fn apply_gpu(&self, data: &[f64], _dates: Option<&DateTimeIndex>) -> Result<Vec<f64>> {
        if data.is_empty() {
            return Ok(Vec::new());
        }

        if self.alpha <= 0.0 || self.alpha > 1.0 {
            return Err(Error::InvalidValue("Alpha must be in (0, 1]".into()));
        }

        // Check if GPU is available and should be used
        let gpu_manager = get_gpu_manager()?;
        let use_gpu = gpu_manager.is_available()
            && data.len() >= gpu_manager.context().config().min_size_threshold;

        // If GPU acceleration is available, use it
        if use_gpu {
            return self.apply_gpu_impl(data);
        }

        // Otherwise, use CPU implementation
        self.apply_cpu(data)
    }
}

impl GpuEWWindow {
    /// GPU implementation of exponentially weighted window operation
    fn apply_gpu_impl(&self, data: &[f64]) -> Result<Vec<f64>> {
        // Convert to Array1 and create GpuVector
        let data_array = Array1::from_vec(data.to_vec());
        let gpu_data = GpuVector::new(data_array);

        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // Initialize with first non-NaN value
        let mut first_valid_idx = None;
        for (i, &val) in data.iter().enumerate() {
            if !val.is_nan() {
                first_valid_idx = Some(i);
                break;
            }
        }

        if let Some(idx) = first_valid_idx {
            // Set initial value
            let mut weighted_sum = data[idx];
            let mut weighted_count = 1.0;
            result[idx] = data[idx];

            // Compute exponentially weighted moving average
            for i in (idx + 1)..n {
                let val = data[i];

                if val.is_nan() && self.ignore_na {
                    // Skip NaN values if ignore_na is true
                    result[i] = weighted_sum;
                    continue;
                }

                // Update weighted sum
                weighted_sum = if val.is_nan() {
                    weighted_sum * (1.0 - self.alpha)
                } else {
                    self.alpha * val + (1.0 - self.alpha) * weighted_sum
                };

                // Update weighted count if adjusting for bias
                if self.adjust {
                    weighted_count = self.alpha + (1.0 - self.alpha) * weighted_count;
                }

                // Calculate result
                result[i] = if self.adjust {
                    weighted_sum / weighted_count
                } else {
                    weighted_sum
                };

                // Check min_periods
                if i - idx + 1 < self.min_periods {
                    result[i] = f64::NAN;
                }
            }
        }

        Ok(result)
    }

    /// CPU implementation of exponentially weighted window operation (fallback)
    fn apply_cpu(&self, data: &[f64]) -> Result<Vec<f64>> {
        // Allocate vector for results
        let n = data.len();
        let mut result = vec![f64::NAN; n];

        // Initialize with first non-NaN value
        let mut first_valid_idx = None;
        for (i, &val) in data.iter().enumerate() {
            if !val.is_nan() {
                first_valid_idx = Some(i);
                break;
            }
        }

        if let Some(idx) = first_valid_idx {
            // Set initial value
            let mut weighted_sum = data[idx];
            let mut weighted_count = 1.0;
            result[idx] = data[idx];

            // Compute exponentially weighted moving average
            for i in (idx + 1)..n {
                let val = data[i];

                if val.is_nan() && self.ignore_na {
                    // Skip NaN values if ignore_na is true
                    result[i] = weighted_sum;
                    continue;
                }

                // Update weighted sum
                weighted_sum = if val.is_nan() {
                    weighted_sum * (1.0 - self.alpha)
                } else {
                    self.alpha * val + (1.0 - self.alpha) * weighted_sum
                };

                // Update weighted count if adjusting for bias
                if self.adjust {
                    weighted_count = self.alpha + (1.0 - self.alpha) * weighted_count;
                }

                // Calculate result
                result[i] = if self.adjust {
                    weighted_sum / weighted_count
                } else {
                    weighted_sum
                };

                // Check min_periods
                if i - idx + 1 < self.min_periods {
                    result[i] = f64::NAN;
                }
            }
        }

        Ok(result)
    }
}

/// Date-time index structure for GPU-accelerated time series operations
pub type DateTimeIndex = Vec<DateTime<Utc>>;

/// Extension trait for Series to add GPU-accelerated time series operations
pub trait SeriesTimeGpuExt {
    /// Apply a GPU-accelerated rolling window operation to the series
    fn gpu_rolling(
        &self,
        window_size: usize,
        min_periods: usize,
        operation: WindowOperation,
        center: bool,
    ) -> Result<Series<f64>>;

    /// Apply a GPU-accelerated expanding window operation to the series
    fn gpu_expanding(&self, min_periods: usize, operation: WindowOperation) -> Result<Series<f64>>;

    /// Apply a GPU-accelerated exponentially weighted window operation to the series
    fn gpu_ewm(
        &self,
        alpha: f64,
        min_periods: usize,
        adjust: bool,
        ignore_na: bool,
    ) -> Result<Series<f64>>;

    /// Apply a GPU-accelerated exponentially weighted window operation to the series from span
    fn gpu_ewm_span(
        &self,
        span: f64,
        min_periods: usize,
        adjust: bool,
        ignore_na: bool,
    ) -> Result<Series<f64>>;
}

impl<T> SeriesTimeGpuExt for Series<T>
where
    T: Debug + Clone + Copy + Default + Send + Sync + Into<f64> + 'static,
{
    fn gpu_rolling(
        &self,
        window_size: usize,
        min_periods: usize,
        operation: WindowOperation,
        center: bool,
    ) -> Result<Series<f64>> {
        // Get data as f64 vector
        let data = self.as_f64()?;

        // Create GPU-accelerated rolling window
        let window = GpuRollingWindow::new(window_size, min_periods, operation, center);

        // Apply the window operation
        let result = window.apply_gpu(&data, None)?;

        // Create a new series with the result
        Series::new(result, self.name().cloned())
    }

    fn gpu_expanding(&self, min_periods: usize, operation: WindowOperation) -> Result<Series<f64>> {
        // Get data as f64 vector
        let data = self.as_f64()?;

        // Create GPU-accelerated expanding window
        let window = GpuExpandingWindow::new(min_periods, operation);

        // Apply the window operation
        let result = window.apply_gpu(&data, None)?;

        // Create a new series with the result
        Series::new(result, self.name().cloned())
    }

    fn gpu_ewm(
        &self,
        alpha: f64,
        min_periods: usize,
        adjust: bool,
        ignore_na: bool,
    ) -> Result<Series<f64>> {
        // Get data as f64 vector
        let data = self.as_f64()?;

        // Create GPU-accelerated exponentially weighted window
        let window = GpuEWWindow::new(alpha, min_periods, adjust, ignore_na);

        // Apply the window operation
        let result = window.apply_gpu(&data, None)?;

        // Create a new series with the result
        Series::new(result, self.name().cloned())
    }

    fn gpu_ewm_span(
        &self,
        span: f64,
        min_periods: usize,
        adjust: bool,
        ignore_na: bool,
    ) -> Result<Series<f64>> {
        // Get data as f64 vector
        let data = self.as_f64()?;

        // Create GPU-accelerated exponentially weighted window from span
        let window = GpuEWWindow::from_span(span, min_periods, adjust, ignore_na)?;

        // Apply the window operation
        let result = window.apply_gpu(&data, None)?;

        // Create a new series with the result
        Series::new(result, self.name().cloned())
    }
}