optirs-learned 0.3.1

OptiRS learned optimizers and meta-learning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
// State management for optimization coordinator

use super::config::*;
use crate::OptimizerError as OptimError;
use crate::neural_architecture_search::ScheduleType;
use scirs2_core::ndarray::Array1;
use scirs2_core::numeric::Float;
use std::collections::{HashMap, VecDeque};
use std::fmt::Debug;
use std::time::{Duration, SystemTime};

/// Result type for state operations
type Result<T> = std::result::Result<T, OptimError>;

/// Comprehensive optimization context
#[derive(Debug, Clone)]
pub struct OptimizationContext<T: Float + Debug + Send + Sync + Debug> {
    /// Current optimization state
    pub state: OptimizationState<T>,

    /// Problem characteristics
    pub problem_characteristics: ProblemCharacteristics<T>,

    /// Resource constraints
    pub resource_constraints: ResourceConstraints<T>,

    /// Time constraints
    pub time_constraints: TimeConstraints,

    /// Performance history
    pub performance_history: Vec<T>,

    /// Current optimization phase
    pub current_phase: OptimizationPhase,

    /// Landscape analysis results
    pub landscape_features: Option<LandscapeFeatures<T>>,

    /// Dimensionality of the problem
    pub dimensionality: usize,

    /// Computational budget
    pub computational_budget: ComputationalBudget,

    /// Convergence criteria
    pub convergence_criteria: ConvergenceCriteria<T>,

    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// Current optimization state
#[derive(Debug, Clone)]
pub struct OptimizationState<T: Float + Debug + Send + Sync + 'static> {
    /// Current iteration number
    pub current_iteration: usize,

    /// Current loss value
    pub current_loss: T,

    /// Gradient norm
    pub gradient_norm: T,

    /// Current step size
    pub step_size: T,

    /// Convergence measure
    pub convergence_measure: T,

    /// Current parameters
    pub current_parameters: Option<Array1<T>>,

    /// Velocity/momentum state
    pub velocity: Option<Array1<T>>,

    /// Adaptive learning rate state
    pub adaptive_state: Option<AdaptiveState<T>>,

    /// Last update timestamp
    pub last_update: SystemTime,

    /// Optimization statistics
    pub statistics: OptimizationStatistics<T>,
}

/// Adaptive optimizer state
#[derive(Debug, Clone)]
pub struct AdaptiveState<T: Float + Debug + Send + Sync + 'static> {
    /// First moment estimate (Adam, etc.)
    pub first_moment: Option<Array1<T>>,

    /// Second moment estimate (Adam, etc.)
    pub second_moment: Option<Array1<T>>,

    /// Time step counter
    pub time_step: usize,

    /// Learning rate schedule
    pub learning_rate_schedule: LearningRateSchedule<T>,

    /// Bias correction terms
    pub bias_correction: BiasCorrection<T>,
}

/// Learning rate schedule
#[derive(Debug, Clone)]
pub struct LearningRateSchedule<T: Float + Debug + Send + Sync + 'static> {
    /// Schedule type
    pub schedule_type: ScheduleType,

    /// Base learning rate
    pub base_lr: T,

    /// Current learning rate
    pub current_lr: T,

    /// Schedule parameters
    pub parameters: HashMap<String, T>,

    /// Step count
    pub step_count: usize,
}

/// Bias correction for adaptive optimizers
#[derive(Debug, Clone)]
pub struct BiasCorrection<T: Float + Debug + Send + Sync + 'static> {
    /// First moment bias correction
    pub beta1_correction: T,

    /// Second moment bias correction
    pub beta2_correction: T,

    /// Bias correction power
    pub power: usize,
}

/// Problem type classification
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProblemType {
    /// Unconstrained optimization
    Unconstrained,
    /// Constrained optimization
    Constrained,
    /// Multi-objective optimization
    MultiObjective,
    /// Stochastic optimization
    Stochastic,
    /// Discrete optimization
    Discrete,
    /// Mixed-integer optimization
    MixedInteger,
}

impl Default for ProblemType {
    fn default() -> Self {
        ProblemType::Unconstrained
    }
}

