use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;
use scirs2_core::numeric::Float;
use std::fmt::Debug;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyticsConfig {
pub enable_performance_monitoring: bool,
pub enable_convergence_analysis: bool,
pub enable_resource_monitoring: bool,
pub enable_pattern_detection: bool,
pub enable_anomaly_detection: bool,
pub enable_trend_analysis: bool,
pub enable_dashboard: bool,
pub performance_config: PerformanceMonitoringConfig,
pub convergence_config: ConvergenceAnalysisConfig,
pub resource_config: ResourceMonitoringConfig,
pub pattern_config: PatternDetectionConfig,
pub anomaly_config: AnomalyDetectionConfig,
pub trend_config: TrendAnalysisConfig,
pub dashboard_config: DashboardConfig,
pub reporting_config: ReportingConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMonitoringConfig {
pub sampling_interval: Duration,
pub max_snapshots: usize,
pub enable_detailed_profiling: bool,
pub performance_thresholds: PerformanceThresholds<f64>,
pub benchmark_config: BenchmarkConfig,
pub model_config: ModelTrackingConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConvergenceAnalysisConfig {
pub detection_methods: Vec<ConvergenceDetectionMethod>,
pub detection_parameters: ConvergenceParameters<f64>,
pub analysis_window_size: usize,
pub min_steps_for_detection: usize,
pub enable_early_stopping: bool,
pub early_stopping_config: EarlyStoppingConfig<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceMonitoringConfig {
pub monitor_cpu: bool,
pub monitor_memory: bool,
pub monitor_gpu: bool,
pub monitor_disk: bool,
pub monitor_network: bool,
pub sampling_frequency: Duration,
pub history_size: usize,
pub resource_thresholds: ResourceThresholds,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternDetectionConfig {
pub enable_loss_patterns: bool,
pub enable_gradient_patterns: bool,
pub enable_performance_patterns: bool,
pub detection_sensitivity: f64,
pub min_pattern_length: usize,
pub max_pattern_length: usize,
pub pattern_tolerance: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyDetectionConfig {
pub detection_methods: Vec<AnomalyDetectionMethod>,
pub sensitivity: f64,
pub window_size: usize,
pub confidence_threshold: f64,
pub enable_real_time_alerts: bool,
pub alert_config: AnomalyAlertConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendAnalysisConfig {
pub forecasting_methods: Vec<ForecastingMethod>,
pub prediction_horizon: usize,
pub trend_window_size: usize,
pub enable_seasonal_decomposition: bool,
pub confidence_intervals: Vec<f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardConfig {
pub update_frequency: Duration,
pub max_display_points: usize,
pub enable_interactive: bool,
pub layout_config: DashboardLayoutConfig,
pub chart_configs: HashMap<String, ChartConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReportingConfig {
pub generation_frequency: Duration,
pub output_formats: Vec<ReportFormat>,
pub include_detailed_analysis: bool,
pub include_visualizations: bool,
pub retention_period: Duration,
pub notification_config: Option<NotificationConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceThresholds<T: Float + Debug + Send + Sync + 'static> {
pub max_loss: Option<T>,
pub min_accuracy: Option<T>,
pub max_training_time: Option<Duration>,
pub max_memory_usage: Option<f64>,
pub min_convergence_rate: Option<T>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkConfig {
pub enable_auto_benchmark: bool,
pub benchmark_frequency: Duration,
pub reference_datasets: Vec<String>,
pub tracked_metrics: Vec<String>,
pub baselines: HashMap<String, f64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelTrackingConfig {
pub track_predictions: bool,
pub track_parameters: bool,
pub track_gradients: bool,
pub enable_versioning: bool,
pub enable_comparison: bool,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ConvergenceDetectionMethod {
LossBased,
GradientNorm,
ParameterChange,
ValidationMetric,
StatisticalTest,
MLBased,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConvergenceParameters<T: Float + Debug + Send + Sync + 'static> {
pub loss_tolerance: T,
pub gradient_tolerance: T,
pub parameter_tolerance: T,
pub window_size: usize,
pub min_improvement: T,
pub patience: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EarlyStoppingConfig<T: Float + Debug + Send + Sync + 'static> {
pub enabled: bool,
pub monitor_metric: String,
pub min_delta: T,
pub patience: usize,
pub restore_best_weights: bool,
pub mode: EarlyStoppingMode,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum EarlyStoppingMode {
Min,
Max,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceThresholds {
pub cpu_threshold: f64,
pub memory_threshold: f64,
pub gpu_threshold: f64,
pub disk_threshold: f64,
pub network_threshold: f64,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum AnomalyDetectionMethod {
Statistical,
IsolationForest,
OneClassSVM,
Autoencoder,
TimeSeries,
Ensemble,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnomalyAlertConfig {
pub severity_levels: Vec<AlertSeverity>,
pub alert_channels: Vec<AlertChannel>,
pub frequency_limits: HashMap<AlertSeverity, Duration>,
pub suppression_rules: Vec<SuppressionRule>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum AlertSeverity {
Low,
Medium,
High,
Critical,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AlertChannel {
Email { recipients: Vec<String> },
Slack { webhook_url: String, channel: String },
Discord { webhook_url: String },
Sms { phone_numbers: Vec<String> },
SystemLog,
Dashboard,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionRule {
pub name: String,
pub conditions: Vec<SuppressionCondition>,
pub duration: Duration,
pub enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionCondition {
pub field: String,
pub operator: ComparisonOperator,
pub value: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ComparisonOperator {
Equal,
NotEqual,
GreaterThan,
LessThan,
GreaterOrEqual,
LessOrEqual,
Contains,
StartsWith,
EndsWith,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ForecastingMethod {
LinearRegression,
ExponentialSmoothing,
Arima,
Prophet,
NeuralNetwork,
Ensemble,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardLayoutConfig {
pub grid_layout: (usize, usize),
pub panels: Vec<PanelConfig>,
pub theme: DashboardTheme,
pub responsive: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PanelConfig {
pub id: String,
pub title: String,
pub panel_type: PanelType,
pub position: (usize, usize),
pub span: (usize, usize),
pub data_source: String,
pub refresh_interval: Duration,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PanelType {
LineChart,
BarChart,
ScatterPlot,
Heatmap,
Gauge,
Table,
Text,
Metric,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChartConfig {
pub chart_type: ChartType,
pub x_axis: AxisConfig,
pub y_axis: AxisConfig,
pub color_scheme: Vec<String>,
pub animation: AnimationConfig,
pub interactions: InteractionConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ChartType {
Line,
Bar,
Scatter,
Area,
Pie,
Donut,
Histogram,
BoxPlot,
Violin,
Candlestick,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxisConfig {
pub label: String,
pub scale: ScaleType,
pub min: Option<f64>,
pub max: Option<f64>,
pub grid: bool,
pub ticks: TickConfig,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ScaleType {
Linear,
Logarithmic,
Time,
Category,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TickConfig {
pub count: Option<usize>,
pub interval: Option<f64>,
pub format: String,
pub rotation: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnimationConfig {
pub enabled: bool,
pub duration: Duration,
pub easing: EasingFunction,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum EasingFunction {
Linear,
EaseIn,
EaseOut,
EaseInOut,
ElasticIn,
ElasticOut,
BounceIn,
BounceOut,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InteractionConfig {
pub zoom: bool,
pub pan: bool,
pub hover: bool,
pub selection: bool,
pub brush: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DashboardTheme {
pub primary_color: String,
pub secondary_color: String,
pub background_color: String,
pub text_color: String,
pub font_family: String,
pub font_size: usize,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ReportFormat {
Pdf,
Html,
Markdown,
Json,
Csv,
Excel,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationConfig {
pub email: Option<EmailConfig>,
pub slack: Option<SlackConfig>,
pub discord: Option<DiscordConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailConfig {
pub smtp_server: String,
pub smtp_port: u16,
pub username: String,
pub password: String,
pub from_address: String,
pub recipients: Vec<String>,
pub use_tls: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SlackConfig {
pub webhook_url: String,
pub channel: String,
pub username: String,
pub icon: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscordConfig {
pub webhook_url: String,
pub username: String,
pub avatar_url: Option<String>,
}
impl Default for AnalyticsConfig {
fn default() -> Self {
Self {
enable_performance_monitoring: true,
enable_convergence_analysis: true,
enable_resource_monitoring: true,
enable_pattern_detection: true,
enable_anomaly_detection: true,
enable_trend_analysis: true,
enable_dashboard: true,
performance_config: PerformanceMonitoringConfig::default(),
convergence_config: ConvergenceAnalysisConfig::default(),
resource_config: ResourceMonitoringConfig::default(),
pattern_config: PatternDetectionConfig::default(),
anomaly_config: AnomalyDetectionConfig::default(),
trend_config: TrendAnalysisConfig::default(),
dashboard_config: DashboardConfig::default(),
reporting_config: ReportingConfig::default(),
}
}
}
impl Default for PerformanceMonitoringConfig {
fn default() -> Self {
Self {
sampling_interval: Duration::from_secs(10),
max_snapshots: 1000,
enable_detailed_profiling: true,
performance_thresholds: PerformanceThresholds::default(),
benchmark_config: BenchmarkConfig::default(),
model_config: ModelTrackingConfig::default(),
}
}
}
impl Default for ConvergenceAnalysisConfig {
fn default() -> Self {
Self {
detection_methods: vec![
ConvergenceDetectionMethod::LossBased,
ConvergenceDetectionMethod::GradientNorm,
],
detection_parameters: ConvergenceParameters::default(),
analysis_window_size: 100,
min_steps_for_detection: 50,
enable_early_stopping: true,
early_stopping_config: EarlyStoppingConfig::default(),
}
}
}
impl Default for ResourceMonitoringConfig {
fn default() -> Self {
Self {
monitor_cpu: true,
monitor_memory: true,
monitor_gpu: true,
monitor_disk: true,
monitor_network: true,
sampling_frequency: Duration::from_secs(5),
history_size: 1000,
resource_thresholds: ResourceThresholds::default(),
}
}
}
impl Default for PatternDetectionConfig {
fn default() -> Self {
Self {
enable_loss_patterns: true,
enable_gradient_patterns: true,
enable_performance_patterns: true,
detection_sensitivity: 0.8,
min_pattern_length: 5,
max_pattern_length: 50,
pattern_tolerance: 0.1,
}
}
}
impl Default for AnomalyDetectionConfig {
fn default() -> Self {
Self {
detection_methods: vec![
AnomalyDetectionMethod::Statistical,
AnomalyDetectionMethod::IsolationForest,
],
sensitivity: 0.95,
window_size: 100,
confidence_threshold: 0.9,
enable_real_time_alerts: true,
alert_config: AnomalyAlertConfig::default(),
}
}
}
impl Default for TrendAnalysisConfig {
fn default() -> Self {
Self {
forecasting_methods: vec![
ForecastingMethod::LinearRegression,
ForecastingMethod::ExponentialSmoothing,
],
prediction_horizon: 50,
trend_window_size: 200,
enable_seasonal_decomposition: true,
confidence_intervals: vec![0.8, 0.95],
}
}
}
impl Default for DashboardConfig {
fn default() -> Self {
Self {
update_frequency: Duration::from_secs(1),
max_display_points: 1000,
enable_interactive: true,
layout_config: DashboardLayoutConfig::default(),
chart_configs: HashMap::new(),
}
}
}
impl Default for ReportingConfig {
fn default() -> Self {
Self {
generation_frequency: Duration::from_secs(3600), output_formats: vec![ReportFormat::Html, ReportFormat::Pdf],
include_detailed_analysis: true,
include_visualizations: true,
retention_period: Duration::from_secs(30 * 24 * 3600), notification_config: None,
}
}
}
impl<T: Float + Debug + Send + Sync + 'static> Default for PerformanceThresholds<T> {
fn default() -> Self {
Self {
max_loss: None,
min_accuracy: None,
max_training_time: Some(Duration::from_secs(3600)),
max_memory_usage: Some(0.9),
min_convergence_rate: None,
}
}
}
impl Default for BenchmarkConfig {
fn default() -> Self {
Self {
enable_auto_benchmark: true,
benchmark_frequency: Duration::from_secs(24 * 3600), reference_datasets: vec!["mnist".to_string(), "cifar10".to_string()],
tracked_metrics: vec!["accuracy".to_string(), "loss".to_string()],
baselines: HashMap::new(),
}
}
}
impl Default for ModelTrackingConfig {
fn default() -> Self {
Self {
track_predictions: true,
track_parameters: true,
track_gradients: true,
enable_versioning: true,
enable_comparison: true,
}
}
}
impl<T: Float + Debug + Send + Sync + 'static> Default for ConvergenceParameters<T> {
fn default() -> Self {
Self {
loss_tolerance: scirs2_core::numeric::NumCast::from(1e-6).unwrap_or_else(|| T::zero()),
gradient_tolerance: scirs2_core::numeric::NumCast::from(1e-8).unwrap_or_else(|| T::zero()),
parameter_tolerance: scirs2_core::numeric::NumCast::from(1e-6).unwrap_or_else(|| T::zero()),
window_size: 10,
min_improvement: scirs2_core::numeric::NumCast::from(1e-4).unwrap_or_else(|| T::zero()),
patience: 10,
}
}
}
impl<T: Float + Debug + Send + Sync + 'static> Default for EarlyStoppingConfig<T> {
fn default() -> Self {
Self {
enabled: true,
monitor_metric: "val_loss".to_string(),
min_delta: scirs2_core::numeric::NumCast::from(1e-4).unwrap_or_else(|| T::zero()),
patience: 10,
restore_best_weights: true,
mode: EarlyStoppingMode::Min,
}
}
}
impl Default for ResourceThresholds {
fn default() -> Self {
Self {
cpu_threshold: 80.0,
memory_threshold: 85.0,
gpu_threshold: 90.0,
disk_threshold: 90.0,
network_threshold: 100.0, }
}
}
impl Default for AnomalyAlertConfig {
fn default() -> Self {
Self {
severity_levels: vec![
AlertSeverity::Low,
AlertSeverity::Medium,
AlertSeverity::High,
AlertSeverity::Critical,
],
alert_channels: vec![AlertChannel::SystemLog, AlertChannel::Dashboard],
frequency_limits: HashMap::new(),
suppression_rules: Vec::new(),
}
}
}
impl Default for DashboardLayoutConfig {
fn default() -> Self {
Self {
grid_layout: (4, 3),
panels: Vec::new(),
theme: DashboardTheme::default(),
responsive: true,
}
}
}
impl Default for DashboardTheme {
fn default() -> Self {
Self {
primary_color: "#007bff".to_string(),
secondary_color: "#6c757d".to_string(),
background_color: "#ffffff".to_string(),
text_color: "#343a40".to_string(),
font_family: "Arial, sans-serif".to_string(),
font_size: 14,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_analytics_config_default() {
let config = AnalyticsConfig::default();
assert!(config.enable_performance_monitoring);
assert!(config.enable_convergence_analysis);
assert!(config.enable_anomaly_detection);
}
#[test]
fn test_performance_thresholds() {
let thresholds = PerformanceThresholds::<f64>::default();
assert!(thresholds.max_training_time.is_some());
assert!(thresholds.max_memory_usage.is_some());
}
#[test]
fn test_convergence_parameters() {
let params = ConvergenceParameters::<f32>::default();
assert!(params.loss_tolerance > 0.0);
assert!(params.gradient_tolerance > 0.0);
assert!(params.window_size > 0);
}
#[test]
fn test_alert_severity_ordering() {
use std::cmp::Ordering;
assert!(AlertSeverity::Critical > AlertSeverity::High);
assert!(AlertSeverity::High > AlertSeverity::Medium);
assert!(AlertSeverity::Medium > AlertSeverity::Low);
}
#[test]
fn test_dashboard_theme_colors() {
let theme = DashboardTheme::default();
assert!(theme.primary_color.starts_with('#'));
assert!(theme.secondary_color.starts_with('#'));
assert_eq!(theme.font_size, 14);
}
}