Skip to main content

stochastic_search/
observer.rs

1//! Runtime reporting: [`Observer`] receives [`Event`]s while an algorithm runs.
2//!
3//! Events are informational only. They never change a run's values, policy or
4//! [`Status`](crate::Status); in particular [`Event::SuspectedDivergence`] is a heuristic
5//! signal, not a verdict.
6
7/// Something worth reporting while an algorithm runs.
8#[non_exhaustive]
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Event {
11    /// Periodic progress, every [`Config::progress_interval`](crate::Config) backups.
12    Progress {
13        /// Bellman backups so far.
14        backups: u64,
15        /// States stored so far.
16        states: u64,
17        /// The current value of the initial state.
18        initial_value: f64,
19        /// LRTDP, RTDP, LAO* and iLAO*: the change of the initial state's value at its most recent
20        /// backup. Value iteration: the largest residual so far in the sweep in progress.
21        /// BRTDP, FRTDP and VPI-RTDP: the gap between the initial state's bounds.
22        residual: f64,
23    },
24    /// A dead-end analysis finished; `count` states were newly proven to have no proper
25    /// policy and became dead ends. Emitted after every analysis, also when `count` is 0.
26    DeadEndsProven {
27        /// States newly turned into dead ends by this analysis.
28        count: u64,
29    },
30    /// The initial state's value keeps rising without its growth slowing down, which is
31    /// what a value climbing a trap cycle looks like.
32    ///
33    /// Heuristic and not authoritative (see
34    /// [`Config::divergence_window`](crate::Config)): LRTDP and RTDP check the initial
35    /// state's value after every trial, iLAO* after every pass, LAO* after every expansion step. If it rose in each of the
36    /// last `divergence_window` checks and the rise in the last is at least half the rise in
37    /// the first of that window,
38    /// the event fires and the window starts over. A solvable problem whose values climb
39    /// slowly towards a large optimum, at a steady rate, triggers it too.
40    SuspectedDivergence {
41        /// The current value of the initial state.
42        value: f64,
43        /// How much the value rose over the window.
44        growth: f64,
45        /// Bellman backups so far.
46        backups: u64,
47    },
48    /// Periodic progress of a multi-objective algorithm ([`molrtdp`](crate::molrtdp()),
49    /// [`molao_star`](crate::molao_star()), [`imolao_star`](crate::imolao_star()),
50    /// [`mo_value_iteration`](crate::mo_value_iteration())), every
51    /// [`Config::progress_interval`](crate::Config) backups.
52    FrontProgress {
53        /// Bellman backups so far.
54        backups: u64,
55        /// States stored so far.
56        states: u64,
57        /// The number of cost vectors in the initial state's current value.
58        front: usize,
59        /// The Hausdorff distance moved by the most recent backup.
60        residual: f64,
61    },
62    /// Periodic progress of a tree planner ([`pomcp`](crate::pomcp()),
63    /// [`despot`](crate::despot())), every `progress_interval` simulations or explorations
64    /// of its configuration.
65    TreeProgress {
66        /// The counters so far.
67        stats: crate::TreeStats,
68        /// The current value estimate of the recommended action: POMCP's best root action
69        /// value, DESPOT's root lower bound `ell(b0)`.
70        value: f64,
71        /// DESPOT: the root gap `mu(b0) - ell(b0)`. POMCP keeps no bounds: `None`.
72        gap: Option<f64>,
73    },
74}
75
76/// Receives [`Event`]s while an algorithm runs.
77///
78/// The method has a no-op default. Implemented for `()` (the default, which ignores
79/// everything), for `&mut O` of any observer `O`, and for closures through
80/// [`observer_fn`]. When [`Observer::ENABLED`] is `false`, as for `()`, the algorithms skip
81/// all bookkeeping for events, so an unused observer costs nothing.
82pub trait Observer {
83    /// Whether the algorithms should produce events at all. Leave it `true` for real
84    /// observers; it is `false` only for `()`.
85    const ENABLED: bool = true;
86
87    /// Receives one event.
88    fn observe(&mut self, event: Event) {
89        let _ = event;
90    }
91}
92
93impl Observer for () {
94    const ENABLED: bool = false;
95}
96
97impl<O: Observer + ?Sized> Observer for &mut O {
98    const ENABLED: bool = O::ENABLED;
99
100    fn observe(&mut self, event: Event) {
101        (**self).observe(event);
102    }
103}
104
105/// Turns a closure `FnMut(Event)` into an [`Observer`].
106///
107/// # Example
108///
109/// ```
110/// use stochastic_search::{Config, Event, observer_fn};
111///
112/// let mut proven = 0;
113/// let config = Config::default().with_observer(observer_fn(|event| {
114///     if let Event::DeadEndsProven { count } = event {
115///         proven += count;
116///     }
117/// }));
118/// # let _ = config;
119/// ```
120pub fn observer_fn<F: FnMut(Event)>(f: F) -> ObserverFn<F> {
121    ObserverFn(f)
122}
123
124/// A closure used as an [`Observer`]; created by [`observer_fn`].
125#[derive(Debug, Clone, Copy)]
126pub struct ObserverFn<F>(F);
127
128impl<F: FnMut(Event)> Observer for ObserverFn<F> {
129    fn observe(&mut self, event: Event) {
130        (self.0)(event);
131    }
132}