Skip to main content

width_search/
bfws.rs

1use std::cmp::Reverse;
2use std::collections::{BinaryHeap, HashMap, HashSet};
3use std::hash::Hash;
4
5use crate::{GoalCount, Node, NoveltyTable, RelaxedPlan, SearchResult, extract_plan};
6
7/// BFWS(f) with `f = ⟨w_{#g}, #g⟩`: best-first search ordered by novelty
8/// (computed separately for each goal-count value `#g`, capped at `k + 1`),
9/// breaking ties by `#g`. Complete on finite state spaces.
10///
11/// # Panics
12///
13/// Panics if `k` is 0.
14pub fn bfws<P>(problem: &P, k: usize) -> SearchResult<P::Action>
15where
16    P: GoalCount,
17    P::State: Hash + Eq,
18{
19    search(problem, k, None::<fn(&P::State, &mut Vec<u32>)>)
20}
21
22/// BFWS(f5) with `f = ⟨w_{#g,#r}, #g⟩` (Lipovetzky & Geffner, AAAI 2017):
23/// like [`bfws`], but novelty is computed separately for each pair of `#g`
24/// and `#r`.
25///
26/// `#r` counts the relaxed-plan features reached on the way to a state. The
27/// relaxed plan comes from [`RelaxedPlan::relaxed_plan_features`], computed at
28/// the initial state and again at every state where `#g` drops, as in
29/// LAPKT's `BFWS-f5`. Features already true in the state the relaxed plan was
30/// computed from are not counted. `#r` is path-dependent: it counts every
31/// relevant feature true in some state since that recomputation.
32///
33/// Complete on finite state spaces.
34///
35/// # Panics
36///
37/// Panics if `k` is 0.
38pub fn bfws_r<P>(problem: &P, k: usize) -> SearchResult<P::Action>
39where
40    P: RelaxedPlan,
41    P::State: Hash + Eq,
42{
43    search(
44        problem,
45        k,
46        Some(|s: &P::State, out: &mut Vec<u32>| problem.relaxed_plan_features(s, out)),
47    )
48}
49
50/// The relaxed-plan features `#r` counts, from one recomputation.
51struct RelevantSet {
52    /// Relevant feature ids, sorted ascending, none true where it was computed.
53    features: Vec<u32>,
54}
55
56/// The `#r` bookkeeping of one search node.
57#[derive(Clone)]
58struct Relevance {
59    /// Index of the [`RelevantSet`] in force for this node.
60    set: usize,
61    /// Bitset over the positions of that set: which features were reached.
62    reached: Vec<u64>,
63    /// Number of set bits in `reached`: the node's `#r`.
64    count: usize,
65}
66
67/// State of the `#r` computation: the relaxed-plan oracle and every set it
68/// produced. `None` oracle means plain BFWS, where `#r` is always 0.
69struct RelevanceTracker<F> {
70    /// Computes relaxed-plan features of a state; `None` disables `#r`.
71    oracle: Option<F>,
72    /// All relevant sets computed so far, indexed by [`Relevance::set`].
73    sets: Vec<RelevantSet>,
74    /// Reused buffer for the oracle's output.
75    buf: Vec<u32>,
76}
77
78impl<F> RelevanceTracker<F> {
79    /// A fresh relevant set computed at a state with features `feats`;
80    /// `None` when `#r` is disabled.
81    fn recompute<S>(&mut self, state: &S, feats: &[u32]) -> Option<Relevance>
82    where
83        F: FnMut(&S, &mut Vec<u32>),
84    {
85        let oracle = self.oracle.as_mut()?;
86        self.buf.clear();
87        oracle(state, &mut self.buf);
88        let mut features: Vec<u32> = self
89            .buf
90            .iter()
91            .copied()
92            .filter(|f| !feats.contains(f))
93            .collect();
94        features.sort_unstable();
95        features.dedup();
96
97        let words = features.len().div_ceil(64);
98        self.sets.push(RelevantSet { features });
99
100        Some(Relevance {
101            set: self.sets.len() - 1,
102            reached: vec![0; words],
103            count: 0,
104        })
105    }
106
107    /// The child's relevance: the parent's, plus the relevant features true
108    /// in the child (`feats`).
109    fn extend(&self, parent: &Relevance, feats: &[u32]) -> Relevance {
110        let set = &self.sets[parent.set].features;
111        let mut child = parent.clone();
112        for f in feats {
113            let Ok(pos) = set.binary_search(f) else {
114                continue;
115            };
116            let (word, bit) = (pos / 64, 1u64 << (pos % 64));
117            if child.reached[word] & bit == 0 {
118                child.reached[word] |= bit;
119                child.count += 1;
120            }
121        }
122
123        child
124    }
125}
126
127/// The `#g` and `#r` of a node: what its novelty is partitioned by.
128type Partition = (usize, Option<Relevance>);
129
130/// Computes `⟨w, #g⟩` of states, owning the novelty tables of every partition.
131struct Evaluator<'p, P, F> {
132    /// The problem being searched.
133    problem: &'p P,
134    /// Width bound; novelty above it is reported as `k + 1`.
135    k: usize,
136    /// One novelty table per `(#g, #r)` pair, created on first use.
137    tables: HashMap<(usize, usize), NoveltyTable>,
138    /// Relaxed-plan sets and the oracle that computes them.
139    tracker: RelevanceTracker<F>,
140    /// Reused buffer for the features of a state.
141    feats: Vec<u32>,
142}
143
144impl<P, F> Evaluator<'_, P, F>
145where
146    P: GoalCount,
147    F: FnMut(&P::State, &mut Vec<u32>),
148{
149    /// The novelty `w` of `state` and its partition. `parent` is the
150    /// parent's partition, `None` for the root. The relaxed plan is
151    /// recomputed at the root and wherever `#g` drops.
152    fn evaluate(&mut self, state: &P::State, parent: Option<&Partition>) -> (usize, Partition) {
153        self.feats.clear();
154        self.problem.features(state, &mut self.feats);
155        let g = self.problem.unsatisfied_goals(state);
156        let rel = match parent {
157            Some((pg, Some(rel))) if g >= *pg => Some(self.tracker.extend(rel, &self.feats)),
158            _ => self.tracker.recompute(state, &self.feats),
159        };
160
161        let r = rel.as_ref().map_or(0, |r| r.count);
162        let (num_features, k) = (self.problem.num_features(), self.k);
163        let table = self
164            .tables
165            .entry((g, r))
166            .or_insert_with(|| NoveltyTable::new(num_features, k));
167        let w = table.evaluate_and_insert(&self.feats).unwrap_or(k + 1);
168
169        (w, (g, rel))
170    }
171}
172
173/// The best-first search behind [`bfws`] and [`bfws_r`]: novelty tables are
174/// partitioned by `(#g, #r)`, and the open list is ordered by `⟨w, #g⟩` with
175/// ties broken by generation order. With `oracle == None`, `#r` is 0.
176fn search<P, F>(problem: &P, k: usize, oracle: Option<F>) -> SearchResult<P::Action>
177where
178    P: GoalCount,
179    P::State: Hash + Eq,
180    F: FnMut(&P::State, &mut Vec<u32>),
181{
182    // Checked up front, not only when the first novelty table is built, so a
183    // goal initial state does not hide the bad bound.
184    assert!(k >= 1, "width bound must be at least 1");
185    let mut eval = Evaluator {
186        problem,
187        k,
188        tables: HashMap::new(),
189        tracker: RelevanceTracker {
190            oracle,
191            sets: Vec::new(),
192            buf: Vec::new(),
193        },
194        feats: Vec::new(),
195    };
196    let mut seen: HashSet<P::State> = HashSet::new();
197    let mut succ = Vec::new();
198    let mut result = SearchResult {
199        plan: None,
200        expanded: 0,
201        generated: 1,
202    };
203
204    let root = problem.initial_state();
205    if problem.is_goal(&root) {
206        result.plan = Some(Vec::new());
207        return result;
208    }
209
210    let (w, part) = eval.evaluate(&root, None);
211    let mut open = BinaryHeap::from([Reverse((w, part.0, 0usize))]);
212    seen.insert(root.clone());
213    let mut nodes = vec![Node {
214        state: root,
215        parent: None,
216        action: None,
217    }];
218    let mut parts = vec![part];
219
220    while let Some(Reverse((_, _, i))) = open.pop() {
221        result.expanded += 1;
222        succ.clear();
223        problem.successors(&nodes[i].state, &mut succ);
224        for (action, state) in succ.drain(..) {
225            result.generated += 1;
226            if !seen.insert(state.clone()) {
227                continue;
228            }
229
230            let goal = problem.is_goal(&state);
231            let (w, part) = eval.evaluate(&state, Some(&parts[i]));
232            open.push(Reverse((w, part.0, nodes.len())));
233            nodes.push(Node {
234                state,
235                parent: Some(i),
236                action: Some(action),
237            });
238            parts.push(part);
239            if goal {
240                result.plan = Some(extract_plan(&nodes, nodes.len() - 1));
241                return result;
242            }
243        }
244    }
245
246    result
247}