Skip to main content

evolutionary_planning/
moead.rs

1//! MOEA/D (Zhang and Li 2007): multi-objective search by decomposition into `N` scalar
2//! subproblems, one per weight vector, each improved by mating within its neighbourhood of
3//! the `T` closest weight vectors; with the neighbourhood mating probability `δ` and the
4//! replacement limit `n_r` of Li and Zhang (2009).
5//!
6//! Constraints are handled by comparing violation first, then the scalarised cost.
7//!
8//! ```
9//! use evolutionary_planning::moead::{Config, Decomposition, Moead};
10//! use evolutionary_planning::operators::real::{Bounds, Polynomial, Sbx};
11//! use evolutionary_planning::operators::{NoRepair, Variation};
12//! use evolutionary_planning::pareto::{das_dennis, hypervolume};
13//! use evolutionary_planning::problems::multi::Zdt;
14//! use evolutionary_planning::{Limits, SplitMix64};
15//!
16//! let bounds = Bounds::uniform(10, 0.0, 1.0);
17//! let mut moead = Moead::new(Config::default(), das_dennis(2, 99), Variation {
18//!     init: bounds.clone(),
19//!     crossover: Sbx { bounds: bounds.clone(), eta: 20.0 },
20//!     mutation: Polynomial { bounds, eta: 20.0, rate: None },
21//!     repair: NoRepair,
22//! });
23//! let outcome = moead.run(&mut Zdt::Zdt1, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
24//! let points: Vec<&[f64]> = outcome.front.iter().map(|e| e.objectives.as_slice()).collect();
25//! assert!(hypervolume(&points, &[1.1, 1.1]) > 0.85);
26//! ```
27
28use alloc::vec::Vec;
29
30use rand_core::Rng;
31
32use crate::multi::{MultiEvaluator, MultiOutcome, first_front};
33use crate::operators::{Crossover, Initializer, Mutation, Repair, Variation};
34use crate::pareto::{Evaluated, ParetoArchive};
35use crate::rng::{below, chance, shuffle};
36use crate::{Budget, MultiObjective, Observer, Stats, Stop};
37
38/// How a weight vector turns an objective vector into a scalar cost.
39#[derive(Debug, Clone, Copy, PartialEq)]
40pub enum Decomposition {
41    /// `Σ λ_i f_i`: finds only convex parts of the front.
42    WeightedSum,
43    /// `max λ_i |f_i - z_i|` with the ideal point `z`; zero weights are raised to `1e-6`.
44    Tchebycheff,
45    /// Penalty-based boundary intersection: `d1 + θ d2`, where `d1` is the distance along
46    /// `λ` from `z` and `d2` the distance from that line.
47    Pbi {
48        /// The penalty `θ`; `5` is customary.
49        theta: f64,
50    },
51}
52
53impl Decomposition {
54    /// The scalarised cost of `f` for weight `lambda` and ideal point `ideal`.
55    #[must_use]
56    pub fn cost(&self, f: &[f64], lambda: &[f64], ideal: &[f64]) -> f64 {
57        match *self {
58            Self::WeightedSum => f.iter().zip(lambda).map(|(a, w)| a * w).sum(),
59            Self::Tchebycheff => f
60                .iter()
61                .zip(lambda)
62                .zip(ideal)
63                .map(|((a, w), z)| w.max(1e-6) * (a - z).abs())
64                .fold(f64::NEG_INFINITY, f64::max),
65            Self::Pbi { theta } => {
66                let norm = libm::sqrt(lambda.iter().map(|w| w * w).sum());
67                let d1 = f
68                    .iter()
69                    .zip(ideal)
70                    .zip(lambda)
71                    .map(|((a, z), w)| (a - z) * w)
72                    .sum::<f64>()
73                    / norm;
74                let d2 = libm::sqrt(
75                    f.iter()
76                        .zip(ideal)
77                        .zip(lambda)
78                        .map(|((a, z), w)| {
79                            let off = a - (z + d1 * w / norm);
80                            off * off
81                        })
82                        .sum(),
83                );
84                d1 + theta * d2
85            }
86        }
87    }
88}
89
90/// Parameters of a [`Moead`] run.
91#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct Config {
93    /// The neighbourhood size `T`, at least `2` (clamped to the number of weights).
94    pub neighbourhood: usize,
95    /// The probability `δ` of mating within the neighbourhood (otherwise the whole population).
96    pub delta: f64,
97    /// The largest number of solutions one child may replace, `n_r`.
98    pub max_replacements: usize,
99    /// The scalarising function.
100    pub decomposition: Decomposition,
101    /// The probability that a pair of parents is recombined.
102    pub crossover_rate: f64,
103    /// The probability that a child is mutated at all.
104    pub mutation_rate: f64,
105    /// Keep an external Pareto archive of all evaluated non-dominated genomes, bounded to this
106    /// size by crowding; `None` keeps none and reports the population's front.
107    pub archive: Option<usize>,
108}
109
110impl Default for Config {
111    /// `T = 20`, `δ = 0.9`, `n_r = 2`, Tchebycheff, crossover rate `1`, no archive.
112    fn default() -> Self {
113        Self {
114            neighbourhood: 20,
115            delta: 0.9,
116            max_replacements: 2,
117            decomposition: Decomposition::Tchebycheff,
118            crossover_rate: 1.0,
119            mutation_rate: 1.0,
120            archive: None,
121        }
122    }
123}
124
125/// MOEA/D with caller-supplied weight vectors (see [`das_dennis`](crate::pareto::das_dennis)).
126#[derive(Debug, Clone, PartialEq)]
127pub struct Moead<I, X, M, P> {
128    /// The run parameters.
129    pub config: Config,
130    /// One weight vector per subproblem; the population size is their number.
131    pub weights: Vec<Vec<f64>>,
132    /// The variation operators.
133    pub variation: Variation<I, X, M, P>,
134}
135
136impl<I, X, M, P> Moead<I, X, M, P> {
137    /// Creates a MOEA/D run.
138    #[must_use]
139    pub fn new(config: Config, weights: Vec<Vec<f64>>, variation: Variation<I, X, M, P>) -> Self {
140        Self {
141            config,
142            weights,
143            variation,
144        }
145    }
146
147    /// Runs until the budget stops it; one generation is one pass over all subproblems.
148    ///
149    /// # Panics
150    ///
151    /// Panics if there are fewer than two weight vectors, or their dimension differs from the
152    /// problem's objective count.
153    pub fn run<G, Pr, B, Obs, R>(
154        &mut self,
155        problem: &mut Pr,
156        budget: &mut B,
157        observer: &mut Obs,
158        rng: &mut R,
159    ) -> MultiOutcome<G>
160    where
161        G: Clone,
162        I: Initializer<G>,
163        X: Crossover<G>,
164        M: Mutation<G>,
165        P: Repair<G>,
166        Pr: MultiObjective<G> + ?Sized,
167        B: Budget<Stats> + ?Sized,
168        Obs: Observer + ?Sized,
169        R: Rng + ?Sized,
170    {
171        let n = self.weights.len();
172        assert!(n >= 2, "MOEA/D needs at least two weight vectors");
173        assert!(
174            self.weights.iter().all(|w| w.len() == problem.objectives()),
175            "weights must have one coordinate per objective"
176        );
177
178        let neighbours = neighbourhoods(&self.weights, self.config.neighbourhood.clamp(2, n));
179        let mut archive = self.config.archive.map(|cap| ParetoArchive::new(Some(cap)));
180        let mut evaluator = MultiEvaluator::new(problem, budget, observer);
181        let mut population = Vec::with_capacity(n);
182        for _ in 0..n {
183            let Some(member) = evaluator.evaluate(self.variation.init.initialize(rng)) else {
184                return finish(&evaluator, population, archive);
185            };
186            offer(&mut archive, &member);
187            population.push(member);
188        }
189
190        let mut ideal = ideal_point(&population);
191        evaluator.end_generation();
192        loop {
193            for neighbourhood in &neighbours {
194                let pool: Vec<usize> = if chance(rng, self.config.delta) {
195                    neighbourhood.clone()
196                } else {
197                    (0..n).collect()
198                };
199                let child = self.child(&population, &pool, rng);
200                let Some(child) = evaluator.evaluate(child) else {
201                    return finish(&evaluator, population, archive);
202                };
203
204                for (z, f) in ideal.iter_mut().zip(&child.objectives) {
205                    *z = z.min(*f);
206                }
207                offer(&mut archive, &child);
208                self.replace(&mut population, &child, pool, &ideal, rng);
209            }
210
211            evaluator.end_generation();
212        }
213    }
214
215    /// Breeds one child from two parents of `pool`.
216    fn child<G, R>(&mut self, population: &[Evaluated<G>], pool: &[usize], rng: &mut R) -> G
217    where
218        G: Clone,
219        X: Crossover<G>,
220        M: Mutation<G>,
221        P: Repair<G>,
222        R: Rng + ?Sized,
223    {
224        let a = pool[below(rng, pool.len())];
225        let b = pool[below(rng, pool.len())];
226        let [child, _] = self.variation.breed(
227            &population[a].genome,
228            &population[b].genome,
229            self.config.crossover_rate,
230            self.config.mutation_rate,
231            rng,
232        );
233
234        child
235    }
236
237    /// Replaces up to `n_r` members of `pool` (in random order) that the child beats on their
238    /// own subproblem.
239    fn replace<G: Clone, R: Rng + ?Sized>(
240        &self,
241        population: &mut [Evaluated<G>],
242        child: &Evaluated<G>,
243        mut pool: Vec<usize>,
244        ideal: &[f64],
245        rng: &mut R,
246    ) {
247        shuffle(rng, &mut pool);
248        let mut replaced = 0;
249        for j in pool {
250            if replaced >= self.config.max_replacements {
251                break;
252            }
253
254            let current = &population[j];
255            let better = if child.violation.total_cmp(&current.violation).is_ne() {
256                child.violation < current.violation
257            } else {
258                let d = &self.config.decomposition;
259                d.cost(&child.objectives, &self.weights[j], ideal)
260                    <= d.cost(&current.objectives, &self.weights[j], ideal)
261            };
262            if better {
263                population[j] = child.clone();
264                replaced += 1;
265            }
266        }
267    }
268}
269
270/// For each weight vector, the indices of the `t` closest ones (itself included), nearest
271/// first, ties by index.
272fn neighbourhoods(weights: &[Vec<f64>], t: usize) -> Vec<Vec<usize>> {
273    weights
274        .iter()
275        .map(|w| {
276            let mut order: Vec<(f64, usize)> = weights
277                .iter()
278                .enumerate()
279                .map(|(j, v)| {
280                    (
281                        w.iter().zip(v).map(|(a, b)| (a - b) * (a - b)).sum::<f64>(),
282                        j,
283                    )
284                })
285                .collect();
286            order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
287            order.into_iter().take(t).map(|(_, j)| j).collect()
288        })
289        .collect()
290}
291
292/// The component-wise minimum of the population's objectives.
293fn ideal_point<G>(population: &[Evaluated<G>]) -> Vec<f64> {
294    let m = population[0].objectives.len();
295
296    (0..m)
297        .map(|j| {
298            population
299                .iter()
300                .map(|e| e.objectives[j])
301                .fold(f64::INFINITY, f64::min)
302        })
303        .collect()
304}
305
306/// Offers a member to the external archive, if one is kept.
307fn offer<G: Clone>(archive: &mut Option<ParetoArchive<G>>, member: &Evaluated<G>) {
308    if let Some(archive) = archive {
309        archive.insert(
310            member.genome.clone(),
311            member.objectives.clone(),
312            member.violation,
313        );
314    }
315}
316
317/// Ends the run; the front comes from the archive when one is kept.
318fn finish<G: Clone, Pr: ?Sized, B, Obs>(
319    evaluator: &MultiEvaluator<'_, Pr, B, Obs>,
320    population: Vec<Evaluated<G>>,
321    archive: Option<ParetoArchive<G>>,
322) -> MultiOutcome<G>
323where
324    B: Budget<Stats> + ?Sized,
325    Obs: Observer + ?Sized,
326{
327    let mut outcome = evaluator.outcome(population, Stop::Budget);
328    if let Some(archive) = archive {
329        outcome.front = first_front(archive.members());
330    }
331
332    outcome
333}
334
335#[cfg(test)]
336mod tests {
337    use super::*;
338    use crate::nsga2::tests::{brute_front, distinct};
339    use crate::operators::NoRepair;
340    use crate::operators::discrete::{BitFlip, RandomBits};
341    use crate::operators::sequence::UniformCrossover;
342    use crate::pareto::das_dennis;
343    use crate::problems::multi::Knapsack;
344    use crate::{Limits, SplitMix64};
345
346    /// Every decomposition returns only brute-force optimal knapsack points; with an archive
347    /// the whole front is found.
348    #[test]
349    fn knapsack_against_brute_force() {
350        let mut problem = Knapsack::generate(12, 7);
351        let expected = brute_front(&mut problem, 12);
352        for decomposition in [
353            Decomposition::Tchebycheff,
354            Decomposition::Pbi { theta: 5.0 },
355            Decomposition::WeightedSum,
356        ] {
357            let config = Config {
358                decomposition,
359                archive: Some(200),
360                ..Config::default()
361            };
362            let mut moead = Moead::new(
363                config,
364                das_dennis(2, 59),
365                Variation {
366                    init: RandomBits { len: 12 },
367                    crossover: UniformCrossover::default(),
368                    mutation: BitFlip::default(),
369                    repair: NoRepair,
370                },
371            );
372            let outcome = moead.run(
373                &mut problem,
374                &mut Limits::evaluations(30_000),
375                &mut (),
376                &mut SplitMix64::new(4),
377            );
378            let found = distinct(&outcome.front);
379
380            assert!(
381                found.iter().all(|p| expected.contains(p)),
382                "{decomposition:?}: {found:?}"
383            );
384            if decomposition == Decomposition::Tchebycheff {
385                assert_eq!(found, expected);
386            }
387        }
388    }
389
390    /// Hand-checked scalarisations.
391    #[test]
392    fn scalarisations() {
393        let f = [2.0, 1.0];
394        let w = [0.5, 0.5];
395        let z = [0.0, 0.0];
396
397        assert_eq!(Decomposition::WeightedSum.cost(&f, &w, &z), 1.5);
398        assert_eq!(Decomposition::Tchebycheff.cost(&f, &w, &z), 1.0);
399        let pbi = Decomposition::Pbi { theta: 5.0 }.cost(&f, &w, &z);
400        let d1 = 1.5 / libm::sqrt(0.5);
401        let d2 = libm::sqrt(0.5);
402        assert!((pbi - (d1 + 5.0 * d2)).abs() < 1e-12);
403    }
404}