fugue-evo 0.1.1

A Probabilistic Genetic Algorithm Library for Rust
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
//! Benchmark fitness functions
//!
//! This module provides standard benchmark functions for testing evolutionary algorithms.

use std::f64::consts::PI;

use crate::fitness::traits::Fitness;
use crate::genome::bit_string::BitString;
use crate::genome::real_vector::RealVector;
use crate::genome::traits::{BinaryGenome, RealValuedGenome};

/// Trait for benchmark functions
pub trait BenchmarkFunction: Send + Sync {
    /// Name of the benchmark function
    fn name(&self) -> &'static str;

    /// Dimensionality of the problem
    fn dimension(&self) -> usize;

    /// Search space bounds (min, max)
    fn bounds(&self) -> (f64, f64);

    /// Optimal (minimum) fitness value
    fn optimal_fitness(&self) -> f64;

    /// Optimal solution (if known)
    fn optimal_solution(&self) -> Option<Vec<f64>>;

    /// Evaluate the function (returns value to be MINIMIZED)
    fn evaluate_raw(&self, x: &[f64]) -> f64;
}

/// Sphere function: f(x) = Σxᵢ²
///
/// Unimodal, convex, separable. Optimum at origin.
#[derive(Clone, Debug)]
pub struct Sphere {
    dimension: usize,
}

impl Sphere {
    /// Create a new Sphere function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for Sphere {
    fn name(&self) -> &'static str {
        "Sphere"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-5.12, 5.12)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![0.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        x.iter().map(|xi| xi * xi).sum()
    }
}

impl Fitness for Sphere {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        // Negate for maximization (GA convention)
        -self.evaluate_raw(genome.genes())
    }
}

/// Rastrigin function: f(x) = 10n + Σ(xᵢ² - 10cos(2πxᵢ))
///
/// Highly multimodal with many local minima. Optimum at origin.
#[derive(Clone, Debug)]
pub struct Rastrigin {
    dimension: usize,
}

impl Rastrigin {
    /// Create a new Rastrigin function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for Rastrigin {
    fn name(&self) -> &'static str {
        "Rastrigin"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-5.12, 5.12)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![0.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let a = 10.0;
        let n = x.len() as f64;
        a * n
            + x.iter()
                .map(|xi| xi * xi - a * (2.0 * PI * xi).cos())
                .sum::<f64>()
    }
}

impl Fitness for Rastrigin {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Rosenbrock function: f(x) = Σ[100(xᵢ₊₁-xᵢ²)² + (1-xᵢ)²]
///
/// Valley structure, non-separable. Optimum at (1,1,...,1).
#[derive(Clone, Debug)]
pub struct Rosenbrock {
    dimension: usize,
}

impl Rosenbrock {
    /// Create a new Rosenbrock function
    pub fn new(dimension: usize) -> Self {
        assert!(dimension >= 2, "Rosenbrock requires at least 2 dimensions");
        Self { dimension }
    }
}

impl BenchmarkFunction for Rosenbrock {
    fn name(&self) -> &'static str {
        "Rosenbrock"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-5.0, 10.0)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![1.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        x.windows(2)
            .map(|w| {
                let xi = w[0];
                let xi1 = w[1];
                100.0 * (xi1 - xi * xi).powi(2) + (1.0 - xi).powi(2)
            })
            .sum()
    }
}

impl Fitness for Rosenbrock {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Ackley function
///
/// Nearly flat outer region with many local minima. Optimum at origin.
#[derive(Clone, Debug)]
pub struct Ackley {
    dimension: usize,
    a: f64,
    b: f64,
    c: f64,
}

impl Ackley {
    /// Create a new Ackley function with default parameters
    pub fn new(dimension: usize) -> Self {
        Self {
            dimension,
            a: 20.0,
            b: 0.2,
            c: 2.0 * PI,
        }
    }

    /// Create with custom parameters
    pub fn with_params(dimension: usize, a: f64, b: f64, c: f64) -> Self {
        Self { dimension, a, b, c }
    }
}

impl BenchmarkFunction for Ackley {
    fn name(&self) -> &'static str {
        "Ackley"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-32.768, 32.768)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![0.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let n = x.len() as f64;
        let sum_sq = x.iter().map(|xi| xi * xi).sum::<f64>();
        let sum_cos = x.iter().map(|xi| (self.c * xi).cos()).sum::<f64>();

        -self.a * (-self.b * (sum_sq / n).sqrt()).exp() - (sum_cos / n).exp()
            + self.a
            + std::f64::consts::E
    }
}

