Skip to main content

evolutionary_planning/
evaluator.rs

1//! The bookkeeping every single-objective algorithm shares: budget checks before each
2//! evaluation, NaN sanitising, the best-so-far genome, counters and events.
3
4use alloc::vec::Vec;
5
6use crate::{Budget, Event, Individual, Objective, Observer, Stats, Stop, sanitize};
7
8/// The result of a single-objective run.
9#[derive(Debug, Clone, PartialEq)]
10pub struct Outcome<G> {
11    /// The best genome evaluated during the whole run (not only in the final population).
12    /// `None` only if the budget allowed no evaluation at all.
13    pub best: Option<Individual<G>>,
14    /// The final population, sorted ascending by cost. Empty for single-point algorithms
15    /// that keep no population other than `best`.
16    pub population: Vec<Individual<G>>,
17    /// The counters at the end of the run.
18    pub stats: Stats,
19    /// Why the run ended.
20    pub stop: Stop,
21}
22
23impl<G> Outcome<G> {
24    /// The best cost found, `+∞` if nothing was evaluated.
25    #[must_use]
26    pub fn best_cost(&self) -> f64 {
27        self.best.as_ref().map_or(f64::INFINITY, |best| best.cost)
28    }
29
30    /// The best genome found, if any.
31    #[must_use]
32    pub fn best_genome(&self) -> Option<&G> {
33        self.best.as_ref().map(|best| &best.genome)
34    }
35}
36
37/// Wraps an objective with a budget and an observer, counting evaluations and keeping the
38/// best genome seen.
39pub(crate) struct Evaluator<'a, G, O: ?Sized, B: ?Sized, Obs: ?Sized> {
40    /// The objective to minimise.
41    objective: &'a mut O,
42    /// Asked before every evaluation.
43    budget: &'a mut B,
44    /// Receives `Improved` and `Generation` events.
45    observer: &'a mut Obs,
46    /// The counters so far.
47    pub(crate) stats: Stats,
48    /// The best genome evaluated so far.
49    pub(crate) best: Option<Individual<G>>,
50}
51
52impl<'a, G: Clone, O, B, Obs> Evaluator<'a, G, O, B, Obs>
53where
54    O: Objective<G> + ?Sized,
55    B: Budget<Stats> + ?Sized,
56    Obs: Observer + ?Sized,
57{
58    /// Starts counting from zero.
59    pub(crate) fn new(objective: &'a mut O, budget: &'a mut B, observer: &'a mut Obs) -> Self {
60        Self {
61            objective,
62            budget,
63            observer,
64            stats: Stats::default(),
65            best: None,
66        }
67    }
68
69    /// Returns `true` if the budget forbids another evaluation.
70    pub(crate) fn exhausted(&mut self) -> bool {
71        self.budget.exhausted(&self.stats)
72    }
73
74    /// Evaluates `genome` unless the budget is exhausted; returns its sanitised cost.
75    pub(crate) fn evaluate(&mut self, genome: &G) -> Option<f64> {
76        if self.exhausted() {
77            return None;
78        }
79
80        let cost = sanitize(self.objective.evaluate(genome));
81        self.stats.evaluations += 1;
82        self.record(genome, cost);
83
84        Some(cost)
85    }
86
87    /// Evaluates `genome` and pairs it with its cost, unless the budget is exhausted.
88    pub(crate) fn individual(&mut self, genome: G) -> Option<Individual<G>> {
89        let cost = self.evaluate(&genome)?;
90
91        Some(Individual { genome, cost })
92    }
93
94    /// Updates the best-so-far genome with a freshly evaluated one and reports improvements.
95    fn record(&mut self, genome: &G, cost: f64) {
96        if cost < self.stats.best_cost || self.best.is_none() {
97            self.stats.best_cost = cost;
98            self.best = Some(Individual {
99                genome: genome.clone(),
100                cost,
101            });
102            if Obs::ENABLED {
103                self.observer.observe(Event::Improved {
104                    evaluations: self.stats.evaluations,
105                    cost,
106                });
107            }
108        }
109    }
110
111    /// Marks a generation as complete and reports it.
112    pub(crate) fn end_generation(&mut self, population_best: f64) {
113        self.stats.generations += 1;
114        if Obs::ENABLED {
115            self.observer.observe(Event::Generation {
116                stats: self.stats,
117                population_best,
118            });
119        }
120    }
121
122    /// Reports another event, such as a restart.
123    pub(crate) fn emit(&mut self, event: Event) {
124        if Obs::ENABLED {
125            self.observer.observe(event);
126        }
127    }
128
129    /// Ends the run, returning the outcome; the best genome moves into it.
130    pub(crate) fn outcome(&mut self, mut population: Vec<Individual<G>>, stop: Stop) -> Outcome<G> {
131        crate::cost::sort_population(&mut population);
132
133        Outcome {
134            best: self.best.take(),
135            population,
136            stats: self.stats,
137            stop,
138        }
139    }
140}