fugue-evo 0.3.0

An implementation of fugue for running evolutionary algorithms as Bayesian inference: priors and likelihoods as probabilistic programs, tempered SMC in trace space, annealed optimization, Pareto posteriors - plus a standalone classical EC toolkit
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
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
//! Mutation operators
//!
//! This module provides various mutation operators for genetic algorithms.

use rand::Rng;
use rand_distr::{Distribution, Normal};

use crate::genome::bit_string::BitString;
use crate::genome::bounds::MultiBounds;
use crate::genome::permutation::Permutation;
use crate::genome::real_vector::RealVector;
use crate::genome::traits::{
    BinaryGenome, EvolutionaryGenome, PermutationGenome, RealValuedGenome,
};
use crate::genome::tree::{Function, Terminal, TreeGenome, TreeNode};
use crate::operators::traits::{BoundedMutationOperator, MutationOperator};

/// Polynomial mutation (bounded)
///
/// Uses the polynomial probability distribution to perturb genes.
/// Respects bounds and is commonly used with NSGA-II.
///
/// Reference: Deb, K. (2001). Multi-Objective Optimization using Evolutionary Algorithms.
#[derive(Clone, Debug)]
pub struct PolynomialMutation {
    /// Distribution index (typically 20-100)
    /// Higher values = smaller mutations
    pub eta_m: f64,
    /// Per-gene mutation probability (default: 1/n)
    pub mutation_probability: Option<f64>,
    /// Standard deviation used by the *unbounded* fallback (see
    /// [`MutationOperator::mutate`]). `None` selects the adaptive default
    /// `0.1 * (1 + |x|)` per gene; `Some(s)` uses a fixed `s`.
    pub unbounded_sigma: Option<f64>,
}

impl PolynomialMutation {
    /// Create a new polynomial mutation with the given distribution index
    pub fn new(eta_m: f64) -> Self {
        assert!(eta_m >= 0.0, "Distribution index must be non-negative");
        Self {
            eta_m,
            mutation_probability: None,
            unbounded_sigma: None,
        }
    }

    /// Set a fixed mutation probability per gene
    pub fn with_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.mutation_probability = Some(probability);
        self
    }

    /// Set the standard deviation of the unbounded Gaussian fallback.
    ///
    /// Polynomial mutation is only defined relative to finite bounds; when the
    /// operator is invoked without bounds it perturbs each gene with Gaussian
    /// noise instead (audit EV-102). By default the per-gene sigma is
    /// `0.1 * (1 + |x|)`; this method pins it to a fixed value.
    pub fn with_unbounded_sigma(mut self, sigma: f64) -> Self {
        assert!(sigma >= 0.0, "Sigma must be non-negative");
        self.unbounded_sigma = Some(sigma);
        self
    }

    /// Apply polynomial mutation to a gene
    fn mutate_gene<R: Rng>(&self, gene: f64, min: f64, max: f64, rng: &mut R) -> f64 {
        let range = max - min;
        if range <= 0.0 {
            return gene;
        }

        let delta1 = (gene - min) / range;
        let delta2 = (max - gene) / range;

        let u = rng.gen::<f64>();
        let delta_q = if u <= 0.5 {
            let val = 2.0 * u + (1.0 - 2.0 * u) * (1.0 - delta1).powf(self.eta_m + 1.0);
            val.powf(1.0 / (self.eta_m + 1.0)) - 1.0
        } else {
            let val = 2.0 * (1.0 - u) + 2.0 * (u - 0.5) * (1.0 - delta2).powf(self.eta_m + 1.0);
            1.0 - val.powf(1.0 / (self.eta_m + 1.0))
        };

        (gene + delta_q * range).clamp(min, max)
    }
}

impl MutationOperator<RealVector> for PolynomialMutation {
    fn mutate<R: Rng>(&self, genome: &mut RealVector, rng: &mut R) {
        // Polynomial mutation is intrinsically bounds-relative and is undefined
        // without a finite range. Rather than fabricating +/-1e10 bounds (which
        // turned an "unbounded" mutation into a destructive, near-random reset
        // of each gene), fall back to a local Gaussian perturbation (EV-102).
        let n = genome.dimension();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);

        for gene in genome.genes_mut() {
            if rng.gen::<f64>() < prob {
                let sigma = self
                    .unbounded_sigma
                    .unwrap_or_else(|| 0.1 * (1.0 + gene.abs()));
                if sigma > 0.0 {
                    let normal = Normal::new(0.0, sigma).unwrap();
                    *gene += normal.sample(rng);
                }
            }
        }
    }

    fn mutation_probability(&self) -> Option<f64> {
        self.mutation_probability
    }
}

impl BoundedMutationOperator<RealVector> for PolynomialMutation {
    fn mutate_bounded<R: Rng>(&self, genome: &mut RealVector, bounds: &MultiBounds, rng: &mut R) {
        let n = genome.dimension();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);

        for i in 0..n {
            if rng.gen::<f64>() < prob {
                if let Some(bound) = bounds.get(i) {
                    genome.genes_mut()[i] =
                        self.mutate_gene(genome.genes()[i], bound.min, bound.max, rng);
                }
            }
        }
    }
}

/// Gaussian mutation
///
/// Adds Gaussian noise to each gene.
#[derive(Clone, Debug)]
pub struct GaussianMutation {
    /// Standard deviation of the Gaussian noise
    pub sigma: f64,
    /// Per-gene mutation probability
    pub mutation_probability: Option<f64>,
}

impl GaussianMutation {
    /// Create a new Gaussian mutation with the given standard deviation
    pub fn new(sigma: f64) -> Self {
        assert!(sigma >= 0.0, "Sigma must be non-negative");
        Self {
            sigma,
            mutation_probability: None,
        }
    }

    /// Set a fixed mutation probability per gene
    pub fn with_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.mutation_probability = Some(probability);
        self
    }
}

impl MutationOperator<RealVector> for GaussianMutation {
    fn mutate<R: Rng>(&self, genome: &mut RealVector, rng: &mut R) {
        let n = genome.dimension();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);
        let normal = Normal::new(0.0, self.sigma).unwrap();

        for gene in genome.genes_mut() {
            if rng.gen::<f64>() < prob {
                *gene += normal.sample(rng);
            }
        }
    }

    fn mutation_probability(&self) -> Option<f64> {
        self.mutation_probability
    }
}

impl BoundedMutationOperator<RealVector> for GaussianMutation {
    fn mutate_bounded<R: Rng>(&self, genome: &mut RealVector, bounds: &MultiBounds, rng: &mut R) {
        let n = genome.dimension();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);
        let normal = Normal::new(0.0, self.sigma).unwrap();