impl Fitness for Ackley {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Griewank function: f(x) = Σxᵢ²/4000 - Πcos(xᵢ/√i) + 1
///
/// Many local minima. Optimum at origin.
#[derive(Clone, Debug)]
pub struct Griewank {
    dimension: usize,
}

impl Griewank {
    /// Create a new Griewank function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for Griewank {
    fn name(&self) -> &'static str {
        "Griewank"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-600.0, 600.0)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![0.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let sum_sq: f64 = x.iter().map(|xi| xi * xi).sum::<f64>() / 4000.0;
        let prod_cos: f64 = x
            .iter()
            .enumerate()
            .map(|(i, xi)| (xi / ((i + 1) as f64).sqrt()).cos())
            .product();
        sum_sq - prod_cos + 1.0
    }
}

impl Fitness for Griewank {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Schwefel function
///
/// Deceptive - global optimum far from local optima.
#[derive(Clone, Debug)]
pub struct Schwefel {
    dimension: usize,
}

impl Schwefel {
    /// Create a new Schwefel function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for Schwefel {
    fn name(&self) -> &'static str {
        "Schwefel"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-500.0, 500.0)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![420.9687; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let n = x.len() as f64;
        418.9829 * n - x.iter().map(|xi| xi * xi.abs().sqrt().sin()).sum::<f64>()
    }
}

impl Fitness for Schwefel {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// OneMax function for bit strings
///
/// Counts the number of 1s in the bit string. Optimum when all bits are 1.
#[derive(Clone, Debug)]
pub struct OneMax {
    length: usize,
}

impl OneMax {
    /// Create a new OneMax function
    pub fn new(length: usize) -> Self {
        Self { length }
    }

    /// Get the length
    pub fn length(&self) -> usize {
        self.length
    }
}

impl Fitness for OneMax {
    type Genome = BitString;
    type Value = usize;

    fn evaluate(&self, genome: &Self::Genome) -> usize {
        genome.count_ones()
    }
}

/// LeadingOnes function for bit strings
///
/// Counts the number of leading 1s before the first 0.
#[derive(Clone, Debug)]
pub struct LeadingOnes {
    #[allow(dead_code)]
    length: usize,
}

impl LeadingOnes {
    /// Create a new LeadingOnes function
    pub fn new(length: usize) -> Self {
        Self { length }
    }
}

impl Fitness for LeadingOnes {
    type Genome = BitString;
    type Value = usize;

    fn evaluate(&self, genome: &Self::Genome) -> usize {
        genome.bits().iter().take_while(|&&b| b).count()
    }
}

// =============================================================================
// Multi-Objective Test Problems (ZDT)
// =============================================================================

/// ZDT1 multi-objective test problem
///
/// Two objectives with a convex Pareto front.
/// Reference: Zitzler, E., Deb, K., & Thiele, L. (2000).
#[derive(Clone, Debug)]
pub struct Zdt1 {
    dimension: usize,
}

impl Zdt1 {
    /// Create a new ZDT1 function
    pub fn new(dimension: usize) -> Self {
        assert!(dimension >= 2, "ZDT1 requires at least 2 dimensions");
        Self { dimension }
    }

    /// Evaluate the function (returns [f1, f2])
    pub fn evaluate(&self, x: &[f64]) -> [f64; 2] {
        let n = x.len() as f64;
        let f1 = x[0];
        let g = 1.0 + 9.0 * x[1..].iter().sum::<f64>() / (n - 1.0);
        let f2 = g * (1.0 - (f1 / g).sqrt());
        [f1, f2]
    }

    /// Bounds for each variable [0, 1]
    pub fn bounds(&self) -> (f64, f64) {
        (0.0, 1.0)
    }

    /// Get the dimension
    pub fn dimension(&self) -> usize {
        self.dimension
    }
}

/// ZDT2 multi-objective test problem
///
/// Two objectives with a non-convex Pareto front.
#[derive(Clone, Debug)]
pub struct Zdt2 {
    dimension: usize,
}

impl Zdt2 {
    /// Create a new ZDT2 function
    pub fn new(dimension: usize) -> Self {
        assert!(dimension >= 2, "ZDT2 requires at least 2 dimensions");
        Self { dimension }
    }

