1mod eigen;
35mod params;
36mod termination;
37
38use alloc::vec::Vec;
39
40use rand_core::Rng;
41
42pub use params::Parameters;
43use termination::History;
44pub use termination::Termination;
45
46use crate::evaluator::Evaluator;
47use crate::operators::real::Bounds;
48use crate::rng::{standard_normal, uniform};
49use crate::{
50 Budget, Event, Individual, Objective, Observer, Outcome, Stats, Stop, ranking, sanitize,
51};
52
53type Population = Vec<Individual<Vec<f64>>>;
55
56#[derive(Debug, Clone, PartialEq)]
58pub struct Config {
59 pub lambda: Option<usize>,
62 pub tol_fun: f64,
65 pub tol_x: Option<f64>,
68 pub tol_x_up: f64,
70 pub max_condition: f64,
72 pub bounds: Option<Bounds>,
76 pub penalty: f64,
79}
80
81impl Default for Config {
82 fn default() -> Self {
83 Self {
84 lambda: None,
85 tol_fun: 1e-12,
86 tol_x: None,
87 tol_x_up: 1e4,
88 max_condition: 1e14,
89 bounds: None,
90 penalty: 1.0,
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq)]
97pub struct CmaEs {
98 config: Config,
100 params: Parameters,
102 mean: Vec<f64>,
104 sigma: f64,
106 covariance: Vec<f64>,
108 basis: Vec<f64>,
111 scales: Vec<f64>,
113 path_sigma: Vec<f64>,
115 path_c: Vec<f64>,
117 generation: u64,
119 decomposed_at: u64,
121 initial_scale: f64,
123 tol_x: f64,
125 degenerate: bool,
127 z: Vec<Vec<f64>>,
129 y: Vec<Vec<f64>>,
131 x: Vec<Vec<f64>>,
133 asked: bool,
135 history: History,
137}
138
139impl CmaEs {
140 #[must_use]
150 pub fn new(mean: Vec<f64>, sigma: f64, config: Config) -> Self {
151 let n = mean.len();
152
153 Self::with_covariance(mean, sigma, eigen::identity(n), config)
154 }
155
156 #[must_use]
164 pub fn with_covariance(
165 mean: Vec<f64>,
166 sigma: f64,
167 covariance: Vec<f64>,
168 config: Config,
169 ) -> Self {
170 let n = mean.len();
171 assert!(n > 0, "CMA-ES needs at least one dimension");
172 assert!(
173 sigma > 0.0 && sigma.is_finite(),
174 "the step size must be positive and finite"
175 );
176 assert_eq!(covariance.len(), n * n, "the covariance must be n × n");
177
178 let lambda = config
179 .lambda
180 .unwrap_or_else(|| Parameters::default_lambda(n));
181 let params = Parameters::new(n, lambda);
182 let tol_x = config.tol_x.unwrap_or(1e-12 * sigma);
183 let mut cma = Self {
184 config,
185 params,
186 mean,
187 sigma,
188 covariance,
189 basis: Vec::new(),
190 scales: Vec::new(),
191 path_sigma: alloc::vec![0.0; n],
192 path_c: alloc::vec![0.0; n],
193 generation: 0,
194 decomposed_at: 0,
195 initial_scale: 0.0,
196 tol_x,
197 degenerate: false,
198 z: Vec::new(),
199 y: Vec::new(),
200 x: Vec::new(),
201 asked: false,
202 history: History::default(),
203 };
204 cma.decompose();
205 cma.initial_scale = cma.sigma * cma.max_scale();
206
207 cma
208 }
209
210 #[must_use]
212 pub fn parameters(&self) -> &Parameters {
213 &self.params
214 }
215
216 #[must_use]
218 pub fn mean(&self) -> &[f64] {
219 &self.mean
220 }
221
222 #[must_use]
224 pub fn sigma(&self) -> f64 {
225 self.sigma
226 }
227
228 #[must_use]
230 pub fn covariance(&self) -> &[f64] {
231 &self.covariance
232 }
233
234 #[must_use]
236 pub fn generation(&self) -> u64 {
237 self.generation
238 }
239
240 #[must_use]
242 pub fn condition(&self) -> f64 {
243 if self.degenerate {
244 return f64::INFINITY;
245 }
246
247 let max = self.max_scale();
248 let min = self.scales.iter().copied().fold(f64::INFINITY, f64::min);
249
250 (max / min) * (max / min)
251 }
252
253 pub fn set_mean(&mut self, mean: Vec<f64>) {
260 assert_eq!(
261 mean.len(),
262 self.mean.len(),
263 "the mean must keep its dimension"
264 );
265 self.mean = mean;
266 self.asked = false;
267 }
268
269 pub fn ask<R: Rng + ?Sized>(&mut self, rng: &mut R) -> &[Vec<f64>] {
271 let n = self.params.n;
272 let lambda = self.params.lambda;
273 self.z.resize_with(lambda, || alloc::vec![0.0; n]);
274 self.y.resize_with(lambda, || alloc::vec![0.0; n]);
275 self.x.resize_with(lambda, || alloc::vec![0.0; n]);
276 for k in 0..lambda {
277 for zi in &mut self.z[k] {
278 *zi = standard_normal(rng);
279 }
280
281 for i in 0..n {
282 let mut yi = 0.0;
283 for j in 0..n {
284 yi += self.basis[i * n + j] * self.scales[j] * self.z[k][j];
285 }
286 self.y[k][i] = yi;
287 self.x[k][i] = self.mean[i] + self.sigma * yi;
288 }
289 }
290
291 self.asked = true;
292 &self.x
293 }
294
295 pub fn tell(&mut self, costs: &[f64]) -> Option<Termination> {
304 assert!(self.asked, "tell without ask");
305 assert_eq!(costs.len(), self.params.lambda, "one cost per candidate");
306 self.asked = false;
307
308 let costs: Vec<f64> = costs.iter().map(|&c| sanitize(c)).collect();
309 let order = ranking(&costs);
310 self.update(&order);
311 self.generation += 1;
312 if self.generation - self.decomposed_at >= self.params.eigen_interval() {
313 self.decompose();
314 }
315
316 let sorted: Vec<f64> = order.iter().map(|&k| costs[k]).collect();
317 self.history.push(&sorted);
318
319 self.termination(&sorted)
320 }
321
322 fn update(&mut self, order: &[usize]) {
324 let p = &self.params;
325 let n = p.n;
326 let mut y_w = alloc::vec![0.0; n];
327 let mut z_w = alloc::vec![0.0; n];
328 for (i, &k) in order.iter().take(p.mu).enumerate() {
329 for j in 0..n {
330 y_w[j] += p.weights[i] * self.y[k][j];
331 z_w[j] += p.weights[i] * self.z[k][j];
332 }
333 }
334
335 for j in 0..n {
336 self.mean[j] += p.c_m * self.sigma * y_w[j];
337 }
338
339 let norm_ps = self.update_path_sigma(&z_w);
340 let h_sigma = self.h_sigma(norm_ps);
341 let p = &self.params;
342 let factor = h_sigma * libm::sqrt(p.c_c * (2.0 - p.c_c) * p.mu_eff);
343 for j in 0..n {
344 self.path_c[j] = (1.0 - p.c_c) * self.path_c[j] + factor * y_w[j];
345 }
346
347 self.update_covariance(order, h_sigma);
348 let p = &self.params;
349 self.sigma *= libm::exp(p.c_sigma / p.d_sigma * (norm_ps / p.chi_n - 1.0));
350 }
351
352 fn update_path_sigma(&mut self, z_w: &[f64]) -> f64 {
354 let p = &self.params;
355 let n = p.n;
356 let factor = libm::sqrt(p.c_sigma * (2.0 - p.c_sigma) * p.mu_eff);
357 let mut norm = 0.0;
358 for i in 0..n {
359 let bz: f64 = (0..n).map(|j| self.basis[i * n + j] * z_w[j]).sum();
360 self.path_sigma[i] = (1.0 - p.c_sigma) * self.path_sigma[i] + factor * bz;
361 norm += self.path_sigma[i] * self.path_sigma[i];
362 }
363
364 libm::sqrt(norm)
365 }
366
367 fn h_sigma(&self, norm_ps: f64) -> f64 {
371 let p = &self.params;
372 #[expect(
373 clippy::cast_precision_loss,
374 reason = "generation counts are far below 2^52"
375 )]
376 let g1 = (self.generation + 1) as f64;
377 let correction = libm::sqrt(1.0 - libm::pow(1.0 - p.c_sigma, 2.0 * g1));
378 #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
379 let threshold = (1.4 + 2.0 / (p.n as f64 + 1.0)) * p.chi_n;
380
381 if norm_ps / correction < threshold {
382 1.0
383 } else {
384 0.0
385 }
386 }
387
388 fn update_covariance(&mut self, order: &[usize], h_sigma: f64) {
390 let p = &self.params;
391 let n = p.n;
392 #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
393 let nf = n as f64;
394 let delta = (1.0 - h_sigma) * p.c_c * (2.0 - p.c_c);
395 let decay = 1.0 + p.c_1 * delta - p.c_1 - p.c_mu * p.weight_sum();
396 let rank_weights: Vec<f64> = order
397 .iter()
398 .enumerate()
399 .map(|(i, &k)| {
400 let w = p.weights[i];
401 if w >= 0.0 {
402 w
403 } else {
404 let z2: f64 = self.z[k].iter().map(|v| v * v).sum();
406 w * nf / z2
407 }
408 })
409 .collect();
410
411 for i in 0..n {
412 for j in i..n {
413 let mut rank_mu = 0.0;
414 for (rank, &k) in order.iter().enumerate() {
415 rank_mu += rank_weights[rank] * self.y[k][i] * self.y[k][j];
416 }
417
418 let value = decay * self.covariance[i * n + j]
419 + p.c_1 * self.path_c[i] * self.path_c[j]
420 + p.c_mu * rank_mu;
421 self.covariance[i * n + j] = value;
422 self.covariance[j * n + i] = value;
423 }
424 }
425 }
426
427 fn decompose(&mut self) {
429 let n = self.params.n;
430 let eigen = if self.basis.len() == n * n {
431 eigen::decompose_in_basis(&self.covariance, n, &self.basis)
432 } else {
433 eigen::decompose(&self.covariance, n)
434 };
435 self.degenerate = eigen.values.iter().any(|&v| !(v > 0.0 && v.is_finite()));
436 self.scales = eigen
437 .values
438 .iter()
439 .map(|&v| libm::sqrt(v.max(f64::MIN_POSITIVE)))
440 .collect();
441 self.basis = eigen.vectors;
442 self.decomposed_at = self.generation;
443 }
444
445 fn max_scale(&self) -> f64 {
447 self.scales.iter().copied().fold(0.0, f64::max)
448 }
449
450 fn termination(&self, sorted_costs: &[f64]) -> Option<Termination> {
452 let n = self.params.n;
453 let window = self.fun_window();
454 let checks = [
455 (Termination::NoEffectAxis, self.no_effect_axis()),
456 (Termination::NoEffectCoord, self.no_effect_coord()),
457 (
458 Termination::ConditionCov,
459 self.condition() > self.config.max_condition,
460 ),
461 (
462 Termination::EqualFunValues,
463 self.history.recent_best_range(window) == Some(0.0),
464 ),
465 (
466 Termination::Stagnation,
467 self.history.stagnated(120 + window - 10, self.generation),
468 ),
469 (
470 Termination::TolXUp,
471 self.sigma * self.max_scale() > self.config.tol_x_up * self.initial_scale,
472 ),
473 (Termination::TolFun, self.tol_fun(sorted_costs, window)),
474 (Termination::TolX, self.tol_x_reached(n)),
475 ];
476
477 checks
478 .into_iter()
479 .find_map(|(criterion, fired)| fired.then_some(criterion))
480 }
481
482 fn fun_window(&self) -> usize {
484 10 + (30 * self.params.n).div_ceil(self.params.lambda)
485 }
486
487 #[expect(
489 clippy::float_cmp,
490 reason = "the criterion is exact floating-point equality"
491 )]
492 fn no_effect_axis(&self) -> bool {
493 let n = self.params.n;
494 #[expect(
495 clippy::cast_possible_truncation,
496 reason = "the remainder is below n, a usize"
497 )]
498 let axis = (self.generation % n as u64) as usize;
499 let step = 0.1 * self.sigma * self.scales[axis];
500
501 (0..n).all(|k| self.mean[k] + step * self.basis[k * n + axis] == self.mean[k])
502 }
503
504 #[expect(
506 clippy::float_cmp,
507 reason = "the criterion is exact floating-point equality"
508 )]
509 fn no_effect_coord(&self) -> bool {
510 let n = self.params.n;
511
512 (0..n).any(|i| {
513 let step = 0.2 * self.sigma * libm::sqrt(self.covariance[i * n + i]);
514 self.mean[i] + step == self.mean[i]
515 })
516 }
517
518 fn tol_fun(&self, sorted_costs: &[f64], window: usize) -> bool {
520 let Some((low, high)) = self.history.recent_best_bounds(window) else {
521 return false;
522 };
523
524 let low = low.min(sorted_costs[0]);
525 let high = high.max(sorted_costs[sorted_costs.len() - 1]);
526
527 high - low < self.config.tol_fun
528 }
529
530 fn tol_x_reached(&self, n: usize) -> bool {
532 (0..n).all(|i| {
533 self.sigma * libm::sqrt(self.covariance[i * n + i]) < self.tol_x
534 && (self.sigma * self.path_c[i]).abs() < self.tol_x
535 })
536 }
537
538 pub fn minimize<O, B, Obs, R>(
544 &mut self,
545 objective: &mut O,
546 budget: &mut B,
547 observer: &mut Obs,
548 rng: &mut R,
549 ) -> Outcome<Vec<f64>>
550 where
551 O: Objective<Vec<f64>> + ?Sized,
552 B: Budget<Stats> + ?Sized,
553 Obs: Observer + ?Sized,
554 R: Rng + ?Sized,
555 {
556 let mut evaluator = Evaluator::new(objective, budget, observer);
557 let (stop, population) = self.run(&mut evaluator, rng);
558
559 evaluator.outcome(population, stop)
560 }
561
562 fn run<O, B, Obs, R>(
564 &mut self,
565 evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
566 rng: &mut R,
567 ) -> (Stop, Population)
568 where
569 O: Objective<Vec<f64>> + ?Sized,
570 B: Budget<Stats> + ?Sized,
571 Obs: Observer + ?Sized,
572 R: Rng + ?Sized,
573 {
574 let mut last = Vec::new();
575 loop {
576 let Some((ranks, population)) = self.evaluate_generation(evaluator, rng) else {
577 return (Stop::Budget, last);
578 };
579
580 let termination = self.tell(&ranks);
581 evaluator.end_generation(crate::ga::population_best(&population));
582 last = population;
583 if let Some(criterion) = termination {
584 return (Stop::CmaEs(criterion), last);
585 }
586 }
587 }
588
589 fn evaluate_generation<O, B, Obs, R>(
592 &mut self,
593 evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
594 rng: &mut R,
595 ) -> Option<(Vec<f64>, Population)>
596 where
597 O: Objective<Vec<f64>> + ?Sized,
598 B: Budget<Stats> + ?Sized,
599 Obs: Observer + ?Sized,
600 R: Rng + ?Sized,
601 {
602 let candidates = self.ask(rng).to_vec();
603 let mut ranks = Vec::with_capacity(candidates.len());
604 let mut population = Vec::with_capacity(candidates.len());
605 for x in candidates {
606 let (repaired, penalty) = match &self.config.bounds {
607 Some(bounds) => {
608 let mut repaired = x.clone();
609 bounds.clamp(&mut repaired);
610 let distance: f64 = x
611 .iter()
612 .zip(&repaired)
613 .map(|(a, b)| (a - b) * (a - b))
614 .sum();
615 (repaired, self.config.penalty * distance)
616 }
617 None => (x, 0.0),
618 };
619
620 let cost = evaluator.evaluate(&repaired)?;
621 ranks.push(cost + penalty);
622 population.push(Individual {
623 genome: repaired,
624 cost,
625 });
626 }
627
628 Some((ranks, population))
629 }
630}
631
632#[derive(Debug, Clone, PartialEq)]
648pub struct Ipop {
649 pub config: Config,
651 pub bounds: Bounds,
653 pub sigma_fraction: f64,
655 pub factor: f64,
657 pub max_restarts: u64,
659}
660
661impl Ipop {
662 #[must_use]
664 pub fn new(config: Config, bounds: Bounds) -> Self {
665 Self {
666 config,
667 bounds,
668 sigma_fraction: 0.3,
669 factor: 2.0,
670 max_restarts: 9,
671 }
672 }
673
674 pub fn run<O, B, Obs, R>(
680 &mut self,
681 objective: &mut O,
682 budget: &mut B,
683 observer: &mut Obs,
684 rng: &mut R,
685 ) -> Outcome<Vec<f64>>
686 where
687 O: Objective<Vec<f64>> + ?Sized,
688 B: Budget<Stats> + ?Sized,
689 Obs: Observer + ?Sized,
690 R: Rng + ?Sized,
691 {
692 let n = self.bounds.dimension();
693 #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
694 let width = (0..n).map(|i| self.bounds.width(i)).sum::<f64>() / n as f64;
695 let sigma = self.sigma_fraction * width;
696 let mut lambda = self
697 .config
698 .lambda
699 .unwrap_or_else(|| Parameters::default_lambda(n));
700 let mut evaluator = Evaluator::new(objective, budget, observer);
701 let mut restart = 0;
702 loop {
703 let mean = (0..n)
704 .map(|i| uniform(rng, self.bounds.lower()[i], self.bounds.upper()[i]))
705 .collect();
706 let config = Config {
707 lambda: Some(lambda),
708 ..self.config.clone()
709 };
710 let mut cma = CmaEs::new(mean, sigma, config);
711 let (stop, population) = cma.run(&mut evaluator, rng);
712 if stop == Stop::Budget || restart >= self.max_restarts {
713 return evaluator.outcome(population, stop);
714 }
715
716 restart += 1;
717 #[expect(
718 clippy::cast_possible_truncation,
719 clippy::cast_sign_loss,
720 clippy::cast_precision_loss,
721 reason = "population sizes are small positive integers"
722 )]
723 {
724 lambda = libm::round(lambda as f64 * self.factor) as usize;
725 }
726 evaluator.emit(Event::Restart {
727 restart,
728 population: lambda,
729 });
730 }
731 }
732}
733
734#[cfg(test)]
735mod tests;