Skip to main content

evolutionary_planning/problems/
multi.rs

1//! Multi-objective benchmark problems: Schaffer, ZDT1–3, DTLZ1–2 and a bi-objective 0/1
2//! knapsack with a capacity constraint. All objectives are minimised.
3
4use alloc::vec::Vec;
5
6use crate::MultiObjective;
7
8/// Schaffer's problem N.1 on one real `x`: `(x², (x - 2)²)`; the Pareto set is `[0, 2]`.
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub struct Schaffer;
11
12impl MultiObjective<Vec<f64>> for Schaffer {
13    fn objectives(&self) -> usize {
14        2
15    }
16
17    fn evaluate(&mut self, genome: &Vec<f64>, out: &mut [f64]) -> f64 {
18        let x = genome[0];
19        out[0] = x * x;
20        out[1] = (x - 2.0) * (x - 2.0);
21
22        0.0
23    }
24}
25
26/// The ZDT problems of Zitzler, Deb and Thiele (2000) on `[0, 1]^n`, two objectives.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Zdt {
29    /// Convex front `f2 = 1 - sqrt(f1)`.
30    Zdt1,
31    /// Concave front `f2 = 1 - f1²`.
32    Zdt2,
33    /// Disconnected front `f2 = 1 - sqrt(f1) - f1 sin(10π f1)`.
34    Zdt3,
35}
36
37impl Zdt {
38    /// The optimal `f2` for `f1` on the front (where it is Pareto-optimal: everywhere for
39    /// ZDT1 and ZDT2, on five disjoint pieces for ZDT3).
40    #[must_use]
41    pub fn front(self, f1: f64) -> f64 {
42        self.shape(f1, 1.0)
43    }
44
45    /// `f2 / g` as a function of `f1 / g`, times `g`.
46    fn shape(self, f1: f64, g: f64) -> f64 {
47        let ratio = f1 / g;
48        let h = match self {
49            Self::Zdt1 => 1.0 - libm::sqrt(ratio),
50            Self::Zdt2 => 1.0 - ratio * ratio,
51            Self::Zdt3 => {
52                1.0 - libm::sqrt(ratio) - ratio * libm::sin(10.0 * core::f64::consts::PI * f1)
53            }
54        };
55
56        g * h
57    }
58}
59
60impl MultiObjective<Vec<f64>> for Zdt {
61    fn objectives(&self) -> usize {
62        2
63    }
64
65    fn evaluate(&mut self, genome: &Vec<f64>, out: &mut [f64]) -> f64 {
66        let n = genome.len();
67        #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
68        let g = if n > 1 {
69            1.0 + 9.0 * genome[1..].iter().sum::<f64>() / (n - 1) as f64
70        } else {
71            1.0
72        };
73        out[0] = genome[0];
74        out[1] = self.shape(genome[0], g);
75
76        0.0
77    }
78}
79
80/// The DTLZ problems of Deb, Thiele, Laumanns and Zitzler (2002) with `objectives` objectives
81/// on `[0, 1]^n`, `n >= objectives`.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub struct Dtlz {
84    /// Which problem.
85    pub kind: DtlzKind,
86    /// The number of objectives `m >= 2`.
87    pub objectives: usize,
88}
89
90/// The DTLZ variants implemented.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum DtlzKind {
93    /// Linear front `Σ f_i = 0.5`, with a multimodal distance function.
94    Dtlz1,
95    /// Spherical front `Σ f_i² = 1`.
96    Dtlz2,
97}
98
99impl MultiObjective<Vec<f64>> for Dtlz {
100    fn objectives(&self) -> usize {
101        self.objectives
102    }
103
104    fn evaluate(&mut self, x: &Vec<f64>, out: &mut [f64]) -> f64 {
105        let m = self.objectives;
106        let tail = &x[m - 1..];
107        let half_pi = core::f64::consts::FRAC_PI_2;
108        match self.kind {
109            DtlzKind::Dtlz1 => {
110                #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
111                let k = tail.len() as f64;
112                let g = 100.0
113                    * (k + tail
114                        .iter()
115                        .map(|v| {
116                            (v - 0.5) * (v - 0.5)
117                                - libm::cos(20.0 * core::f64::consts::PI * (v - 0.5))
118                        })
119                        .sum::<f64>());
120                for (i, f) in out.iter_mut().enumerate().take(m) {
121                    let mut value = f64::midpoint(1.0, g);
122                    value *= x[..m - 1 - i].iter().product::<f64>();
123                    if i > 0 {
124                        value *= 1.0 - x[m - 1 - i];
125                    }
126                    *f = value;
127                }
128            }
129            DtlzKind::Dtlz2 => {
130                let g: f64 = tail.iter().map(|v| (v - 0.5) * (v - 0.5)).sum();
131                for (i, f) in out.iter_mut().enumerate().take(m) {
132                    let mut value = 1.0 + g;
133                    value *= x[..m - 1 - i]
134                        .iter()
135                        .map(|v| libm::cos(v * half_pi))
136                        .product::<f64>();
137                    if i > 0 {
138                        value *= libm::sin(x[m - 1 - i] * half_pi);
139                    }
140                    *f = value;
141                }
142            }
143        }
144
145        0.0
146    }
147}
148
149/// A bi-objective 0/1 knapsack: maximise two values (returned negated as costs) under a weight
150/// capacity; the violation is the excess weight.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct Knapsack {
153    /// Per item: `(weight, value_1, value_2)`.
154    pub items: Vec<(u32, u32, u32)>,
155    /// The weight capacity.
156    pub capacity: u32,
157}
158
159impl Knapsack {
160    /// A deterministic pseudo-random instance with `n` items and capacity half the total
161    /// weight; weights and values are in `1..=30`.
162    ///
163    /// # Panics
164    ///
165    /// Panics if the total weight overflows `u32` (more than about `10^8` items).
166    #[must_use]
167    pub fn generate(n: usize, seed: u64) -> Self {
168        let mut rng = crate::SplitMix64::new(seed);
169        let mut draw = || 1 + u32::try_from(crate::below(&mut rng, 30)).expect("below 30");
170        let items: Vec<(u32, u32, u32)> = (0..n).map(|_| (draw(), draw(), draw())).collect();
171        let capacity = items.iter().map(|i| i.0).sum::<u32>() / 2;
172
173        Self { items, capacity }
174    }
175
176    /// The costs `(-value_1, -value_2)` and the excess weight of a selection.
177    #[must_use]
178    pub fn assess(&self, take: &[bool]) -> ([f64; 2], f64) {
179        let (mut weight, mut v1, mut v2) = (0, 0, 0);
180        for (&(w, a, b), _) in self.items.iter().zip(take).filter(|(_, t)| **t) {
181            weight += w;
182            v1 += a;
183            v2 += b;
184        }
185
186        (
187            [-f64::from(v1), -f64::from(v2)],
188            f64::from(weight.saturating_sub(self.capacity)),
189        )
190    }
191}
192
193impl MultiObjective<Vec<bool>> for Knapsack {
194    fn objectives(&self) -> usize {
195        2
196    }
197
198    fn evaluate(&mut self, genome: &Vec<bool>, out: &mut [f64]) -> f64 {
199        let (costs, violation) = self.assess(genome);
200        out.copy_from_slice(&costs);
201
202        violation
203    }
204}
205
206/// LOTZ, LeadingOnes-TrailingZeros (Laumanns, Thiele and Zitzler 2004), as costs: minimise
207/// `-(leading ones)` and `-(trailing zeros)` of a bit string of length `n`. The Pareto front
208/// is the `n + 1` points `(-k, -(n - k))`, each reached by `1^k 0^(n-k)` only.
209#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
210pub struct Lotz;
211
212impl MultiObjective<Vec<bool>> for Lotz {
213    fn objectives(&self) -> usize {
214        2
215    }
216
217    fn evaluate(&mut self, genome: &Vec<bool>, out: &mut [f64]) -> f64 {
218        let leading = genome.iter().take_while(|&&b| b).count();
219        let trailing = genome.iter().rev().take_while(|&&b| !b).count();
220        #[expect(clippy::cast_precision_loss, reason = "lengths are far below 2^52")]
221        {
222            out[0] = -(leading as f64);
223            out[1] = -(trailing as f64);
224        }
225
226        0.0
227    }
228}
229
230/// Every objective vector (and violation) of the `2^n` bit strings of length `n`, for
231/// brute-force reference fronts.
232///
233/// # Panics
234///
235/// Panics if `n > 20` (a million genomes).
236#[must_use]
237pub fn enumerate_bits<M: MultiObjective<Vec<bool>>>(
238    problem: &mut M,
239    n: usize,
240) -> Vec<(Vec<bool>, Vec<f64>, f64)> {
241    assert!(n <= 20, "too many genomes to enumerate");
242
243    let m = problem.objectives();
244    (0..1u32 << n)
245        .map(|mask| {
246            let genome: Vec<bool> = (0..n).map(|i| mask >> i & 1 == 1).collect();
247            let mut out = alloc::vec![0.0; m];
248            let violation = problem.evaluate(&genome, &mut out);
249            (genome, out, violation)
250        })
251        .collect()
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    /// Points of the Pareto set lie on the documented fronts.
259    #[test]
260    fn fronts() {
261        let mut out = [0.0; 3];
262        let mut zdt = Zdt::Zdt1;
263        zdt.evaluate(&alloc::vec![0.25, 0.0, 0.0], &mut out[..2]);
264        assert!((out[1] - 0.5).abs() < 1e-12);
265
266        let mut dtlz2 = Dtlz {
267            kind: DtlzKind::Dtlz2,
268            objectives: 3,
269        };
270        dtlz2.evaluate(&alloc::vec![0.3, 0.7, 0.5, 0.5], &mut out);
271        assert!((out.iter().map(|f| f * f).sum::<f64>() - 1.0).abs() < 1e-12);
272
273        let mut dtlz1 = Dtlz {
274            kind: DtlzKind::Dtlz1,
275            objectives: 3,
276        };
277        dtlz1.evaluate(&alloc::vec![0.3, 0.7, 0.5, 0.5], &mut out);
278        assert!((out.iter().sum::<f64>() - 0.5).abs() < 1e-12);
279    }
280}