/// Problem characteristics
#[derive(Debug, Clone)]
pub struct ProblemCharacteristics<T: Float + Debug + Send + Sync + 'static> {
    /// Problem dimensionality
    pub dimensionality: usize,

    /// Condition number estimate
    pub conditioning: T,

    /// Noise level estimate
    pub noise_level: T,

    /// Multimodality measure
    pub multimodality: T,

    /// Convexity measure
    pub convexity: T,

    /// Separability measure
    pub separability: T,

    /// Smoothness measure
    pub smoothness: T,

    /// Sparsity level
    pub sparsity: T,

    /// Problem type
    pub problem_type: ProblemType,

    /// Domain-specific features
    pub domain_features: HashMap<String, T>,
}

/// Resource constraints
#[derive(Debug, Clone)]
pub struct ResourceConstraints<T: Float + Debug + Send + Sync + 'static> {
    /// Maximum memory usage (MB)
    pub max_memory: T,

    /// Maximum compute resources
    pub max_compute: T,

    /// Maximum wall-clock time
    pub max_time: Duration,

    /// Maximum energy consumption
    pub max_energy: T,

    /// Available CPU cores
    pub available_cores: usize,

    /// Available GPU devices
    pub available_gpus: usize,

    /// Network bandwidth constraints
    pub network_bandwidth: T,

    /// Storage constraints
    pub storage_limit: T,
}

/// Time constraints
#[derive(Debug, Clone)]
pub struct TimeConstraints {
    /// Absolute deadline
    pub deadline: Option<SystemTime>,

    /// Time budget for optimization
    pub time_budget: Duration,

    /// Checkpoint frequency
    pub checkpoint_frequency: Duration,

    /// Timeout for individual steps
    pub step_timeout: Duration,

    /// Warm-up time allowance
    pub warmup_time: Duration,

    /// Cooldown time allowance
    pub cooldown_time: Duration,
}

/// Optimization phase tracking
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum OptimizationPhase {
    /// Initialization phase
    Initialization,
    /// Exploration phase
    Exploration,
    /// Exploitation phase
    Exploitation,
    /// Refinement phase
    Refinement,
    /// Convergence phase
    Convergence,
    /// Completion phase
    Completion,
    /// Error/failure phase
    Error,
}

/// State transition information
#[derive(Debug, Clone)]
pub struct StateTransition<T: Float + Debug + Send + Sync + 'static> {
    /// Source phase
    pub from_phase: OptimizationPhase,

    /// Target phase
    pub to_phase: OptimizationPhase,

    /// Transition timestamp
    pub transition_time: SystemTime,

    /// Trigger that caused transition
    pub trigger: String,

    /// Performance change
    pub performance_delta: T,

    /// Transition duration
    pub duration: Duration,

    /// Transition reason
    pub reason: TransitionReason,

    /// Confidence in transition decision
    pub confidence: T,
}

/// Transition reasons
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TransitionReason {
    /// Performance threshold reached
    PerformanceThreshold,
    /// Time constraint
    TimeConstraint,
    /// Resource constraint
    ResourceConstraint,
    /// Convergence detected
    ConvergenceDetected,
    /// Stagnation detected
    StagnationDetected,
    /// External trigger
    ExternalTrigger,
    /// Automatic progression
    AutomaticProgression,
    /// Error recovery
    ErrorRecovery,
}

/// Landscape features for problem analysis
#[derive(Debug, Clone)]
pub struct LandscapeFeatures<T: Float + Debug + Send + Sync + 'static> {
    /// Curvature information
    pub curvature_info: CurvatureInfo<T>,

    /// Gradient characteristics
    pub gradient_characteristics: GradientCharacteristics<T>,

    /// Local geometry features
    pub local_geometry: LocalGeometry<T>,

    /// Global structure features
    pub global_structure: GlobalStructure<T>,

    /// Noise characteristics
    pub noise_characteristics: NoiseCharacteristics<T>,

    /// Optimization trajectory features
    pub trajectory_features: TrajectoryFeatures<T>,

    /// Feature extraction timestamp
    pub extraction_time: SystemTime,

    /// Feature validity duration
    pub validity_duration: Duration,
}

