pub struct QuantumAnomalyDetector { /* private fields */ }Expand description
Main quantum anomaly detector
Implementations§
Source§impl QuantumAnomalyDetector
impl QuantumAnomalyDetector
Sourcepub fn new(config: QuantumAnomalyConfig) -> Result<Self>
pub fn new(config: QuantumAnomalyConfig) -> Result<Self>
Create a new quantum anomaly detector
Examples found in repository?
examples/anomaly_detection_demo.rs (line 28)
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}Sourcepub fn fit(&mut self, data: &Array2<f64>) -> Result<()>
pub fn fit(&mut self, data: &Array2<f64>) -> Result<()>
Train the anomaly detector
Examples found in repository?
examples/anomaly_detection_demo.rs (line 47)
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}Sourcepub fn detect(&self, data: &Array2<f64>) -> Result<AnomalyResult>
pub fn detect(&self, data: &Array2<f64>) -> Result<AnomalyResult>
Detect anomalies in new data
Examples found in repository?
examples/anomaly_detection_demo.rs (line 76)
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}Sourcepub fn update(
&mut self,
data: &Array2<f64>,
labels: Option<&Array1<i32>>,
) -> Result<()>
pub fn update( &mut self, data: &Array2<f64>, labels: Option<&Array1<i32>>, ) -> Result<()>
Update detector with new data (online learning)
Sourcepub fn get_config(&self) -> &QuantumAnomalyConfig
pub fn get_config(&self) -> &QuantumAnomalyConfig
Get detector configuration
Sourcepub fn get_training_stats(&self) -> Option<&TrainingStats>
pub fn get_training_stats(&self) -> Option<&TrainingStats>
Get training statistics
Examples found in repository?
examples/anomaly_detection_demo.rs (line 49)
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}Auto Trait Implementations§
impl Freeze for QuantumAnomalyDetector
impl !RefUnwindSafe for QuantumAnomalyDetector
impl !Send for QuantumAnomalyDetector
impl !Sync for QuantumAnomalyDetector
impl Unpin for QuantumAnomalyDetector
impl UnsafeUnpin for QuantumAnomalyDetector
impl !UnwindSafe for QuantumAnomalyDetector
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
Converts
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
impl<SS, SP> SupersetOf<SS> for SPwhere
SS: SubsetOf<SP>,
Source§fn to_subset(&self) -> Option<SS>
fn to_subset(&self) -> Option<SS>
The inverse inclusion map: attempts to construct
self from the equivalent element of its
superset. Read moreSource§fn is_in_subset(&self) -> bool
fn is_in_subset(&self) -> bool
Checks if
self is actually part of its subset T (and can be converted to it).Source§fn to_subset_unchecked(&self) -> SS
fn to_subset_unchecked(&self) -> SS
Use with care! Same as
self.to_subset but without any property checks. Always succeeds.Source§fn from_subset(element: &SS) -> SP
fn from_subset(element: &SS) -> SP
The inclusion map: converts
self to the equivalent element of its superset.