    /// Evaluate the function (returns [f1, f2])
    pub fn evaluate(&self, x: &[f64]) -> [f64; 2] {
        let n = x.len() as f64;
        let f1 = x[0];
        let g = 1.0 + 9.0 * x[1..].iter().sum::<f64>() / (n - 1.0);
        let f2 = g * (1.0 - (f1 / g).powi(2));
        [f1, f2]
    }

    /// Bounds for each variable [0, 1]
    pub fn bounds(&self) -> (f64, f64) {
        (0.0, 1.0)
    }

    /// Get the dimension
    pub fn dimension(&self) -> usize {
        self.dimension
    }
}

/// ZDT3 multi-objective test problem
///
/// Two objectives with a disconnected Pareto front.
#[derive(Clone, Debug)]
pub struct Zdt3 {
    dimension: usize,
}

impl Zdt3 {
    /// Create a new ZDT3 function
    pub fn new(dimension: usize) -> Self {
        assert!(dimension >= 2, "ZDT3 requires at least 2 dimensions");
        Self { dimension }
    }

    /// Evaluate the function (returns [f1, f2])
    pub fn evaluate(&self, x: &[f64]) -> [f64; 2] {
        let n = x.len() as f64;
        let f1 = x[0];
        let g = 1.0 + 9.0 * x[1..].iter().sum::<f64>() / (n - 1.0);
        let h = 1.0 - (f1 / g).sqrt() - (f1 / g) * (10.0 * PI * f1).sin();
        let f2 = g * h;
        [f1, f2]
    }

    /// Bounds for each variable [0, 1]
    pub fn bounds(&self) -> (f64, f64) {
        (0.0, 1.0)
    }

    /// Get the dimension
    pub fn dimension(&self) -> usize {
        self.dimension
    }
}

/// Schaffer N.1 multi-objective problem
///
/// Simple bi-objective problem with a single variable.
#[derive(Clone, Debug)]
pub struct SchafferN1;

impl SchafferN1 {
    /// Create a new Schaffer N.1 function
    pub fn new() -> Self {
        Self
    }

    /// Evaluate the function (returns [f1, f2])
    pub fn evaluate(&self, x: f64) -> [f64; 2] {
        let f1 = x * x;
        let f2 = (x - 2.0) * (x - 2.0);
        [f1, f2]
    }

    /// Bounds for the variable
    pub fn bounds(&self) -> (f64, f64) {
        (-10.0, 10.0)
    }
}

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

// =============================================================================
// Additional Single-Objective Functions
// =============================================================================

/// Levy function
///
/// Multimodal with many local minima. Optimum at (1, 1, ..., 1).
#[derive(Clone, Debug)]
pub struct Levy {
    dimension: usize,
}

impl Levy {
    /// Create a new Levy function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for Levy {
    fn name(&self) -> &'static str {
        "Levy"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-10.0, 10.0)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![1.0; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let w: Vec<f64> = x.iter().map(|xi| 1.0 + (xi - 1.0) / 4.0).collect();
        let n = w.len();

        let term1 = (PI * w[0]).sin().powi(2);

        let sum: f64 = w[..n - 1]
            .iter()
            .map(|wi| (wi - 1.0).powi(2) * (1.0 + 10.0 * (PI * wi + 1.0).sin().powi(2)))
            .sum();

        let term3 = (w[n - 1] - 1.0).powi(2) * (1.0 + (2.0 * PI * w[n - 1]).sin().powi(2));

        term1 + sum + term3
    }
}