/// Curvature information
#[derive(Debug, Clone)]
pub struct CurvatureInfo<T: Float + Debug + Send + Sync + 'static> {
    /// Mean curvature
    pub mean_curvature: T,

    /// Maximum curvature
    pub max_curvature: T,

    /// Condition number
    pub condition_number: T,

    /// Spectral gap
    pub spectral_gap: T,

    /// Eigenvalue distribution
    pub eigenvalue_distribution: EigenvalueDistribution<T>,

    /// Hessian approximation quality
    pub hessian_quality: T,
}

/// Eigenvalue distribution characteristics
#[derive(Debug, Clone)]
pub struct EigenvalueDistribution<T: Float + Debug + Send + Sync + 'static> {
    /// Largest eigenvalue
    pub largest_eigenvalue: T,

    /// Smallest eigenvalue
    pub smallest_eigenvalue: T,

    /// Mean eigenvalue
    pub mean_eigenvalue: T,

    /// Eigenvalue variance
    pub eigenvalue_variance: T,

    /// Number of negative eigenvalues
    pub negative_eigenvalues: usize,

    /// Spectral density
    pub spectral_density: Vec<T>,
}

/// Gradient characteristics
#[derive(Debug, Clone)]
pub struct GradientCharacteristics<T: Float + Debug + Send + Sync + 'static> {
    /// Current gradient norm
    pub gradient_norm: T,

    /// Gradient variance
    pub gradient_variance: T,

    /// Gradient correlation
    pub gradient_correlation: T,

    /// Directional derivative
    pub directional_derivative: T,

    /// Gradient predictability
    pub gradient_predictability: T,

    /// Gradient consistency
    pub gradient_consistency: T,

    /// Signal-to-noise ratio
    pub signal_to_noise_ratio: T,
}

/// Local geometry features
#[derive(Debug, Clone)]
pub struct LocalGeometry<T: Float + Debug + Send + Sync + 'static> {
    /// Local minima density
    pub local_minima_density: T,

    /// Saddle point density
    pub saddle_point_density: T,

    /// Basin width estimate
    pub basin_width: T,

    /// Escape difficulty
    pub escape_difficulty: T,

    /// Local convexity
    pub local_convexity: T,

    /// Local smoothness
    pub local_smoothness: T,

    /// Barrier height
    pub barrier_height: T,
}

/// Global structure features
#[derive(Debug, Clone)]
pub struct GlobalStructure<T: Float + Debug + Send + Sync + 'static> {
    /// Connectivity measure
    pub connectivity: T,

    /// Symmetry measure
    pub symmetry: T,

    /// Hierarchical structure
    pub hierarchical_structure: T,

    /// Fractal dimension
    pub fractal_dimension: T,

    /// Global convexity
    pub global_convexity: T,

    /// Scale separation
    pub scale_separation: T,

    /// Modularity
    pub modularity: T,
}

/// Noise characteristics
#[derive(Debug, Clone)]
pub struct NoiseCharacteristics<T: Float + Debug + Send + Sync + 'static> {
    /// Noise level
    pub noise_level: T,

    /// Noise type
    pub noise_type: NoiseType,

    /// Signal-to-noise ratio
    pub signal_to_noise_ratio: T,

    /// Noise correlation
    pub noise_correlation: T,

    /// Noise stationarity
    pub noise_stationarity: T,

    /// Noise predictability
    pub noise_predictability: T,

    /// Noise frequency spectrum
    pub frequency_spectrum: Vec<T>,
}

/// Noise types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoiseType {
    /// Gaussian white noise
    Gaussian,
    /// Uniform noise
    Uniform,
    /// Structured noise
    Structured,
    /// Adversarial noise
    Adversarial,
    /// Multiplicative noise
    Multiplicative,
    /// Time-correlated noise
    TimeCorrelated,
}

