Skip to main content

qualia_core_db/specialized_libs/statistical_computing/
analytics.rs

1use super::*;
2
3/// Statistical analysis engine
4pub struct StatisticalAnalysisEngine {
5    analysis_algorithms: Vec<AnalysisAlgorithm>,
6    pattern_recognition: PatternRecognition,
7    anomaly_detection: AnomalyDetection,
8    forecasting_engine: ForecastingEngine,
9}
10
11/// Analysis algorithms
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub enum AnalysisAlgorithm {
14    DescriptiveAnalysis,
15    InferentialAnalysis,
16    PredictiveAnalysis,
17    PrescriptiveAnalysis,
18    CausalAnalysis,
19    TimeSeriesAnalysis,
20    SurvivalAnalysis,
21    BayesianAnalysis,
22}
23
24/// Pattern recognition
25pub struct PatternRecognition {
26    pattern_types: Vec<PatternType>,
27    recognition_algorithms: Vec<RecognitionAlgorithm>,
28    pattern_library: PatternLibrary,
29}
30
31/// Pattern types
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33pub enum PatternType {
34    Trend,
35    Seasonal,
36    Cyclical,
37    Outlier,
38    Cluster,
39    Association,
40    Sequential,
41    Spatial,
42}
43
44/// Recognition algorithms
45#[derive(Debug, Clone, PartialEq)]
46pub enum RecognitionAlgorithm {
47    Statistical,
48    MachineLearning,
49    DeepLearning,
50    Hybrid,
51    Custom(String),
52}
53
54/// Pattern library
55pub struct PatternLibrary {
56    patterns: HashMap<String, StatisticalPattern>,
57    pattern_templates: Vec<PatternTemplate>,
58}
59
60/// Statistical pattern
61#[derive(Debug, Clone)]
62pub struct StatisticalPattern {
63    pub pattern_id: String,
64    pub pattern_type: PatternType,
65    pub parameters: Vec<f64>,
66    pub confidence: f64,
67    pub frequency: f64,
68}
69
70/// Pattern template
71#[derive(Debug, Clone)]
72pub struct PatternTemplate {
73    pub template_id: String,
74    pub pattern_type: PatternType,
75    pub parameter_schema: ParameterSchema,
76}
77
78/// Parameter schema
79#[derive(Debug, Clone)]
80pub struct ParameterSchema {
81    pub parameters: Vec<ParameterDefinition>,
82    pub constraints: Vec<Constraint>,
83}
84
85/// Parameter definition
86#[derive(Debug, Clone)]
87pub struct ParameterDefinition {
88    pub name: String,
89    pub parameter_type: DataType,
90    pub required: bool,
91    pub default_value: Option<f64>,
92}
93
94/// Constraint
95#[derive(Debug, Clone)]
96pub struct Constraint {
97    pub constraint_type: ConstraintType,
98    pub parameters: Vec<String>,
99    pub condition: String,
100}
101
102/// Constraint types
103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
104pub enum ConstraintType {
105    Range,
106    Equality,
107    Inequality,
108    Logical,
109    Custom(String),
110}
111
112/// Anomaly detection
113pub struct AnomalyDetection {
114    detection_algorithms: Vec<DetectionAlgorithm>,
115    threshold_methods: Vec<ThresholdMethod>,
116    alert_system: AlertSystem,
117}
118
119/// Detection algorithms
120#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
121pub enum DetectionAlgorithm {
122    Statistical,
123    MachineLearning,
124    DeepLearning,
125    Ensemble,
126    Custom(String),
127}
128
129/// Threshold methods
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub enum ThresholdMethod {
132    Static,
133    Dynamic,
134    Adaptive,
135    Learned,
136    Custom(String),
137}
138
139/// Alert system
140pub struct AlertSystem {
141    alert_types: Vec<AlertType>,
142    notification_channels: Vec<NotificationChannel>,
143    escalation_policies: Vec<EscalationPolicy>,
144}
145
146/// Alert types
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
148pub enum AlertType {
149    Threshold,
150    Pattern,
151    Anomaly,
152    System,
153    Security,
154    Custom(String),
155}
156
157/// Notification channels
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159pub enum NotificationChannel {
160    Email,
161    SMS,
162    Webhook,
163    Slack,
164    Custom(String),
165}
166
167/// Escalation policies
168#[derive(Debug, Clone)]
169pub struct EscalationPolicy {
170    pub policy_id: String,
171    pub trigger_conditions: Vec<String>,
172    pub escalation_steps: Vec<EscalationStep>,
173    pub timeout: u64,
174}
175
176/// Escalation step
177#[derive(Debug, Clone)]
178pub struct EscalationStep {
179    pub step_id: String,
180    pub action: EscalationAction,
181    pub target: String,
182    pub delay: u64,
183}
184
185/// Escalation actions
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
187pub enum EscalationAction {
188    Notify,
189    Escalate,
190    Block,
191    Custom(String),
192}
193
194/// Forecasting engine
195pub struct ForecastingEngine {
196    forecasting_models: Vec<ForecastingModel>,
197    accuracy_metrics: AccuracyMetrics,
198    model_selection: ModelSelection,
199}
200
201/// Forecasting models
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
203pub enum ForecastingModel {
204    ARIMA,
205    ExponentialSmoothing,
206    Prophet,
207    LSTM,
208    Transformer,
209    Ensemble,
210    Custom(String),
211}
212
213/// Accuracy metrics
214#[derive(Debug, Clone)]
215pub struct AccuracyMetrics {
216    pub mae: f64,
217    pub mse: f64,
218    pub rmse: f64,
219    pub mape: f64,
220    pub smape: f64,
221    pub r_squared: f64,
222}
223
224/// Model selection
225pub struct ModelSelection {
226    selection_criteria: Vec<SelectionCriterion>,
227    cross_validation: CrossValidation,
228    hyperparameter_tuning: HyperparameterTuning,
229}
230
231/// Selection criteria
232#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
233pub enum SelectionCriterion {
234    Accuracy,
235    Speed,
236    Memory,
237    Interpretability,
238    Robustness,
239    Custom(String),
240}
241
242/// Cross validation
243pub struct CrossValidation {
244    pub cv_method: CVMethod,
245    pub folds: usize,
246    pub shuffle: bool,
247    pub stratify: bool,
248}
249
250/// CV methods
251#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
252pub enum CVMethod {
253    KFold,
254    StratifiedKFold,
255    TimeSeriesSplit,
256    LeaveOneOut,
257    Custom(String),
258}
259
260/// Hyperparameter tuning
261pub struct HyperparameterTuning {
262    pub tuning_method: TuningMethod,
263    pub search_space: SearchSpace,
264    pub max_iterations: usize,
265}
266
267/// Tuning methods
268#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
269pub enum TuningMethod {
270    GridSearch,
271    RandomSearch,
272    BayesianOptimization,
273    GeneticAlgorithm,
274    Custom(String),
275}
276
277/// Search space
278#[derive(Debug, Clone)]
279pub struct SearchSpace {
280    pub parameters: Vec<Hyperparameter>,
281    pub constraints: Vec<Constraint>,
282}
283
284/// Hyperparameter
285#[derive(Debug, Clone)]
286pub struct Hyperparameter {
287    pub name: String,
288    pub parameter_type: HyperparameterType,
289    pub range: ParameterRange,
290}
291
292/// Hyperparameter types
293#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
294pub enum HyperparameterType {
295    Continuous,
296    Integer,
297    Categorical,
298    Boolean,
299}
300
301/// Parameter range
302#[derive(Debug, Clone)]
303pub struct ParameterRange {
304    pub min: Option<f64>,
305    pub max: Option<f64>,
306    pub values: Option<Vec<String>>,
307}
308
309/// Statistical performance monitor
310pub struct StatisticalPerformanceMonitor {
311    operation_metrics: HashMap<String, OperationMetrics>,
312    dataset_metrics: HashMap<String, DatasetMetrics>,
313    system_metrics: SystemMetrics,
314    privacy_metrics: PrivacyMetrics,
315}
316
317/// Operation metrics
318#[derive(Debug, Clone)]
319pub struct OperationMetrics {
320    pub operation_id: String,
321    pub operation_type: StatisticalOperation,
322    pub execution_time: u64,
323    pub memory_usage: u64,
324    pub cpu_usage: f64,
325    pub accuracy: f64,
326    pub privacy_cost: f64,
327}
328
329/// Dataset metrics
330#[derive(Debug, Clone)]
331pub struct DatasetMetrics {
332    pub dataset_id: String,
333    pub size: u64,
334    pub access_count: u64,
335    pub access_frequency: f64,
336    pub compression_ratio: f64,
337    pub privacy_level: PrivacyLevel,
338}
339
340/// System metrics
341#[derive(Debug, Clone)]
342pub struct SystemMetrics {
343    pub total_operations: u64,
344    pub average_execution_time: f64,
345    pub throughput: f64,
346    pub memory_utilization: f64,
347    pub cpu_utilization: f64,
348    pub storage_utilization: f64,
349    pub energy_efficiency: f64,
350}
351
352/// Privacy metrics
353#[derive(Debug, Clone)]
354pub struct PrivacyMetrics {
355    pub epsilon_spent: f64,
356    pub delta_spent: f64,
357    pub privacy_preserved_operations: u64,
358    pub total_operations: u64,
359    pub privacy_efficiency: f64,
360}
361
362impl StatisticalAnalysisEngine {
363    pub fn new() -> Self {
364        Self {
365            analysis_algorithms: vec![
366                AnalysisAlgorithm::DescriptiveAnalysis,
367                AnalysisAlgorithm::InferentialAnalysis,
368            ],
369            pattern_recognition: PatternRecognition::new(),
370            anomaly_detection: AnomalyDetection::new(),
371            forecasting_engine: ForecastingEngine::new(),
372        }
373    }
374
375    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
376        self.pattern_recognition.initialize()?;
377        self.anomaly_detection.initialize()?;
378        self.forecasting_engine.initialize()?;
379        Ok(())
380    }
381
382    /// Returns the list of analysis algorithms available to this engine.
383    pub fn analysis_algorithms(&self) -> &[AnalysisAlgorithm] {
384        &self.analysis_algorithms
385    }
386
387    /// Register an additional analysis algorithm if not already present.
388    pub fn add_analysis_algorithm(&mut self, algorithm: AnalysisAlgorithm) {
389        if !self.analysis_algorithms.contains(&algorithm) {
390            self.analysis_algorithms.push(algorithm);
391        }
392    }
393
394    /// Returns `true` when the given analysis algorithm is registered.
395    pub fn supports_analysis_algorithm(&self, algorithm: &AnalysisAlgorithm) -> bool {
396        self.analysis_algorithms.contains(algorithm)
397    }
398
399    /// Returns a reference to the pattern recognition subsystem.
400    pub fn pattern_recognition(&self) -> &PatternRecognition {
401        &self.pattern_recognition
402    }
403
404    /// Returns a mutable reference to the pattern recognition subsystem.
405    pub fn pattern_recognition_mut(&mut self) -> &mut PatternRecognition {
406        &mut self.pattern_recognition
407    }
408
409    /// Returns a reference to the anomaly detection subsystem.
410    pub fn anomaly_detection(&self) -> &AnomalyDetection {
411        &self.anomaly_detection
412    }
413
414    /// Returns a mutable reference to the anomaly detection subsystem.
415    pub fn anomaly_detection_mut(&mut self) -> &mut AnomalyDetection {
416        &mut self.anomaly_detection
417    }
418
419    /// Returns a reference to the forecasting engine.
420    pub fn forecasting_engine(&self) -> &ForecastingEngine {
421        &self.forecasting_engine
422    }
423
424    /// Returns a mutable reference to the forecasting engine.
425    pub fn forecasting_engine_mut(&mut self) -> &mut ForecastingEngine {
426        &mut self.forecasting_engine
427    }
428}
429
430impl PatternRecognition {
431    pub fn new() -> Self {
432        Self {
433            pattern_types: vec![
434                PatternType::Trend,
435                PatternType::Seasonal,
436                PatternType::Outlier,
437            ],
438            recognition_algorithms: vec![RecognitionAlgorithm::Statistical],
439            pattern_library: PatternLibrary::new(),
440        }
441    }
442
443    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
444        self.pattern_library.initialize()?;
445        Ok(())
446    }
447
448    /// Returns the list of pattern types this recognizer looks for.
449    pub fn pattern_types(&self) -> &[PatternType] {
450        &self.pattern_types
451    }
452
453    /// Register an additional pattern type if not already present.
454    pub fn add_pattern_type(&mut self, pattern_type: PatternType) {
455        if !self.pattern_types.contains(&pattern_type) {
456            self.pattern_types.push(pattern_type);
457        }
458    }
459
460    /// Returns the list of recognition algorithms available.
461    pub fn recognition_algorithms(&self) -> &[RecognitionAlgorithm] {
462        &self.recognition_algorithms
463    }
464
465    /// Register an additional recognition algorithm if not already present.
466    pub fn add_recognition_algorithm(&mut self, algorithm: RecognitionAlgorithm) {
467        if !self.recognition_algorithms.contains(&algorithm) {
468            self.recognition_algorithms.push(algorithm);
469        }
470    }
471
472    /// Returns a reference to the pattern library.
473    pub fn pattern_library(&self) -> &PatternLibrary {
474        &self.pattern_library
475    }
476
477    /// Returns a mutable reference to the pattern library.
478    pub fn pattern_library_mut(&mut self) -> &mut PatternLibrary {
479        &mut self.pattern_library
480    }
481}
482
483impl PatternLibrary {
484    pub fn new() -> Self {
485        Self {
486            patterns: HashMap::new(),
487            pattern_templates: Vec::new(),
488        }
489    }
490
491    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
492        Ok(())
493    }
494
495    /// Add (or replace) a named statistical pattern.
496    pub fn add_pattern(&mut self, pattern: StatisticalPattern) {
497        self.patterns.insert(pattern.pattern_id.clone(), pattern);
498    }
499
500    /// Look up a statistical pattern by id.
501    pub fn get_pattern(&self, pattern_id: &str) -> Option<&StatisticalPattern> {
502        self.patterns.get(pattern_id)
503    }
504
505    /// Remove a statistical pattern by id.
506    pub fn remove_pattern(&mut self, pattern_id: &str) -> Option<StatisticalPattern> {
507        self.patterns.remove(pattern_id)
508    }
509
510    /// List the ids of all stored patterns.
511    pub fn list_pattern_ids(&self) -> Vec<String> {
512        self.patterns.keys().cloned().collect()
513    }
514
515    /// Returns the number of stored patterns.
516    pub fn pattern_count(&self) -> usize {
517        self.patterns.len()
518    }
519
520    /// Register a pattern template.
521    pub fn add_pattern_template(&mut self, template: PatternTemplate) {
522        self.pattern_templates.push(template);
523    }
524
525    /// Returns the list of registered pattern templates.
526    pub fn pattern_templates(&self) -> &[PatternTemplate] {
527        &self.pattern_templates
528    }
529
530    /// Look up a pattern template by id.
531    pub fn get_pattern_template(&self, template_id: &str) -> Option<&PatternTemplate> {
532        self.pattern_templates
533            .iter()
534            .find(|t| t.template_id == template_id)
535    }
536
537    /// Returns the number of registered pattern templates.
538    pub fn pattern_template_count(&self) -> usize {
539        self.pattern_templates.len()
540    }
541}
542
543impl AnomalyDetection {
544    pub fn new() -> Self {
545        Self {
546            detection_algorithms: vec![DetectionAlgorithm::Statistical],
547            threshold_methods: vec![ThresholdMethod::Static],
548            alert_system: AlertSystem::new(),
549        }
550    }
551
552    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
553        self.alert_system.initialize()?;
554        Ok(())
555    }
556
557    /// Returns the list of registered detection algorithms.
558    pub fn detection_algorithms(&self) -> &[DetectionAlgorithm] {
559        &self.detection_algorithms
560    }
561
562    /// Register an additional detection algorithm if not already present.
563    pub fn add_detection_algorithm(&mut self, algorithm: DetectionAlgorithm) {
564        if !self.detection_algorithms.contains(&algorithm) {
565            self.detection_algorithms.push(algorithm);
566        }
567    }
568
569    /// Returns the list of registered threshold methods.
570    pub fn threshold_methods(&self) -> &[ThresholdMethod] {
571        &self.threshold_methods
572    }
573
574    /// Register an additional threshold method if not already present.
575    pub fn add_threshold_method(&mut self, method: ThresholdMethod) {
576        if !self.threshold_methods.contains(&method) {
577            self.threshold_methods.push(method);
578        }
579    }
580
581    /// Returns a reference to the alert system.
582    pub fn alert_system(&self) -> &AlertSystem {
583        &self.alert_system
584    }
585
586    /// Returns a mutable reference to the alert system.
587    pub fn alert_system_mut(&mut self) -> &mut AlertSystem {
588        &mut self.alert_system
589    }
590}
591
592impl AlertSystem {
593    pub fn new() -> Self {
594        Self {
595            alert_types: vec![AlertType::Threshold, AlertType::Anomaly],
596            notification_channels: vec![NotificationChannel::Email],
597            escalation_policies: Vec::new(),
598        }
599    }
600
601    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
602        Ok(())
603    }
604
605    /// Returns the list of registered alert types.
606    pub fn alert_types(&self) -> &[AlertType] {
607        &self.alert_types
608    }
609
610    /// Register an additional alert type if not already present.
611    pub fn add_alert_type(&mut self, alert_type: AlertType) {
612        if !self.alert_types.contains(&alert_type) {
613            self.alert_types.push(alert_type);
614        }
615    }
616
617    /// Returns the list of registered notification channels.
618    pub fn notification_channels(&self) -> &[NotificationChannel] {
619        &self.notification_channels
620    }
621
622    /// Register an additional notification channel if not already present.
623    pub fn add_notification_channel(&mut self, channel: NotificationChannel) {
624        if !self.notification_channels.contains(&channel) {
625            self.notification_channels.push(channel);
626        }
627    }
628
629    /// Register an escalation policy.
630    pub fn add_escalation_policy(&mut self, policy: EscalationPolicy) {
631        self.escalation_policies.push(policy);
632    }
633
634    /// Returns the list of registered escalation policies.
635    pub fn escalation_policies(&self) -> &[EscalationPolicy] {
636        &self.escalation_policies
637    }
638
639    /// Look up an escalation policy by id.
640    pub fn get_escalation_policy(&self, policy_id: &str) -> Option<&EscalationPolicy> {
641        self.escalation_policies
642            .iter()
643            .find(|p| p.policy_id == policy_id)
644    }
645
646    /// Returns the number of registered escalation policies.
647    pub fn escalation_policy_count(&self) -> usize {
648        self.escalation_policies.len()
649    }
650}
651
652impl ForecastingEngine {
653    pub fn new() -> Self {
654        Self {
655            forecasting_models: vec![
656                ForecastingModel::ARIMA,
657                ForecastingModel::ExponentialSmoothing,
658            ],
659            accuracy_metrics: AccuracyMetrics {
660                mae: 0.0,
661                mse: 0.0,
662                rmse: 0.0,
663                mape: 0.0,
664                smape: 0.0,
665                r_squared: 0.0,
666            },
667            model_selection: ModelSelection::new(),
668        }
669    }
670
671    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
672        self.model_selection.initialize()?;
673        Ok(())
674    }
675
676    /// Returns the list of registered forecasting models.
677    pub fn forecasting_models(&self) -> &[ForecastingModel] {
678        &self.forecasting_models
679    }
680
681    /// Register an additional forecasting model if not already present.
682    pub fn add_forecasting_model(&mut self, model: ForecastingModel) {
683        if !self.forecasting_models.contains(&model) {
684            self.forecasting_models.push(model);
685        }
686    }
687
688    /// Returns `true` when the given forecasting model is registered.
689    pub fn supports_forecasting_model(&self, model: &ForecastingModel) -> bool {
690        self.forecasting_models.contains(model)
691    }
692
693    /// Returns a reference to the current accuracy metrics.
694    pub fn accuracy_metrics(&self) -> &AccuracyMetrics {
695        &self.accuracy_metrics
696    }
697
698    /// Update the accuracy metrics after a forecasting run.
699    pub fn set_accuracy_metrics(&mut self, metrics: AccuracyMetrics) {
700        self.accuracy_metrics = metrics;
701    }
702
703    /// Returns a reference to the model selection subsystem.
704    pub fn model_selection(&self) -> &ModelSelection {
705        &self.model_selection
706    }
707
708    /// Returns a mutable reference to the model selection subsystem.
709    pub fn model_selection_mut(&mut self) -> &mut ModelSelection {
710        &mut self.model_selection
711    }
712}
713
714impl ModelSelection {
715    pub fn new() -> Self {
716        Self {
717            selection_criteria: vec![SelectionCriterion::Accuracy, SelectionCriterion::Speed],
718            cross_validation: CrossValidation::new(),
719            hyperparameter_tuning: HyperparameterTuning::new(),
720        }
721    }
722
723    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
724        Ok(())
725    }
726
727    /// Returns the list of registered selection criteria.
728    pub fn selection_criteria(&self) -> &[SelectionCriterion] {
729        &self.selection_criteria
730    }
731
732    /// Register an additional selection criterion if not already present.
733    pub fn add_selection_criterion(&mut self, criterion: SelectionCriterion) {
734        if !self.selection_criteria.contains(&criterion) {
735            self.selection_criteria.push(criterion);
736        }
737    }
738
739    /// Returns a reference to the cross-validation configuration.
740    pub fn cross_validation(&self) -> &CrossValidation {
741        &self.cross_validation
742    }
743
744    /// Returns a mutable reference to the cross-validation configuration.
745    pub fn cross_validation_mut(&mut self) -> &mut CrossValidation {
746        &mut self.cross_validation
747    }
748
749    /// Returns a reference to the hyperparameter tuning configuration.
750    pub fn hyperparameter_tuning(&self) -> &HyperparameterTuning {
751        &self.hyperparameter_tuning
752    }
753
754    /// Returns a mutable reference to the hyperparameter tuning configuration.
755    pub fn hyperparameter_tuning_mut(&mut self) -> &mut HyperparameterTuning {
756        &mut self.hyperparameter_tuning
757    }
758}
759
760impl CrossValidation {
761    pub fn new() -> Self {
762        Self {
763            cv_method: CVMethod::KFold,
764            folds: 5,
765            shuffle: true,
766            stratify: false,
767        }
768    }
769}
770
771impl HyperparameterTuning {
772    pub fn new() -> Self {
773        Self {
774            tuning_method: TuningMethod::GridSearch,
775            search_space: SearchSpace::new(),
776            max_iterations: 100,
777        }
778    }
779}
780
781impl SearchSpace {
782    pub fn new() -> Self {
783        Self {
784            parameters: Vec::new(),
785            constraints: Vec::new(),
786        }
787    }
788}
789
790impl StatisticalPerformanceMonitor {
791    pub fn new() -> Self {
792        Self {
793            operation_metrics: HashMap::new(),
794            dataset_metrics: HashMap::new(),
795            system_metrics: SystemMetrics {
796                total_operations: 0,
797                average_execution_time: 0.0,
798                throughput: 0.0,
799                memory_utilization: 0.0,
800                cpu_utilization: 0.0,
801                storage_utilization: 0.0,
802                energy_efficiency: 0.0,
803            },
804            privacy_metrics: PrivacyMetrics {
805                epsilon_spent: 0.0,
806                delta_spent: 0.0,
807                privacy_preserved_operations: 0,
808                total_operations: 0,
809                privacy_efficiency: 0.0,
810            },
811        }
812    }
813
814    pub fn record_operation(
815        &mut self,
816        _operation_type: &str,
817        execution_time: u64,
818        _memory_usage: u64,
819        privacy_cost: f64,
820    ) {
821        self.system_metrics.total_operations += 1;
822        self.system_metrics.average_execution_time = (self.system_metrics.average_execution_time
823            * (self.system_metrics.total_operations - 1) as f64
824            + execution_time as f64)
825            / self.system_metrics.total_operations as f64;
826
827        self.privacy_metrics.total_operations += 1;
828        self.privacy_metrics.epsilon_spent += privacy_cost;
829        if privacy_cost > 0.0 {
830            self.privacy_metrics.privacy_preserved_operations += 1;
831        }
832    }
833
834    pub fn get_system_metrics(&self) -> SystemMetrics {
835        self.system_metrics.clone()
836    }
837
838    /// Record metrics for a specific operation, keyed by `operation_id`.
839    pub fn record_operation_metrics(&mut self, metrics: OperationMetrics) {
840        self.operation_metrics
841            .insert(metrics.operation_id.clone(), metrics);
842    }
843
844    /// Look up metrics for a specific operation by id.
845    pub fn get_operation_metrics(&self, operation_id: &str) -> Option<&OperationMetrics> {
846        self.operation_metrics.get(operation_id)
847    }
848
849    /// Returns the number of operations with recorded metrics.
850    pub fn operation_metrics_count(&self) -> usize {
851        self.operation_metrics.len()
852    }
853
854    /// Record metrics for a specific dataset, keyed by `dataset_id`.
855    pub fn record_dataset_metrics(&mut self, metrics: DatasetMetrics) {
856        self.dataset_metrics
857            .insert(metrics.dataset_id.clone(), metrics);
858    }
859
860    /// Look up metrics for a specific dataset by id.
861    pub fn get_dataset_metrics(&self, dataset_id: &str) -> Option<&DatasetMetrics> {
862        self.dataset_metrics.get(dataset_id)
863    }
864
865    /// Returns the number of datasets with recorded metrics.
866    pub fn dataset_metrics_count(&self) -> usize {
867        self.dataset_metrics.len()
868    }
869
870    /// Returns a reference to the privacy metrics.
871    pub fn privacy_metrics(&self) -> &PrivacyMetrics {
872        &self.privacy_metrics
873    }
874}