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
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
// Mutation operators for neural architecture search
//
// This module provides various mutation operators that can modify architectures
// during the search process to explore the search space effectively.

#[allow(dead_code)]

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::numeric::Float;
use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt::Debug;

use crate::error::{OptimError, Result};

/// Configuration for mutation operators
#[derive(Debug, Clone)]
pub struct MutationConfig<T: Float + Debug + Send + Sync + 'static> {
    /// Mutation probability
    pub mutation_probability: T,
    
    /// Maximum mutations per architecture
    pub max_mutations_per_arch: usize,
    
    /// Mutation strength (how drastic the mutations are)
    pub mutation_strength: T,
    
    /// Available mutation operators
    pub available_operators: Vec<MutationType>,
    
    /// Operator weights for selection
    pub operator_weights: HashMap<MutationType, T>,
    
    /// Adaptive mutation parameters
    pub adaptive_params: Option<AdaptiveMutationParams<T>>,
    
    /// Constraint preservation settings
    pub preserve_constraints: bool,
    
    /// Mutation history tracking
    pub track_history: bool,
}

/// Types of mutation operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MutationType {
    /// Add a new operation/layer
    AddOperation,
    
    /// Remove an existing operation/layer
    RemoveOperation,
    
    /// Replace an operation with another
    ReplaceOperation,
    
    /// Modify operation parameters
    ModifyParameters,
    
    /// Add a new connection/edge
    AddConnection,
    
    /// Remove an existing connection
    RemoveConnection,
    
    /// Modify connection weights
    ModifyConnection,
    
    /// Change layer depth
    ChangeDepth,
    
    /// Change layer width
    ChangeWidth,
    
    /// Duplicate a block/module
    DuplicateBlock,
    
    /// Remove a block/module
    RemoveBlock,
    
    /// Swap two operations
    SwapOperations,
    
    /// Insert skip connection
    InsertSkip,
    
    /// Remove skip connection
    RemoveSkip,
    
    /// Modify activation function
    ChangeActivation,
    
    /// Modify normalization
    ChangeNormalization,
    
    /// Split an operation into multiple
    SplitOperation,
    
    /// Merge multiple operations
    MergeOperations,
    
    /// Randomize architecture section
    RandomizeSection,
    
    /// Apply macro-level changes
    MacroMutation,
}

/// Adaptive mutation parameters
#[derive(Debug, Clone)]
pub struct AdaptiveMutationParams<T: Float + Debug + Send + Sync + 'static> {
    /// Learning rate for adaptation
    pub adaptation_rate: T,
    
    /// Success-based adaptation
    pub success_threshold: T,
    
    /// Failure penalty
    pub failure_penalty: T,
    
    /// Adaptation window size
    pub window_size: usize,
    
    /// Minimum mutation rate
    pub min_mutation_rate: T,
    
    /// Maximum mutation rate
    pub max_mutation_rate: T,
}

/// Architecture mutation operator
#[derive(Debug)]
pub struct ArchitectureMutator<T: Float + Debug + Send + Sync + 'static> {
    /// Configuration
    config: MutationConfig<T>,
    
    /// Available operations pool
    operation_pool: OperationPool<T>,
    
    /// Mutation operators
    operators: HashMap<MutationType, Box<dyn MutationOperator<T>>>,
    
    /// Mutation history
    mutation_history: MutationHistory<T>,
    
    /// Performance feedback for adaptation
    performance_feedback: PerformanceFeedback<T>,
    
    /// Constraint validator
    constraint_validator: Option<Box<dyn ConstraintValidator<T>>>,
}

/// Pool of available operations for mutations
#[derive(Debug, Clone)]
pub struct OperationPool<T: Float + Debug + Send + Sync + 'static> {
    /// Available operation types
    pub operation_types: Vec<OperationType>,
    
    /// Operation templates with default parameters
    pub operation_templates: HashMap<String, OperationTemplate<T>>,
    
    /// Compatibility matrix
    pub compatibility_matrix: Array2<bool>,
    
    /// Operation frequencies (for biased sampling)
    pub operation_frequencies: HashMap<String, T>,
}

/// Operation types available for mutation
#[derive(Debug, Clone)]
pub struct OperationType {
    /// Type identifier
    pub id: String,
    
    /// Type name
    pub name: String,
    
    /// Operation category
    pub category: OperationCategory,
    
    /// Parameter ranges
    pub parameter_ranges: HashMap<String, ParameterRange>,
    
    /// Computational cost estimate
    pub cost_estimate: CostEstimate,
}

/// Operation categories
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OperationCategory {
    Convolution, Dense, Normalization, Activation, 
    Pooling, Attention, Recurrent, Custom,
}

/// Parameter range for operation parameters
#[derive(Debug, Clone)]
pub enum ParameterRange {
    /// Integer range
    Integer { min: i64, max: i64, default: i64 },
    
    /// Float range
    Float { min: f64, max: f64, default: f64 },
    