/// Trajectory features
#[derive(Debug, Clone)]
pub struct TrajectoryFeatures<T: Float + Debug + Send + Sync + 'static> {
    /// Path length
    pub path_length: T,

    /// Path efficiency
    pub path_efficiency: T,

    /// Oscillation measure
    pub oscillation: T,

    /// Convergence rate
    pub convergence_rate: T,

    /// Step size consistency
    pub step_consistency: T,

    /// Direction consistency
    pub direction_consistency: T,

    /// Progress rate
    pub progress_rate: T,
}

/// Optimization statistics
#[derive(Debug, Clone)]
pub struct OptimizationStatistics<T: Float + Debug + Send + Sync + 'static> {
    /// Total iterations performed
    pub total_iterations: usize,

    /// Total function evaluations
    pub total_evaluations: usize,

    /// Total gradient evaluations
    pub total_gradient_evaluations: usize,

    /// Best objective value achieved
    pub best_objective: T,

    /// Current objective value
    pub current_objective: T,

    /// Improvement rate
    pub improvement_rate: T,

    /// Convergence history
    pub convergence_history: VecDeque<ConvergenceRecord<T>>,

    /// Performance metrics
    pub performance_metrics: PerformanceMetrics<T>,

    /// Time statistics
    pub time_statistics: TimeStatistics,
}

/// Convergence record
#[derive(Debug, Clone)]
pub struct ConvergenceRecord<T: Float + Debug + Send + Sync + 'static> {
    /// Iteration number
    pub iteration: usize,

    /// Objective value
    pub objective: T,

    /// Gradient norm
    pub gradient_norm: T,

    /// Step size
    pub step_size: T,

    /// Timestamp
    pub timestamp: SystemTime,

    /// Convergence measure
    pub convergence_measure: T,
}

/// Performance metrics
#[derive(Debug, Clone)]
pub struct PerformanceMetrics<T: Float + Debug + Send + Sync + 'static> {
    /// Convergence speed
    pub convergence_speed: T,

    /// Final accuracy
    pub final_accuracy: T,

    /// Robustness measure
    pub robustness: T,

    /// Efficiency score
    pub efficiency: T,

    /// Reliability score
    pub reliability: T,

    /// Adaptability score
    pub adaptability: T,
}

/// Time statistics
#[derive(Debug, Clone)]
pub struct TimeStatistics {
    /// Total optimization time
    pub total_time: Duration,

    /// Average iteration time
    pub average_iteration_time: Duration,

    /// Time per function evaluation
    pub time_per_evaluation: Duration,

    /// Setup time
    pub setup_time: Duration,

    /// Cleanup time
    pub cleanup_time: Duration,

    /// Idle time
    pub idle_time: Duration,
}

/// Computational budget tracking
#[derive(Debug, Clone)]
pub struct ComputationalBudget {
    /// Maximum function evaluations
    pub max_evaluations: usize,

    /// Used function evaluations
    pub used_evaluations: usize,

    /// Maximum wall-clock time
    pub max_time: Duration,

    /// Elapsed time
    pub elapsed_time: Duration,

    /// Maximum memory usage (bytes)
    pub max_memory: usize,

    /// Current memory usage
    pub current_memory: usize,

    /// Available CPU cores
    pub available_cores: usize,

    /// Budget utilization rate
    pub utilization_rate: f64,
}

/// Convergence criteria
#[derive(Debug, Clone)]
pub struct ConvergenceCriteria<T: Float + Debug + Send + Sync + 'static> {
    /// Tolerance for function value changes
    pub function_tolerance: T,

    /// Tolerance for parameter changes
    pub parameter_tolerance: T,

    /// Tolerance for gradient norm
    pub gradient_tolerance: T,

    /// Maximum iterations
    pub max_iterations: usize,

    /// Stagnation threshold (consecutive iterations without improvement)
    pub stagnation_threshold: usize,

    /// Relative improvement threshold
    pub relative_improvement_threshold: T,

    /// Absolute improvement threshold
    pub absolute_improvement_threshold: T,

    /// Target objective value
    pub target_objective: Option<T>,
}

/// State manager for coordination
#[derive(Debug)]
pub struct StateManager<T: Float + Debug + Send + Sync + Debug> {
    /// Current optimization context
    pub current_context: OptimizationContext<T>,

    /// State transition history
    pub transition_history: VecDeque<StateTransition<T>>,