        for i in 0..n {
            if rng.gen::<f64>() < prob {
                genome.genes_mut()[i] += normal.sample(rng);
                if let Some(bound) = bounds.get(i) {
                    genome.genes_mut()[i] = bound.clamp(genome.genes()[i]);
                }
            }
        }
    }
}

/// Uniform mutation
///
/// Replaces genes with random values within bounds.
#[derive(Clone, Debug)]
pub struct UniformMutation {
    /// Per-gene mutation probability
    pub mutation_probability: Option<f64>,
}

impl UniformMutation {
    /// Create a new uniform mutation
    pub fn new() -> Self {
        Self {
            mutation_probability: None,
        }
    }

    /// Set a fixed mutation probability per gene
    pub fn with_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.mutation_probability = Some(probability);
        self
    }
}

impl Default for UniformMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<RealVector> for UniformMutation {
    fn mutate<R: Rng>(&self, genome: &mut RealVector, rng: &mut R) {
        // Uniform mutation requires a finite range; without explicit bounds we
        // fall back to the modest, non-destructive default range [-1, 1].
        // Prefer [`mutate_bounded`] with real bounds whenever they are known.
        let default_bounds = MultiBounds::symmetric(1.0, genome.dimension());
        self.mutate_bounded(genome, &default_bounds, rng);
    }

    fn mutation_probability(&self) -> Option<f64> {
        self.mutation_probability
    }
}

impl BoundedMutationOperator<RealVector> for UniformMutation {
    fn mutate_bounded<R: Rng>(&self, genome: &mut RealVector, bounds: &MultiBounds, rng: &mut R) {
        let n = genome.dimension();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);

        for i in 0..n {
            if rng.gen::<f64>() < prob {
                if let Some(bound) = bounds.get(i) {
                    genome.genes_mut()[i] = rng.gen_range(bound.min..=bound.max);
                }
            }
        }
    }
}

/// Bit-flip mutation for bit strings
///
/// Flips each bit with a given probability.
#[derive(Clone, Debug)]
pub struct BitFlipMutation {
    /// Per-bit mutation probability (default: 1/n)
    pub mutation_probability: Option<f64>,
}

impl BitFlipMutation {
    /// Create a new bit-flip mutation
    pub fn new() -> Self {
        Self {
            mutation_probability: None,
        }
    }

    /// Set a fixed mutation probability per bit
    pub fn with_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.mutation_probability = Some(probability);
        self
    }
}

impl Default for BitFlipMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<BitString> for BitFlipMutation {
    fn mutate<R: Rng>(&self, genome: &mut BitString, rng: &mut R) {
        let n = genome.len();
        let prob = self.mutation_probability.unwrap_or(1.0 / n as f64);

        for i in 0..n {
            if rng.gen::<f64>() < prob {
                genome.flip(i);
            }
        }
    }

    fn mutation_probability(&self) -> Option<f64> {
        self.mutation_probability
    }
}

/// Swap mutation for permutation genomes (also works on any genome)
///
/// Swaps two random positions in the genome.
#[derive(Clone, Debug)]
pub struct SwapMutation {
    /// Number of swaps to perform
    pub num_swaps: usize,
}

impl SwapMutation {
    /// Create a new swap mutation with a single swap
    pub fn new() -> Self {
        Self { num_swaps: 1 }
    }

    /// Create with multiple swaps
    pub fn with_swaps(num_swaps: usize) -> Self {
        Self { num_swaps }
    }
}

impl Default for SwapMutation {
    /// Delegates to [`SwapMutation::new`] (a single swap). A derived `Default`
    /// would set `num_swaps = 0`, producing a silent no-op operator (EV-101).
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<BitString> for SwapMutation {
    fn mutate<R: Rng>(&self, genome: &mut BitString, rng: &mut R) {
        let n = genome.len();
        if n < 2 {
            return;
        }

        for _ in 0..self.num_swaps {
            let i = rng.gen_range(0..n);
            let j = rng.gen_range(0..n);
            if i != j {
                let temp = genome.bits()[i];
                genome.bits_mut()[i] = genome.bits()[j];
                genome.bits_mut()[j] = temp;
            }
        }
    }
}

impl MutationOperator<RealVector> for SwapMutation {
    fn mutate<R: Rng>(&self, genome: &mut RealVector, rng: &mut R) {
        let n = genome.dimension();
        if n < 2 {
            return;
        }

        for _ in 0..self.num_swaps {
            let i = rng.gen_range(0..n);
            let j = rng.gen_range(0..n);
            if i != j {
                genome.genes_mut().swap(i, j);
            }
        }
    }
}

/// Scramble mutation
///
/// Scrambles a random segment of the genome.
#[derive(Clone, Debug, Default)]
pub struct ScrambleMutation;

impl ScrambleMutation {
    /// Create a new scramble mutation
    pub fn new() -> Self {
        Self
    }
}

impl MutationOperator<BitString> for ScrambleMutation {
    fn mutate<R: Rng>(&self, genome: &mut BitString, rng: &mut R) {
        use rand::seq::SliceRandom;

        let n = genome.len();
        if n < 2 {
            return;
        }

        let mut start = rng.gen_range(0..n);
        let mut end = rng.gen_range(0..n);
        if start > end {
            std::mem::swap(&mut start, &mut end);
        }

        // Extract segment, shuffle, and put back
        let segment: Vec<bool> = (start..=end).map(|i| genome.bits()[i]).collect();
        let mut shuffled = segment;
        shuffled.shuffle(rng);

        for (i, val) in shuffled.into_iter().enumerate() {
            genome.bits_mut()[start + i] = val;
        }
    }
}

impl MutationOperator<RealVector> for ScrambleMutation {
    fn mutate<R: Rng>(&self, genome: &mut RealVector, rng: &mut R) {
        use rand::seq::SliceRandom;

        let n = genome.dimension();
        if n < 2 {
            return;
        }

        let mut start = rng.gen_range(0..n);
        let mut end = rng.gen_range(0..n);
        if start > end {
            std::mem::swap(&mut start, &mut end);
        }

        // Shuffle the segment in place
        let slice = &mut genome.genes_mut()[start..=end];
        slice.shuffle(rng);
    }
}

// =============================================================================
// Permutation Mutation Operators
// =============================================================================

/// Swap mutation for permutation genomes
///
/// Swaps two random positions in the permutation.
/// This is one of the simplest and most commonly used permutation mutations.
#[derive(Clone, Debug)]
pub struct PermutationSwapMutation {
    /// Number of swaps to perform
    pub num_swaps: usize,
}

impl PermutationSwapMutation {
    /// Create a new swap mutation with a single swap
    pub fn new() -> Self {
        Self { num_swaps: 1 }
    }

