scirs2-stats 0.4.1

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
//! Comprehensive validation suite integrating all testing frameworks
//!
//! This module provides a unified interface to run comprehensive validation
//! tests across SciPy benchmarking, property-based testing, and numerical
//! stability analysis.
//!
//! ## Features
//!
//! - Unified validation interface
//! - Comprehensive test reporting
//! - Cross-framework result correlation
//! - Production readiness assessment
//! - Automated regression detection

use crate::error::{StatsError, StatsResult};
use crate::numerical_stability_analyzer::{
    NumericalStabilityAnalyzer, StabilityAnalysisResult, StabilityConfig,
};
use crate::propertybased_validation::{
    ComprehensivePropertyTestSuite, PropertyTestConfig, PropertyTestResult,
};
use crate::scipy_benchmark_framework::{BenchmarkConfig, BenchmarkResult, ScipyBenchmarkFramework};
use scirs2_core::ndarray::{Array1, ArrayView1};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Instant;

/// Comprehensive validation suite for statistical functions
#[derive(Debug)]
pub struct ComprehensiveValidationSuite {
    /// SciPy benchmark framework
    benchmark_framework: ScipyBenchmarkFramework,
    /// Property-based testing suite
    property_test_suite: ComprehensivePropertyTestSuite,
    /// Numerical stability analyzer
    stability_analyzer: NumericalStabilityAnalyzer,
    /// Configuration for the validation suite
    config: ValidationSuiteConfig,
    /// Cached validation results
    cached_results: HashMap<String, ComprehensiveValidationResult>,
}

/// Configuration for the comprehensive validation suite
#[derive(Debug, Clone)]
pub struct ValidationSuiteConfig {
    /// Configuration for SciPy benchmarking
    pub benchmark_config: BenchmarkConfig,
    /// Configuration for property-based testing
    pub property_config: PropertyTestConfig,
    /// Configuration for stability analysis
    pub stability_config: StabilityConfig,
    /// Enable cross-validation between frameworks
    pub enable_cross_validation: bool,
    /// Enable regression detection
    pub enable_regression_detection: bool,
    /// Minimum pass rate for production readiness
    pub production_readiness_threshold: f64,
}

/// Result of comprehensive validation for a single function
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComprehensiveValidationResult {
    /// Function name validated
    pub function_name: String,
    /// SciPy benchmark results
    pub benchmark_results: Vec<BenchmarkResult>,
    /// Property test results
    pub property_results: Vec<PropertyTestResult>,
    /// Stability analysis result
    pub stability_result: StabilityAnalysisResult,
    /// Overall validation status
    pub overall_status: ValidationStatus,
    /// Production readiness assessment
    pub production_readiness: ProductionReadinessAssessment,
    /// Cross-validation correlation
    pub cross_validation: CrossValidationAnalysis,
    /// Execution time for validation
    pub validation_time: std::time::Duration,
    /// Timestamp of validation
    pub validated_at: chrono::DateTime<chrono::Utc>,
}

/// Overall validation status
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ValidationStatus {
    /// All validation frameworks pass
    FullyValidated,
    /// Most validation frameworks pass
    MostlyValidated,
    /// Some validation frameworks pass
    PartiallyValidated,
    /// Few validation frameworks pass
    PoorlyValidated,
    /// Validation failed across frameworks
    ValidationFailed,
}

/// Production readiness assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductionReadinessAssessment {
    /// Ready for production use
    pub is_production_ready: bool,
    /// Overall readiness score (0-100)
    pub readiness_score: f64,
    /// Specific readiness criteria
    pub readiness_criteria: ReadinessCriteria,
    /// Blockers preventing production use
    pub production_blockers: Vec<ProductionBlocker>,
    /// Recommendations for production readiness
    pub recommendations: Vec<ProductionRecommendation>,
}