    /// Discrete choices
    Discrete { choices: Vec<String>, default: String },
    
    /// Boolean parameter
    Boolean { default: bool },
}

/// Cost estimate for operations
#[derive(Debug, Clone)]
pub struct CostEstimate {
    /// Parameter count multiplier
    pub param_multiplier: f64,
    
    /// FLOPS multiplier
    pub flops_multiplier: f64,
    
    /// Memory multiplier
    pub memory_multiplier: f64,
    
    /// Latency multiplier
    pub latency_multiplier: f64,
}

/// Operation template with default configuration
#[derive(Debug, Clone)]
pub struct OperationTemplate<T: Float + Debug + Send + Sync + 'static> {
    /// Template identifier
    pub id: String,
    
    /// Operation type
    pub operation_type: String,
    
    /// Default parameters
    pub default_parameters: HashMap<String, T>,
    
    /// Parameter constraints
    pub constraints: Vec<ParameterConstraint<T>>,
    
    /// Compatibility information
    pub compatibility: CompatibilityInfo,
}

/// Parameter constraints
#[derive(Debug, Clone)]
pub enum ParameterConstraint<T: Float + Debug + Send + Sync + 'static> {
    /// Range constraint
    Range { param: String, min: T, max: T },
    
    /// Dependency constraint
    Dependency { param: String, depends_on: String, condition: String },
    
    /// Mutual exclusion
    MutualExclusion { params: Vec<String> },
    
    /// Custom constraint
    Custom { name: String, description: String },
}

/// Compatibility information
#[derive(Debug, Clone)]
pub struct CompatibilityInfo {
    /// Compatible input types
    pub input_types: Vec<String>,
    
    /// Compatible output types
    pub output_types: Vec<String>,
    
    /// Shape requirements
    pub shape_requirements: Vec<ShapeRequirement>,
    
    /// Incompatible operations
    pub incompatible_with: Vec<String>,
}

/// Shape requirements for operations
#[derive(Debug, Clone)]
pub enum ShapeRequirement {
    /// Exact shape
    Exact(Vec<usize>),
    
    /// Minimum dimensions
    MinDims(usize),
    
    /// Maximum dimensions
    MaxDims(usize),
    
    /// Divisible by
    DivisibleBy { dim: usize, factor: usize },
    
    /// Shape relationship
    Relationship { relation: String, factor: f64 },
}

/// Trait for mutation operators
pub trait MutationOperator<T: Float + Debug + Send + Sync + 'static> {
    /// Apply mutation to architecture
    fn mutate(&self, architecture: &ArchitectureGenotype<T>) -> Result<ArchitectureGenotype<T>>;
    
    /// Check if mutation is applicable
    fn is_applicable(&self, architecture: &ArchitectureGenotype<T>) -> bool;
    
    /// Get mutation metadata
    fn get_metadata(&self) -> MutationMetadata;
    
    /// Get estimated impact
    fn estimate_impact(&self, architecture: &ArchitectureGenotype<T>) -> MutationImpact<T>;
}

/// Architecture genotype representation
#[derive(Debug, Clone)]
pub struct ArchitectureGenotype<T: Float + Debug + Send + Sync + 'static> {
    /// Architecture identifier
    pub id: String,
    
    /// Operations in the architecture
    pub operations: Vec<OperationGene<T>>,
    
    /// Connections between operations
    pub connections: Vec<ConnectionGene<T>>,
    
    /// Global parameters
    pub global_parameters: HashMap<String, T>,
    
    /// Architecture metadata
    pub metadata: GenotypeMetadata,
    
    /// Constraint satisfaction status
    pub is_valid: bool,
}

/// Operation gene representation
#[derive(Debug, Clone)]
pub struct OperationGene<T: Float + Debug + Send + Sync + 'static> {
    /// Gene identifier
    pub id: String,
    
    /// Operation type
    pub operation_type: String,
    
    /// Operation parameters
    pub parameters: HashMap<String, T>,
    
    /// Position in architecture
    pub position: Position,
    
    /// Gene-specific metadata
    pub metadata: GeneMetadata,
}

/// Connection gene representation
#[derive(Debug, Clone)]
pub struct ConnectionGene<T: Float + Debug + Send + Sync + 'static> {
    /// Gene identifier
    pub id: String,
    
    /// Source operation
    pub source: String,
    
    /// Target operation
    pub target: String,
    
    /// Connection type
    pub connection_type: ConnectionType,
    
    /// Connection weight/strength
    pub weight: T,
    
    /// Connection metadata
    pub metadata: GeneMetadata,
}

/// Connection types
#[derive(Debug, Clone, Copy)]
pub enum ConnectionType {
    Standard, Skip, Residual, Dense, Attention,
}

/// Position in architecture
#[derive(Debug, Clone)]
pub struct Position {
    /// Layer index
    pub layer: usize,
    
    /// Position within layer
    pub index: usize,
    
    /// Depth in hierarchy
    pub depth: usize,
}

