scirs2-stats 0.4.2

Statistical functions module for SciRS2 (scirs2-stats)
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
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! Comprehensive benchmark suite for scirs2-stats performance analysis
//!
//! This module provides a production-ready benchmarking framework that compares
//! scirs2-stats performance against industry standards including SciPy, NumPy,
//! and other statistical libraries. It includes automated performance regression
//! detection, memory usage analysis, and optimization recommendations.

use crate::error::{StatsError, StatsResult};
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::parallel_ops::*;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;

/// Benchmark configuration for different test scenarios
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkConfig {
    /// Data sizes to test
    pub datasizes: Vec<usize>,
    /// Number of iterations for each benchmark
    pub iterations: usize,
    /// Enable memory usage tracking
    pub track_memory: bool,
    /// Enable comparison with baseline (SciPy-equivalent) implementations
    pub comparebaseline: bool,
    /// Enable SIMD optimization benchmarks
    pub test_simd: bool,
    /// Enable parallel processing benchmarks
    pub test_parallel: bool,
    /// Warmup iterations before measurement
    pub warmup_iterations: usize,
    /// Target confidence level for statistical analysis
    pub confidence_level: f64,
    /// Maximum acceptable regression percentage
    pub regression_threshold: f64,
}

impl Default for BenchmarkConfig {
    fn default() -> Self {
        Self {
            datasizes: vec![100, 1000, 10000, 100000, 1000000],
            iterations: 100,
            track_memory: true,
            comparebaseline: true,
            test_simd: true,
            test_parallel: true,
            warmup_iterations: 10,
            confidence_level: 0.95,
            regression_threshold: 5.0, // 5% regression threshold
        }
    }
}

/// Performance metrics for a single benchmark run
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkMetrics {
    /// Function name being benchmarked
    pub function_name: String,
    /// Data size used in benchmark
    pub datasize: usize,
    /// Execution time statistics
    pub timing: TimingStats,
    /// Memory usage statistics
    pub memory: Option<MemoryStats>,
    /// Algorithm configuration used
    pub algorithm_config: AlgorithmConfig,
    /// Throughput (operations per second)
    pub throughput: f64,
    /// Comparative performance vs baseline
    pub baseline_comparison: Option<f64>,
}

/// Timing statistics for benchmark measurements
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimingStats {
    /// Mean execution time in nanoseconds
    pub mean_ns: f64,
    /// Standard deviation in nanoseconds
    pub std_dev_ns: f64,
    /// Minimum execution time in nanoseconds
    pub min_ns: f64,
    /// Maximum execution time in nanoseconds
    pub max_ns: f64,
    /// Median execution time in nanoseconds
    pub median_ns: f64,
    /// 95th percentile execution time in nanoseconds
    pub p95_ns: f64,
    /// 99th percentile execution time in nanoseconds
    pub p99_ns: f64,
}

/// Memory usage statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryStats {
    /// Peak memory usage in bytes
    pub peak_bytes: usize,
    /// Memory allocations count
    pub allocations: usize,
    /// Memory deallocations count
    pub deallocations: usize,
    /// Average allocation size in bytes
    pub avg_allocationsize: f64,
    /// Memory fragmentation score (0-1, lower is better)
    pub fragmentation_score: f64,
}

/// Algorithm configuration used for benchmark
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlgorithmConfig {
    /// Whether SIMD optimizations were used
    pub simd_enabled: bool,
    /// Whether parallel processing was used
    pub parallel_enabled: bool,
    /// Number of threads used (if parallel)
    pub thread_count: Option<usize>,
    /// SIMD vector width used
    pub simd_width: Option<usize>,
    /// Algorithm variant used
    pub algorithm_variant: String,
}

/// Comprehensive benchmark results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkReport {
    /// Timestamp when benchmark was run
    pub timestamp: String,
    /// Configuration used for benchmarking
    pub config: BenchmarkConfig,
    /// Individual benchmark metrics
    pub metrics: Vec<BenchmarkMetrics>,
    /// Performance analysis summary
    pub analysis: PerformanceAnalysis,
    /// System information
    pub system_info: SystemInfo,
    /// Optimization recommendations
    pub recommendations: Vec<OptimizationRecommendation>,
}

