quantrs2_device/vqa_support/
statistical.rs1use scirs2_core::ndarray::{Array1, Array2};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone)]
11pub struct VQAStatistics {
12 pub convergence_rate: f64,
14 pub parameter_variance: Vec<f64>,
16 pub objective_stats: ObjectiveStatistics,
18}
19
20#[derive(Debug, Clone)]
22pub struct ObjectiveStatistics {
23 pub mean: f64,
25 pub std: f64,
27 pub best: f64,
29 pub worst: f64,
31}
32
33impl Default for VQAStatistics {
34 fn default() -> Self {
35 Self {
36 convergence_rate: 0.0,
37 parameter_variance: Vec::new(),
38 objective_stats: ObjectiveStatistics::default(),
39 }
40 }
41}
42
43impl Default for ObjectiveStatistics {
44 fn default() -> Self {
45 Self {
46 mean: 0.0,
47 std: 0.0,
48 best: 0.0,
49 worst: 0.0,
50 }
51 }
52}
53
54pub fn analyze_convergence(objective_history: &[f64]) -> VQAStatistics {
56 if objective_history.is_empty() {
57 return VQAStatistics::default();
58 }
59
60 let mean = objective_history.iter().sum::<f64>() / objective_history.len() as f64;
61 let variance: f64 = objective_history
62 .iter()
63 .map(|x| (x - mean).powi(2))
64 .sum::<f64>()
65 / objective_history.len() as f64;
66 let std = variance.sqrt();
67
68 let best = objective_history
69 .iter()
70 .fold(f64::INFINITY, |a, &b| a.min(b));
71 let worst = objective_history
72 .iter()
73 .fold(f64::NEG_INFINITY, |a, &b| a.max(b));
74
75 VQAStatistics {
76 convergence_rate: if objective_history.len() > 1 {
77 (objective_history[0] - objective_history[objective_history.len() - 1]).abs()
78 / objective_history.len() as f64
79 } else {
80 0.0
81 },
82 parameter_variance: vec![variance],
83 objective_stats: ObjectiveStatistics {
84 mean,
85 std,
86 best,
87 worst,
88 },
89 }
90}