impl Fitness for Levy {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Dixon-Price function
///
/// Valley structure. Optimum depends on dimension.
#[derive(Clone, Debug)]
pub struct DixonPrice {
    dimension: usize,
}

impl DixonPrice {
    /// Create a new Dixon-Price function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for DixonPrice {
    fn name(&self) -> &'static str {
        "Dixon-Price"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-10.0, 10.0)
    }

    fn optimal_fitness(&self) -> f64 {
        0.0
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        // Canonical Dixon-Price global minimizer (1-based index j = 1..d):
        //     x_j = 2^{ -(2^j - 2) / 2^j }
        // Here `i` is 0-based, so the 1-based index is j = i + 1 and both the
        // numerator and denominator exponents must use `i + 1` consistently.
        let optimal: Vec<f64> = (0..self.dimension)
            .map(|i| {
                let two_pow_j = (1u64 << (i + 1)) as f64; // 2^{i+1} = 2^j
                let exp_num = two_pow_j - 2.0; // 2^j - 2
                let exp_den = two_pow_j; // 2^j
                2.0_f64.powf(-exp_num / exp_den)
            })
            .collect();
        Some(optimal)
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        let term1 = (x[0] - 1.0).powi(2);

        let sum: f64 = x
            .windows(2)
            .enumerate()
            .map(|(i, w)| (i + 2) as f64 * (2.0 * w[1] * w[1] - w[0]).powi(2))
            .sum();

        term1 + sum
    }
}

impl Fitness for DixonPrice {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

/// Styblinski-Tang function
///
/// Multimodal. Optimum at (-2.903534, ..., -2.903534).
#[derive(Clone, Debug)]
pub struct StyblinskiTang {
    dimension: usize,
}

impl StyblinskiTang {
    /// Create a new Styblinski-Tang function
    pub fn new(dimension: usize) -> Self {
        Self { dimension }
    }
}

impl BenchmarkFunction for StyblinskiTang {
    fn name(&self) -> &'static str {
        "Styblinski-Tang"
    }

    fn dimension(&self) -> usize {
        self.dimension
    }

    fn bounds(&self) -> (f64, f64) {
        (-5.0, 5.0)
    }

    fn optimal_fitness(&self) -> f64 {
        // f(optimal) = -39.16617 * dimension
        -39.16617 * self.dimension as f64
    }

    fn optimal_solution(&self) -> Option<Vec<f64>> {
        Some(vec![-2.903534; self.dimension])
    }

    fn evaluate_raw(&self, x: &[f64]) -> f64 {
        x.iter()
            .map(|xi| xi.powi(4) - 16.0 * xi.powi(2) + 5.0 * xi)
            .sum::<f64>()
            / 2.0
    }
}

impl Fitness for StyblinskiTang {
    type Genome = RealVector;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        -self.evaluate_raw(genome.genes())
    }
}

// ============================================================================
// Combinatorial Benchmarks
// ============================================================================

/// Royal Road function
///
/// Tests the "building block hypothesis" - fitness is the count of complete
/// schemas (contiguous blocks of 1s). Rewards completing full blocks rather
/// than partial solutions.
///
/// For example, with schema_size=8 and num_schemas=4 (32-bit string):
/// - 11111111 00000000 11111111 00000000 has fitness 2 (two complete blocks)
/// - 11111110 11111111 11111111 11111111 has fitness 3 (one incomplete)
#[derive(Clone, Debug)]
pub struct RoyalRoad {
    /// Size of each schema (block of consecutive 1s)
    pub schema_size: usize,
    /// Number of schemas in the genome
    pub num_schemas: usize,
}

impl RoyalRoad {
    /// Create a new Royal Road function
    ///
    /// # Arguments
    /// * `schema_size` - Number of bits in each schema (typically 8)
    /// * `num_schemas` - Number of schemas (typically 8)
    pub fn new(schema_size: usize, num_schemas: usize) -> Self {
        Self {
            schema_size,
            num_schemas,
        }
    }

    /// Standard Royal Road configuration (8x8 = 64 bits)
    pub fn standard() -> Self {
        Self::new(8, 8)
    }

    /// Total genome length required
    pub fn genome_length(&self) -> usize {
        self.schema_size * self.num_schemas
    }

    /// Check if a schema (block) is complete (all 1s)
    fn is_complete_schema(&self, bits: &[bool], schema_index: usize) -> bool {
        let start = schema_index * self.schema_size;
        let end = start + self.schema_size;

        if end > bits.len() {
            return false;
        }

        bits[start..end].iter().all(|&b| b)
    }

    /// Count the number of complete schemas
    pub fn count_complete_schemas(&self, bits: &[bool]) -> usize {
        (0..self.num_schemas)
            .filter(|&i| self.is_complete_schema(bits, i))
            .count()
    }
}

impl Fitness for RoyalRoad {
    type Genome = BitString;
    type Value = usize;

    fn evaluate(&self, genome: &Self::Genome) -> usize {
        self.count_complete_schemas(genome.bits())
    }
}