    /// Phase durations
    pub phase_durations: HashMap<OptimizationPhase, Duration>,

    /// State snapshots
    pub state_snapshots: VecDeque<StateSnapshot<T>>,

    /// State validation rules
    pub validation_rules: Vec<StateValidationRule<T>>,

    /// State persistence configuration
    pub persistence_config: StatePersistenceConfig,
}

/// State snapshot for checkpointing
#[derive(Debug, Clone)]
pub struct StateSnapshot<T: Float + Debug + Send + Sync + 'static> {
    /// Snapshot timestamp
    pub timestamp: SystemTime,

    /// Optimization state
    pub state: OptimizationState<T>,

    /// Performance metrics at snapshot
    pub metrics: PerformanceMetrics<T>,

    /// Snapshot reason
    pub reason: SnapshotReason,

    /// Snapshot size (bytes)
    pub size: usize,

    /// Snapshot validation hash
    pub validation_hash: u64,
}

/// Snapshot reasons
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SnapshotReason {
    /// Periodic checkpoint
    Periodic,
    /// Phase transition
    PhaseTransition,
    /// Performance milestone
    PerformanceMilestone,
    /// Error recovery point
    ErrorRecovery,
    /// User requested
    UserRequested,
    /// Automatic backup
    AutomaticBackup,
}

/// State validation rule
pub struct StateValidationRule<T: Float + Debug + Send + Sync + Debug> {
    /// Rule name
    pub name: String,

    /// Rule description
    pub description: String,

    /// Validation function
    pub validator: Box<dyn Fn(&OptimizationContext<T>) -> Result<bool> + Send + Sync>,

    /// Rule severity
    pub severity: ValidationSeverity,

    /// Enabled flag
    pub enabled: bool,
}

impl<T: Float + Debug + Send + Sync + 'static> std::fmt::Debug for StateValidationRule<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StateValidationRule")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("validator", &"<closure>")
            .field("severity", &self.severity)
            .field("enabled", &self.enabled)
            .finish()
    }
}

/// Validation severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidationSeverity {
    /// Warning level
    Warning,
    /// Error level
    Error,
    /// Critical level
    Critical,
}

/// State persistence configuration
#[derive(Debug, Clone)]
pub struct StatePersistenceConfig {
    /// Enable state persistence
    pub enabled: bool,

    /// Persistence interval
    pub persistence_interval: Duration,

    /// Maximum snapshots to keep
    pub max_snapshots: usize,

    /// Compression enabled
    pub compression_enabled: bool,

    /// Storage path
    pub storage_path: String,

    /// Encryption enabled
    pub encryption_enabled: bool,
}

