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    /// Creates the engine with default pattern/anomaly/forecast subsystems.
364    pub fn new() -> Self {
365        Self {
366            analysis_algorithms: vec![
367                AnalysisAlgorithm::DescriptiveAnalysis,
368                AnalysisAlgorithm::InferentialAnalysis,
369            ],
370            pattern_recognition: PatternRecognition::new(),
371            anomaly_detection: AnomalyDetection::new(),
372            forecasting_engine: ForecastingEngine::new(),
373        }
374    }
375
376    /// Initializes pattern recognition, anomaly detection, and forecasting; `StatisticalError` propagates.
377    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
378        self.pattern_recognition.initialize()?;
379        self.anomaly_detection.initialize()?;
380        self.forecasting_engine.initialize()?;
381        Ok(())
382    }
383
384    /// Returns the list of analysis algorithms available to this engine.
385    pub fn analysis_algorithms(&self) -> &[AnalysisAlgorithm] {
386        &self.analysis_algorithms
387    }
388
389    /// Register an additional analysis algorithm if not already present.
390    pub fn add_analysis_algorithm(&mut self, algorithm: AnalysisAlgorithm) {
391        if !self.analysis_algorithms.contains(&algorithm) {
392            self.analysis_algorithms.push(algorithm);
393        }
394    }
395
396    /// Returns `true` when the given analysis algorithm is registered.
397    pub fn supports_analysis_algorithm(&self, algorithm: &AnalysisAlgorithm) -> bool {
398        self.analysis_algorithms.contains(algorithm)
399    }
400
401    /// Returns a reference to the pattern recognition subsystem.
402    pub fn pattern_recognition(&self) -> &PatternRecognition {
403        &self.pattern_recognition
404    }
405
406    /// Returns a mutable reference to the pattern recognition subsystem.
407    pub fn pattern_recognition_mut(&mut self) -> &mut PatternRecognition {
408        &mut self.pattern_recognition
409    }
410
411    /// Returns a reference to the anomaly detection subsystem.
412    pub fn anomaly_detection(&self) -> &AnomalyDetection {
413        &self.anomaly_detection
414    }
415
416    /// Returns a mutable reference to the anomaly detection subsystem.
417    pub fn anomaly_detection_mut(&mut self) -> &mut AnomalyDetection {
418        &mut self.anomaly_detection
419    }
420
421    /// Returns a reference to the forecasting engine.
422    pub fn forecasting_engine(&self) -> &ForecastingEngine {
423        &self.forecasting_engine
424    }
425
426    /// Returns a mutable reference to the forecasting engine.
427    pub fn forecasting_engine_mut(&mut self) -> &mut ForecastingEngine {
428        &mut self.forecasting_engine
429    }
430}
431
432impl PatternRecognition {
433    /// Creates pattern recognition with an empty pattern library.
434    pub fn new() -> Self {
435        Self {
436            pattern_types: vec![
437                PatternType::Trend,
438                PatternType::Seasonal,
439                PatternType::Outlier,
440            ],
441            recognition_algorithms: vec![RecognitionAlgorithm::Statistical],
442            pattern_library: PatternLibrary::new(),
443        }
444    }
445
446    /// Initializes the pattern library; `StatisticalError` propagates.
447    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
448        self.pattern_library.initialize()?;
449        Ok(())
450    }
451
452    /// Returns the list of pattern types this recognizer looks for.
453    pub fn pattern_types(&self) -> &[PatternType] {
454        &self.pattern_types
455    }
456
457    /// Register an additional pattern type if not already present.
458    pub fn add_pattern_type(&mut self, pattern_type: PatternType) {
459        if !self.pattern_types.contains(&pattern_type) {
460            self.pattern_types.push(pattern_type);
461        }
462    }
463
464    /// Returns the list of recognition algorithms available.
465    pub fn recognition_algorithms(&self) -> &[RecognitionAlgorithm] {
466        &self.recognition_algorithms
467    }
468
469    /// Register an additional recognition algorithm if not already present.
470    pub fn add_recognition_algorithm(&mut self, algorithm: RecognitionAlgorithm) {
471        if !self.recognition_algorithms.contains(&algorithm) {
472            self.recognition_algorithms.push(algorithm);
473        }
474    }
475
476    /// Returns a reference to the pattern library.
477    pub fn pattern_library(&self) -> &PatternLibrary {
478        &self.pattern_library
479    }
480
481    /// Returns a mutable reference to the pattern library.
482    pub fn pattern_library_mut(&mut self) -> &mut PatternLibrary {
483        &mut self.pattern_library
484    }
485}
486
487impl PatternLibrary {
488    /// Creates an empty pattern library.
489    pub fn new() -> Self {
490        Self {
491            patterns: HashMap::new(),
492            pattern_templates: Vec::new(),
493        }
494    }
495
496    /// No-op returning `Ok(())` — in-memory library needs no setup.
497    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
498        Ok(())
499    }
500
501    /// Add (or replace) a named statistical pattern.
502    pub fn add_pattern(&mut self, pattern: StatisticalPattern) {
503        self.patterns.insert(pattern.pattern_id.clone(), pattern);
504    }
505
506    /// Look up a statistical pattern by id.
507    pub fn get_pattern(&self, pattern_id: &str) -> Option<&StatisticalPattern> {
508        self.patterns.get(pattern_id)
509    }
510
511    /// Remove a statistical pattern by id.
512    pub fn remove_pattern(&mut self, pattern_id: &str) -> Option<StatisticalPattern> {
513        self.patterns.remove(pattern_id)
514    }
515
516    /// List the ids of all stored patterns.
517    pub fn list_pattern_ids(&self) -> Vec<String> {
518        self.patterns.keys().cloned().collect()
519    }
520
521    /// Returns the number of stored patterns.
522    pub fn pattern_count(&self) -> usize {
523        self.patterns.len()
524    }
525
526    /// Register a pattern template.
527    pub fn add_pattern_template(&mut self, template: PatternTemplate) {
528        self.pattern_templates.push(template);
529    }
530
531    /// Returns the list of registered pattern templates.
532    pub fn pattern_templates(&self) -> &[PatternTemplate] {
533        &self.pattern_templates
534    }
535
536    /// Look up a pattern template by id.
537    pub fn get_pattern_template(&self, template_id: &str) -> Option<&PatternTemplate> {
538        self.pattern_templates
539            .iter()
540            .find(|t| t.template_id == template_id)
541    }
542
543    /// Returns the number of registered pattern templates.
544    pub fn pattern_template_count(&self) -> usize {
545        self.pattern_templates.len()
546    }
547}
548
549impl AnomalyDetection {
550    /// Creates anomaly detection with default alert system.
551    pub fn new() -> Self {
552        Self {
553            detection_algorithms: vec![DetectionAlgorithm::Statistical],
554            threshold_methods: vec![ThresholdMethod::Static],
555            alert_system: AlertSystem::new(),
556        }
557    }
558
559    /// Initializes the alert system; `StatisticalError` propagates.
560    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
561        self.alert_system.initialize()?;
562        Ok(())
563    }
564
565    /// Returns the list of registered detection algorithms.
566    pub fn detection_algorithms(&self) -> &[DetectionAlgorithm] {
567        &self.detection_algorithms
568    }
569
570    /// Register an additional detection algorithm if not already present.
571    pub fn add_detection_algorithm(&mut self, algorithm: DetectionAlgorithm) {
572        if !self.detection_algorithms.contains(&algorithm) {
573            self.detection_algorithms.push(algorithm);
574        }
575    }
576
577    /// Returns the list of registered threshold methods.
578    pub fn threshold_methods(&self) -> &[ThresholdMethod] {
579        &self.threshold_methods
580    }
581
582    /// Register an additional threshold method if not already present.
583    pub fn add_threshold_method(&mut self, method: ThresholdMethod) {
584        if !self.threshold_methods.contains(&method) {
585            self.threshold_methods.push(method);
586        }
587    }
588
589    /// Returns a reference to the alert system.
590    pub fn alert_system(&self) -> &AlertSystem {
591        &self.alert_system
592    }
593
594    /// Returns a mutable reference to the alert system.
595    pub fn alert_system_mut(&mut self) -> &mut AlertSystem {
596        &mut self.alert_system
597    }
598}
599
600impl AlertSystem {
601    /// Creates a default alert system.
602    pub fn new() -> Self {
603        Self {
604            alert_types: vec![AlertType::Threshold, AlertType::Anomaly],
605            notification_channels: vec![NotificationChannel::Email],
606            escalation_policies: Vec::new(),
607        }
608    }
609
610    /// No-op returning `Ok(())`.
611    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
612        Ok(())
613    }
614
615    /// Returns the list of registered alert types.
616    pub fn alert_types(&self) -> &[AlertType] {
617        &self.alert_types
618    }
619
620    /// Register an additional alert type if not already present.
621    pub fn add_alert_type(&mut self, alert_type: AlertType) {
622        if !self.alert_types.contains(&alert_type) {
623            self.alert_types.push(alert_type);
624        }
625    }
626
627    /// Returns the list of registered notification channels.
628    pub fn notification_channels(&self) -> &[NotificationChannel] {
629        &self.notification_channels
630    }
631
632    /// Register an additional notification channel if not already present.
633    pub fn add_notification_channel(&mut self, channel: NotificationChannel) {
634        if !self.notification_channels.contains(&channel) {
635            self.notification_channels.push(channel);
636        }
637    }
638
639    /// Register an escalation policy.
640    pub fn add_escalation_policy(&mut self, policy: EscalationPolicy) {
641        self.escalation_policies.push(policy);
642    }
643
644    /// Returns the list of registered escalation policies.
645    pub fn escalation_policies(&self) -> &[EscalationPolicy] {
646        &self.escalation_policies
647    }
648
649    /// Look up an escalation policy by id.
650    pub fn get_escalation_policy(&self, policy_id: &str) -> Option<&EscalationPolicy> {
651        self.escalation_policies
652            .iter()
653            .find(|p| p.policy_id == policy_id)
654    }
655
656    /// Returns the number of registered escalation policies.
657    pub fn escalation_policy_count(&self) -> usize {
658        self.escalation_policies.len()
659    }
660}
661
662impl ForecastingEngine {
663    /// Creates a forecasting engine with default model-selection state.
664    pub fn new() -> Self {
665        Self {
666            forecasting_models: vec![
667                ForecastingModel::ARIMA,
668                ForecastingModel::ExponentialSmoothing,
669            ],
670            accuracy_metrics: AccuracyMetrics {
671                mae: 0.0,
672                mse: 0.0,
673                rmse: 0.0,
674                mape: 0.0,
675                smape: 0.0,
676                r_squared: 0.0,
677            },
678            model_selection: ModelSelection::new(),
679        }
680    }
681
682    /// Initializes model selection; `StatisticalError` propagates.
683    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
684        self.model_selection.initialize()?;
685        Ok(())
686    }
687
688    /// Returns the list of registered forecasting models.
689    pub fn forecasting_models(&self) -> &[ForecastingModel] {
690        &self.forecasting_models
691    }
692
693    /// Register an additional forecasting model if not already present.
694    pub fn add_forecasting_model(&mut self, model: ForecastingModel) {
695        if !self.forecasting_models.contains(&model) {
696            self.forecasting_models.push(model);
697        }
698    }
699
700    /// Returns `true` when the given forecasting model is registered.
701    pub fn supports_forecasting_model(&self, model: &ForecastingModel) -> bool {
702        self.forecasting_models.contains(model)
703    }
704
705    /// Returns a reference to the current accuracy metrics.
706    pub fn accuracy_metrics(&self) -> &AccuracyMetrics {
707        &self.accuracy_metrics
708    }
709
710    /// Update the accuracy metrics after a forecasting run.
711    pub fn set_accuracy_metrics(&mut self, metrics: AccuracyMetrics) {
712        self.accuracy_metrics = metrics;
713    }
714
715    /// Returns a reference to the model selection subsystem.
716    pub fn model_selection(&self) -> &ModelSelection {
717        &self.model_selection
718    }
719
720    /// Returns a mutable reference to the model selection subsystem.
721    pub fn model_selection_mut(&mut self) -> &mut ModelSelection {
722        &mut self.model_selection
723    }
724}
725
726impl ModelSelection {
727    /// Creates model selection with default cross-validation and tuning.
728    pub fn new() -> Self {
729        Self {
730            selection_criteria: vec![SelectionCriterion::Accuracy, SelectionCriterion::Speed],
731            cross_validation: CrossValidation::new(),
732            hyperparameter_tuning: HyperparameterTuning::new(),
733        }
734    }
735
736    /// No-op returning `Ok(())`.
737    pub fn initialize(&mut self) -> Result<(), StatisticalError> {
738        Ok(())
739    }
740
741    /// Returns the list of registered selection criteria.
742    pub fn selection_criteria(&self) -> &[SelectionCriterion] {
743        &self.selection_criteria
744    }
745
746    /// Register an additional selection criterion if not already present.
747    pub fn add_selection_criterion(&mut self, criterion: SelectionCriterion) {
748        if !self.selection_criteria.contains(&criterion) {
749            self.selection_criteria.push(criterion);
750        }
751    }
752
753    /// Returns a reference to the cross-validation configuration.
754    pub fn cross_validation(&self) -> &CrossValidation {
755        &self.cross_validation
756    }
757
758    /// Returns a mutable reference to the cross-validation configuration.
759    pub fn cross_validation_mut(&mut self) -> &mut CrossValidation {
760        &mut self.cross_validation
761    }
762
763    /// Returns a reference to the hyperparameter tuning configuration.
764    pub fn hyperparameter_tuning(&self) -> &HyperparameterTuning {
765        &self.hyperparameter_tuning
766    }
767
768    /// Returns a mutable reference to the hyperparameter tuning configuration.
769    pub fn hyperparameter_tuning_mut(&mut self) -> &mut HyperparameterTuning {
770        &mut self.hyperparameter_tuning
771    }
772}
773
774impl CrossValidation {
775    /// Creates a default `CrossValidation` config.
776    pub fn new() -> Self {
777        Self {
778            cv_method: CVMethod::KFold,
779            folds: 5,
780            shuffle: true,
781            stratify: false,
782        }
783    }
784}
785
786impl HyperparameterTuning {
787    /// Creates tuning state with default search space.
788    pub fn new() -> Self {
789        Self {
790            tuning_method: TuningMethod::GridSearch,
791            search_space: SearchSpace::new(),
792            max_iterations: 100,
793        }
794    }
795}
796
797impl SearchSpace {
798    /// Creates an empty `SearchSpace`.
799    pub fn new() -> Self {
800        Self {
801            parameters: Vec::new(),
802            constraints: Vec::new(),
803        }
804    }
805}
806
807impl StatisticalPerformanceMonitor {
808    /// Creates a monitor with zeroed system/privacy metrics.
809    pub fn new() -> Self {
810        Self {
811            operation_metrics: HashMap::new(),
812            dataset_metrics: HashMap::new(),
813            system_metrics: SystemMetrics {
814                total_operations: 0,
815                average_execution_time: 0.0,
816                throughput: 0.0,
817                memory_utilization: 0.0,
818                cpu_utilization: 0.0,
819                storage_utilization: 0.0,
820                energy_efficiency: 0.0,
821            },
822            privacy_metrics: PrivacyMetrics {
823                epsilon_spent: 0.0,
824                delta_spent: 0.0,
825                privacy_preserved_operations: 0,
826                total_operations: 0,
827                privacy_efficiency: 0.0,
828            },
829        }
830    }
831
832    /// Records one operation: updates running average execution time and accumulates `privacy_cost` into epsilon spent (counts privacy-preserved ops). `_operation_type` and `_memory_usage` are accepted but not yet tracked.
833    pub fn record_operation(
834        &mut self,
835        _operation_type: &str,
836        execution_time: u64,
837        _memory_usage: u64,
838        privacy_cost: f64,
839    ) {
840        self.system_metrics.total_operations += 1;
841        self.system_metrics.average_execution_time = (self.system_metrics.average_execution_time
842            * (self.system_metrics.total_operations - 1) as f64
843            + execution_time as f64)
844            / self.system_metrics.total_operations as f64;
845
846        self.privacy_metrics.total_operations += 1;
847        self.privacy_metrics.epsilon_spent += privacy_cost;
848        if privacy_cost > 0.0 {
849            self.privacy_metrics.privacy_preserved_operations += 1;
850        }
851    }
852
853    /// Snapshot of aggregated `SystemMetrics`.
854    pub fn get_system_metrics(&self) -> SystemMetrics {
855        self.system_metrics.clone()
856    }
857
858    /// Record metrics for a specific operation, keyed by `operation_id`.
859    pub fn record_operation_metrics(&mut self, metrics: OperationMetrics) {
860        self.operation_metrics
861            .insert(metrics.operation_id.clone(), metrics);
862    }
863
864    /// Look up metrics for a specific operation by id.
865    pub fn get_operation_metrics(&self, operation_id: &str) -> Option<&OperationMetrics> {
866        self.operation_metrics.get(operation_id)
867    }
868
869    /// Returns the number of operations with recorded metrics.
870    pub fn operation_metrics_count(&self) -> usize {
871        self.operation_metrics.len()
872    }
873
874    /// Record metrics for a specific dataset, keyed by `dataset_id`.
875    pub fn record_dataset_metrics(&mut self, metrics: DatasetMetrics) {
876        self.dataset_metrics
877            .insert(metrics.dataset_id.clone(), metrics);
878    }
879
880    /// Look up metrics for a specific dataset by id.
881    pub fn get_dataset_metrics(&self, dataset_id: &str) -> Option<&DatasetMetrics> {
882        self.dataset_metrics.get(dataset_id)
883    }
884
885    /// Returns the number of datasets with recorded metrics.
886    pub fn dataset_metrics_count(&self) -> usize {
887        self.dataset_metrics.len()
888    }
889
890    /// Returns a reference to the privacy metrics.
891    pub fn privacy_metrics(&self) -> &PrivacyMetrics {
892        &self.privacy_metrics
893    }
894}