1use alloc::vec::Vec;
18
19use rand_core::Rng;
20
21use crate::evaluator::Evaluator;
22use crate::operators::Initializer;
23use crate::rng::{below, distinct_indices, standard_normal};
24use crate::{Budget, Individual, Objective, Observer, Outcome, Stats, Stop};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Survival {
29 Comma,
31 Plus,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum StepSizes {
38 Global,
40 PerCoordinate,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Recombination {
48 Intermediate,
50 Discrete,
52}
53
54#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Config {
57 pub mu: usize,
59 pub rho: usize,
61 pub lambda: usize,
63 pub survival: Survival,
65 pub step_sizes: StepSizes,
67 pub recombination: Recombination,
69 pub initial_sigma: f64,
71 pub min_sigma: f64,
73}
74
75impl Default for Config {
76 fn default() -> Self {
79 Self {
80 mu: 15,
81 rho: 2,
82 lambda: 100,
83 survival: Survival::Comma,
84 step_sizes: StepSizes::PerCoordinate,
85 recombination: Recombination::Intermediate,
86 initial_sigma: 0.3,
87 min_sigma: 1e-300,
88 }
89 }
90}
91
92#[derive(Debug, Clone, PartialEq)]
94struct Member {
95 x: Vec<f64>,
97 sigma: Vec<f64>,
99 cost: f64,
101}
102
103#[derive(Debug, Clone, PartialEq)]
106pub struct Es {
107 pub config: Config,
109 pub bounds: crate::operators::real::Bounds,
111}
112
113impl Es {
114 #[must_use]
116 pub fn new(config: Config, bounds: crate::operators::real::Bounds) -> Self {
117 Self { config, bounds }
118 }
119
120 pub fn run<O, B, Obs, R>(
127 &mut self,
128 objective: &mut O,
129 budget: &mut B,
130 observer: &mut Obs,
131 rng: &mut R,
132 ) -> Outcome<Vec<f64>>
133 where
134 O: Objective<Vec<f64>> + ?Sized,
135 B: Budget<Stats> + ?Sized,
136 Obs: Observer + ?Sized,
137 R: Rng + ?Sized,
138 {
139 self.validate();
140 let mut evaluator = Evaluator::new(objective, budget, observer);
141 let Some(mut parents) = self.initial_parents(&mut evaluator, rng) else {
142 return evaluator.outcome(Vec::new(), Stop::Budget);
143 };
144
145 loop {
146 let mut offspring = Vec::with_capacity(self.config.lambda);
147 for _ in 0..self.config.lambda {
148 let child = self.offspring(&parents, rng);
149 let Some(cost) = evaluator.evaluate(&child.x) else {
150 return evaluator.outcome(population(parents), Stop::Budget);
151 };
152 offspring.push(Member { cost, ..child });
153 }
154
155 if self.config.survival == Survival::Plus {
156 offspring.extend(parents);
157 }
158
159 offspring.sort_by(|a, b| a.cost.total_cmp(&b.cost));
160 offspring.truncate(self.config.mu);
161 parents = offspring;
162 evaluator.end_generation(parents[0].cost);
163 }
164 }
165
166 fn validate(&self) {
168 let c = &self.config;
169 assert!(
170 c.mu > 0 && c.lambda > 0 && c.rho > 0,
171 "mu, rho and lambda must be positive"
172 );
173 assert!(c.rho <= c.mu, "rho must not exceed mu");
174 assert!(
175 c.survival == Survival::Plus || c.lambda >= c.mu,
176 "comma selection needs lambda >= mu"
177 );
178 }
179
180 fn initial_parents<O, B, Obs, R>(
182 &mut self,
183 evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
184 rng: &mut R,
185 ) -> Option<Vec<Member>>
186 where
187 O: Objective<Vec<f64>> + ?Sized,
188 B: Budget<Stats> + ?Sized,
189 Obs: Observer + ?Sized,
190 R: Rng + ?Sized,
191 {
192 let n = self.bounds.dimension();
193 let sigma: Vec<f64> = match self.config.step_sizes {
194 StepSizes::Global => {
195 let mean_width = (0..n).map(|i| self.bounds.width(i)).sum::<f64>() / dimension(n);
196 alloc::vec![self.config.initial_sigma * mean_width; 1]
197 }
198 StepSizes::PerCoordinate => (0..n)
199 .map(|i| self.config.initial_sigma * self.bounds.width(i))
200 .collect(),
201 };
202
203 let mut parents = Vec::with_capacity(self.config.mu);
204 for _ in 0..self.config.mu {
205 let x = self.bounds.initialize(rng);
206 let cost = evaluator.evaluate(&x)?;
207 parents.push(Member {
208 x,
209 sigma: sigma.clone(),
210 cost,
211 });
212 }
213
214 Some(parents)
215 }
216
217 fn offspring<R: Rng + ?Sized>(&self, parents: &[Member], rng: &mut R) -> Member {
219 let chosen = distinct_indices(rng, parents.len(), self.config.rho, None);
220 let mut child = self.recombine(parents, &chosen, rng);
221 self.mutate_sigma(&mut child.sigma, rng);
222 for (i, x) in child.x.iter_mut().enumerate() {
223 let sigma = if child.sigma.len() == 1 {
224 child.sigma[0]
225 } else {
226 child.sigma[i]
227 };
228 *x += sigma * standard_normal(rng);
229 }
230
231 let mut repair = crate::operators::real::Reflect(self.bounds.clone());
232 crate::operators::Repair::repair(&mut repair, &mut child.x, rng);
233 child
234 }
235
236 fn recombine<R: Rng + ?Sized>(
238 &self,
239 parents: &[Member],
240 chosen: &[usize],
241 rng: &mut R,
242 ) -> Member {
243 let n = parents[0].x.len();
244 let k = parents[0].sigma.len();
245 let mut x = alloc::vec![0.0; n];
246 let mut sigma = alloc::vec![0.0; k];
247 match self.config.recombination {
248 Recombination::Intermediate => {
249 #[expect(clippy::cast_precision_loss, reason = "rho is tiny")]
250 let weight = 1.0 / chosen.len() as f64;
251 for &p in chosen {
252 x.iter_mut()
253 .zip(&parents[p].x)
254 .for_each(|(a, b)| *a += weight * b);
255 sigma
256 .iter_mut()
257 .zip(&parents[p].sigma)
258 .for_each(|(a, b)| *a += weight * b);
259 }
260 }
261 Recombination::Discrete => {
262 for (i, xi) in x.iter_mut().enumerate() {
263 *xi = parents[chosen[below(rng, chosen.len())]].x[i];
264 }
265 for (j, s) in sigma.iter_mut().enumerate() {
266 *s = parents[chosen[below(rng, chosen.len())]].sigma[j];
267 }
268 }
269 }
270
271 Member {
272 x,
273 sigma,
274 cost: f64::INFINITY,
275 }
276 }
277
278 fn mutate_sigma<R: Rng + ?Sized>(&self, sigma: &mut [f64], rng: &mut R) {
280 let n = dimension(self.bounds.dimension());
281 let floor = self.config.min_sigma;
282 if sigma.len() == 1 {
283 let tau = 1.0 / libm::sqrt(n);
284 sigma[0] = (sigma[0] * libm::exp(tau * standard_normal(rng))).max(floor);
285 return;
286 }
287
288 let tau_global = 1.0 / libm::sqrt(2.0 * n);
289 let tau_local = 1.0 / libm::sqrt(2.0 * libm::sqrt(n));
290 let global = tau_global * standard_normal(rng);
291 for s in sigma.iter_mut() {
292 *s = (*s * libm::exp(global + tau_local * standard_normal(rng))).max(floor);
293 }
294 }
295}
296
297fn dimension(n: usize) -> f64 {
299 #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
300 let n = n.max(1) as f64;
301
302 n
303}
304
305fn population(members: Vec<Member>) -> Vec<Individual<Vec<f64>>> {
307 members
308 .into_iter()
309 .map(|m| Individual {
310 genome: m.x,
311 cost: m.cost,
312 })
313 .collect()
314}
315
316#[derive(Debug, Clone, Copy, PartialEq)]
331pub struct OnePlusOne {
332 pub sigma: f64,
334 pub min_sigma: f64,
336}
337
338impl OnePlusOne {
339 pub fn run<O, B, Obs, R>(
341 &mut self,
342 start: Vec<f64>,
343 objective: &mut O,
344 budget: &mut B,
345 observer: &mut Obs,
346 rng: &mut R,
347 ) -> Outcome<Vec<f64>>
348 where
349 O: Objective<Vec<f64>> + ?Sized,
350 B: Budget<Stats> + ?Sized,
351 Obs: Observer + ?Sized,
352 R: Rng + ?Sized,
353 {
354 let mut evaluator = Evaluator::new(objective, budget, observer);
355 let Some(mut current) = evaluator.individual(start) else {
356 return evaluator.outcome(Vec::new(), Stop::Budget);
357 };
358
359 let mut sigma = self.sigma;
360 loop {
361 let candidate: Vec<f64> = current
362 .genome
363 .iter()
364 .map(|x| x + sigma * standard_normal(rng))
365 .collect();
366 let Some(cost) = evaluator.evaluate(&candidate) else {
367 break;
368 };
369
370 if cost <= current.cost {
371 current = Individual {
372 genome: candidate,
373 cost,
374 };
375 sigma *= libm::exp(1.0 / 3.0);
376 } else {
377 sigma = (sigma * libm::exp(-1.0 / 12.0)).max(self.min_sigma);
378 }
379
380 evaluator.end_generation(current.cost);
381 }
382
383 evaluator.outcome(alloc::vec![current], Stop::Budget)
384 }
385}
386
387#[cfg(test)]
388mod tests {
389 use super::*;
390 use crate::operators::real::Bounds;
391 use crate::problems::single::{ellipsoid, rosenbrock, sphere};
392 use crate::{Limits, SplitMix64};
393
394 #[test]
396 fn variants_converge_on_sphere() {
397 for survival in [Survival::Comma, Survival::Plus] {
398 for step_sizes in [StepSizes::Global, StepSizes::PerCoordinate] {
399 for recombination in [Recombination::Intermediate, Recombination::Discrete] {
400 let config = Config {
401 survival,
402 step_sizes,
403 recombination,
404 ..Config::default()
405 };
406 let mut es = Es::new(config, Bounds::uniform(4, -5.0, 5.0));
407 let mut objective = |x: &Vec<f64>| sphere(x);
408 let outcome = es.run(
409 &mut objective,
410 &mut Limits::evaluations(30_000),
411 &mut (),
412 &mut SplitMix64::new(3),
413 );
414 assert!(
415 outcome.best_cost() < 1e-6,
416 "{config:?}: {}",
417 outcome.best_cost()
418 );
419 }
420 }
421 }
422 }
423
424 #[test]
426 fn per_coordinate_on_ellipsoid() {
427 let mut es = Es::new(Config::default(), Bounds::uniform(5, -3.0, 3.0));
428 let mut objective = |x: &Vec<f64>| ellipsoid(x);
429 let outcome = es.run(
430 &mut objective,
431 &mut Limits::evaluations(100_000),
432 &mut (),
433 &mut SplitMix64::new(1),
434 );
435
436 assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
437 }
438
439 #[test]
441 fn one_plus_one() {
442 let mut es = OnePlusOne {
443 sigma: 1.0,
444 min_sigma: 1e-300,
445 };
446 let mut objective = |x: &Vec<f64>| sphere(x);
447 let outcome = es.run(
448 alloc::vec![3.0; 10],
449 &mut objective,
450 &mut Limits::evaluations(5_000),
451 &mut (),
452 &mut SplitMix64::new(2),
453 );
454 assert!(outcome.best_cost() < 1e-10, "{}", outcome.best_cost());
455
456 let mut objective = |x: &Vec<f64>| rosenbrock(x);
457 let outcome = es.run(
458 alloc::vec![0.0; 2],
459 &mut objective,
460 &mut Limits::evaluations(20_000),
461 &mut (),
462 &mut SplitMix64::new(2),
463 );
464 assert!(outcome.best_cost() < 1e-6, "{}", outcome.best_cost());
465 }
466
467 #[test]
469 fn deterministic() {
470 let run = || {
471 let mut es = Es::new(Config::default(), Bounds::uniform(3, -1.0, 1.0));
472 let mut objective = |x: &Vec<f64>| sphere(x);
473 es.run(
474 &mut objective,
475 &mut Limits::evaluations(777),
476 &mut (),
477 &mut SplitMix64::new(9),
478 )
479 };
480
481 assert_eq!(run(), run());
482 assert_eq!(run().stats.evaluations, 777);
483 }
484}