/// Genotype metadata
#[derive(Debug, Clone)]
pub struct GenotypeMetadata {
    /// Creation timestamp
    pub created_at: u64,
    
    /// Parent architectures
    pub parents: Vec<String>,
    
    /// Generation number
    pub generation: usize,
    
    /// Mutation history
    pub mutations_applied: Vec<String>,
}

/// Gene metadata
#[derive(Debug, Clone)]
pub struct GeneMetadata {
    /// Gene age (generations since creation)
    pub age: usize,
    
    /// Mutation count
    pub mutation_count: usize,
    
    /// Last mutation timestamp
    pub last_mutated: u64,
    
    /// Performance contribution
    pub performance_contribution: Option<f64>,
}

/// Mutation metadata
#[derive(Debug, Clone)]
pub struct MutationMetadata {
    /// Mutation operator name
    pub operator_name: String,
    
    /// Mutation type
    pub mutation_type: MutationType,
    
    /// Difficulty level
    pub difficulty: MutationDifficulty,
    
    /// Expected impact level
    pub expected_impact: ImpactLevel,
}

/// Mutation difficulty levels
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MutationDifficulty {
    Easy, Medium, Hard, Expert,
}

/// Impact levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ImpactLevel {
    Minimal, Low, Medium, High, Critical,
}

/// Mutation impact estimate
#[derive(Debug, Clone)]
pub struct MutationImpact<T: Float + Debug + Send + Sync + 'static> {
    /// Expected performance change
    pub performance_delta: T,
    
    /// Expected complexity change
    pub complexity_delta: T,
    
    /// Expected resource change
    pub resource_delta: HashMap<String, T>,
    
    /// Confidence in estimates
    pub confidence: T,
    
    /// Risk assessment
    pub risk_level: RiskLevel,
}

/// Risk levels for mutations
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    VeryLow, Low, Medium, High, VeryHigh,
}

/// Mutation history tracking
#[derive(Debug)]
pub struct MutationHistory<T: Float + Debug + Send + Sync + 'static> {
    /// Applied mutations log
    pub mutation_log: Vec<MutationRecord<T>>,
    
    /// Success statistics per operator
    pub operator_stats: HashMap<MutationType, OperatorStatistics<T>>,
    
    /// Rollback information
    pub rollback_info: HashMap<String, ArchitectureGenotype<T>>,
    
    /// Performance tracking
    pub performance_tracking: Vec<PerformanceRecord<T>>,
}

/// Mutation record
#[derive(Debug, Clone)]
pub struct MutationRecord<T: Float + Debug + Send + Sync + 'static> {
    /// Record identifier
    pub id: String,
    
    /// Mutation type applied
    pub mutation_type: MutationType,
    
    /// Source architecture
    pub source_architecture: String,
    
    /// Resulting architecture
    pub result_architecture: String,
    
    /// Mutation parameters
    pub parameters: HashMap<String, String>,
    
    /// Performance before mutation
    pub performance_before: Option<T>,
    
    /// Performance after mutation
    pub performance_after: Option<T>,
    
    /// Success indicator
    pub success: Option<bool>,
    
    /// Timestamp
    pub timestamp: u64,
}

/// Statistics for mutation operators
#[derive(Debug, Clone)]
pub struct OperatorStatistics<T: Float + Debug + Send + Sync + 'static> {
    /// Number of applications
    pub applications: usize,
    
    /// Number of successful mutations
    pub successes: usize,
    
    /// Average performance improvement
    pub avg_improvement: T,
    
    /// Success rate
    pub success_rate: T,
    
    /// Average impact magnitude
    pub avg_impact: T,
    
    /// Operator reliability score
    pub reliability_score: T,
}

/// Performance feedback for adaptive mutation
#[derive(Debug)]
pub struct PerformanceFeedback<T: Float + Debug + Send + Sync + 'static> {
    /// Recent performance changes
    pub recent_changes: VecDeque<T>,
    
    /// Moving average performance
    pub moving_average: T,
    
    /// Performance trend
    pub trend: PerformanceTrend,
    
    /// Stagnation detection
    pub stagnation_counter: usize,
    
    /// Best performance seen
    pub best_performance: T,
}

/// Performance trend indicators
#[derive(Debug, Clone, Copy)]
pub enum PerformanceTrend {
    Improving, Declining, Stable, Volatile,
}

/// Performance record
#[derive(Debug, Clone)]
pub struct PerformanceRecord<T: Float + Debug + Send + Sync + 'static> {
    /// Architecture identifier
    pub architecture_id: String,
    
    /// Performance value
    pub performance: T,
    
    /// Timestamp
    pub timestamp: u64,
    
    /// Context information
    pub context: HashMap<String, String>,
}

/// Constraint validator trait
pub trait ConstraintValidator<T: Float + Debug + Send + Sync + 'static> {
    /// Validate architecture constraints
    fn validate(&self, architecture: &ArchitectureGenotype<T>) -> Result<bool>;
    
    /// Get constraint violations
    fn get_violations(&self, architecture: &ArchitectureGenotype<T>) -> Vec<String>;
    
    /// Suggest constraint fixes
    fn suggest_fixes(&self, architecture: &ArchitectureGenotype<T>) -> Vec<String>;
}

