Skip to main content

evolutionary_planning/cmaes/
params.rs

1//! The strategy parameters of CMA-ES: Table 1 of Hansen's tutorial (the 2016 defaults with
2//! negative recombination weights).
3
4use alloc::vec::Vec;
5
6/// The derived strategy parameters for dimension `n` and population size `λ`, computed
7/// exactly as in Table 1 of Hansen (2016), equations (48)–(58).
8#[derive(Debug, Clone, PartialEq)]
9pub struct Parameters {
10    /// The dimension `n`.
11    pub n: usize,
12    /// The population size `λ` (48): `4 + ⌊3 ln n⌋` by default.
13    pub lambda: usize,
14    /// The number of positive weights `μ = ⌊λ/2⌋`.
15    pub mu: usize,
16    /// The recombination weights `w_1 ≥ … ≥ w_λ` (53): the first `μ` are positive and sum to
17    /// one, the rest are non-positive ("active" CMA).
18    pub weights: Vec<f64>,
19    /// The variance effective selection mass `μ_eff = (Σ w_i)² / Σ w_i²` over the positive
20    /// weights.
21    pub mu_eff: f64,
22    /// The variance effective selection mass of the negative weights, `μ_eff^-`.
23    pub mu_eff_negative: f64,
24    /// The learning rate of the mean, `c_m = 1` (54).
25    pub c_m: f64,
26    /// The cumulation constant of the step-size path, `c_σ` (55).
27    pub c_sigma: f64,
28    /// The step-size damping `d_σ` (55).
29    pub d_sigma: f64,
30    /// The cumulation constant of the rank-one path, `c_c` (56).
31    pub c_c: f64,
32    /// The rank-one learning rate `c_1` (57).
33    pub c_1: f64,
34    /// The rank-μ learning rate `c_μ` (58).
35    pub c_mu: f64,
36    /// `E‖N(0, I)‖ ≈ √n (1 - 1/(4n) + 1/(21n²))`.
37    pub chi_n: f64,
38}
39
40impl Parameters {
41    /// The default population size `4 + ⌊3 ln n⌋` (48).
42    #[must_use]
43    pub fn default_lambda(n: usize) -> usize {
44        #[expect(clippy::cast_precision_loss, reason = "dimensions are far below 2^52")]
45        let log = libm::log(n.max(1) as f64);
46
47        #[expect(
48            clippy::cast_possible_truncation,
49            clippy::cast_sign_loss,
50            reason = "a small non-negative count"
51        )]
52        let extra = libm::floor(3.0 * log) as usize;
53
54        4 + extra
55    }
56
57    /// Computes every parameter for dimension `n` and population size `lambda`.
58    ///
59    /// # Panics
60    ///
61    /// Panics if `n == 0` or `lambda < 2`.
62    #[must_use]
63    pub fn new(n: usize, lambda: usize) -> Self {
64        assert!(n > 0, "CMA-ES needs at least one dimension");
65        assert!(lambda >= 2, "CMA-ES needs a population of at least two");
66
67        let nf = to_f64(n);
68        let mu = lambda / 2;
69        let raw = raw_weights(lambda);
70        let mu_eff = selection_mass(&raw[..mu]);
71        let mu_eff_negative = selection_mass(&raw[mu..]);
72
73        let c_sigma = (mu_eff + 2.0) / (nf + mu_eff + 5.0);
74        let d_sigma =
75            1.0 + 2.0 * (libm::sqrt((mu_eff - 1.0) / (nf + 1.0)) - 1.0).max(0.0) + c_sigma;
76        let c_c = (4.0 + mu_eff / nf) / (nf + 4.0 + 2.0 * mu_eff / nf);
77        let alpha_cov = 2.0;
78        let c_1 = alpha_cov / ((nf + 1.3) * (nf + 1.3) + mu_eff);
79        let c_mu = (1.0 - c_1).min(
80            alpha_cov * (0.25 + mu_eff + 1.0 / mu_eff - 2.0)
81                / ((nf + 2.0) * (nf + 2.0) + alpha_cov * mu_eff / 2.0),
82        );
83        let weights = final_weights(&raw, mu, n, c_1, c_mu, mu_eff, mu_eff_negative);
84        let chi_n = libm::sqrt(nf) * (1.0 - 1.0 / (4.0 * nf) + 1.0 / (21.0 * nf * nf));
85
86        Self {
87            n,
88            lambda,
89            mu,
90            weights,
91            mu_eff,
92            mu_eff_negative,
93            c_m: 1.0,
94            c_sigma,
95            d_sigma,
96            c_c,
97            c_1,
98            c_mu,
99            chi_n,
100        }
101    }
102
103    /// The sum of all weights `Σ w_j`, which enters the decay factor of (47).
104    #[must_use]
105    pub fn weight_sum(&self) -> f64 {
106        self.weights.iter().sum()
107    }
108
109    /// The number of generations between eigendecompositions,
110    /// `max(1, ⌊1 / (10 n (c_1 + c_μ))⌋)` (Appendix B.2).
111    #[must_use]
112    pub fn eigen_interval(&self) -> u64 {
113        let interval = libm::floor(1.0 / (10.0 * to_f64(self.n) * (self.c_1 + self.c_mu)));
114
115        #[expect(
116            clippy::cast_possible_truncation,
117            clippy::cast_sign_loss,
118            reason = "a small non-negative count"
119        )]
120        let interval = interval as u64;
121
122        interval.max(1)
123    }
124}
125
126/// Converts a count to `f64`.
127fn to_f64(n: usize) -> f64 {
128    #[expect(
129        clippy::cast_precision_loss,
130        reason = "dimensions and population sizes are far below 2^52"
131    )]
132    let n = n as f64;
133
134    n
135}
136
137/// The preliminary weights `w'_i = ln((λ+1)/2) - ln i` (49).
138fn raw_weights(lambda: usize) -> Vec<f64> {
139    let base = libm::log(f64::midpoint(to_f64(lambda), 1.0));
140
141    (1..=lambda).map(|i| base - libm::log(to_f64(i))).collect()
142}
143
144/// `(Σ w)² / Σ w²`, the variance effective selection mass of a group of weights; `0` for an
145/// empty or all-zero group.
146fn selection_mass(weights: &[f64]) -> f64 {
147    let sum: f64 = weights.iter().sum();
148    let squares: f64 = weights.iter().map(|w| w * w).sum();
149
150    if squares > 0.0 {
151        sum * sum / squares
152    } else {
153        0.0
154    }
155}
156
157/// The final weights (53): positive ones normalised to sum one, negative ones scaled to sum
158/// to `-min(α_μ^-, α_μeff^-, α_posdef^-)`.
159fn final_weights(
160    raw: &[f64],
161    mu: usize,
162    n: usize,
163    c_1: f64,
164    c_mu: f64,
165    mu_eff: f64,
166    mu_eff_negative: f64,
167) -> Vec<f64> {
168    let positive: f64 = raw.iter().filter(|&&w| w >= 0.0).sum();
169    let negative: f64 = raw.iter().filter(|&&w| w < 0.0).map(|w| -w).sum();
170    let alpha_mu = 1.0 + c_1 / c_mu;
171    let alpha_mu_eff = 1.0 + 2.0 * mu_eff_negative / (mu_eff + 2.0);
172    let alpha_pos_def = (1.0 - c_1 - c_mu) / (to_f64(n) * c_mu);
173    let scale = alpha_mu.min(alpha_mu_eff).min(alpha_pos_def);
174    debug_assert!(
175        raw[..mu].iter().all(|&w| w > 0.0),
176        "the first mu raw weights are positive"
177    );
178
179    raw.iter()
180        .map(|&w| {
181            if w >= 0.0 {
182                w / positive
183            } else {
184                scale * w / negative
185            }
186        })
187        .collect()
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    /// Figure 7 of the tutorial: default λ and the sum of all weights for n = 5, 10, 25, 100.
195    ///
196    /// The printed sums (-0.95, -0.63, -0.42, -0.28) differ from Table 1's formulas by up to
197    /// 0.04 for small n (Table 1 gives -0.988 and -0.649 for n = 5 and 10, exactly `-c_1 /
198    /// c_μ`); the figure was presumably drawn with a slightly different parameter version.
199    /// Table 1 is normative here, so the figure is checked to 0.05.
200    #[test]
201    fn matches_figure_7() {
202        for (n, lambda, sum) in [
203            (5, 8, -0.95),
204            (10, 10, -0.63),
205            (25, 13, -0.42),
206            (100, 17, -0.28),
207        ] {
208            let p = Parameters::new(n, Parameters::default_lambda(n));
209
210            assert_eq!(p.lambda, lambda, "n = {n}");
211            assert!(
212                (p.weight_sum() - sum).abs() < 0.05,
213                "n = {n}: {}",
214                p.weight_sum()
215            );
216            assert!((p.weight_sum() + p.c_1 / p.c_mu).abs() < 1e-12, "n = {n}");
217        }
218    }
219
220    /// Positive weights sum to one; `c_1 + c_μ Σ w_j >= 0` always (C never grows by decay),
221    /// with equality when `α_μ^-` is the binding bound, as for the default λ from n = 5 on.
222    #[test]
223    fn weight_normalisation() {
224        for n in [1, 2, 3, 5, 10, 40] {
225            for lambda in [Parameters::default_lambda(n), 50] {
226                let p = Parameters::new(n, lambda);
227                let positive: f64 = p.weights[..p.mu].iter().sum();
228                let decay = p.c_1 + p.c_mu * p.weight_sum();
229
230                assert!((positive - 1.0).abs() < 1e-12);
231                assert!(decay >= -1e-12, "n = {n}, λ = {lambda}");
232                assert!(p.weights.windows(2).all(|w| w[0] >= w[1]));
233                if n >= 5 && lambda == Parameters::default_lambda(n) {
234                    assert!(decay.abs() < 1e-12, "n = {n}");
235                }
236            }
237        }
238    }
239
240    /// The textbook values for n = 10: `μ_eff ≈ 3.17`, and the lazy update interval.
241    #[test]
242    fn known_values() {
243        let p = Parameters::new(10, 10);
244
245        assert_eq!(p.mu, 5);
246        assert!((p.mu_eff - 3.1672).abs() < 1e-3, "{}", p.mu_eff);
247        assert!((p.chi_n - 3.0847).abs() < 1e-3, "{}", p.chi_n);
248        assert!(p.eigen_interval() >= 1);
249    }
250}