    /// Create with multiple swaps
    pub fn with_swaps(num_swaps: usize) -> Self {
        Self { num_swaps }
    }
}

impl Default for PermutationSwapMutation {
    /// Delegates to [`PermutationSwapMutation::new`] (a single swap). A derived
    /// `Default` would set `num_swaps = 0`, a silent no-op operator (EV-101).
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<Permutation> for PermutationSwapMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        let n = genome.dimension();
        if n < 2 {
            return;
        }

        for _ in 0..self.num_swaps {
            let i = rng.gen_range(0..n);
            let j = rng.gen_range(0..n);
            if i != j {
                genome.swap(i, j);
            }
        }
    }
}

/// Insert mutation for permutation genomes
///
/// Removes an element from one position and inserts it at another.
/// This preserves adjacencies better than swap mutation.
#[derive(Clone, Debug)]
pub struct InsertMutation {
    /// Number of insert operations to perform
    pub num_inserts: usize,
}

impl InsertMutation {
    /// Create a new insert mutation with a single insert
    pub fn new() -> Self {
        Self { num_inserts: 1 }
    }

    /// Create with multiple inserts
    pub fn with_inserts(num_inserts: usize) -> Self {
        Self { num_inserts }
    }
}

impl Default for InsertMutation {
    /// Delegates to [`InsertMutation::new`] (a single insert). A derived
    /// `Default` would set `num_inserts = 0`, a silent no-op operator (EV-101).
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<Permutation> for InsertMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        let n = genome.dimension();
        if n < 2 {
            return;
        }

        for _ in 0..self.num_inserts {
            let from = rng.gen_range(0..n);
            let to = rng.gen_range(0..n);
            if from != to {
                genome.insert(from, to);
            }
        }
    }
}

/// Inversion mutation (2-opt) for permutation genomes
///
/// Reverses a random segment of the permutation.
/// This is particularly effective for TSP-like problems as it can
/// remove crossing edges.
#[derive(Clone, Debug, Default)]
pub struct InversionMutation;

impl InversionMutation {
    /// Create a new inversion mutation
    pub fn new() -> Self {
        Self
    }
}

impl MutationOperator<Permutation> for InversionMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        let n = genome.dimension();
        if n < 2 {
            return;
        }

        let mut start = rng.gen_range(0..n);
        let mut end = rng.gen_range(0..n);
        if start > end {
            std::mem::swap(&mut start, &mut end);
        }

        genome.reverse_segment(start, end);
    }
}

/// Scramble mutation for permutation genomes
///
/// Shuffles a random segment of the permutation.
/// More disruptive than inversion, but still preserves some structure.
#[derive(Clone, Debug, Default)]
pub struct PermutationScrambleMutation;

impl PermutationScrambleMutation {
    /// Create a new scramble mutation
    pub fn new() -> Self {
        Self
    }
}

impl MutationOperator<Permutation> for PermutationScrambleMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        use rand::seq::SliceRandom;

        let n = genome.dimension();
        if n < 2 {
            return;
        }

        let mut start = rng.gen_range(0..n);
        let mut end = rng.gen_range(0..n);
        if start > end {
            std::mem::swap(&mut start, &mut end);
        }

        // Shuffle the segment
        let perm = genome.permutation_mut();
        perm[start..=end].shuffle(rng);
    }
}

/// Displacement mutation for permutation genomes
///
/// Selects a segment, removes it, and inserts it at a random position.
/// This is similar to insert mutation but operates on segments.
#[derive(Clone, Debug, Default)]
pub struct DisplacementMutation;

impl DisplacementMutation {
    /// Create a new displacement mutation
    pub fn new() -> Self {
        Self
    }
}

impl MutationOperator<Permutation> for DisplacementMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        let n = genome.dimension();
        if n < 3 {
            return;
        }

        // Select segment
        let mut start = rng.gen_range(0..n);
        let mut end = rng.gen_range(0..n);
        if start > end {
            std::mem::swap(&mut start, &mut end);
        }

        let segment_len = end - start + 1;
        if segment_len >= n {
            return; // Can't displace the entire permutation
        }

        // Extract segment
        let perm = genome.permutation_mut();
        let segment: Vec<usize> = perm[start..=end].to_vec();

        // Remove segment
        let remaining: Vec<usize> = perm[..start]
            .iter()
            .chain(perm[end + 1..].iter())
            .copied()
            .collect();

        // Choose insertion point in remaining
        let insert_pos = rng.gen_range(0..=remaining.len());

        // Rebuild permutation
        let new_perm: Vec<usize> = remaining[..insert_pos]
            .iter()
            .chain(segment.iter())
            .chain(remaining[insert_pos..].iter())
            .copied()
            .collect();

        perm.copy_from_slice(&new_perm);
    }
}

/// Adaptive mutation rate for permutation genomes
///
/// Combines multiple mutation operators with configurable probabilities.
#[derive(Clone, Debug)]
pub struct AdaptivePermutationMutation {
    /// Probability of swap mutation
    pub swap_prob: f64,
    /// Probability of insert mutation
    pub insert_prob: f64,
    /// Probability of inversion mutation
    pub inversion_prob: f64,
    /// Probability of scramble mutation
    pub scramble_prob: f64,
}

impl AdaptivePermutationMutation {
    /// Create with default probabilities (each equally likely)
    pub fn new() -> Self {
        Self {
            swap_prob: 0.25,
            insert_prob: 0.25,
            inversion_prob: 0.25,
            scramble_prob: 0.25,
        }
    }

    /// Create with custom probabilities
    pub fn with_probs(swap: f64, insert: f64, inversion: f64, scramble: f64) -> Self {
        Self {
            swap_prob: swap,
            insert_prob: insert,
            inversion_prob: inversion,
            scramble_prob: scramble,
        }
    }
}

impl Default for AdaptivePermutationMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl MutationOperator<Permutation> for AdaptivePermutationMutation {
    fn mutate<R: Rng>(&self, genome: &mut Permutation, rng: &mut R) {
        let total = self.swap_prob + self.insert_prob + self.inversion_prob + self.scramble_prob;
        if total <= 0.0 {
            return;
        }

        let r = rng.gen::<f64>() * total;
        let mut cumulative = 0.0;

        cumulative += self.swap_prob;
        if r < cumulative {
            PermutationSwapMutation::new().mutate(genome, rng);
            return;
        }

        cumulative += self.insert_prob;
        if r < cumulative {
            InsertMutation::new().mutate(genome, rng);
            return;
        }

        cumulative += self.inversion_prob;
        if r < cumulative {
            InversionMutation::new().mutate(genome, rng);
            return;
        }

        PermutationScrambleMutation::new().mutate(genome, rng);
    }
}

