Skip to main content

evolutionary_planning/cmaes/
termination.rs

1//! The termination criteria of Appendix B.3 of Hansen's tutorial, and the history they need.
2
3use alloc::collections::VecDeque;
4use alloc::vec::Vec;
5
6/// A CMA-ES termination criterion (Hansen 2016, Appendix B.3).
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum Termination {
9    /// Adding a 0.1-standard deviation vector along a principal axis of C does not change the
10    /// mean.
11    NoEffectAxis,
12    /// Adding 0.2 standard deviations in a coordinate does not change the mean.
13    NoEffectCoord,
14    /// The condition number of C exceeds [`Config::max_condition`](super::Config).
15    ConditionCov,
16    /// The best costs of the last `10 + ⌈30 n / λ⌉` generations are all equal.
17    EqualFunValues,
18    /// Over a long window, the median of the most recent 30 % of both the best and the
19    /// median costs is not better than the median of the first 30 %.
20    Stagnation,
21    /// `σ · max(diag(D))` grew by more than [`Config::tol_x_up`](super::Config): σ was far
22    /// too small initially, or the run diverges.
23    TolXUp,
24    /// The best costs of the last `10 + ⌈30 n / λ⌉` generations and all costs of the current
25    /// one lie within a range below [`Config::tol_fun`](super::Config).
26    TolFun,
27    /// Every coordinate's standard deviation and every component of `σ p_c` is below
28    /// [`Config::tol_x`](super::Config).
29    TolX,
30}
31
32/// The cost history the criteria look at.
33#[derive(Debug, Clone, Default, PartialEq)]
34pub(crate) struct History {
35    /// The best cost of each generation, most recent last, at most `MAX_STAGNATION` long.
36    pub(crate) best: VecDeque<f64>,
37    /// The median cost of each generation, most recent last.
38    pub(crate) median: VecDeque<f64>,
39}
40
41/// The longest stagnation window of the tutorial: 20 000 generations.
42const MAX_STAGNATION: usize = 20_000;
43
44impl History {
45    /// Records one generation's sorted costs.
46    pub(crate) fn push(&mut self, sorted_costs: &[f64]) {
47        self.best.push_back(sorted_costs[0]);
48        self.median.push_back(median_of_sorted(sorted_costs));
49        if self.best.len() > MAX_STAGNATION {
50            self.best.pop_front();
51            self.median.pop_front();
52        }
53    }
54
55    /// The range (max - min) of the last `window` best costs, if that many exist.
56    pub(crate) fn recent_best_range(&self, window: usize) -> Option<f64> {
57        self.recent_best_bounds(window)
58            .map(|(low, high)| high - low)
59    }
60
61    /// The smallest and largest of the last `window` best costs, if that many exist.
62    pub(crate) fn recent_best_bounds(&self, window: usize) -> Option<(f64, f64)> {
63        if self.best.len() < window {
64            return None;
65        }
66
67        let recent = self.best.iter().skip(self.best.len() - window);
68
69        Some(
70            recent.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &v| {
71                (lo.min(v), hi.max(v))
72            }),
73        )
74    }
75
76    /// The stagnation test over a window of `max(minimum, 20 % of generations)` (capped at
77    /// 20 000) generations.
78    pub(crate) fn stagnated(&self, minimum: usize, generations: u64) -> bool {
79        let fifth = usize::try_from(generations / 5).unwrap_or(usize::MAX);
80        let window = minimum.max(fifth).min(MAX_STAGNATION);
81        if self.best.len() < window {
82            return false;
83        }
84
85        stalled(&self.best, window) && stalled(&self.median, window)
86    }
87}
88
89/// Whether the median of the last 30 % of the window is not better than that of the first
90/// 30 %.
91fn stalled(values: &VecDeque<f64>, window: usize) -> bool {
92    let recent: Vec<f64> = values.iter().skip(values.len() - window).copied().collect();
93    let part = (window * 3).div_ceil(10).max(1);
94
95    median(&recent[window - part..]) >= median(&recent[..part])
96}
97
98/// The median of an unsorted slice.
99fn median(values: &[f64]) -> f64 {
100    let mut sorted = values.to_vec();
101    sorted.sort_by(f64::total_cmp);
102
103    median_of_sorted(&sorted)
104}
105
106/// The median of a sorted, non-empty slice.
107fn median_of_sorted(sorted: &[f64]) -> f64 {
108    let n = sorted.len();
109    if n % 2 == 1 {
110        sorted[n / 2]
111    } else {
112        f64::midpoint(sorted[n / 2 - 1], sorted[n / 2])
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    /// A flat history stagnates; a steadily improving one does not.
121    #[test]
122    fn stagnation() {
123        let mut flat = History::default();
124        let mut improving = History::default();
125        for g in 0..200 {
126            flat.push(&[1.0, 2.0, 3.0]);
127            let v = f64::from(200 - g);
128            improving.push(&[v, v + 1.0, v + 2.0]);
129        }
130
131        assert!(flat.stagnated(150, 200));
132        assert!(!improving.stagnated(150, 200));
133        assert_eq!(flat.recent_best_range(50), Some(0.0));
134        assert_eq!(flat.recent_best_range(500), None);
135    }
136}