optirs-nas 0.3.2

OptiRS Neural Architecture Search and hyperparameter optimization
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
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
// Neural Architecture Search Configuration
//
// This module contains all configuration types, enums, and parameter definitions
// for the Neural Architecture Search system.

use crate::EvaluationMetric;
use scirs2_core::numeric::Float;
use std::collections::HashMap;
use std::fmt::Debug;
use std::time::Duration;

/// Neural Architecture Search configuration for optimizers
#[derive(Debug, Clone)]
pub struct NASConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Search strategy to use
    pub search_strategy: SearchStrategyType,

    /// Architecture search space
    pub search_space: SearchSpaceConfig,

    /// Performance evaluation configuration
    pub evaluation_config: EvaluationConfig<T>,

    /// Multi-objective optimization settings
    pub multi_objective_config: MultiObjectiveConfig<T>,

    /// Search budget (number of architectures to evaluate)
    pub search_budget: usize,

    /// Early stopping criteria
    pub early_stopping: EarlyStoppingConfig<T>,

    /// Enable progressive search
    pub progressive_search: bool,

    /// Population size for evolutionary/genetic algorithms
    pub population_size: usize,

    /// Enable architecture transfer learning
    pub enable_transfer_learning: bool,

    /// Architecture encoding strategy
    pub encoding_strategy: ArchitectureEncodingStrategy,

    /// Enable performance prediction
    pub enable_performance_prediction: bool,

    /// Search parallelization factor
    pub parallelization_factor: usize,

    /// Enable automated hyperparameter tuning
    pub auto_hyperparameter_tuning: bool,

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

/// Search strategy types
#[derive(Debug, Clone)]
pub enum SearchStrategyType {
    /// Random search baseline
    Random,

    /// Evolutionary/genetic algorithm search
    Evolutionary,

    /// Reinforcement learning-based search
    ReinforcementLearning,

    /// Differentiable architecture search (DARTS)
    Differentiable,

    /// Bayesian optimization
    BayesianOptimization,

    /// Progressive search
    Progressive,

    /// Multi-objective evolutionary algorithm
    MultiObjectiveEvolutionary,

    /// Neural predictor-based search
    NeuralPredictorBased,
}

/// Search space configuration
#[derive(Debug, Clone)]
pub struct SearchSpaceConfig {
    /// Available optimizer components
    pub components: Vec<OptimizerComponentConfig>,

    /// Connection patterns between components
    pub connection_patterns: Vec<ConnectionPatternType>,

    /// Learning rate schedule search space
    pub learning_rate_schedules: LearningRateScheduleSpace,

    /// Regularization technique search space
    pub regularization_techniques: RegularizationSpace,

    /// Adaptive mechanism search space
    pub adaptive_mechanisms: AdaptiveMechanismSpace,

    /// Memory usage constraints
    pub memory_constraints: MemoryConstraints,

    /// Computation constraints
    pub computation_constraints: ComputationConstraints,

    /// Component types to include in search
    pub component_types: Vec<ComponentType>,

    /// Maximum number of components
    pub max_components: usize,

    /// Minimum number of components
    pub min_components: usize,

    /// Maximum number of connections
    pub max_connections: usize,
}

/// Optimizer component configuration for search
#[derive(Debug, Clone)]
pub struct OptimizerComponentConfig {
    /// Component type
    pub component_type: ComponentType,

    /// Hyperparameter search ranges
    pub hyperparameter_ranges: HashMap<String, ParameterRange>,

    /// Component complexity score
    pub complexity_score: f64,

    /// Memory requirement estimate
    pub memory_requirement: usize,

    /// Computational cost estimate
    pub computational_cost: f64,

    /// Compatibility constraints
    pub compatibility_constraints: Vec<CompatibilityConstraint>,
}

/// Architecture constraints for components
#[derive(Debug, Clone, Default)]
pub struct ArchitectureConstraints {
    /// Minimum parameter count
    pub min_parameters: Option<usize>,
    /// Maximum parameter count
    pub max_parameters: Option<usize>,
    /// Required input dimensions
    pub input_dimensions: Vec<usize>,
    /// Output dimension constraints
    pub output_dimensions: Vec<usize>,
    /// Compatibility rules
    pub compatibility_rules: Vec<String>,
}