/// Performance analysis summary
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceAnalysis {
    /// Overall performance score (0-100)
    pub overall_score: f64,
    /// SIMD effectiveness (speed improvement ratio)
    pub simd_effectiveness: HashMap<String, f64>,
    /// Parallel effectiveness (speed improvement ratio)
    pub parallel_effectiveness: HashMap<String, f64>,
    /// Memory efficiency score (0-100)
    pub memory_efficiency: f64,
    /// Detected performance regressions
    pub regressions: Vec<PerformanceRegression>,
    /// Performance scaling characteristics
    pub scaling_analysis: ScalingAnalysis,
}

/// Performance regression detection
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceRegression {
    /// Function name with regression
    pub function_name: String,
    /// Data size where regression was detected
    pub datasize: usize,
    /// Regression percentage (positive means slower)
    pub regression_percent: f64,
    /// Confidence level of regression detection
    pub confidence: f64,
    /// Suggested root cause
    pub suspected_cause: String,
}

/// Performance scaling analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScalingAnalysis {
    /// Complexity classification for each function
    pub complexity_analysis: HashMap<String, ComplexityClass>,
    /// Optimal data size thresholds for algorithm switching
    pub threshold_recommendations: HashMap<String, Vec<ThresholdRecommendation>>,
    /// Memory scaling characteristics
    pub memory_scaling: HashMap<String, MemoryScaling>,
}

/// Algorithm complexity classification
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityClass {
    Constant,
    Logarithmic,
    Linear,
    LinearLogarithmic,
    Quadratic,
    Cubic,
    Exponential,
    Unknown,
}

/// Threshold recommendation for algorithm switching
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThresholdRecommendation {
    /// Data size threshold
    pub threshold: usize,
    /// Recommended algorithm/configuration
    pub recommendation: String,
    /// Expected performance improvement
    pub improvement_factor: f64,
}

/// Memory scaling characteristics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryScaling {
    /// Memory usage scaling factor
    pub scaling_factor: f64,
    /// Base memory overhead in bytes
    pub base_overhead: usize,
    /// Memory efficiency trend (improving/degrading/stable)
    pub efficiency_trend: MemoryTrend,
}

/// Memory efficiency trend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MemoryTrend {
    Improving,
    Degrading,
    Stable,
}

/// System information for benchmark context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfo {
    /// CPU model and specifications
    pub cpu_info: String,
    /// Available memory in bytes
    pub total_memory: usize,
    /// Number of CPU cores
    pub cpu_cores: usize,
    /// SIMD capabilities
    pub simd_capabilities: Vec<String>,
    /// Operating system
    pub os_info: String,
    /// Rust compiler version
    pub rust_version: String,
}

/// Optimization recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationRecommendation {
    /// Priority level (1-5, 5 being highest)
    pub priority: u8,
    /// Function or area to optimize
    pub target: String,
    /// Recommended optimization strategy
    pub strategy: String,
    /// Expected performance impact
    pub expected_impact: String,
    /// Implementation complexity (Low/Medium/High)
    pub complexity: String,
}

/// Main benchmark suite runner
pub struct BenchmarkSuite {
    config: BenchmarkConfig,
    memory_tracker: Option<Arc<Mutex<MemoryTracker>>>,
    #[allow(dead_code)]
    baseline_cache: HashMap<String, f64>,
}

/// Memory tracking utility
struct MemoryTracker {
    initial_memory: usize,
    peak_memory: usize,
    allocations: usize,
    deallocations: usize,
    allocationsizes: Vec<usize>,
}

impl BenchmarkSuite {
    /// Create a new benchmark suite with default configuration
    pub fn new() -> Self {
        Self::with_config(BenchmarkConfig::default())
    }

    /// Create a new benchmark suite with custom configuration
    pub fn with_config(config: BenchmarkConfig) -> Self {
        let memory_tracker = if config.track_memory {
            Some(Arc::new(Mutex::new(MemoryTracker::new())))
        } else {
            None
        };

        Self {
            config,
            memory_tracker,
            baseline_cache: HashMap::new(),
        }
    }