/// Specific mutation operators

/// Add operation mutation operator
#[derive(Debug)]
pub struct AddOperationMutator<T: Float + Debug + Send + Sync + 'static> {
    /// Operation pool for selection
    operation_pool: OperationPool<T>,
    
    /// Insertion strategy
    insertion_strategy: InsertionStrategy,
    
    /// Maximum operations to add
    max_additions: usize,
}

/// Insertion strategies for new operations
#[derive(Debug, Clone, Copy)]
pub enum InsertionStrategy {
    /// Insert at random position
    Random,
    
    /// Insert at optimal position
    Optimal,
    
    /// Insert at end
    Append,
    
    /// Insert at beginning
    Prepend,
    
    /// Insert based on compatibility
    Compatible,
}

/// Remove operation mutation operator
#[derive(Debug)]
pub struct RemoveOperationMutator<T: Float + Debug + Send + Sync + 'static> {
    /// Minimum operations to keep
    min_operations: usize,
    
    /// Removal strategy
    removal_strategy: RemovalStrategy,
    
    /// Preserve critical operations
    preserve_critical: bool,
    
    /// Critical operation identifiers
    critical_operations: HashSet<String>,
}

/// Removal strategies
#[derive(Debug, Clone, Copy)]
pub enum RemovalStrategy {
    /// Remove random operation
    Random,
    
    /// Remove least important operation
    LeastImportant,
    
    /// Remove redundant operations
    Redundant,
    
    /// Remove based on performance impact
    PerformanceBased,
}

/// Replace operation mutation operator
#[derive(Debug)]
pub struct ReplaceOperationMutator<T: Float + Debug + Send + Sync + 'static> {
    /// Operation pool for replacements
    operation_pool: OperationPool<T>,
    
    /// Replacement strategy
    replacement_strategy: ReplacementStrategy,
    
    /// Compatibility checking
    check_compatibility: bool,
}

/// Replacement strategies
#[derive(Debug, Clone, Copy)]
pub enum ReplacementStrategy {
    /// Replace with random compatible operation
    RandomCompatible,
    
    /// Replace with similar operation
    Similar,
    
    /// Replace with better performing operation
    Performance,
    
    /// Replace with more efficient operation
    Efficiency,
}

/// Parameter modification mutation operator
#[derive(Debug)]
pub struct ParameterMutator<T: Float + Debug + Send + Sync + 'static> {
    /// Mutation strength
    strength: T,
    
    /// Mutation distribution
    distribution: ParameterDistribution<T>,
    
    /// Parameter selection strategy
    selection_strategy: ParameterSelectionStrategy,
}

/// Parameter mutation distributions
#[derive(Debug, Clone)]
pub enum ParameterDistribution<T: Float + Debug + Send + Sync + 'static> {
    /// Gaussian noise
    Gaussian { std: T },
    
    /// Uniform noise
    Uniform { range: T },
    
    /// Exponential scaling
    Exponential { factor: T },
    
    /// Discrete jumps
    Discrete { steps: Vec<T> },
}

/// Parameter selection strategies
#[derive(Debug, Clone, Copy)]
pub enum ParameterSelectionStrategy {
    /// Select random parameter
    Random,
    
    /// Select most sensitive parameter
    MostSensitive,
    
    /// Select all parameters
    All,
    
    /// Select based on importance
    ImportanceBased,
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> ArchitectureMutator<T> {
    /// Create new architecture mutator
    pub fn new(config: MutationConfig<T>) -> Result<Self> {
        let mut mutator = Self {
            config: config.clone(),
            operation_pool: OperationPool::new()?,
            operators: HashMap::new(),
            mutation_history: MutationHistory::new(),
            performance_feedback: PerformanceFeedback::new(),
            constraint_validator: None,
        };
        
        // Initialize mutation operators
        mutator.initialize_operators()?;
        
        Ok(mutator)
    }
    
    /// Initialize mutation operators
    fn initialize_operators(&mut self) -> Result<()> {
        // Add operation mutator
        if self.config.available_operators.contains(&MutationType::AddOperation) {
            let add_mutator = AddOperationMutator {
                operation_pool: self.operation_pool.clone(),
                insertion_strategy: InsertionStrategy::Random,
                max_additions: 3,
            };
            self.operators.insert(MutationType::AddOperation, Box::new(add_mutator));
        }
        
        // Remove operation mutator
        if self.config.available_operators.contains(&MutationType::RemoveOperation) {
            let remove_mutator = RemoveOperationMutator {
                min_operations: 1,
                removal_strategy: RemovalStrategy::Random,
                preserve_critical: true,
                critical_operations: HashSet::new(),
            };
            self.operators.insert(MutationType::RemoveOperation, Box::new(remove_mutator));
        }
        
        // Replace operation mutator
        if self.config.available_operators.contains(&MutationType::ReplaceOperation) {
            let replace_mutator = ReplaceOperationMutator {
                operation_pool: self.operation_pool.clone(),
                replacement_strategy: ReplacementStrategy::RandomCompatible,
                check_compatibility: true,
            };
            self.operators.insert(MutationType::ReplaceOperation, Box::new(replace_mutator));
        }
        
        // Parameter mutator
        if self.config.available_operators.contains(&MutationType::ModifyParameters) {
            let param_mutator = ParameterMutator {
                strength: self.config.mutation_strength,
                distribution: ParameterDistribution::Gaussian { std: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()) },
                selection_strategy: ParameterSelectionStrategy::Random,
            };
            self.operators.insert(MutationType::ModifyParameters, Box::new(param_mutator));
        }
        
        Ok(())
    }
    