/// Component type configuration
#[derive(Debug, Clone)]
pub struct ComponentTypeConfig {
    /// Component type name
    pub name: String,
    /// Available parameters
    pub parameters: Vec<String>,
    /// Default configuration
    pub defaults: HashMap<String, String>,
    /// Whether this component type is enabled
    pub enabled: bool,
    /// Probability of selection during search
    pub probability: f64,
    /// Hyperparameter ranges for this component
    pub hyperparameter_ranges: HashMap<String, ParameterRange>,
    /// Dependencies on other components
    pub dependencies: Vec<String>,
    /// Component type
    pub component_type: ComponentType,
    /// Architecture constraints
    pub constraints: ArchitectureConstraints,
}

/// Component types for optimizers
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ComponentType {
    /// Gradient computation methods
    GradientComputation,

    /// Momentum techniques
    Momentum,

    /// Adaptive learning rate methods
    AdaptiveLearningRate,

    /// Regularization techniques
    Regularization,

    /// Normalization methods
    Normalization,

    /// Second-order methods
    SecondOrder,

    /// Preconditioning techniques
    Preconditioning,

    /// Learning rate scheduling
    LearningRateScheduling,

    /// Gradient clipping methods
    GradientClipping,

    /// Memory management
    MemoryManagement,

    /// Convergence acceleration
    ConvergenceAcceleration,

    /// Specific optimizer types
    SGD,
    Adam,
    AdamW,
    RMSprop,
    AdaGrad,
    AdaDelta,
    Nesterov,
    LRScheduler,
    BatchNorm,
    Dropout,
    LAMB,
    LARS,
    Lion,
    RAdam,
    Lookahead,
    SAM,
    LBFGS,
    SparseAdam,
    GroupedAdam,
    MAML,
    Reptile,
    MetaSGD,
    ConstantLR,
    ExponentialLR,
    StepLR,
    CosineAnnealingLR,
    OneCycleLR,
    CyclicLR,
    L1Regularizer,
    L2Regularizer,
    ElasticNetRegularizer,
    DropoutRegularizer,
    WeightDecay,
    AdaptiveLR,
    AdaptiveMomentum,
    AdaptiveRegularization,
    LSTMOptimizer,
    TransformerOptimizer,
    AttentionOptimizer,

    /// Custom components
    Custom(String),
}

/// Parameter range for hyperparameter search
#[derive(Debug, Clone)]
pub enum ParameterRange {
    /// Continuous range [min, max]
    Continuous(f64, f64),

    /// Discrete set of values
    Discrete(Vec<f64>),

    /// Integer range [min, max]
    Integer(i32, i32),

    /// Boolean choice
    Boolean,

    /// Categorical choice
    Categorical(Vec<String>),

    /// Log-uniform distribution
    LogUniform(f64, f64),
}

/// Connection pattern types
#[derive(Debug, Clone)]
pub enum ConnectionPatternType {
    /// Sequential connection
    Sequential,

    /// Parallel branches
    Parallel,

    /// Skip connections
    SkipConnection,

    /// Dense connections
    DenseConnection,

    /// Residual connections
    ResidualConnection,

    /// Attention-based connections
    AttentionConnection,

    /// Highway connections
    HighwayConnection,

    /// Squeeze-and-excitation connections
    SqueezeExcitationConnection,

    /// Custom connection patterns
    Custom(String),
}

/// Learning rate schedule search space
#[derive(Debug, Clone)]
pub struct LearningRateScheduleSpace {
    /// Available schedule types
    pub schedule_types: Vec<ScheduleType>,

    /// Initial learning rate range
    pub initial_lr_range: ParameterRange,

    /// Schedule-specific parameters
    pub schedule_parameters: HashMap<ScheduleType, HashMap<String, ParameterRange>>,
}

/// Schedule types for learning rate
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ScheduleType {
    Constant,
    StepDecay,
    ExponentialDecay,
    CosineAnnealing,
    CyclicalLR,
    OneCycleLR,
    ReduceOnPlateau,
    WarmupLinear,
    WarmupCosine,
    Custom(String),
}

/// Regularization search space
#[derive(Debug, Clone)]
pub struct RegularizationSpace {
    /// Available regularization techniques
    pub techniques: Vec<RegularizationTechnique>,

    /// Regularization strength ranges
    pub strength_ranges: HashMap<RegularizationTechnique, ParameterRange>,

    /// Combination strategies
    pub combination_strategies: Vec<String>,
}

/// Regularization techniques
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RegularizationTechnique {
    L1,
    L2,
    Dropout,
    DropConnect,
    BatchNormalization,
    LayerNormalization,
    GroupNormalization,
    SpectralNormalization,
    WeightDecay,
    EarlyStopping,
    Custom(String),
}

