1pub mod rades;
18mod warm_start;
19
20use alloc::vec::Vec;
21
22use rand_core::Rng;
23pub use warm_start::WarmStartLibrary;
24
25use crate::evaluator::Evaluator;
26use crate::operators::Initializer;
27use crate::operators::real::{Bounds, latin_hypercube};
28use crate::rng::{below, distinct_indices, unit_f64};
29use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Strategy {
34 Rand1,
36 Best1,
38 CurrentToBest1,
40 Rand2,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum CrossoverKind {
47 Binomial,
49 Exponential,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Initialization {
57 Uniform,
59 LatinHypercube,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq)]
65pub struct Config {
66 pub population_size: usize,
68 pub f: f64,
70 pub cr: f64,
72 pub strategy: Strategy,
74 pub crossover: CrossoverKind,
76 pub initialization: Initialization,
78}
79
80impl Default for Config {
81 fn default() -> Self {
84 Self {
85 population_size: 40,
86 f: 0.5,
87 cr: 0.9,
88 strategy: Strategy::Rand1,
89 crossover: CrossoverKind::Binomial,
90 initialization: Initialization::LatinHypercube,
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq)]
99pub struct De {
100 pub config: Config,
102 pub bounds: Bounds,
104}
105
106impl De {
107 #[must_use]
109 pub fn new(config: Config, bounds: Bounds) -> Self {
110 Self { config, bounds }
111 }
112
113 pub fn run<O, B, Obs, R>(
119 &mut self,
120 objective: &mut O,
121 budget: &mut B,
122 observer: &mut Obs,
123 rng: &mut R,
124 ) -> Outcome<Vec<f64>>
125 where
126 O: Objective<Vec<f64>> + ?Sized,
127 B: Budget<Stats> + ?Sized,
128 Obs: Observer + ?Sized,
129 R: Rng + ?Sized,
130 {
131 self.run_from(Vec::new(), objective, budget, observer, rng)
132 }
133
134 pub fn run_from<O, B, Obs, R>(
142 &mut self,
143 seeds: Vec<Vec<f64>>,
144 objective: &mut O,
145 budget: &mut B,
146 observer: &mut Obs,
147 rng: &mut R,
148 ) -> Outcome<Vec<f64>>
149 where
150 O: Objective<Vec<f64>> + ?Sized,
151 B: Budget<Stats> + ?Sized,
152 Obs: Observer + ?Sized,
153 R: Rng + ?Sized,
154 {
155 assert!(
156 self.config.population_size >= 6,
157 "DE needs a population of at least six"
158 );
159
160 let mut evaluator = Evaluator::new(objective, budget, observer);
161 let genomes = self.initial_genomes(seeds, rng);
162 let Some(mut population) = evaluate_all(genomes, &mut evaluator) else {
163 return evaluator.outcome(Vec::new(), Stop::Budget);
164 };
165
166 evaluator.end_generation(crate::ga::population_best(&population));
167 loop {
168 let best = best_index(&population);
169 let mut next = population.clone();
170 for i in 0..population.len() {
171 let trial = self.trial(&population, i, best, rng);
172 let Some(cost) = evaluator.evaluate(&trial) else {
173 return evaluator.outcome(population, Stop::Budget);
174 };
175
176 if cost <= population[i].cost {
177 next[i] = Individual {
178 genome: trial,
179 cost,
180 };
181 }
182 }
183
184 population = next;
185 evaluator.end_generation(crate::ga::population_best(&population));
186 }
187 }
188
189 fn initial_genomes<R: Rng + ?Sized>(
191 &self,
192 mut seeds: Vec<Vec<f64>>,
193 rng: &mut R,
194 ) -> Vec<Vec<f64>> {
195 let size = self.config.population_size;
196 seeds.truncate(size);
197 for seed in &mut seeds {
198 self.bounds.clamp(seed);
199 }
200
201 let missing = size - seeds.len();
202 match self.config.initialization {
203 Initialization::Uniform => {
204 let mut bounds = self.bounds.clone();
205 seeds.extend((0..missing).map(|_| bounds.initialize(rng)));
206 }
207 Initialization::LatinHypercube => {
208 seeds.extend(latin_hypercube(&self.bounds, missing, rng));
209 }
210 }
211
212 seeds
213 }
214
215 fn trial<R: Rng + ?Sized>(
217 &self,
218 population: &[Individual<Vec<f64>>],
219 i: usize,
220 best: usize,
221 rng: &mut R,
222 ) -> Vec<f64> {
223 let mutant = self.mutant(population, i, best, rng);
224 let target = &population[i].genome;
225 let mut trial = cross(target, &mutant, self.config.cr, self.config.crossover, rng);
226 bounce_back(&mut trial, target, &self.bounds);
227
228 trial
229 }
230
231 #[expect(
233 clippy::many_single_char_names,
234 reason = "the textbook names of the DE formulas"
235 )]
236 fn mutant<R: Rng + ?Sized>(
237 &self,
238 population: &[Individual<Vec<f64>>],
239 i: usize,
240 best: usize,
241 rng: &mut R,
242 ) -> Vec<f64> {
243 let x = |k: usize| &population[k].genome;
244 let f = self.config.f;
245 let n = self.bounds.dimension();
246 let r = distinct_indices(rng, population.len(), 5, Some(i));
247 (0..n)
248 .map(|d| match self.config.strategy {
249 Strategy::Rand1 => x(r[0])[d] + f * (x(r[1])[d] - x(r[2])[d]),
250 Strategy::Best1 => x(best)[d] + f * (x(r[0])[d] - x(r[1])[d]),
251 Strategy::CurrentToBest1 => {
252 x(i)[d] + f * (x(best)[d] - x(i)[d]) + f * (x(r[0])[d] - x(r[1])[d])
253 }
254 Strategy::Rand2 => {
255 x(r[0])[d] + f * (x(r[1])[d] - x(r[2])[d]) + f * (x(r[3])[d] - x(r[4])[d])
256 }
257 })
258 .collect()
259 }
260}
261
262fn evaluate_all<O, B, Obs>(
264 genomes: Vec<Vec<f64>>,
265 evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
266) -> Option<Vec<Individual<Vec<f64>>>>
267where
268 O: Objective<Vec<f64>> + ?Sized,
269 B: Budget<Stats> + ?Sized,
270 Obs: Observer + ?Sized,
271{
272 genomes
273 .into_iter()
274 .map(|g| evaluator.individual(g))
275 .collect()
276}
277
278pub(crate) fn best_index<G>(population: &[Individual<G>]) -> usize {
280 let mut best = 0;
281 for (k, individual) in population.iter().enumerate() {
282 if individual.cost < population[best].cost {
283 best = k;
284 }
285 }
286
287 best
288}
289
290pub(crate) fn cross<R: Rng + ?Sized>(
292 target: &[f64],
293 mutant: &[f64],
294 cr: f64,
295 kind: CrossoverKind,
296 rng: &mut R,
297) -> Vec<f64> {
298 let n = target.len();
299 let mut trial = target.to_vec();
300 let forced = below(rng, n);
301 match kind {
302 CrossoverKind::Binomial => {
303 for d in 0..n {
304 if d == forced || unit_f64(rng) < cr {
305 trial[d] = mutant[d];
306 }
307 }
308 }
309 CrossoverKind::Exponential => {
310 let mut d = forced;
311 for _ in 0..n {
312 trial[d] = mutant[d];
313 d = (d + 1) % n;
314 if unit_f64(rng) >= cr {
315 break;
316 }
317 }
318 }
319 }
320
321 trial
322}
323
324pub(crate) fn bounce_back(trial: &mut [f64], target: &[f64], bounds: &Bounds) {
326 for (d, value) in trial.iter_mut().enumerate() {
327 let (low, high) = (bounds.lower()[d], bounds.upper()[d]);
328 if *value < low {
329 *value = f64::midpoint(low, target[d]);
330 } else if *value > high {
331 *value = f64::midpoint(high, target[d]);
332 }
333 }
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use crate::problems::single::{rastrigin, sphere};
340 use crate::{Limits, SplitMix64};
341
342 #[test]
344 fn strategies_solve_sphere() {
345 for strategy in [
346 Strategy::Rand1,
347 Strategy::Best1,
348 Strategy::CurrentToBest1,
349 Strategy::Rand2,
350 ] {
351 for crossover in [CrossoverKind::Binomial, CrossoverKind::Exponential] {
352 let config = Config {
353 strategy,
354 crossover,
355 cr: if crossover == CrossoverKind::Binomial {
356 0.9
357 } else {
358 0.95
359 },
360 ..Config::default()
361 };
362 let mut de = De::new(config, Bounds::uniform(5, -5.0, 5.0));
363 let mut objective = |x: &Vec<f64>| sphere(x);
364 let outcome = de.run(
365 &mut objective,
366 &mut Limits::evaluations(40_000),
367 &mut (),
368 &mut SplitMix64::new(2),
369 );
370 assert!(
371 outcome.best_cost() < 1e-6,
372 "{config:?}: {}",
373 outcome.best_cost()
374 );
375 }
376 }
377 }
378
379 #[test]
381 fn separable_rastrigin() {
382 let config = Config {
383 cr: 0.1,
384 ..Config::default()
385 };
386 let mut de = De::new(config, Bounds::uniform(5, -5.12, 5.12));
387 let mut objective = |x: &Vec<f64>| rastrigin(x);
388 let outcome = de.run(
389 &mut objective,
390 &mut Limits::evaluations(100_000),
391 &mut (),
392 &mut SplitMix64::new(4),
393 );
394
395 assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
396 }
397
398 #[test]
400 fn bounded_and_deterministic() {
401 let bounds = Bounds::uniform(3, 0.0, 1.0);
402 let run = || {
403 let mut de = De::new(Config::default(), bounds.clone());
404 let mut objective = |x: &Vec<f64>| x.iter().map(|v| (v + 3.0) * (v + 3.0)).sum::<f64>();
406 de.run(
407 &mut objective,
408 &mut Limits::evaluations(2_001),
409 &mut (),
410 &mut SplitMix64::new(8),
411 )
412 };
413 let outcome = run();
414
415 assert_eq!(outcome, run());
416 assert_eq!(outcome.stats.evaluations, 2_001);
417 assert!(
418 outcome
419 .population
420 .iter()
421 .all(|i| bounds.contains(&i.genome))
422 );
423 }
424}