use alloc::collections::VecDeque;
use alloc::vec::Vec;
pub(super) const UNEXPANDED: u32 = u32::MAX;
pub(super) const ROOT: u32 = 0;
#[derive(Debug, Clone)]
pub(super) struct Node<S> {
pub(super) depth: usize,
pub(super) parent: Option<u32>,
pub(super) scenarios: Vec<(u32, S)>,
pub(super) heuristic_upper: f64,
pub(super) upper: f64,
pub(super) default_value: f64,
pub(super) default_utility: f64,
pub(super) mu: f64,
pub(super) ell: f64,
pub(super) first_branch: u32,
pub(super) fixed: bool,
}
impl<S> Node<S> {
fn clone_without_scenarios(&self) -> Self {
Self {
depth: self.depth,
parent: self.parent,
scenarios: Vec::new(),
heuristic_upper: self.heuristic_upper,
upper: self.upper,
default_value: self.default_value,
default_utility: self.default_utility,
mu: self.mu,
ell: self.ell,
first_branch: self.first_branch,
fixed: self.fixed,
}
}
}
#[derive(Debug, Clone)]
pub(super) struct Branch<O> {
pub(super) reward_sum: f64,
pub(super) children: Vec<(O, u32)>,
}
#[derive(Debug, Clone)]
pub(super) struct Tree<S, O> {
pub(super) nodes: Vec<Node<S>>,
pub(super) branches: Vec<Branch<O>>,
}
impl<S, O> Tree<S, O> {
pub(super) fn node(&self, id: u32) -> &Node<S> {
&self.nodes[id as usize]
}
pub(super) fn node_mut(&mut self, id: u32) -> &mut Node<S> {
&mut self.nodes[id as usize]
}
pub(super) fn branches_of(&self, id: u32, actions: usize) -> &[Branch<O>] {
let first = self.node(id).first_branch as usize;
&self.branches[first..first + actions]
}
pub(super) fn push(&mut self, node: Node<S>) -> u32 {
let id = u32::try_from(self.nodes.len()).expect("at most u32::MAX nodes");
self.nodes.push(node);
id
}
pub(super) fn into_subtree(mut self, root: u32, actions: usize) -> Self {
let mut tree = Self {
nodes: Vec::new(),
branches: Vec::new(),
};
let mut queue = VecDeque::from([(root, None)]);
while let Some((old, parent)) = queue.pop_front() {
let id = u32::try_from(tree.nodes.len()).expect("at most u32::MAX nodes");
let mut node = self.nodes[old as usize].clone_without_scenarios();
node.scenarios = core::mem::take(&mut self.nodes[old as usize].scenarios);
node.parent = parent;
if node.first_branch != UNEXPANDED {
let first = node.first_branch as usize;
node.first_branch =
u32::try_from(tree.branches.len()).expect("at most u32::MAX branches");
for branch in &mut self.branches[first..first + actions] {
let mut children = core::mem::take(&mut branch.children);
for (_, child) in &mut children {
let position = tree.nodes.len() + 1 + queue.len();
queue.push_back((*child, Some(id)));
*child = u32::try_from(position).expect("at most u32::MAX nodes");
}
tree.branches.push(Branch {
reward_sum: branch.reward_sum,
children,
});
}
}
tree.nodes.push(node);
}
tree
}
pub(super) fn make_default(&mut self, id: u32) {
let node = self.node_mut(id);
node.upper = node.default_value;
node.mu = node.default_utility;
node.ell = node.default_utility;
node.fixed = true;
}
}