    /// Apply mutation to architecture
    pub fn mutate(&mut self, architecture: &ArchitectureGenotype<T>) -> Result<ArchitectureGenotype<T>> {
        // Select mutation operator
        let mutation_type = self.select_mutation_operator(architecture)?;
        
        // Apply mutation
        if let Some(operator) = self.operators.get(&mutation_type) {
            let mutated_architecture = operator.mutate(architecture)?;
            
            // Validate constraints if validator is available
            let is_valid = if let Some(ref validator) = self.constraint_validator {
                validator.validate(&mutated_architecture)?
            } else {
                true
            };
            
            let mut final_architecture = mutated_architecture;
            final_architecture.is_valid = is_valid;
            
            // Record mutation
            if self.config.track_history {
                self.record_mutation(mutation_type, architecture, &final_architecture)?;
            }
            
            // Update adaptive parameters
            if self.config.adaptive_params.is_some() {
                self.update_adaptive_parameters(mutation_type, is_valid)?;
            }
            
            Ok(final_architecture)
        } else {
            Err(OptimError::UnsupportedOperation(
                format!("Mutation operator {:?} not available", mutation_type)
            ))
        }
    }
    
    /// Select mutation operator based on strategy
    fn select_mutation_operator(&self, architecture: &ArchitectureGenotype<T>) -> Result<MutationType> {
        use scirs2_core::random::Rng;
        let mut rng = scirs2_core::random::thread_rng();
        
        // Filter applicable operators
        let applicable_ops: Vec<MutationType> = self.config.available_operators
            .iter()
            .filter(|&&op_type| {
                if let Some(operator) = self.operators.get(&op_type) {
                    operator.is_applicable(architecture)
                } else {
                    false
                }
            })
            .copied()
            .collect();
        
        if applicable_ops.is_empty() {
            return Err(OptimError::SearchFailed(
                "No applicable mutation operators".to_string()
            ));
        }
        
        // Weighted selection
        if !self.config.operator_weights.is_empty() {
            let total_weight: T = applicable_ops.iter()
                .map(|op| self.config.operator_weights.get(op).unwrap_or(&T::one()))
                .cloned()
                .fold(T::zero(), |acc, w| acc + w);
            
            let mut cumulative_weight = T::zero();
            let random_weight = T::from(rng.random::<f64>()).expect("unwrap failed") * total_weight;
            
            for &op_type in &applicable_ops {
                let weight = self.config.operator_weights.get(&op_type).unwrap_or(&T::one());
                cumulative_weight = cumulative_weight + *weight;
                if random_weight <= cumulative_weight {
                    return Ok(op_type);
                }
            }
        }
        
        // Fallback to random selection
        let selected_idx = rng.gen_range(0..applicable_ops.len());
        Ok(applicable_ops[selected_idx])
    }
    
    /// Record mutation in history
    fn record_mutation(&mut self, mutation_type: MutationType, 
                      source: &ArchitectureGenotype<T>,
                      result: &ArchitectureGenotype<T>) -> Result<()> {
        let record = MutationRecord {
            id: format!("mut_{}", scirs2_core::random::random::<u64>()),
            mutation_type,
            source_architecture: source.id.clone(),
            result_architecture: result.id.clone(),
            parameters: HashMap::new(),
            performance_before: None,
            performance_after: None,
            success: Some(result.is_valid),
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        };
        
        self.mutation_history.mutation_log.push(record);
        
        // Update operator statistics
        let stats = self.mutation_history.operator_stats
            .entry(mutation_type)
            .or_insert_with(|| OperatorStatistics {
                applications: 0,
                successes: 0,
                avg_improvement: T::zero(),
                success_rate: T::zero(),
                avg_impact: T::zero(),
                reliability_score: T::zero(),
            });
        
        stats.applications += 1;
        if result.is_valid {
            stats.successes += 1;
        }
        stats.success_rate = scirs2_core::numeric::NumCast::from(stats.successes as f64 / stats.applications as f64).unwrap_or_else(|| T::zero());
        
        Ok(())
    }
    
