quantrs2_core/realtime_monitoring/
functions.rs1use crate::{
6 error::{QuantRS2Error, QuantRS2Result},
7 hardware_compilation::{HardwarePlatform, NativeGateType},
8 qubit::QubitId,
9};
10use std::{
11 collections::{HashMap, HashSet, VecDeque},
12 fmt,
13 sync::{Arc, RwLock},
14 thread,
15 time::{Duration, SystemTime},
16};
17
18use super::types::{
19 Alert, AlertLevel, AlertStatus, AlertThresholds, Anomaly, Correlation, DifficultyLevel,
20 ExpectedImprovement, ExportDestination, ExportFormat, ExportSettings, MetricMeasurement,
21 MetricType, MetricValue, MonitoringConfig, MonitoringStatus, OptimizationRecommendation,
22 PlatformMonitoringConfig, Prediction, RealtimeDataStore, RealtimeMonitor,
23 RecommendationPriority, RecommendationType, SuperconductingCollector, SystemStatus,
24 TrainingExample, TrendAnalysis, WidgetConfig, WidgetData,
25};
26
27pub trait MetricCollector: std::fmt::Debug + Send + Sync {
29 fn collect_metrics(&self) -> QuantRS2Result<Vec<MetricMeasurement>>;
31 fn supported_metrics(&self) -> HashSet<MetricType>;
33 fn platform(&self) -> HardwarePlatform;
35 fn initialize(&mut self) -> QuantRS2Result<()>;
37 fn is_connected(&self) -> bool;
39 fn disconnect(&mut self) -> QuantRS2Result<()>;
41}
42pub trait TrendAnalyzer: std::fmt::Debug + Send + Sync {
44 fn analyze_trend(&self, data: &[MetricMeasurement]) -> QuantRS2Result<TrendAnalysis>;
46 fn name(&self) -> &str;
48}
49pub trait AnomalyDetector: std::fmt::Debug + Send + Sync {
51 fn detect_anomalies(&self, data: &[MetricMeasurement]) -> QuantRS2Result<Vec<Anomaly>>;
53 fn name(&self) -> &str;
55 fn confidence_threshold(&self) -> f64;
57}
58pub trait CorrelationAnalyzer: std::fmt::Debug + Send + Sync {
60 fn analyze_correlations(
62 &self,
63 data: &HashMap<MetricType, Vec<MetricMeasurement>>,
64 ) -> QuantRS2Result<Vec<Correlation>>;
65 fn name(&self) -> &str;
67}
68pub trait PredictiveModel: std::fmt::Debug + Send + Sync {
70 fn predict(
72 &self,
73 historical_data: &[MetricMeasurement],
74 horizon: Duration,
75 ) -> QuantRS2Result<Prediction>;
76 fn update(&mut self, new_data: &[MetricMeasurement]) -> QuantRS2Result<()>;
78 fn name(&self) -> &str;
80 fn accuracy(&self) -> f64;
82}
83pub trait AlertHandler: std::fmt::Debug + Send + Sync {
85 fn handle_alert(&self, alert: &Alert) -> QuantRS2Result<()>;
87 fn name(&self) -> &str;
89 fn can_handle(&self, level: AlertLevel) -> bool;
91}
92pub trait OptimizationStrategy: std::fmt::Debug + Send + Sync {
94 fn analyze(&self, data: &RealtimeDataStore) -> QuantRS2Result<Vec<OptimizationRecommendation>>;
96 fn name(&self) -> &str;
98 fn priority(&self) -> u32;
100}
101pub trait MLModel: std::fmt::Debug + Send + Sync {
103 fn train(&mut self, training_data: &[TrainingExample]) -> QuantRS2Result<()>;
105 fn predict(
107 &self,
108 input_data: &[MetricMeasurement],
109 ) -> QuantRS2Result<Vec<OptimizationRecommendation>>;
110 fn accuracy(&self) -> f64;
112 fn name(&self) -> &str;
114}
115pub trait DashboardWidget: std::fmt::Debug + Send + Sync {
117 fn render(&self, data: &RealtimeDataStore) -> QuantRS2Result<WidgetData>;
119 fn get_config(&self) -> WidgetConfig;
121 fn update_config(&mut self, config: WidgetConfig) -> QuantRS2Result<()>;
123}
124pub trait DataExporter: std::fmt::Debug + Send + Sync {
126 fn export(
128 &self,
129 data: &[MetricMeasurement],
130 destination: &ExportDestination,
131 ) -> QuantRS2Result<()>;
132 fn format(&self) -> ExportFormat;
134 fn validate_config(&self, destination: &ExportDestination) -> QuantRS2Result<()>;
136}
137#[cfg(test)]
138mod tests {
139 use super::*;
140 #[test]
141 fn test_realtime_monitor_creation() {
142 let config = MonitoringConfig::default();
143 let monitor = RealtimeMonitor::new(config);
144 assert!(monitor.is_ok());
145 }
146 #[test]
147 fn test_metric_measurement() {
148 let measurement = MetricMeasurement {
149 metric_type: MetricType::GateErrorRate,
150 value: MetricValue::Float(0.001),
151 timestamp: SystemTime::now(),
152 qubit: Some(QubitId::new(0)),
153 gate_type: Some(NativeGateType::CNOT),
154 metadata: HashMap::new(),
155 uncertainty: Some(0.0001),
156 };
157 assert_eq!(measurement.metric_type, MetricType::GateErrorRate);
158 assert!(matches!(measurement.value, MetricValue::Float(0.001)));
159 }
160 #[test]
161 fn test_superconducting_collector() {
162 let config = PlatformMonitoringConfig {
163 platform: HardwarePlatform::Superconducting,
164 monitored_metrics: HashSet::new(),
165 sampling_rates: HashMap::new(),
166 custom_thresholds: HashMap::new(),
167 connection_settings: HashMap::new(),
168 };
169 let mut collector = SuperconductingCollector::new(config);
170 assert_eq!(collector.platform(), HardwarePlatform::Superconducting);
171 assert!(!collector.is_connected());
172 assert!(collector.initialize().is_ok());
173 assert!(collector.is_connected());
174 let metrics = collector.collect_metrics();
175 assert!(metrics.is_ok());
176 assert!(!metrics
177 .expect("Metrics collection should succeed")
178 .is_empty());
179 }
180 #[test]
181 fn test_data_store() {
182 let mut store = RealtimeDataStore::new(Duration::from_secs(3600));
183 let measurement = MetricMeasurement {
184 metric_type: MetricType::GateErrorRate,
185 value: MetricValue::Float(0.001),
186 timestamp: SystemTime::now(),
187 qubit: None,
188 gate_type: None,
189 metadata: HashMap::new(),
190 uncertainty: None,
191 };
192 store.add_measurement(measurement);
193 assert!(store.time_series.contains_key(&MetricType::GateErrorRate));
194 assert!(store
195 .aggregated_stats
196 .contains_key(&MetricType::GateErrorRate));
197 let stats = store
198 .aggregated_stats
199 .get(&MetricType::GateErrorRate)
200 .expect("GateErrorRate stats should exist after adding measurement");
201 assert_eq!(stats.sample_count, 1);
202 assert_eq!(stats.mean, 0.001);
203 }
204 #[test]
205 fn test_alert_creation() {
206 let alert = Alert {
207 id: "test_alert".to_string(),
208 level: AlertLevel::Warning,
209 message: "Test alert message".to_string(),
210 affected_metrics: vec![MetricType::GateErrorRate],
211 timestamp: SystemTime::now(),
212 source: "test".to_string(),
213 suggested_actions: vec!["Check calibration".to_string()],
214 status: AlertStatus::Active,
215 };
216 assert_eq!(alert.level, AlertLevel::Warning);
217 assert_eq!(alert.status, AlertStatus::Active);
218 assert!(alert.affected_metrics.contains(&MetricType::GateErrorRate));
219 }
220 #[test]
221 fn test_monitoring_config() {
222 let config = MonitoringConfig::default();
223 assert_eq!(config.monitoring_interval, Duration::from_secs(1));
224 assert_eq!(config.data_retention_period, Duration::from_secs(24 * 3600));
225 assert!(!config.export_settings.enable_export);
226 }
227 #[test]
228 fn test_metric_value_types() {
229 let float_value = MetricValue::Float(1.23);
230 let int_value = MetricValue::Integer(42);
231 let bool_value = MetricValue::Boolean(true);
232 let duration_value = MetricValue::Duration(Duration::from_millis(100));
233 assert!(matches!(float_value, MetricValue::Float(1.23)));
234 assert!(matches!(int_value, MetricValue::Integer(42)));
235 assert!(matches!(bool_value, MetricValue::Boolean(true)));
236 assert!(matches!(duration_value, MetricValue::Duration(_)));
237 }
238 #[test]
239 fn test_alert_thresholds() {
240 let thresholds = AlertThresholds::default();
241 assert_eq!(thresholds.max_gate_error_rate, 0.01);
242 assert_eq!(thresholds.max_readout_error_rate, 0.05);
243 assert_eq!(thresholds.min_coherence_time, Duration::from_micros(50));
244 }
245 #[test]
246 fn test_optimization_recommendation() {
247 let recommendation = OptimizationRecommendation {
248 id: "test_rec".to_string(),
249 recommendation_type: RecommendationType::GateOptimization,
250 description: "Optimize gate sequence".to_string(),
251 affected_components: vec!["qubit_0".to_string()],
252 expected_improvement: ExpectedImprovement {
253 fidelity_improvement: Some(0.001),
254 speed_improvement: Some(0.1),
255 error_rate_reduction: Some(0.0005),
256 resource_savings: None,
257 },
258 implementation_difficulty: DifficultyLevel::Medium,
259 priority: RecommendationPriority::High,
260 timestamp: SystemTime::now(),
261 };
262 assert_eq!(
263 recommendation.recommendation_type,
264 RecommendationType::GateOptimization
265 );
266 assert_eq!(
267 recommendation.implementation_difficulty,
268 DifficultyLevel::Medium
269 );
270 assert_eq!(recommendation.priority, RecommendationPriority::High);
271 }
272 #[test]
273 fn test_export_settings() {
274 let settings = ExportSettings {
275 enable_export: true,
276 export_formats: vec![ExportFormat::JSON, ExportFormat::CSV],
277 export_destinations: vec![],
278 export_frequency: Duration::from_secs(1800),
279 compression_enabled: true,
280 };
281 assert!(settings.enable_export);
282 assert_eq!(settings.export_formats.len(), 2);
283 assert!(settings.compression_enabled);
284 }
285 #[test]
286 fn test_monitoring_status() {
287 let status = MonitoringStatus::new();
288 assert_eq!(status.overall_status, SystemStatus::Offline);
289 assert_eq!(status.active_collectors, 0);
290 assert_eq!(status.total_data_points, 0);
291 }
292}