/// NK Landscape
///
/// A tunable fitness landscape with controllable epistasis (gene interactions).
/// - N is the genome length
/// - K is the number of other genes that affect each gene's fitness contribution
///
/// Higher K = more rugged landscape with more local optima.
/// K=0: smooth landscape (separable)
/// K=N-1: maximally rugged (all genes interact)
///
/// The fitness is the average of local fitness contributions.
#[derive(Clone, Debug)]
pub struct NkLandscape {
    /// Genome length (N)
    n: usize,
    /// Epistasis degree (K)
    k: usize,
    /// Neighbor indices for each gene position
    neighbors: Vec<Vec<usize>>,
    /// Fitness contribution lookup tables
    /// For each gene i, maps (gene i value, neighbor values) -> contribution
    contributions: Vec<std::collections::HashMap<Vec<bool>, f64>>,
}

impl NkLandscape {
    /// Create a new NK Landscape with random fitness contributions
    ///
    /// # Arguments
    /// * `n` - Genome length
    /// * `k` - Epistasis degree (must be < n)
    /// * `seed` - Random seed for reproducibility
    pub fn new(n: usize, k: usize, seed: u64) -> Self {
        assert!(k < n, "K must be less than N");

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

        // Generate random neighbors for each position
        let mut neighbors = Vec::with_capacity(n);
        for i in 0..n {
            let mut gene_neighbors: Vec<usize> = (0..n).filter(|&j| j != i).collect();
            // Shuffle and take first k neighbors
            use rand::seq::SliceRandom;
            gene_neighbors.shuffle(&mut rng);
            gene_neighbors.truncate(k);
            gene_neighbors.sort();
            neighbors.push(gene_neighbors);
        }

        // Generate random fitness contributions for each configuration
        let mut contributions = Vec::with_capacity(n);
        for _i in 0..n {
            let num_configs = 1 << (k + 1); // 2^(k+1) configurations
            let mut table = std::collections::HashMap::with_capacity(num_configs);

            // Generate all possible configurations
            for config_bits in 0..num_configs {
                let config: Vec<bool> = (0..=k).map(|j| (config_bits >> j) & 1 == 1).collect();
                use rand::Rng;
                table.insert(config, rng.gen::<f64>());
            }

            contributions.push(table);
        }

        Self {
            n,
            k,
            neighbors,
            contributions,
        }
    }

    /// Create an NK Landscape with adjacent neighbors
    /// (each gene interacts with its k nearest neighbors)
    pub fn with_adjacent_neighbors(n: usize, k: usize, seed: u64) -> Self {
        assert!(k < n, "K must be less than N");

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

        // Adjacent neighbors
        let mut neighbors = Vec::with_capacity(n);
        for i in 0..n {
            let gene_neighbors: Vec<usize> = (1..=k).map(|offset| (i + offset) % n).collect();
            neighbors.push(gene_neighbors);
        }

        // Generate random fitness contributions
        let mut contributions = Vec::with_capacity(n);
        for _i in 0..n {
            let num_configs = 1 << (k + 1);
            let mut table = std::collections::HashMap::with_capacity(num_configs);

            for config_bits in 0..num_configs {
                let config: Vec<bool> = (0..=k).map(|j| (config_bits >> j) & 1 == 1).collect();
                use rand::Rng;
                table.insert(config, rng.gen::<f64>());
            }

            contributions.push(table);
        }

        Self {
            n,
            k,
            neighbors,
            contributions,
        }
    }

    /// Get genome length (N)
    pub fn genome_length(&self) -> usize {
        self.n
    }

    /// Get epistasis degree (K)
    pub fn epistasis(&self) -> usize {
        self.k
    }

    /// Evaluate fitness for a bit string
    pub fn evaluate_bits(&self, bits: &[bool]) -> f64 {
        assert!(bits.len() >= self.n);

        let mut total = 0.0;

        for i in 0..self.n {
            // Build configuration: [gene_i, neighbor_1, neighbor_2, ...]
            let mut config = Vec::with_capacity(self.k + 1);
            config.push(bits[i]);
            for &j in &self.neighbors[i] {
                config.push(bits[j]);
            }

            // Look up contribution
            if let Some(&contribution) = self.contributions[i].get(&config) {
                total += contribution;
            }
        }

        // Return average fitness
        total / self.n as f64
    }
}

