pub struct AnomalyGridConfig {
pub max_order: usize,
pub smoothing_alpha: f64,
pub memory_limit: Option<usize>,
pub min_probability: f64,
pub likelihood_weight: f64,
pub information_weight: f64,
pub normalization_factor: f64,
pub min_sequence_length: usize,
}Expand description
Configuration parameters for Anomaly Grid components
Fields§
§max_order: usizeMaximum context order for Markov model
smoothing_alpha: f64Laplace smoothing parameter (alpha)
memory_limit: Option<usize>Maximum number of contexts to store (None = unlimited)
min_probability: f64Minimum probability for numerical stability
likelihood_weight: f64Weight for likelihood component in anomaly strength calculation
information_weight: f64Weight for information component in anomaly strength calculation
normalization_factor: f64Normalization factor for tanh scaling in anomaly strength
min_sequence_length: usizeMinimum sequence length for training
Implementations§
Source§impl AnomalyGridConfig
impl AnomalyGridConfig
Sourcepub fn for_small_alphabet() -> Self
pub fn for_small_alphabet() -> Self
Create a configuration optimized for small alphabets (≤ 10 states)
Sourcepub fn for_large_alphabet() -> Self
pub fn for_large_alphabet() -> Self
Create a configuration optimized for large alphabets (> 20 states)
Sourcepub fn for_low_memory() -> Self
pub fn for_low_memory() -> Self
Create a configuration optimized for memory-constrained environments
Sourcepub fn for_high_accuracy() -> Self
pub fn for_high_accuracy() -> Self
Create a configuration optimized for high accuracy
Sourcepub fn validate(&self) -> AnomalyGridResult<()>
pub fn validate(&self) -> AnomalyGridResult<()>
Validate the configuration parameters
Sourcepub fn with_max_order(self, max_order: usize) -> AnomalyGridResult<Self>
pub fn with_max_order(self, max_order: usize) -> AnomalyGridResult<Self>
Set max_order with validation
Examples found in repository?
11fn main() -> Result<(), Box<dyn std::error::Error>> {
12 println!("🛡️ Network Security Monitoring with Anomaly Grid");
13 println!("Detecting APTs, DDoS, and network intrusions\n");
14
15 // Simulate 30 days of normal enterprise network traffic
16 let normal_traffic = generate_enterprise_traffic(30);
17 println!(
18 "Generated {} normal network events (30 days)",
19 normal_traffic.len()
20 );
21
22 // Initialize anomaly detection system
23 let mut detector = AnomalyDetector::new(4)?; // Order 4 for complex patterns
24
25 // Train on normal network traffic patterns
26 let train_start = Instant::now();
27 detector.train(&normal_traffic)?;
28 println!("Training completed in {:?}", train_start.elapsed());
29
30 // Real-time monitoring simulation
31 println!("\n🔍 Starting real-time network monitoring...");
32
33 // Test various attack scenarios
34 let attack_scenarios = vec![
35 ("Advanced Persistent Threat", generate_apt_campaign()),
36 ("DDoS Attack", generate_ddos_attack()),
37 ("Port Scan", generate_port_scan()),
38 ("SQL Injection", generate_sql_injection()),
39 ("Lateral Movement", generate_lateral_movement()),
40 ];
41
42 for (attack_name, attack_sequence) in attack_scenarios {
43 println!("\nTesting: {attack_name}");
44
45 let detect_start = Instant::now();
46 let anomalies = detector.detect_anomalies(&attack_sequence, 0.001)?;
47 let detect_time = detect_start.elapsed();
48
49 if !anomalies.is_empty() {
50 let max_strength = anomalies
51 .iter()
52 .map(|a| a.anomaly_strength)
53 .fold(0.0, f64::max);
54
55 let min_likelihood = anomalies
56 .iter()
57 .map(|a| a.likelihood)
58 .fold(f64::INFINITY, f64::min);
59
60 println!(" ✅ THREAT DETECTED");
61 println!(" 📊 Anomalies found: {}", anomalies.len());
62 println!(" Max anomaly strength: {max_strength:.3}");
63 println!(" Min likelihood: {min_likelihood:.2e}");
64 println!(" Detection time: {detect_time:?}");
65
66 // Alert classification
67 let threat_level = if max_strength > 0.9 {
68 "CRITICAL"
69 } else if max_strength > 0.7 {
70 "HIGH"
71 } else if max_strength > 0.5 {
72 "MEDIUM"
73 } else {
74 "LOW"
75 };
76
77 println!(" Threat Level: {threat_level}");
78 } else {
79 println!(" ❌ No anomalies detected");
80 }
81 }
82
83 // Batch processing demonstration
84 println!("\n📦 Batch Processing Demonstration");
85 let batch_sequences = vec![
86 generate_normal_session(),
87 generate_malware_communication(),
88 generate_data_exfiltration(),
89 ];
90
91 let batch_start = Instant::now();
92 let config = AnomalyGridConfig::default().with_max_order(5)?;
93 let batch_results = batch_process_sequences(&batch_sequences, &config, 0.01)?;
94 let batch_time = batch_start.elapsed();
95
96 println!(
97 "Processed {} sequences in {:?}",
98 batch_sequences.len(),
99 batch_time
100 );
101 for (i, results) in batch_results.iter().enumerate() {
102 println!(" Sequence {}: {} anomalies detected", i + 1, results.len());
103 }
104
105 Ok(())
106}More examples
10fn main() -> Result<(), Box<dyn std::error::Error>> {
11 println!("🏭 Industrial IoT Monitoring with Anomaly Grid");
12 println!("Predictive maintenance and equipment failure detection\n");
13
14 // Simulate 1 year of normal industrial operations
15 let normal_operations = generate_industrial_data(365); // 1 year
16 println!(
17 "Generated {} sensor readings (1 year)",
18 normal_operations.len()
19 );
20
21 // Initialize anomaly detection for IoT sensor data
22 let mut detector = AnomalyDetector::new(4)?; // Order 4 for sensor patterns
23
24 // Train on normal operational data
25 detector.train(&normal_operations)?;
26
27 // Equipment monitoring scenarios
28 println!("\n🔧 Equipment Health Monitoring");
29
30 let equipment_scenarios = vec![
31 ("Bearing Wear", generate_bearing_wear_pattern()),
32 ("Vibration Anomaly", generate_vibration_anomaly()),
33 ("Temperature Drift", generate_temperature_drift()),
34 ("Pressure Fluctuation", generate_pressure_fluctuation()),
35 ("Lubrication Failure", generate_lubrication_failure()),
36 ("Motor Imbalance", generate_motor_imbalance()),
37 ("Seal Degradation", generate_seal_degradation()),
38 ];
39
40 let mut maintenance_alerts = 0;
41 let mut critical_failures_prevented = 0;
42
43 for (equipment_issue, sensor_sequence) in equipment_scenarios {
44 println!("\nMonitoring: {equipment_issue}");
45
46 let detect_start = Instant::now();
47 let anomalies = detector.detect_anomalies(&sensor_sequence, 0.005)?; // Sensitive for safety
48 let detect_time = detect_start.elapsed();
49
50 if !anomalies.is_empty() {
51 maintenance_alerts += 1;
52
53 let severity = calculate_severity(&anomalies);
54 let time_to_failure = estimate_time_to_failure(&sensor_sequence);
55 let maintenance_cost = estimate_maintenance_cost(equipment_issue);
56
57 println!(" ⚠️ MAINTENANCE ALERT");
58 println!(" 📊 Anomalies detected: {}", anomalies.len());
59 println!(" Severity: {severity}");
60 println!(" Time to failure: {time_to_failure} hours");
61 println!(" Estimated maintenance cost: ${maintenance_cost:.0}");
62 println!(" Detection time: {detect_time:?}");
63
64 if severity == "CRITICAL" {
65 critical_failures_prevented += 1;
66 println!(" 🚨 IMMEDIATE SHUTDOWN RECOMMENDED");
67 }
68
69 generate_maintenance_recommendation(equipment_issue, &severity, time_to_failure);
70 } else {
71 println!(" ✅ Equipment operating normally");
72 }
73 }
74
75 // Production line monitoring
76 println!("\n🏭 Production Line Monitoring");
77 let production_data = generate_production_line_data();
78
79 let line_start = Instant::now();
80 let line_anomalies = detector.detect_anomalies(&production_data, 0.01)?;
81 let line_time = line_start.elapsed();
82
83 if !line_anomalies.is_empty() {
84 let efficiency_impact = calculate_efficiency_impact(&line_anomalies);
85 println!("Production anomalies detected: {}", line_anomalies.len());
86 println!("Efficiency impact: {efficiency_impact:.1}%");
87 println!("Detection time: {line_time:?}");
88 } else {
89 println!("Production line operating normally");
90 }
91
92 // Energy consumption monitoring
93 println!("\n⚡ Energy Consumption Monitoring");
94 let energy_data = generate_energy_consumption_data();
95
96 let energy_start = Instant::now();
97 let energy_anomalies = detector.detect_anomalies(&energy_data, 0.02)?;
98 let energy_time = energy_start.elapsed();
99
100 if !energy_anomalies.is_empty() {
101 let energy_waste = calculate_energy_waste(&energy_anomalies);
102 println!("Energy anomalies detected: {}", energy_anomalies.len());
103 println!("Estimated energy waste: {energy_waste:.0} kWh");
104 println!("Cost impact: ${:.2}", energy_waste * 0.12); // $0.12/kWh
105 println!("Detection time: {energy_time:?}");
106 } else {
107 println!("Energy consumption within normal parameters");
108 }
109
110 // Batch processing for multiple machines
111 println!("\n📦 Multi-Machine Batch Processing");
112 let machine_data = vec![
113 generate_machine_data("CNC_001"),
114 generate_machine_data("PRESS_002"),
115 generate_machine_data("ROBOT_003"),
116 generate_machine_data("CONVEYOR_004"),
117 generate_machine_data("WELDER_005"),
118 ];
119
120 let batch_start = Instant::now();
121 let config = AnomalyGridConfig::default().with_max_order(6)?;
122 let batch_results = batch_process_sequences(&machine_data, &config, 0.01)?;
123 let batch_time = batch_start.elapsed();
124
125 println!(
126 "Processed {} machines in {:?}",
127 machine_data.len(),
128 batch_time
129 );
130 for (i, results) in batch_results.iter().enumerate() {
131 let machine_names = [
132 "CNC_001",
133 "PRESS_002",
134 "ROBOT_003",
135 "CONVEYOR_004",
136 "WELDER_005",
137 ];
138 println!(
139 " {}: {} anomalies detected",
140 machine_names[i],
141 results.len()
142 );
143 }
144
145 // Summary and ROI calculation
146 println!("\n📊 Predictive Maintenance Summary");
147 println!("Maintenance alerts generated: {maintenance_alerts}");
148 println!("Critical failures prevented: {critical_failures_prevented}");
149
150 let downtime_prevented = critical_failures_prevented * 8; // 8 hours per failure
151 let cost_savings = downtime_prevented as f64 * 5000.0; // $5000/hour downtime cost
152 let maintenance_costs = maintenance_alerts as f64 * 2000.0; // $2000 per maintenance
153 let net_savings = cost_savings - maintenance_costs;
154
155 println!("Downtime prevented: {downtime_prevented} hours");
156 println!("Cost savings: ${cost_savings:.0}");
157 println!("Maintenance costs: ${maintenance_costs:.0}");
158 println!("Net savings: ${net_savings:.0}");
159 println!("ROI: {:.1}%", (net_savings / maintenance_costs) * 100.0);
160
161 Ok(())
162}Sourcepub fn with_smoothing_alpha(self, alpha: f64) -> AnomalyGridResult<Self>
pub fn with_smoothing_alpha(self, alpha: f64) -> AnomalyGridResult<Self>
Set smoothing_alpha with validation
Sourcepub fn with_memory_limit(self, limit: Option<usize>) -> AnomalyGridResult<Self>
pub fn with_memory_limit(self, limit: Option<usize>) -> AnomalyGridResult<Self>
Set memory_limit with validation
Sourcepub fn with_weights(
self,
likelihood_weight: f64,
information_weight: f64,
) -> AnomalyGridResult<Self>
pub fn with_weights( self, likelihood_weight: f64, information_weight: f64, ) -> AnomalyGridResult<Self>
Set anomaly strength weights with validation
Sourcepub fn estimate_memory_usage(&self, alphabet_size: usize) -> usize
pub fn estimate_memory_usage(&self, alphabet_size: usize) -> usize
Get estimated memory usage for given alphabet size
Sourcepub fn is_suitable_for_alphabet(&self, alphabet_size: usize) -> bool
pub fn is_suitable_for_alphabet(&self, alphabet_size: usize) -> bool
Check if configuration is suitable for given alphabet size
Trait Implementations§
Source§impl Clone for AnomalyGridConfig
impl Clone for AnomalyGridConfig
Source§fn clone(&self) -> AnomalyGridConfig
fn clone(&self) -> AnomalyGridConfig
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for AnomalyGridConfig
impl Debug for AnomalyGridConfig
Source§impl Default for AnomalyGridConfig
impl Default for AnomalyGridConfig
Source§impl PartialEq for AnomalyGridConfig
impl PartialEq for AnomalyGridConfig
impl StructuralPartialEq for AnomalyGridConfig
Auto Trait Implementations§
impl Freeze for AnomalyGridConfig
impl RefUnwindSafe for AnomalyGridConfig
impl Send for AnomalyGridConfig
impl Sync for AnomalyGridConfig
impl Unpin for AnomalyGridConfig
impl UnwindSafe for AnomalyGridConfig
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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>
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>
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 more