/// Adaptive mechanism search space
#[derive(Debug, Clone)]
pub struct AdaptiveMechanismSpace {
    /// Available adaptation strategies
    pub adaptation_strategies: Vec<AdaptationStrategy>,

    /// Adaptation parameters
    pub adaptation_parameters: HashMap<AdaptationStrategy, HashMap<String, ParameterRange>>,

    /// Adaptation frequency options
    pub adaptation_frequencies: Vec<usize>,
}

/// Adaptation strategies
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum AdaptationStrategy {
    PerformanceBased,
    GradientBased,
    LossBased,
    TimeBased,
    HybridAdaptation,
    Custom(String),
}

/// Memory constraints for architecture search
#[derive(Debug, Clone)]
pub struct MemoryConstraints {
    /// Maximum memory usage (bytes)
    pub max_memory_bytes: usize,

    /// Memory usage per component limits
    pub component_memory_limits: HashMap<ComponentType, usize>,

    /// Enable memory optimization
    pub enable_memory_optimization: bool,

    /// Memory allocation strategy
    pub allocation_strategy: MemoryAllocationStrategy,
}

/// Memory allocation strategies
#[derive(Debug, Clone)]
pub enum MemoryAllocationStrategy {
    Static,
    Dynamic,
    Adaptive,
    Lazy,
}

/// Computation constraints
#[derive(Debug, Clone)]
pub struct ComputationConstraints {
    /// Maximum computational cost
    pub max_computational_cost: f64,

    /// Cost per component limits
    pub component_cost_limits: HashMap<ComponentType, f64>,

    /// Enable computation optimization
    pub enable_computation_optimization: bool,

    /// Parallelization constraints
    pub parallelization_constraints: ParallelizationConstraints,
}

/// Parallelization constraints
#[derive(Debug, Clone)]
pub struct ParallelizationConstraints {
    /// Maximum parallel workers
    pub max_workers: usize,

    /// Minimum batch size for parallelization
    pub min_batch_size: usize,

    /// Enable SIMD optimization
    pub enable_simd: bool,

    /// Enable GPU acceleration
    pub enable_gpu: bool,
}

/// Compatibility constraint between components
#[derive(Debug, Clone)]
pub struct CompatibilityConstraint {
    /// Constraint type
    pub constraint_type: CompatibilityType,

    /// Target components
    pub target_components: Vec<ComponentType>,

    /// Constraint condition
    pub condition: ConstraintCondition,
}

/// Compatibility constraint types
#[derive(Debug, Clone)]
pub enum CompatibilityType {
    /// Components must be used together
    Requires,

    /// Components cannot be used together
    Excludes,

    /// Components have conditional compatibility
    Conditional,

    /// Components have version requirements
    VersionRequirement,

    /// Components have parameter constraints
    ParameterConstraint,

    /// Custom compatibility rules
    Custom(String),
}

/// Constraint conditions
#[derive(Debug, Clone)]
pub enum ConstraintCondition {
    /// Always applies
    Always,

    /// Never applies
    Never,

    /// Applies under certain parameter conditions
    ParameterCondition(ParameterCondition),

    /// Applies based on architecture properties
    ArchitectureCondition(String),

    /// Custom condition logic
    Custom(String),
}

/// Parameter-based constraint conditions
#[derive(Debug, Clone)]
pub enum ParameterCondition {
    /// Parameter equals specific value
    Equals(String, f64),

    /// Parameter is greater than value
    GreaterThan(String, f64),

    /// Parameter is less than value
    LessThan(String, f64),

    /// Parameter is within range
    InRange(String, f64, f64),

    /// Parameter is in set of values
    InSet(String, Vec<f64>),

    /// Complex boolean conditions
    BooleanExpression(String),
}

/// Performance evaluation configuration
#[derive(Debug, Clone)]
pub struct EvaluationConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Evaluation metrics to use
    pub metrics: Vec<EvaluationMetric>,

    /// Benchmark datasets
    pub benchmark_datasets: Vec<BenchmarkDataset>,

    /// Evaluation budget (time/iterations)
    pub evaluation_budget: EvaluationBudget,

    /// Statistical testing configuration
    pub statistical_testing: StatisticalTestingConfig,

    /// Cross-validation settings
    pub cross_validation_folds: usize,

    /// Enable early stopping during evaluation
    pub enable_early_stopping: bool,

    /// Evaluation parallelization
    pub parallelization_factor: usize,

    /// Problem domain specification
    pub problem_domains: Vec<ProblemDomain>,

    /// Resource limits for evaluation
    pub resource_limits: HashMap<ResourceType, T>,
}

