mod eigen;
mod params;
mod termination;
use alloc::vec::Vec;
use rand_core::Rng;
pub use params::Parameters;
use termination::History;
pub use termination::Termination;
use crate::evaluator::Evaluator;
use crate::operators::real::Bounds;
use crate::rng::{standard_normal, uniform};
use crate::{
Budget, Event, Individual, Objective, Observer, Outcome, Stats, Stop, ranking, sanitize,
};
type Population = Vec<Individual<Vec<f64>>>;
#[derive(Debug, Clone, PartialEq)]
pub struct Config {
pub lambda: Option<usize>,
pub tol_fun: f64,
pub tol_x: Option<f64>,
pub tol_x_up: f64,
pub max_condition: f64,
pub bounds: Option<Bounds>,
pub penalty: f64,
}
impl Default for Config {
fn default() -> Self {
Self {
lambda: None,
tol_fun: 1e-12,
tol_x: None,
tol_x_up: 1e4,
max_condition: 1e14,
bounds: None,
penalty: 1.0,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct CmaEs {
config: Config,
params: Parameters,
mean: Vec<f64>,
sigma: f64,
covariance: Vec<f64>,
basis: Vec<f64>,
scales: Vec<f64>,
path_sigma: Vec<f64>,
path_c: Vec<f64>,
generation: u64,
decomposed_at: u64,
initial_scale: f64,
tol_x: f64,
degenerate: bool,
z: Vec<Vec<f64>>,
y: Vec<Vec<f64>>,
x: Vec<Vec<f64>>,
asked: bool,
history: History,
}
impl CmaEs {
#[must_use]
pub fn new(mean: Vec<f64>, sigma: f64, config: Config) -> Self {
let n = mean.len();
Self::with_covariance(mean, sigma, eigen::identity(n), config)
}
#[must_use]
pub fn with_covariance(
mean: Vec<f64>,
sigma: f64,
covariance: Vec<f64>,
config: Config,
) -> Self {
let n = mean.len();
assert!(n > 0, "CMA-ES needs at least one dimension");
assert!(
sigma > 0.0 && sigma.is_finite(),
"the step size must be positive and finite"
);
assert_eq!(covariance.len(), n * n, "the covariance must be n × n");
let lambda = config
.lambda
.unwrap_or_else(|| Parameters::default_lambda(n));
let params = Parameters::new(n, lambda);
let tol_x = config.tol_x.unwrap_or(1e-12 * sigma);
let mut cma = Self {
config,
params,
mean,
sigma,
covariance,
basis: Vec::new(),
scales: Vec::new(),
path_sigma: alloc::vec![0.0; n],
path_c: alloc::vec![0.0; n],
generation: 0,
decomposed_at: 0,
initial_scale: 0.0,
tol_x,
degenerate: false,
z: Vec::new(),
y: Vec::new(),
x: Vec::new(),
asked: false,
history: History::default(),
};
cma.decompose();
cma.initial_scale = cma.sigma * cma.max_scale();
cma
}
#[must_use]
pub fn parameters(&self) -> &Parameters {
&self.params
}
#[must_use]
pub fn mean(&self) -> &[f64] {
&self.mean
}
#[must_use]
pub fn sigma(&self) -> f64 {
self.sigma
}
#[must_use]
pub fn covariance(&self) -> &[f64] {
&self.covariance
}
#[must_use]
pub fn generation(&self) -> u64 {
self.generation
}
#[must_use]
pub fn condition(&self) -> f64 {
if self.degenerate {
return f64::INFINITY;
}
let max = self.max_scale();
let min = self.scales.iter().copied().fold(f64::INFINITY, f64::min);
(max / min) * (max / min)
}
pub fn set_mean(&mut self, mean: Vec<f64>) {
assert_eq!(
mean.len(),
self.mean.len(),
"the mean must keep its dimension"
);
self.mean = mean;
self.asked = false;
}
pub fn ask<R: Rng + ?Sized>(&mut self, rng: &mut R) -> &[Vec<f64>] {
let n = self.params.n;
let lambda = self.params.lambda;
self.z.resize_with(lambda, || alloc::vec![0.0; n]);
self.y.resize_with(lambda, || alloc::vec![0.0; n]);
self.x.resize_with(lambda, || alloc::vec![0.0; n]);
for k in 0..lambda {
for zi in &mut self.z[k] {
*zi = standard_normal(rng);
}
for i in 0..n {
let mut yi = 0.0;
for j in 0..n {
yi += self.basis[i * n + j] * self.scales[j] * self.z[k][j];
}
self.y[k][i] = yi;
self.x[k][i] = self.mean[i] + self.sigma * yi;
}
}
self.asked = true;
&self.x
}
pub fn tell(&mut self, costs: &[f64]) -> Option<Termination> {
assert!(self.asked, "tell without ask");
assert_eq!(costs.len(), self.params.lambda, "one cost per candidate");
self.asked = false;
let costs: Vec<f64> = costs.iter().map(|&c| sanitize(c)).collect();
let order = ranking(&costs);
self.update(&order);
self.generation += 1;
if self.generation - self.decomposed_at >= self.params.eigen_interval() {
self.decompose();
}
let sorted: Vec<f64> = order.iter().map(|&k| costs[k]).collect();
self.history.push(&sorted);
self.termination(&sorted)
}
fn update(&mut self, order: &[usize]) {
let p = &self.params;
let n = p.n;
let mut y_w = alloc::vec![0.0; n];
let mut z_w = alloc::vec![0.0; n];
for (i, &k) in order.iter().take(p.mu).enumerate() {
for j in 0..n {
y_w[j] += p.weights[i] * self.y[k][j];
z_w[j] += p.weights[i] * self.z[k][j];
}
}
for j in 0..n {
self.mean[j] += p.c_m * self.sigma * y_w[j];
}
let norm_ps = self.update_path_sigma(&z_w);
let h_sigma = self.h_sigma(norm_ps);
let p = &self.params;
let factor = h_sigma * libm::sqrt(p.c_c * (2.0 - p.c_c) * p.mu_eff);
for j in 0..n {
self.path_c[j] = (1.0 - p.c_c) * self.path_c[j] + factor * y_w[j];
}
self.update_covariance(order, h_sigma);
let p = &self.params;
self.sigma *= libm::exp(p.c_sigma / p.d_sigma * (norm_ps / p.chi_n - 1.0));
}
fn update_path_sigma(&mut self, z_w: &[f64]) -> f64 {
let p = &self.params;
let n = p.n;
let factor = libm::sqrt(p.c_sigma * (2.0 - p.c_sigma) * p.mu_eff);
let mut norm = 0.0;
for i in 0..n {
let bz: f64 = (0..n).map(|j| self.basis[i * n + j] * z_w[j]).sum();
self.path_sigma[i] = (1.0 - p.c_sigma) * self.path_sigma[i] + factor * bz;
norm += self.path_sigma[i] * self.path_sigma[i];
}
libm::sqrt(norm)
}
fn h_sigma(&self, norm_ps: f64) -> f64 {
let p = &self.params;
#[expect(
clippy::cast_precision_loss,
reason = "generation counts are far below 2^52"
)]
let g1 = (self.generation + 1) as f64;
let correction = libm::sqrt(1.0 - libm::pow(1.0 - p.c_sigma, 2.0 * g1));
#[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
let threshold = (1.4 + 2.0 / (p.n as f64 + 1.0)) * p.chi_n;
if norm_ps / correction < threshold {
1.0
} else {
0.0
}
}
fn update_covariance(&mut self, order: &[usize], h_sigma: f64) {
let p = &self.params;
let n = p.n;
#[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
let nf = n as f64;
let delta = (1.0 - h_sigma) * p.c_c * (2.0 - p.c_c);
let decay = 1.0 + p.c_1 * delta - p.c_1 - p.c_mu * p.weight_sum();
let rank_weights: Vec<f64> = order
.iter()
.enumerate()
.map(|(i, &k)| {
let w = p.weights[i];
if w >= 0.0 {
w
} else {
let z2: f64 = self.z[k].iter().map(|v| v * v).sum();
w * nf / z2
}
})
.collect();
for i in 0..n {
for j in i..n {
let mut rank_mu = 0.0;
for (rank, &k) in order.iter().enumerate() {
rank_mu += rank_weights[rank] * self.y[k][i] * self.y[k][j];
}
let value = decay * self.covariance[i * n + j]
+ p.c_1 * self.path_c[i] * self.path_c[j]
+ p.c_mu * rank_mu;
self.covariance[i * n + j] = value;
self.covariance[j * n + i] = value;
}
}
}
fn decompose(&mut self) {
let n = self.params.n;
let eigen = if self.basis.len() == n * n {
eigen::decompose_in_basis(&self.covariance, n, &self.basis)
} else {
eigen::decompose(&self.covariance, n)
};
self.degenerate = eigen.values.iter().any(|&v| !(v > 0.0 && v.is_finite()));
self.scales = eigen
.values
.iter()
.map(|&v| libm::sqrt(v.max(f64::MIN_POSITIVE)))
.collect();
self.basis = eigen.vectors;
self.decomposed_at = self.generation;
}
fn max_scale(&self) -> f64 {
self.scales.iter().copied().fold(0.0, f64::max)
}
fn termination(&self, sorted_costs: &[f64]) -> Option<Termination> {
let n = self.params.n;
let window = self.fun_window();
let checks = [
(Termination::NoEffectAxis, self.no_effect_axis()),
(Termination::NoEffectCoord, self.no_effect_coord()),
(
Termination::ConditionCov,
self.condition() > self.config.max_condition,
),
(
Termination::EqualFunValues,
self.history.recent_best_range(window) == Some(0.0),
),
(
Termination::Stagnation,
self.history.stagnated(120 + window - 10, self.generation),
),
(
Termination::TolXUp,
self.sigma * self.max_scale() > self.config.tol_x_up * self.initial_scale,
),
(Termination::TolFun, self.tol_fun(sorted_costs, window)),
(Termination::TolX, self.tol_x_reached(n)),
];
checks
.into_iter()
.find_map(|(criterion, fired)| fired.then_some(criterion))
}
fn fun_window(&self) -> usize {
10 + (30 * self.params.n).div_ceil(self.params.lambda)
}
#[expect(
clippy::float_cmp,
reason = "the criterion is exact floating-point equality"
)]
fn no_effect_axis(&self) -> bool {
let n = self.params.n;
#[expect(
clippy::cast_possible_truncation,
reason = "the remainder is below n, a usize"
)]
let axis = (self.generation % n as u64) as usize;
let step = 0.1 * self.sigma * self.scales[axis];
(0..n).all(|k| self.mean[k] + step * self.basis[k * n + axis] == self.mean[k])
}
#[expect(
clippy::float_cmp,
reason = "the criterion is exact floating-point equality"
)]
fn no_effect_coord(&self) -> bool {
let n = self.params.n;
(0..n).any(|i| {
let step = 0.2 * self.sigma * libm::sqrt(self.covariance[i * n + i]);
self.mean[i] + step == self.mean[i]
})
}
fn tol_fun(&self, sorted_costs: &[f64], window: usize) -> bool {
let Some((low, high)) = self.history.recent_best_bounds(window) else {
return false;
};
let low = low.min(sorted_costs[0]);
let high = high.max(sorted_costs[sorted_costs.len() - 1]);
high - low < self.config.tol_fun
}
fn tol_x_reached(&self, n: usize) -> bool {
(0..n).all(|i| {
self.sigma * libm::sqrt(self.covariance[i * n + i]) < self.tol_x
&& (self.sigma * self.path_c[i]).abs() < self.tol_x
})
}
pub fn minimize<O, B, Obs, R>(
&mut self,
objective: &mut O,
budget: &mut B,
observer: &mut Obs,
rng: &mut R,
) -> Outcome<Vec<f64>>
where
O: Objective<Vec<f64>> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let mut evaluator = Evaluator::new(objective, budget, observer);
let (stop, population) = self.run(&mut evaluator, rng);
evaluator.outcome(population, stop)
}
fn run<O, B, Obs, R>(
&mut self,
evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
rng: &mut R,
) -> (Stop, Population)
where
O: Objective<Vec<f64>> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let mut last = Vec::new();
loop {
let Some((ranks, population)) = self.evaluate_generation(evaluator, rng) else {
return (Stop::Budget, last);
};
let termination = self.tell(&ranks);
evaluator.end_generation(crate::ga::population_best(&population));
last = population;
if let Some(criterion) = termination {
return (Stop::CmaEs(criterion), last);
}
}
}
fn evaluate_generation<O, B, Obs, R>(
&mut self,
evaluator: &mut Evaluator<'_, Vec<f64>, O, B, Obs>,
rng: &mut R,
) -> Option<(Vec<f64>, Population)>
where
O: Objective<Vec<f64>> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let candidates = self.ask(rng).to_vec();
let mut ranks = Vec::with_capacity(candidates.len());
let mut population = Vec::with_capacity(candidates.len());
for x in candidates {
let (repaired, penalty) = match &self.config.bounds {
Some(bounds) => {
let mut repaired = x.clone();
bounds.clamp(&mut repaired);
let distance: f64 = x
.iter()
.zip(&repaired)
.map(|(a, b)| (a - b) * (a - b))
.sum();
(repaired, self.config.penalty * distance)
}
None => (x, 0.0),
};
let cost = evaluator.evaluate(&repaired)?;
ranks.push(cost + penalty);
population.push(Individual {
genome: repaired,
cost,
});
}
Some((ranks, population))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Ipop {
pub config: Config,
pub bounds: Bounds,
pub sigma_fraction: f64,
pub factor: f64,
pub max_restarts: u64,
}
impl Ipop {
#[must_use]
pub fn new(config: Config, bounds: Bounds) -> Self {
Self {
config,
bounds,
sigma_fraction: 0.3,
factor: 2.0,
max_restarts: 9,
}
}
pub fn run<O, B, Obs, R>(
&mut self,
objective: &mut O,
budget: &mut B,
observer: &mut Obs,
rng: &mut R,
) -> Outcome<Vec<f64>>
where
O: Objective<Vec<f64>> + ?Sized,
B: Budget<Stats> + ?Sized,
Obs: Observer + ?Sized,
R: Rng + ?Sized,
{
let n = self.bounds.dimension();
#[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
let width = (0..n).map(|i| self.bounds.width(i)).sum::<f64>() / n as f64;
let sigma = self.sigma_fraction * width;
let mut lambda = self
.config
.lambda
.unwrap_or_else(|| Parameters::default_lambda(n));
let mut evaluator = Evaluator::new(objective, budget, observer);
let mut restart = 0;
loop {
let mean = (0..n)
.map(|i| uniform(rng, self.bounds.lower()[i], self.bounds.upper()[i]))
.collect();
let config = Config {
lambda: Some(lambda),
..self.config.clone()
};
let mut cma = CmaEs::new(mean, sigma, config);
let (stop, population) = cma.run(&mut evaluator, rng);
if stop == Stop::Budget || restart >= self.max_restarts {
return evaluator.outcome(population, stop);
}
restart += 1;
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_precision_loss,
reason = "population sizes are small positive integers"
)]
{
lambda = libm::round(lambda as f64 * self.factor) as usize;
}
evaluator.emit(Event::Restart {
restart,
population: lambda,
});
}
}
}
#[cfg(test)]
mod tests;