use alloc::collections::VecDeque;
use alloc::vec::Vec;
pub(super) const ROOT: u32 = 0;
const UNEXPANDED: u32 = u32::MAX;
#[derive(Debug, Clone)]
struct History {
visits: u64,
first_action: u32,
}
#[derive(Debug, Clone)]
struct ActionNode<O> {
visits: u64,
value: f64,
children: Vec<(O, u32)>,
}
#[derive(Debug, Clone)]
pub(super) struct Tree<O> {
actions: usize,
histories: Vec<History>,
action_nodes: Vec<ActionNode<O>>,
}
impl<O: PartialEq> Tree<O> {
pub(super) fn new(actions: usize) -> Self {
let mut tree = Self {
actions,
histories: Vec::new(),
action_nodes: Vec::new(),
};
tree.add_history();
tree.expand(ROOT);
tree
}
pub(super) fn len(&self) -> usize {
self.histories.len()
}
pub(super) fn is_expanded(&self, history: u32) -> bool {
self.histories[history as usize].first_action != UNEXPANDED
}
pub(super) fn expand(&mut self, history: u32) {
let first = u32::try_from(self.action_nodes.len()).expect("at most u32::MAX action nodes");
self.histories[history as usize].first_action = first;
for _ in 0..self.actions {
self.action_nodes.push(ActionNode {
visits: 0,
value: 0.0,
children: Vec::new(),
});
}
}
pub(super) fn position(&self, history: u32, action: u32) -> usize {
(action - self.histories[history as usize].first_action) as usize
}
pub(super) fn select(&mut self, history: u32, exploration: f64) -> u32 {
let node = &mut self.histories[history as usize];
node.visits += 1;
let first = node.first_action;
#[expect(
clippy::cast_precision_loss,
reason = "visit counts beyond 2^53 only lose precision in the exploration bonus"
)]
let log_visits = libm::log(node.visits as f64);
let mut best = (first, f64::NEG_INFINITY);
for (offset, entry) in self.action_nodes[first as usize..][..self.actions]
.iter()
.enumerate()
{
let index = first + u32::try_from(offset).expect("action positions fit u32");
if entry.visits == 0 {
return index;
}
#[expect(
clippy::cast_precision_loss,
reason = "visit counts beyond 2^53 only lose precision in the exploration bonus"
)]
let score = entry.value + exploration * libm::sqrt(log_visits / entry.visits as f64);
if score > best.1 {
best = (index, score);
}
}
best.0
}
pub(super) fn child(&mut self, action: u32, observation: O) -> u32 {
let children = &self.action_nodes[action as usize].children;
if let Some(&(_, id)) = children.iter().find(|(seen, _)| *seen == observation) {
return id;
}
let id = self.add_history();
self.action_nodes[action as usize]
.children
.push((observation, id));
id
}
pub(super) fn record(&mut self, action: u32, value: f64) {
let node = &mut self.action_nodes[action as usize];
node.visits += 1;
#[expect(
clippy::cast_precision_loss,
reason = "visit counts beyond 2^53 only lose precision in the running mean"
)]
let weight = 1.0 / node.visits as f64;
node.value += (value - node.value) * weight;
}
pub(super) fn best_root_action(&self) -> (usize, f64) {
let first = self.histories[ROOT as usize].first_action as usize;
let mut best = (0, f64::NAN);
for (position, entry) in self.action_nodes[first..][..self.actions]
.iter()
.enumerate()
{
if entry.visits > 0 && (best.1.is_nan() || entry.value > best.1) {
best = (position, entry.value);
}
}
best
}
pub(super) fn child_of_root(&self, position: usize, observation: &O) -> Option<u32> {
let first = self.histories[ROOT as usize].first_action as usize;
self.action_nodes[first + position]
.children
.iter()
.find(|(seen, _)| seen == observation)
.map(|&(_, id)| id)
}
pub(super) fn into_subtree(mut self, root: u32) -> Self {
let mut tree = Self {
actions: self.actions,
histories: Vec::new(),
action_nodes: Vec::new(),
};
let mut queue = VecDeque::from([root]);
tree.histories.push(History {
visits: self.histories[root as usize].visits,
first_action: UNEXPANDED,
});
let mut next = 0;
while let Some(old) = queue.pop_front() {
let new = next;
next += 1;
if !self.is_expanded(old) {
continue;
}
let first = self.histories[old as usize].first_action as usize;
tree.histories[new].first_action =
u32::try_from(tree.action_nodes.len()).expect("at most u32::MAX action nodes");
for index in first..first + self.actions {
let node = &mut self.action_nodes[index];
let mut children = core::mem::take(&mut node.children);
for (_, child) in &mut children {
queue.push_back(*child);
*child = tree.add_history_with(self.histories[*child as usize].visits);
}
tree.action_nodes.push(ActionNode {
visits: node.visits,
value: node.value,
children,
});
}
}
if !tree.is_expanded(ROOT) {
tree.expand(ROOT);
}
tree
}
fn add_history_with(&mut self, visits: u64) -> u32 {
let id = self.add_history();
self.histories[id as usize].visits = visits;
id
}
fn add_history(&mut self) -> u32 {
let id = u32::try_from(self.histories.len()).expect("at most u32::MAX histories");
self.histories.push(History {
visits: 0,
first_action: UNEXPANDED,
});
id
}
}
#[cfg(test)]
mod tests {
use super::{ROOT, Tree};
#[test]
fn select_tries_every_action_then_exploits() {
let mut tree: Tree<u8> = Tree::new(2);
let first = tree.select(ROOT, 0.0);
tree.record(first, 1.0);
let second = tree.select(ROOT, 0.0);
assert_ne!(first, second);
tree.record(second, 5.0);
assert_eq!(tree.select(ROOT, 0.0), second);
assert_eq!(tree.best_root_action(), (1, 5.0));
}
#[test]
fn children_are_shared_per_observation() {
let mut tree: Tree<u8> = Tree::new(1);
let action = tree.select(ROOT, 1.0);
let a = tree.child(action, 7);
assert_eq!(tree.child(action, 7), a);
assert_ne!(tree.child(action, 8), a);
assert_eq!(tree.len(), 3);
}
#[test]
fn subtree_keeps_the_history_below() {
let mut tree: Tree<u8> = Tree::new(2);
let action = tree.select(ROOT, 0.0);
tree.record(action, 3.0);
let kept = tree.child(action, 7);
let _dropped = tree.child(action, 8);
tree.expand(kept);
let below = tree.select(kept, 0.0);
tree.record(below, 4.0);
let grandchild = tree.child(below, 1);
assert_eq!(tree.len(), 4);
assert_eq!(tree.child_of_root(0, &7), Some(kept));
assert_eq!(tree.child_of_root(0, &9), None);
let mut subtree = tree.into_subtree(kept);
assert_eq!(subtree.len(), 2);
assert_eq!(subtree.best_root_action(), (0, 4.0));
assert_eq!(subtree.child_of_root(0, &1), Some(1));
let _ = grandchild;
assert!(subtree.is_expanded(ROOT));
assert!(!subtree.is_expanded(1));
assert_eq!(subtree.select(ROOT, 0.0), 1);
}
#[test]
fn subtree_of_a_leaf_is_expanded() {
let mut tree: Tree<u8> = Tree::new(2);
let action = tree.select(ROOT, 0.0);
let leaf = tree.child(action, 7);
let subtree = tree.into_subtree(leaf);
assert_eq!(subtree.len(), 1);
assert!(subtree.is_expanded(ROOT));
}
#[test]
fn untried_root_has_no_value() {
let tree: Tree<u8> = Tree::new(3);
let (position, value) = tree.best_root_action();
assert_eq!(position, 0);
assert!(value.is_nan());
}
}