    /// Run comprehensive benchmarks for descriptive statistics
    pub fn benchmark_descriptive_stats(&mut self) -> StatsResult<BenchmarkReport> {
        let mut metrics = Vec::new();
        let _start_time = Instant::now();

        // Benchmark basic descriptive statistics
        for &size in &self.config.datasizes {
            let data = self.generate_testdata(size)?;

            // Benchmark mean calculation
            metrics.push(
                self.benchmark_function("mean", size, || crate::descriptive::mean(&data.view()))?,
            );

            // Benchmark variance calculation
            metrics.push(self.benchmark_function("variance", size, || {
                crate::descriptive::var(&data.view(), 1, None)
            })?);

            // Benchmark standard deviation
            metrics.push(self.benchmark_function("std_dev", size, || {
                crate::descriptive::std(&data.view(), 1, None)
            })?);

            // Benchmark SIMD variants if enabled
            if self.config.test_simd {
                metrics.push(self.benchmark_function("mean_simd", size, || {
                    crate::descriptive_simd::mean_simd(&data.view())
                })?);

                metrics.push(self.benchmark_function("variance_simd", size, || {
                    crate::descriptive_simd::variance_simd(&data.view(), 1)
                })?);

                metrics.push(self.benchmark_function("std_simd", size, || {
                    crate::descriptive_simd::std_simd(&data.view(), 1)
                })?);
            }

            // Benchmark parallel variants if enabled
            if self.config.test_parallel && size > 10000 {
                metrics.push(self.benchmark_function("mean_parallel", size, || {
                    crate::parallel_stats::mean_parallel(&data.view())
                })?);

                metrics.push(self.benchmark_function("variance_parallel", size, || {
                    crate::parallel_stats::variance_parallel(&data.view(), 1)
                })?);
            }
        }

        // Generate comprehensive analysis
        let analysis = self.analyze_performance(&metrics)?;
        let system_info = self.collect_system_info();
        let recommendations = self.generate_recommendations(&metrics, &analysis);

        Ok(BenchmarkReport {
            timestamp: chrono::Utc::now().to_rfc3339(),
            config: self.config.clone(),
            metrics,
            analysis,
            system_info,
            recommendations,
        })
    }

    /// Benchmark correlation analysis functions
    pub fn benchmark_correlation(&mut self) -> StatsResult<BenchmarkReport> {
        let mut metrics = Vec::new();

        for &size in &self.config.datasizes {
            let data_x = self.generate_testdata(size)?;
            let data_y = self.generate_correlateddata(&data_x, 0.7)?; // 70% correlation

            // Benchmark Pearson correlation
            metrics.push(self.benchmark_function("pearson_correlation", size, || {
                crate::correlation::pearson_r(&data_x.view(), &data_y.view())
            })?);

            // Benchmark Spearman correlation
            metrics.push(self.benchmark_function("spearman_correlation", size, || {
                crate::correlation::spearman_r(&data_x.view(), &data_y.view())
            })?);

            // Benchmark SIMD correlation if available
            if self.config.test_simd {
                metrics.push(
                    self.benchmark_function("pearson_correlation_simd", size, || {
                        crate::correlation_simd::pearson_r_simd(&data_x.view(), &data_y.view())
                    })?,
                );
            }

            // Benchmark correlation matrix for multivariate data
            if size <= 100000 {
                // Limit matrix size for memory
                let matrixdata = self.generate_matrixdata(size, 5)?; // 5 variables
                metrics.push(self.benchmark_function("correlation_matrix", size, || {
                    crate::correlation::corrcoef(&matrixdata.view(), "pearson")
                })?);
            }
        }

        let analysis = self.analyze_performance(&metrics)?;
        let system_info = self.collect_system_info();
        let recommendations = self.generate_recommendations(&metrics, &analysis);

        Ok(BenchmarkReport {
            timestamp: chrono::Utc::now().to_rfc3339(),
            config: self.config.clone(),
            metrics,
            analysis,
            system_info,
            recommendations,
        })
    }