/// Problem domains for evaluation
#[derive(Debug, Clone)]
pub enum ProblemDomain {
    Classification,
    Regression,
    Reinforcement,
    GenerativeModeling,
    SequenceModeling,
    ComputerVision,
    NaturalLanguageProcessing,
    TimeSeriesForecasting,
    Custom(String),
}

/// Resource types for evaluation limits
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResourceType {
    Memory,
    CPUTime,
    GPUTime,
    NetworkBandwidth,
    StorageSpace,
}

/// Benchmark dataset configuration
#[derive(Debug, Clone)]
pub struct BenchmarkDataset {
    /// Dataset name
    pub name: String,

    /// Dataset path or URL
    pub path: String,

    /// Dataset characteristics
    pub characteristics: DatasetCharacteristics,

    /// Problem type
    pub problem_type: ProblemType,

    /// Evaluation weight
    pub weight: f64,

    /// Enable data augmentation
    pub enable_augmentation: bool,
}

/// Dataset characteristics
#[derive(Debug, Clone)]
pub struct DatasetCharacteristics {
    /// Number of samples
    pub num_samples: usize,

    /// Number of features
    pub num_features: usize,

    /// Number of classes (for classification)
    pub num_classes: Option<usize>,

    /// Dataset size category
    pub size_category: DatasetSizeCategory,

    /// Feature correlation structure
    pub correlation_structure: CorrelationStructure,

    /// Noise level estimate
    pub noise_level: f64,

    /// Imbalance ratio (for classification)
    pub imbalance_ratio: Option<f64>,
}

/// Problem types for evaluation
#[derive(Debug, Clone)]
pub enum ProblemType {
    BinaryClassification,
    MultiClassClassification,
    Regression,
    MultiTaskLearning,
    MetaLearning,
    TransferLearning,
    FewShotLearning,
    Custom(String),
}

/// Dataset size categories
#[derive(Debug, Clone)]
pub enum DatasetSizeCategory {
    Small,     // < 1K samples
    Medium,    // 1K - 100K samples
    Large,     // 100K - 1M samples
    VeryLarge, // > 1M samples
}

/// Correlation structure in datasets
#[derive(Debug, Clone)]
pub enum CorrelationStructure {
    Independent,
    LowCorrelation,
    ModerateCorrelation,
    HighCorrelation,
    BlockStructure,
    Hierarchical,
}

/// Evaluation budget configuration
#[derive(Debug, Clone)]
pub struct EvaluationBudget {
    /// Maximum evaluation time per architecture
    pub max_time_per_architecture: Duration,

    /// Maximum number of training epochs
    pub max_epochs: usize,

    /// Maximum number of function evaluations
    pub max_function_evaluations: usize,

    /// Early stopping patience
    pub early_stopping_patience: usize,

    /// Resource allocation per evaluation
    pub resource_allocation: ResourceAllocation,
}

/// Resource allocation for evaluations
#[derive(Debug, Clone)]
pub struct ResourceAllocation {
    /// CPU cores allocated
    pub cpu_cores: usize,

    /// Memory allocated (GB)
    pub memory_gb: f64,

    /// GPU devices allocated
    pub gpu_devices: usize,

    /// Storage space allocated (GB)
    pub storage_gb: f64,
}

/// Statistical testing configuration
#[derive(Debug, Clone)]
pub struct StatisticalTestingConfig {
    /// Significance level (alpha)
    pub significance_level: f64,

    /// Statistical test type
    pub test_type: StatisticalTestType,

    /// Multiple comparison correction
    pub multiple_comparison_correction: MultipleComparisonCorrection,

    /// Minimum effect size
    pub min_effect_size: f64,

    /// Bootstrap samples for confidence intervals
    pub bootstrap_samples: usize,
}

/// Statistical test types
#[derive(Debug, Clone)]
pub enum StatisticalTestType {
    TTest,
    WilcoxonRankSum,
    KruskalWallis,
    FriedmanTest,
    Bootstrap,
}

/// Multiple comparison correction methods
#[derive(Debug, Clone)]
pub enum MultipleComparisonCorrection {
    None,
    Bonferroni,
    BenjaminiHochberg,
    BenjaminiYekutieli,
    Holm,
}

