scirs2_integrate/analysis/ml_prediction/
monitoring.rs

1//! Real-time Bifurcation Monitoring
2//!
3//! This module contains structures for real-time monitoring, alerting,
4//! and adaptive threshold systems for bifurcation detection.
5
6use crate::analysis::types::BifurcationType;
7use scirs2_core::ndarray::Array1;
8use std::collections::{HashMap, VecDeque};
9use std::sync::{Arc, Mutex};
10
11/// Real-time bifurcation monitoring system
12#[derive(Debug)]
13pub struct RealTimeBifurcationMonitor {
14    /// Streaming data buffer
15    pub data_buffer: Arc<Mutex<VecDeque<Array1<f64>>>>,
16    /// Prediction models
17    pub prediction_models: Vec<super::neural_network::BifurcationPredictionNetwork>,
18    /// Alert system configuration
19    pub alert_system: AlertSystemConfig,
20    /// Monitoring configuration
21    pub monitoring_config: MonitoringConfig,
22    /// Performance tracker
23    pub performance_tracker: PerformanceTracker,
24    /// Adaptive threshold system
25    pub adaptive_thresholds: AdaptiveThresholdSystem,
26}
27
28/// Alert system configuration
29#[derive(Debug, Clone, Default)]
30pub struct AlertSystemConfig {
31    /// Alert thresholds for different bifurcation types
32    pub alert_thresholds: HashMap<BifurcationType, f64>,
33    /// Alert escalation levels
34    pub escalation_levels: Vec<EscalationLevel>,
35    /// Notification methods
36    pub notification_methods: Vec<NotificationMethod>,
37    /// Alert suppression configuration
38    pub suppression_config: AlertSuppressionConfig,
39}
40
41/// Alert escalation levels
42#[derive(Debug, Clone)]
43pub struct EscalationLevel {
44    /// Level name
45    pub level_name: String,
46    /// Threshold for this level
47    pub threshold: f64,
48    /// Time delay before escalation
49    pub escalation_delay: std::time::Duration,
50    /// Actions to take at this level
51    pub actions: Vec<AlertAction>,
52}
53
54/// Alert actions
55#[derive(Debug, Clone)]
56pub enum AlertAction {
57    /// Log alert to file
58    LogToFile(String),
59    /// Send email notification
60    SendEmail(String),
61    /// Trigger system shutdown
62    SystemShutdown,
63    /// Execute custom script
64    ExecuteScript(String),
65    /// Update model parameters
66    UpdateModel,
67}
68
69/// Notification methods
70#[derive(Debug, Clone)]
71pub enum NotificationMethod {
72    /// Email notification
73    Email {
74        recipients: Vec<String>,
75        smtp_config: String,
76    },
77    /// SMS notification
78    SMS {
79        phone_numbers: Vec<String>,
80        service_config: String,
81    },
82    /// Webhook notification
83    Webhook {
84        url: String,
85        headers: HashMap<String, String>,
86    },
87    /// File logging
88    FileLog { log_path: String, format: LogFormat },
89}
90
91/// Log format options
92#[derive(Debug, Clone, Copy)]
93pub enum LogFormat {
94    JSON,
95    CSV,
96    PlainText,
97    XML,
98}
99
100/// Alert suppression configuration
101#[derive(Debug, Clone)]
102pub struct AlertSuppressionConfig {
103    /// Minimum time between alerts of same type
104    pub min_interval: std::time::Duration,
105    /// Maximum number of alerts per time window
106    pub max_alerts_per_window: usize,
107    /// Time window for alert counting
108    pub time_window: std::time::Duration,
109    /// Suppress alerts during maintenance
110    pub maintenance_mode: bool,
111}
112
113/// Real-time monitoring configuration
114#[derive(Debug, Clone)]
115pub struct MonitoringConfig {
116    /// Data sampling rate
117    pub sampling_rate: f64,
118    /// Buffer size for streaming data
119    pub buffer_size: usize,
120    /// Prediction update frequency
121    pub update_frequency: f64,
122    /// Model ensemble configuration
123    pub ensemble_config: MonitoringEnsembleConfig,
124    /// Data preprocessing pipeline
125    pub preprocessing: super::preprocessing::PreprocessingPipeline,
126}
127
128/// Ensemble configuration for monitoring
129#[derive(Debug, Clone)]
130pub struct MonitoringEnsembleConfig {
131    /// Use multiple models for robustness
132    pub use_ensemble: bool,
133    /// Voting strategy for ensemble
134    pub voting_strategy: VotingStrategy,
135    /// Confidence threshold for predictions
136    pub confidence_threshold: f64,
137    /// Agreement threshold among models
138    pub agreement_threshold: f64,
139}
140
141/// Voting strategies for ensemble
142#[derive(Debug, Clone, Copy)]
143pub enum VotingStrategy {
144    /// Majority voting
145    Majority,
146    /// Weighted voting by model performance
147    Weighted,
148    /// Confidence-based voting
149    ConfidenceBased,
150    /// Unanimous voting (all models agree)
151    Unanimous,
152}
153
154/// Performance tracking for monitoring system
155#[derive(Debug, Clone)]
156pub struct PerformanceTracker {
157    /// Latency metrics
158    pub latency_metrics: LatencyMetrics,
159    /// Accuracy metrics
160    pub accuracy_metrics: AccuracyMetrics,
161    /// Resource usage metrics
162    pub resource_metrics: ResourceMetrics,
163    /// Alert performance metrics
164    pub alert_metrics: AlertMetrics,
165}
166
167/// Latency metrics for real-time monitoring
168#[derive(Debug, Clone)]
169pub struct LatencyMetrics {
170    /// Average prediction latency
171    pub avg_prediction_latency: f64,
172    /// Maximum prediction latency
173    pub max_prediction_latency: f64,
174    /// 95th percentile latency
175    pub p95_latency: f64,
176    /// Data processing latency
177    pub processing_latency: f64,
178}
179
180/// Accuracy metrics for monitoring
181#[derive(Debug, Clone)]
182pub struct AccuracyMetrics {
183    /// True positive rate
184    pub true_positive_rate: f64,
185    /// False positive rate
186    pub false_positive_rate: f64,
187    /// Precision score
188    pub precision: f64,
189    /// Recall score
190    pub recall: f64,
191    /// F1 score
192    pub f1_score: f64,
193}
194
195/// Resource usage metrics
196#[derive(Debug, Clone)]
197pub struct ResourceMetrics {
198    /// CPU usage percentage
199    pub cpu_usage: f64,
200    /// Memory usage in bytes
201    pub memory_usage: usize,
202    /// Network bandwidth usage
203    pub network_usage: f64,
204    /// Disk I/O operations
205    pub disk_io: f64,
206}
207
208/// Alert performance metrics
209#[derive(Debug, Clone)]
210pub struct AlertMetrics {
211    /// Total number of alerts generated
212    pub total_alerts: usize,
213    /// Number of true alerts
214    pub true_alerts: usize,
215    /// Number of false alerts
216    pub false_alerts: usize,
217    /// Average alert response time
218    pub avg_response_time: f64,
219}
220
221/// Adaptive threshold system
222#[derive(Debug, Clone)]
223pub struct AdaptiveThresholdSystem {
224    /// Current threshold values
225    pub current_thresholds: HashMap<BifurcationType, f64>,
226    /// Threshold adaptation method
227    pub adaptation_method: ThresholdAdaptationMethod,
228    /// Feedback mechanism for threshold adjustment
229    pub feedback_mechanism: FeedbackMechanism,
230    /// Historical performance data
231    pub performance_history: Vec<f64>,
232}
233
234/// Methods for adapting thresholds
235#[derive(Debug, Clone, Copy)]
236pub enum ThresholdAdaptationMethod {
237    /// Fixed thresholds (no adaptation)
238    Fixed,
239    /// Statistical-based adaptation
240    Statistical,
241    /// Machine learning-based adaptation
242    MachineLearning,
243    /// Feedback-based adaptation
244    FeedbackBased,
245}
246
247/// Feedback mechanisms for threshold adjustment
248#[derive(Debug, Clone, Copy)]
249pub enum FeedbackMechanism {
250    /// Manual feedback from operators
251    Manual,
252    /// Automated feedback from validation
253    Automated,
254    /// Hybrid manual and automated
255    Hybrid,
256}
257
258impl Default for AlertSuppressionConfig {
259    fn default() -> Self {
260        Self {
261            min_interval: std::time::Duration::from_secs(60),
262            max_alerts_per_window: 10,
263            time_window: std::time::Duration::from_secs(3600),
264            maintenance_mode: false,
265        }
266    }
267}
268
269impl Default for AlertMetrics {
270    fn default() -> Self {
271        Self {
272            total_alerts: 0,
273            true_alerts: 0,
274            false_alerts: 0,
275            avg_response_time: 0.0,
276        }
277    }
278}
279
280impl Default for AdaptiveThresholdSystem {
281    fn default() -> Self {
282        Self {
283            current_thresholds: HashMap::new(),
284            adaptation_method: ThresholdAdaptationMethod::Statistical,
285            feedback_mechanism: FeedbackMechanism::Automated,
286            performance_history: Vec::new(),
287        }
288    }
289}