// Implementation of StateManager
impl<T: Float + Debug + Send + Sync + 'static> StateManager<T> {
    /// Create a new state manager
    pub fn new(initial_context: OptimizationContext<T>) -> Self {
        Self {
            current_context: initial_context,
            transition_history: VecDeque::new(),
            phase_durations: HashMap::new(),
            state_snapshots: VecDeque::new(),
            validation_rules: Vec::new(),
            persistence_config: StatePersistenceConfig::default(),
        }
    }

    /// Update the current context
    pub fn update_context(&mut self, new_context: OptimizationContext<T>) -> Result<()> {
        // Validate the new context
        self.validate_context(&new_context)?;

        // Record transition if phase changed
        if new_context.current_phase != self.current_context.current_phase {
            let transition = StateTransition {
                from_phase: self.current_context.current_phase,
                to_phase: new_context.current_phase,
                transition_time: SystemTime::now(),
                trigger: "context_update".to_string(),
                performance_delta: T::zero(), // Would be computed from actual performance
                duration: Duration::from_secs(0),
                reason: TransitionReason::AutomaticProgression,
                confidence: scirs2_core::numeric::NumCast::from(1.0).unwrap_or_else(|| T::zero()),
            };

            self.record_transition(transition)?;
        }

        self.current_context = new_context;
        Ok(())
    }

    /// Record a state transition
    pub fn record_transition(&mut self, transition: StateTransition<T>) -> Result<()> {
        self.transition_history.push_back(transition.clone());

        // Update phase duration tracking
        if let Some(last_transition) = self.transition_history.iter().rev().nth(1) {
            if last_transition.to_phase == transition.from_phase {
                let duration = transition.transition_time
                    .duration_since(last_transition.transition_time)
                    .unwrap_or(Duration::from_secs(0));

                *self.phase_durations.entry(transition.from_phase).or_insert(Duration::from_secs(0)) += duration;
            }
        }

        // Limit history size
        if self.transition_history.len() > 1000 {
            self.transition_history.pop_front();
        }

        Ok(())
    }

    /// Create a state snapshot
    pub fn create_snapshot(&mut self, reason: SnapshotReason) -> Result<()> {
        let snapshot = StateSnapshot {
            timestamp: SystemTime::now(),
            state: self.current_context.state.clone(),
            metrics: self.current_context.state.statistics.performance_metrics.clone(),
            reason,
            size: std::mem::size_of_val(&self.current_context.state),
            validation_hash: self.compute_state_hash(&self.current_context.state)?,
        };

        self.state_snapshots.push_back(snapshot);

        // Limit snapshot storage
        if self.state_snapshots.len() > self.persistence_config.max_snapshots {
            self.state_snapshots.pop_front();
        }

        Ok(())
    }

    /// Restore from a snapshot
    pub fn restore_from_snapshot(&mut self, snapshot_index: usize) -> Result<()> {
        if let Some(snapshot) = self.state_snapshots.get(snapshot_index) {
            // Validate snapshot integrity
            let current_hash = self.compute_state_hash(&snapshot.state)?;
            if current_hash != snapshot.validation_hash {
                return Err(OptimError::ComputationError("Snapshot validation failed".to_string()));
            }

            self.current_context.state = snapshot.state.clone();
            Ok(())
        } else {
            Err(OptimError::ComputationError("Snapshot not found".to_string()))
        }
    }

    /// Validate the current context
    pub fn validate_context(&self, context: &OptimizationContext<T>) -> Result<()> {
        for rule in &self.validation_rules {
            if rule.enabled {
                let is_valid = (rule.validator)(context)?;
                if !is_valid {
                    match rule.severity {
                        ValidationSeverity::Warning => {
                            eprintln!("Warning: {}", rule.description);
                        }
                        ValidationSeverity::Error => {
                            return Err(OptimError::ComputationError(format!("Validation error: {}", rule.description)));
                        }
                        ValidationSeverity::Critical => {
                            return Err(OptimError::ComputationError(format!("Critical validation error: {}", rule.description)));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Add a validation rule
    pub fn add_validation_rule(&mut self, rule: StateValidationRule<T>) {
        self.validation_rules.push(rule);
    }

    /// Get state statistics
    pub fn get_state_statistics(&self) -> StateStatistics<T> {
        StateStatistics {
            total_transitions: self.transition_history.len(),
            total_snapshots: self.state_snapshots.len(),
            current_phase: self.current_context.current_phase,
            time_in_current_phase: self.get_time_in_current_phase(),
            average_phase_duration: self.compute_average_phase_duration(),
            most_common_transition: self.get_most_common_transition(),
            _phantom: std::marker::PhantomData,
        }
    }

    // Helper methods

    fn compute_state_hash(&self, state: &OptimizationState<T>) -> Result<u64> {
        // Simple hash computation for state validation
        // In practice, would use a proper cryptographic hash
        let hash = state.current_iteration as u64
            ^ (state.current_loss.to_f64().unwrap_or(0.0) as u64)
            ^ state.last_update.duration_since(SystemTime::UNIX_EPOCH)
                .unwrap_or(Duration::from_secs(0)).as_secs();
        Ok(hash)
    }

    fn get_time_in_current_phase(&self) -> Duration {
        if let Some(last_transition) = self.transition_history.back() {
            if last_transition.to_phase == self.current_context.current_phase {
                return SystemTime::now()
                    .duration_since(last_transition.transition_time)
                    .unwrap_or(Duration::from_secs(0));
            }
        }
        Duration::from_secs(0)
    }

    fn compute_average_phase_duration(&self) -> Duration {
        if self.phase_durations.is_empty() {
            return Duration::from_secs(0);
        }

        let total_duration: Duration = self.phase_durations.values().sum();
        total_duration / self.phase_durations.len() as u32
    }

    fn get_most_common_transition(&self) -> Option<(OptimizationPhase, OptimizationPhase)> {
        let mut transition_counts: HashMap<(OptimizationPhase, OptimizationPhase), usize> = HashMap::new();

        for transition in &self.transition_history {
            *transition_counts.entry((transition.from_phase, transition.to_phase)).or_insert(0) += 1;
        }

        transition_counts.into_iter()
            .max_by_key(|(_, count)| *count)
            .map(|(transition, _)| transition)
    }
}

/// State statistics
#[derive(Debug, Clone)]
pub struct StateStatistics<T: Float + Debug + Send + Sync + 'static> {
    /// Total number of state transitions
    pub total_transitions: usize,

    /// Total number of snapshots
    pub total_snapshots: usize,

    /// Current optimization phase
    pub current_phase: OptimizationPhase,

    /// Time spent in current phase
    pub time_in_current_phase: Duration,

    /// Average phase duration
    pub average_phase_duration: Duration,

    /// Most common state transition
    pub most_common_transition: Option<(OptimizationPhase, OptimizationPhase)>,

    /// Phantom data for type parameter
    _phantom: std::marker::PhantomData<T>,
}

// Default implementations

impl<T: Float + Debug + Send + Sync + 'static> Default for OptimizationContext<T> {
    fn default() -> Self {
        Self {
            state: OptimizationState::default(),
            problem_characteristics: ProblemCharacteristics::default(),
            resource_constraints: ResourceConstraints::default(),
            time_constraints: TimeConstraints::default(),
            performance_history: Vec::new(),
            current_phase: OptimizationPhase::Initialization,
            landscape_features: None,
            dimensionality: 100,
            computational_budget: ComputationalBudget::default(),
            convergence_criteria: ConvergenceCriteria::default(),
            metadata: HashMap::new(),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for OptimizationState<T> {
    fn default() -> Self {
        Self {
            current_iteration: 0,
            current_loss: T::zero(),
            gradient_norm: T::zero(),
            step_size: scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()),
            convergence_measure: T::zero(),
            current_parameters: None,
            velocity: None,
            adaptive_state: None,
            last_update: SystemTime::now(),
            statistics: OptimizationStatistics::default(),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for ProblemCharacteristics<T> {
    fn default() -> Self {
        Self {
            dimensionality: 100,
            conditioning: scirs2_core::numeric::NumCast::from(10.0).unwrap_or_else(|| T::zero()),
            noise_level: scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()),
            multimodality: scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()),
            convexity: scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()),
            separability: scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()),
            smoothness: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
            sparsity: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
            problem_type: ProblemType::NonConvex,
            domain_features: HashMap::new(),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for ResourceConstraints<T> {
    fn default() -> Self {
        Self {
            max_memory: scirs2_core::numeric::NumCast::from(8192.0).unwrap_or_else(|| T::zero()), // 8GB
            max_compute: scirs2_core::numeric::NumCast::from(1.0).unwrap_or_else(|| T::zero()),
            max_time: Duration::from_secs(3600), // 1 hour
            max_energy: scirs2_core::numeric::NumCast::from(1000.0).unwrap_or_else(|| T::zero()),
            available_cores: num_cpus::get(),
            available_gpus: 0,
            network_bandwidth: scirs2_core::numeric::NumCast::from(1000.0).unwrap_or_else(|| T::zero()), // 1Gbps
            storage_limit: scirs2_core::numeric::NumCast::from(100000.0).unwrap_or_else(|| T::zero()), // 100GB
        }
    }
}

impl Default for TimeConstraints {
    fn default() -> Self {
        Self {
            deadline: None,
            time_budget: Duration::from_secs(3600), // 1 hour
            checkpoint_frequency: Duration::from_secs(300), // 5 minutes
            step_timeout: Duration::from_secs(60), // 1 minute
            warmup_time: Duration::from_secs(60),
            cooldown_time: Duration::from_secs(30),
        }
    }
}

impl Default for ComputationalBudget {
    fn default() -> Self {
        Self {
            max_evaluations: 10000,
            used_evaluations: 0,
            max_time: Duration::from_secs(3600), // 1 hour
            elapsed_time: Duration::from_secs(0),
            max_memory: 1024 * 1024 * 1024, // 1GB
            current_memory: 0,
            available_cores: num_cpus::get(),
            utilization_rate: 0.0,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for ConvergenceCriteria<T> {
    fn default() -> Self {
        Self {
            function_tolerance: scirs2_core::numeric::NumCast::from(1e-6).unwrap_or_else(|| T::zero()),
            parameter_tolerance: scirs2_core::numeric::NumCast::from(1e-8).unwrap_or_else(|| T::zero()),
            gradient_tolerance: scirs2_core::numeric::NumCast::from(1e-6).unwrap_or_else(|| T::zero()),
            max_iterations: 1000,
            stagnation_threshold: 50,
            relative_improvement_threshold: scirs2_core::numeric::NumCast::from(1e-4).unwrap_or_else(|| T::zero()),
            absolute_improvement_threshold: scirs2_core::numeric::NumCast::from(1e-6).unwrap_or_else(|| T::zero()),
            target_objective: None,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for OptimizationStatistics<T> {
    fn default() -> Self {
        Self {
            total_iterations: 0,
            total_evaluations: 0,
            total_gradient_evaluations: 0,
            best_objective: T::infinity(),
            current_objective: T::infinity(),
            improvement_rate: T::zero(),
            convergence_history: VecDeque::new(),
            performance_metrics: PerformanceMetrics::default(),
            time_statistics: TimeStatistics::default(),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for PerformanceMetrics<T> {
    fn default() -> Self {
        Self {
            convergence_speed: T::zero(),
            final_accuracy: T::zero(),
            robustness: T::zero(),
            efficiency: T::zero(),
            reliability: T::zero(),
            adaptability: T::zero(),
        }
    }
}

impl Default for TimeStatistics {
    fn default() -> Self {
        Self {
            total_time: Duration::from_secs(0),
            average_iteration_time: Duration::from_secs(0),
            time_per_evaluation: Duration::from_secs(0),
            setup_time: Duration::from_secs(0),
            cleanup_time: Duration::from_secs(0),
            idle_time: Duration::from_secs(0),
        }
    }
}

impl Default for StatePersistenceConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            persistence_interval: Duration::from_secs(300), // 5 minutes
            max_snapshots: 10,
            compression_enabled: true,
            storage_path: "/tmp/optimization_state".to_string(),
            encryption_enabled: false,
        }
    }
}










#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_state_manager_creation() {
        let context = OptimizationContext::<f32>::default();
        let manager = StateManager::new(context);
        assert_eq!(manager.current_context.current_phase, OptimizationPhase::Initialization);
    }

    #[test]
    fn test_state_transition() {
        let context = OptimizationContext::<f32>::default();
        let mut manager = StateManager::new(context);

        let transition = StateTransition {
            from_phase: OptimizationPhase::Initialization,
            to_phase: OptimizationPhase::Exploration,
            transition_time: SystemTime::now(),
            trigger: "test".to_string(),
            performance_delta: 0.1,
            duration: Duration::from_secs(1),
            reason: TransitionReason::AutomaticProgression,
            confidence: 0.9,
        };

        assert!(manager.record_transition(transition).is_ok());
        assert_eq!(manager.transition_history.len(), 1);
    }

    #[test]
    fn test_state_snapshot() {
        let context = OptimizationContext::<f32>::default();
        let mut manager = StateManager::new(context);

        assert!(manager.create_snapshot(SnapshotReason::Periodic).is_ok());
        assert_eq!(manager.state_snapshots.len(), 1);
    }

    #[test]
    fn test_optimization_context_default() {
        let context = OptimizationContext::<f64>::default();
        assert_eq!(context.dimensionality, 100);
        assert_eq!(context.current_phase, OptimizationPhase::Initialization);
        assert!(context.performance_history.is_empty());
    }
}