impl Fitness for NkLandscape {
    type Genome = BitString;
    type Value = f64;

    fn evaluate(&self, genome: &Self::Genome) -> f64 {
        self.evaluate_bits(genome.bits())
    }
}

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

    // Sphere function tests
    #[test]
    fn test_sphere_at_optimum() {
        let sphere = Sphere::new(3);
        let optimum = RealVector::new(vec![0.0, 0.0, 0.0]);
        assert_relative_eq!(sphere.evaluate(&optimum), 0.0);
    }

    #[test]
    fn test_sphere_non_optimum() {
        let sphere = Sphere::new(3);
        let point = RealVector::new(vec![1.0, 2.0, 3.0]);
        // 1 + 4 + 9 = 14, negated = -14
        assert_relative_eq!(sphere.evaluate(&point), -14.0);
    }

    #[test]
    fn test_sphere_metadata() {
        let sphere = Sphere::new(5);
        assert_eq!(sphere.name(), "Sphere");
        assert_eq!(sphere.dimension(), 5);
        assert_eq!(sphere.bounds(), (-5.12, 5.12));
        assert_relative_eq!(sphere.optimal_fitness(), 0.0);
        assert_eq!(sphere.optimal_solution(), Some(vec![0.0; 5]));
    }

    // Rastrigin function tests
    #[test]
    fn test_rastrigin_at_optimum() {
        let rastrigin = Rastrigin::new(3);
        let optimum = RealVector::new(vec![0.0, 0.0, 0.0]);
        assert_relative_eq!(rastrigin.evaluate(&optimum), 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_rastrigin_non_optimum() {
        let rastrigin = Rastrigin::new(2);
        let point = RealVector::new(vec![1.0, 1.0]);
        // At x=1, cos(2π*1) = 1, so each term is 1 - 10*1 = -9
        // Total = 10*2 + 2*(-9) = 20 - 18 = 2, but we need to calculate more precisely
        let expected = 10.0 * 2.0
            + (1.0 * 1.0 - 10.0 * (2.0 * PI * 1.0).cos())
            + (1.0 * 1.0 - 10.0 * (2.0 * PI * 1.0).cos());
        assert_relative_eq!(rastrigin.evaluate(&point), -expected, epsilon = 1e-10);
    }

    #[test]
    fn test_rastrigin_metadata() {
        let rastrigin = Rastrigin::new(10);
        assert_eq!(rastrigin.name(), "Rastrigin");
        assert_eq!(rastrigin.dimension(), 10);
        assert_eq!(rastrigin.bounds(), (-5.12, 5.12));
    }

    // Rosenbrock function tests
    #[test]
    fn test_rosenbrock_at_optimum() {
        let rosenbrock = Rosenbrock::new(3);
        let optimum = RealVector::new(vec![1.0, 1.0, 1.0]);
        assert_relative_eq!(rosenbrock.evaluate(&optimum), 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_rosenbrock_non_optimum() {
        let rosenbrock = Rosenbrock::new(2);
        let point = RealVector::new(vec![0.0, 0.0]);
        // 100*(0 - 0)^2 + (1 - 0)^2 = 1
        assert_relative_eq!(rosenbrock.evaluate(&point), -1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_rosenbrock_metadata() {
        let rosenbrock = Rosenbrock::new(5);
        assert_eq!(rosenbrock.name(), "Rosenbrock");
        assert_eq!(rosenbrock.dimension(), 5);
        assert_eq!(rosenbrock.bounds(), (-5.0, 10.0));
        assert_eq!(rosenbrock.optimal_solution(), Some(vec![1.0; 5]));
    }

    // Ackley function tests
    #[test]
    fn test_ackley_at_optimum() {
        let ackley = Ackley::new(3);
        let optimum = RealVector::new(vec![0.0, 0.0, 0.0]);
        assert_relative_eq!(ackley.evaluate(&optimum), 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_ackley_metadata() {
        let ackley = Ackley::new(10);
        assert_eq!(ackley.name(), "Ackley");
        assert_eq!(ackley.dimension(), 10);
        assert_eq!(ackley.bounds(), (-32.768, 32.768));
    }

    // Griewank function tests
    #[test]
    fn test_griewank_at_optimum() {
        let griewank = Griewank::new(3);
        let optimum = RealVector::new(vec![0.0, 0.0, 0.0]);
        assert_relative_eq!(griewank.evaluate(&optimum), 0.0, epsilon = 1e-10);
    }

    #[test]
    fn test_griewank_metadata() {
        let griewank = Griewank::new(10);
        assert_eq!(griewank.name(), "Griewank");
        assert_eq!(griewank.dimension(), 10);
        assert_eq!(griewank.bounds(), (-600.0, 600.0));
    }

    // Schwefel function tests
    #[test]
    fn test_schwefel_metadata() {
        let schwefel = Schwefel::new(10);
        assert_eq!(schwefel.name(), "Schwefel");
        assert_eq!(schwefel.dimension(), 10);
        assert_eq!(schwefel.bounds(), (-500.0, 500.0));
    }

    // OneMax function tests
    #[test]
    fn test_onemax_all_ones() {
        let onemax = OneMax::new(10);
        let genome = BitString::ones(10);
        assert_eq!(onemax.evaluate(&genome), 10);
    }

    #[test]
    fn test_onemax_all_zeros() {
        let onemax = OneMax::new(10);
        let genome = BitString::zeros(10);
        assert_eq!(onemax.evaluate(&genome), 0);
    }

    #[test]
    fn test_onemax_mixed() {
        let onemax = OneMax::new(5);
        let genome = BitString::new(vec![true, false, true, false, true]);
        assert_eq!(onemax.evaluate(&genome), 3);
    }

    // LeadingOnes function tests
    #[test]
    fn test_leadingones_all_ones() {
        let lo = LeadingOnes::new(10);
        let genome = BitString::ones(10);
        assert_eq!(lo.evaluate(&genome), 10);
    }

    #[test]
    fn test_leadingones_all_zeros() {
        let lo = LeadingOnes::new(10);
        let genome = BitString::zeros(10);
        assert_eq!(lo.evaluate(&genome), 0);
    }

    #[test]
    fn test_leadingones_mixed() {
        let lo = LeadingOnes::new(5);
        let genome = BitString::new(vec![true, true, false, true, true]);
        assert_eq!(lo.evaluate(&genome), 2); // First 2 are 1s, then a 0
    }

    #[test]
    fn test_leadingones_starts_with_zero() {
        let lo = LeadingOnes::new(5);
        let genome = BitString::new(vec![false, true, true, true, true]);
        assert_eq!(lo.evaluate(&genome), 0);
    }

    // ZDT1 tests
    #[test]
    fn test_zdt1_pareto_front() {
        let zdt1 = Zdt1::new(10);
        // On the Pareto front, all x_i = 0 for i > 0, and x_0 varies from 0 to 1
        let x = vec![0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        let [f1, f2] = zdt1.evaluate(&x);

        // f1 should equal x_0
        assert_relative_eq!(f1, 0.5, epsilon = 1e-10);

        // On Pareto front with g=1: f2 = 1 - sqrt(f1)
        assert_relative_eq!(f2, 1.0 - f1.sqrt(), epsilon = 1e-10);
    }

    // ZDT2 tests
    #[test]
    fn test_zdt2_pareto_front() {
        let zdt2 = Zdt2::new(10);
        let x = vec![0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];
        let [f1, f2] = zdt2.evaluate(&x);

        assert_relative_eq!(f1, 0.5, epsilon = 1e-10);
        // On Pareto front with g=1: f2 = 1 - f1^2
        assert_relative_eq!(f2, 1.0 - f1 * f1, epsilon = 1e-10);
    }

    // Schaffer N.1 tests
    #[test]
    fn test_schaffer_n1() {
        let schaffer = SchafferN1::new();
        let [f1, f2] = schaffer.evaluate(0.0);
        assert_relative_eq!(f1, 0.0, epsilon = 1e-10);
        assert_relative_eq!(f2, 4.0, epsilon = 1e-10);
    }

    // Levy function tests
    #[test]
    fn test_levy_at_optimum() {
        let levy = Levy::new(3);
        let optimum = RealVector::new(vec![1.0, 1.0, 1.0]);
        assert_relative_eq!(levy.evaluate(&optimum), 0.0, epsilon = 1e-10);
    }

    // Dixon-Price tests
    #[test]
    fn test_dixonprice_metadata() {
        let dp = DixonPrice::new(5);
        assert_eq!(dp.name(), "Dixon-Price");
        assert_eq!(dp.dimension(), 5);
    }

    // regression: EV-15 — optimal_solution() must actually be the global minimizer,
    // i.e. evaluate_raw() at the declared optimum must be (numerically) zero.
    // The pre-fix exponent used 2^i-2 over 2^{i+1}, yielding f > 0.85 at every
    // dimension, so this test fails on the old code.
    #[test]
    fn test_dixonprice_optimal_solution_is_optimum() {
        for dim in 2..=6 {
            let dp = DixonPrice::new(dim);
            let opt = dp
                .optimal_solution()
                .expect("Dixon-Price exposes an optimal solution");
            let value = dp.evaluate_raw(&opt);
            assert!(
                value < 1e-12,
                "f(optimal_solution()) for dim={dim} was {value}, expected < 1e-12"
            );
        }
    }

    // Styblinski-Tang tests
    #[test]
    fn test_styblinskitang_near_optimum() {
        let st = StyblinskiTang::new(2);
        let near_opt = RealVector::new(vec![-2.9, -2.9]);
        // Should be close to optimal fitness
        let fitness = st.evaluate(&near_opt);
        let optimal = st.optimal_fitness();
        // The returned fitness is negated, so compare negatives
        assert!(
            fitness > optimal - 1.0,
            "Fitness {} should be close to optimal {}",
            fitness,
            optimal
        );
    }

    // Royal Road tests
    #[test]
    fn test_royal_road_all_ones() {
        let rr = RoyalRoad::new(4, 4); // 16-bit genome
        let genome = BitString::ones(16);
        let fitness: usize = rr.evaluate(&genome);
        assert_eq!(fitness, 4); // All 4 schemas complete
    }

    #[test]
    fn test_royal_road_all_zeros() {
        let rr = RoyalRoad::new(4, 4);
        let genome = BitString::zeros(16);
        let fitness: usize = rr.evaluate(&genome);
        assert_eq!(fitness, 0); // No schemas complete
    }

    #[test]
    fn test_royal_road_partial() {
        let rr = RoyalRoad::new(4, 4);
        // First and third schemas complete
        let bits = vec![
            true, true, true, true, // Schema 0: complete
            false, false, false, false, // Schema 1: empty
            true, true, true, true, // Schema 2: complete
            true, true, true, false, // Schema 3: incomplete
        ];
        let genome = BitString::new(bits);
        let fitness: usize = rr.evaluate(&genome);
        assert_eq!(fitness, 2);
    }

    #[test]
    fn test_royal_road_standard() {
        let rr = RoyalRoad::standard();
        assert_eq!(rr.genome_length(), 64);
        assert_eq!(rr.schema_size, 8);
        assert_eq!(rr.num_schemas, 8);
    }

    // NK Landscape tests
    #[test]
    fn test_nk_landscape_creation() {
        let nk = NkLandscape::new(10, 2, 42);
        assert_eq!(nk.genome_length(), 10);
        assert_eq!(nk.epistasis(), 2);
    }

    #[test]
    fn test_nk_landscape_deterministic() {
        // Same seed should give same landscape
        let nk1 = NkLandscape::new(8, 2, 123);
        let nk2 = NkLandscape::new(8, 2, 123);

        let genome = BitString::new(vec![true, false, true, false, true, false, true, false]);
        let f1: f64 = nk1.evaluate(&genome);
        let f2: f64 = nk2.evaluate(&genome);

        assert_relative_eq!(f1, f2);
    }

    #[test]
    fn test_nk_landscape_fitness_range() {
        let nk = NkLandscape::new(10, 3, 42);
        let genome = BitString::new(vec![true; 10]);
        let fitness: f64 = nk.evaluate(&genome);

        // Fitness should be average of contributions, so in [0, 1]
        assert!((0.0..=1.0).contains(&fitness));
    }

    #[test]
    fn test_nk_landscape_adjacent() {
        let nk = NkLandscape::with_adjacent_neighbors(10, 2, 42);
        let genome = BitString::ones(10);
        let fitness: f64 = nk.evaluate(&genome);

        assert!((0.0..=1.0).contains(&fitness));
    }

    #[test]
    #[should_panic(expected = "K must be less than N")]
    fn test_nk_landscape_invalid_k() {
        let _nk = NkLandscape::new(5, 5, 42); // K = N is invalid
    }
}