evolutionary_planning/de/
rades.rs1use alloc::vec::Vec;
28
29use rand_core::Rng;
30
31use super::{CrossoverKind, best_index, bounce_back, cross};
32use crate::evaluator::Evaluator;
33use crate::operators::Initializer;
34use crate::operators::real::Bounds;
35use crate::rng::{below, unit_f64};
36use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop, ranking};
37
38#[derive(Debug, Clone, Copy, PartialEq)]
40pub struct Config {
41 pub population_size: usize,
43 pub f: f64,
45 pub cr: f64,
47 pub stagnation: u64,
49 pub beta: f64,
51}
52
53impl Default for Config {
54 fn default() -> Self {
55 Self {
56 population_size: 10,
57 f: 0.7,
58 cr: 0.5,
59 stagnation: 128,
60 beta: 2.0,
61 }
62 }
63}
64
65#[derive(Debug, Clone, PartialEq)]
67pub struct Rades {
68 pub config: Config,
70 pub bounds: Bounds,
72}
73
74struct State {
76 population: Vec<Individual<Vec<f64>>>,
78 archive: Vec<Individual<Vec<f64>>>,
80 stale: Vec<u64>,
82}
83
84impl Rades {
85 #[must_use]
87 pub fn new(config: Config, bounds: Bounds) -> Self {
88 Self { config, bounds }
89 }
90
91 pub fn run<O, B, Obs, R>(
97 &mut self,
98 objective: &mut O,
99 budget: &mut B,
100 observer: &mut Obs,
101 rng: &mut R,
102 ) -> Outcome<Vec<f64>>
103 where
104 O: Objective<Vec<f64>> + ?Sized,
105 B: Budget<Stats> + ?Sized,
106 Obs: Observer + ?Sized,
107 R: Rng + ?Sized,
108 {
109 assert!(
110 self.config.population_size >= 3,
111 "RADES needs a population of at least three"
112 );
113 assert!(self.config.beta > 1.0, "the rank bias must exceed one");
114
115 let mut evaluator = Evaluator::new(objective, budget, observer);
116 let mut state = State {
117 population: Vec::with_capacity(self.config.population_size),
118 archive: Vec::new(),
119 stale: alloc::vec![0; self.config.population_size],
120 };
121 for _ in 0..self.config.population_size {
122 let Some(individual) = evaluator.individual(self.bounds.clone().initialize(rng)) else {
123 return evaluator.outcome(state.population, Stop::Budget);
124 };
125 state.population.push(individual);
126 }
127
128 state.archive.clone_from(&state.population);
130 loop {
131 if !self.generation(&mut state, &mut evaluator, rng) {
132 return evaluator.outcome(state.population, Stop::Budget);
133 }
134
135 evaluator.end_generation(crate::ga::population_best(&state.population));
136 }
137 }
138
139 fn generation<O, B, Obs, R>(
141 &self,
142 state: &mut State,
143 evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
144 rng: &mut R,
145 ) -> bool
146 where
147 O: Objective<Vec<f64>> + ?Sized,
148 B: Budget<Stats> + ?Sized,
149 Obs: Observer + ?Sized,
150 R: Rng + ?Sized,
151 {
152 let population_order = ranking(&costs(&state.population));
153 let archive_order = ranking(&costs(&state.archive));
154 let best = best_index(&state.population);
155 let archive_best = archive_order.first().copied();
156 for i in 0..state.population.len() {
157 let explore = state.stale[i] > self.config.stagnation && archive_best.is_some();
158 let trial = if explore {
159 let archive_i = &state.archive[i % state.archive.len()].genome;
160 self.trial(
161 archive_i,
162 &state.archive,
163 &archive_order,
164 archive_best.unwrap_or(0),
165 rng,
166 )
167 } else {
168 let x_i = state.population[i].genome.clone();
169 self.trial(&x_i, &state.population, &population_order, best, rng)
170 };
171
172 let Some(cost) = evaluator.evaluate(&trial) else {
173 return false;
174 };
175
176 if cost < state.population[i].cost {
177 let individual = Individual {
178 genome: trial,
179 cost,
180 };
181 state.population[i] = individual.clone();
182 Self::archive(state, individual, rng);
183 state.stale[i] = 0;
184 } else {
185 state.stale[i] += 1;
186 }
187 }
188
189 true
190 }
191
192 fn trial<R: Rng + ?Sized>(
194 &self,
195 reference: &[f64],
196 source: &[Individual<Vec<f64>>],
197 order: &[usize],
198 best: usize,
199 rng: &mut R,
200 ) -> Vec<f64> {
201 let r1 = order[self.biased_rank(source.len(), rng)];
202 let mut r2 = order[self.biased_rank(source.len(), rng)];
203 for _ in 0..16 {
205 if r2 != r1 || source.len() < 2 {
206 break;
207 }
208 r2 = order[self.biased_rank(source.len(), rng)];
209 }
210 let x = |k: usize| &source[k].genome;
211 let mutant: Vec<f64> = (0..reference.len())
212 .map(|d| x(best)[d] + self.config.f * (x(r1)[d] - x(r2)[d]))
213 .collect();
214 let mut trial = cross(
215 reference,
216 &mutant,
217 self.config.cr,
218 CrossoverKind::Binomial,
219 rng,
220 );
221 bounce_back(&mut trial, reference, &self.bounds);
222
223 trial
224 }
225
226 fn biased_rank<R: Rng + ?Sized>(&self, size: usize, rng: &mut R) -> usize {
228 let beta = self.config.beta;
229 let u = unit_f64(rng);
230 #[expect(
231 clippy::cast_precision_loss,
232 reason = "population sizes are far below 2^52"
233 )]
234 let scale = size as f64 / (2.0 * beta - 1.0);
235 let value = scale * (beta - libm::sqrt(beta * beta - 4.0 * (beta - 1.0) * u));
236
237 #[expect(
238 clippy::cast_possible_truncation,
239 clippy::cast_sign_loss,
240 reason = "a non-negative rank below size"
241 )]
242 let rank = libm::floor(value) as usize;
243
244 rank.min(size - 1)
245 }
246
247 fn archive<R: Rng + ?Sized>(state: &mut State, individual: Individual<Vec<f64>>, rng: &mut R) {
249 state.archive.push(individual);
250 if state.archive.len() > state.population.len() {
251 let victim = below(rng, state.archive.len());
252 state.archive.swap_remove(victim);
253 }
254 }
255}
256
257fn costs(population: &[Individual<Vec<f64>>]) -> Vec<f64> {
259 population.iter().map(|i| i.cost).collect()
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265 use crate::problems::single::{rastrigin, rosenbrock};
266 use crate::{Limits, SplitMix64};
267
268 #[test]
270 fn biased_ranks() {
271 let rades = Rades::new(Config::default(), Bounds::uniform(1, 0.0, 1.0));
272 let mut rng = SplitMix64::new(1);
273 let mut counts = [0usize; 10];
274 for _ in 0..10_000 {
275 counts[rades.biased_rank(10, &mut rng)] += 1;
276 }
277
278 assert!(counts[0] > counts[5]);
279 assert_eq!(counts.iter().sum::<usize>(), 10_000);
280 }
281
282 #[test]
287 fn optimises_standard_functions() {
288 let mut rades = Rades::new(
289 Config {
290 population_size: 20,
291 ..Config::default()
292 },
293 Bounds::uniform(2, -2.0, 2.0),
294 );
295 let mut objective = |x: &Vec<f64>| rosenbrock(x);
296 let outcome = rades.run(
297 &mut objective,
298 &mut Limits::evaluations(20_000),
299 &mut (),
300 &mut SplitMix64::new(3),
301 );
302 assert!(outcome.best_cost() < 1e-2, "{}", outcome.best_cost());
303
304 let mut rades = Rades::new(
305 Config {
306 population_size: 20,
307 ..Config::default()
308 },
309 Bounds::uniform(3, -5.12, 5.12),
310 );
311 let mut objective = |x: &Vec<f64>| rastrigin(x);
312 let outcome = rades.run(
313 &mut objective,
314 &mut Limits::evaluations(60_000),
315 &mut (),
316 &mut SplitMix64::new(3),
317 );
318 assert!(outcome.best_cost() < 4.0, "{}", outcome.best_cost());
319 }
320
321 #[test]
323 fn deterministic() {
324 let run = || {
325 let mut rades = Rades::new(Config::default(), Bounds::uniform(3, -1.0, 1.0));
326 let mut objective = |x: &Vec<f64>| x.iter().sum::<f64>();
327 rades.run(
328 &mut objective,
329 &mut Limits::evaluations(1_000),
330 &mut (),
331 &mut SplitMix64::new(5),
332 )
333 };
334
335 assert_eq!(run(), run());
336 assert_eq!(run().stats.evaluations, 1_000);
337 }
338}