Skip to main content

width_search/
rollout.rs

1use crate::{Node, SearchResult, WidthProblem, extract_plan};
2
3/// Rollout IW(1) (Bandres, Bonet & Geffner, AAAI 2018), goal-directed.
4///
5/// Builds a search tree by repeated rollouts from the root. Each rollout
6/// walks down through a random child not yet labeled solved, generating
7/// children lazily, and stops by labeling a node solved. Novelty uses the
8/// smallest depth `d[f]` at which each feature `f` was reached:
9///
10/// - a new node at depth `d` continues the rollout if `d < d[f]` for some
11///   feature `f` it makes true, and lowers `d[f]` to `d` for all of them;
12///   otherwise it is labeled solved (pruned);
13/// - a node already in the tree continues if `d == d[f]` for some feature,
14///   and is labeled solved otherwise (a shallower path took its features).
15///
16/// A node with no successors is solved; a node is solved once all of its
17/// children are. The search returns as soon as a goal state is generated,
18/// and gives up (`plan: None`) when the root is solved.
19///
20/// The paper's algorithm picks actions for a reward-maximizing agent within a
21/// time budget; this version has no budget and stops at the first goal. Like
22/// IW(1), it reaches every goal of width 1, but its plans need not be
23/// shortest. `seed` fixes the random child choices.
24pub fn rollout_iw<P: WidthProblem>(problem: &P, seed: u64) -> SearchResult<P::Action> {
25    let mut tree = Tree::new(problem, seed);
26    let root = problem.initial_state();
27    if problem.is_goal(&root) {
28        tree.result.plan = Some(Vec::new());
29        return tree.result;
30    }
31
32    tree.add_root(root);
33    while !tree.meta[0].solved {
34        if let Some(goal) = tree.rollout() {
35            tree.result.plan = Some(extract_plan(&tree.nodes, goal));
36            break;
37        }
38    }
39
40    tree.result
41}
42
43/// Per-node rollout bookkeeping, parallel to [`Tree::nodes`].
44struct Meta {
45    /// Number of actions from the root.
46    depth: usize,
47    /// Arena indices of the children; `None` until the node is expanded.
48    children: Option<Vec<usize>>,
49    /// Whether the subtree below needs no further rollouts.
50    solved: bool,
51    /// Whether a rollout has already run the novelty test on this node.
52    visited: bool,
53}
54
55/// What the novelty test says about the node a rollout just entered.
56enum Verdict {
57    /// The node is novel: continue the rollout below it.
58    Continue,
59    /// The node is not novel: label it solved and end the rollout.
60    Prune,
61}
62
63/// The search tree of a Rollout IW(1) run and its novelty table.
64struct Tree<'p, P: WidthProblem> {
65    /// The problem being searched.
66    problem: &'p P,
67    /// Node arena: states and parent links.
68    nodes: Vec<Node<P::State, P::Action>>,
69    /// Rollout data of each node, same indices as `nodes`.
70    meta: Vec<Meta>,
71    /// Smallest depth at which each feature was reached; `usize::MAX` if never.
72    depth_of: Vec<usize>,
73    /// Pseudo-random state for child selection (`SplitMix64`).
74    rng: u64,
75    /// Reused buffer for the features of a state.
76    feats: Vec<u32>,
77    /// Reused buffer for successors.
78    succ: Vec<(P::Action, P::State)>,
79    /// Node counts so far; `plan` is filled in by [`rollout_iw`].
80    result: SearchResult<P::Action>,
81}
82
83impl<'p, P: WidthProblem> Tree<'p, P> {
84    /// An empty tree for `problem`.
85    fn new(problem: &'p P, seed: u64) -> Self {
86        Self {
87            problem,
88            nodes: Vec::new(),
89            meta: Vec::new(),
90            depth_of: vec![usize::MAX; problem.num_features()],
91            rng: seed,
92            feats: Vec::new(),
93            succ: Vec::new(),
94            result: SearchResult {
95                plan: None,
96                expanded: 0,
97                generated: 1,
98            },
99        }
100    }
101
102    /// Adds the root at depth 0 and records its features at depth 0.
103    fn add_root(&mut self, root: P::State) {
104        self.feats.clear();
105        self.problem.features(&root, &mut self.feats);
106        for &f in &self.feats {
107            self.depth_of[f as usize] = 0;
108        }
109
110        self.push(root, None, None, 0);
111        self.meta[0].visited = true;
112    }
113
114    /// One rollout from the root; returns the index of a goal node if one
115    /// was generated.
116    fn rollout(&mut self) -> Option<usize> {
117        let mut n = 0;
118        loop {
119            if self.meta[n].children.is_none() {
120                if let Some(goal) = self.expand(n) {
121                    return Some(goal);
122                }
123            }
124
125            let Some(child) = self.pick_unsolved_child(n) else {
126                // No unsolved children: nothing left to explore below n.
127                self.solve(n);
128                return None;
129            };
130
131            n = child;
132            if let Verdict::Prune = self.novelty(n) {
133                self.solve(n);
134                return None;
135            }
136        }
137    }
138
139    /// Generates all children of `n`; returns the first goal child, if any.
140    fn expand(&mut self, n: usize) -> Option<usize> {
141        self.result.expanded += 1;
142        let mut succ = std::mem::take(&mut self.succ);
143        succ.clear();
144        self.problem.successors(&self.nodes[n].state, &mut succ);
145
146        let depth = self.meta[n].depth + 1;
147        let mut children = Vec::with_capacity(succ.len());
148        let mut goal = None;
149        for (action, state) in succ.drain(..) {
150            self.result.generated += 1;
151            let is_goal = self.problem.is_goal(&state);
152            let child = self.push(state, Some(n), Some(action), depth);
153            children.push(child);
154            if is_goal {
155                goal.get_or_insert(child);
156            }
157        }
158
159        self.succ = succ;
160        self.meta[n].children = Some(children);
161        goal
162    }
163
164    /// Runs the depth-aware novelty test on `n`, updating the depth table
165    /// for a new node.
166    fn novelty(&mut self, n: usize) -> Verdict {
167        let depth = self.meta[n].depth;
168        self.feats.clear();
169        self.problem.features(&self.nodes[n].state, &mut self.feats);
170
171        if self.meta[n].visited {
172            let kept = self
173                .feats
174                .iter()
175                .any(|&f| self.depth_of[f as usize] == depth);
176            return if kept {
177                Verdict::Continue
178            } else {
179                Verdict::Prune
180            };
181        }
182
183        self.meta[n].visited = true;
184        let mut novel = false;
185        for &f in &self.feats {
186            let d = &mut self.depth_of[f as usize];
187            if depth < *d {
188                *d = depth;
189                novel = true;
190            }
191        }
192
193        if novel {
194            Verdict::Continue
195        } else {
196            Verdict::Prune
197        }
198    }
199
200    /// A uniformly random child of `n` not labeled solved, if any.
201    fn pick_unsolved_child(&mut self, n: usize) -> Option<usize> {
202        let count_unsolved = |t: &Self| {
203            let children = t.meta[n].children.as_deref().unwrap_or_default();
204            children.iter().filter(|&&c| !t.meta[c].solved).count()
205        };
206        let unsolved = count_unsolved(self);
207        if unsolved == 0 {
208            return None;
209        }
210
211        // shortcut: modulo bias is negligible for branching factors far below 2^64.
212        let pick = usize::try_from(self.next_random() % unsolved as u64).expect("below a usize");
213        self.meta[n]
214            .children
215            .as_deref()
216            .unwrap_or_default()
217            .iter()
218            .copied()
219            .filter(|&c| !self.meta[c].solved)
220            .nth(pick)
221    }
222
223    /// Labels `n` solved and propagates the label to every ancestor whose
224    /// children are now all solved.
225    fn solve(&mut self, mut n: usize) {
226        self.meta[n].solved = true;
227        while let Some(p) = self.nodes[n].parent {
228            let children = self.meta[p].children.as_deref().unwrap_or_default();
229            if !children.iter().all(|&c| self.meta[c].solved) {
230                return;
231            }
232
233            self.meta[p].solved = true;
234            n = p;
235        }
236    }
237
238    /// Appends a node and returns its index.
239    fn push(
240        &mut self,
241        state: P::State,
242        parent: Option<usize>,
243        action: Option<P::Action>,
244        depth: usize,
245    ) -> usize {
246        self.nodes.push(Node {
247            state,
248            parent,
249            action,
250        });
251        self.meta.push(Meta {
252            depth,
253            children: None,
254            solved: false,
255            visited: false,
256        });
257
258        self.nodes.len() - 1
259    }
260
261    /// The next `SplitMix64` output.
262    fn next_random(&mut self) -> u64 {
263        self.rng = self.rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
264        let mut z = self.rng;
265        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
266        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
267        z ^ (z >> 31)
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    /// Walking from 0 to `len` on a line, one step either way.
276    struct Line {
277        /// The goal position, also the largest one.
278        len: u32,
279    }
280
281    impl WidthProblem for Line {
282        type State = u32;
283        type Action = i8;
284
285        fn initial_state(&self) -> u32 {
286            0
287        }
288        fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
289            if *s > 0 {
290                out.push((-1, s - 1));
291            }
292            if *s < self.len {
293                out.push((1, s + 1));
294            }
295        }
296        fn features(&self, s: &u32, out: &mut Vec<u32>) {
297            out.push(*s);
298        }
299        fn num_features(&self) -> usize {
300            self.len as usize + 1
301        }
302        fn is_goal(&self, s: &u32) -> bool {
303            *s == self.len
304        }
305    }
306
307    /// The goal has width 1, so every seed reaches it, and along a line the
308    /// only plan that survives the depth test is the shortest one.
309    #[test]
310    fn reaches_a_width_one_goal_for_every_seed() {
311        let line = Line { len: 6 };
312        for seed in 0..50 {
313            let plan = rollout_iw(&line, seed).plan.expect("width-1 goal");
314            assert_eq!(plan, [1; 6], "seed {seed}");
315        }
316    }
317
318    /// Without a goal the search ends once the root is solved.
319    #[test]
320    fn gives_up_when_the_root_is_solved() {
321        let r = rollout_iw(&NoGoal(Line { len: 6 }), 3);
322        assert!(r.plan.is_none());
323        assert_eq!(r.expanded, 7, "every position expanded once");
324    }
325
326    /// A [`Line`] whose goal is never reached.
327    struct NoGoal(Line);
328
329    impl WidthProblem for NoGoal {
330        type State = u32;
331        type Action = i8;
332
333        fn initial_state(&self) -> u32 {
334            self.0.initial_state()
335        }
336        fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
337            self.0.successors(s, out);
338        }
339        fn features(&self, s: &u32, out: &mut Vec<u32>) {
340            self.0.features(s, out);
341        }
342        fn num_features(&self) -> usize {
343            self.0.num_features()
344        }
345        fn is_goal(&self, _: &u32) -> bool {
346            false
347        }
348    }
349}