anomaly_detection_demo/
anomaly_detection_demo.rs1#![allow(
2 clippy::pedantic,
3 clippy::unnecessary_wraps,
4 clippy::needless_range_loop,
5 clippy::useless_vec,
6 clippy::needless_collect,
7 clippy::too_many_arguments
8)]
9use quantrs2_ml::prelude::*;
15use scirs2_core::ndarray::{Array1, Array2};
16use scirs2_core::random::prelude::*;
17
18fn main() -> quantrs2_ml::Result<()> {
19 println!("Quantum Anomaly Detection Demo");
20 println!("===============================");
21
22 let config = QuantumAnomalyConfig::default();
24 println!("Created default anomaly detection configuration");
25 println!("Primary method: {:?}", config.primary_method);
26
27 let mut detector = QuantumAnomalyDetector::new(config)?;
29 println!("Created quantum anomaly detector");
30
31 let n_samples = 1000;
33 let n_features = 8;
34 let mut normal_data = Array2::zeros((n_samples, n_features));
35
36 for i in 0..n_samples {
37 for j in 0..n_features {
38 normal_data[[i, j]] = thread_rng().random::<f64>().mul_add(2.0, -1.0);
39 }
41 }
42
43 println!("Generated {n_samples} normal samples with {n_features} features");
44
45 println!("Training anomaly detector...");
47 detector.fit(&normal_data)?;
48
49 if let Some(stats) = detector.get_training_stats() {
50 println!("Training completed in {:.3} seconds", stats.training_time);
51 println!("Training samples: {}", stats.n_training_samples);
52 }
53
54 let n_test = 100;
56 let mut test_data = Array2::zeros((n_test, n_features));
57
58 for i in 0..80 {
60 for j in 0..n_features {
61 test_data[[i, j]] = thread_rng().random::<f64>().mul_add(2.0, -1.0);
62 }
63 }
64
65 for i in 80..n_test {
67 for j in 0..n_features {
68 test_data[[i, j]] = thread_rng().random::<f64>().mul_add(6.0, 5.0); }
70 }
71
72 println!("Generated {n_test} test samples (80 normal, 20 anomalous)");
73
74 println!("Detecting anomalies...");
76 let result = detector.detect(&test_data)?;
77
78 println!("\nDetection Results:");
80 println!("==================");
81 println!(
82 "Anomaly scores range: [{:.3}, {:.3}]",
83 result.anomaly_scores.fold(f64::INFINITY, |a, &b| a.min(b)),
84 result
85 .anomaly_scores
86 .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
87 );
88
89 let anomaly_count = result.anomaly_labels.iter().sum::<i32>();
90 println!("Detected {anomaly_count} anomalies out of {n_test} samples");
91
92 println!("\nPerformance Metrics:");
94 println!("====================");
95 println!("AUC-ROC: {:.3}", result.metrics.auc_roc);
96 println!("Precision: {:.3}", result.metrics.precision);
97 println!("Recall: {:.3}", result.metrics.recall);
98 println!("F1-Score: {:.3}", result.metrics.f1_score);
99
100 println!("\nQuantum Metrics:");
102 println!("================");
103 println!(
104 "Quantum Advantage: {:.3}x",
105 result.metrics.quantum_metrics.quantum_advantage
106 );
107 println!(
108 "Entanglement Utilization: {:.1}%",
109 result.metrics.quantum_metrics.entanglement_utilization * 100.0
110 );
111 println!(
112 "Circuit Efficiency: {:.1}%",
113 result.metrics.quantum_metrics.circuit_efficiency * 100.0
114 );
115
116 println!("\nProcessing Statistics:");
118 println!("======================");
119 println!(
120 "Total time: {:.3} seconds",
121 result.processing_stats.total_time
122 );
123 println!(
124 "Quantum time: {:.3} seconds",
125 result.processing_stats.quantum_time
126 );
127 println!(
128 "Classical time: {:.3} seconds",
129 result.processing_stats.classical_time
130 );
131 println!(
132 "Memory usage: {:.1} MB",
133 result.processing_stats.memory_usage
134 );
135 println!(
136 "Quantum executions: {}",
137 result.processing_stats.quantum_executions
138 );
139
140 println!("\n{}", "=".repeat(50));
142 println!("Testing Different Configurations");
143 println!("{}", "=".repeat(50));
144
145 let network_config = QuantumAnomalyConfig::default();
147 let mut network_detector = QuantumAnomalyDetector::new(network_config)?;
148 network_detector.fit(&normal_data)?;
149 let network_result = network_detector.detect(&test_data)?;
150
151 println!("\nNetwork Security Detection:");
152 println!("AUC-ROC: {:.3}", network_result.metrics.auc_roc);
153 println!(
154 "Detected anomalies: {}",
155 network_result.anomaly_labels.iter().sum::<i32>()
156 );
157
158 let fraud_config = QuantumAnomalyConfig::default();
160 let mut fraud_detector = QuantumAnomalyDetector::new(fraud_config)?;
161 fraud_detector.fit(&normal_data)?;
162 let fraud_result = fraud_detector.detect(&test_data)?;
163
164 println!("\nFinancial Fraud Detection:");
165 println!("AUC-ROC: {:.3}", fraud_result.metrics.auc_roc);
166 println!(
167 "Detected anomalies: {}",
168 fraud_result.anomaly_labels.iter().sum::<i32>()
169 );
170
171 println!("\n{}", "=".repeat(50));
173 println!("Testing Streaming Detection");
174 println!("{}", "=".repeat(50));
175
176 let iot_config = QuantumAnomalyConfig::default();
177 let mut streaming_detector = QuantumAnomalyDetector::new(iot_config)?;
178 streaming_detector.fit(&normal_data)?;
179
180 println!("Testing real-time streaming detection...");
181 for i in 0..10 {
182 let sample = test_data.row(i).to_owned();
183 let sample_2d = sample.clone().insert_axis(scirs2_core::ndarray::Axis(0));
184 let result = streaming_detector.detect(&sample_2d)?;
185 let anomaly_score = result.anomaly_scores[0];
186 let is_anomaly = if anomaly_score > 0.5 {
187 "ANOMALY"
188 } else {
189 "normal"
190 };
191 println!(
192 "Sample {}: score = {:.3} -> {}",
193 i + 1,
194 anomaly_score,
195 is_anomaly
196 );
197 }
198
199 println!("\nQuantum Anomaly Detection Demo completed successfully!");
200
201 Ok(())
202}