/// Multi-objective optimization configuration
#[derive(Debug, Clone)]
pub struct MultiObjectiveConfig<T: Float + Debug + Send + Sync + 'static> {
    /// List of objectives to optimize
    pub objectives: Vec<ObjectiveConfig<T>>,

    /// Multi-objective algorithm to use
    pub algorithm: MultiObjectiveAlgorithm,

    /// User preferences for trade-offs.
    ///
    /// **Not yet consulted by any optimizer.** Interactive / a-priori preference
    /// articulation is not implemented: `NSGA2`, `NSGA3`, `MOEADOptimizer` and
    /// `WeightedSum` all ignore this field. Per-objective trade-offs that *are*
    /// honoured must be expressed through [`ObjectiveConfig::weight`] and
    /// [`ObjectiveConfig::direction`], which the weighted-sum scalarizer and the
    /// dominance comparisons do read.
    pub user_preferences: Option<UserPreferences<T>>,

    /// Diversity promotion strategy
    pub diversity_strategy: DiversityStrategy,

    /// Constraint handling method.
    ///
    /// **Not yet consulted by any optimizer.** Constrained multi-objective search
    /// (penalty functions, feasibility rules, epsilon-constraint) is not
    /// implemented; every optimizer in [`crate::multi_objective`] treats all
    /// candidates as feasible and leaves `ParetoSolution::constraint_violations`
    /// empty. Hard resource limits are enforced separately, by
    /// [`crate::nas_engine::resources::ResourceMonitor`].
    pub constraint_handling: ConstraintHandlingMethod,
}

/// Objective configuration
#[derive(Debug, Clone)]
pub struct ObjectiveConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Objective name
    pub name: String,

    /// Objective type
    pub objective_type: ObjectiveType,

    /// Optimization direction
    pub direction: OptimizationDirection,

    /// Objective weight
    pub weight: T,

    /// Objective priority
    pub priority: ObjectivePriority,

    /// Normalization bounds
    pub normalization_bounds: Option<(T, T)>,
}

/// Objective types
#[derive(Debug, Clone)]
pub enum ObjectiveType {
    Accuracy,
    Loss,
    TrainingTime,
    InferenceTime,
    MemoryUsage,
    EnergyConsumption,
    ModelSize,
    Robustness,
    Fairness,
    Performance,
    Efficiency,
    Interpretability,
    Privacy,
    Sustainability,
    Cost,
    Custom(String),
}

/// Optimization directions
#[derive(Debug, Clone)]
pub enum OptimizationDirection {
    Minimize,
    Maximize,
}

/// Objective priorities
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ObjectivePriority {
    Low,
    Medium,
    High,
    Critical,
}

/// Multi-objective algorithms
#[derive(Debug, Clone)]
pub enum MultiObjectiveAlgorithm {
    NSGA2,
    NSGA3,
    MOEAD,
    SPEA2,
    PAES,
    WeightedSum,
    EpsilonConstraint,
    GoalProgramming,
    Custom(String),
}

/// User preferences for multi-objective optimization
#[derive(Debug, Clone)]
pub struct UserPreferences<T: Float + Debug + Send + Sync + 'static> {
    /// Preference type
    pub preference_type: PreferenceType<T>,

    /// Reference point (for reference point methods)
    pub reference_point: Option<Vec<T>>,

    /// Aspiration levels
    pub aspiration_levels: Option<Vec<T>>,

    /// Reservation levels
    pub reservation_levels: Option<Vec<T>>,
}

/// Preference specification types
#[derive(Debug, Clone)]
pub enum PreferenceType<T: Float + Debug + Send + Sync + 'static> {
    WeightVector(Vec<T>),
    ReferencePoint(Vec<T>),
    GoalVector(Vec<T>),
    RankingOrder(Vec<usize>),
    PairwiseComparison(Vec<(usize, usize)>),
}

/// Diversity promotion strategies
#[derive(Debug, Clone)]
pub enum DiversityStrategy {
    Crowding,
    Sharing,
    Clearing,
    Clustering,
    Novelty,
    Custom(String),
}

/// Constraint handling methods
#[derive(Debug, Clone)]
pub enum ConstraintHandlingMethod {
    PenaltyFunction,
    DeathPenalty,
    Repair,
    Decoder,
    PreserveFeasibility,
    Custom(String),
}

