use crate::{Node, SearchResult, WidthProblem, extract_plan};
pub fn rollout_iw<P: WidthProblem>(problem: &P, seed: u64) -> SearchResult<P::Action> {
let mut tree = Tree::new(problem, seed);
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.meta[0].solved {
if let Some(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,
}
enum Verdict {
Continue,
Prune,
}
struct Tree<'p, P: WidthProblem> {
problem: &'p P,
nodes: Vec<Node<P::State, P::Action>>,
meta: Vec<Meta>,
depth_of: Vec<usize>,
rng: u64,
feats: Vec<u32>,
succ: Vec<(P::Action, P::State)>,
result: SearchResult<P::Action>,
}
impl<'p, P: WidthProblem> Tree<'p, P> {
fn new(problem: &'p P, seed: u64) -> Self {
Self {
problem,
nodes: Vec::new(),
meta: Vec::new(),
depth_of: vec![usize::MAX; problem.num_features()],
rng: seed,
feats: Vec::new(),
succ: Vec::new(),
result: SearchResult {
plan: None,
expanded: 0,
generated: 1,
},
}
}
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);
self.meta[0].visited = true;
}
fn rollout(&mut self) -> Option<usize> {
let mut n = 0;
loop {
if self.meta[n].children.is_none() {
if let Some(goal) = self.expand(n) {
return Some(goal);
}
}
let Some(child) = self.pick_unsolved_child(n) else {
self.solve(n);
return None;
};
n = child;
if let Verdict::Prune = self.novelty(n) {
self.solve(n);
return None;
}
}
}
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);
let depth = self.meta[n].depth + 1;
let mut children = Vec::with_capacity(succ.len());
let mut goal = None;
for (action, state) in succ.drain(..) {
self.result.generated += 1;
let is_goal = self.problem.is_goal(&state);
let child = self.push(state, Some(n), Some(action), depth);
children.push(child);
if is_goal {
goal.get_or_insert(child);
}
}
self.succ = succ;
self.meta[n].children = Some(children);
goal
}
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> {
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 = usize::try_from(self.next_random() % unsolved as u64).expect("below a usize");
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,
) -> usize {
self.nodes.push(Node {
state,
parent,
action,
});
self.meta.push(Meta {
depth,
children: None,
solved: false,
visited: false,
});
self.nodes.len() - 1
}
fn next_random(&mut self) -> u64 {
self.rng = self.rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.rng;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
}
#[cfg(test)]
mod tests {
use super::*;
struct Line {
len: u32,
}
impl WidthProblem for Line {
type State = u32;
type Action = i8;
fn initial_state(&self) -> u32 {
0
}
fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
if *s > 0 {
out.push((-1, s - 1));
}
if *s < self.len {
out.push((1, s + 1));
}
}
fn features(&self, s: &u32, out: &mut Vec<u32>) {
out.push(*s);
}
fn num_features(&self) -> usize {
self.len as usize + 1
}
fn is_goal(&self, s: &u32) -> bool {
*s == self.len
}
}
#[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 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
}
}
}