// =============================================================================
// Tree (GP) Mutation Operators
// =============================================================================

/// Point mutation for tree genomes (genetic programming)
///
/// Selects a random node and replaces it with a new random node of the same
/// type. For function nodes, the replacement has the same arity. For terminal
/// nodes, another random terminal is selected.
///
/// This is a non-destructive mutation that preserves tree structure while
/// changing individual nodes.
#[derive(Clone, Debug)]
pub struct PointMutation {
    /// Per-node mutation probability
    pub mutation_probability: f64,
    /// Probability of selecting a function node (vs terminal)
    pub function_probability: f64,
}

impl PointMutation {
    /// Create a new point mutation with default settings
    ///
    /// Defaults: 0.1 per-node probability, 0.9 function probability
    pub fn new() -> Self {
        Self {
            mutation_probability: 0.1,
            function_probability: 0.9,
        }
    }

    /// Set the per-node mutation probability
    pub fn with_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.mutation_probability = probability;
        self
    }

    /// Set the function selection probability
    pub fn with_function_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.function_probability = probability;
        self
    }

    /// Mutate a single node *in place*, preserving its arity.
    ///
    /// A terminal is replaced with a fresh random terminal; a function is swapped
    /// for a randomly chosen function of the same arity (its children are left
    /// untouched, so tree structure is preserved). In-place mutation via `&mut`
    /// (rather than returning a new owned node) is what lets the whole traversal
    /// avoid moving values out of an owned `TreeNode`, which would conflict with
    /// `TreeNode`'s stack-safe `Drop` impl (EV-60).
    fn mutate_node_in_place<T: Terminal, F: Function, R: Rng>(
        &self,
        node: &mut TreeNode<T, F>,
        rng: &mut R,
    ) {
        match node {
            TreeNode::Terminal(t) => *t = T::random(rng),
            TreeNode::Function(func, _children) => {
                let target_arity = func.arity();
                let matching_funcs: Vec<&F> = F::functions()
                    .iter()
                    .filter(|f| f.arity() == target_arity)
                    .collect();
                if !matching_funcs.is_empty() {
                    *func = matching_funcs[rng.gen_range(0..matching_funcs.len())].clone();
                }
                // Children are preserved: point mutation keeps arity/structure.
            }
        }
    }
}

impl Default for PointMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Terminal, F: Function> MutationOperator<TreeGenome<T, F>> for PointMutation {
    fn mutate<R: Rng>(&self, genome: &mut TreeGenome<T, F>, rng: &mut R) {
        // Iterative (explicit-stack) in-place point mutation (EV-60): visit every
        // node without recursion so a pathologically deep tree cannot overflow the
        // call stack. Each node is independently mutated with probability
        // `mutation_probability`; point mutation preserves arity, so children are
        // left in place and only the node's own label may change.
        let mut stack: Vec<&mut TreeNode<T, F>> = vec![&mut genome.root];
        while let Some(node) = stack.pop() {
            if rng.gen::<f64>() < self.mutation_probability {
                self.mutate_node_in_place(node, rng);
            }
            if let TreeNode::Function(_, children) = node {
                for child in children.iter_mut() {
                    stack.push(child);
                }
            }
        }
    }

    fn mutation_probability(&self) -> Option<f64> {
        Some(self.mutation_probability)
    }
}

/// Subtree mutation for tree genomes (genetic programming)
///
/// Replaces a randomly selected subtree with a new randomly generated subtree.
/// This is a more disruptive mutation than point mutation.
#[derive(Clone, Debug)]
pub struct SubtreeMutation {
    /// Maximum depth of the generated subtree
    pub max_subtree_depth: usize,
    /// Probability of selecting a function node for replacement
    pub function_probability: f64,
    /// Terminal probability for grow method
    pub terminal_probability: f64,
}

impl SubtreeMutation {
    /// Create a new subtree mutation with default settings
    pub fn new() -> Self {
        Self {
            max_subtree_depth: 4,
            function_probability: 0.9,
            terminal_probability: 0.3,
        }
    }

    /// Set the maximum depth for generated subtrees
    pub fn with_max_depth(mut self, depth: usize) -> Self {
        self.max_subtree_depth = depth;
        self
    }

    /// Set the function selection probability
    pub fn with_function_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.function_probability = probability;
        self
    }

    /// Set the terminal probability for tree generation
    pub fn with_terminal_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.terminal_probability = probability;
        self
    }
}

impl Default for SubtreeMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Terminal, F: Function> MutationOperator<TreeGenome<T, F>> for SubtreeMutation {
    fn mutate<R: Rng>(&self, genome: &mut TreeGenome<T, F>, rng: &mut R) {
        // Decide whether to select a function or terminal position
        let position = if rng.gen::<f64>() < self.function_probability {
            genome
                .random_function_position(rng)
                .unwrap_or_else(|| genome.random_terminal_position(rng).unwrap_or_default())
        } else {
            genome
                .random_terminal_position(rng)
                .unwrap_or_else(|| genome.random_function_position(rng).unwrap_or_default())
        };

        // Depth budget for the replacement subtree (EV-27).
        //
        // `position` has one entry per edge from the root, so the selected node
        // sits at tree level `position.len() + 1` (the root is level 1).
        // Replacing it with a subtree `S` yields a tree whose depth along that
        // branch is `position.len() + S.depth()`. To keep the whole tree within
        // `genome.max_depth` we require `S.depth() <= max_depth - position.len()`.
        let point_depth = position.len();
        let budget = genome
            .max_depth
            .saturating_sub(point_depth)
            .min(self.max_subtree_depth)
            .max(1);

        // `TreeGenome::generate_grow(_, m, _)` can produce a subtree whose
        // `depth()` is up to `m + 1` (a function node may be created at the last
        // permitted level and still receives terminal children one level
        // deeper). We therefore ask for `budget - 1` so the result's depth is at
        // most `budget`.
        let new_root =
            TreeGenome::<T, F>::generate_grow(rng, budget - 1, self.terminal_probability).root;

        // Defensive guard mirroring SubtreeCrossover: if the generated subtree
        // would still violate the depth limit, fall back to a single terminal,
        // which always fits since `budget >= 1`.
        let new_root = if point_depth + new_root.depth() > genome.max_depth {
            TreeNode::Terminal(T::random(rng))
        } else {
            new_root
        };

        // Replace the subtree
        genome.root.replace_subtree(&position, new_root);
    }
}

