mod tree;
use core::mem;
use alloc::vec::Vec;
use crate::budget::{Budget, Limits, TreeStats};
use crate::despot::tree::{Branch, Node, ROOT, Tree, UNEXPANDED};
use crate::error::Error;
use crate::observer::{Event, Observer};
use crate::pomdp::{
Plan, Pomdp, RolloutPolicy, below, check_horizon, check_reward, collect_actions,
};
use crate::rng::{SplitMix64, derive_seed};
use crate::solution::Status;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DespotConfig<B = Limits, O = ()> {
pub discount: f64,
pub scenarios: usize,
pub regularization: f64,
pub xi: f64,
pub max_depth: usize,
pub target_gap: f64,
pub seed: u64,
pub budget: B,
pub observer: O,
pub progress_interval: Option<u64>,
}
impl DespotConfig {
pub const DEFAULT_LIMITS: Limits = Limits {
max_trials: Some(1_000),
..Limits::DEFAULT
};
}
impl Default for DespotConfig {
fn default() -> Self {
Self {
discount: 0.95,
scenarios: 500,
regularization: 0.0,
xi: 0.95,
max_depth: 90,
target_gap: 1e-6,
seed: 0,
budget: Self::DEFAULT_LIMITS,
observer: (),
progress_interval: Some(1_000),
}
}
}
impl<B, O> DespotConfig<B, O> {
#[must_use]
pub fn with_discount(self, discount: f64) -> Self {
Self { discount, ..self }
}
#[must_use]
pub fn with_scenarios(self, scenarios: usize) -> Self {
Self { scenarios, ..self }
}
#[must_use]
pub fn with_regularization(self, regularization: f64) -> Self {
Self {
regularization,
..self
}
}
#[must_use]
pub fn with_xi(self, xi: f64) -> Self {
Self { xi, ..self }
}
#[must_use]
pub fn with_max_depth(self, max_depth: usize) -> Self {
Self { max_depth, ..self }
}
#[must_use]
pub fn with_target_gap(self, target_gap: f64) -> Self {
Self { target_gap, ..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_budget<B2: Budget<TreeStats>>(self, budget: B2) -> DespotConfig<B2, O> {
DespotConfig {
discount: self.discount,
scenarios: self.scenarios,
regularization: self.regularization,
xi: self.xi,
max_depth: self.max_depth,
target_gap: self.target_gap,
seed: self.seed,
budget,
observer: self.observer,
progress_interval: self.progress_interval,
}
}
#[must_use]
pub fn with_observer<O2: Observer>(self, observer: O2) -> DespotConfig<B, O2> {
DespotConfig {
discount: self.discount,
scenarios: self.scenarios,
regularization: self.regularization,
xi: self.xi,
max_depth: self.max_depth,
target_gap: self.target_gap,
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)?;
let reason = if self.scenarios == 0 {
"scenarios must be at least 1"
} else if !(self.regularization.is_finite() && self.regularization >= 0.0) {
"regularization must be finite and non-negative"
} else if !(0.0..1.0).contains(&self.xi) {
"xi must lie in [0, 1)"
} else if !(self.target_gap.is_finite() && self.target_gap >= 0.0) {
"target_gap must be finite and non-negative"
} else if self.progress_interval == Some(0) {
"progress_interval must be at least 1"
} else {
return Ok(());
};
Err(Error::InvalidConfig { reason })
}
}
pub fn despot<P, R, U, B, O>(
pomdp: &P,
belief: &[P::State],
default: R,
upper: U,
config: DespotConfig<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>,
U: FnMut(&P::State) -> f64,
B: Budget<TreeStats>,
O: Observer,
{
Despot::new(pomdp, belief, default, upper, config)?.plan()
}
pub struct Despot<'a, P: Pomdp, R, U, B = Limits, O = ()> {
pomdp: &'a P,
actions: Vec<P::Action>,
tree: Tree<P::State, P::Observation>,
default: R,
upper: U,
budget: B,
observer: O,
progress_interval: Option<u64>,
stats: TreeStats,
seed: u64,
discount: f64,
powers: Vec<f64>,
scenarios: f64,
lambda: f64,
xi: f64,
max_depth: usize,
target_gap: f64,
root_depth: usize,
scenario_count: usize,
lost: bool,
}
impl<'a, P, R, U, B, O> Despot<'a, P, R, U, B, O>
where
P: Pomdp,
P::State: Clone,
P::Action: Clone,
P::Observation: PartialEq,
R: RolloutPolicy<P::State>,
U: FnMut(&P::State) -> f64,
B: Budget<TreeStats>,
O: Observer,
{
pub fn new(
pomdp: &'a P,
belief: &[P::State],
default: R,
upper: U,
config: DespotConfig<B, O>,
) -> Result<Self, Error<P::State>> {
config.validate()?;
if belief.is_empty() {
return Err(Error::EmptyBelief);
}
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let scenarios = config.scenarios as f64;
let mut search = Self {
pomdp,
actions: collect_actions(pomdp)?,
tree: Tree {
nodes: Vec::new(),
branches: Vec::new(),
},
default,
upper,
budget: config.budget,
observer: config.observer,
progress_interval: config.progress_interval,
stats: TreeStats::default(),
seed: config.seed,
discount: config.discount,
powers: powers(config.discount, config.max_depth + 1),
scenarios,
lambda: config.regularization,
xi: config.xi,
max_depth: config.max_depth,
target_gap: config.target_gap,
root_depth: 0,
scenario_count: config.scenarios,
lost: false,
};
let particles = search.sample_scenarios(belief, config.scenarios);
search.add_node(None, 0, particles)?;
Ok(search)
}
#[cfg(test)]
fn with_root(
pomdp: &'a P,
scenarios: Particles<P::State>,
depth: usize,
default: R,
upper: U,
config: DespotConfig<B, O>,
) -> Result<Self, Error<P::State>> {
let belief: Vec<P::State> = scenarios.iter().map(|(_, state)| state.clone()).collect();
let mut search = Self::new(pomdp, &belief, default, upper, config)?;
search.tree.nodes.clear();
search.root_depth = depth;
search.scenarios = count_of(&scenarios);
search.add_node(None, depth, scenarios)?;
Ok(search)
}
fn sample_scenarios(&self, belief: &[P::State], count: usize) -> Vec<(u32, P::State)> {
let mut rng = SplitMix64::new(self.seed);
(0..count)
.map(|k| {
let id = u32::try_from(k).expect("at most u32::MAX scenarios");
(id, belief[below(&mut rng, belief.len())].clone())
})
.collect()
}
pub fn plan(&mut self) -> Result<Plan<P::Action>, Error<P::State>> {
if self.lost {
return Err(Error::UnseenHistory);
}
self.stats = TreeStats::default();
let status = self.run()?;
Ok(self.recommend(status))
}
pub fn advance(
&mut self,
action: &P::Action,
observation: &P::Observation,
) -> Result<(), Error<P::State>>
where
P::Action: PartialEq,
{
let Some(child) = self.child_of_root(action, observation) else {
self.lost = true;
return Err(Error::UnseenHistory);
};
self.tree = core::mem::replace(
&mut self.tree,
Tree {
nodes: Vec::new(),
branches: Vec::new(),
},
)
.into_subtree(child, self.actions.len());
self.root_depth = self.tree.node(ROOT).depth;
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let scenarios = self.tree.node(ROOT).scenarios.len() as f64;
self.scenarios = scenarios;
self.recompute_bounds()?;
Ok(())
}
pub fn reset(&mut self, belief: &[P::State]) -> Result<(), Error<P::State>> {
if belief.is_empty() {
return Err(Error::EmptyBelief);
}
self.tree.nodes.clear();
self.tree.branches.clear();
self.root_depth = 0;
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let scenarios = self.scenario_count as f64;
self.scenarios = scenarios;
let particles = self.sample_scenarios(belief, self.scenario_count);
self.add_node(None, 0, particles)?;
self.lost = false;
Ok(())
}
#[must_use]
pub fn tree_size(&self) -> usize {
self.tree.nodes.len()
}
pub fn belief(&self) -> impl ExactSizeIterator<Item = &P::State> {
self.tree
.node(ROOT)
.scenarios
.iter()
.map(|(_, state)| state)
}
fn child_of_root(&self, action: &P::Action, observation: &P::Observation) -> Option<u32>
where
P::Action: PartialEq,
{
let position = self.actions.iter().position(|known| known == action)?;
if self.tree.node(ROOT).first_branch == UNEXPANDED {
return None;
}
self.tree.branches_of(ROOT, self.actions.len())[position]
.children
.iter()
.find(|(seen, _)| seen == observation)
.map(|&(_, child)| child)
}
fn recompute_bounds(&mut self) -> Result<(), Error<P::State>> {
for id in 0..self.tree.nodes.len() {
let id = u32::try_from(id).expect("at most u32::MAX nodes");
let scenarios = core::mem::take(&mut self.tree.node_mut(id).scenarios);
let depth = self.tree.node(id).depth;
let result = self.default_value(&scenarios, depth);
self.tree.node_mut(id).scenarios = scenarios;
let default_value = result?;
let heuristic_upper = self.tree.node(id).heuristic_upper;
let count = count_of(&self.tree.node(id).scenarios);
let initial = self.initial_bounds(depth, default_value, heuristic_upper, count);
let node = self.tree.node_mut(id);
node.default_value = default_value;
node.upper = initial.upper;
node.default_utility = initial.ell;
node.mu = initial.mu;
node.ell = initial.ell;
node.fixed = false;
}
for id in (0..self.tree.nodes.len()).rev() {
self.back_up(u32::try_from(id).expect("at most u32::MAX nodes"));
}
Ok(())
}
fn run(&mut self) -> Result<Status, Error<P::State>> {
while self.gap(ROOT) > self.target_gap {
self.stats.nodes = self.tree.nodes.len() as u64;
if self.budget.exhausted(&self.stats) {
return Ok(Status::BudgetExhausted);
}
self.stats.simulations += 1;
let leaf = self.explore()?;
self.back_up_path(leaf);
self.report_progress();
}
self.stats.nodes = self.tree.nodes.len() as u64;
Ok(Status::Converged)
}
fn explore(&mut self) -> Result<u32, Error<P::State>> {
let mut node = ROOT;
loop {
if self.tree.node(node).depth - self.root_depth > self.max_depth {
self.tree.make_default(node);
return Ok(node);
}
if self.tree.node(node).fixed
|| self.excess_uncertainty(node) <= 0.0
|| self.prune(node)
{
return Ok(node);
}
if self.tree.node(node).first_branch == UNEXPANDED {
self.expand(node)?;
}
let Some(child) = self.most_uncertain_child(node) else {
return Ok(node);
};
node = child;
}
}
fn most_uncertain_child(&self, node: u32) -> Option<u32> {
let (action, _) = self.best_action(node, |n| n.mu);
let branch = &self.tree.branches_of(node, self.actions.len())[action];
branch
.children
.iter()
.map(|&(_, child)| (child, self.excess_uncertainty(child)))
.fold(None, |best: Option<(u32, f64)>, (child, e)| match best {
Some((_, best_e)) if best_e >= e => best,
_ => Some((child, e)),
})
.map(|(child, _)| child)
}
fn gap(&self, node: u32) -> f64 {
let node = self.tree.node(node);
node.mu - node.ell
}
fn excess_uncertainty(&self, node: u32) -> f64 {
self.gap(node) - self.weight(node) * self.xi * self.gap(ROOT)
}
fn weight(&self, node: u32) -> f64 {
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let count = self.tree.node(node).scenarios.len() as f64;
count / self.scenarios
}
fn prune(&mut self, node: u32) -> bool {
let mut current = node;
let mut blocked = false;
while self.is_blocked(current) {
self.tree.make_default(current);
self.back_up_path(current);
blocked = true;
match self.tree.node(current).parent {
Some(parent) => current = parent,
None => break,
}
}
blocked
}
fn is_blocked(&self, node: u32) -> bool {
let depth = self.tree.node(node).depth;
let mut ancestor = self.tree.node(node).parent;
while let Some(id) = ancestor {
let candidate = self.tree.node(id);
let potential = self.weight(id)
* self.power(candidate.depth)
* (candidate.upper - candidate.default_value);
#[expect(
clippy::cast_precision_loss,
reason = "depths are bounded by max_depth, far below 2^53"
)]
let cost = self.lambda * (depth - candidate.depth) as f64;
if potential <= cost {
return true;
}
ancestor = candidate.parent;
}
false
}
fn expand(&mut self, node: u32) -> Result<(), Error<P::State>> {
let scenarios = mem::take(&mut self.tree.node_mut(node).scenarios);
let depth = self.tree.node(node).depth;
let first = u32::try_from(self.tree.branches.len()).expect("at most u32::MAX branches");
let mut result = Ok(());
for position in 0..self.actions.len() {
result = self.add_branch(node, depth, &scenarios, position);
if result.is_err() {
break;
}
}
let entry = self.tree.node_mut(node);
entry.scenarios = scenarios;
if result.is_ok() {
entry.first_branch = first;
} else {
self.tree.branches.truncate(first as usize);
}
result
}
fn add_branch(
&mut self,
node: u32,
depth: usize,
scenarios: &[(u32, P::State)],
position: usize,
) -> Result<(), Error<P::State>> {
let mut reward_sum = 0.0;
let mut groups: Vec<(P::Observation, Particles<P::State>)> = Vec::new();
for (scenario, state) in scenarios {
let mut rng = self.stream(*scenario, depth, false);
let step = self.pomdp.step(state, &self.actions[position], &mut rng);
self.stats.steps += 1;
check_reward(state, step.reward)?;
reward_sum += step.reward;
if step.terminal {
continue;
}
match groups
.iter_mut()
.find(|(seen, _)| *seen == step.observation)
{
Some((_, group)) => group.push((*scenario, step.state)),
None => groups.push((step.observation, alloc::vec![(*scenario, step.state)])),
}
}
let mut children = Vec::with_capacity(groups.len());
for (observation, group) in groups {
children.push((observation, self.add_node(Some(node), depth + 1, group)?));
}
self.tree.branches.push(Branch {
reward_sum,
children,
});
Ok(())
}
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.nodes.len() as u64;
let root = self.tree.node(ROOT);
let (value, gap) = (root.ell, root.mu - root.ell);
self.observer.observe(Event::TreeProgress {
stats: self.stats,
value,
gap: Some(gap),
});
}
}
fn add_node(
&mut self,
parent: Option<u32>,
depth: usize,
scenarios: Vec<(u32, P::State)>,
) -> Result<u32, Error<P::State>> {
let default_value = self.default_value(&scenarios, depth)?;
let mut upper_sum = 0.0;
for (_, state) in &scenarios {
let bound = (self.upper)(state);
if !bound.is_finite() {
return Err(Error::InvalidHeuristic {
state: state.clone(),
});
}
upper_sum += bound;
}
let heuristic_upper = upper_sum / count_of(&scenarios);
self.stats.depth = self.stats.depth.max((depth - self.root_depth) as u64);
let initial =
self.initial_bounds(depth, default_value, heuristic_upper, count_of(&scenarios));
Ok(self.tree.push(Node {
depth,
parent,
scenarios,
heuristic_upper,
upper: initial.upper,
default_value,
default_utility: initial.ell,
mu: initial.mu,
ell: initial.ell,
first_branch: UNEXPANDED,
fixed: false,
}))
}
fn default_value(
&mut self,
scenarios: &[(u32, P::State)],
depth: usize,
) -> Result<f64, Error<P::State>> {
let mut sum = 0.0;
for (scenario, state) in scenarios {
sum += self.simulate_default(*scenario, state.clone(), depth)?;
}
Ok(sum / count_of(scenarios))
}
fn initial_bounds(
&self,
depth: usize,
default_value: f64,
heuristic_upper: f64,
count: f64,
) -> Bounds {
let upper = heuristic_upper.max(default_value);
let relative = (depth - self.root_depth).min(self.max_depth + 1);
let scale = count / self.scenarios * self.powers[relative];
let default_utility = scale * default_value;
Bounds {
mu: default_utility.max(scale * upper - self.lambda),
ell: default_utility,
upper,
}
}
fn power(&self, depth: usize) -> f64 {
self.powers[depth - self.root_depth]
}
fn simulate_default(
&mut self,
scenario: u32,
mut state: P::State,
depth: usize,
) -> Result<f64, Error<P::State>> {
let mut total = 0.0;
let mut weight = 1.0;
for step_depth in depth..=self.root_depth + self.max_depth {
let mut choice = self.stream(scenario, step_depth, true);
let position = self.default.action(&state, self.actions.len(), &mut choice);
let mut rng = self.stream(scenario, step_depth, false);
let step = self.pomdp.step(&state, &self.actions[position], &mut rng);
self.stats.steps += 1;
check_reward(&state, step.reward)?;
total += weight * step.reward;
if step.terminal {
break;
}
weight *= self.discount;
state = step.state;
}
Ok(total)
}
fn stream(&self, scenario: u32, depth: usize, policy: bool) -> SplitMix64 {
let slot = 2 * depth as u64 + u64::from(policy);
SplitMix64::new(derive_seed(self.seed, u64::from(scenario), slot))
}
fn back_up_path(&mut self, node: u32) {
let mut current = Some(node);
while let Some(id) = current {
self.back_up(id);
self.stats.backups += 1;
current = self.tree.node(id).parent;
}
}
fn back_up(&mut self, id: u32) {
let node = self.tree.node(id);
if node.fixed || node.first_branch == UNEXPANDED {
return;
}
let (mut mu, mut ell, mut upper) = (
node.default_utility,
node.default_utility,
f64::NEG_INFINITY,
);
for branch in self.tree.branches_of(id, self.actions.len()) {
let bounds = self.branch_bounds(id, branch);
mu = mu.max(bounds.mu);
ell = ell.max(bounds.ell);
upper = upper.max(bounds.upper);
}
let node = self.tree.node_mut(id);
node.mu = mu;
node.ell = ell;
node.upper = upper.max(node.default_value);
}
fn branch_bounds(&self, node: u32, branch: &Branch<P::Observation>) -> Bounds {
let entry = self.tree.node(node);
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let count = entry.scenarios.len() as f64;
let rho = self.power(entry.depth) * branch.reward_sum / self.scenarios - self.lambda;
let mut bounds = Bounds {
mu: rho,
ell: rho,
upper: branch.reward_sum / count,
};
for &(_, child) in &branch.children {
let child = self.tree.node(child);
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let share = child.scenarios.len() as f64 / count;
bounds.mu += child.mu;
bounds.ell += child.ell;
bounds.upper += self.discount * share * child.upper;
}
bounds
}
fn best_action(&self, node: u32, key: impl Fn(&Bounds) -> f64) -> (usize, f64) {
self.tree
.branches_of(node, self.actions.len())
.iter()
.enumerate()
.map(|(position, branch)| (position, key(&self.branch_bounds(node, branch))))
.fold((0, f64::NEG_INFINITY), |best, candidate| {
if candidate.1 > best.1 {
candidate
} else {
best
}
})
}
fn recommend(&mut self, status: Status) -> Plan<P::Action> {
let root = self.tree.node(ROOT);
let value = root.ell;
let default_utility = root.default_utility;
let position = if root.first_branch == UNEXPANDED {
None
} else {
Some(self.best_action(ROOT, |b| b.ell))
.filter(|&(_, ell)| ell >= default_utility)
.map(|(position, _)| position)
};
let position = position.unwrap_or_else(|| self.default_action());
Plan {
action: self.actions[position].clone(),
value,
status,
stats: self.stats,
}
}
fn default_action(&mut self) -> usize {
let (scenario, state) = self.tree.node(ROOT).scenarios[0].clone();
let mut choice = self.stream(scenario, self.root_depth, true);
self.default.action(&state, self.actions.len(), &mut choice)
}
}
type Particles<S> = Vec<(u32, S)>;
fn count_of<S>(scenarios: &[(u32, S)]) -> f64 {
#[expect(
clippy::cast_precision_loss,
reason = "scenario counts beyond 2^53 are far outside any memory budget"
)]
let count = scenarios.len() as f64;
count
}
#[derive(Debug, Clone, Copy)]
struct Bounds {
mu: f64,
ell: f64,
upper: f64,
}
fn powers(gamma: f64, last: usize) -> Vec<f64> {
let mut powers = Vec::with_capacity(last + 1);
let mut power = 1.0;
for _ in 0..=last {
powers.push(power);
power *= gamma;
}
powers
}
#[cfg(test)]
mod tests {
use rand_core::Rng;
use super::{Despot, DespotConfig, ROOT};
use crate::pomdp::{Pomdp, Step, UniformRandom};
use crate::rng::unit_interval;
struct Coin;
impl Pomdp for Coin {
type State = bool;
type Action = u8;
type Observation = Option<bool>;
fn actions(&self, mut emit: impl FnMut(u8)) {
emit(0);
emit(1);
emit(2);
}
fn step<R: Rng + ?Sized>(
&self,
heads: &bool,
action: &u8,
rng: &mut R,
) -> Step<bool, Option<bool>> {
if *action == 0 {
let truthful = unit_interval(rng) < 0.9;
return Step::new(*heads, Some(*heads == truthful), -1.0);
}
let right = *heads == (*action == 1);
Step::new(*heads, None, if right { 10.0 } else { -10.0 }).terminal()
}
}
fn check_bounds(regularization: f64, explorations: usize) {
let config = DespotConfig {
scenarios: 50,
max_depth: 8,
regularization,
..DespotConfig::default()
};
let mut search = Despot::new(
&Coin,
&[true, false],
UniformRandom,
|_: &bool| 10.0,
config,
)
.expect("valid input");
let (mut mu, mut ell) = (search.tree.node(ROOT).mu, search.tree.node(ROOT).ell);
for _ in 0..explorations {
let leaf = search.explore().expect("valid model");
search.back_up_path(leaf);
for node in &search.tree.nodes {
assert!(node.ell <= node.mu + 1e-12, "ell above mu");
}
let root = search.tree.node(ROOT);
assert!(
root.mu <= mu + 1e-12,
"root mu rose from {mu} to {}",
root.mu
);
if regularization == 0.0 {
assert!(
root.ell >= ell - 1e-12,
"root ell fell from {ell} to {}",
root.ell
);
}
(mu, ell) = (root.mu, root.ell);
}
assert!(search.tree.nodes.len() > 1, "the tree never grew");
}
#[test]
fn bounds_stay_ordered_and_monotone() {
check_bounds(0.0, 200);
}
#[test]
fn bounds_stay_ordered_with_regularization() {
check_bounds(0.5, 200);
}
fn assert_leaves_match_a_fresh_build<U, V>(
search: &Despot<'_, Coin, UniformRandom, U>,
fresh: &mut Despot<'_, Coin, UniformRandom, V>,
) where
U: FnMut(&bool) -> f64,
V: FnMut(&bool) -> f64,
{
for node in &search.tree.nodes {
assert!(node.ell <= node.mu + 1e-12, "ell above mu");
if node.first_branch != super::UNEXPANDED {
continue;
}
let id = fresh
.add_node(None, node.depth, node.scenarios.clone())
.expect("valid model");
let built = fresh.tree.node(id);
assert_eq!(built.mu.to_bits(), node.mu.to_bits());
assert_eq!(built.ell.to_bits(), node.ell.to_bits());
assert_eq!(built.upper.to_bits(), node.upper.to_bits());
assert_eq!(built.default_value.to_bits(), node.default_value.to_bits());
}
}
fn assert_replay_rebuilds_the_kept_tree<U: FnMut(&bool) -> f64>(
search: &Despot<'_, Coin, UniformRandom, U>,
config: DespotConfig,
) {
let scenarios = search.tree.node(ROOT).scenarios.clone();
let mut replay =
Despot::with_root(&Coin, scenarios, 1, UniformRandom, |_: &bool| 10.0, config)
.expect("valid input");
for id in 0..search.tree.nodes.len() {
let id = u32::try_from(id).expect("small tree");
if search.tree.node(id).first_branch != super::UNEXPANDED {
replay.expand(id).expect("valid model");
}
}
for id in (0..replay.tree.nodes.len()).rev() {
replay.back_up(u32::try_from(id).expect("small tree"));
}
assert_eq!(replay.tree.nodes.len(), search.tree.nodes.len());
for (kept, built) in search.tree.nodes.iter().zip(&replay.tree.nodes) {
assert_eq!(kept.parent, built.parent);
assert_eq!(kept.first_branch, built.first_branch);
assert_eq!(kept.scenarios, built.scenarios);
assert_eq!(kept.mu.to_bits(), built.mu.to_bits());
assert_eq!(kept.ell.to_bits(), built.ell.to_bits());
assert_eq!(kept.upper.to_bits(), built.upper.to_bits());
}
}
#[test]
fn rerooted_leaves_match_a_fresh_build() {
let config = DespotConfig {
scenarios: 60,
max_depth: 6,
regularization: 0.1,
..DespotConfig::default()
};
let mut search = Despot::new(
&Coin,
&[true, false],
UniformRandom,
|_: &bool| 10.0,
config,
)
.expect("valid input");
search.plan().expect("valid model");
search.advance(&0, &Some(true)).expect("a seen history");
assert_eq!(search.root_depth, 1);
assert!(search.tree_size() > 1, "the subtree is kept");
let scenarios = search.tree.node(ROOT).scenarios.clone();
let mut fresh =
Despot::with_root(&Coin, scenarios, 1, UniformRandom, |_: &bool| 10.0, config)
.expect("valid input");
assert_leaves_match_a_fresh_build(&search, &mut fresh);
assert_replay_rebuilds_the_kept_tree(&search, config);
let root = search.tree.node(ROOT);
assert!(root.parent.is_none());
let fresh_root = fresh.tree.node(ROOT);
assert_eq!(
fresh_root.default_value.to_bits(),
root.default_value.to_bits()
);
assert!(
root.mu <= fresh_root.mu + 1e-12,
"backed-up mu is at most the initial one"
);
assert_eq!(search.plan().expect("valid model").action, 1, "call heads");
}
#[test]
fn advance_to_an_unseen_history_needs_a_reset() {
use crate::Error;
let mut search = Despot::new(
&Coin,
&[true, false],
UniformRandom,
|_: &bool| 10.0,
DespotConfig::default(),
)
.expect("valid input");
assert_eq!(search.advance(&0, &Some(true)), Err(Error::UnseenHistory));
assert_eq!(search.plan(), Err(Error::UnseenHistory));
search.reset(&[true, false]).expect("valid input");
search.plan().expect("valid model");
assert_eq!(search.advance(&1, &Some(true)), Err(Error::UnseenHistory));
assert_eq!(search.advance(&7, &None), Err(Error::UnseenHistory));
assert_eq!(search.reset(&[]), Err(Error::EmptyBelief));
search.reset(&[true]).expect("valid input");
assert_eq!(search.tree_size(), 1);
assert_eq!(search.plan().expect("valid model").action, 1, "call heads");
}
#[test]
fn same_seed_same_tree() {
let build = || {
let config = DespotConfig {
scenarios: 30,
max_depth: 6,
..DespotConfig::default()
}
.with_budget(crate::Limits {
max_trials: Some(50),
..DespotConfig::DEFAULT_LIMITS
});
let mut search = Despot::new(
&Coin,
&[true, false],
UniformRandom,
|_: &bool| 10.0,
config,
)
.expect("valid input");
search.run().expect("valid model");
search
.tree
.nodes
.iter()
.map(|n| {
(
n.depth,
n.scenarios.clone(),
n.mu.to_bits(),
n.ell.to_bits(),
)
})
.collect::<alloc::vec::Vec<_>>()
};
assert_eq!(build(), build());
}
}