evolutionary_planning/cmaes/
termination.rs1use alloc::collections::VecDeque;
4use alloc::vec::Vec;
5
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum Termination {
9 NoEffectAxis,
12 NoEffectCoord,
14 ConditionCov,
16 EqualFunValues,
18 Stagnation,
21 TolXUp,
24 TolFun,
27 TolX,
30}
31
32#[derive(Debug, Clone, Default, PartialEq)]
34pub(crate) struct History {
35 pub(crate) best: VecDeque<f64>,
37 pub(crate) median: VecDeque<f64>,
39}
40
41const MAX_STAGNATION: usize = 20_000;
43
44impl History {
45 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 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 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 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
89fn 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
98fn 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
106fn 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 #[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}