1use 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#[derive(Debug, Clone, Copy, PartialEq)]
47pub struct Config {
48 pub population_size: usize,
50 pub crossover_rate: f64,
52 pub mutation_rate: f64,
54}
55
56impl Default for Config {
57 fn default() -> Self {
60 Self {
61 population_size: 100,
62 crossover_rate: 0.9,
63 mutation_rate: 1.0,
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq)]
70pub struct Nsga2<I, X, M, P> {
71 pub config: Config,
73 pub variation: Variation<I, X, M, P>,
75}
76
77impl<I, X, M, P> Nsga2<I, X, M, P> {
78 #[must_use]
80 pub fn new(config: Config, variation: Variation<I, X, M, P>) -> Self {
81 Self { config, variation }
82 }
83
84 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
153fn 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
165fn 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
181pub(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;