use rand_core::Rng;
use crate::budget::TreeStats;
use crate::error::Error;
use crate::solution::Status;
pub trait Pomdp {
type State;
type Action;
type Observation;
fn actions(&self, emit: impl FnMut(Self::Action));
fn step<R: Rng + ?Sized>(
&self,
state: &Self::State,
action: &Self::Action,
rng: &mut R,
) -> Step<Self::State, Self::Observation>;
}
#[derive(Debug, Clone, PartialEq)]
pub struct Step<S, O> {
pub state: S,
pub observation: O,
pub reward: f64,
pub terminal: bool,
}
impl<S, O> Step<S, O> {
#[must_use]
pub fn new(state: S, observation: O, reward: f64) -> Self {
Self {
state,
observation,
reward,
terminal: false,
}
}
#[must_use]
pub fn terminal(self) -> Self {
Self {
terminal: true,
..self
}
}
}
pub trait RolloutPolicy<S> {
fn action<R: Rng + ?Sized>(&mut self, state: &S, actions: usize, rng: &mut R) -> usize;
}
impl<S, P: RolloutPolicy<S> + ?Sized> RolloutPolicy<S> for &mut P {
fn action<R: Rng + ?Sized>(&mut self, state: &S, actions: usize, rng: &mut R) -> usize {
(**self).action(state, actions, rng)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct UniformRandom;
impl<S> RolloutPolicy<S> for UniformRandom {
fn action<R: Rng + ?Sized>(&mut self, _state: &S, actions: usize, rng: &mut R) -> usize {
below(rng, actions)
}
}
pub(crate) fn below<R: Rng + ?Sized>(rng: &mut R, bound: usize) -> usize {
let product = u128::from(rng.next_u64()) * bound as u128;
usize::try_from(product >> 64).expect("the result is below bound, a usize")
}
#[derive(Debug, Clone, PartialEq)]
pub struct Plan<A> {
pub action: A,
pub value: f64,
pub status: Status,
pub stats: TreeStats,
}
pub(crate) fn collect_actions<P: Pomdp>(
pomdp: &P,
) -> Result<alloc::vec::Vec<P::Action>, Error<P::State>> {
let mut actions = alloc::vec::Vec::new();
pomdp.actions(|action| actions.push(action));
if actions.is_empty() {
return Err(Error::NoActions);
}
Ok(actions)
}
pub(crate) fn check_reward<S: Clone>(state: &S, reward: f64) -> Result<(), Error<S>> {
if reward.is_finite() {
Ok(())
} else {
Err(Error::InvalidReward {
state: state.clone(),
reward,
})
}
}
pub(crate) fn check_horizon<S>(discount: f64, max_depth: usize) -> Result<(), Error<S>> {
if !(discount > 0.0 && discount <= 1.0) {
return Err(Error::InvalidConfig {
reason: "discount must lie in (0, 1]",
});
}
if max_depth == 0 {
return Err(Error::InvalidConfig {
reason: "max_depth must be at least 1",
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::below;
use crate::rng::SplitMix64;
#[test]
fn below_covers_the_range() {
let mut rng = SplitMix64::new(3);
let mut seen = [false; 5];
for _ in 0..1000 {
seen[below(&mut rng, 5)] = true;
}
assert!(seen.iter().all(|&s| s));
}
}