/// Hoist mutation for tree genomes (genetic programming)
///
/// Selects a random subtree and replaces the entire tree with it.
/// This is useful for bloat control.
#[derive(Clone, Debug, Default)]
pub struct HoistMutation {
    /// Probability of selecting a function node
    pub function_probability: f64,
}

impl HoistMutation {
    /// Create a new hoist mutation
    pub fn new() -> Self {
        Self {
            function_probability: 0.5,
        }
    }

    /// Set the function selection probability
    pub fn with_function_probability(mut self, probability: f64) -> Self {
        assert!(
            (0.0..=1.0).contains(&probability),
            "Probability must be in [0, 1]"
        );
        self.function_probability = probability;
        self
    }
}

impl<T: Terminal, F: Function> MutationOperator<TreeGenome<T, F>> for HoistMutation {
    fn mutate<R: Rng>(&self, genome: &mut TreeGenome<T, F>, rng: &mut R) {
        // Select a random position (prefer function nodes to make it interesting)
        let position = if rng.gen::<f64>() < self.function_probability {
            genome
                .random_function_position(rng)
                .unwrap_or_else(|| genome.random_terminal_position(rng).unwrap_or_default())
        } else {
            genome.random_position(rng)
        };

        // Skip if selecting the root (no change)
        if position.is_empty() {
            return;
        }

        // Get the subtree and make it the new root
        if let Some(subtree) = genome.root.get_subtree(&position) {
            genome.root = subtree.clone();
        }
    }
}

/// Shrink mutation for tree genomes (genetic programming)
///
/// Replaces a randomly selected subtree with one of its terminals.
/// This reduces tree size and helps with bloat control.
#[derive(Clone, Debug, Default)]
pub struct ShrinkMutation;

impl ShrinkMutation {
    /// Create a new shrink mutation
    pub fn new() -> Self {
        Self
    }
}

impl<T: Terminal, F: Function> MutationOperator<TreeGenome<T, F>> for ShrinkMutation {
    fn mutate<R: Rng>(&self, genome: &mut TreeGenome<T, F>, rng: &mut R) {
        // Find a function node to shrink
        if let Some(func_position) = genome.random_function_position(rng) {
            // Skip root to maintain some structure
            if func_position.is_empty() {
                return;
            }

            // Get a terminal from within the selected subtree
            if let Some(subtree) = genome.root.get_subtree(&func_position) {
                let terminal_positions = subtree.terminal_positions();
                if !terminal_positions.is_empty() {
                    // Pick a random terminal from the subtree
                    let term_pos = &terminal_positions[rng.gen_range(0..terminal_positions.len())];

                    // Get the terminal value
                    if let Some(terminal_node) = subtree.get_subtree(term_pos) {
                        let replacement = terminal_node.clone();
                        // Replace the function node with the terminal
                        genome.root.replace_subtree(&func_position, replacement);
                    }
                }
            }
        }
    }
}

/// Adaptive mutation for tree genomes (genetic programming)
///
/// Combines multiple tree mutations with configurable probabilities.
#[derive(Clone, Debug)]
pub struct AdaptiveTreeMutation {
    /// Probability of point mutation
    pub point_prob: f64,
    /// Probability of subtree mutation
    pub subtree_prob: f64,
    /// Probability of hoist mutation
    pub hoist_prob: f64,
    /// Probability of shrink mutation
    pub shrink_prob: f64,
}

impl AdaptiveTreeMutation {
    /// Create with default probabilities
    pub fn new() -> Self {
        Self {
            point_prob: 0.4,
            subtree_prob: 0.3,
            hoist_prob: 0.15,
            shrink_prob: 0.15,
        }
    }

    /// Create with custom probabilities
    pub fn with_probs(point: f64, subtree: f64, hoist: f64, shrink: f64) -> Self {
        Self {
            point_prob: point,
            subtree_prob: subtree,
            hoist_prob: hoist,
            shrink_prob: shrink,
        }
    }
}

impl Default for AdaptiveTreeMutation {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Terminal, F: Function> MutationOperator<TreeGenome<T, F>> for AdaptiveTreeMutation {
    fn mutate<R: Rng>(&self, genome: &mut TreeGenome<T, F>, rng: &mut R) {
        let total = self.point_prob + self.subtree_prob + self.hoist_prob + self.shrink_prob;
        if total <= 0.0 {
            return;
        }

        let r = rng.gen::<f64>() * total;
        let mut cumulative = 0.0;

        cumulative += self.point_prob;
        if r < cumulative {
            PointMutation::new().mutate(genome, rng);
            return;
        }

        cumulative += self.subtree_prob;
        if r < cumulative {
            SubtreeMutation::new().mutate(genome, rng);
            return;
        }

        cumulative += self.hoist_prob;
        if r < cumulative {
            HoistMutation::new().mutate(genome, rng);
            return;
        }

        ShrinkMutation::new().mutate(genome, rng);
    }
}

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

    #[test]
    fn test_polynomial_mutation_respects_bounds() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(5.0, 10);

