Skip to main content

evolutionary_planning/
nsga2.rs

1//! NSGA-II (Deb, Pratap, Agarwal and Meyarivan 2002): elitist multi-objective search by
2//! non-dominated sorting and crowding distance, with Deb's constrained domination.
3//!
4//! ```mermaid
5//! graph LR
6//!     P[population P] --> T[binary crowded tournament]
7//!     T --> V[crossover, mutation, repair]
8//!     V --> Q[offspring Q, evaluated]
9//!     Q --> R["R = P ∪ Q"]
10//!     R --> S[non-dominated sort]
11//!     S --> F[fill by fronts, last front by crowding]
12//!     F --> P
13//! ```
14//!
15//! ```
16//! use evolutionary_planning::nsga2::{Config, Nsga2};
17//! use evolutionary_planning::operators::real::{Bounds, Polynomial, Sbx};
18//! use evolutionary_planning::operators::{NoRepair, Variation};
19//! use evolutionary_planning::pareto::hypervolume;
20//! use evolutionary_planning::problems::multi::Zdt;
21//! use evolutionary_planning::{Limits, SplitMix64};
22//!
23//! let bounds = Bounds::uniform(10, 0.0, 1.0);
24//! let mut nsga2 = Nsga2::new(Config::default(), Variation {
25//!     init: bounds.clone(),
26//!     crossover: Sbx { bounds: bounds.clone(), eta: 15.0 },
27//!     mutation: Polynomial { bounds, eta: 20.0, rate: None },
28//!     repair: NoRepair,
29//! });
30//! let outcome = nsga2.run(&mut Zdt::Zdt1, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
31//! let points: Vec<&[f64]> = outcome.front.iter().map(|e| e.objectives.as_slice()).collect();
32//! assert!(hypervolume(&points, &[1.1, 1.1]) > 0.85);
33//! ```
34
35use alloc::vec::Vec;
36
37use rand_core::Rng;
38
39use crate::multi::{MultiEvaluator, MultiOutcome};
40use crate::operators::{Crossover, Initializer, Mutation, Repair, Variation};
41use crate::pareto::{Evaluated, crowded_order, crowding_distance, non_dominated_sort};
42use crate::rng::below;
43use crate::{Budget, MultiObjective, Observer, Stats, Stop};
44
45/// Parameters of an [`Nsga2`] run.
46#[derive(Debug, Clone, Copy, PartialEq)]
47pub struct Config {
48    /// The population size `N`, at least `2`.
49    pub population_size: usize,
50    /// The probability that a pair of parents is recombined.
51    pub crossover_rate: f64,
52    /// The probability that a child is mutated at all.
53    pub mutation_rate: f64,
54}
55
56impl Default for Config {
57    /// `N = 100`, crossover rate `0.9`, every child mutated (the per-gene rate is the
58    /// mutation operator's).
59    fn default() -> Self {
60        Self {
61            population_size: 100,
62            crossover_rate: 0.9,
63            mutation_rate: 1.0,
64        }
65    }
66}
67
68/// NSGA-II over any genome.
69#[derive(Debug, Clone, PartialEq)]
70pub struct Nsga2<I, X, M, P> {
71    /// The run parameters.
72    pub config: Config,
73    /// The variation operators.
74    pub variation: Variation<I, X, M, P>,
75}
76
77impl<I, X, M, P> Nsga2<I, X, M, P> {
78    /// Creates an NSGA-II run.
79    #[must_use]
80    pub fn new(config: Config, variation: Variation<I, X, M, P>) -> Self {
81        Self { config, variation }
82    }
83
84    /// Runs until the budget stops it; returns the final population and its first front.
85    ///
86    /// # Panics
87    ///
88    /// Panics if the population size is below `2`.
89    pub fn run<G, Pr, B, Obs, R>(
90        &mut self,
91        problem: &mut Pr,
92        budget: &mut B,
93        observer: &mut Obs,
94        rng: &mut R,
95    ) -> MultiOutcome<G>
96    where
97        G: Clone,
98        I: Initializer<G>,
99        X: Crossover<G>,
100        M: Mutation<G>,
101        P: Repair<G>,
102        Pr: MultiObjective<G> + ?Sized,
103        B: Budget<Stats> + ?Sized,
104        Obs: Observer + ?Sized,
105        R: Rng + ?Sized,
106    {
107        let n = self.config.population_size;
108        assert!(n >= 2, "NSGA-II needs at least two individuals");
109
110        let mut evaluator = MultiEvaluator::new(problem, budget, observer);
111        let mut population = Vec::with_capacity(n);
112        for _ in 0..n {
113            let Some(member) = evaluator.evaluate(self.variation.init.initialize(rng)) else {
114                return evaluator.outcome(population, Stop::Budget);
115            };
116            population.push(member);
117        }
118
119        let (mut rank, mut crowd) = rank_and_crowd(&population);
120        evaluator.end_generation();
121        loop {
122            let mut offspring = Vec::with_capacity(n);
123            while offspring.len() < n {
124                let a = tournament(&rank, &crowd, rng);
125                let b = tournament(&rank, &crowd, rng);
126                let children = self.variation.breed(
127                    &population[a].genome,
128                    &population[b].genome,
129                    self.config.crossover_rate,
130                    self.config.mutation_rate,
131                    rng,
132                );
133                for child in children {
134                    if offspring.len() == n {
135                        break;
136                    }
137
138                    let Some(member) = evaluator.evaluate(child) else {
139                        return evaluator.outcome(population, Stop::Budget);
140                    };
141                    offspring.push(member);
142                }
143            }
144
145            population.extend(offspring);
146            population = environmental_selection(population, n);
147            (rank, crowd) = rank_and_crowd(&population);
148            evaluator.end_generation();
149        }
150    }
151}
152
153/// The binary crowded tournament: the better of two uniform picks by rank, then crowding.
154fn tournament<R: Rng + ?Sized>(rank: &[usize], crowd: &[f64], rng: &mut R) -> usize {
155    let a = below(rng, rank.len());
156    let b = below(rng, rank.len());
157
158    if crowded_order(rank[b], crowd[b], rank[a], crowd[a]).is_lt() {
159        b
160    } else {
161        a
162    }
163}
164
165/// The front rank and crowding distance of every member.
166fn rank_and_crowd<G>(population: &[Evaluated<G>]) -> (Vec<usize>, Vec<f64>) {
167    let points: Vec<&[f64]> = population.iter().map(|e| e.objectives.as_slice()).collect();
168    let violations: Vec<f64> = population.iter().map(|e| e.violation).collect();
169    let mut rank = alloc::vec![0; population.len()];
170    let mut crowd = alloc::vec![0.0; population.len()];
171    for (r, front) in non_dominated_sort(&points, &violations).iter().enumerate() {
172        for (slot, d) in front.iter().zip(crowding_distance(&points, front)) {
173            rank[*slot] = r;
174            crowd[*slot] = d;
175        }
176    }
177
178    (rank, crowd)
179}
180
181/// Keeps the `n` best of `combined` by front, then crowding distance within the last front.
182pub(crate) fn environmental_selection<G>(
183    combined: Vec<Evaluated<G>>,
184    n: usize,
185) -> Vec<Evaluated<G>> {
186    let points: Vec<&[f64]> = combined.iter().map(|e| e.objectives.as_slice()).collect();
187    let violations: Vec<f64> = combined.iter().map(|e| e.violation).collect();
188    let mut chosen = Vec::with_capacity(n);
189    for front in non_dominated_sort(&points, &violations) {
190        if chosen.len() + front.len() <= n {
191            chosen.extend_from_slice(&front);
192            if chosen.len() == n {
193                break;
194            }
195            continue;
196        }
197
198        let crowd = crowding_distance(&points, &front);
199        let mut order: Vec<usize> = (0..front.len()).collect();
200        order.sort_by(|&a, &b| crowd[b].total_cmp(&crowd[a]).then(a.cmp(&b)));
201        chosen.extend(
202            order
203                .into_iter()
204                .take(n - chosen.len())
205                .map(|slot| front[slot]),
206        );
207        break;
208    }
209
210    chosen.sort_unstable();
211    let mut keep = alloc::vec![false; combined.len()];
212    for &i in &chosen {
213        keep[i] = true;
214    }
215
216    combined
217        .into_iter()
218        .zip(keep)
219        .filter_map(|(e, k)| k.then_some(e))
220        .collect()
221}
222
223#[cfg(test)]
224pub(crate) mod tests;