/// Early stopping configuration
#[derive(Debug, Clone)]
pub struct EarlyStoppingConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Enable early stopping
    pub enabled: bool,

    /// Patience (number of generations without improvement)
    pub patience: usize,

    /// Minimum improvement threshold
    pub min_improvement: T,

    /// Convergence detection strategy
    pub convergence_strategy: ConvergenceDetectionStrategy,

    /// Minimum number of generations before stopping
    pub min_generations: usize,

    /// Metric to monitor for early stopping
    pub metric: EvaluationMetric,

    /// Target performance value
    pub target_performance: Option<T>,

    /// Convergence detection strategy
    pub convergence_detection: ConvergenceDetectionStrategy,
}

/// Convergence detection strategies
#[derive(Debug, Clone)]
pub enum ConvergenceDetectionStrategy {
    BestScore,
    AverageScore,
    PopulationDiversity,
    ParetoFrontStability,
    NoImprovement,
    Custom(String),
}

/// Architecture encoding strategies
#[derive(Debug, Clone)]
pub enum ArchitectureEncodingStrategy {
    /// Direct parameter encoding
    Direct,

    /// Graph-based encoding
    Graph,

    /// String-based encoding
    String,

    /// Binary encoding
    Binary,

    /// Real-valued encoding
    RealValued,

    /// Hierarchical encoding
    Hierarchical,

    /// Neural encoding (using neural networks)
    Neural,

    /// Hybrid encoding strategies
    Hybrid,

    /// Custom encoding
    Custom(String),
}

/// Resource constraints for NAS
#[derive(Debug, Clone)]
pub struct ResourceConstraints<T: Float + Debug + Send + Sync + 'static> {
    /// Hardware resource limits
    pub hardware_resources: HardwareResources,

    /// Time constraints
    pub time_constraints: TimeConstraints,

    /// Energy constraints
    pub energy_constraints: Option<T>,

    /// Cost constraints
    pub cost_constraints: Option<T>,

    /// Resource violation handling
    pub violation_handling: ResourceViolationHandling,

    /// Maximum memory in GB
    pub max_memory_gb: T,

    /// Maximum computation hours
    pub max_computation_hours: T,

    /// Maximum energy in kWh
    pub max_energy_kwh: T,

    /// Maximum cost in USD
    pub max_cost_usd: T,

    /// Enable resource monitoring
    pub enable_monitoring: bool,
}

/// Hardware resource specifications
#[derive(Debug, Clone)]
pub struct HardwareResources {
    /// Maximum memory usage (GB)
    pub max_memory_gb: f64,

    /// Maximum CPU cores
    pub max_cpu_cores: usize,

    /// Maximum GPU devices
    pub max_gpu_devices: usize,

    /// Maximum storage space (GB)
    pub max_storage_gb: f64,

    /// Network bandwidth limits (MB/s)
    pub max_network_bandwidth: f64,

    /// Enable cloud resource scaling
    pub enable_cloud_scaling: bool,

    /// Cloud resource budget
    pub cloud_budget: Option<f64>,

    /// CPU cores available
    pub cpu_cores: usize,

    /// RAM in GB
    pub ram_gb: u32,

    /// Number of GPUs
    pub num_gpus: usize,

    /// GPU memory in GB
    pub gpu_memory_gb: u32,

    /// Storage in GB
    pub storage_gb: u32,

    /// Network bandwidth in Mbps
    pub network_bandwidth_mbps: f32,
}

/// Time constraints for search
#[derive(Debug, Clone)]
pub struct TimeConstraints {
    /// Maximum total search time
    pub max_search_time: Duration,

    /// Maximum time per architecture evaluation
    pub max_evaluation_time: Duration,

    /// Search deadline
    pub search_deadline: Option<std::time::Instant>,

    /// Time budget allocation strategy
    pub budget_allocation: TimeBudgetAllocation,
}

/// Time budget allocation strategies
#[derive(Debug, Clone)]
pub enum TimeBudgetAllocation {
    Uniform,
    AdaptiveByComplexity,
    AdaptiveByPerformance,
    PriorityBased,
    Custom(String),
}

/// Resource violation handling strategies
#[derive(Debug, Clone)]
pub enum ResourceViolationHandling {
    /// Stop search immediately
    Abort,

    /// Skip violating architectures
    Skip,

    /// Scale down resources
    ScaleDown,

    /// Use approximation methods
    Approximate,

    /// Dynamic resource allocation
    Dynamic,

    /// Apply penalty to objective function
    Penalty,

    /// Custom handling
    Custom(String),
}

