AnomalyGridConfig

Struct AnomalyGridConfig 

Source
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: usize

Maximum context order for Markov model

§smoothing_alpha: f64

Laplace smoothing parameter (alpha)

§memory_limit: Option<usize>

Maximum number of contexts to store (None = unlimited)

§min_probability: f64

Minimum probability for numerical stability

§likelihood_weight: f64

Weight for likelihood component in anomaly strength calculation

§information_weight: f64

Weight for information component in anomaly strength calculation

§normalization_factor: f64

Normalization factor for tanh scaling in anomaly strength

§min_sequence_length: usize

Minimum sequence length for training

Implementations§

Source§

impl AnomalyGridConfig

Source

pub fn new() -> Self

Create a new configuration with default values

Source

pub fn for_small_alphabet() -> Self

Create a configuration optimized for small alphabets (≤ 10 states)

Source

pub fn for_large_alphabet() -> Self

Create a configuration optimized for large alphabets (> 20 states)

Source

pub fn for_low_memory() -> Self

Create a configuration optimized for memory-constrained environments

Source

pub fn for_high_accuracy() -> Self

Create a configuration optimized for high accuracy

Source

pub fn validate(&self) -> AnomalyGridResult<()>

Validate the configuration parameters

Source

pub fn with_max_order(self, max_order: usize) -> AnomalyGridResult<Self>

Set max_order with validation

Examples found in repository?
examples/network_security_monitoring.rs (line 92)
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
Hide additional examples
examples/industrial_iot_monitoring.rs (line 122)
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}
Source

pub fn with_smoothing_alpha(self, alpha: f64) -> AnomalyGridResult<Self>

Set smoothing_alpha with validation

Source

pub fn with_memory_limit(self, limit: Option<usize>) -> AnomalyGridResult<Self>

Set memory_limit with validation

Source

pub fn with_weights( self, likelihood_weight: f64, information_weight: f64, ) -> AnomalyGridResult<Self>

Set anomaly strength weights with validation

Source

pub fn estimate_memory_usage(&self, alphabet_size: usize) -> usize

Get estimated memory usage for given alphabet size

Source

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

Source§

fn clone(&self) -> AnomalyGridConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AnomalyGridConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for AnomalyGridConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl PartialEq for AnomalyGridConfig

Source§

fn eq(&self, other: &AnomalyGridConfig) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for AnomalyGridConfig

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

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 more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.