Skip to main content

stochastic_search/bounds/
frtdp.rs

1//! Focused real-time dynamic programming (FRTDP, Smith and Simmons 2006): priority-driven
2//! successor choice and adaptive maximum depth.
3
4use core::hash::Hash;
5
6use alloc::vec::Vec;
7
8use crate::bounds::{Explorer, Run, solve};
9use crate::budget::{Budget, Limits, Stats};
10use crate::config::Config;
11use crate::error::Error;
12use crate::model::{Goal, Heuristic, Mdp};
13use crate::observer::Observer;
14use crate::solution::SolveResult;
15use crate::space::Id;
16
17/// Settings of [`frtdp`]: the shared [`Config`] and FRTDP's adaptive maximum depth.
18///
19/// Build one with [`FrtdpConfig::default`], or with [`FrtdpConfig::new`] (or `into`) from a
20/// [`Config`], and adjust it with [`FrtdpConfig::with_depth`].
21#[non_exhaustive]
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct FrtdpConfig<B = Limits, O = ()> {
24    /// Epsilon (the gap that ends the run, and twice the gap below which a state counts as
25    /// settled), dead ends, trial length, budget and observer. The seed only drives the
26    /// fallback BRTDP trials (see [`frtdp`]).
27    pub base: Config<B, O>,
28    /// The initial maximum trial depth `D0`. Finite and at least `1`. Default `10`, as in
29    /// the paper.
30    pub initial_depth: f64,
31    /// The factor `kD` by which the maximum depth grows after a trial whose late updates
32    /// were at least as useful as its early ones. Finite and at least `1`; `1` keeps the
33    /// depth fixed. Default `1.1`, as in the paper.
34    pub depth_factor: f64,
35}
36
37impl Default for FrtdpConfig {
38    fn default() -> Self {
39        Self::new(Config::default())
40    }
41}
42
43impl<B, O> FrtdpConfig<B, O> {
44    /// Wraps `base` with the paper's depth settings, `D0 = 10` and `kD = 1.1`.
45    #[must_use]
46    pub fn new(base: Config<B, O>) -> Self {
47        Self {
48            base,
49            initial_depth: 10.0,
50            depth_factor: 1.1,
51        }
52    }
53
54    /// Returns the same settings with another initial depth `D0` and growth factor `kD`.
55    #[must_use]
56    pub fn with_depth(self, initial_depth: f64, depth_factor: f64) -> Self {
57        Self {
58            initial_depth,
59            depth_factor,
60            ..self
61        }
62    }
63
64    /// Checks the depth settings.
65    ///
66    /// # Errors
67    ///
68    /// Returns [`Error::InvalidConfig`] for an initial depth or depth factor that is not
69    /// finite and at least 1.
70    fn validate<S>(&self) -> Result<(), Error<S>> {
71        let valid = |x: f64| x.is_finite() && x >= 1.0;
72        if valid(self.initial_depth) && valid(self.depth_factor) {
73            Ok(())
74        } else {
75            Err(Error::InvalidConfig {
76                reason: "initial_depth and depth_factor must be finite and at least 1",
77            })
78        }
79    }
80}
81
82impl<B, O> From<Config<B, O>> for FrtdpConfig<B, O> {
83    fn from(base: Config<B, O>) -> Self {
84        Self::new(base)
85    }
86}
87
88/// Solves an SSP from `initial` with focused RTDP, keeping a lower and an upper bound on
89/// every stored state's optimal value.
90///
91/// FRTDP (Smith and Simmons 2006) differs from [`brtdp`](crate::brtdp()) only in how trials
92/// pick states; bounds, dead-end handling, guarantee, policy (greedy on the upper bound,
93/// with the fill pass after convergence), events and errors are as documented there.
94///
95/// Every state carries a priority, initially its excess gap `gap(s) - epsilon / 2`, and after
96/// each backup `min(gap(s) - epsilon / 2, max_s' P(s' | s, a) * priority(s'))` for the
97/// lower-greedy action `a`: an estimate of how much the uncertainty below `s` contributes to
98/// the gap at `initial`. A trial follows, deterministically, the successor of highest
99/// probability times priority, and ends at a state whose excess gap is not positive or at
100/// the current maximum depth `D` (the paper's adaptive maximum depth). `D` starts at
101/// [`FrtdpConfig::initial_depth`] and is multiplied by [`FrtdpConfig::depth_factor`] after a
102/// trial whose average update quality (the change of the lower bound times the path
103/// probability) in its late part (depth above `D / kD`) is at least that of its early part;
104/// an empty part averages 0. [`Config::max_trial_length`] still caps every trial.
105///
106/// The paper maximizes rewards; here its optimistic bound is the lower bound and its
107/// pessimistic one the upper bound. Ties go to the first successor emitted.
108///
109/// # Deviation from the paper
110///
111/// The deterministic choice can stall: on a random SSP of 11 states, the bounds stopped
112/// changing for 10^7 backups with the initial gap at about 1.2 (the probable cause is a
113/// low-probability successor that holds the gap up and is never the highest-priority one;
114/// the per-state priorities were not inspected). After an FRTDP trial that did not
115/// shrink the initial state's gap, the next trial therefore runs as a plain BRTDP trial
116/// (with `tau = 10`), which samples successors by gap with the seed of
117/// [`Config::seed`]. So at least every second trial after a stalled one is a BRTDP
118/// trial, which restores BRTDP's convergence argument; it is no speed guarantee.
119///
120/// # Errors
121///
122/// As for [`brtdp`](crate::brtdp()), with invalid depth settings reported as
123/// [`Error::InvalidConfig`].
124///
125/// # Panics
126///
127/// Panics if more than `u32::MAX` states, actions or outcomes are stored.
128///
129/// # Example
130///
131/// A sure route for cost 3, or a coin flip for cost 1 that retries on failure (expected
132/// cost 2):
133///
134/// ```
135/// use stochastic_search::{FrtdpConfig, Mdp, Zero, frtdp, heuristic_fn};
136///
137/// struct Routes;
138///
139/// impl Mdp for Routes {
140///     type State = bool;
141///     type Action = &'static str;
142///
143///     fn actions(&self, _done: &bool, mut emit: impl FnMut(&'static str, f64)) {
144///         emit("sure", 3.0);
145///         emit("flip", 1.0);
146///     }
147///
148///     fn outcomes(&self, _done: &bool, action: &&'static str, mut emit: impl FnMut(bool, f64)) {
149///         if *action == "sure" {
150///             emit(true, 1.0);
151///         } else {
152///             emit(true, 0.5);
153///             emit(false, 0.5);
154///         }
155///     }
156/// }
157///
158/// let upper = heuristic_fn(|_: &bool| Some(3.0));
159/// let config = FrtdpConfig::default();
160/// let solution = frtdp(&Routes, false, &|done: &bool| *done, Zero, upper, config)?;
161///
162/// assert!(solution.is_converged());
163/// let (lower, upper) = (solution.initial_value(), solution.initial_upper_bound().unwrap());
164/// assert!(lower <= 2.0 && 2.0 <= upper && upper - lower <= 1e-6);
165/// assert_eq!(solution.initial_action(), Some(&"flip"));
166/// # Ok::<(), stochastic_search::Error<bool>>(())
167/// ```
168pub fn frtdp<M, G, L, U, B, O>(
169    mdp: &M,
170    initial: M::State,
171    goal: &G,
172    lower: L,
173    upper: U,
174    config: FrtdpConfig<B, O>,
175) -> SolveResult<M>
176where
177    M: Mdp,
178    M::State: Clone + Eq + Hash,
179    G: Goal<M::State>,
180    L: Heuristic<M::State, f64>,
181    U: Heuristic<M::State, f64>,
182    B: Budget<Stats>,
183    O: Observer,
184{
185    config.validate()?;
186    let explorer = Explorer::Frtdp(Focus::new(config.initial_depth, config.depth_factor));
187
188    solve((mdp, initial, goal), lower, upper, config.base, explorer)
189}
190
191/// FRTDP's per-run state: priorities and the adaptive maximum depth.
192pub(crate) struct Focus {
193    /// The priority of every stored state, indexed by [`Id`].
194    pub(crate) priority: Vec<f64>,
195    /// The current maximum trial depth `D`.
196    depth_limit: f64,
197    /// The growth factor `kD`.
198    depth_factor: f64,
199    /// The probability of the current trial's path so far (the occupancy estimate `W`).
200    path_probability: f64,
201    /// Summed update quality and update count in the early part of the current trial.
202    early: (f64, u32),
203    /// Summed update quality and update count in the late part of the current trial.
204    late: (f64, u32),
205}
206
207impl Focus {
208    /// Starts with maximum depth `initial_depth` and growth factor `depth_factor`.
209    fn new(initial_depth: f64, depth_factor: f64) -> Self {
210        Self {
211            priority: Vec::new(),
212            depth_limit: initial_depth,
213            depth_factor,
214            path_probability: 1.0,
215            early: (0.0, 0),
216            late: (0.0, 0),
217        }
218    }
219
220    /// Resets the per-trial statistics.
221    pub(crate) fn start_trial(&mut self) {
222        self.path_probability = 1.0;
223        self.early = (0.0, 0);
224        self.late = (0.0, 0);
225    }
226
227    /// Grows the maximum depth if the late updates of the trial were at least as useful
228    /// as the early ones.
229    pub(crate) fn end_trial(&mut self) {
230        let average = |(sum, count): (f64, u32)| {
231            if count == 0 {
232                0.0
233            } else {
234                sum / f64::from(count)
235            }
236        };
237
238        if average(self.late) >= average(self.early) {
239            self.depth_limit *= self.depth_factor;
240        }
241    }
242
243    /// Records the quality of an update at trial depth `depth` in the late or early part.
244    fn track(&mut self, quality: f64, depth: f64) {
245        let part = if depth > self.depth_limit / self.depth_factor {
246            &mut self.late
247        } else {
248            &mut self.early
249        };
250
251        part.0 += quality;
252        part.1 = part.1.saturating_add(1);
253    }
254}
255
256impl<M: Mdp, G, L, U, B, O> Run<'_, M, G, L, U, B, O> {
257    /// The FRTDP state of this run.
258    fn focus(&mut self) -> &mut Focus {
259        match &mut self.explorer {
260            Explorer::Frtdp(focus) => focus,
261            _ => unreachable!("only FRTDP runs ask for their focus"),
262        }
263    }
264
265    /// The excess gap `gap(s) - epsilon / 2`: positive while `state` is not settled.
266    fn excess(&self, state: Id) -> f64 {
267        self.gap(state) - self.epsilon / 2.0
268    }
269
270    /// Sets the priority of `state` after its backup, from its lower-greedy `action`.
271    pub(crate) fn update_priority(&mut self, state: Id, action: Option<u32>) {
272        let mut priority = self.excess(state);
273        if let Some(action) = action {
274            let (_, best) = self.best_successor(action);
275            priority = priority.min(best);
276        }
277
278        self.focus().priority[state as usize] = priority;
279    }
280
281    /// The successor of the action at `index` with the highest probability times priority,
282    /// and that product. Ties go to the first outcome.
283    fn best_successor(&self, index: u32) -> (Id, f64) {
284        let Explorer::Frtdp(focus) = &self.explorer else {
285            unreachable!("only FRTDP runs have priorities");
286        };
287
288        let mut best = (0, f64::NEG_INFINITY);
289        for outcome in self.space.outcomes(index) {
290            let score = outcome.probability * focus.priority[outcome.target as usize];
291            if score > best.1 {
292                best = (outcome.target, score);
293            }
294        }
295
296        best
297    }
298
299    /// FRTDP's successor choice at `state`, backed up just now, under its lower-greedy action
300    /// at `index`: records the update quality, ends the trial at a settled state or at the
301    /// depth limit, and otherwise follows the successor of highest priority.
302    pub(crate) fn frtdp_next(&mut self, state: Id, index: u32, depth: usize) -> Option<Id> {
303        let depth = f64::from(u32::try_from(depth).unwrap_or(u32::MAX));
304        let change = self.last_change;
305        let focus = self.focus();
306        focus.track(change * focus.path_probability, depth);
307        if self.excess(state) <= 0.0 || depth >= self.focus().depth_limit {
308            return None;
309        }
310
311        let (next, _) = self.best_successor(index);
312        let probability: f64 = self
313            .space
314            .outcomes(index)
315            .iter()
316            .filter(|outcome| outcome.target == next)
317            .map(|outcome| outcome.probability)
318            .sum();
319        self.focus().path_probability *= probability;
320
321        Some(next)
322    }
323}