1use 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#[derive(Debug, Clone, Copy, PartialEq)]
40pub enum Decomposition {
41 WeightedSum,
43 Tchebycheff,
45 Pbi {
48 theta: f64,
50 },
51}
52
53impl Decomposition {
54 #[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#[derive(Debug, Clone, Copy, PartialEq)]
92pub struct Config {
93 pub neighbourhood: usize,
95 pub delta: f64,
97 pub max_replacements: usize,
99 pub decomposition: Decomposition,
101 pub crossover_rate: f64,
103 pub mutation_rate: f64,
105 pub archive: Option<usize>,
108}
109
110impl Default for Config {
111 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#[derive(Debug, Clone, PartialEq)]
127pub struct Moead<I, X, M, P> {
128 pub config: Config,
130 pub weights: Vec<Vec<f64>>,
132 pub variation: Variation<I, X, M, P>,
134}
135
136impl<I, X, M, P> Moead<I, X, M, P> {
137 #[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 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 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 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(¤t.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(¤t.objectives, &self.weights[j], ideal)
261 };
262 if better {
263 population[j] = child.clone();
264 replaced += 1;
265 }
266 }
267 }
268}
269
270fn 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
292fn 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
306fn 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
317fn 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 #[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 #[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}