// Default implementations
impl<T: Float + Debug + Send + Sync + 'static> Default for NASConfig<T> {
    fn default() -> Self {
        Self {
            search_strategy: SearchStrategyType::Evolutionary,
            search_space: SearchSpaceConfig::default(),
            evaluation_config: EvaluationConfig::default(),
            multi_objective_config: MultiObjectiveConfig::default(),
            search_budget: 100,
            early_stopping: EarlyStoppingConfig::default(),
            progressive_search: false,
            population_size: 20,
            enable_transfer_learning: false,
            encoding_strategy: ArchitectureEncodingStrategy::Graph,
            enable_performance_prediction: false,
            parallelization_factor: 1,
            auto_hyperparameter_tuning: false,
            resource_constraints: ResourceConstraints::default(),
        }
    }
}

impl Default for SearchSpaceConfig {
    fn default() -> Self {
        Self {
            components: Vec::new(),
            connection_patterns: vec![
                ConnectionPatternType::Sequential,
                ConnectionPatternType::Parallel,
                ConnectionPatternType::SkipConnection,
            ],
            learning_rate_schedules: LearningRateScheduleSpace::default(),
            regularization_techniques: RegularizationSpace::default(),
            adaptive_mechanisms: AdaptiveMechanismSpace::default(),
            memory_constraints: MemoryConstraints::default(),
            computation_constraints: ComputationConstraints::default(),
            component_types: vec![ComponentType::SGD, ComponentType::Adam],
            max_components: 10,
            min_components: 1,
            max_connections: 20,
        }
    }
}

impl Default for LearningRateScheduleSpace {
    fn default() -> Self {
        Self {
            schedule_types: vec![
                ScheduleType::Constant,
                ScheduleType::StepDecay,
                ScheduleType::ExponentialDecay,
                ScheduleType::CosineAnnealing,
            ],
            initial_lr_range: ParameterRange::LogUniform(1e-5, 1e-1),
            schedule_parameters: HashMap::new(),
        }
    }
}

impl Default for RegularizationSpace {
    fn default() -> Self {
        Self {
            techniques: vec![
                RegularizationTechnique::L1,
                RegularizationTechnique::L2,
                RegularizationTechnique::Dropout,
                RegularizationTechnique::WeightDecay,
            ],
            strength_ranges: HashMap::new(),
            combination_strategies: Vec::new(),
        }
    }
}

impl Default for AdaptiveMechanismSpace {
    fn default() -> Self {
        Self {
            adaptation_strategies: vec![
                AdaptationStrategy::PerformanceBased,
                AdaptationStrategy::GradientBased,
                AdaptationStrategy::LossBased,
            ],
            adaptation_parameters: HashMap::new(),
            adaptation_frequencies: vec![1, 5, 10, 25, 50, 100],
        }
    }
}

impl Default for MemoryConstraints {
    fn default() -> Self {
        Self {
            max_memory_bytes: 32 * 1024 * 1024 * 1024, // 32GB
            component_memory_limits: HashMap::new(),
            enable_memory_optimization: true,
            allocation_strategy: MemoryAllocationStrategy::Dynamic,
        }
    }
}

impl Default for ComputationConstraints {
    fn default() -> Self {
        Self {
            max_computational_cost: 1000.0,
            component_cost_limits: HashMap::new(),
            enable_computation_optimization: true,
            parallelization_constraints: ParallelizationConstraints::default(),
        }
    }
}