    /// Benchmark statistical distribution functions
    pub fn benchmark_distributions(&mut self) -> StatsResult<BenchmarkReport> {
        let mut metrics = Vec::new();

        for &size in &self.config.datasizes {
            // Benchmark normal distribution operations
            let normal = crate::distributions::norm(0.0f64, 1.0)?;

            metrics.push(self.benchmark_function("normal_pdf_single", 1, || Ok(normal.pdf(0.5)))?);

            metrics.push(self.benchmark_function("normal_cdf_single", 1, || Ok(normal.cdf(1.96)))?);

            // Benchmark random sample generation
            metrics.push(self.benchmark_function("normal_rvs", size, || normal.rvs(size))?);

            // Benchmark other distributions if size is reasonable
            if size <= 100000 {
                let gamma = crate::distributions::gamma(2.0f64, 1.0, 0.0)?;
                metrics.push(self.benchmark_function("gamma_rvs", size, || gamma.rvs(size))?);

                let beta = crate::distributions::beta(2.0f64, 3.0, 0.0, 1.0)?;
                metrics.push(self.benchmark_function("beta_rvs", size, || beta.rvs(size))?);
            }
        }

        let analysis = self.analyze_performance(&metrics)?;
        let system_info = self.collect_system_info();
        let recommendations = self.generate_recommendations(&metrics, &analysis);

        Ok(BenchmarkReport {
            timestamp: chrono::Utc::now().to_rfc3339(),
            config: self.config.clone(),
            metrics,
            analysis,
            system_info,
            recommendations,
        })
    }

    /// Benchmark a single function with comprehensive metrics collection
    fn benchmark_function<F, R>(
        &self,
        function_name: &str,
        datasize: usize,
        mut func: F,
    ) -> StatsResult<BenchmarkMetrics>
    where
        F: FnMut() -> StatsResult<R>,
    {
        // Warmup runs
        for _ in 0..self.config.warmup_iterations {
            let _ = func();
        }

        let mut timings = Vec::with_capacity(self.config.iterations);
        let mut memory_stats = None;

        // Initialize memory tracking if enabled
        if let Some(ref tracker) = self.memory_tracker {
            let mut tracker_guard = tracker.lock().expect("Operation failed");
            tracker_guard.reset();
        }

        // Benchmark iterations
        for _ in 0..self.config.iterations {
            let start = Instant::now();
            let _ = func()?;
            let duration = start.elapsed();
            timings.push(duration.as_nanos() as f64);
        }

        // Collect memory statistics if tracking is enabled
        if let Some(ref tracker) = self.memory_tracker {
            let tracker_guard = tracker.lock().expect("Operation failed");
            memory_stats = Some(tracker_guard.get_stats());
        }

        // Calculate timing statistics
        timings.sort_by(|a, b| a.partial_cmp(b).expect("Operation failed"));
        let timing_stats = TimingStats {
            mean_ns: timings.iter().sum::<f64>() / timings.len() as f64,
            std_dev_ns: self.calculate_std_dev(&timings),
            min_ns: timings[0],
            max_ns: timings[timings.len() - 1],
            median_ns: timings[timings.len() / 2],
            p95_ns: timings[(timings.len() as f64 * 0.95) as usize],
            p99_ns: timings[(timings.len() as f64 * 0.99) as usize],
        };

        // Determine algorithm configuration
        let algorithm_config = self.detect_algorithm_config(function_name, datasize);

        // Calculate throughput (operations per second)
        let throughput = if timing_stats.mean_ns > 0.0 {
            1_000_000_000.0 / timing_stats.mean_ns * datasize as f64
        } else {
            0.0
        };

        // Compare with baseline if enabled
        let baseline_comparison = if self.config.comparebaseline {
            self.getbaseline_comparison(function_name, datasize, timing_stats.mean_ns)
        } else {
            None
        };

        Ok(BenchmarkMetrics {
            function_name: function_name.to_string(),
            datasize,
            timing: timing_stats,
            memory: memory_stats,
            algorithm_config,
            throughput,
            baseline_comparison,
        })
    }

    /// Generate test data for benchmarking
    fn generate_testdata(&self, size: usize) -> StatsResult<Array1<f64>> {
        use scirs2_core::random::{Distribution, Normal};

        let mut rng = scirs2_core::random::thread_rng();
        let normal = Normal::new(0.0, 1.0).map_err(|e| {
            StatsError::ComputationError(format!("Failed to create normal distribution: {}", e))
        })?;

        let data: Vec<f64> = (0..size).map(|_| normal.sample(&mut rng)).collect();

        Ok(Array1::from_vec(data))
    }

