Skip to main content

evolutionary_planning/
budget.rs

1//! Run counters ([`Stats`]), early stopping ([`Budget`], [`Limits`]) and why a run ended
2//! ([`Stop`]).
3//!
4//! Every algorithm asks its budget **before every objective evaluation**, with the counters so
5//! far, so a run stopped by [`Limits::max_evaluations`] `= n` has evaluated exactly `n`
6//! genomes.
7
8pub use search_core::Budget;
9
10/// Counters collected during one run, handed to the [`Budget`] before every evaluation and
11/// returned in every outcome.
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct Stats {
14    /// Objective evaluations performed so far, including those of local searches.
15    pub evaluations: u64,
16    /// Completed generations (or iterations of a non-generational algorithm such as RMHC,
17    /// where one iteration is one evaluation).
18    pub generations: u64,
19    /// The cost of the best genome evaluated so far; `+∞` before the first evaluation.
20    pub best_cost: f64,
21}
22
23impl Default for Stats {
24    fn default() -> Self {
25        Self {
26            evaluations: 0,
27            generations: 0,
28            best_cost: f64::INFINITY,
29        }
30    }
31}
32
33/// Simple limits on evaluations, generations and the target cost.
34///
35/// [`Limits::DEFAULT`] allows `10^6` evaluations, which keeps every run finite. Any
36/// `FnMut(&Stats) -> bool` is a [`Budget`] too, for example to add a wall-clock deadline in a
37/// `std` crate (annotate the argument type: `|stats: &Stats| ...`).
38///
39/// ```
40/// use evolutionary_planning::{Budget, Limits, Stats};
41///
42/// let mut limits = Limits { target_cost: Some(1e-9), ..Limits::evaluations(500) };
43/// let stats = Stats { evaluations: 500, ..Stats::default() };
44/// assert!(limits.exhausted(&stats));
45/// ```
46#[derive(Debug, Clone, Copy, PartialEq)]
47pub struct Limits {
48    /// Stop once this many evaluations have been performed. `None` is unbounded.
49    pub max_evaluations: Option<u64>,
50    /// Stop once this many generations have completed. `None` is unbounded.
51    pub max_generations: Option<u64>,
52    /// Stop once the best cost is at or below this value. `None` never stops on quality.
53    pub target_cost: Option<f64>,
54}
55
56impl Limits {
57    /// `10^6` evaluations, no other limit.
58    pub const DEFAULT: Self = Self {
59        max_evaluations: Some(1_000_000),
60        max_generations: None,
61        target_cost: None,
62    };
63
64    /// No limits at all: the run ends only through an algorithm's own convergence test.
65    #[must_use]
66    pub const fn unlimited() -> Self {
67        Self {
68            max_evaluations: None,
69            max_generations: None,
70            target_cost: None,
71        }
72    }
73
74    /// Stops after `max` evaluations, with no other limit.
75    #[must_use]
76    pub const fn evaluations(max: u64) -> Self {
77        Self {
78            max_evaluations: Some(max),
79            ..Self::unlimited()
80        }
81    }
82
83    /// Stops after `max` generations, with no other limit.
84    #[must_use]
85    pub const fn generations(max: u64) -> Self {
86        Self {
87            max_generations: Some(max),
88            ..Self::unlimited()
89        }
90    }
91
92    /// Adds a target cost to these limits.
93    #[must_use]
94    pub const fn with_target(self, target: f64) -> Self {
95        Self {
96            target_cost: Some(target),
97            ..self
98        }
99    }
100}
101
102impl Default for Limits {
103    fn default() -> Self {
104        Self::DEFAULT
105    }
106}
107
108impl Budget<Stats> for Limits {
109    fn exhausted(&mut self, stats: &Stats) -> bool {
110        self.max_evaluations
111            .is_some_and(|max| stats.evaluations >= max)
112            || self
113                .max_generations
114                .is_some_and(|max| stats.generations >= max)
115            || self
116                .target_cost
117                .is_some_and(|target| stats.best_cost <= target)
118    }
119}
120
121/// Why a run ended.
122#[non_exhaustive]
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum Stop {
125    /// The [`Budget`] said stop.
126    Budget,
127    /// An algorithm-specific stagnation criterion fired (for example RMHC's restart limit,
128    /// the diffusion model's stagnation counters, or DE's population collapse).
129    Stagnation,
130    /// A CMA-ES termination criterion from the tutorial's Appendix B.3 fired.
131    CmaEs(crate::cmaes::Termination),
132}