    /// Update adaptive mutation parameters
    fn update_adaptive_parameters(&mut self, mutation_type: MutationType, success: bool) -> Result<()> {
        if let Some(ref params) = self.config.adaptive_params {
            // Update operator weight based on success
            let current_weight = self.config.operator_weights
                .get(&mutation_type)
                .copied()
                .unwrap_or(T::one());
            
            let new_weight = if success {
                current_weight * (T::one() + params.adaptation_rate)
            } else {
                current_weight * (T::one() - params.failure_penalty)
            };
            
            let clamped_weight = new_weight.max(scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero())).min(scirs2_core::numeric::NumCast::from(10.0).unwrap_or_else(|| T::zero()));
            self.config.operator_weights.insert(mutation_type, clamped_weight);
        }
        
        Ok(())
    }
    
    /// Apply multiple mutations to architecture
    pub fn mutate_multiple(&mut self, architecture: &ArchitectureGenotype<T>, 
                          num_mutations: usize) -> Result<ArchitectureGenotype<T>> {
        let mut current_arch = architecture.clone();
        
        for _ in 0..num_mutations.min(self.config.max_mutations_per_arch) {
            current_arch = self.mutate(&current_arch)?;
            
            // Stop early if mutation fails
            if !current_arch.is_valid {
                break;
            }
        }
        
        Ok(current_arch)
    }
    
    /// Get mutation statistics
    pub fn get_statistics(&self) -> &HashMap<MutationType, OperatorStatistics<T>> {
        &self.mutation_history.operator_stats
    }
    
    /// Get mutation history
    pub fn get_mutation_history(&self) -> &[MutationRecord<T>] {
        &self.mutation_history.mutation_log
    }
    
    /// Set constraint validator
    pub fn set_constraint_validator(&mut self, validator: Box<dyn ConstraintValidator<T>>) {
        self.constraint_validator = Some(validator);
    }
    
    /// Update performance feedback
    pub fn update_performance_feedback(&mut self, architecture_id: &str, performance: T) -> Result<()> {
        self.performance_feedback.recent_changes.push_back(performance);
        
        // Maintain window size
        let window_size = if let Some(ref params) = self.config.adaptive_params {
            params.window_size
        } else {
            10
        };
        
        while self.performance_feedback.recent_changes.len() > window_size {
            self.performance_feedback.recent_changes.pop_front();
        }
        
        // Update moving average
        let sum: T = self.performance_feedback.recent_changes.iter().cloned().sum();
        let count = T::from(self.performance_feedback.recent_changes.len() as f64).expect("unwrap failed");
        self.performance_feedback.moving_average = sum / count;
        
        // Update best performance
        self.performance_feedback.best_performance = 
            self.performance_feedback.best_performance.max(performance);
        
        Ok(())
    }
}