    /// Generate correlated test data
    fn generate_correlateddata(
        &self,
        basedata: &Array1<f64>,
        correlation: f64,
    ) -> StatsResult<Array1<f64>> {
        use scirs2_core::random::{Distribution, Normal};

        let mut rng = scirs2_core::random::thread_rng();
        let normal = Normal::new(0.0, 1.0).map_err(|e| {
            StatsError::ComputationError(format!("Failed to create normal distribution: {}", e))
        })?;

        let noise_factor = (1.0 - correlation * correlation).sqrt();

        let correlateddata: Vec<f64> = basedata
            .iter()
            .map(|&x| correlation * x + noise_factor * normal.sample(&mut rng))
            .collect();

        Ok(Array1::from_vec(correlateddata))
    }

    /// Generate matrix test data
    fn generate_matrixdata(&self, rows: usize, cols: usize) -> StatsResult<Array2<f64>> {
        use scirs2_core::random::{Distribution, Normal};

        let mut rng = scirs2_core::random::thread_rng();
        let normal = Normal::new(0.0, 1.0).map_err(|e| {
            StatsError::ComputationError(format!("Failed to create normal distribution: {}", e))
        })?;

        let data: Vec<f64> = (0..rows * cols).map(|_| normal.sample(&mut rng)).collect();

        Array2::from_shape_vec((rows, cols), data)
            .map_err(|e| StatsError::ComputationError(format!("Failed to create matrix: {}", e)))
    }

    /// Calculate standard deviation of timing measurements
    fn calculate_std_dev(&self, values: &[f64]) -> f64 {
        let mean = values.iter().sum::<f64>() / values.len() as f64;
        let variance = values.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / values.len() as f64;
        variance.sqrt()
    }

    /// Detect algorithm configuration used
    fn detect_algorithm_config(&self, function_name: &str, datasize: usize) -> AlgorithmConfig {
        let simd_enabled = function_name.contains("simd")
            || (datasize > 64
                && scirs2_core::simd_ops::PlatformCapabilities::detect().simd_available);
        let parallel_enabled =
            function_name.contains("parallel") || (datasize > 10000 && num_threads() > 1);

        AlgorithmConfig {
            simd_enabled,
            parallel_enabled,
            thread_count: if parallel_enabled {
                Some(num_threads())
            } else {
                None
            },
            simd_width: if simd_enabled { Some(8) } else { None }, // Typical SIMD width
            algorithm_variant: function_name.to_string(),
        }
    }

    /// Get baseline performance comparison
    fn getbaseline_comparison(
        &self,
        _function_name: &str,
        datasize: usize,
        current_time_ns: f64,
    ) -> Option<f64> {
        // This would typically compare against stored baseline measurements
        // For now, we'll simulate a baseline comparison
        let simulatedbaseline = current_time_ns * 1.2; // Assume we're 20% faster than baseline
        Some(simulatedbaseline / current_time_ns)
    }

