Skip to main content

anomaly_detection_demo/
anomaly_detection_demo.rs

1#![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)]
9//! Quantum Anomaly Detection Example
10//!
11//! This example demonstrates how to use the quantum anomaly detection module
12//! for various types of anomaly detection tasks.
13
14use 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    // Create default configuration
23    let config = QuantumAnomalyConfig::default();
24    println!("Created default anomaly detection configuration");
25    println!("Primary method: {:?}", config.primary_method);
26
27    // Create quantum anomaly detector
28    let mut detector = QuantumAnomalyDetector::new(config)?;
29    println!("Created quantum anomaly detector");
30
31    // Generate synthetic normal data (multivariate normal distribution)
32    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            // Normal range [-1, 1]
40        }
41    }
42
43    println!("Generated {n_samples} normal samples with {n_features} features");
44
45    // Train the detector on normal data
46    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    // Generate test data with some anomalies
55    let n_test = 100;
56    let mut test_data = Array2::zeros((n_test, n_features));
57
58    // Normal samples (first 80)
59    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    // Anomalous samples (last 20) - outliers with larger values
66    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); // Anomalous range [5, 11]
69        }
70    }
71
72    println!("Generated {n_test} test samples (80 normal, 20 anomalous)");
73
74    // Detect anomalies
75    println!("Detecting anomalies...");
76    let result = detector.detect(&test_data)?;
77
78    // Display results
79    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    // Performance metrics
93    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    // Quantum-specific metrics
101    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    // Processing statistics
117    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    // Test different configurations
141    println!("\n{}", "=".repeat(50));
142    println!("Testing Different Configurations");
143    println!("{}", "=".repeat(50));
144
145    // Network security configuration
146    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    // Financial fraud configuration
159    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    // Test streaming detection
172    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}