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 20)
10fn main() -> quantrs2_ml::Result<()> {
11 println!("Quantum Anomaly Detection Demo");
12 println!("===============================");
13
14 // Create default configuration
15 let config = QuantumAnomalyConfig::default();
16 println!("Created default anomaly detection configuration");
17 println!("Primary method: {:?}", config.primary_method);
18
19 // Create quantum anomaly detector
20 let mut detector = QuantumAnomalyDetector::new(config)?;
21 println!("Created quantum anomaly detector");
22
23 // Generate synthetic normal data (multivariate normal distribution)
24 let n_samples = 1000;
25 let n_features = 8;
26 let mut normal_data = Array2::zeros((n_samples, n_features));
27
28 for i in 0..n_samples {
29 for j in 0..n_features {
30 normal_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0; // Normal range [-1, 1]
31 }
32 }
33
34 println!(
35 "Generated {} normal samples with {} features",
36 n_samples, n_features
37 );
38
39 // Train the detector on normal data
40 println!("Training anomaly detector...");
41 detector.fit(&normal_data)?;
42
43 if let Some(stats) = detector.get_training_stats() {
44 println!("Training completed in {:.3} seconds", stats.training_time);
45 println!("Training samples: {}", stats.n_training_samples);
46 }
47
48 // Generate test data with some anomalies
49 let n_test = 100;
50 let mut test_data = Array2::zeros((n_test, n_features));
51
52 // Normal samples (first 80)
53 for i in 0..80 {
54 for j in 0..n_features {
55 test_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0;
56 }
57 }
58
59 // Anomalous samples (last 20) - outliers with larger values
60 for i in 80..n_test {
61 for j in 0..n_features {
62 test_data[[i, j]] = thread_rng().gen::<f64>() * 6.0 + 5.0; // Anomalous range [5, 11]
63 }
64 }
65
66 println!(
67 "Generated {} test samples (80 normal, 20 anomalous)",
68 n_test
69 );
70
71 // Detect anomalies
72 println!("Detecting anomalies...");
73 let result = detector.detect(&test_data)?;
74
75 // Display results
76 println!("\nDetection Results:");
77 println!("==================");
78 println!(
79 "Anomaly scores range: [{:.3}, {:.3}]",
80 result.anomaly_scores.fold(f64::INFINITY, |a, &b| a.min(b)),
81 result
82 .anomaly_scores
83 .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
84 );
85
86 let anomaly_count = result.anomaly_labels.iter().sum::<i32>();
87 println!(
88 "Detected {} anomalies out of {} samples",
89 anomaly_count, n_test
90 );
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 41)
10fn main() -> quantrs2_ml::Result<()> {
11 println!("Quantum Anomaly Detection Demo");
12 println!("===============================");
13
14 // Create default configuration
15 let config = QuantumAnomalyConfig::default();
16 println!("Created default anomaly detection configuration");
17 println!("Primary method: {:?}", config.primary_method);
18
19 // Create quantum anomaly detector
20 let mut detector = QuantumAnomalyDetector::new(config)?;
21 println!("Created quantum anomaly detector");
22
23 // Generate synthetic normal data (multivariate normal distribution)
24 let n_samples = 1000;
25 let n_features = 8;
26 let mut normal_data = Array2::zeros((n_samples, n_features));
27
28 for i in 0..n_samples {
29 for j in 0..n_features {
30 normal_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0; // Normal range [-1, 1]
31 }
32 }
33
34 println!(
35 "Generated {} normal samples with {} features",
36 n_samples, n_features
37 );
38
39 // Train the detector on normal data
40 println!("Training anomaly detector...");
41 detector.fit(&normal_data)?;
42
43 if let Some(stats) = detector.get_training_stats() {
44 println!("Training completed in {:.3} seconds", stats.training_time);
45 println!("Training samples: {}", stats.n_training_samples);
46 }
47
48 // Generate test data with some anomalies
49 let n_test = 100;
50 let mut test_data = Array2::zeros((n_test, n_features));
51
52 // Normal samples (first 80)
53 for i in 0..80 {
54 for j in 0..n_features {
55 test_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0;
56 }
57 }
58
59 // Anomalous samples (last 20) - outliers with larger values
60 for i in 80..n_test {
61 for j in 0..n_features {
62 test_data[[i, j]] = thread_rng().gen::<f64>() * 6.0 + 5.0; // Anomalous range [5, 11]
63 }
64 }
65
66 println!(
67 "Generated {} test samples (80 normal, 20 anomalous)",
68 n_test
69 );
70
71 // Detect anomalies
72 println!("Detecting anomalies...");
73 let result = detector.detect(&test_data)?;
74
75 // Display results
76 println!("\nDetection Results:");
77 println!("==================");
78 println!(
79 "Anomaly scores range: [{:.3}, {:.3}]",
80 result.anomaly_scores.fold(f64::INFINITY, |a, &b| a.min(b)),
81 result
82 .anomaly_scores
83 .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
84 );
85
86 let anomaly_count = result.anomaly_labels.iter().sum::<i32>();
87 println!(
88 "Detected {} anomalies out of {} samples",
89 anomaly_count, n_test
90 );
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 73)
10fn main() -> quantrs2_ml::Result<()> {
11 println!("Quantum Anomaly Detection Demo");
12 println!("===============================");
13
14 // Create default configuration
15 let config = QuantumAnomalyConfig::default();
16 println!("Created default anomaly detection configuration");
17 println!("Primary method: {:?}", config.primary_method);
18
19 // Create quantum anomaly detector
20 let mut detector = QuantumAnomalyDetector::new(config)?;
21 println!("Created quantum anomaly detector");
22
23 // Generate synthetic normal data (multivariate normal distribution)
24 let n_samples = 1000;
25 let n_features = 8;
26 let mut normal_data = Array2::zeros((n_samples, n_features));
27
28 for i in 0..n_samples {
29 for j in 0..n_features {
30 normal_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0; // Normal range [-1, 1]
31 }
32 }
33
34 println!(
35 "Generated {} normal samples with {} features",
36 n_samples, n_features
37 );
38
39 // Train the detector on normal data
40 println!("Training anomaly detector...");
41 detector.fit(&normal_data)?;
42
43 if let Some(stats) = detector.get_training_stats() {
44 println!("Training completed in {:.3} seconds", stats.training_time);
45 println!("Training samples: {}", stats.n_training_samples);
46 }
47
48 // Generate test data with some anomalies
49 let n_test = 100;
50 let mut test_data = Array2::zeros((n_test, n_features));
51
52 // Normal samples (first 80)
53 for i in 0..80 {
54 for j in 0..n_features {
55 test_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0;
56 }
57 }
58
59 // Anomalous samples (last 20) - outliers with larger values
60 for i in 80..n_test {
61 for j in 0..n_features {
62 test_data[[i, j]] = thread_rng().gen::<f64>() * 6.0 + 5.0; // Anomalous range [5, 11]
63 }
64 }
65
66 println!(
67 "Generated {} test samples (80 normal, 20 anomalous)",
68 n_test
69 );
70
71 // Detect anomalies
72 println!("Detecting anomalies...");
73 let result = detector.detect(&test_data)?;
74
75 // Display results
76 println!("\nDetection Results:");
77 println!("==================");
78 println!(
79 "Anomaly scores range: [{:.3}, {:.3}]",
80 result.anomaly_scores.fold(f64::INFINITY, |a, &b| a.min(b)),
81 result
82 .anomaly_scores
83 .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
84 );
85
86 let anomaly_count = result.anomaly_labels.iter().sum::<i32>();
87 println!(
88 "Detected {} anomalies out of {} samples",
89 anomaly_count, n_test
90 );
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 43)
10fn main() -> quantrs2_ml::Result<()> {
11 println!("Quantum Anomaly Detection Demo");
12 println!("===============================");
13
14 // Create default configuration
15 let config = QuantumAnomalyConfig::default();
16 println!("Created default anomaly detection configuration");
17 println!("Primary method: {:?}", config.primary_method);
18
19 // Create quantum anomaly detector
20 let mut detector = QuantumAnomalyDetector::new(config)?;
21 println!("Created quantum anomaly detector");
22
23 // Generate synthetic normal data (multivariate normal distribution)
24 let n_samples = 1000;
25 let n_features = 8;
26 let mut normal_data = Array2::zeros((n_samples, n_features));
27
28 for i in 0..n_samples {
29 for j in 0..n_features {
30 normal_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0; // Normal range [-1, 1]
31 }
32 }
33
34 println!(
35 "Generated {} normal samples with {} features",
36 n_samples, n_features
37 );
38
39 // Train the detector on normal data
40 println!("Training anomaly detector...");
41 detector.fit(&normal_data)?;
42
43 if let Some(stats) = detector.get_training_stats() {
44 println!("Training completed in {:.3} seconds", stats.training_time);
45 println!("Training samples: {}", stats.n_training_samples);
46 }
47
48 // Generate test data with some anomalies
49 let n_test = 100;
50 let mut test_data = Array2::zeros((n_test, n_features));
51
52 // Normal samples (first 80)
53 for i in 0..80 {
54 for j in 0..n_features {
55 test_data[[i, j]] = thread_rng().gen::<f64>() * 2.0 - 1.0;
56 }
57 }
58
59 // Anomalous samples (last 20) - outliers with larger values
60 for i in 80..n_test {
61 for j in 0..n_features {
62 test_data[[i, j]] = thread_rng().gen::<f64>() * 6.0 + 5.0; // Anomalous range [5, 11]
63 }
64 }
65
66 println!(
67 "Generated {} test samples (80 normal, 20 anomalous)",
68 n_test
69 );
70
71 // Detect anomalies
72 println!("Detecting anomalies...");
73 let result = detector.detect(&test_data)?;
74
75 // Display results
76 println!("\nDetection Results:");
77 println!("==================");
78 println!(
79 "Anomaly scores range: [{:.3}, {:.3}]",
80 result.anomaly_scores.fold(f64::INFINITY, |a, &b| a.min(b)),
81 result
82 .anomaly_scores
83 .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
84 );
85
86 let anomaly_count = result.anomaly_labels.iter().sum::<i32>();
87 println!(
88 "Detected {} anomalies out of {} samples",
89 anomaly_count, n_test
90 );
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 !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.