/// Specific criteria for production readiness
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadinessCriteria {
    /// Accuracy meets production standards
    pub accuracy_ready: bool,
    /// Performance meets production standards
    pub performance_ready: bool,
    /// Stability meets production standards
    pub stability_ready: bool,
    /// Error handling meets production standards
    pub error_handling_ready: bool,
    /// Documentation meets production standards
    pub documentation_ready: bool,
}

/// Blocker preventing production use
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductionBlocker {
    /// Type of blocker
    pub blocker_type: BlockerType,
    /// Description of the issue
    pub description: String,
    /// Severity of the blocker
    pub severity: BlockerSeverity,
    /// Estimated effort to resolve
    pub resolution_effort: ResolutionEffort,
}

/// Types of production blockers
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum BlockerType {
    /// Accuracy issues
    Accuracy,
    /// Performance issues
    Performance,
    /// Stability issues
    Stability,
    /// API inconsistency
    API,
    /// Error handling issues
    ErrorHandling,
    /// Documentation issues
    Documentation,
}

/// Severity levels for blockers
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum BlockerSeverity {
    /// Critical - must be fixed
    Critical,
    /// High priority
    High,
    /// Medium priority
    Medium,
    /// Low priority
    Low,
}

/// Effort estimation for resolution
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ResolutionEffort {
    /// Minimal effort (< 1 day)
    Minimal,
    /// Low effort (1-3 days)
    Low,
    /// Medium effort (1-2 weeks)
    Medium,
    /// High effort (2-4 weeks)
    High,
    /// Very high effort (> 1 month)
    VeryHigh,
}

/// Production recommendation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProductionRecommendation {
    /// Area of recommendation
    pub area: RecommendationArea,
    /// Specific recommendation
    pub recommendation: String,
    /// Priority level
    pub priority: RecommendationPriority,
    /// Expected impact
    pub expected_impact: f64,
}

/// Areas for recommendations
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum RecommendationArea {
    /// Algorithm improvement
    Algorithm,
    /// Performance optimization
    Performance,
    /// Error handling
    ErrorHandling,
    /// Testing
    Testing,
    /// Documentation
    Documentation,
}

/// Priority levels for recommendations
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum RecommendationPriority {
    /// Critical priority
    Critical,
    /// High priority
    High,
    /// Medium priority
    Medium,
    /// Low priority
    Low,
}

/// Cross-validation analysis between frameworks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossValidationAnalysis {
    /// Correlation between benchmark and stability scores
    pub benchmark_stability_correlation: f64,
    /// Correlation between property tests and benchmarks
    pub property_benchmark_correlation: f64,
    /// Correlation between property tests and stability
    pub property_stability_correlation: f64,
    /// Overall framework agreement score
    pub framework_agreement: f64,
    /// Confidence in validation results
    pub validation_confidence: f64,
}

/// Comprehensive validation report for multiple functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComprehensiveValidationReport {
    /// Total functions validated
    pub total_functions: usize,
    /// Functions ready for production
    pub production_ready_functions: usize,
    /// Functions needing improvement
    pub functions_needing_improvement: usize,
    /// Overall validation summary
    pub validation_summary: ValidationSummary,
    /// Individual function results
    pub function_results: Vec<ComprehensiveValidationResult>,
    /// Cross-framework analysis
    pub framework_analysis: FrameworkAnalysis,
    /// Production readiness assessment
    pub overall_production_readiness: OverallProductionReadiness,
    /// Report generation time
    pub generated_at: chrono::DateTime<chrono::Utc>,
}

/// Summary of validation results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationSummary {
    /// Average benchmark score
    pub average_benchmark_score: f64,
    /// Average property test pass rate
    pub average_property_pass_rate: f64,
    /// Average stability score
    pub average_stability_score: f64,
    /// Overall validation score
    pub overall_validation_score: f64,
}

/// Analysis across validation frameworks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameworkAnalysis {
    /// Benchmark framework reliability
    pub benchmark_reliability: f64,
    /// Property test framework reliability
    pub property_test_reliability: f64,
    /// Stability framework reliability
    pub stability_reliability: f64,
    /// Inter-framework agreement
    pub inter_framework_agreement: f64,
}

