Skip to main content

evolutionary_planning/
nsga3.rs

1//! NSGA-III (Deb and Jain 2014): NSGA-II's non-dominated sorting with reference-point based
2//! niching instead of crowding, for three or more objectives.
3//!
4//! Environmental selection: the fronts of parents plus offspring are added until at least
5//! `N` members are chosen; if the last front does not fit, the chosen set is normalised
6//! (ideal point, extreme points by the achievement scalarising function, hyperplane
7//! intercepts, falling back to the nadir of the first front on degenerate hyperplanes), every
8//! member is associated with the reference line nearest by perpendicular distance, and the
9//! remaining slots go to members of the last front in the least crowded niches. Parents are
10//! chosen uniformly, as in the original.
11//!
12//! ```
13//! use evolutionary_planning::nsga3::{Config, Nsga3};
14//! use evolutionary_planning::operators::real::{Bounds, Polynomial, Sbx};
15//! use evolutionary_planning::operators::{NoRepair, Variation};
16//! use evolutionary_planning::pareto::das_dennis;
17//! use evolutionary_planning::problems::multi::{Dtlz, DtlzKind};
18//! use evolutionary_planning::{Limits, SplitMix64};
19//!
20//! let bounds = Bounds::uniform(7, 0.0, 1.0);
21//! let references = das_dennis(3, 6);
22//! let mut nsga3 = Nsga3::new(Config::for_references(&references), references, Variation {
23//!     init: bounds.clone(),
24//!     crossover: Sbx { bounds: bounds.clone(), eta: 30.0 },
25//!     mutation: Polynomial { bounds, eta: 20.0, rate: None },
26//!     repair: NoRepair,
27//! });
28//! let mut problem = Dtlz { kind: DtlzKind::Dtlz2, objectives: 3 };
29//! let outcome = nsga3.run(&mut problem, &mut Limits::evaluations(20_000), &mut (), &mut SplitMix64::new(1));
30//! for member in &outcome.front {
31//!     let radius: f64 = member.objectives.iter().map(|f| f * f).sum();
32//!     assert!((radius.sqrt() - 1.0).abs() < 0.05);
33//! }
34//! ```
35
36use alloc::vec::Vec;
37
38use rand_core::Rng;
39
40use crate::multi::{MultiEvaluator, MultiOutcome};
41use crate::operators::{Crossover, Initializer, Mutation, Repair, Variation};
42use crate::pareto::{Evaluated, non_dominated_sort};
43use crate::rng::below;
44use crate::{Budget, MultiObjective, Observer, Stats, Stop};
45
46/// Parameters of an [`Nsga3`] run.
47#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct Config {
49    /// The population size `N`, at least `2`; about the number of reference points.
50    pub population_size: usize,
51    /// The probability that a pair of parents is recombined.
52    pub crossover_rate: f64,
53    /// The probability that a child is mutated at all.
54    pub mutation_rate: f64,
55}
56
57impl Config {
58    /// The paper's sizing: the smallest multiple of four not below the number of reference
59    /// points; crossover rate `1`, every child mutated.
60    #[must_use]
61    pub fn for_references(references: &[Vec<f64>]) -> Self {
62        Self {
63            population_size: references.len().next_multiple_of(4).max(4),
64            crossover_rate: 1.0,
65            mutation_rate: 1.0,
66        }
67    }
68}
69
70/// NSGA-III over any genome, with caller-supplied reference points (see
71/// [`das_dennis`](crate::pareto::das_dennis) and [`two_layer`](crate::pareto::two_layer)).
72#[derive(Debug, Clone, PartialEq)]
73pub struct Nsga3<I, X, M, P> {
74    /// The run parameters.
75    pub config: Config,
76    /// The reference points on the normalised hyperplane, each with `m` coordinates.
77    pub references: Vec<Vec<f64>>,
78    /// The variation operators.
79    pub variation: Variation<I, X, M, P>,
80}
81
82impl<I, X, M, P> Nsga3<I, X, M, P> {
83    /// Creates an NSGA-III run.
84    #[must_use]
85    pub fn new(
86        config: Config,
87        references: Vec<Vec<f64>>,
88        variation: Variation<I, X, M, P>,
89    ) -> Self {
90        Self {
91            config,
92            references,
93            variation,
94        }
95    }
96
97    /// Runs until the budget stops it.
98    ///
99    /// # Panics
100    ///
101    /// Panics if the population size is below `2`, there are no reference points, or their
102    /// dimension differs from the problem's objective count.
103    pub fn run<G, Pr, B, Obs, R>(
104        &mut self,
105        problem: &mut Pr,
106        budget: &mut B,
107        observer: &mut Obs,
108        rng: &mut R,
109    ) -> MultiOutcome<G>
110    where
111        G: Clone,
112        I: Initializer<G>,
113        X: Crossover<G>,
114        M: Mutation<G>,
115        P: Repair<G>,
116        Pr: MultiObjective<G> + ?Sized,
117        B: Budget<Stats> + ?Sized,
118        Obs: Observer + ?Sized,
119        R: Rng + ?Sized,
120    {
121        let n = self.config.population_size;
122        assert!(n >= 2, "NSGA-III needs at least two individuals");
123        assert!(
124            !self.references.is_empty(),
125            "NSGA-III needs reference points"
126        );
127        assert!(
128            self.references
129                .iter()
130                .all(|r| r.len() == problem.objectives()),
131            "reference points must have one coordinate per objective"
132        );
133
134        let mut evaluator = MultiEvaluator::new(problem, budget, observer);
135        let mut population = Vec::with_capacity(n);
136        for _ in 0..n {
137            let Some(member) = evaluator.evaluate(self.variation.init.initialize(rng)) else {
138                return evaluator.outcome(population, Stop::Budget);
139            };
140            population.push(member);
141        }
142
143        evaluator.end_generation();
144        loop {
145            let mut offspring = Vec::with_capacity(n);
146            while offspring.len() < n {
147                let a = below(rng, population.len());
148                let b = below(rng, population.len());
149                let children = self.variation.breed(
150                    &population[a].genome,
151                    &population[b].genome,
152                    self.config.crossover_rate,
153                    self.config.mutation_rate,
154                    rng,
155                );
156                for child in children {
157                    if offspring.len() == n {
158                        break;
159                    }
160
161                    let Some(member) = evaluator.evaluate(child) else {
162                        return evaluator.outcome(population, Stop::Budget);
163                    };
164                    offspring.push(member);
165                }
166            }
167
168            population.extend(offspring);
169            population = self.select(population, n, rng);
170            evaluator.end_generation();
171        }
172    }
173
174    /// NSGA-III environmental selection of `n` members from `combined`.
175    fn select<G, R: Rng + ?Sized>(
176        &self,
177        combined: Vec<Evaluated<G>>,
178        n: usize,
179        rng: &mut R,
180    ) -> Vec<Evaluated<G>> {
181        let points: Vec<&[f64]> = combined.iter().map(|e| e.objectives.as_slice()).collect();
182        let violations: Vec<f64> = combined.iter().map(|e| e.violation).collect();
183        let fronts = non_dominated_sort(&points, &violations);
184        let mut chosen: Vec<usize> = Vec::with_capacity(n);
185        let mut last: Vec<usize> = Vec::new();
186        for front in &fronts {
187            if chosen.len() + front.len() <= n {
188                chosen.extend_from_slice(front);
189            } else {
190                last.clone_from(front);
191            }
192
193            if chosen.len() >= n || !last.is_empty() {
194                break;
195            }
196        }
197
198        if !last.is_empty() {
199            let candidates: Vec<usize> = chosen.iter().chain(&last).copied().collect();
200            let first_front = &fronts[0];
201            let normalised = normalise(&points, &candidates, first_front);
202            let niches = associate(&normalised, &self.references);
203            let picked = niching(
204                n - chosen.len(),
205                chosen.len(),
206                &niches,
207                self.references.len(),
208                rng,
209            );
210            chosen.extend(picked.into_iter().map(|slot| last[slot]));
211        }
212
213        keep(combined, &chosen)
214    }
215}
216
217/// Keeps the members of `combined` at the indices `chosen`.
218fn keep<G>(combined: Vec<Evaluated<G>>, chosen: &[usize]) -> Vec<Evaluated<G>> {
219    let mut flags = alloc::vec![false; combined.len()];
220    for &i in chosen {
221        flags[i] = true;
222    }
223
224    combined
225        .into_iter()
226        .zip(flags)
227        .filter_map(|(e, k)| k.then_some(e))
228        .collect()
229}
230
231/// Normalises the objective vectors of `candidates` (indices into `points`): translated by
232/// the ideal point and divided by the hyperplane intercepts.
233fn normalise(points: &[&[f64]], candidates: &[usize], first_front: &[usize]) -> Vec<Vec<f64>> {
234    let m = points[candidates[0]].len();
235    let ideal: Vec<f64> = (0..m)
236        .map(|j| {
237            candidates
238                .iter()
239                .map(|&i| points[i][j])
240                .fold(f64::INFINITY, f64::min)
241        })
242        .collect();
243    let translated: Vec<Vec<f64>> = candidates
244        .iter()
245        .map(|&i| points[i].iter().zip(&ideal).map(|(f, z)| f - z).collect())
246        .collect();
247    let intercepts = intercepts(&translated, candidates, first_front, m);
248
249    translated
250        .into_iter()
251        .map(|f| f.iter().zip(&intercepts).map(|(v, a)| v / a).collect())
252        .collect()
253}
254
255/// The hyperplane intercepts through the extreme points, or the nadir of the first front
256/// (per objective maximum, at least `1e-10`) when the hyperplane is degenerate.
257fn intercepts(
258    translated: &[Vec<f64>],
259    candidates: &[usize],
260    first_front: &[usize],
261    m: usize,
262) -> Vec<f64> {
263    let extremes: Vec<Vec<f64>> = (0..m)
264        .map(|axis| {
265            let asf = |f: &[f64]| {
266                f.iter()
267                    .enumerate()
268                    .map(|(j, v)| v / if j == axis { 1.0 } else { 1e-6 })
269                    .fold(f64::NEG_INFINITY, f64::max)
270            };
271            translated
272                .iter()
273                .min_by(|a, b| asf(a).total_cmp(&asf(b)))
274                .cloned()
275                .unwrap_or_default()
276        })
277        .collect();
278
279    let nadir = || {
280        (0..m)
281            .map(|j| {
282                translated
283                    .iter()
284                    .zip(candidates)
285                    .filter(|(_, i)| first_front.contains(i))
286                    .map(|(f, _)| f[j])
287                    .fold(0.0, f64::max)
288                    .max(1e-10)
289            })
290            .collect()
291    };
292
293    match solve(extremes, alloc::vec![1.0; m]) {
294        Some(a) if a.iter().all(|&v| v > 1e-10 && v.is_finite()) => {
295            let intercepts: Vec<f64> = a.iter().map(|v| 1.0 / v).collect();
296            if intercepts.iter().all(|&v| v > 1e-10 && v.is_finite()) {
297                intercepts
298            } else {
299                nadir()
300            }
301        }
302        _ => nadir(),
303    }
304}
305
306/// Solves `A x = b` by Gaussian elimination with partial pivoting; `None` if singular.
307fn solve(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
308    let n = b.len();
309    for col in 0..n {
310        let pivot = (col..n).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
311        if a[pivot][col].abs() < 1e-12 {
312            return None;
313        }
314
315        a.swap(col, pivot);
316        b.swap(col, pivot);
317        for row in col + 1..n {
318            let factor = a[row][col] / a[col][col];
319            for k in col..n {
320                a[row][k] -= factor * a[col][k];
321            }
322            b[row] -= factor * b[col];
323        }
324    }
325
326    let mut x = alloc::vec![0.0; n];
327    for row in (0..n).rev() {
328        let tail: f64 = (row + 1..n).map(|k| a[row][k] * x[k]).sum();
329        x[row] = (b[row] - tail) / a[row][row];
330    }
331
332    Some(x)
333}
334
335/// For each normalised point: its nearest reference line and the perpendicular distance.
336fn associate(normalised: &[Vec<f64>], references: &[Vec<f64>]) -> Vec<(usize, f64)> {
337    normalised
338        .iter()
339        .map(|f| {
340            references
341                .iter()
342                .enumerate()
343                .map(|(r, w)| (r, perpendicular_distance(f, w)))
344                .min_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0)))
345                .unwrap_or((0, f64::INFINITY))
346        })
347        .collect()
348}
349
350/// The distance from `f` to the line through the origin along `w`.
351fn perpendicular_distance(f: &[f64], w: &[f64]) -> f64 {
352    let norm2: f64 = w.iter().map(|v| v * v).sum();
353    let projection: f64 = f.iter().zip(w).map(|(a, b)| a * b).sum::<f64>() / norm2;
354
355    libm::sqrt(
356        f.iter()
357            .zip(w)
358            .map(|(a, b)| (a - projection * b) * (a - projection * b))
359            .sum(),
360    )
361}
362
363/// Picks `k` members of the last front by niche count. `niches` holds the association of the
364/// already chosen members (`chosen` of them, first) followed by the last front's.
365fn niching<R: Rng + ?Sized>(
366    k: usize,
367    chosen: usize,
368    niches: &[(usize, f64)],
369    references: usize,
370    rng: &mut R,
371) -> Vec<usize> {
372    let mut counts = alloc::vec![0usize; references];
373    for &(r, _) in &niches[..chosen] {
374        counts[r] += 1;
375    }
376
377    let last = &niches[chosen..];
378    let mut taken = alloc::vec![false; last.len()];
379    let mut excluded = alloc::vec![false; references];
380    let mut picked = Vec::with_capacity(k);
381    while picked.len() < k {
382        let Some(min_count) = (0..references)
383            .filter(|&r| !excluded[r])
384            .map(|r| counts[r])
385            .min()
386        else {
387            break;
388        };
389
390        let candidates: Vec<usize> = (0..references)
391            .filter(|&r| !excluded[r] && counts[r] == min_count)
392            .collect();
393        let r = candidates[below(rng, candidates.len())];
394        let members: Vec<usize> = (0..last.len())
395            .filter(|&s| !taken[s] && last[s].0 == r)
396            .collect();
397        if members.is_empty() {
398            excluded[r] = true;
399            continue;
400        }
401
402        let slot = if counts[r] == 0 {
403            *members
404                .iter()
405                .min_by(|&&a, &&b| last[a].1.total_cmp(&last[b].1).then(a.cmp(&b)))
406                .unwrap_or(&members[0])
407        } else {
408            members[below(rng, members.len())]
409        };
410        taken[slot] = true;
411        counts[r] += 1;
412        picked.push(slot);
413    }
414
415    picked
416}
417
418#[cfg(test)]
419mod tests {
420    use super::*;
421    use crate::nsga2::tests::{brute_front, distinct};
422    use crate::operators::NoRepair;
423    use crate::operators::discrete::{BitFlip, RandomBits};
424    use crate::operators::real::{Bounds, Polynomial, Sbx};
425    use crate::operators::sequence::UniformCrossover;
426    use crate::pareto::das_dennis;
427    use crate::problems::multi::{Dtlz, DtlzKind, Knapsack};
428    use crate::{Limits, SplitMix64};
429
430    /// On DTLZ2 with three objectives, the front lies on the unit sphere and covers most
431    /// reference directions.
432    #[test]
433    fn dtlz2_converges_and_spreads() {
434        let bounds = Bounds::uniform(12, 0.0, 1.0);
435        let references = das_dennis(3, 12);
436        let mut nsga3 = Nsga3::new(
437            Config::for_references(&references),
438            references.clone(),
439            Variation {
440                init: bounds.clone(),
441                crossover: Sbx {
442                    bounds: bounds.clone(),
443                    eta: 30.0,
444                },
445                mutation: Polynomial {
446                    bounds,
447                    eta: 20.0,
448                    rate: None,
449                },
450                repair: NoRepair,
451            },
452        );
453        let mut problem = Dtlz {
454            kind: DtlzKind::Dtlz2,
455            objectives: 3,
456        };
457        let outcome = nsga3.run(
458            &mut problem,
459            &mut Limits::evaluations(60_000),
460            &mut (),
461            &mut SplitMix64::new(2),
462        );
463
464        let mut covered = alloc::vec![false; references.len()];
465        for member in &outcome.front {
466            let radius = libm::sqrt(member.objectives.iter().map(|f| f * f).sum());
467            assert!((radius - 1.0).abs() < 0.01, "radius {radius}");
468            let (r, _) = associate(core::slice::from_ref(&member.objectives), &references)[0];
469            covered[r] = true;
470        }
471
472        let coverage = covered.iter().filter(|&&c| c).count();
473        assert!(
474            coverage * 10 >= references.len() * 9,
475            "{coverage} of {}",
476            references.len()
477        );
478    }
479
480    /// On the constrained knapsack, NSGA-III returns only brute-force Pareto-optimal points.
481    #[test]
482    fn knapsack_points_are_optimal() {
483        let mut problem = Knapsack::generate(12, 7);
484        let expected = brute_front(&mut problem, 12);
485        let references = das_dennis(2, 39);
486        let mut nsga3 = Nsga3::new(
487            Config::for_references(&references),
488            references,
489            Variation {
490                init: RandomBits { len: 12 },
491                crossover: UniformCrossover::default(),
492                mutation: BitFlip::default(),
493                repair: NoRepair,
494            },
495        );
496        let outcome = nsga3.run(
497            &mut problem,
498            &mut Limits::evaluations(30_000),
499            &mut (),
500            &mut SplitMix64::new(1),
501        );
502        let found = distinct(&outcome.front);
503
504        assert!(found.iter().all(|p| expected.contains(p)), "{found:?}");
505        assert!(
506            found.len() * 10 >= expected.len() * 8,
507            "{} of {}",
508            found.len(),
509            expected.len()
510        );
511    }
512
513    /// The linear solver and the perpendicular distance on hand-checked inputs.
514    #[test]
515    fn geometry_helpers() {
516        let x = solve(
517            alloc::vec![alloc::vec![2.0, 1.0], alloc::vec![1.0, 3.0]],
518            alloc::vec![3.0, 5.0],
519        )
520        .expect("regular");
521        assert!((x[0] - 0.8).abs() < 1e-12 && (x[1] - 1.4).abs() < 1e-12);
522        assert!(
523            solve(
524                alloc::vec![alloc::vec![1.0, 2.0], alloc::vec![2.0, 4.0]],
525                alloc::vec![1.0, 1.0]
526            )
527            .is_none()
528        );
529        assert!((perpendicular_distance(&[1.0, 1.0], &[1.0, 0.0]) - 1.0).abs() < 1e-12);
530    }
531}