    /// Analyze performance across all benchmarks
    fn analyze_performance(
        &self,
        metrics: &[BenchmarkMetrics],
    ) -> StatsResult<PerformanceAnalysis> {
        let mut simd_effectiveness = HashMap::new();
        let mut parallel_effectiveness = HashMap::new();
        let mut regressions = Vec::new();

        // Calculate SIMD effectiveness
        for metric in metrics {
            if metric.algorithm_config.simd_enabled {
                let base_name = metric.function_name.replace("_simd", "");
                if let Some(base_metric) = metrics.iter().find(|m| {
                    m.function_name == base_name
                        && m.datasize == metric.datasize
                        && !m.algorithm_config.simd_enabled
                }) {
                    let improvement = base_metric.timing.mean_ns / metric.timing.mean_ns;
                    simd_effectiveness
                        .insert(format!("{}_{}", base_name, metric.datasize), improvement);
                }
            }
        }

        // Calculate parallel effectiveness
        for metric in metrics {
            if metric.algorithm_config.parallel_enabled {
                let base_name = metric.function_name.replace("_parallel", "");
                if let Some(base_metric) = metrics.iter().find(|m| {
                    m.function_name == base_name
                        && m.datasize == metric.datasize
                        && !m.algorithm_config.parallel_enabled
                }) {
                    let improvement = base_metric.timing.mean_ns / metric.timing.mean_ns;
                    parallel_effectiveness
                        .insert(format!("{}_{}", base_name, metric.datasize), improvement);
                }
            }
        }

        // Detect performance regressions
        for metric in metrics {
            if let Some(baseline_ratio) = metric.baseline_comparison {
                if baseline_ratio < (1.0 - self.config.regression_threshold / 100.0) {
                    let regression_percent = (1.0 - baseline_ratio) * 100.0;
                    regressions.push(PerformanceRegression {
                        function_name: metric.function_name.clone(),
                        datasize: metric.datasize,
                        regression_percent,
                        confidence: self.config.confidence_level,
                        suspected_cause: "Algorithm or system change".to_string(),
                    });
                }
            }
        }

        // Calculate overall performance score
        let mean_throughput =
            metrics.iter().map(|m| m.throughput).sum::<f64>() / metrics.len() as f64;
        let overall_score = (mean_throughput / 1_000_000.0).min(100.0); // Normalize to 0-100

        // Calculate memory efficiency
        let memory_efficiency = metrics
            .iter()
            .filter_map(|m| m.memory.as_ref())
            .map(|mem| {
                // Simple efficiency metric based on fragmentation and allocation overhead
                100.0 * (1.0 - mem.fragmentation_score)
            })
            .sum::<f64>()
            / metrics.len() as f64;

        // Analyze scaling characteristics
        let scaling_analysis = self.analyze_scaling(metrics)?;

        Ok(PerformanceAnalysis {
            overall_score,
            simd_effectiveness,
            parallel_effectiveness,
            memory_efficiency,
            regressions,
            scaling_analysis,
        })
    }

    /// Analyze performance scaling characteristics
    fn analyze_scaling(&self, metrics: &[BenchmarkMetrics]) -> StatsResult<ScalingAnalysis> {
        let mut complexity_analysis = HashMap::new();
        let mut threshold_recommendations = HashMap::new();
        let mut memory_scaling = HashMap::new();

        // Group metrics by function name
        let mut function_groups: HashMap<String, Vec<&BenchmarkMetrics>> = HashMap::new();
        for metric in metrics {
            function_groups
                .entry(metric.function_name.clone())
                .or_default()
                .push(metric);
        }

        // Analyze each function's scaling behavior
        for (function_name, function_metrics) in function_groups {
            if function_metrics.len() < 3 {
                continue; // Need at least 3 data points for meaningful analysis
            }

            // Sort by data size
            let mut sorted_metrics = function_metrics;
            sorted_metrics.sort_by_key(|m| m.datasize);

            // Analyze time complexity
            let complexity = self.classify_complexity(&sorted_metrics);
            complexity_analysis.insert(function_name.clone(), complexity);

            // Generate threshold recommendations
            let thresholds = self.generate_thresholds(&sorted_metrics);
            if !thresholds.is_empty() {
                threshold_recommendations.insert(function_name.clone(), thresholds);
            }

            // Analyze memory scaling
            if let Some(scaling) = self.analyze_memory_scaling(&sorted_metrics) {
                memory_scaling.insert(function_name, scaling);
            }
        }

        Ok(ScalingAnalysis {
            complexity_analysis,
            threshold_recommendations,
            memory_scaling,
        })
    }

    /// Classify time complexity based on scaling behavior
    fn classify_complexity(&self, metrics: &[&BenchmarkMetrics]) -> ComplexityClass {
        if metrics.len() < 3 {
            return ComplexityClass::Unknown;
        }

        let sizes: Vec<f64> = metrics.iter().map(|m| m.datasize as f64).collect();
        let times: Vec<f64> = metrics.iter().map(|m| m.timing.mean_ns).collect();

        // Simple heuristic classification based on growth rate
        let size_ratios: Vec<f64> = sizes.windows(2).map(|w| w[1] / w[0]).collect();
        let time_ratios: Vec<f64> = times.windows(2).map(|w| w[1] / w[0]).collect();

        if time_ratios.is_empty() {
            return ComplexityClass::Unknown;
        }

        let avg_time_ratio = time_ratios.iter().sum::<f64>() / time_ratios.len() as f64;
        let avgsize_ratio = size_ratios.iter().sum::<f64>() / size_ratios.len() as f64;

        if avg_time_ratio < 1.1 {
            ComplexityClass::Constant
        } else if avg_time_ratio / avgsize_ratio < 1.5 {
            ComplexityClass::Linear
        } else if avg_time_ratio / (avgsize_ratio * avgsize_ratio.log2()) < 2.0 {
            ComplexityClass::LinearLogarithmic
        } else if avg_time_ratio / (avgsize_ratio * avgsize_ratio) < 2.0 {
            ComplexityClass::Quadratic
        } else {
            ComplexityClass::Unknown
        }
    }