impl Default for ParallelizationConstraints {
    fn default() -> Self {
        Self {
            max_workers: num_cpus::get(),
            min_batch_size: 32,
            enable_simd: true,
            enable_gpu: true,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for EvaluationConfig<T> {
    fn default() -> Self {
        Self {
            metrics: vec![EvaluationMetric::Accuracy, EvaluationMetric::TrainingTime],
            benchmark_datasets: Vec::new(),
            evaluation_budget: EvaluationBudget::default(),
            statistical_testing: StatisticalTestingConfig::default(),
            cross_validation_folds: 5,
            enable_early_stopping: true,
            parallelization_factor: 1,
            problem_domains: vec![ProblemDomain::Classification],
            resource_limits: HashMap::new(),
        }
    }
}

impl Default for EvaluationBudget {
    fn default() -> Self {
        Self {
            max_time_per_architecture: Duration::from_secs(300),
            max_epochs: 100,
            max_function_evaluations: 1000,
            early_stopping_patience: 10,
            resource_allocation: ResourceAllocation::default(),
        }
    }
}

impl Default for ResourceAllocation {
    fn default() -> Self {
        Self {
            cpu_cores: 4,
            memory_gb: 8.0,
            gpu_devices: 1,
            storage_gb: 10.0,
        }
    }
}

impl Default for StatisticalTestingConfig {
    fn default() -> Self {
        Self {
            significance_level: 0.05,
            test_type: StatisticalTestType::TTest,
            multiple_comparison_correction: MultipleComparisonCorrection::BenjaminiHochberg,
            min_effect_size: 0.1,
            bootstrap_samples: 1000,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for MultiObjectiveConfig<T> {
    fn default() -> Self {
        Self {
            objectives: Vec::new(),
            algorithm: MultiObjectiveAlgorithm::NSGA2,
            user_preferences: None,
            diversity_strategy: DiversityStrategy::Crowding,
            constraint_handling: ConstraintHandlingMethod::PenaltyFunction,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for EarlyStoppingConfig<T> {
    fn default() -> Self {
        Self {
            enabled: true,
            patience: 20,
            min_improvement: scirs2_core::numeric::NumCast::from(0.001)
                .unwrap_or_else(|| T::zero()),
            convergence_strategy: ConvergenceDetectionStrategy::BestScore,
            min_generations: 10,
            metric: EvaluationMetric::Accuracy,
            target_performance: None,
            convergence_detection: ConvergenceDetectionStrategy::NoImprovement,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static> Default for ResourceConstraints<T> {
    fn default() -> Self {
        Self {
            hardware_resources: HardwareResources::default(),
            time_constraints: TimeConstraints::default(),
            energy_constraints: None,
            cost_constraints: None,
            violation_handling: ResourceViolationHandling::Skip,
            max_memory_gb: scirs2_core::numeric::NumCast::from(32.0).unwrap_or_else(|| T::zero()),
            max_computation_hours: scirs2_core::numeric::NumCast::from(24.0)
                .unwrap_or_else(|| T::zero()),
            max_energy_kwh: scirs2_core::numeric::NumCast::from(100.0).unwrap_or_else(|| T::zero()),
            max_cost_usd: scirs2_core::numeric::NumCast::from(1000.0).unwrap_or_else(|| T::zero()),
            enable_monitoring: true,
        }
    }
}

impl Default for HardwareResources {
    fn default() -> Self {
        Self {
            max_memory_gb: 32.0,
            max_cpu_cores: num_cpus::get(),
            max_gpu_devices: 4,
            max_storage_gb: 100.0,
            max_network_bandwidth: 1000.0, // 1 GB/s
            enable_cloud_scaling: false,
            cloud_budget: None,
            cpu_cores: num_cpus::get(),
            ram_gb: 32,
            num_gpus: 1,
            gpu_memory_gb: 8,
            storage_gb: 100,
            network_bandwidth_mbps: 1000.0,
        }
    }
}

impl Default for TimeConstraints {
    fn default() -> Self {
        Self {
            max_search_time: Duration::from_secs(3600),    // 1 hour
            max_evaluation_time: Duration::from_secs(300), // 5 minutes
            search_deadline: None,
            budget_allocation: TimeBudgetAllocation::Uniform,
        }
    }
}

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

    #[test]
    fn test_nas_config_default() {
        let config = NASConfig::<f32>::default();
        assert_eq!(config.search_budget, 100);
        assert_eq!(config.population_size, 20);
        assert!(!config.progressive_search);
    }

    #[test]
    fn test_search_space_config_default() {
        let config = SearchSpaceConfig::default();
        assert!(!config.connection_patterns.is_empty());
        assert_eq!(config.connection_patterns.len(), 3);
    }

    #[test]
    fn test_parameter_range_variants() {
        let continuous = ParameterRange::Continuous(0.0, 1.0);
        let discrete = ParameterRange::Discrete(vec![0.1, 0.5, 0.9]);
        let integer = ParameterRange::Integer(1, 10);

        match continuous {
            ParameterRange::Continuous(min, max) => {
                assert_eq!(min, 0.0);
                assert_eq!(max, 1.0);
            }
            _ => panic!("Expected continuous range"),
        }

        match discrete {
            ParameterRange::Discrete(values) => {
                assert_eq!(values.len(), 3);
            }
            _ => panic!("Expected discrete range"),
        }

        match integer {
            ParameterRange::Integer(min, max) => {
                assert_eq!(min, 1);
                assert_eq!(max, 10);
            }
            _ => panic!("Expected integer range"),
        }
    }
}