evolutionary_planning/observer.rs
1//! Runtime reporting: an [`Observer`] receives [`Event`]s while an algorithm runs.
2//!
3//! Events are informational only; they never change a run.
4
5use crate::Stats;
6
7/// Something worth reporting while an algorithm runs.
8#[non_exhaustive]
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Event {
11 /// A generation (or iteration) completed.
12 Generation {
13 /// The counters after the generation.
14 stats: Stats,
15 /// The cost of the best member of the current population, which can be worse than
16 /// [`Stats::best_cost`] for non-elitist algorithms.
17 population_best: f64,
18 },
19 /// A new best-so-far genome was evaluated.
20 Improved {
21 /// Evaluations so far, including the improving one.
22 evaluations: u64,
23 /// The new best cost.
24 cost: f64,
25 },
26 /// A restart began (IPOP-CMA-ES, RMHC with restarts).
27 Restart {
28 /// The restart number, `1` for the first restart.
29 restart: u64,
30 /// The population size of the restarted run.
31 population: usize,
32 },
33}
34
35/// Receives [`Event`]s while an algorithm runs.
36///
37/// Implemented for `()` (ignores everything; [`Observer::ENABLED`] is `false`, so the
38/// algorithms skip all event bookkeeping), for `&mut O`, and for closures through
39/// [`observer_fn`].
40pub trait Observer {
41 /// Whether the algorithms should produce events at all; `false` only for `()`.
42 const ENABLED: bool = true;
43
44 /// Receives one event.
45 fn observe(&mut self, event: Event) {
46 let _ = event;
47 }
48}
49
50impl Observer for () {
51 const ENABLED: bool = false;
52}
53
54impl<O: Observer + ?Sized> Observer for &mut O {
55 const ENABLED: bool = O::ENABLED;
56
57 fn observe(&mut self, event: Event) {
58 (**self).observe(event);
59 }
60}
61
62/// Turns a closure `FnMut(Event)` into an [`Observer`].
63///
64/// ```
65/// use evolutionary_planning::{Event, Observer, observer_fn};
66///
67/// let mut improvements = 0;
68/// {
69/// let mut observer = observer_fn(|event| {
70/// if let Event::Improved { .. } = event {
71/// improvements += 1;
72/// }
73/// });
74/// observer.observe(Event::Improved { evaluations: 1, cost: 0.5 });
75/// }
76/// assert_eq!(improvements, 1);
77/// ```
78pub fn observer_fn<F: FnMut(Event)>(f: F) -> ObserverFn<F> {
79 ObserverFn(f)
80}
81
82/// A closure used as an [`Observer`]; created by [`observer_fn`].
83#[derive(Debug, Clone, Copy)]
84pub struct ObserverFn<F>(F);
85
86impl<F: FnMut(Event)> Observer for ObserverFn<F> {
87 fn observe(&mut self, event: Event) {
88 (self.0)(event);
89 }
90}