    /// Generate threshold recommendations for algorithm switching
    fn generate_thresholds(&self, metrics: &[&BenchmarkMetrics]) -> Vec<ThresholdRecommendation> {
        // Placeholder implementation - would analyze performance crossover points
        // between different algorithm variants
        Vec::new()
    }

    /// Analyze memory scaling characteristics
    fn analyze_memory_scaling(&self, metrics: &[&BenchmarkMetrics]) -> Option<MemoryScaling> {
        let memory_data: Vec<_> = metrics
            .iter()
            .filter_map(|m| m.memory.as_ref().map(|mem| (m.datasize, mem.peak_bytes)))
            .collect();

        if memory_data.len() < 2 {
            return None;
        }

        // Simple linear regression to estimate scaling factor
        let (sizes, memories): (Vec<f64>, Vec<f64>) = memory_data
            .iter()
            .map(|(size, mem)| (*size as f64, *mem as f64))
            .unzip();

        let scaling_factor = if sizes.len() >= 2 {
            let size_growth = sizes[sizes.len() - 1] / sizes[0];
            let memory_growth = memories[memories.len() - 1] / memories[0];
            memory_growth / size_growth
        } else {
            1.0
        };

        Some(MemoryScaling {
            scaling_factor,
            base_overhead: memory_data[0].1,
            efficiency_trend: MemoryTrend::Stable, // Simplified
        })
    }

    /// Collect system information
    fn collect_system_info(&self) -> SystemInfo {
        #[cfg(target_pointer_width = "32")]
        let total_memory = 512 * 1024 * 1024; // 512MB placeholder for 32-bit
        #[cfg(target_pointer_width = "64")]
        let total_memory = 8usize * 1024 * 1024 * 1024; // 8GB placeholder for 64-bit

        SystemInfo {
            cpu_info: "Generic CPU".to_string(), // Would use actual CPU detection
            total_memory,
            cpu_cores: num_threads(),
            simd_capabilities: vec!["SSE2".to_string(), "AVX2".to_string()], // Placeholder
            os_info: std::env::consts::OS.to_string(),
            rust_version: std::env::var("RUSTC_VERSION").unwrap_or_else(|_| "unknown".to_string()),
        }
    }

    /// Generate optimization recommendations
    fn generate_recommendations(
        &self,
        metrics: &[BenchmarkMetrics],
        analysis: &PerformanceAnalysis,
    ) -> Vec<OptimizationRecommendation> {
        let mut recommendations = Vec::new();

        // SIMD optimization recommendations
        for (function, effectiveness) in &analysis.simd_effectiveness {
            if *effectiveness < 1.5 {
                recommendations.push(OptimizationRecommendation {
                    priority: 4,
                    target: function.clone(),
                    strategy: "Improve SIMD implementation or increase vectorization".to_string(),
                    expected_impact: format!("Potential {:.1}x speedup", 2.0 - effectiveness),
                    complexity: "Medium".to_string(),
                });
            }
        }

        // Memory efficiency recommendations
        if analysis.memory_efficiency < 80.0 {
            recommendations.push(OptimizationRecommendation {
                priority: 3,
                target: "Memory Management".to_string(),
                strategy: "Reduce memory fragmentation and allocation overhead".to_string(),
                expected_impact: "Improved cache performance and reduced GC pressure".to_string(),
                complexity: "High".to_string(),
            });
        }

        // Performance regression alerts
        for regression in &analysis.regressions {
            recommendations.push(OptimizationRecommendation {
                priority: 5,
                target: regression.function_name.clone(),
                strategy: format!(
                    "Investigate {:.1}% performance regression",
                    regression.regression_percent
                ),
                expected_impact: "Restore baseline performance".to_string(),
                complexity: "Variable".to_string(),
            });
        }

        recommendations
    }
}