        for _ in 0..100 {
            let mut genome = RealVector::generate(&mut rng, &bounds);
            let mutation = PolynomialMutation::new(20.0).with_probability(1.0);
            mutation.mutate_bounded(&mut genome, &bounds, &mut rng);

            for (i, &gene) in genome.genes().iter().enumerate() {
                let bound = bounds.get(i).unwrap();
                assert!(
                    gene >= bound.min && gene <= bound.max,
                    "Gene {} out of bounds: {} not in [{}, {}]",
                    i,
                    gene,
                    bound.min,
                    bound.max
                );
            }
        }
    }

    #[test]
    fn test_polynomial_mutation_changes_genome() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(5.0, 10);
        let original = RealVector::zeros(10);
        let mut genome = original.clone();

        let mutation = PolynomialMutation::new(20.0).with_probability(1.0);
        mutation.mutate_bounded(&mut genome, &bounds, &mut rng);

        // At least some genes should have changed
        let changed = genome
            .genes()
            .iter()
            .zip(original.genes())
            .filter(|(&a, &b)| a != b)
            .count();
        assert!(changed > 0, "No genes were mutated");
    }

    #[test]
    fn test_polynomial_mutation_eta_effect() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(1.0, 1);

        // Low eta = larger mutations
        let low_eta = PolynomialMutation::new(1.0).with_probability(1.0);
        // High eta = smaller mutations
        let high_eta = PolynomialMutation::new(100.0).with_probability(1.0);

        let mut low_total_change = 0.0;
        let mut high_total_change = 0.0;
        let trials = 1000;

        for _ in 0..trials {
            let mut genome_low = RealVector::new(vec![0.0]);
            let mut genome_high = RealVector::new(vec![0.0]);

            low_eta.mutate_bounded(&mut genome_low, &bounds, &mut rng);
            high_eta.mutate_bounded(&mut genome_high, &bounds, &mut rng);

            low_total_change += genome_low[0].abs();
            high_total_change += genome_high[0].abs();
        }

        assert!(
            low_total_change > high_total_change,
            "Low eta should produce larger average changes"
        );
    }

    #[test]
    fn test_gaussian_mutation_changes_genome() {
        let mut rng = rand::thread_rng();
        let original = RealVector::zeros(10);
        let mut genome = original.clone();

        let mutation = GaussianMutation::new(0.1).with_probability(1.0);
        mutation.mutate(&mut genome, &mut rng);

        assert_ne!(genome, original);
    }

    #[test]
    fn test_gaussian_mutation_bounded() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(1.0, 10);

        for _ in 0..100 {
            let mut genome = RealVector::zeros(10);
            let mutation = GaussianMutation::new(10.0).with_probability(1.0);
            mutation.mutate_bounded(&mut genome, &bounds, &mut rng);

            for (i, &gene) in genome.genes().iter().enumerate() {
                let bound = bounds.get(i).unwrap();
                assert!(gene >= bound.min && gene <= bound.max);
            }
        }
    }

    #[test]
    fn test_uniform_mutation() {
        let mut rng = rand::thread_rng();
        let bounds = MultiBounds::symmetric(1.0, 10);

        for _ in 0..100 {
            let mut genome = RealVector::zeros(10);
            let mutation = UniformMutation::new().with_probability(1.0);
            mutation.mutate_bounded(&mut genome, &bounds, &mut rng);

            for (i, &gene) in genome.genes().iter().enumerate() {
                let bound = bounds.get(i).unwrap();
                assert!(gene >= bound.min && gene <= bound.max);
            }
        }
    }

    #[test]
    fn test_bit_flip_mutation() {
        let mut rng = rand::thread_rng();
        let original = BitString::zeros(100);
        let mut genome = original.clone();

        let mutation = BitFlipMutation::new().with_probability(0.5);
        mutation.mutate(&mut genome, &mut rng);

        // About half should be flipped
        let flipped = genome.count_ones();
        assert!(
            flipped > 20 && flipped < 80,
            "Expected ~50 flips, got {}",
            flipped
        );
    }

    #[test]
    fn test_bit_flip_mutation_default_probability() {
        let mut rng = rand::thread_rng();
        let original = BitString::zeros(100);
        let mut genome = original.clone();

        let mutation = BitFlipMutation::new(); // 1/n probability
        mutation.mutate(&mut genome, &mut rng);

        // With 1/100 probability, expect ~1 flip on average
        // But due to randomness, we just check some change occurred
        // over multiple trials
        let mut total_flips = 0;
        for _ in 0..100 {
            let mut g = BitString::zeros(100);
            mutation.mutate(&mut g, &mut rng);
            total_flips += g.count_ones();
        }

        // Average should be close to 1
        let avg = total_flips as f64 / 100.0;
        assert!(avg > 0.5 && avg < 2.0, "Expected avg ~1, got {}", avg);
    }

    #[test]
    fn test_swap_mutation() {
        let mut rng = rand::thread_rng();
        let mut genome = RealVector::new(vec![0.0, 1.0, 2.0, 3.0, 4.0]);

        let mutation = SwapMutation::new();
        mutation.mutate(&mut genome, &mut rng);

        // The sum should be preserved
        let sum: f64 = genome.genes().iter().sum();
        assert_relative_eq!(sum, 10.0);
    }

    #[test]
    fn test_swap_mutation_multiple() {
        let mut rng = rand::thread_rng();
        let original: Vec<f64> = (0..10).map(|i| i as f64).collect();
        let mut genome = RealVector::new(original.clone());

        let mutation = SwapMutation::with_swaps(5);
        mutation.mutate(&mut genome, &mut rng);

        // Sum should be preserved
        let sum: f64 = genome.genes().iter().sum();
        assert_relative_eq!(sum, 45.0);
    }

    #[test]
    fn test_scramble_mutation() {
        let mut rng = rand::thread_rng();
        let original: Vec<f64> = (0..10).map(|i| i as f64).collect();
        let mut genome = RealVector::new(original.clone());

        let mutation = ScrambleMutation::new();
        mutation.mutate(&mut genome, &mut rng);

        // Sum should be preserved
        let sum: f64 = genome.genes().iter().sum();
        assert_relative_eq!(sum, 45.0);

        // All values should still be present
        let mut sorted: Vec<f64> = genome.genes().to_vec();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        assert_eq!(sorted, original);
    }

    #[test]
    fn test_scramble_mutation_bitstring() {
        let mut rng = rand::thread_rng();
        let original = BitString::new(vec![true, true, true, false, false, false, true, false]);
        let mut genome = original.clone();

        let mutation = ScrambleMutation::new();
        mutation.mutate(&mut genome, &mut rng);

        // Count should be preserved
        assert_eq!(genome.count_ones(), original.count_ones());
    }

    // =========================================================================
    // Permutation Mutation Tests
    // =========================================================================

    #[test]
    fn test_permutation_swap_mutation() {
        let mut rng = rand::thread_rng();
        let original = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);
        let mut genome = original.clone();

        let mutation = PermutationSwapMutation::new();
        mutation.mutate(&mut genome, &mut rng);

        // Should still be valid permutation
        assert!(genome.is_valid_permutation());
        assert_eq!(genome.dimension(), 8);
    }

    #[test]
    fn test_permutation_swap_mutation_multiple() {
        let mut rng = rand::thread_rng();
        let original = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
        let mut genome = original.clone();

        let mutation = PermutationSwapMutation::with_swaps(5);
        mutation.mutate(&mut genome, &mut rng);

        // Should still be valid permutation
        assert!(genome.is_valid_permutation());
        assert_eq!(genome.dimension(), 10);
    }

    #[test]
    fn test_insert_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..50 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);

            let mutation = InsertMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
            assert_eq!(genome.dimension(), 8);
        }
    }

    #[test]
    fn test_inversion_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..50 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);

            let mutation = InversionMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
            assert_eq!(genome.dimension(), 8);
        }
    }

    #[test]
    fn test_inversion_mutation_reverses_segment() {
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);

        let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);

        let mutation = InversionMutation::new();
        mutation.mutate(&mut genome, &mut rng);

        // Should still be valid permutation
        assert!(genome.is_valid_permutation());
    }

    #[test]
    fn test_permutation_scramble_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..50 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);

            let mutation = PermutationScrambleMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
            assert_eq!(genome.dimension(), 8);
        }
    }

    #[test]
    fn test_displacement_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..50 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);

            let mutation = DisplacementMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
            assert_eq!(genome.dimension(), 10);
        }
    }

    #[test]
    fn test_adaptive_permutation_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..100 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);

            let mutation = AdaptivePermutationMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
            assert_eq!(genome.dimension(), 8);
        }
    }

    #[test]
    fn test_adaptive_permutation_mutation_custom_probs() {
        let mut rng = rand::thread_rng();

        // Test with only inversion mutation
        let mutation = AdaptivePermutationMutation::with_probs(0.0, 0.0, 1.0, 0.0);

        for _ in 0..50 {
            let mut genome = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);
            mutation.mutate(&mut genome, &mut rng);

            assert!(genome.is_valid_permutation());
        }
    }

    // =========================================================================
    // Tree (GP) Mutation Tests
    // =========================================================================

    use crate::genome::tree::{ArithmeticFunction, ArithmeticTerminal};

    fn create_test_tree() -> TreeGenome<ArithmeticTerminal, ArithmeticFunction> {
        // Create: (+ x0 (* 1.0 x1))
        let x0 = TreeNode::terminal(ArithmeticTerminal::Variable(0));
        let c1 = TreeNode::terminal(ArithmeticTerminal::Constant(1.0));
        let x1 = TreeNode::terminal(ArithmeticTerminal::Variable(1));
        let mul = TreeNode::function(ArithmeticFunction::Mul, vec![c1, x1]);
        let add = TreeNode::function(ArithmeticFunction::Add, vec![x0, mul]);
        TreeGenome::new(add, 5)
    }

    #[test]
    fn test_point_mutation_preserves_structure() {
        let mut rng = rand::thread_rng();
        let original = create_test_tree();
        let original_size = original.size();

        for _ in 0..50 {
            let mut genome = original.clone();
            let mutation = PointMutation::new().with_probability(1.0);
            mutation.mutate(&mut genome, &mut rng);

            // Point mutation preserves tree structure (size)
            assert_eq!(genome.size(), original_size);
            assert!(genome.evaluate(&[1.0, 2.0]).is_finite());
        }
    }

    #[test]
    fn test_point_mutation_changes_tree() {
        let mut rng = rand::thread_rng();
        let original = create_test_tree();
        let mut any_changed = false;

        for _ in 0..100 {
            let mut genome = original.clone();
            let mutation = PointMutation::new().with_probability(1.0);
            mutation.mutate(&mut genome, &mut rng);

            // Check if the evaluation changed (indicates mutation occurred)
            let orig_val = original.evaluate(&[1.0, 2.0]);
            let new_val = genome.evaluate(&[1.0, 2.0]);
            if (orig_val - new_val).abs() > 1e-10 {
                any_changed = true;
                break;
            }
        }

        assert!(
            any_changed,
            "Point mutation should sometimes change the tree"
        );
    }

    #[test]
    fn test_point_mutation_deep_tree_no_stack_overflow() {
        // regression: EV-60 — PointMutation must traverse iteratively so a
        // ~100k-deep tree can be mutated without overflowing the call stack. The
        // previous recursive `mutate_recursive` overflowed at this depth.
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(7);
        let depth = 100_000usize;
        let mut root: TreeNode<ArithmeticTerminal, ArithmeticFunction> =
            TreeNode::terminal(ArithmeticTerminal::Constant(1.0));
        for _ in 0..depth {
            root = TreeNode::function(ArithmeticFunction::Neg, vec![root]);
        }
        let mut genome = TreeGenome::new(root, depth + 1);
        let size_before = genome.size();

        // mutate every node (probability 1.0) — must not overflow.
        PointMutation::new()
            .with_probability(1.0)
            .mutate(&mut genome, &mut rng);

        // Point mutation preserves structure (arity/size) even at extreme depth.
        assert_eq!(genome.size(), size_before);
        // Free iteratively so the test itself doesn't overflow on teardown.
        genome.dismantle();
    }

    #[test]
    fn test_subtree_mutation() {
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(42);
        let original = create_test_tree();

        for _ in 0..50 {
            let mut genome = original.clone();
            let mutation = SubtreeMutation::new().with_max_depth(3);
            mutation.mutate(&mut genome, &mut rng);

            // Tree should still be valid and have at least one node
            assert!(genome.size() >= 1);
            // Subtree mutation may generate expressions that are NaN/Inf for some inputs
            // (e.g., division by zero), so we only check structural validity
            let result = genome.evaluate(&[1.0, 2.0]);
            assert!(result.is_nan() || result.is_finite());
        }
    }

    #[test]
    fn test_hoist_mutation_reduces_tree() {
        let mut rng = rand::thread_rng();

        // Create a deeper tree
        let tree: TreeGenome<ArithmeticTerminal, ArithmeticFunction> =
            TreeGenome::generate_full(&mut rng, 4, 5);

        let original_size = tree.size();

        for _ in 0..50 {
            let mut genome = tree.clone();
            let mutation = HoistMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            // Hoist mutation should reduce or maintain tree size
            assert!(genome.size() <= original_size);
            assert!(genome.evaluate(&[1.0, 2.0]).is_finite());
        }
    }

    #[test]
    fn test_shrink_mutation_reduces_tree() {
        let mut rng = rand::thread_rng();

        // Create a deeper tree
        let tree: TreeGenome<ArithmeticTerminal, ArithmeticFunction> =
            TreeGenome::generate_full(&mut rng, 4, 5);

        for _ in 0..50 {
            let mut genome = tree.clone();
            let original_size = genome.size();
            let mutation = ShrinkMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            // Shrink mutation should reduce or maintain tree size
            assert!(genome.size() <= original_size);
            assert!(genome.evaluate(&[1.0, 2.0]).is_finite());
        }
    }

    #[test]
    fn test_adaptive_tree_mutation() {
        let mut rng = rand::thread_rng();

        for _ in 0..100 {
            let mut genome: TreeGenome<ArithmeticTerminal, ArithmeticFunction> =
                TreeGenome::generate_ramped_half_and_half(&mut rng, 2, 5);

            let mutation = AdaptiveTreeMutation::new();
            mutation.mutate(&mut genome, &mut rng);

            // Tree should still be valid
            assert!(genome.size() >= 1);
            assert!(genome.evaluate(&[1.0, 2.0]).is_finite());
        }
    }

    #[test]
    fn test_adaptive_tree_mutation_custom_probs() {
        let mut rng = rand::thread_rng();

        // Test with only point mutation
        let mutation = AdaptiveTreeMutation::with_probs(1.0, 0.0, 0.0, 0.0);

        for _ in 0..50 {
            let mut genome: TreeGenome<ArithmeticTerminal, ArithmeticFunction> =
                TreeGenome::generate_ramped_half_and_half(&mut rng, 2, 5);
            let original_size = genome.size();
            mutation.mutate(&mut genome, &mut rng);

            // Point mutation preserves structure
            assert_eq!(genome.size(), original_size);
        }
    }

    #[test]
    fn test_subtree_mutation_respects_max_depth() {
        // regression: EV-27 — SubtreeMutation must never grow a tree beyond its
        // `max_depth`. Pre-fix, the depth budget was off by one (generate_grow
        // can produce a subtree one level deeper than requested) and the
        // violation compounded across repeated mutations. Fuzz 500 mutations
        // with a large `max_subtree_depth` (to stress the budget) and assert the
        // depth invariant after every single mutation.
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(2024);

        let max_depth = 5;
        // Start from a valid full tree at exactly `max_depth`
        // (generate_full(_, d, _) yields depth d + 1).
        let mut genome: TreeGenome<ArithmeticTerminal, ArithmeticFunction> =
            TreeGenome::generate_full(&mut rng, max_depth - 1, max_depth);
        assert!(genome.depth() <= max_depth);

        // Large subtree budget + low terminal probability => generate_grow tends
        // to emit functions, maximally exercising the off-by-one path.
        let mutation = SubtreeMutation::new()
            .with_max_depth(12)
            .with_terminal_probability(0.1);

        for i in 0..500 {
            mutation.mutate(&mut genome, &mut rng);
            assert!(
                genome.depth() <= max_depth,
                "iteration {i}: tree depth {} exceeded max_depth {max_depth}",
                genome.depth()
            );
        }
    }

    #[test]
    fn test_default_swap_mutations_actually_mutate() {
        // regression: EV-101 — SwapMutation / PermutationSwapMutation /
        // InsertMutation previously derived Default, giving num=0 (a silent
        // no-op). Default::default() must now behave like new() (num=1) and
        // actually change the genome.
        assert_eq!(SwapMutation::default().num_swaps, 1);
        assert_eq!(PermutationSwapMutation::default().num_swaps, 1);
        assert_eq!(InsertMutation::default().num_inserts, 1);

        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(99);

        // A default SwapMutation must eventually move genes (num_swaps=0 never would).
        let mut any_changed = false;
        for _ in 0..50 {
            let original = RealVector::new(vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]);
            let mut genome = original.clone();
            SwapMutation::default().mutate(&mut genome, &mut rng);
            if genome.genes() != original.genes() {
                any_changed = true;
                break;
            }
        }
        assert!(
            any_changed,
            "Default SwapMutation never mutated (num_swaps == 0?)"
        );

        // Default permutation swap: a valid perm with a moved element.
        let mut perm_changed = false;
        for _ in 0..50 {
            let original = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);
            let mut genome = original.clone();
            PermutationSwapMutation::default().mutate(&mut genome, &mut rng);
            if genome.as_slice() != original.as_slice() {
                perm_changed = true;
                break;
            }
        }
        assert!(
            perm_changed,
            "Default PermutationSwapMutation never mutated (num_swaps == 0?)"
        );

        // Default insert mutation.
        let mut insert_changed = false;
        for _ in 0..50 {
            let original = Permutation::new(vec![0, 1, 2, 3, 4, 5, 6, 7]);
            let mut genome = original.clone();
            InsertMutation::default().mutate(&mut genome, &mut rng);
            if genome.as_slice() != original.as_slice() {
                insert_changed = true;
                break;
            }
        }
        assert!(
            insert_changed,
            "Default InsertMutation never mutated (num_inserts == 0?)"
        );
    }

    #[test]
    fn test_unbounded_polynomial_mutation_stays_local() {
        // regression: EV-102 — the unbounded PolynomialMutation path used to
        // fabricate +/-1e10 bounds, turning a mutation into a near-random reset
        // spanning ~1e10 in magnitude. It must instead apply a local Gaussian
        // perturbation and keep genes near their original values.
        use rand::SeedableRng;
        let mut rng = rand::rngs::StdRng::seed_from_u64(1);

        for _ in 0..200 {
            let mut genome = RealVector::new(vec![0.0, 1.0, -1.0, 2.5, -3.0]);
            let mutation = PolynomialMutation::new(20.0).with_probability(1.0);
            mutation.mutate(&mut genome, &mut rng); // unbounded path

            for &g in genome.genes() {
                assert!(
                    g.abs() < 100.0,
                    "unbounded polynomial mutation produced a destructive value: {g}"
                );
            }
        }

        // A fixed sigma is honored.
        let mut genome = RealVector::new(vec![0.0; 1000]);
        let mutation = PolynomialMutation::new(20.0)
            .with_probability(1.0)
            .with_unbounded_sigma(0.05);
        mutation.mutate(&mut genome, &mut rng);
        let variance: f64 =
            genome.genes().iter().map(|g| g * g).sum::<f64>() / genome.dimension() as f64;
        // Sample std should be near 0.05 (well under any 1e10 fabrication).
        assert!(
            variance.sqrt() < 0.2,
            "fixed sigma not honored: std {}",
            variance.sqrt()
        );
    }

    #[test]
    fn test_mutation_probability_reports_effective_rate() {
        // regression: EV-103 — mutation_probability() used to report 1.0 while
        // the operators actually applied the per-gene default 1/n. It must now
        // report `None` for the length-dependent default and `Some(p)` for a
        // configured rate.
        assert_eq!(
            MutationOperator::<RealVector>::mutation_probability(&PolynomialMutation::new(20.0)),
            None
        );
        assert_eq!(
            MutationOperator::<RealVector>::mutation_probability(
                &PolynomialMutation::new(20.0).with_probability(0.25)
            ),
            Some(0.25)
        );
        assert_eq!(
            MutationOperator::<RealVector>::mutation_probability(&GaussianMutation::new(0.1)),
            None
        );
        assert_eq!(
            MutationOperator::<RealVector>::mutation_probability(&UniformMutation::new()),
            None
        );
        assert_eq!(
            MutationOperator::<BitString>::mutation_probability(&BitFlipMutation::new()),
            None
        );
        assert_eq!(
            MutationOperator::<BitString>::mutation_probability(
                &BitFlipMutation::new().with_probability(0.5)
            ),
            Some(0.5)
        );
    }
}