mod tree;
use alloc::vec::Vec;
use crate::budget::{Budget, Limits, TreeStats};
use crate::error::Error;
use crate::observer::{Event, Observer};
use crate::pomcp::tree::{ROOT, Tree};
use crate::pomdp::{
Plan, Pomdp, RolloutPolicy, below, check_horizon, check_reward, collect_actions,
};
use crate::rng::SplitMix64;
use crate::solution::Status;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PomcpConfig<B = Limits, O = ()> {
pub discount: f64,
pub exploration: f64,
pub max_depth: usize,
pub seed: u64,
pub budget: B,
pub observer: O,
pub progress_interval: Option<u64>,
}
impl PomcpConfig {
pub const DEFAULT_LIMITS: Limits = Limits {
max_trials: Some(10_000),
..Limits::DEFAULT
};
}
impl Default for PomcpConfig {
fn default() -> Self {
Self {
discount: 0.95,
exploration: 1.0,
max_depth: 100,
seed: 0,
budget: Self::DEFAULT_LIMITS,
observer: (),
progress_interval: Some(1_000),
}
}
}
impl<B, O> PomcpConfig<B, O> {
#[must_use]
pub fn with_discount(self, discount: f64) -> Self {
Self { discount, ..self }
}
#[must_use]
pub fn with_exploration(self, exploration: f64) -> Self {
Self {
exploration,
..self
}
}
#[must_use]
pub fn with_max_depth(self, max_depth: usize) -> Self {
Self { max_depth, ..self }
}
#[must_use]
pub fn with_seed(self, seed: u64) -> Self {
Self { seed, ..self }
}
#[must_use]
pub fn with_progress_interval(self, progress_interval: Option<u64>) -> Self {
Self {
progress_interval,
..self
}
}
#[must_use]
pub fn with_reward_range(self, min: f64, max: f64) -> Self {
let depth = u32::try_from(self.max_depth).map_or(f64::from(u32::MAX), f64::from);
let horizon = if self.discount < 1.0 {
(1.0 - libm::pow(self.discount, depth)) / (1.0 - self.discount)
} else {
depth
};
Self {
exploration: (max - min) * horizon,
..self
}
}
#[must_use]
pub fn with_budget<B2: Budget<TreeStats>>(self, budget: B2) -> PomcpConfig<B2, O> {
PomcpConfig {
discount: self.discount,
exploration: self.exploration,
max_depth: self.max_depth,
seed: self.seed,
budget,
observer: self.observer,
progress_interval: self.progress_interval,
}
}
#[must_use]
pub fn with_observer<O2: Observer>(self, observer: O2) -> PomcpConfig<B, O2> {
PomcpConfig {
discount: self.discount,
exploration: self.exploration,
max_depth: self.max_depth,
seed: self.seed,
budget: self.budget,
observer,
progress_interval: self.progress_interval,
}
}
fn validate<S>(&self) -> Result<(), Error<S>> {
check_horizon(self.discount, self.max_depth)?;
if !(self.exploration.is_finite() && self.exploration >= 0.0) {
return Err(Error::InvalidConfig {
reason: "exploration must be finite and non-negative",
});
}
if self.progress_interval == Some(0) {
return Err(Error::InvalidConfig {
reason: "progress_interval must be at least 1",
});
}
Ok(())
}
}
pub fn pomcp<P, R, B, O>(
pomdp: &P,
belief: &[P::State],
rollout: R,
config: PomcpConfig<B, O>,
) -> Result<Plan<P::Action>, Error<P::State>>
where
P: Pomdp,
P::State: Clone,
P::Action: Clone,
P::Observation: PartialEq,
R: RolloutPolicy<P::State>,
B: Budget<TreeStats>,
O: Observer,
{
Pomcp::new(pomdp, rollout, config)?.plan(belief)
}
pub fn pomcp_exploration<P, R, B, O>(
pomdp: &P,
belief: &[P::State],
rollout: R,
config: &PomcpConfig<B, O>,
simulations: u64,
) -> Result<f64, Error<P::State>>
where
P: Pomdp,
P::State: Clone,
P::Action: Clone,
P::Observation: PartialEq,
R: RolloutPolicy<P::State>,
{
if simulations == 0 {
return Err(Error::InvalidConfig {
reason: "pomcp_exploration needs at least one simulation",
});
}
let config = PomcpConfig {
discount: config.discount,
exploration: 0.0,
max_depth: config.max_depth,
seed: config.seed,
budget: Limits {
max_trials: Some(simulations),
..PomcpConfig::DEFAULT_LIMITS
},
observer: (),
progress_interval: None,
};
let mut planner = Pomcp::new(pomdp, rollout, config)?;
planner.plan(belief)?;
let returns = planner.returns;
let lowest = if returns.lowest_rollout.is_finite() {
returns.lowest_rollout
} else {
returns.lowest
};
Ok((returns.highest - lowest).max(0.0))
}
pub struct Pomcp<'a, P: Pomdp, R, B = Limits, O = ()> {
pomdp: &'a P,
actions: Vec<P::Action>,
tree: Tree<P::Observation>,
rollout: R,
rng: SplitMix64,
discount: f64,
exploration: f64,
max_depth: usize,
budget: B,
observer: O,
progress_interval: Option<u64>,
stats: TreeStats,
path: Vec<(u32, f64)>,
returns: Returns,
}
#[derive(Debug, Clone, Copy)]
struct Returns {
highest: f64,
lowest_rollout: f64,
lowest: f64,
}
impl Default for Returns {
fn default() -> Self {
Self {
highest: f64::NEG_INFINITY,
lowest_rollout: f64::INFINITY,
lowest: f64::INFINITY,
}
}
}
impl<'a, P, R, B, O> Pomcp<'a, P, R, B, O>
where
P: Pomdp,
P::State: Clone,
P::Action: Clone,
P::Observation: PartialEq,
R: RolloutPolicy<P::State>,
B: Budget<TreeStats>,
O: Observer,
{
pub fn new(
pomdp: &'a P,
rollout: R,
config: PomcpConfig<B, O>,
) -> Result<Self, Error<P::State>> {
config.validate()?;
let actions = collect_actions(pomdp)?;
Ok(Self {
pomdp,
tree: Tree::new(actions.len()),
actions,
rollout,
rng: SplitMix64::new(config.seed),
discount: config.discount,
exploration: config.exploration,
max_depth: config.max_depth,
budget: config.budget,
observer: config.observer,
progress_interval: config.progress_interval,
stats: TreeStats::default(),
path: Vec::new(),
returns: Returns::default(),
})
}
pub fn plan(&mut self, belief: &[P::State]) -> Result<Plan<P::Action>, Error<P::State>> {
if belief.is_empty() {
return Err(Error::EmptyBelief);
}
self.stats = TreeStats::default();
while !self.exhausted() {
self.stats.simulations += 1;
let particle = belief[below(&mut self.rng, belief.len())].clone();
self.simulate(particle)?;
self.report_progress();
}
Ok(self.recommend())
}
pub fn advance(&mut self, action: &P::Action, observation: &P::Observation) -> bool
where
P::Action: PartialEq,
{
let position = self.actions.iter().position(|known| known == action);
let tree = core::mem::replace(&mut self.tree, Tree::new(self.actions.len()));
match position.and_then(|position| tree.child_of_root(position, observation)) {
Some(child) => {
self.tree = tree.into_subtree(child);
true
}
None => false,
}
}
#[must_use]
pub fn tree_size(&self) -> usize {
self.tree.len()
}
fn report_progress(&mut self) {
let due = self
.progress_interval
.is_some_and(|interval| self.stats.simulations % interval == 0);
if O::ENABLED && due {
self.stats.nodes = self.tree.len() as u64;
let (_, value) = self.tree.best_root_action();
self.observer.observe(Event::TreeProgress {
stats: self.stats,
value,
gap: None,
});
}
}
fn exhausted(&mut self) -> bool {
self.stats.nodes = self.tree.len() as u64;
self.budget.exhausted(&self.stats)
}
fn simulate(&mut self, state: P::State) -> Result<(), Error<P::State>> {
self.path.clear();
let tail = self.descend(state)?;
self.back_up(tail);
Ok(())
}
fn descend(&mut self, mut state: P::State) -> Result<f64, Error<P::State>> {
let mut node = ROOT;
for depth in 0..self.max_depth {
if !self.tree.is_expanded(node) {
self.tree.expand(node);
return self.roll_out(state, depth);
}
let action = self.tree.select(node, self.exploration);
let label = &self.actions[self.tree.position(node, action)];
let step = self.pomdp.step(&state, label, &mut self.rng);
self.stats.steps += 1;
check_reward(&state, step.reward)?;
self.path.push((action, step.reward));
if step.terminal {
return Ok(0.0);
}
node = self.tree.child(action, step.observation);
self.stats.depth = self.stats.depth.max(depth as u64 + 1);
state = step.state;
}
Ok(0.0)
}
fn roll_out(&mut self, mut state: P::State, depth: usize) -> Result<f64, Error<P::State>> {
let mut total = 0.0;
let mut weight = 1.0;
for _ in depth..self.max_depth {
let index = self
.rollout
.action(&state, self.actions.len(), &mut self.rng);
let step = self.pomdp.step(&state, &self.actions[index], &mut self.rng);
self.stats.steps += 1;
check_reward(&state, step.reward)?;
total += weight * step.reward;
if step.terminal {
break;
}
weight *= self.discount;
state = step.state;
}
self.returns.lowest_rollout = self.returns.lowest_rollout.min(total);
Ok(total)
}
fn back_up(&mut self, tail: f64) {
let mut value = tail;
for &(action, reward) in self.path.iter().rev() {
value = reward + self.discount * value;
self.tree.record(action, value);
self.stats.backups += 1;
}
self.returns.highest = self.returns.highest.max(value);
self.returns.lowest = self.returns.lowest.min(value);
}
fn recommend(&mut self) -> Plan<P::Action> {
let (position, value) = self.tree.best_root_action();
self.stats.nodes = self.tree.len() as u64;
Plan {
action: self.actions[position].clone(),
value,
status: Status::BudgetExhausted,
stats: self.stats,
}
}
}