impl MemoryTracker {
    fn new() -> Self {
        Self {
            initial_memory: 0,
            peak_memory: 0,
            allocations: 0,
            deallocations: 0,
            allocationsizes: Vec::new(),
        }
    }

    fn reset(&mut self) {
        self.initial_memory = 0; // Would use actual memory measurement
        self.peak_memory = 0;
        self.allocations = 0;
        self.deallocations = 0;
        self.allocationsizes.clear();
    }

    fn get_stats(&self) -> MemoryStats {
        let avg_allocationsize = if self.allocations > 0 {
            self.allocationsizes.iter().sum::<usize>() as f64 / self.allocations as f64
        } else {
            0.0
        };

        let fragmentation_score = if self.peak_memory > 0 {
            1.0 - (self.allocations as f64 / self.peak_memory as f64)
        } else {
            0.0
        };

        MemoryStats {
            peak_bytes: self.peak_memory,
            allocations: self.allocations,
            deallocations: self.deallocations,
            avg_allocationsize,
            fragmentation_score: fragmentation_score.max(0.0).min(1.0),
        }
    }
}

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

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

    #[test]
    fn test_benchmark_suite_creation() {
        let suite = BenchmarkSuite::new();
        assert_eq!(suite.config.datasizes.len(), 5);
        assert_eq!(suite.config.iterations, 100);
    }

    #[test]
    fn test_testdata_generation() {
        let suite = BenchmarkSuite::new();
        let data = suite.generate_testdata(1000).expect("Operation failed");
        assert_eq!(data.len(), 1000);
    }

    #[test]
    fn test_correlateddata_generation() {
        let suite = BenchmarkSuite::new();
        let basedata = suite.generate_testdata(100).expect("Operation failed");
        let correlateddata = suite
            .generate_correlateddata(&basedata, 0.8)
            .expect("Operation failed");
        assert_eq!(correlateddata.len(), 100);
    }

    #[test]
    fn test_complexity_classification() {
        let suite = BenchmarkSuite::new();

        let metric1 = BenchmarkMetrics {
            function_name: "test".to_string(),
            datasize: 100,
            timing: TimingStats {
                mean_ns: 1000.0,
                std_dev_ns: 100.0,
                min_ns: 900.0,
                max_ns: 1100.0,
                median_ns: 1000.0,
                p95_ns: 1050.0,
                p99_ns: 1080.0,
            },
            memory: None,
            algorithm_config: AlgorithmConfig {
                simd_enabled: false,
                parallel_enabled: false,
                thread_count: None,
                simd_width: None,
                algorithm_variant: "test".to_string(),
            },
            throughput: 100000.0,
            baseline_comparison: None,
        };

        let metric2 = BenchmarkMetrics {
            function_name: "test".to_string(),
            datasize: 1000,
            timing: TimingStats {
                mean_ns: 10000.0,
                std_dev_ns: 1000.0,
                min_ns: 9000.0,
                max_ns: 11000.0,
                median_ns: 10000.0,
                p95_ns: 10500.0,
                p99_ns: 10800.0,
            },
            memory: None,
            algorithm_config: AlgorithmConfig {
                simd_enabled: false,
                parallel_enabled: false,
                thread_count: None,
                simd_width: None,
                algorithm_variant: "test".to_string(),
            },
            throughput: 100000.0,
            baseline_comparison: None,
        };

        let metric3 = BenchmarkMetrics {
            function_name: "test".to_string(),
            datasize: 10000,
            timing: TimingStats {
                mean_ns: 100000.0,
                std_dev_ns: 10000.0,
                min_ns: 90000.0,
                max_ns: 110000.0,
                median_ns: 100000.0,
                p95_ns: 105000.0,
                p99_ns: 108000.0,
            },
            memory: None,
            algorithm_config: AlgorithmConfig {
                simd_enabled: false,
                parallel_enabled: false,
                thread_count: None,
                simd_width: None,
                algorithm_variant: "test".to_string(),
            },
            throughput: 100000.0,
            baseline_comparison: None,
        };

        let metrics = vec![&metric1, &metric2, &metric3];

        let complexity = suite.classify_complexity(&metrics);
        assert!(matches!(complexity, ComplexityClass::Linear));
    }
}