Skip to main content

width_search/
rollout.rs

1use crate::rng::SplitMix64;
2use crate::{Node, SearchResult, WidthProblem, extract_plan};
3
4/// Rollout IW(1) (Bandres, Bonet & Geffner, AAAI 2018), goal-directed.
5///
6/// Builds a search tree by repeated rollouts from the root. Each rollout
7/// walks down through a random child not yet labeled solved, generating
8/// children lazily, and stops by labeling a node solved. Novelty uses the
9/// smallest depth `d[f]` at which each feature `f` was reached:
10///
11/// - a new node at depth `d` continues the rollout if `d < d[f]` for some
12///   feature `f` it makes true, and lowers `d[f]` to `d` for all of them;
13///   otherwise it is labeled solved (pruned);
14/// - a node already in the tree continues if `d == d[f]` for some feature,
15///   and is labeled solved otherwise (a shallower path took its features).
16///
17/// A node with no successors is solved; a node is solved once all of its
18/// children are. The search returns as soon as a goal state is generated,
19/// and gives up (`plan: None`) when the root is solved.
20///
21/// The paper's algorithm picks actions for a reward-maximizing agent within a
22/// time budget; this version has no budget and stops at the first goal. Like
23/// IW(1), it reaches every goal of width 1, but its plans need not be
24/// shortest. `seed` fixes the random child choices.
25pub fn rollout_iw<P: WidthProblem>(problem: &P, seed: u64) -> SearchResult<P::Action> {
26    search(problem, None::<Weights<P>>, seed)
27}
28
29/// π-IW (Junyent, Jonsson & Gómez, ICAPS 2019): [`rollout_iw`] with rollouts
30/// guided by a policy.
31///
32/// When a node is expanded, `policy` gets its state and all of its
33/// `(action, successor)` pairs, and pushes one weight per successor into the
34/// (empty) output vector, for example the action probabilities of a learned
35/// policy. A rollout then moves to an unsolved child with probability
36/// proportional to its weight. Children of weight 0 are picked, uniformly at
37/// random, only once every unsolved sibling has weight 0, so π-IW explores the
38/// same tree as [`rollout_iw`] in a different order and still reaches every
39/// goal of width 1. Constant weights give uniform choices.
40///
41/// The paper also learns the policy from the planner's choices; that loop is
42/// left to the caller. `seed` fixes the random choices.
43///
44/// # Panics
45///
46/// Panics if `policy` pushes a different number of weights than there are
47/// successors, a weight that is negative or not finite, or weights whose sum
48/// is not finite.
49pub fn pi_iw<P, F>(problem: &P, policy: F, seed: u64) -> SearchResult<P::Action>
50where
51    P: WidthProblem,
52    F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
53{
54    search(problem, Some(policy), seed)
55}
56
57/// The signature of a π-IW policy, as taken by [`pi_iw`].
58type Weights<P> = fn(
59    &<P as WidthProblem>::State,
60    &[(<P as WidthProblem>::Action, <P as WidthProblem>::State)],
61    &mut Vec<f64>,
62);
63
64/// The search behind [`rollout_iw`] (`policy == None`, uniform choices) and
65/// [`pi_iw`].
66fn search<P, F>(problem: &P, policy: Option<F>, seed: u64) -> SearchResult<P::Action>
67where
68    P: WidthProblem,
69    F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
70{
71    let mut tree = Tree::new(problem, policy, seed, None);
72    let root = problem.initial_state();
73    if problem.is_goal(&root) {
74        tree.result.plan = Some(Vec::new());
75        return tree.result;
76    }
77
78    tree.add_root(root);
79    while !tree.is_exhausted() {
80        if let Outcome::Goal(goal) = tree.rollout() {
81            tree.result.plan = Some(extract_plan(&tree.nodes, goal));
82            break;
83        }
84    }
85
86    tree.result
87}
88
89/// Per-node rollout bookkeeping, parallel to [`Tree::nodes`].
90struct Meta {
91    /// Number of actions from the root.
92    depth: usize,
93    /// Arena indices of the children; `None` until the node is expanded.
94    children: Option<Vec<usize>>,
95    /// Whether the subtree below needs no further rollouts.
96    solved: bool,
97    /// Whether a rollout has already run the novelty test on this node.
98    visited: bool,
99    /// The policy's weight for reaching this node from its parent; finite
100    /// and non-negative. Unused without a policy and at the root.
101    weight: f64,
102}
103
104/// How a rollout ended.
105pub(crate) enum Outcome {
106    /// It generated a goal state, at this arena index.
107    Goal(usize),
108    /// It entered a state outside the root's high-level partition, at this
109    /// arena index; see [`Tree::new`].
110    Boundary(usize),
111    /// It labeled a node solved; nothing to report.
112    Solved,
113}
114
115/// The high-level feature function of π-HIW and the sorted high-level
116/// features of a tree's root: states with other features are boundaries.
117pub(crate) type Partition<'a, S> = (&'a dyn Fn(&S, &mut Vec<u32>), Vec<u32>);
118
119/// What the novelty test says about the node a rollout just entered.
120enum Verdict {
121    /// The node is novel: continue the rollout below it.
122    Continue,
123    /// The node is not novel: label it solved and end the rollout.
124    Prune,
125}
126
127/// The search tree of a Rollout IW(1) run and its novelty table.
128pub(crate) struct Tree<'p, P: WidthProblem, F> {
129    /// The problem being searched.
130    problem: &'p P,
131    /// For π-HIW: the high-level partition of the root. A rollout entering
132    /// a state outside it stops there; `None` for a flat search.
133    partition: Option<Partition<'p, P::State>>,
134    /// The π-IW policy; `None` picks children uniformly.
135    policy: Option<F>,
136    /// Reused buffer for the policy's weights.
137    weights: Vec<f64>,
138    /// Node arena: states and parent links.
139    pub nodes: Vec<Node<P::State, P::Action>>,
140    /// Rollout data of each node, same indices as `nodes`.
141    meta: Vec<Meta>,
142    /// Smallest depth at which each feature was reached; `usize::MAX` if never.
143    depth_of: Vec<usize>,
144    /// Random source for child selection.
145    rng: SplitMix64,
146    /// Reused buffer for the features of a state.
147    feats: Vec<u32>,
148    /// Reused buffer for successors.
149    succ: Vec<(P::Action, P::State)>,
150    /// Node counts so far; `plan` is filled in by [`rollout_iw`].
151    pub result: SearchResult<P::Action>,
152}
153
154impl<'p, P, F> Tree<'p, P, F>
155where
156    P: WidthProblem,
157    F: FnMut(&P::State, &[(P::Action, P::State)], &mut Vec<f64>),
158{
159    /// An empty tree for `problem`, guided by `policy` if set, and confined
160    /// to a high-level `partition` if set.
161    pub fn new(
162        problem: &'p P,
163        policy: Option<F>,
164        seed: u64,
165        partition: Option<Partition<'p, P::State>>,
166    ) -> Self {
167        Self {
168            problem,
169            partition,
170            policy,
171            weights: Vec::new(),
172            nodes: Vec::new(),
173            meta: Vec::new(),
174            depth_of: vec![usize::MAX; problem.num_features()],
175            rng: SplitMix64::new(seed),
176            feats: Vec::new(),
177            succ: Vec::new(),
178            result: SearchResult {
179                plan: None,
180                expanded: 0,
181                generated: 1,
182            },
183        }
184    }
185
186    /// Adds the root at depth 0 and records its features at depth 0.
187    pub fn add_root(&mut self, root: P::State) {
188        self.feats.clear();
189        self.problem.features(&root, &mut self.feats);
190        for &f in &self.feats {
191            self.depth_of[f as usize] = 0;
192        }
193
194        self.push(root, None, None, 0, 0.0);
195        self.meta[0].visited = true;
196    }
197
198    /// Whether every node is solved, so no rollout is left to run.
199    pub fn is_exhausted(&self) -> bool {
200        self.meta[0].solved
201    }
202
203    /// One rollout from the root. A boundary node it enters is labeled
204    /// solved, so each is reported once.
205    pub fn rollout(&mut self) -> Outcome {
206        let mut n = 0;
207        loop {
208            if self.meta[n].children.is_none() {
209                if let Some(goal) = self.expand(n) {
210                    return Outcome::Goal(goal);
211                }
212            }
213
214            let Some(child) = self.pick_unsolved_child(n) else {
215                // No unsolved children: nothing left to explore below n.
216                self.solve(n);
217                return Outcome::Solved;
218            };
219
220            n = child;
221            if self.is_boundary(n) {
222                self.solve(n);
223                return Outcome::Boundary(n);
224            }
225
226            if let Verdict::Prune = self.novelty(n) {
227                self.solve(n);
228                return Outcome::Solved;
229            }
230        }
231    }
232
233    /// Whether node `n` lies outside the root's high-level partition.
234    fn is_boundary(&mut self, n: usize) -> bool {
235        let Some((high, root_features)) = &self.partition else {
236            return false;
237        };
238
239        self.feats.clear();
240        high(&self.nodes[n].state, &mut self.feats);
241        self.feats.sort_unstable();
242        self.feats.dedup();
243        self.feats != *root_features
244    }
245
246    /// Generates all children of `n`; returns the first goal child, if any.
247    fn expand(&mut self, n: usize) -> Option<usize> {
248        self.result.expanded += 1;
249        let mut succ = std::mem::take(&mut self.succ);
250        succ.clear();
251        self.problem.successors(&self.nodes[n].state, &mut succ);
252        self.ask_policy(n, &succ);
253
254        let depth = self.meta[n].depth + 1;
255        let mut children = Vec::with_capacity(succ.len());
256        let mut goal = None;
257        for (i, (action, state)) in succ.drain(..).enumerate() {
258            self.result.generated += 1;
259            let is_goal = self.problem.is_goal(&state);
260            let weight = self.weights.get(i).copied().unwrap_or(1.0);
261            let child = self.push(state, Some(n), Some(action), depth, weight);
262            children.push(child);
263            if is_goal {
264                goal.get_or_insert(child);
265            }
266        }
267
268        self.succ = succ;
269        self.meta[n].children = Some(children);
270        goal
271    }
272
273    /// Fills [`Tree::weights`] with the policy's weights for the successors
274    /// `succ` of node `n`; leaves it empty without a policy.
275    ///
276    /// # Panics
277    ///
278    /// Panics if the policy breaks the contract of [`pi_iw`].
279    fn ask_policy(&mut self, n: usize, succ: &[(P::Action, P::State)]) {
280        self.weights.clear();
281        let Some(policy) = self.policy.as_mut() else {
282            return;
283        };
284
285        policy(&self.nodes[n].state, succ, &mut self.weights);
286        assert_eq!(
287            self.weights.len(),
288            succ.len(),
289            "policy must push one weight per successor"
290        );
291        assert!(
292            self.weights.iter().all(|w| w.is_finite() && *w >= 0.0),
293            "policy weights must be finite and non-negative"
294        );
295        // An infinite sum would make every weighted draw pick the last child.
296        assert!(
297            self.weights.iter().sum::<f64>().is_finite(),
298            "policy weights must have a finite sum"
299        );
300    }
301
302    /// Runs the depth-aware novelty test on `n`, updating the depth table
303    /// for a new node.
304    fn novelty(&mut self, n: usize) -> Verdict {
305        let depth = self.meta[n].depth;
306        self.feats.clear();
307        self.problem.features(&self.nodes[n].state, &mut self.feats);
308
309        if self.meta[n].visited {
310            let kept = self
311                .feats
312                .iter()
313                .any(|&f| self.depth_of[f as usize] == depth);
314            return if kept {
315                Verdict::Continue
316            } else {
317                Verdict::Prune
318            };
319        }
320
321        self.meta[n].visited = true;
322        let mut novel = false;
323        for &f in &self.feats {
324            let d = &mut self.depth_of[f as usize];
325            if depth < *d {
326                *d = depth;
327                novel = true;
328            }
329        }
330
331        if novel {
332            Verdict::Continue
333        } else {
334            Verdict::Prune
335        }
336    }
337
338    /// A child of `n` not labeled solved, if any: drawn by policy weight with
339    /// a policy (uniformly when all unsolved children have weight 0), and
340    /// uniformly without one.
341    fn pick_unsolved_child(&mut self, n: usize) -> Option<usize> {
342        if self.policy.is_some() {
343            if let Some(child) = self.pick_weighted_child(n) {
344                return Some(child);
345            }
346        }
347
348        self.pick_uniform_child(n)
349    }
350
351    /// An unsolved child of `n` drawn with probability proportional to its
352    /// weight; `None` if no unsolved child has a positive weight.
353    fn pick_weighted_child(&mut self, n: usize) -> Option<usize> {
354        let unit = self.rng.unit();
355        let meta = &self.meta;
356        let candidates = || {
357            meta[n]
358                .children
359                .as_deref()
360                .unwrap_or_default()
361                .iter()
362                .copied()
363                .filter(|&c| !meta[c].solved && meta[c].weight > 0.0)
364        };
365        let total: f64 = candidates().map(|c| meta[c].weight).sum();
366        let last = candidates().next_back()?;
367
368        let mut target = unit * total;
369        for c in candidates() {
370            target -= meta[c].weight;
371            if target < 0.0 {
372                return Some(c);
373            }
374        }
375
376        // Rounding left `target` at or just above 0: take the last candidate.
377        Some(last)
378    }
379
380    /// A uniformly random child of `n` not labeled solved, if any.
381    fn pick_uniform_child(&mut self, n: usize) -> Option<usize> {
382        let count_unsolved = |t: &Self| {
383            let children = t.meta[n].children.as_deref().unwrap_or_default();
384            children.iter().filter(|&&c| !t.meta[c].solved).count()
385        };
386        let unsolved = count_unsolved(self);
387        if unsolved == 0 {
388            return None;
389        }
390
391        let pick = self.rng.below(unsolved);
392        self.meta[n]
393            .children
394            .as_deref()
395            .unwrap_or_default()
396            .iter()
397            .copied()
398            .filter(|&c| !self.meta[c].solved)
399            .nth(pick)
400    }
401
402    /// Labels `n` solved and propagates the label to every ancestor whose
403    /// children are now all solved.
404    fn solve(&mut self, mut n: usize) {
405        self.meta[n].solved = true;
406        while let Some(p) = self.nodes[n].parent {
407            let children = self.meta[p].children.as_deref().unwrap_or_default();
408            if !children.iter().all(|&c| self.meta[c].solved) {
409                return;
410            }
411
412            self.meta[p].solved = true;
413            n = p;
414        }
415    }
416
417    /// Appends a node and returns its index.
418    fn push(
419        &mut self,
420        state: P::State,
421        parent: Option<usize>,
422        action: Option<P::Action>,
423        depth: usize,
424        weight: f64,
425    ) -> usize {
426        self.nodes.push(Node {
427            state,
428            parent,
429            action,
430        });
431        self.meta.push(Meta {
432            depth,
433            children: None,
434            solved: false,
435            visited: false,
436            weight,
437        });
438
439        self.nodes.len() - 1
440    }
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::test_problems::Line;
447
448    /// The goal has width 1, so every seed reaches it, and along a line the
449    /// only plan that survives the depth test is the shortest one.
450    #[test]
451    fn reaches_a_width_one_goal_for_every_seed() {
452        let line = Line { len: 6 };
453        for seed in 0..50 {
454            let plan = rollout_iw(&line, seed).plan.expect("width-1 goal");
455            assert_eq!(plan, [1; 6], "seed {seed}");
456        }
457    }
458
459    /// A policy that only weights the step towards the goal walks straight
460    /// there: every rollout follows it, so only positions 0 to 5 are expanded.
461    #[test]
462    fn a_greedy_policy_walks_straight_to_the_goal() {
463        let line = Line { len: 6 };
464        let towards_goal = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
465            out.extend(succ.iter().map(|&(a, _)| if a > 0 { 1.0 } else { 0.0 }));
466        };
467        for seed in 0..20 {
468            let r = pi_iw(&line, towards_goal, seed);
469            assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]), "seed {seed}");
470            assert_eq!(r.expanded, 6, "seed {seed}");
471        }
472    }
473
474    /// A policy that weights only the step away from the goal still reaches
475    /// it: once the weighted children are solved, the weight-0 ones are tried.
476    #[test]
477    fn zero_weight_children_are_tried_last() {
478        let line = Line { len: 6 };
479        let away = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
480            out.extend(succ.iter().map(|&(a, _)| if a < 0 { 1.0 } else { 0.0 }));
481        };
482        for seed in 0..20 {
483            let plan = pi_iw(&line, away, seed).plan.expect("width-1 goal");
484            assert_eq!(plan, [1; 6], "seed {seed}");
485        }
486    }
487
488    /// A negative weight breaks the policy contract.
489    #[test]
490    #[should_panic(expected = "finite and non-negative")]
491    fn rejects_negative_weights() {
492        let negative = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
493            out.extend(succ.iter().map(|_| -1.0));
494        };
495        pi_iw(&Line { len: 3 }, negative, 0);
496    }
497
498    /// Weights that are finite one by one but overflow when summed break the
499    /// policy contract: position 1 has two successors of weight `f64::MAX`.
500    #[test]
501    #[should_panic(expected = "finite sum")]
502    fn rejects_weights_with_an_infinite_sum() {
503        let huge = |_: &u32, succ: &[(i8, u32)], out: &mut Vec<f64>| {
504            out.extend(succ.iter().map(|_| f64::MAX));
505        };
506        pi_iw(&Line { len: 3 }, huge, 0);
507    }
508
509    /// A policy must push exactly one weight per successor.
510    #[test]
511    #[should_panic(expected = "one weight per successor")]
512    fn rejects_a_missing_weight() {
513        pi_iw(
514            &Line { len: 3 },
515            |_: &u32, _: &[(i8, u32)], _: &mut Vec<f64>| {},
516            0,
517        );
518    }
519
520    /// Without a goal the search ends once the root is solved.
521    #[test]
522    fn gives_up_when_the_root_is_solved() {
523        let r = rollout_iw(&NoGoal(Line { len: 6 }), 3);
524        assert!(r.plan.is_none());
525        assert_eq!(r.expanded, 7, "every position expanded once");
526    }
527
528    /// A [`Line`] whose goal is never reached.
529    struct NoGoal(Line);
530
531    impl WidthProblem for NoGoal {
532        type State = u32;
533        type Action = i8;
534
535        fn initial_state(&self) -> u32 {
536            self.0.initial_state()
537        }
538        fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
539            self.0.successors(s, out);
540        }
541        fn features(&self, s: &u32, out: &mut Vec<u32>) {
542            self.0.features(s, out);
543        }
544        fn num_features(&self) -> usize {
545            self.0.num_features()
546        }
547        fn is_goal(&self, _: &u32) -> bool {
548            false
549        }
550    }
551}