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 // Generate 5 days of normal network traffic (reduced for performance)
16 let normal_events = generate_enterprise_traffic(5);
17 println!(
18 "Generated {} normal network events (5 days)",
19 normal_events.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 patterns
26 let train_start = Instant::now();
27 detector.train(&normal_events)?;
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 // Generate 1 month of normal sensor data (reduced for performance)
15 let normal_readings = generate_industrial_data(30);
16 println!(
17 "Generated {} sensor readings (1 month)",
18 normal_readings.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 // Train on normal operational patterns
26 detector.train(&normal_readings)?;
27
28 // Equipment monitoring scenarios
29 println!("\n🔧 Equipment Health Monitoring");
30
31 let equipment_scenarios = vec![
32 ("Bearing Wear", generate_bearing_wear_pattern()),
33 ("Vibration Anomaly", generate_vibration_anomaly()),
34 ("Temperature Drift", generate_temperature_drift()),
35 ("Pressure Fluctuation", generate_pressure_fluctuation()),
36 ("Lubrication Failure", generate_lubrication_failure()),
37 ("Motor Imbalance", generate_motor_imbalance()),
38 ("Seal Degradation", generate_seal_degradation()),
39 ];
40
41 let mut maintenance_alerts = 0;
42 let mut critical_failures_prevented = 0;
43
44 for (equipment_issue, sensor_sequence) in equipment_scenarios {
45 println!("\nMonitoring: {equipment_issue}");
46
47 let detect_start = Instant::now();
48 let anomalies = detector.detect_anomalies(&sensor_sequence, 0.005)?; // Sensitive for safety
49 let detect_time = detect_start.elapsed();
50
51 if !anomalies.is_empty() {
52 maintenance_alerts += 1;
53
54 let severity = calculate_severity(&anomalies);
55 let time_to_failure = estimate_time_to_failure(&sensor_sequence);
56 let maintenance_cost = estimate_maintenance_cost(equipment_issue);
57
58 println!(" ⚠️ MAINTENANCE ALERT");
59 println!(" 📊 Anomalies detected: {}", anomalies.len());
60 println!(" Severity: {severity}");
61 println!(" Time to failure: {time_to_failure} hours");
62 println!(" Estimated maintenance cost: ${maintenance_cost:.0}");
63 println!(" Detection time: {detect_time:?}");
64
65 if severity == "CRITICAL" {
66 critical_failures_prevented += 1;
67 println!(" 🚨 IMMEDIATE SHUTDOWN RECOMMENDED");
68 }
69
70 generate_maintenance_recommendation(equipment_issue, &severity, time_to_failure);
71 } else {
72 println!(" ✅ Equipment operating normally");
73 }
74 }
75
76 // Production line monitoring
77 println!("\n🏭 Production Line Monitoring");
78 let production_data = generate_production_line_data();
79
80 let line_start = Instant::now();
81 let line_anomalies = detector.detect_anomalies(&production_data, 0.01)?;
82 let line_time = line_start.elapsed();
83
84 if !line_anomalies.is_empty() {
85 let efficiency_impact = calculate_efficiency_impact(&line_anomalies);
86 println!("Production anomalies detected: {}", line_anomalies.len());
87 println!("Efficiency impact: {efficiency_impact:.1}%");
88 println!("Detection time: {line_time:?}");
89 } else {
90 println!("Production line operating normally");
91 }
92
93 // Energy consumption monitoring
94 println!("\n⚡ Energy Consumption Monitoring");
95 let energy_data = generate_energy_consumption_data();
96
97 let energy_start = Instant::now();
98 let energy_anomalies = detector.detect_anomalies(&energy_data, 0.02)?;
99 let energy_time = energy_start.elapsed();
100
101 if !energy_anomalies.is_empty() {
102 let energy_waste = calculate_energy_waste(&energy_anomalies);
103 println!("Energy anomalies detected: {}", energy_anomalies.len());
104 println!("Estimated energy waste: {energy_waste:.0} kWh");
105 println!("Cost impact: ${:.2}", energy_waste * 0.12); // $0.12/kWh
106 println!("Detection time: {energy_time:?}");
107 } else {
108 println!("Energy consumption within normal parameters");
109 }
110
111 // Batch processing for multiple machines
112 println!("\n📦 Multi-Machine Batch Processing");
113 let machine_data = vec![
114 generate_machine_data("CNC_001"),
115 generate_machine_data("PRESS_002"),
116 generate_machine_data("ROBOT_003"),
117 generate_machine_data("CONVEYOR_004"),
118 generate_machine_data("WELDER_005"),
119 ];
120
121 let batch_start = Instant::now();
122 let config = AnomalyGridConfig::default().with_max_order(6)?;
123 let batch_results = batch_process_sequences(&machine_data, &config, 0.01)?;
124 let batch_time = batch_start.elapsed();
125
126 println!(
127 "Processed {} machines in {:?}",
128 machine_data.len(),
129 batch_time
130 );
131 for (i, results) in batch_results.iter().enumerate() {
132 let machine_names = [
133 "CNC_001",
134 "PRESS_002",
135 "ROBOT_003",
136 "CONVEYOR_004",
137 "WELDER_005",
138 ];
139 println!(
140 " {}: {} anomalies detected",
141 machine_names[i],
142 results.len()
143 );
144 }
145
146 // Summary and ROI calculation
147 println!("\n📊 Predictive Maintenance Summary");
148 println!("Maintenance alerts generated: {maintenance_alerts}");
149 println!("Critical failures prevented: {critical_failures_prevented}");
150
151 let downtime_prevented = critical_failures_prevented * 8; // 8 hours per failure
152 let cost_savings = downtime_prevented as f64 * 5000.0; // $5000/hour downtime cost
153 let maintenance_costs = maintenance_alerts as f64 * 2000.0; // $2000 per maintenance
154 let net_savings = cost_savings - maintenance_costs;
155
156 println!("Downtime prevented: {downtime_prevented} hours");
157 println!("Cost savings: ${cost_savings:.0}");
158 println!("Maintenance costs: ${maintenance_costs:.0}");
159 println!("Net savings: ${net_savings:.0}");
160 println!("ROI: {:.1}%", (net_savings / maintenance_costs) * 100.0);
161
162 Ok(())
163}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