Skip to main content

stochastic_search/
pomdp.rs

1//! The generative POMDP model ([`Pomdp`], [`Step`]), rollout policies ([`RolloutPolicy`],
2//! [`UniformRandom`]) and the result of an online planning call ([`Plan`]).
3//!
4//! The belief-space planners [`pomcp`](crate::pomcp()) and [`despot`](crate::despot())
5//! never see transition or observation probabilities. They only sample: given a hidden
6//! state and an action, the model draws a successor, an observation and a reward from a
7//! caller-visible random generator. Beliefs are particle sets: a slice of states, each an
8//! equally likely guess of the hidden state.
9
10use rand_core::Rng;
11
12use crate::budget::TreeStats;
13use crate::error::Error;
14use crate::solution::Status;
15
16/// A partially observable Markov decision process, given as a generative model.
17///
18/// Unlike [`Mdp`](crate::Mdp), a POMDP maximizes discounted reward, as in the POMCP and
19/// DESPOT papers: the planners maximize `E[sum_t gamma^t r_t]`. The action set is the same
20/// in every state (the agent cannot tell states apart), so [`Pomdp::actions`] takes no
21/// state.
22///
23/// # Determinism
24///
25/// [`Pomdp::step`] must draw all its randomness from `rng`. Then a seed reproduces a
26/// planning call, and DESPOT's determinized scenarios work as intended: the same state,
27/// action and generator state must give the same [`Step`].
28///
29/// # Example
30///
31/// A coin whose side is hidden. `peek` costs 1 and shows the side with probability 0.9;
32/// `heads` and `tails` call a side and end the episode with reward 10 if right, -10 if
33/// wrong.
34///
35/// ```
36/// use rand_core::Rng;
37/// use stochastic_search::{Pomdp, Step, unit_interval};
38///
39/// struct Coin;
40///
41/// impl Pomdp for Coin {
42///     type State = bool; // heads?
43///     type Action = &'static str;
44///     type Observation = Option<bool>;
45///
46///     fn actions(&self, mut emit: impl FnMut(&'static str)) {
47///         emit("peek");
48///         emit("heads");
49///         emit("tails");
50///     }
51///
52///     fn step<R: Rng + ?Sized>(&self, heads: &bool, action: &&'static str, rng: &mut R)
53///         -> Step<bool, Option<bool>>
54///     {
55///         if *action == "peek" {
56///             let truthful = unit_interval(rng) < 0.9;
57///             Step::new(*heads, Some(*heads == truthful), -1.0)
58///         } else {
59///             let right = *heads == (*action == "heads");
60///             Step::new(*heads, None, if right { 10.0 } else { -10.0 }).terminal()
61///         }
62///     }
63/// }
64/// ```
65pub trait Pomdp {
66    /// A hidden state. Planners clone states into particle sets.
67    type State;
68    /// An action label, returned in [`Plan::action`].
69    type Action;
70    /// An observation. Planners compare observations with `==` to group histories.
71    type Observation;
72
73    /// Calls `emit` once for every action, in a fixed order. There must be at least one.
74    ///
75    /// Called once per planning call; planners refer to actions by their position in this
76    /// order (as [`RolloutPolicy::action`] does).
77    fn actions(&self, emit: impl FnMut(Self::Action));
78
79    /// Samples the result of taking `action` in the hidden `state`: the successor state,
80    /// the observation the agent receives, and the reward. The reward must be finite.
81    ///
82    /// Never called on a state that ended an episode ([`Step::terminal`]).
83    fn step<R: Rng + ?Sized>(
84        &self,
85        state: &Self::State,
86        action: &Self::Action,
87        rng: &mut R,
88    ) -> Step<Self::State, Self::Observation>;
89}
90
91/// One sampled transition of a [`Pomdp`].
92#[derive(Debug, Clone, PartialEq)]
93pub struct Step<S, O> {
94    /// The successor state.
95    pub state: S,
96    /// The observation received after the transition.
97    pub observation: O,
98    /// The reward of the transition. Must be finite.
99    pub reward: f64,
100    /// Whether the episode ends with this transition. No reward follows a terminal step.
101    pub terminal: bool,
102}
103
104impl<S, O> Step<S, O> {
105    /// A non-terminal step.
106    #[must_use]
107    pub fn new(state: S, observation: O, reward: f64) -> Self {
108        Self {
109            state,
110            observation,
111            reward,
112            terminal: false,
113        }
114    }
115
116    /// The same step, marked as ending the episode.
117    #[must_use]
118    pub fn terminal(self) -> Self {
119        Self {
120            terminal: true,
121            ..self
122        }
123    }
124}
125
126/// Picks actions for simulations below the search tree: POMCP's rollout policy and
127/// DESPOT's default policy (whose simulated value is DESPOT's lower bound).
128///
129/// A good rollout policy is the main domain knowledge the planners can use; the default,
130/// [`UniformRandom`], knows nothing. Implemented for `&mut P` of any policy `P`.
131pub trait RolloutPolicy<S> {
132    /// Returns the position of the action to take in `state`, below `actions` (the number
133    /// of actions [`Pomdp::actions`] emits). Must draw all its randomness from `rng`.
134    fn action<R: Rng + ?Sized>(&mut self, state: &S, actions: usize, rng: &mut R) -> usize;
135}
136
137impl<S, P: RolloutPolicy<S> + ?Sized> RolloutPolicy<S> for &mut P {
138    fn action<R: Rng + ?Sized>(&mut self, state: &S, actions: usize, rng: &mut R) -> usize {
139        (**self).action(state, actions, rng)
140    }
141}
142
143/// The rollout policy that picks every action with equal probability.
144#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
145pub struct UniformRandom;
146
147impl<S> RolloutPolicy<S> for UniformRandom {
148    fn action<R: Rng + ?Sized>(&mut self, _state: &S, actions: usize, rng: &mut R) -> usize {
149        below(rng, actions)
150    }
151}
152
153/// Returns a uniform sample from `0..bound` (`bound > 0`).
154///
155/// Uses the 64-bit multiply-shift reduction; its bias of at most `bound / 2^64` does not
156/// matter for simulations.
157pub(crate) fn below<R: Rng + ?Sized>(rng: &mut R, bound: usize) -> usize {
158    let product = u128::from(rng.next_u64()) * bound as u128;
159
160    usize::try_from(product >> 64).expect("the result is below bound, a usize")
161}
162
163/// The answer of an online POMDP planner for one decision.
164#[derive(Debug, Clone, PartialEq)]
165pub struct Plan<A> {
166    /// The recommended action.
167    pub action: A,
168    /// The planner's estimate of the recommended action's value from the given belief. See
169    /// [`pomcp`](crate::pomcp()) and [`despot`](crate::despot()) for what it means for each.
170    pub value: f64,
171    /// [`Status::Converged`] if the planner's own stopping rule fired (DESPOT's bound gap),
172    /// [`Status::BudgetExhausted`] if the budget stopped it. POMCP has no stopping rule, so
173    /// it always reports an exhausted budget.
174    pub status: Status,
175    /// Counters of the call; see each planner for what they count.
176    pub stats: TreeStats,
177}
178
179/// Collects the actions of `pomdp` in emission order.
180///
181/// # Errors
182///
183/// Returns [`Error::NoActions`] if there are none.
184pub(crate) fn collect_actions<P: Pomdp>(
185    pomdp: &P,
186) -> Result<alloc::vec::Vec<P::Action>, Error<P::State>> {
187    let mut actions = alloc::vec::Vec::new();
188    pomdp.actions(|action| actions.push(action));
189    if actions.is_empty() {
190        return Err(Error::NoActions);
191    }
192
193    Ok(actions)
194}
195
196/// Checks that a sampled reward is finite.
197///
198/// # Errors
199///
200/// Returns [`Error::InvalidReward`] with the state the step started from otherwise.
201pub(crate) fn check_reward<S: Clone>(state: &S, reward: f64) -> Result<(), Error<S>> {
202    if reward.is_finite() {
203        Ok(())
204    } else {
205        Err(Error::InvalidReward {
206            state: state.clone(),
207            reward,
208        })
209    }
210}
211
212/// Checks the discount factor and the depth limit shared by the planners' configurations.
213///
214/// # Errors
215///
216/// Returns [`Error::InvalidConfig`] for a discount outside `(0, 1]` or a zero depth.
217pub(crate) fn check_horizon<S>(discount: f64, max_depth: usize) -> Result<(), Error<S>> {
218    if !(discount > 0.0 && discount <= 1.0) {
219        return Err(Error::InvalidConfig {
220            reason: "discount must lie in (0, 1]",
221        });
222    }
223
224    if max_depth == 0 {
225        return Err(Error::InvalidConfig {
226            reason: "max_depth must be at least 1",
227        });
228    }
229
230    Ok(())
231}
232
233#[cfg(test)]
234mod tests {
235    use super::below;
236    use crate::rng::SplitMix64;
237
238    /// Every value below the bound shows up, and nothing at or above it.
239    #[test]
240    fn below_covers_the_range() {
241        let mut rng = SplitMix64::new(3);
242        let mut seen = [false; 5];
243        for _ in 0..1000 {
244            seen[below(&mut rng, 5)] = true;
245        }
246
247        assert!(seen.iter().all(|&s| s));
248    }
249}