stochastic_search/bounds/vpi.rs
1//! VPI-RTDP (Sanner, Goetschalckx, Driessens and Shani 2009): successor choice by the
2//! myopic value of perfect information about a successor's value.
3
4use core::hash::Hash;
5
6use alloc::vec::Vec;
7
8use crate::bounds::{Explorer, Run, gap, 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 [`vpi_rtdp`]: the shared [`Config`] and VPI-RTDP's two thresholds.
18///
19/// Build one with [`VpiRtdpConfig::default`], or with [`VpiRtdpConfig::new`] (or `into`)
20/// from a [`Config`], and adjust it with [`VpiRtdpConfig::with_alpha`] and
21/// [`VpiRtdpConfig::with_beta`].
22#[non_exhaustive]
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct VpiRtdpConfig<B = Limits, O = ()> {
25 /// Epsilon (the gap that ends the run), dead ends, seed, trial length, budget and
26 /// observer.
27 pub base: Config<B, O>,
28 /// The probability `alpha` of continuing a trial by gap-weighted sampling where every
29 /// successor has zero value of information. In `[0, 1]`; above `0`, every state BRTDP
30 /// could update keeps a positive probability of an update, which is what the paper's
31 /// convergence argument needs. Default `0.001`, as in the paper.
32 pub alpha: f64,
33 /// The fraction `beta` of the initial state's initial gap above which a successor's
34 /// gap counts as "close to maximal uncertainty": if any successor's gap exceeds it,
35 /// the trial samples by gap as BRTDP does, since the value of information is
36 /// uninformative there. In `(0, 1]`. Default `0.95`, the paper's "95% of the maximum
37 /// possible bound", read here as relative to the initial gap of `initial`.
38 pub beta: f64,
39 /// BRTDP's trial-end ratio, used where every successor has zero value of information:
40 /// the trial still continues by gap while the expected successor gap is at least the
41 /// initial state's gap divided by `tau`. Finite and greater than `1`. Default `10`, as
42 /// for [`BrtdpConfig`](crate::BrtdpConfig). Not in the paper; see [`vpi_rtdp`].
43 pub tau: f64,
44}
45
46impl Default for VpiRtdpConfig {
47 fn default() -> Self {
48 Self::new(Config::default())
49 }
50}
51
52impl<B, O> VpiRtdpConfig<B, O> {
53 /// Wraps `base` with the paper's thresholds, `alpha = 0.001` and `beta = 0.95`, and
54 /// `tau = 10`.
55 #[must_use]
56 pub fn new(base: Config<B, O>) -> Self {
57 Self {
58 base,
59 alpha: 0.001,
60 beta: 0.95,
61 tau: crate::BrtdpConfig::DEFAULT_TAU,
62 }
63 }
64
65 /// Returns the same settings with another `tau`.
66 #[must_use]
67 pub fn with_tau(self, tau: f64) -> Self {
68 Self { tau, ..self }
69 }
70
71 /// Returns the same settings with another `alpha`.
72 #[must_use]
73 pub fn with_alpha(self, alpha: f64) -> Self {
74 Self { alpha, ..self }
75 }
76
77 /// Returns the same settings with another `beta`.
78 #[must_use]
79 pub fn with_beta(self, beta: f64) -> Self {
80 Self { beta, ..self }
81 }
82
83 /// Checks the thresholds.
84 ///
85 /// # Errors
86 ///
87 /// Returns [`Error::InvalidConfig`] for an `alpha` outside `[0, 1]`, a `beta` outside
88 /// `(0, 1]` or a `tau` that is not finite and greater than 1.
89 fn validate<S>(&self) -> Result<(), Error<S>> {
90 if !(0.0..=1.0).contains(&self.alpha) {
91 return Err(Error::InvalidConfig {
92 reason: "alpha must lie in [0, 1]",
93 });
94 }
95
96 if !(self.beta > 0.0 && self.beta <= 1.0) {
97 return Err(Error::InvalidConfig {
98 reason: "beta must lie in (0, 1]",
99 });
100 }
101
102 if !(self.tau.is_finite() && self.tau > 1.0) {
103 return Err(Error::InvalidConfig {
104 reason: "tau must be finite and greater than 1",
105 });
106 }
107
108 Ok(())
109 }
110}
111
112impl<B, O> From<Config<B, O>> for VpiRtdpConfig<B, O> {
113 fn from(base: Config<B, O>) -> Self {
114 Self::new(base)
115 }
116}
117
118/// Solves an SSP from `initial` with VPI-RTDP, keeping a lower and an upper bound on every
119/// stored state's optimal value.
120///
121/// VPI-RTDP (Sanner, Goetschalckx, Driessens and Shani 2009) differs from
122/// [`brtdp`](crate::brtdp()) only in how trials pick states; bounds, dead-end handling,
123/// guarantee, policy (greedy on the upper bound, with the fill pass after convergence),
124/// events and errors are as documented there.
125///
126/// After backing up `s`, with `a*` the lower-greedy action, the trial picks a successor `t`:
127///
128/// 1. If some successor's gap exceeds `beta` times the initial gap of `initial`, it samples
129/// `t` by `P(t) * gap(t)` as BRTDP does.
130/// 2. Otherwise it computes, for every successor, the myopic value of perfect information
131/// `VPI(t)`: values are taken as uniform between the bounds, and `VPI(t)` is the largest
132/// expected gain over the actions `a != a*` from learning the true value of `t`, i.e.
133/// the average over `v` in `[L(t), U(t)]` of
134/// `max(0, E[Q(s, a*) | v] - E[Q(s, a) | v])`. If some `VPI(t)` is positive, it samples
135/// `t` by `VPI(t)`.
136/// 3. Otherwise, if the expected successor gap `sum P(t) * gap(t)` is at least the initial
137/// state's gap divided by `tau`, it samples by gap (BRTDP's rule); else, with
138/// probability `alpha`, it samples by gap if any gap is positive; else the trial ends.
139///
140/// # Deviations from the paper
141///
142/// The paper measures anytime policy quality and stops on a time limit. It deliberately
143/// skips updates where the policy has settled but the bounds have not. This crate stops on
144/// `U(initial) - L(initial) <= epsilon`, which pure VPI steering may never reach: a trial can
145/// keep following a successor of positive VPI (a self-loop, say) whose backups no longer
146/// change anything, while the states that hold the gap up have zero VPI. Two additions
147/// restore BRTDP's convergence argument (at least every second trial after a stalled one
148/// is a BRTDP trial), with no speed guarantee: on random SSPs VPI-RTDP needed up to 75
149/// times BRTDP's backups:
150///
151/// - step 3 first applies BRTDP's rule: while the expected successor gap is at least the
152/// initial state's gap divided by `tau`, the trial samples by gap;
153/// - after a trial that did not shrink the initial state's gap, the next trial runs as a
154/// plain BRTDP trial.
155///
156/// The paper maximizes rewards; here an action gains by having the lower expected cost.
157/// `E[Q(s, a) | v]` is `Q(s, a)` under the bound midpoints `(L + U) / 2`, with `t` fixed at
158/// `v`; actions with an infinite expected cost (a dead-end successor) gain nothing. A
159/// successor whose bounds meet has `VPI = 0`.
160///
161/// # Errors
162///
163/// As for [`brtdp`](crate::brtdp()), with invalid thresholds reported as
164/// [`Error::InvalidConfig`].
165///
166/// # Panics
167///
168/// Panics if more than `u32::MAX` states, actions or outcomes are stored.
169///
170/// # Example
171///
172/// A sure route for cost 3, or a coin flip for cost 1 that retries on failure (expected
173/// cost 2):
174///
175/// ```
176/// use stochastic_search::{Mdp, VpiRtdpConfig, Zero, heuristic_fn, vpi_rtdp};
177///
178/// struct Routes;
179///
180/// impl Mdp for Routes {
181/// type State = bool;
182/// type Action = &'static str;
183///
184/// fn actions(&self, _done: &bool, mut emit: impl FnMut(&'static str, f64)) {
185/// emit("sure", 3.0);
186/// emit("flip", 1.0);
187/// }
188///
189/// fn outcomes(&self, _done: &bool, action: &&'static str, mut emit: impl FnMut(bool, f64)) {
190/// if *action == "sure" {
191/// emit(true, 1.0);
192/// } else {
193/// emit(true, 0.5);
194/// emit(false, 0.5);
195/// }
196/// }
197/// }
198///
199/// let upper = heuristic_fn(|_: &bool| Some(3.0));
200/// let config = VpiRtdpConfig::default();
201/// let solution = vpi_rtdp(&Routes, false, &|done: &bool| *done, Zero, upper, config)?;
202///
203/// assert!(solution.is_converged());
204/// let (lower, upper) = (solution.initial_value(), solution.initial_upper_bound().unwrap());
205/// assert!(lower <= 2.0 && 2.0 <= upper && upper - lower <= 1e-6);
206/// assert_eq!(solution.initial_action(), Some(&"flip"));
207/// # Ok::<(), stochastic_search::Error<bool>>(())
208/// ```
209pub fn vpi_rtdp<M, G, L, U, B, O>(
210 mdp: &M,
211 initial: M::State,
212 goal: &G,
213 lower: L,
214 upper: U,
215 config: VpiRtdpConfig<B, O>,
216) -> SolveResult<M>
217where
218 M: Mdp,
219 M::State: Clone + Eq + Hash,
220 G: Goal<M::State>,
221 L: Heuristic<M::State, f64>,
222 U: Heuristic<M::State, f64>,
223 B: Budget<Stats>,
224 O: Observer,
225{
226 config.validate()?;
227 let explorer = Explorer::Vpi(Vpi {
228 alpha: config.alpha,
229 beta: config.beta,
230 tau: config.tau,
231 threshold: 0.0,
232 means: Vec::new(),
233 });
234
235 solve((mdp, initial, goal), lower, upper, config.base, explorer)
236}
237
238/// VPI-RTDP's per-run state.
239pub(crate) struct Vpi {
240 /// The probability of continuing a trial without value of information.
241 alpha: f64,
242 /// The fraction of the initial gap that counts as maximal uncertainty.
243 beta: f64,
244 /// BRTDP's trial-end ratio, for states without value of information.
245 tau: f64,
246
247 /// `beta` times the initial gap of the initial state; set once the run starts.
248 threshold: f64,
249 /// Reused buffer: the expected Q-value of every action of the current state under the
250 /// bound midpoints.
251 means: Vec<f64>,
252}
253
254impl Vpi {
255 /// Fixes the gap threshold from the initial state's initial gap.
256 pub(crate) fn set_threshold(&mut self, initial_gap: f64) {
257 self.threshold = self.beta * initial_gap;
258 }
259
260 /// The trial-end ratio of the `tau` rule, also used by fallback trials.
261 pub(crate) fn tau(&self) -> f64 {
262 self.tau
263 }
264}
265
266impl<M: Mdp, G, L, U, B, O> Run<'_, M, G, L, U, B, O> {
267 /// VPI-RTDP's successor choice at `state` under its lower-greedy action at `index`.
268 pub(crate) fn vpi_next(&mut self, state: Id, index: u32) -> Option<Id> {
269 let Explorer::Vpi(vpi) = &self.explorer else {
270 unreachable!("only VPI-RTDP runs choose by value of information");
271 };
272
273 let (alpha, tau, threshold) = (vpi.alpha, vpi.tau, vpi.threshold);
274
275 let u = self.rng.next_unit();
276 let (total, largest) = self.gap_weights(index);
277 if largest > threshold {
278 return self.pick_weighted(index, total, u);
279 }
280
281 let information = self.information_weights(state, index);
282 if information > 0.0 {
283 return self.pick_weighted(index, information, u);
284 }
285
286 self.gap_weights(index);
287 if total > 0.0 && total >= self.gap(self.start) / tau {
288 return self.pick_weighted(index, total, u);
289 }
290
291 let r = self.rng.next_unit();
292 if r < alpha && total > 0.0 {
293 return self.pick_weighted(index, total, u);
294 }
295
296 None
297 }
298
299 /// Fills [`Run::weights`] with `VPI(t)` for every outcome `t` of the action at `index`
300 /// (the lower-greedy action of `state`) and returns their sum.
301 fn information_weights(&mut self, state: Id, index: u32) -> f64 {
302 let Explorer::Vpi(vpi) = &mut self.explorer else {
303 unreachable!("only VPI-RTDP runs choose by value of information");
304 };
305
306 let mut means = core::mem::take(&mut vpi.means);
307 means.clear();
308 means.extend(
309 self.space
310 .actions_of(state)
311 .map(|(action, entry)| entry.cost + self.expected_midpoint(action)),
312 );
313
314 let mut weights = core::mem::take(&mut self.weights);
315 weights.clear();
316 let (first, _) = self.space.node(state).actions;
317 for outcome in self.space.outcomes(index) {
318 weights.push(self.information(state, index - first, outcome.target, &means));
319 }
320
321 let total = weights.iter().sum();
322 self.weights = weights;
323 if let Explorer::Vpi(vpi) = &mut self.explorer {
324 vpi.means = means;
325 }
326
327 total
328 }
329
330 /// The expected value of the successors of the action at `index` under the bound
331 /// midpoints.
332 fn expected_midpoint(&self, index: u32) -> f64 {
333 self.space
334 .outcomes(index)
335 .iter()
336 .map(|outcome| outcome.probability * self.midpoint(outcome.target))
337 .sum()
338 }
339
340 /// The midpoint `(L + U) / 2` of the bounds of `id`.
341 fn midpoint(&self, id: Id) -> f64 {
342 f64::midpoint(self.space.node(id).value, self.upper[id as usize])
343 }
344
345 /// `VPI(t)` at `state` with greedy action number `greedy` (its position among the
346 /// state's actions), given the expected Q-value `means` of every action.
347 fn information(&self, state: Id, greedy: u32, t: Id, means: &[f64]) -> f64 {
348 let (lower, upper) = (self.space.node(t).value, self.upper[t as usize]);
349 if gap(lower, upper) <= 0.0 {
350 return 0.0;
351 }
352
353 let midpoint = self.midpoint(t);
354 let (first, _) = self.space.node(state).actions;
355 let greedy_mean = means[greedy as usize];
356 let greedy_probability = self.probability_of(first + greedy, t);
357 let mut best = 0.0_f64;
358 for (position, &mean) in means.iter().enumerate() {
359 let position = u32::try_from(position).expect("action positions fit u32");
360 if position == greedy || !mean.is_finite() {
361 continue;
362 }
363
364 let slope = greedy_probability - self.probability_of(first + position, t);
365 let gain = |v: f64| (greedy_mean - mean) + slope * (v - midpoint);
366 best = best.max(average_positive_part(gain(lower), gain(upper)));
367 }
368
369 best
370 }
371
372 /// The probability of reaching `t` with the action at `index`, summed over repeated
373 /// outcomes.
374 fn probability_of(&self, index: u32, t: Id) -> f64 {
375 self.space
376 .outcomes(index)
377 .iter()
378 .filter(|outcome| outcome.target == t)
379 .map(|outcome| outcome.probability)
380 .sum()
381 }
382}
383
384/// The average of `max(0, f)` over an interval on which the linear function `f` goes from
385/// `at_start` to `at_end`.
386fn average_positive_part(at_start: f64, at_end: f64) -> f64 {
387 if at_start >= 0.0 && at_end >= 0.0 {
388 f64::midpoint(at_start, at_end)
389 } else if at_start <= 0.0 && at_end <= 0.0 {
390 0.0
391 } else {
392 let (positive, negative) = (at_start.max(at_end), at_start.min(at_end));
393
394 positive * positive / (2.0 * (positive - negative))
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use super::average_positive_part;
401
402 /// The closed form matches the triangle and trapezoid areas.
403 #[test]
404 fn average_positive_part_is_the_mean_gain() {
405 assert_eq!(average_positive_part(2.0, 4.0), 3.0);
406 assert_eq!(average_positive_part(-2.0, -4.0), 0.0);
407 // Crosses zero at the midpoint: a triangle of height 2 over half the interval.
408 assert_eq!(average_positive_part(2.0, -2.0), 0.5);
409 assert_eq!(average_positive_part(-2.0, 2.0), 0.5);
410 }
411}