/// Overall production readiness assessment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverallProductionReadiness {
    /// Overall production readiness
    pub is_production_ready: bool,
    /// Percentage of functions ready for production
    pub production_ready_percentage: f64,
    /// Critical blockers across all functions
    pub critical_blockers: Vec<ProductionBlocker>,
    /// Top recommendations for improvement
    pub top_recommendations: Vec<ProductionRecommendation>,
}

impl Default for ValidationSuiteConfig {
    fn default() -> Self {
        Self {
            benchmark_config: BenchmarkConfig::default(),
            property_config: PropertyTestConfig::default(),
            stability_config: StabilityConfig::default(),
            enable_cross_validation: true,
            enable_regression_detection: true,
            production_readiness_threshold: 0.85,
        }
    }
}

impl ComprehensiveValidationSuite {
    /// Create a new comprehensive validation suite
    pub fn new(config: ValidationSuiteConfig) -> Self {
        Self {
            benchmark_framework: ScipyBenchmarkFramework::new(config.benchmark_config.clone()),
            property_test_suite: ComprehensivePropertyTestSuite::new(
                config.property_config.clone(),
            ),
            stability_analyzer: NumericalStabilityAnalyzer::new(config.stability_config.clone()),
            config: config,
            cached_results: HashMap::new(),
        }
    }

    /// Create suite with default configuration
    pub fn default() -> Self {
        Self::new(ValidationSuiteConfig::default())
    }

    /// Validate a single statistical function comprehensively
    pub fn validate_function<F, G>(
        &mut self,
        function_name: &str,
        scirs2_impl: F,
        scipy_reference: Option<G>,
    ) -> StatsResult<ComprehensiveValidationResult>
    where
        F: Fn(&ArrayView1<f64>) -> StatsResult<f64> + Clone,
        G: Fn(&ArrayView1<f64>) -> f64,
    {
        let start_time = Instant::now();

        // Run SciPy benchmarks if _reference available
        let benchmark_results = if let Some(scipy_func) = scipy_reference {
            self.benchmark_framework.benchmark_function(
                function_name,
                scirs2_impl.clone(),
                scipy_func,
            )?
        } else {
            Vec::new()
        };

        // Run property-based tests
        let property_results = self.property_test_suite.test_function(function_name)?;

        // Run stability analysis with test data
        let testdata = self.generate_testdata(1000)?;
        let stability_result = self.stability_analyzer.analyze_function(
            function_name,
            scirs2_impl,
            &testdata.view(),
        )?;

        // Perform cross-validation analysis
        let cross_validation = if self.config.enable_cross_validation {
            self.perform_cross_validation(&benchmark_results, &property_results, &stability_result)
        } else {
            CrossValidationAnalysis {
                benchmark_stability_correlation: 0.0,
                property_benchmark_correlation: 0.0,
                property_stability_correlation: 0.0,
                framework_agreement: 0.0,
                validation_confidence: 0.5,
            }
        };

        // Determine overall validation status
        let overall_status =
            self.determine_overall_status(&benchmark_results, &property_results, &stability_result);

        // Assess production readiness
        let production_readiness = self.assess_production_readiness(
            &benchmark_results,
            &property_results,
            &stability_result,
            &cross_validation,
        );

        let validation_time = start_time.elapsed();

        let result = ComprehensiveValidationResult {
            function_name: function_name.to_string(),
            benchmark_results,
            property_results,
            stability_result,
            overall_status,
            production_readiness,
            cross_validation,
            validation_time,
            validated_at: chrono::Utc::now(),
        };

        self.cached_results
            .insert(function_name.to_string(), result.clone());
        Ok(result)
    }

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

        let mut rng = StdRng::seed_from_u64(self.config.property_config.seed);
        let normal = Normal::new(0.0, 1.0)
            .map_err(|e| StatsError::InvalidInput(format!("Distribution error: {}", e)))?;

