use std::cell::RefCell;
use std::collections::HashMap;
use crate::rng::SplitMix64;
use crate::rollout::{Outcome, Tree};
use crate::{SearchResult, WidthProblem, extract_plan, sorted_set};
pub fn pi_hiw<P, H, F>(
problem: &P,
high: H,
num_high: usize,
policy: F,
tau: f64,
seed: u64,
) -> SearchResult<P::Action>
where
P: WidthProblem,
H: Fn(&P::State, &mut Vec<u32>),
F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
{
assert!(
tau.is_finite() && tau > 0.0,
"tau must be finite and positive"
);
let root = problem.initial_state();
if problem.is_goal(&root) {
return SearchResult {
plan: Some(Vec::new()),
expanded: 0,
generated: 1,
};
}
let policy = RefCell::new(policy);
let shared = |s: &P::State, succ: &[(P::Action, P::State)], out: &mut Vec<f64>| {
(policy.borrow_mut())(s, succ, out);
};
let mut search = HighSearch {
problem,
high: &high,
policy: shared,
tau,
rng: SplitMix64::new(seed),
nodes: Vec::new(),
open: Vec::new(),
counts: HashMap::new(),
depth_of: vec![usize::MAX; num_high],
owner: vec![None; num_high],
};
search.add_node(root, None, 0);
let goal = search.run();
let mut result = search.totals();
result.plan = goal.map(|(h, j)| search.plan(h, j));
result
}
struct HighNode<'p, P: WidthProblem, F> {
tree: Tree<'p, P, F>,
features: Vec<u32>,
origin: Option<(usize, usize)>,
depth: usize,
novel: Vec<u32>,
children: Vec<usize>,
open: bool,
}
struct HighSearch<'p, P: WidthProblem, F> {
problem: &'p P,
high: &'p dyn Fn(&P::State, &mut Vec<u32>),
policy: F,
tau: f64,
rng: SplitMix64,
nodes: Vec<HighNode<'p, P, F>>,
open: Vec<usize>,
counts: HashMap<Vec<u32>, usize>,
depth_of: Vec<usize>,
owner: Vec<Option<usize>>,
}
impl<P, F> HighSearch<'_, P, F>
where
P: WidthProblem,
F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>) + Copy,
{
fn run(&mut self) -> Option<(usize, usize)> {
while !self.open.is_empty() {
let mut n = self.select();
loop {
let features = self.nodes[n].features.clone();
*self.counts.entry(features).or_default() += 1;
match self.successor(n) {
Step::Goal(j) => return Some((n, j)),
Step::Exhausted => {
self.close(n);
break;
}
Step::Boundary(j) => {
let Some(s) = self.admit(n, j) else {
break;
};
n = s;
}
}
}
}
None
}
fn select(&mut self) -> usize {
let exponent = |n: usize| {
let c = self
.counts
.get(&self.nodes[n].features)
.copied()
.unwrap_or(0);
#[expect(clippy::cast_precision_loss, reason = "counts stay far below 2^53")]
let c = c as f64;
1.0 / (self.tau * (c + 1.0))
};
let max = self
.open
.iter()
.map(|&n| exponent(n))
.fold(f64::MIN, f64::max);
let weights: Vec<f64> = self
.open
.iter()
.map(|&n| (exponent(n) - max).exp())
.collect();
let mut target = self.rng.unit() * weights.iter().sum::<f64>();
for (&n, w) in self.open.iter().zip(&weights) {
target -= w;
if target < 0.0 {
return n;
}
}
*self
.open
.last()
.expect("select is only called with open nodes")
}
fn successor(&mut self, n: usize) -> Step {
let tree = &mut self.nodes[n].tree;
while !tree.is_exhausted() {
match tree.rollout() {
Outcome::Goal(j) => return Step::Goal(j),
Outcome::Boundary(j) => return Step::Boundary(j),
Outcome::Solved => {}
}
}
Step::Exhausted
}
fn admit(&mut self, n: usize, j: usize) -> Option<usize> {
let state = self.nodes[n].tree.nodes[j].state.clone();
let features = sorted_set(|out| (self.high)(&state, out));
let depth = self.nodes[n].depth + 1;
let novel: Vec<u32> = features
.iter()
.copied()
.filter(|&f| depth < self.depth_of[f as usize])
.collect();
if novel.is_empty() {
return None;
}
let s = self.add_node(state, Some((n, j)), depth);
self.nodes[n].children.push(s);
for &f in &novel {
self.take_over(f, s, depth);
}
self.nodes[s].novel = novel;
Some(s)
}
fn take_over(&mut self, f: u32, s: usize, depth: usize) {
let f_index = f as usize;
self.depth_of[f_index] = depth;
if let Some(o) = self.owner[f_index].replace(s) {
self.nodes[o].novel.retain(|&g| g != f);
if self.nodes[o].novel.is_empty() && o != 0 {
self.close_subtree(o);
}
}
}
fn add_node(&mut self, state: P::State, origin: Option<(usize, usize)>, depth: usize) -> usize {
let features = sorted_set(|out| (self.high)(&state, out));
let seed = self.rng.next_u64();
let mut tree = Tree::new(
self.problem,
Some(self.policy),
seed,
Some((self.high, features.clone())),
);
tree.add_root(state);
if origin.is_none() {
for &f in &features {
self.depth_of[f as usize] = 0;
self.owner[f as usize] = Some(0);
}
}
self.nodes.push(HighNode {
tree,
novel: if origin.is_none() {
features.clone()
} else {
Vec::new()
},
features,
origin,
depth,
children: Vec::new(),
open: true,
});
let index = self.nodes.len() - 1;
self.open.push(index);
index
}
fn close(&mut self, n: usize) {
if std::mem::replace(&mut self.nodes[n].open, false) {
self.open.retain(|&o| o != n);
}
}
fn close_subtree(&mut self, n: usize) {
let mut stack = vec![n];
while let Some(m) = stack.pop() {
self.close(m);
stack.extend(self.nodes[m].children.iter().copied());
}
}
fn plan(&self, mut h: usize, j: usize) -> Vec<P::Action> {
let mut pieces = vec![extract_plan(&self.nodes[h].tree.nodes, j)];
while let Some((parent, boundary)) = self.nodes[h].origin {
pieces.push(extract_plan(&self.nodes[parent].tree.nodes, boundary));
h = parent;
}
pieces.into_iter().rev().flatten().collect()
}
fn totals(&self) -> SearchResult<P::Action> {
let mut total = SearchResult {
plan: None,
expanded: 0,
generated: 1,
};
for node in &self.nodes {
total.expanded += node.tree.result.expanded;
total.generated += node.tree.result.generated - 1;
}
total
}
}
enum Step {
Goal(usize),
Boundary(usize),
Exhausted,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::hiw::tests::Corridor;
fn uniform<S, A>(_: &S, succ: &[(A, S)], out: &mut Vec<f64>) {
out.extend(succ.iter().map(|_| 1.0));
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "matches the high-level feature closure signature"
)]
fn key(&(_, key): &(u32, bool), out: &mut Vec<u32>) {
if key {
out.push(0);
}
}
#[test]
fn the_key_splits_the_corridor() {
let corridor = Corridor::new(5);
for seed in 0..20 {
let r = pi_hiw(&corridor, key, 1, uniform, 0.005, seed);
assert_eq!(
r.plan.as_deref(),
Some(&[1, 1, 1, 1, 1, -1, -1, -1, -1, -1][..]),
"seed {seed}"
);
}
}
#[test]
fn without_high_level_features_it_terminates() {
let none = |_: &(u32, bool), _: &mut Vec<u32>| {};
let r = pi_hiw(&Corridor::new(5), none, 0, uniform, 1.0, 3);
assert!(r.plan.is_none());
}
#[test]
#[should_panic(expected = "tau must be finite and positive")]
fn rejects_zero_tau() {
pi_hiw(&Corridor::new(2), key, 1, uniform, 0.0, 0);
}
}