Skip to main content

evolutionary_planning/problems/
single.rs

1//! Single-objective benchmark functions, all minimised with optimum `0` unless noted.
2
3use alloc::vec::Vec;
4
5/// The sphere `Σ x_i²`; optimum `0` at the origin.
6#[must_use]
7pub fn sphere(x: &[f64]) -> f64 {
8    x.iter().map(|v| v * v).sum()
9}
10
11/// The axis-parallel ellipsoid `Σ 10^(6 (i-1)/(n-1)) x_i²` with condition number `10^6`, as
12/// in Hansen's tutorial; optimum `0` at the origin. For `n = 1` it is the sphere.
13#[must_use]
14pub fn ellipsoid(x: &[f64]) -> f64 {
15    let n = x.len();
16    if n <= 1 {
17        return sphere(x);
18    }
19
20    #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
21    let denominator = (n - 1) as f64;
22    x.iter()
23        .enumerate()
24        .map(|(i, v)| {
25            #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
26            let exponent = 6.0 * i as f64 / denominator;
27            libm::pow(10.0, exponent) * v * v
28        })
29        .sum()
30}
31
32/// Rosenbrock's function `Σ 100 (x_{i+1} - x_i²)² + (1 - x_i)²`; optimum `0` at
33/// `(1, …, 1)`. For `n >= 4` it has a second local minimum near `(-1, 1, …, 1)`.
34#[must_use]
35pub fn rosenbrock(x: &[f64]) -> f64 {
36    x.windows(2)
37        .map(|w| {
38            let (a, b) = (w[1] - w[0] * w[0], 1.0 - w[0]);
39            100.0 * a * a + b * b
40        })
41        .sum()
42}
43
44/// Rastrigin's function `10 n + Σ (x_i² - 10 cos(2π x_i))`; optimum `0` at the origin,
45/// highly multimodal.
46#[must_use]
47pub fn rastrigin(x: &[f64]) -> f64 {
48    #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
49    let base = 10.0 * x.len() as f64;
50
51    base + x
52        .iter()
53        .map(|v| v * v - 10.0 * libm::cos(2.0 * core::f64::consts::PI * v))
54        .sum::<f64>()
55}
56
57/// OneMax as a cost: the number of zero bits; optimum `0` (all ones).
58#[must_use]
59pub fn one_max(bits: &[bool]) -> f64 {
60    #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
61    let zeros = bits.iter().filter(|&&b| !b).count() as f64;
62
63    zeros
64}
65
66/// LeadingOnes as a cost: `n` minus the length of the leading run of ones; optimum `0`.
67#[must_use]
68pub fn leading_ones(bits: &[bool]) -> f64 {
69    let ones = bits.iter().take_while(|&&b| b).count();
70
71    #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
72    let cost = (bits.len() - ones) as f64;
73
74    cost
75}
76
77/// A symmetric travelling-salesperson instance over points in the plane.
78#[derive(Debug, Clone, PartialEq)]
79pub struct Tour {
80    /// The city coordinates.
81    pub cities: Vec<(f64, f64)>,
82}
83
84impl Tour {
85    /// The length of the closed tour visiting the cities in `order`.
86    #[must_use]
87    pub fn length(&self, order: &[usize]) -> f64 {
88        let n = order.len();
89        (0..n)
90            .map(|k| {
91                let (a, b) = (self.cities[order[k]], self.cities[order[(k + 1) % n]]);
92                libm::hypot(a.0 - b.0, a.1 - b.1)
93            })
94            .sum()
95    }
96
97    /// The `n` cities on a circle of radius 1, numbered in a scrambled order; the optimal tour
98    /// is the circle, of length `2 n sin(π / n)`.
99    #[must_use]
100    pub fn circle(n: usize) -> Self {
101        let cities = (0..n)
102            .map(|k| {
103                // A fixed scramble (7k mod n with n coprime to 7 would also do); any order works.
104                #[expect(clippy::cast_precision_loss, reason = "city counts are tiny")]
105                let angle = 2.0 * core::f64::consts::PI * ((k * 7) % n) as f64 / n as f64;
106                (libm::cos(angle), libm::sin(angle))
107            })
108            .collect();
109
110        Self { cities }
111    }
112
113    /// The optimal length of [`Tour::circle`]`(n)`.
114    #[must_use]
115    pub fn circle_optimum(n: usize) -> f64 {
116        #[expect(clippy::cast_precision_loss, reason = "city counts are tiny")]
117        let n = n as f64;
118
119        2.0 * n * libm::sin(core::f64::consts::PI / n)
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    /// The optima are where they are documented.
128    #[test]
129    fn optima() {
130        assert_eq!(sphere(&[0.0; 5]), 0.0);
131        assert_eq!(ellipsoid(&[0.0; 5]), 0.0);
132        assert_eq!(rosenbrock(&[1.0; 5]), 0.0);
133        assert!(rastrigin(&[0.0; 5]).abs() < 1e-12);
134        assert_eq!(one_max(&[true; 4]), 0.0);
135        assert_eq!(leading_ones(&[true, false, true]), 2.0);
136        assert!((ellipsoid(&[0.0, 1.0]) - 1e6).abs() < 1e-6);
137    }
138
139    /// The circle tour in angular order has the documented length.
140    #[test]
141    fn circle_tour_optimum() {
142        let tour = Tour::circle(11);
143        let mut order: alloc::vec::Vec<usize> = (0..11).collect();
144        order.sort_by(|&a, &b| {
145            let angle = |k: usize| libm::atan2(tour.cities[k].1, tour.cities[k].0);
146            angle(a).total_cmp(&angle(b))
147        });
148
149        assert!((tour.length(&order) - Tour::circle_optimum(11)).abs() < 1e-9);
150    }
151}