1use alloc::vec::Vec;
41
42use rand_core::Rng;
43
44use crate::evaluator::Evaluator;
45use crate::ga::{NoRefine, Operators, Refine, population_best};
46use crate::operators::{Crossover, Initializer, Mutation, Repair, Selection};
47use crate::rng::chance;
48use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Acceptance {
53 Always,
55 LocalLeast,
57 BetterParent,
59 LocalElitist,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq)]
66pub struct Config {
67 pub population_size: usize,
69 pub deme_size: usize,
72 pub offspring: usize,
74 pub crossover_rate: f64,
77 pub acceptance: Acceptance,
79 pub max_without_improvement: Option<u64>,
81 pub max_without_acceptance: Option<u64>,
83}
84
85impl Default for Config {
86 fn default() -> Self {
89 Self {
90 population_size: 60,
91 deme_size: 9,
92 offspring: 2,
93 crossover_rate: 0.6,
94 acceptance: Acceptance::LocalElitist,
95 max_without_improvement: None,
96 max_without_acceptance: None,
97 }
98 }
99}
100
101#[derive(Debug, Clone, PartialEq)]
104pub struct Diffusion<I, S, X, M, P> {
105 pub config: Config,
107 pub operators: Operators<I, S, X, M, P>,
109}
110
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
113struct Progress {
114 improved: bool,
116 accepted: bool,
118}
119
120impl<I, S, X, M, P> Diffusion<I, S, X, M, P> {
121 #[must_use]
123 pub fn new(config: Config, operators: Operators<I, S, X, M, P>) -> Self {
124 Self { config, operators }
125 }
126
127 pub fn run<G, O, B, Obs, R>(
133 &mut self,
134 objective: &mut O,
135 budget: &mut B,
136 observer: &mut Obs,
137 rng: &mut R,
138 ) -> Outcome<G>
139 where
140 G: Clone,
141 I: Initializer<G>,
142 S: Selection,
143 X: Crossover<G>,
144 M: Mutation<G>,
145 P: Repair<G>,
146 O: Objective<G> + ?Sized,
147 B: Budget<Stats> + ?Sized,
148 Obs: Observer + ?Sized,
149 R: Rng + ?Sized,
150 {
151 let mut evaluator = Evaluator::new(objective, budget, observer);
152
153 self.evolve(&mut evaluator, &mut NoRefine, rng)
154 }
155
156 pub fn run_memetic<G, L, O, B, Obs, R>(
163 &mut self,
164 memetic: &mut crate::memetic::Memetic<L>,
165 objective: &mut O,
166 budget: &mut B,
167 observer: &mut Obs,
168 rng: &mut R,
169 ) -> Outcome<G>
170 where
171 G: Clone,
172 I: Initializer<G>,
173 S: Selection,
174 X: Crossover<G>,
175 M: Mutation<G>,
176 P: Repair<G>,
177 L: crate::memetic::LocalSearch<G>,
178 O: Objective<G> + ?Sized,
179 B: Budget<Stats> + ?Sized,
180 Obs: Observer + ?Sized,
181 R: Rng + ?Sized,
182 {
183 let mut evaluator = Evaluator::new(objective, budget, observer);
184
185 self.evolve(&mut evaluator, memetic, rng)
186 }
187
188 fn evolve<G, O, B, Obs, F, R>(
190 &mut self,
191 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
192 refine: &mut F,
193 rng: &mut R,
194 ) -> Outcome<G>
195 where
196 G: Clone,
197 I: Initializer<G>,
198 S: Selection,
199 X: Crossover<G>,
200 M: Mutation<G>,
201 P: Repair<G>,
202 O: Objective<G> + ?Sized,
203 B: Budget<Stats> + ?Sized,
204 Obs: Observer + ?Sized,
205 F: Refine<G>,
206 R: Rng + ?Sized,
207 {
208 let radius = self.config.deme_size.max(3) / 2;
209 assert!(
210 self.config.population_size >= 2 * (2 * radius + 1),
211 "the ring must hold at least two demes"
212 );
213
214 let mut population = Vec::with_capacity(self.config.population_size);
215 for _ in 0..self.config.population_size {
216 let Some(member) = evaluator.individual(self.operators.init.initialize(rng)) else {
217 return evaluator.outcome(population, Stop::Budget);
218 };
219 population.push(member);
220 }
221
222 evaluator.end_generation(population_best(&population));
223 let (mut without_improvement, mut without_acceptance) = (0, 0);
224 loop {
225 let Some(progress) = self.generation(&mut population, radius, evaluator, refine, rng)
226 else {
227 return evaluator.outcome(population, Stop::Budget);
228 };
229
230 evaluator.end_generation(population_best(&population));
231 without_improvement = if progress.improved {
232 0
233 } else {
234 without_improvement + 1
235 };
236 without_acceptance = if progress.accepted {
237 0
238 } else {
239 without_acceptance + 1
240 };
241 let stagnated = self
242 .config
243 .max_without_improvement
244 .is_some_and(|m| without_improvement >= m)
245 || self
246 .config
247 .max_without_acceptance
248 .is_some_and(|m| without_acceptance >= m);
249 if stagnated {
250 return evaluator.outcome(population, Stop::Stagnation);
251 }
252 }
253 }
254
255 fn generation<G, O, B, Obs, F, R>(
257 &mut self,
258 population: &mut [Individual<G>],
259 radius: usize,
260 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
261 refine: &mut F,
262 rng: &mut R,
263 ) -> Option<Progress>
264 where
265 G: Clone,
266 S: Selection,
267 X: Crossover<G>,
268 M: Mutation<G>,
269 P: Repair<G>,
270 O: Objective<G> + ?Sized,
271 B: Budget<Stats> + ?Sized,
272 Obs: Observer + ?Sized,
273 F: Refine<G>,
274 R: Rng + ?Sized,
275 {
276 let n = population.len();
277 let mut progress = Progress::default();
278 let mut picked = Vec::with_capacity(1);
279 for centre in 0..n {
280 let neighbours: Vec<usize> = (1..=radius)
281 .flat_map(|d| [(centre + n - d) % n, (centre + d) % n])
282 .collect();
283 let costs: Vec<f64> = neighbours.iter().map(|&k| population[k].cost).collect();
284 picked.clear();
285 self.operators.selection.select(&costs, 1, rng, &mut picked);
286 let partner = neighbours[picked[0]];
287 let child = self.best_offspring(
288 &population[centre].genome,
289 &population[partner].genome,
290 evaluator,
291 rng,
292 )?;
293 let child = refine.refine(child, evaluator, rng);
294 let deme_worst = costs
295 .iter()
296 .copied()
297 .fold(population[centre].cost, f64::max);
298 let deme_best = costs
299 .iter()
300 .copied()
301 .fold(population[centre].cost, f64::min);
302 if self.accepts(&child, &population[centre], deme_worst, deme_best) {
303 progress.accepted = true;
304 progress.improved |= child.cost < deme_best;
305 population[centre] = child;
306 }
307 }
308
309 Some(progress)
310 }
311
312 fn best_offspring<G, O, B, Obs, R>(
314 &mut self,
315 own: &G,
316 partner: &G,
317 evaluator: &mut Evaluator<'_, G, O, B, Obs>,
318 rng: &mut R,
319 ) -> Option<Individual<G>>
320 where
321 G: Clone,
322 X: Crossover<G>,
323 M: Mutation<G>,
324 P: Repair<G>,
325 O: Objective<G> + ?Sized,
326 B: Budget<Stats> + ?Sized,
327 Obs: Observer + ?Sized,
328 R: Rng + ?Sized,
329 {
330 let mut best: Option<Individual<G>> = None;
331 let mut produced = 0;
332 while produced < self.config.offspring.max(1) {
333 let children = if chance(rng, self.config.crossover_rate) {
334 self.operators.crossover.crossover(own, partner, rng)
335 } else {
336 [own.clone(), own.clone()]
337 };
338
339 for mut child in children {
340 if produced == self.config.offspring.max(1) {
341 break;
342 }
343
344 self.operators.mutation.mutate(&mut child, rng);
345 self.operators.repair.repair(&mut child, rng);
346 let individual = evaluator.individual(child)?;
347 produced += 1;
348 if best.as_ref().is_none_or(|b| individual.cost < b.cost) {
349 best = Some(individual);
350 }
351 }
352 }
353
354 best
355 }
356
357 fn accepts<G>(
359 &self,
360 child: &Individual<G>,
361 parent: &Individual<G>,
362 deme_worst: f64,
363 deme_best: f64,
364 ) -> bool {
365 match self.config.acceptance {
366 Acceptance::Always => true,
367 Acceptance::LocalLeast => child.cost < deme_worst,
368 Acceptance::BetterParent => child.cost < parent.cost,
369 Acceptance::LocalElitist => {
370 let parent_is_best = parent.cost <= deme_best;
371 child.cost < deme_worst && (!parent_is_best || child.cost < parent.cost)
372 }
373 }
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::memetic::{Memetic, Rosenbrock};
381 use crate::operators::NoRepair;
382 use crate::operators::real::{Bounds, Polynomial, Sbx};
383 use crate::operators::selection::LinearRanking;
384 use crate::problems::single::{rastrigin, rosenbrock};
385 use crate::{Limits, SplitMix64};
386
387 fn real(
389 acceptance: Acceptance,
390 bounds: &Bounds,
391 ) -> Diffusion<Bounds, LinearRanking, Sbx, Polynomial, NoRepair> {
392 Diffusion::new(
393 Config {
394 acceptance,
395 ..Config::default()
396 },
397 Operators {
398 init: bounds.clone(),
399 selection: LinearRanking::default(),
400 crossover: Sbx {
401 bounds: bounds.clone(),
402 eta: 15.0,
403 },
404 mutation: Polynomial {
405 bounds: bounds.clone(),
406 eta: 20.0,
407 rate: None,
408 },
409 repair: NoRepair,
410 },
411 )
412 }
413
414 #[test]
417 fn acceptance_rules() {
418 let bounds = Bounds::uniform(4, -5.12, 5.12);
419 for acceptance in [
420 Acceptance::Always,
421 Acceptance::LocalLeast,
422 Acceptance::BetterParent,
423 Acceptance::LocalElitist,
424 ] {
425 let mut objective = |x: &Vec<f64>| rastrigin(x);
426 let outcome = real(acceptance, &bounds).run(
427 &mut objective,
428 &mut Limits::evaluations(40_000),
429 &mut (),
430 &mut SplitMix64::new(2),
431 );
432 assert!(
433 outcome.best_cost() < 3.0,
434 "{acceptance:?}: {}",
435 outcome.best_cost()
436 );
437 if matches!(
438 acceptance,
439 Acceptance::BetterParent | Acceptance::LocalElitist
440 ) {
441 assert_eq!(
442 outcome.population[0].cost,
443 outcome.best_cost(),
444 "{acceptance:?}"
445 );
446 }
447 }
448 }
449
450 #[test]
452 fn stagnation_stops() {
453 let bounds = Bounds::uniform(2, -1.0, 1.0);
454 let mut diffusion = real(Acceptance::BetterParent, &bounds);
455 diffusion.config.max_without_acceptance = Some(5);
456 let mut flat = |_: &Vec<f64>| 1.0;
457 let outcome = diffusion.run(
458 &mut flat,
459 &mut Limits::evaluations(1_000_000),
460 &mut (),
461 &mut SplitMix64::new(1),
462 );
463
464 assert_eq!(outcome.stop, Stop::Stagnation);
465 assert!(outcome.stats.evaluations < 1_000);
466 }
467
468 #[test]
470 fn hygleam_solves_rosenbrock() {
471 let bounds = Bounds::uniform(5, -2.0, 2.0);
472 let mut diffusion = real(Acceptance::LocalElitist, &bounds);
473 diffusion.config.population_size = 20;
474 diffusion.config.deme_size = 5;
475 let mut memetic = Memetic::adaptive(Rosenbrock::default());
476 let mut objective = |x: &Vec<f64>| rosenbrock(x);
477 let outcome = diffusion.run_memetic(
478 &mut memetic,
479 &mut objective,
480 &mut Limits::evaluations(40_000),
481 &mut (),
482 &mut SplitMix64::new(3),
483 );
484
485 assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
486 }
487}