// Implementations for specific mutation operators

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> MutationOperator<T> for AddOperationMutator<T> {
    fn mutate(&self, architecture: &ArchitectureGenotype<T>) -> Result<ArchitectureGenotype<T>> {
        use scirs2_core::random::Rng;
        let mut rng = scirs2_core::random::thread_rng();
        
        let mut mutated = architecture.clone();
        mutated.id = format!("{}_{}", architecture.id, "add_op");
        
        // Select operation to add
        let op_types: Vec<&OperationType> = self.operation_pool.operation_types.iter().collect();
        if op_types.is_empty() {
            return Err(OptimError::SearchFailed("No operations available to add".to_string()));
        }
        
        let selected_op = &op_types[rng.gen_range(0..op_types.len())];
        
        // Create new operation gene
        let new_op = OperationGene {
            id: format!("op_{}", scirs2_core::random::random::<u64>()),
            operation_type: selected_op.id.clone(),
            parameters: HashMap::new(), // Would be populated from template
            position: Position {
                layer: rng.gen_range(0..mutated.operations.len() + 1),
                index: 0,
                depth: 0,
            },
            metadata: GeneMetadata {
                age: 0,
                mutation_count: 0,
                last_mutated: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs(),
                performance_contribution: None,
            },
        };
        
        // Insert operation
        match self.insertion_strategy {
            InsertionStrategy::Random => {
                let pos = rng.gen_range(0..=mutated.operations.len());
                mutated.operations.insert(pos, new_op);
            }
            InsertionStrategy::Append => {
                mutated.operations.push(new_op);
            }
            _ => {
                mutated.operations.push(new_op); // Fallback
            }
        }
        
        Ok(mutated)
    }
    
    fn is_applicable(&self, architecture: &ArchitectureGenotype<T>) -> bool {
        architecture.operations.len() < 100 // Arbitrary limit
    }
    
    fn get_metadata(&self) -> MutationMetadata {
        MutationMetadata {
            operator_name: "AddOperation".to_string(),
            mutation_type: MutationType::AddOperation,
            difficulty: MutationDifficulty::Easy,
            expected_impact: ImpactLevel::Medium,
        }
    }
    
    fn estimate_impact(&self, _architecture: &ArchitectureGenotype<T>) -> MutationImpact<T> {
        MutationImpact {
            performance_delta: scirs2_core::numeric::NumCast::from(0.05).unwrap_or_else(|| T::zero()), // Small positive impact
            complexity_delta: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),   // Increased complexity
            resource_delta: {
                let mut resources = HashMap::new();
                resources.insert("memory".to_string(), scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()));
                resources.insert("flops".to_string(), scirs2_core::numeric::NumCast::from(0.15).unwrap_or_else(|| T::zero()));
                resources
            },
            confidence: scirs2_core::numeric::NumCast::from(0.7).unwrap_or_else(|| T::zero()),
            risk_level: RiskLevel::Low,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> MutationOperator<T> for RemoveOperationMutator<T> {
    fn mutate(&self, architecture: &ArchitectureGenotype<T>) -> Result<ArchitectureGenotype<T>> {
        use scirs2_core::random::Rng;
        let mut rng = scirs2_core::random::thread_rng();
        
        if architecture.operations.len() <= self.min_operations {
            return Err(OptimError::InvalidInput(
                "Cannot remove operation: minimum operations reached".to_string()
            ));
        }
        
        let mut mutated = architecture.clone();
        mutated.id = format!("{}_{}", architecture.id, "remove_op");
        
        // Select operation to remove
        let removal_idx = match self.removal_strategy {
            RemovalStrategy::Random => {
                rng.gen_range(0..mutated.operations.len())
            }
            _ => {
                // Fallback to random
                rng.gen_range(0..mutated.operations.len())
            }
        };
        
        // Check if operation is critical
        let op_to_remove = &mutated.operations[removal_idx];
        if self.preserve_critical && self.critical_operations.contains(&op_to_remove.id) {
            return Err(OptimError::InvalidInput(
                "Cannot remove critical operation".to_string()
            ));
        }
        
        // Remove operation
        mutated.operations.remove(removal_idx);
        
        // Remove associated connections
        mutated.connections.retain(|conn| {
            conn.source != op_to_remove.id && conn.target != op_to_remove.id
        });
        
        Ok(mutated)
    }
    
    fn is_applicable(&self, architecture: &ArchitectureGenotype<T>) -> bool {
        architecture.operations.len() > self.min_operations
    }
    
    fn get_metadata(&self) -> MutationMetadata {
        MutationMetadata {
            operator_name: "RemoveOperation".to_string(),
            mutation_type: MutationType::RemoveOperation,
            difficulty: MutationDifficulty::Medium,
            expected_impact: ImpactLevel::High,
        }
    }
    
    fn estimate_impact(&self, _architecture: &ArchitectureGenotype<T>) -> MutationImpact<T> {
        MutationImpact {
            performance_delta: scirs2_core::numeric::NumCast::from(-0.1).unwrap_or_else(|| T::zero()), // Potential negative impact
            complexity_delta: scirs2_core::numeric::NumCast::from(-0.2).unwrap_or_else(|| T::zero()),  // Reduced complexity
            resource_delta: {
                let mut resources = HashMap::new();
                resources.insert("memory".to_string(), scirs2_core::numeric::NumCast::from(-0.1).unwrap_or_else(|| T::zero()));
                resources.insert("flops".to_string(), scirs2_core::numeric::NumCast::from(-0.15).unwrap_or_else(|| T::zero()));
                resources
            },
            confidence: scirs2_core::numeric::NumCast::from(0.6).unwrap_or_else(|| T::zero()),
            risk_level: RiskLevel::Medium,
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> MutationOperator<T> for ParameterMutator<T> {
    fn mutate(&self, architecture: &ArchitectureGenotype<T>) -> Result<ArchitectureGenotype<T>> {
        use scirs2_core::random::Rng;
        let mut rng = scirs2_core::random::thread_rng();
        
        let mut mutated = architecture.clone();
        mutated.id = format!("{}_{}", architecture.id, "param_mut");
        
        // Select operation to mutate
        if mutated.operations.is_empty() {
            return Ok(mutated);
        }
        
        let op_idx = rng.gen_range(0..mutated.operations.len());
        let operation = &mut mutated.operations[op_idx];
        
        // Select parameter to mutate
        let param_keys: Vec<String> = operation.parameters.keys().cloned().collect();
        if param_keys.is_empty() {
            return Ok(mutated);
        }
        
        let param_key = &param_keys[rng.gen_range(0..param_keys.len())];
        
        // Apply mutation based on distribution
        if let Some(current_value) = operation.parameters.get(param_key) {
            let new_value = match &self.distribution {
                ParameterDistribution::Gaussian { std } => {
                    let noise = T::from(rng.random::<f64>() - 0.5).expect("unwrap failed") * *std * scirs2_core::numeric::NumCast::from(2.0).unwrap_or_else(|| T::zero());
                    *current_value + noise
                }
                ParameterDistribution::Uniform { range } => {
                    let noise = T::from(rng.random::<f64>() - 0.5).expect("unwrap failed") * *range * scirs2_core::numeric::NumCast::from(2.0).unwrap_or_else(|| T::zero());
                    *current_value + noise
                }
                _ => *current_value, // Fallback
            };
            
            operation.parameters.insert(param_key.clone(), new_value);
            operation.metadata.mutation_count += 1;
            operation.metadata.last_mutated = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs();
        }
        
        Ok(mutated)
    }
    
    fn is_applicable(&self, architecture: &ArchitectureGenotype<T>) -> bool {
        !architecture.operations.is_empty() &&
        architecture.operations.iter().any(|op| !op.parameters.is_empty())
    }
    
    fn get_metadata(&self) -> MutationMetadata {
        MutationMetadata {
            operator_name: "ParameterMutation".to_string(),
            mutation_type: MutationType::ModifyParameters,
            difficulty: MutationDifficulty::Easy,
            expected_impact: ImpactLevel::Low,
        }
    }
    
    fn estimate_impact(&self, _architecture: &ArchitectureGenotype<T>) -> MutationImpact<T> {
        MutationImpact {
            performance_delta: T::zero(), // Neutral expected impact
            complexity_delta: T::zero(),  // No complexity change
            resource_delta: HashMap::new(),
            confidence: scirs2_core::numeric::NumCast::from(0.8).unwrap_or_else(|| T::zero()),
            risk_level: RiskLevel::VeryLow,
        }
    }
}

// Helper implementations

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> OperationPool<T> {
    fn new() -> Result<Self> {
        Ok(Self {
            operation_types: vec![
                OperationType {
                    id: "conv2d".to_string(),
                    name: "2D Convolution".to_string(),
                    category: OperationCategory::Convolution,
                    parameter_ranges: HashMap::new(),
                    cost_estimate: CostEstimate {
                        param_multiplier: 1.0,
                        flops_multiplier: 2.0,
                        memory_multiplier: 1.5,
                        latency_multiplier: 1.0,
                    },
                },
                OperationType {
                    id: "dense".to_string(),
                    name: "Dense Layer".to_string(),
                    category: OperationCategory::Dense,
                    parameter_ranges: HashMap::new(),
                    cost_estimate: CostEstimate {
                        param_multiplier: 1.5,
                        flops_multiplier: 1.0,
                        memory_multiplier: 1.0,
                        latency_multiplier: 0.8,
                    },
                },
            ],
            operation_templates: HashMap::new(),
            compatibility_matrix: Array2::eye(2),
            operation_frequencies: HashMap::new(),
        })
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> MutationHistory<T> {
    fn new() -> Self {
        Self {
            mutation_log: Vec::new(),
            operator_stats: HashMap::new(),
            rollback_info: HashMap::new(),
            performance_tracking: Vec::new(),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> PerformanceFeedback<T> {
    fn new() -> Self {
        Self {
            recent_changes: VecDeque::new(),
            moving_average: T::zero(),
            trend: PerformanceTrend::Stable,
            stagnation_counter: 0,
            best_performance: scirs2_core::numeric::NumCast::from(f64::NEG_INFINITY).unwrap_or_else(|| T::zero()),
        }
    }
}

impl<T: Float + Debug + Send + Sync + 'static + Default + Clone> Default for MutationConfig<T> {
    fn default() -> Self {
        let mut operator_weights = HashMap::new();
        operator_weights.insert(MutationType::AddOperation, scirs2_core::numeric::NumCast::from(0.3).unwrap_or_else(|| T::zero()));
        operator_weights.insert(MutationType::RemoveOperation, scirs2_core::numeric::NumCast::from(0.2).unwrap_or_else(|| T::zero()));
        operator_weights.insert(MutationType::ReplaceOperation, scirs2_core::numeric::NumCast::from(0.25).unwrap_or_else(|| T::zero()));
        operator_weights.insert(MutationType::ModifyParameters, scirs2_core::numeric::NumCast::from(0.25).unwrap_or_else(|| T::zero()));
        
        Self {
            mutation_probability: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
            max_mutations_per_arch: 3,
            mutation_strength: scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()),
            available_operators: vec![
                MutationType::AddOperation,
                MutationType::RemoveOperation,
                MutationType::ReplaceOperation,
                MutationType::ModifyParameters,
            ],
            operator_weights,
            adaptive_params: Some(AdaptiveMutationParams {
                adaptation_rate: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
                success_threshold: scirs2_core::numeric::NumCast::from(0.6).unwrap_or_else(|| T::zero()),
                failure_penalty: scirs2_core::numeric::NumCast::from(0.1).unwrap_or_else(|| T::zero()),
                window_size: 10,
                min_mutation_rate: scirs2_core::numeric::NumCast::from(0.01).unwrap_or_else(|| T::zero()),
                max_mutation_rate: scirs2_core::numeric::NumCast::from(0.5).unwrap_or_else(|| T::zero()),
            }),
            preserve_constraints: true,
            track_history: true,
        }
    }
}