Skip to main content

width_search/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3
4/// Best-first width search: BFWS(⟨w_{#g}, #g⟩) and BFWS(⟨w_{#g,#r}, #g⟩).
5mod bfws;
6/// Hierarchical IW: IW over high-level features, refined by IW per high-level state.
7mod hiw;
8/// IW(k) and iterated width.
9mod iw;
10/// The novelty table shared by all searches.
11mod novelty;
12/// `#r`: relaxed-plan features reached on the path to a node.
13mod relevance;
14/// A seeded `SplitMix64` generator for randomized searches.
15mod rng;
16/// Rollout IW(1) and π-IW: depth-first rollouts with depth-aware novelty.
17mod rollout;
18/// Adapter that runs width-based search on a [`sas_plus::Task`].
19#[cfg(feature = "sas-plus")]
20pub mod sas;
21/// Serialized IW and SIW+: one IW (or IW+) search per achieved goal.
22mod siw;
23/// Sketches and SIW-R: serialized IW with subgoals given by sketch rules.
24mod sketch;
25
26pub use bfws::{bfws, bfws_r};
27pub use hiw::{hiw, ihiw, pi_hiw};
28pub use iw::{iterated_width, iw};
29pub use novelty::NoveltyTable;
30pub use rollout::{pi_iw, rollout_iw};
31pub use siw::{siw, siw_plus};
32pub use sketch::{Condition, Effect, Rule, siw_r};
33
34/// A search problem described by successors and integer features.
35///
36/// Width-based search never inspects states directly. It only needs the
37/// successors of a state, the goal test, and the features that are true in a
38/// state, numbered `0..num_features()`. Novelty is computed over those
39/// features, so their choice decides what counts as "new".
40pub trait WidthProblem {
41    /// A search state. Cloned when a node is stored.
42    type State: Clone;
43    /// The label of a transition; plans are sequences of actions.
44    type Action: Clone;
45
46    /// The state the search starts from.
47    fn initial_state(&self) -> Self::State;
48    /// Push all `(action, successor)` pairs of `state` into `out`.
49    fn successors(&self, state: &Self::State, out: &mut Vec<(Self::Action, Self::State)>);
50    /// Push the feature ids (`< num_features()`) true in `state` into `out`.
51    fn features(&self, state: &Self::State, out: &mut Vec<u32>);
52    /// Number of distinct features; every id from [`WidthProblem::features`]
53    /// must be below it.
54    fn num_features(&self) -> usize;
55    /// Whether `state` satisfies the goal.
56    fn is_goal(&self, state: &Self::State) -> bool;
57}
58
59/// Goal-directed information used by BFWS.
60pub trait GoalCount: WidthProblem {
61    /// Number of goal conditions not yet satisfied (`#g`).
62    fn unsatisfied_goals(&self, state: &Self::State) -> usize;
63}
64
65/// Relaxed-plan information used by [`bfws_r`] to compute `#r`.
66pub trait RelaxedPlan: GoalCount {
67    /// Push into `out` the features a relaxed plan from `state` makes true,
68    /// for example the add effects of its actions (LAPKT's choice).
69    ///
70    /// Push nothing when the goal is unreachable even under the relaxation.
71    /// Features already true in `state` are ignored by the search.
72    fn relaxed_plan_features(&self, state: &Self::State, out: &mut Vec<u32>);
73}
74
75/// The outcome of a search: a plan, if one was found, and node counts.
76#[derive(Clone, Debug)]
77pub struct SearchResult<A> {
78    /// The actions from the initial state to a goal, or `None` if the search
79    /// gave up (pruning) or exhausted the state space.
80    pub plan: Option<Vec<A>>,
81    /// Number of nodes whose successors were generated.
82    pub expanded: usize,
83    /// Number of states generated, the initial state included.
84    pub generated: usize,
85}
86
87/// A search node, stored in an arena and linked to its parent by index.
88pub(crate) struct Node<S, A> {
89    /// The state this node represents.
90    pub state: S,
91    /// Arena index of the parent node; `None` only for the root.
92    pub parent: Option<usize>,
93    /// The action that led from the parent here; `None` only for the root.
94    pub action: Option<A>,
95}
96
97/// The feature ids `fill` pushes, sorted and deduplicated, so that two sets
98/// compare equal exactly when they hold the same ids.
99pub(crate) fn sorted_set(fill: impl FnOnce(&mut Vec<u32>)) -> Vec<u32> {
100    let mut ids = Vec::new();
101    fill(&mut ids);
102    ids.sort_unstable();
103    ids.dedup();
104
105    ids
106}
107
108/// Follows parent links from node `i` back to the root and returns the
109/// actions along the way, in execution order.
110pub(crate) fn extract_plan<S, A: Clone>(nodes: &[Node<S, A>], mut i: usize) -> Vec<A> {
111    let mut plan = Vec::new();
112    while let Some(p) = nodes[i].parent {
113        plan.push(
114            nodes[i]
115                .action
116                .clone()
117                .expect("non-root node has an action"),
118        );
119        i = p;
120    }
121
122    plan.reverse();
123    plan
124}
125
126/// Small problems shared by the unit tests of several modules.
127#[cfg(test)]
128pub(crate) mod test_problems {
129    use crate::WidthProblem;
130
131    /// Walking from 0 to `len` on a line, one step either way. The only
132    /// feature is the position.
133    pub(crate) struct Line {
134        /// The goal position, also the largest one.
135        pub len: u32,
136    }
137
138    impl WidthProblem for Line {
139        type State = u32;
140        type Action = i8;
141
142        fn initial_state(&self) -> u32 {
143            0
144        }
145        fn successors(&self, s: &u32, out: &mut Vec<(i8, u32)>) {
146            if *s > 0 {
147                out.push((-1, s - 1));
148            }
149            if *s < self.len {
150                out.push((1, s + 1));
151            }
152        }
153        fn features(&self, s: &u32, out: &mut Vec<u32>) {
154            out.push(*s);
155        }
156        fn num_features(&self) -> usize {
157            self.len as usize + 1
158        }
159        fn is_goal(&self, s: &u32) -> bool {
160            *s == self.len
161        }
162    }
163}