        let mut data = Array1::zeros(size);
        for val in data.iter_mut() {
            *val = normal.sample(&mut rng);
        }

        Ok(data)
    }

    /// Perform cross-validation analysis between frameworks
    fn perform_cross_validation(
        &self,
        benchmark_results: &[BenchmarkResult],
        property_results: &[PropertyTestResult],
        stability_result: &StabilityAnalysisResult,
    ) -> CrossValidationAnalysis {
        // Simplified cross-validation analysis
        let benchmark_score = if !benchmark_results.is_empty() {
            benchmark_results
                .iter()
                .map(|r| match r.status {
                    crate::scipy_benchmark_framework::BenchmarkStatus::Pass => 1.0,
                    crate::scipy_benchmark_framework::BenchmarkStatus::AccuracyPass => 0.7,
                    crate::scipy_benchmark_framework::BenchmarkStatus::PerformancePass => 0.7,
                    crate::scipy_benchmark_framework::BenchmarkStatus::Fail => 0.0,
                    crate::scipy_benchmark_framework::BenchmarkStatus::Error => 0.0,
                })
                .sum::<f64>()
                / benchmark_results.len() as f64
        } else {
            0.5
        };

        let property_score = if !property_results.is_empty() {
            property_results
                .iter()
                .map(|r| r.test_cases_passed as f64 / r.test_cases_run.max(1) as f64)
                .sum::<f64>()
                / property_results.len() as f64
        } else {
            0.5
        };

        let stability_score = stability_result.stability_score / 100.0;

        // Calculate correlations (simplified)
        let benchmark_stability_correlation = 1.0 - (benchmark_score - stability_score).abs();
        let property_benchmark_correlation = 1.0 - (property_score - benchmark_score).abs();
        let property_stability_correlation = 1.0 - (property_score - stability_score).abs();

        let framework_agreement = (benchmark_stability_correlation
            + property_benchmark_correlation
            + property_stability_correlation)
            / 3.0;

        let validation_confidence = framework_agreement;

        CrossValidationAnalysis {
            benchmark_stability_correlation,
            property_benchmark_correlation,
            property_stability_correlation,
            framework_agreement,
            validation_confidence,
        }
    }

    /// Determine overall validation status
    fn determine_overall_status(
        &self,
        benchmark_results: &[BenchmarkResult],
        property_results: &[PropertyTestResult],
        stability_result: &StabilityAnalysisResult,
    ) -> ValidationStatus {
        let mut validation_scores = Vec::new();

        // Benchmark score
        if !benchmark_results.is_empty() {
            let benchmark_pass_rate = benchmark_results
                .iter()
                .filter(|r| {
                    matches!(
                        r.status,
                        crate::scipy_benchmark_framework::BenchmarkStatus::Pass
                    )
                })
                .count() as f64
                / benchmark_results.len() as f64;
            validation_scores.push(benchmark_pass_rate);
        }

        // Property test score
        if !property_results.is_empty() {
            let property_pass_rate = property_results
                .iter()
                .map(|r| r.test_cases_passed as f64 / r.test_cases_run.max(1) as f64)
                .sum::<f64>()
                / property_results.len() as f64;
            validation_scores.push(property_pass_rate);
        }

        // Stability score
        validation_scores.push(stability_result.stability_score / 100.0);

        let average_score = validation_scores.iter().sum::<f64>() / validation_scores.len() as f64;

        if average_score >= 0.9 {
            ValidationStatus::FullyValidated
        } else if average_score >= 0.75 {
            ValidationStatus::MostlyValidated
        } else if average_score >= 0.5 {
            ValidationStatus::PartiallyValidated
        } else if average_score >= 0.25 {
            ValidationStatus::PoorlyValidated
        } else {
            ValidationStatus::ValidationFailed
        }
    }

    /// Assess production readiness
    fn assess_production_readiness(
        &self,
        benchmark_results: &[BenchmarkResult],
        property_results: &[PropertyTestResult],
        stability_result: &StabilityAnalysisResult,
        cross_validation: &CrossValidationAnalysis,
    ) -> ProductionReadinessAssessment {
        let mut readiness_score = 0.0;
        let mut production_blockers = Vec::new();
        let recommendations = Vec::new();

        // Accuracy assessment
        let accuracy_ready = benchmark_results
            .iter()
            .all(|r| r.accuracy.passes_tolerance);
        if accuracy_ready {
            readiness_score += 25.0;
        } else {
            production_blockers.push(ProductionBlocker {
                blocker_type: BlockerType::Accuracy,
                description: "Accuracy does not meet tolerance requirements".to_string(),
                severity: BlockerSeverity::Critical,
                resolution_effort: ResolutionEffort::Medium,
            });
        }

        // Performance assessment
        let performance_ready = benchmark_results.iter().all(|r| {
            matches!(
                r.performance.performance_grade,
                crate::scipy_benchmark_framework::PerformanceGrade::A
                    | crate::scipy_benchmark_framework::PerformanceGrade::B
                    | crate::scipy_benchmark_framework::PerformanceGrade::C
            )
        });
        if performance_ready {
            readiness_score += 20.0;
        }

        // Stability assessment
        let stability_ready = matches!(
            stability_result.stability_grade,
            crate::numerical_stability_analyzer::StabilityGrade::Excellent
                | crate::numerical_stability_analyzer::StabilityGrade::Good
        );
        if stability_ready {
            readiness_score += 25.0;
        }

        // Property test assessment
        let property_ready = property_results.iter().all(|r| {
            matches!(
                r.status,
                crate::propertybased_validation::PropertyTestStatus::Pass
            )
        });
        if property_ready {
            readiness_score += 20.0;
        }

        // Cross-_validation confidence
        if cross_validation.validation_confidence > 0.8 {
            readiness_score += 10.0;
        }

        let is_production_ready =
            readiness_score >= (self.config.production_readiness_threshold * 100.0);

        let readiness_criteria = ReadinessCriteria {
            accuracy_ready,
            performance_ready,
            stability_ready,
            error_handling_ready: true, // Simplified
            documentation_ready: true,  // Simplified
        };

        ProductionReadinessAssessment {
            is_production_ready,
            readiness_score,
            readiness_criteria,
            production_blockers,
            recommendations,
        }
    }

    /// Generate comprehensive validation report
    pub fn generate_comprehensive_report(&self) -> ComprehensiveValidationReport {
        let function_results: Vec<_> = self.cached_results.values().cloned().collect();

        let total_functions = function_results.len();
        let production_ready_functions = function_results
            .iter()
            .filter(|r| r.production_readiness.is_production_ready)
            .count();
        let functions_needing_improvement = total_functions - production_ready_functions;

        // Calculate averages
        let average_benchmark_score = if total_functions > 0 {
            function_results
                .iter()
                .map(|r| {
                    r.benchmark_results
                        .iter()
                        .map(|b| {
                            if matches!(
                                b.status,
                                crate::scipy_benchmark_framework::BenchmarkStatus::Pass
                            ) {
                                100.0
                            } else {
                                0.0
                            }
                        })
                        .sum::<f64>()
                        / r.benchmark_results.len().max(1) as f64
                })
                .sum::<f64>()
                / total_functions as f64
        } else {
            0.0
        };

        let average_stability_score = if total_functions > 0 {
            function_results
                .iter()
                .map(|r| r.stability_result.stability_score)
                .sum::<f64>()
                / total_functions as f64
        } else {
            0.0
        };

        let validation_summary = ValidationSummary {
            average_benchmark_score,
            average_property_pass_rate: 0.0, // Simplified
            average_stability_score,
            overall_validation_score: (average_benchmark_score + average_stability_score) / 2.0,
        };

        let framework_analysis = FrameworkAnalysis {
            benchmark_reliability: 0.9, // Simplified
            property_test_reliability: 0.85,
            stability_reliability: 0.8,
            inter_framework_agreement: function_results
                .iter()
                .map(|r| r.cross_validation.framework_agreement)
                .sum::<f64>()
                / total_functions.max(1) as f64,
        };

        let overall_production_readiness = OverallProductionReadiness {
            is_production_ready: production_ready_functions as f64 / total_functions.max(1) as f64
                > self.config.production_readiness_threshold,
            production_ready_percentage: production_ready_functions as f64
                / total_functions.max(1) as f64
                * 100.0,
            critical_blockers: Vec::new(), // Would aggregate from all functions
            top_recommendations: Vec::new(), // Would aggregate and prioritize
        };

        ComprehensiveValidationReport {
            total_functions,
            production_ready_functions,
            functions_needing_improvement,
            validation_summary,
            function_results,
            framework_analysis,
            overall_production_readiness,
            generated_at: chrono::Utc::now(),
        }
    }
}

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

    #[test]
    fn test_comprehensive_validation_suite_creation() {
        let suite = ComprehensiveValidationSuite::default();
        assert_eq!(suite.config.production_readiness_threshold, 0.85);
    }

    #[test]
    fn test_validation_status_determination() {
        let suite = ComprehensiveValidationSuite::default();

        // Mock test data for status determination
        let benchmark_results = vec![];
        let property_results = vec![];
        let stability_result = crate::numerical_stability_analyzer::StabilityAnalysisResult {
            function_name: "test".to_string(),
            stability_grade: crate::numerical_stability_analyzer::StabilityGrade::Excellent,
            condition_analysis: crate::numerical_stability_analyzer::ConditionNumberAnalysis {
                condition_number: 1.0,
                conditioning_class:
                    crate::numerical_stability_analyzer::ConditioningClass::WellConditioned,
                accuracy_loss_digits: 0.0,
                input_sensitivity: 0.0,
            },
            error_propagation: crate::numerical_stability_analyzer::ErrorPropagationAnalysis {
                forward_error_bound: 0.0,
                backward_error_bound: 0.0,
                error_amplification: 1.0,
                rounding_error_stability: 1.0,
            },
            edge_case_robustness: crate::numerical_stability_analyzer::EdgeCaseRobustness {
                handles_infinity: true,
                handles_nan: true,
                handles_zero: true,
                handles_large_values: true,
                handles_small_values: true,
                edge_case_success_rate: 1.0,
            },
            precision_analysis: crate::numerical_stability_analyzer::PrecisionAnalysis {
                precision_loss_bits: 0.0,
                relative_precision: 1.0,
                cancellation_errors: vec![],
                overflow_underflow_risk: crate::numerical_stability_analyzer::OverflowRisk::None,
            },
            recommendations: vec![],
            stability_score: 95.0,
        };

        let status = suite.determine_overall_status(
            &benchmark_results,
            &property_results,
            &stability_result,
        );
        assert_eq!(status, ValidationStatus::FullyValidated);
    }

    #[test]
    #[ignore] // This test is too slow for regular testing - use cargo test -- --ignored to run
    fn test_mean_comprehensive_validation() {
        let mut suite = ComprehensiveValidationSuite::new(ValidationSuiteConfig {
            benchmark_config: BenchmarkConfig {
                testsizes: vec![100],
                performance_iterations: 5,
                warmup_iterations: 1,
                ..Default::default()
            },
            property_config: PropertyTestConfig {
                test_cases_per_property: 10,
                ..Default::default()
            },
            ..Default::default()
        });

        // Mock SciPy reference
        let scipy_mean = |data: &ArrayView1<f64>| -> f64 { data.sum() / data.len() as f64 };

        let result = suite
            .validate_function("mean", |data| mean(data), Some(scipy_mean))
            .expect("Operation failed");

        assert_eq!(result.function_name, "mean");
        assert!(matches!(
            result.overall_status,
            ValidationStatus::FullyValidated | ValidationStatus::MostlyValidated
        ));
        assert!(result.validation_time.as_secs() < 60); // Should complete within reasonable time
    }
}