evolutionary_planning/
evaluator.rs1use alloc::vec::Vec;
5
6use crate::{Budget, Event, Individual, Objective, Observer, Stats, Stop, sanitize};
7
8#[derive(Debug, Clone, PartialEq)]
10pub struct Outcome<G> {
11 pub best: Option<Individual<G>>,
14 pub population: Vec<Individual<G>>,
17 pub stats: Stats,
19 pub stop: Stop,
21}
22
23impl<G> Outcome<G> {
24 #[must_use]
26 pub fn best_cost(&self) -> f64 {
27 self.best.as_ref().map_or(f64::INFINITY, |best| best.cost)
28 }
29
30 #[must_use]
32 pub fn best_genome(&self) -> Option<&G> {
33 self.best.as_ref().map(|best| &best.genome)
34 }
35}
36
37pub(crate) struct Evaluator<'a, G, O: ?Sized, B: ?Sized, Obs: ?Sized> {
40 objective: &'a mut O,
42 budget: &'a mut B,
44 observer: &'a mut Obs,
46 pub(crate) stats: Stats,
48 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 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 pub(crate) fn exhausted(&mut self) -> bool {
71 self.budget.exhausted(&self.stats)
72 }
73
74 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 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 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 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 pub(crate) fn emit(&mut self, event: Event) {
124 if Obs::ENABLED {
125 self.observer.observe(event);
126 }
127 }
128
129 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}