use crate::rng::SplitMix64;
use crate::{Node, SearchResult, WidthProblem, extract_plan};
pub fn rollout_iw<P: WidthProblem>(problem: &P, seed: u64) -> SearchResult<P::Action> {
search(problem, None::<Weights<P>>, seed)
}
pub fn pi_iw<P, F>(problem: &P, policy: F, seed: u64) -> SearchResult<P::Action>
where
P: WidthProblem,
F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
{
search(problem, Some(policy), seed)
}
type Weights<P> = fn(
&<P as WidthProblem>::State,
&[(<P as WidthProblem>::Action, <P as WidthProblem>::State)],
&mut Vec<f64>,
);
fn search<P, F>(problem: &P, policy: Option<F>, seed: u64) -> SearchResult<P::Action>
where
P: WidthProblem,
F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
{
let mut tree = Tree::new(problem, policy, seed, None);
let root = problem.initial_state();
if problem.is_goal(&root) {
tree.result.plan = Some(Vec::new());
return tree.result;
}
tree.add_root(root);
while !tree.is_exhausted() {
if let Outcome::Goal(goal) = tree.rollout() {
tree.result.plan = Some(extract_plan(&tree.nodes, goal));
break;
}
}
tree.result
}
struct Meta {
depth: usize,
children: Option<Vec<usize>>,
solved: bool,
visited: bool,
weight: f64,
}
pub(crate) enum Outcome {
Goal(usize),
Boundary(usize),
Solved,
}
pub(crate) type Partition<'a, S> = (&'a dyn Fn(&S, &mut Vec<u32>), Vec<u32>);
enum Verdict {
Continue,
Prune,
}
pub(crate) struct Tree<'p, P: WidthProblem, F> {
problem: &'p P,
partition: Option<Partition<'p, P::State>>,
policy: Option<F>,
weights: Vec<f64>,
pub nodes: Vec<Node<P::State, P::Action>>,
meta: Vec<Meta>,
depth_of: Vec<usize>,
rng: SplitMix64,
feats: Vec<u32>,
succ: Vec<(P::Action, P::State)>,
pub result: SearchResult<P::Action>,
}
impl<'p, P, F> Tree<'p, P, F>
where
P: WidthProblem,
F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
{
pub fn new(
problem: &'p P,
policy: Option<F>,
seed: u64,
partition: Option<Partition<'p, P::State>>,
) -> Self {
Self {
problem,
partition,
policy,
weights: Vec::new(),
nodes: Vec::new(),
meta: Vec::new(),
depth_of: vec![usize::MAX; problem.num_features()],
rng: SplitMix64::new(seed),
feats: Vec::new(),
succ: Vec::new(),
result: SearchResult {
plan: None,
expanded: 0,
generated: 1,
},
}
}
pub fn add_root(&mut self, root: P::State) {
self.feats.clear();
self.problem.features(&root, &mut self.feats);
for &f in &self.feats {
self.depth_of[f as usize] = 0;
}
self.push(root, None, None, 0, 0.0);
self.meta[0].visited = true;
}
pub fn is_exhausted(&self) -> bool {
self.meta[0].solved
}
pub fn rollout(&mut self) -> Outcome {
let mut n = 0;
loop {
if self.meta[n].children.is_none() {
if let Some(goal) = self.expand(n) {
return Outcome::Goal(goal);
}
}
let Some(child) = self.pick_unsolved_child(n) else {
self.solve(n);
return Outcome::Solved;
};
n = child;
if self.is_boundary(n) {
self.solve(n);
return Outcome::Boundary(n);
}
if let Verdict::Prune = self.novelty(n) {
self.solve(n);
return Outcome::Solved;
}
}
}
fn is_boundary(&mut self, n: usize) -> bool {
let Some((high, root_features)) = &self.partition else {
return false;
};
self.feats.clear();
high(&self.nodes[n].state, &mut self.feats);
self.feats.sort_unstable();
self.feats.dedup();
self.feats != *root_features
}
fn expand(&mut self, n: usize) -> Option<usize> {
self.result.expanded += 1;
let mut succ = std::mem::take(&mut self.succ);
succ.clear();
self.problem.successors(&self.nodes[n].state, &mut succ);
self.ask_policy(n, &succ);
let depth = self.meta[n].depth + 1;
let mut children = Vec::with_capacity(succ.len());
let mut goal = None;
for (i, (action, state)) in succ.drain(..).enumerate() {
self.result.generated += 1;
let is_goal = self.problem.is_goal(&state);
let weight = self.weights.get(i).copied().unwrap_or(1.0);
let child = self.push(state, Some(n), Some(action), depth, weight);
children.push(child);
if is_goal {
goal.get_or_insert(child);
}
}
self.succ = succ;
self.meta[n].children = Some(children);
goal
}
fn ask_policy(&mut self, n: usize, succ: &[(P::Action, P::State)]) {
self.weights.clear();
let Some(policy) = self.policy.as_mut() else {
return;
};
policy(&self.nodes[n].state, succ, &mut self.weights);
assert_eq!(
self.weights.len(),
succ.len(),
"policy must push one weight per successor"
);
assert!(
self.weights.iter().all(|w| w.is_finite() && *w >= 0.0),
"policy weights must be finite and non-negative"
);
assert!(
self.weights.iter().sum::<f64>().is_finite(),
"policy weights must have a finite sum"
);
}
fn novelty(&mut self, n: usize) -> Verdict {
let depth = self.meta[n].depth;
self.feats.clear();
self.problem.features(&self.nodes[n].state, &mut self.feats);
if self.meta[n].visited {
let kept = self
.feats
.iter()
.any(|&f| self.depth_of[f as usize] == depth);
return if kept {
Verdict::Continue
} else {
Verdict::Prune
};
}
self.meta[n].visited = true;
let mut novel = false;
for &f in &self.feats {
let d = &mut self.depth_of[f as usize];
if depth < *d {
*d = depth;
novel = true;
}
}
if novel {
Verdict::Continue
} else {
Verdict::Prune
}
}
fn pick_unsolved_child(&mut self, n: usize) -> Option<usize> {
if self.policy.is_some() {
if let Some(child) = self.pick_weighted_child(n) {
return Some(child);
}
}
self.pick_uniform_child(n)
}
fn pick_weighted_child(&mut self, n: usize) -> Option<usize> {
let unit = self.rng.unit();
let meta = &self.meta;
let candidates = || {
meta[n]
.children
.as_deref()
.unwrap_or_default()
.iter()
.copied()
.filter(|&c| !meta[c].solved && meta[c].weight > 0.0)
};
let total: f64 = candidates().map(|c| meta[c].weight).sum();
let last = candidates().next_back()?;
let mut target = unit * total;
for c in candidates() {
target -= meta[c].weight;
if target < 0.0 {
return Some(c);
}
}
Some(last)
}
fn pick_uniform_child(&mut self, n: usize) -> Option<usize> {
let count_unsolved = |t: &Self| {
let children = t.meta[n].children.as_deref().unwrap_or_default();
children.iter().filter(|&&c| !t.meta[c].solved).count()
};
let unsolved = count_unsolved(self);
if unsolved == 0 {
return None;
}
let pick = self.rng.below(unsolved);
self.meta[n]
.children
.as_deref()
.unwrap_or_default()
.iter()
.copied()
.filter(|&c| !self.meta[c].solved)
.nth(pick)
}
fn solve(&mut self, mut n: usize) {
self.meta[n].solved = true;
while let Some(p) = self.nodes[n].parent {
let children = self.meta[p].children.as_deref().unwrap_or_default();
if !children.iter().all(|&c| self.meta[c].solved) {
return;
}
self.meta[p].solved = true;
n = p;
}
}
fn push(
&mut self,
state: P::State,
parent: Option<usize>,
action: Option<P::Action>,
depth: usize,
weight: f64,
) -> usize {
self.nodes.push(Node {
state,
parent,
action,
});
self.meta.push(Meta {
depth,
children: None,
solved: false,
visited: false,
weight,
});
self.nodes.len() - 1
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_problems::Line;
#[test]
fn reaches_a_width_one_goal_for_every_seed() {
let line = Line { len: 6 };
for seed in 0..50 {
let plan = rollout_iw(&line, seed).plan.expect("width-1 goal");
assert_eq!(plan, [1; 6], "seed {seed}");
}
}
#[test]
fn a_greedy_policy_walks_straight_to_the_goal() {
let line = Line { len: 6 };
let towards_goal = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
out.extend(succ.iter().map(|&(a, _)| if a > 0 { 1.0 } else { 0.0 }));
};
for seed in 0..20 {
let r = pi_iw(&line, towards_goal, seed);
assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]), "seed {seed}");
assert_eq!(r.expanded, 6, "seed {seed}");
}
}
#[test]
fn zero_weight_children_are_tried_last() {
let line = Line { len: 6 };
let away = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
out.extend(succ.iter().map(|&(a, _)| if a < 0 { 1.0 } else { 0.0 }));
};
for seed in 0..20 {
let plan = pi_iw(&line, away, seed).plan.expect("width-1 goal");
assert_eq!(plan, [1; 6], "seed {seed}");
}
}
#[test]
#[should_panic(expected = "finite and non-negative")]
fn rejects_negative_weights() {
let negative = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
out.extend(succ.iter().map(|_| -1.0));
};
pi_iw(&Line { len: 3 }, negative, 0);
}
#[test]
#[should_panic(expected = "finite sum")]
fn rejects_weights_with_an_infinite_sum() {
let huge = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
out.extend(succ.iter().map(|_| f64::MAX));
};
pi_iw(&Line { len: 3 }, huge, 0);
}
#[test]
#[should_panic(expected = "one weight per successor")]
fn rejects_a_missing_weight() {
pi_iw(
&Line { len: 3 },
|_: &u32, _: &[(i8, u32)], _: &mut Vec<f64>| {},
0,
);
}
#[test]
fn gives_up_when_the_root_is_solved() {
let r = rollout_iw(&NoGoal(Line { len: 6 }), 3);
assert!(r.plan.is_none());
assert_eq!(r.expanded, 7, "every position expanded once");
}
struct NoGoal(Line);
impl WidthProblem for NoGoal {
type State = u32;
type Action = i8;
fn initial_state(&self) -> u32 {
self.0.initial_state()
}
fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
self.0.successors(s, out);
}
fn features(&self, s: &u32, out: &mut Vec<u32>) {
self.0.features(s, out);
}
fn num_features(&self) -> usize {
self.0.num_features()
}
fn is_goal(&self, _: &u32) -> bool {
false
}
}
}