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::relevance::{Relevance, RelevanceTracker};
6use crate::{GoalCount, Node, NoveltyTable, RelaxedPlan, SearchResult, extract_plan};
7
8/// BFWS(f) with `f = ⟨w_{#g}, #g⟩`: best-first search ordered by novelty
9/// (computed separately for each goal-count value `#g`, capped at `k + 1`),
10/// breaking ties by `#g`. Complete on finite state spaces.
11///
12/// # Panics
13///
14/// Panics if `k` is 0.
15pub fn bfws<P>(problem: &P, k: usize) -> SearchResult<P::Action>
16where
17    P: GoalCount,
18    P::State: Hash + Eq,
19{
20    search(problem, k, None::<fn(&P::State, &mut Vec<u32>)>)
21}
22
23/// BFWS(f5) with `f = ⟨w_{#g,#r}, #g⟩` (Lipovetzky & Geffner, AAAI 2017):
24/// like [`bfws`], but novelty is computed separately for each pair of `#g`
25/// and `#r`.
26///
27/// `#r` counts the relaxed-plan features reached on the way to a state. The
28/// relaxed plan comes from [`RelaxedPlan::relaxed_plan_features`], computed at
29/// the initial state and again at every state where `#g` drops, as in
30/// LAPKT's `BFWS-f5`. Features already true in the state the relaxed plan was
31/// computed from are not counted. `#r` is path-dependent: it counts every
32/// relevant feature true in some state since that recomputation.
33///
34/// Complete on finite state spaces.
35///
36/// # Panics
37///
38/// Panics if `k` is 0.
39pub fn bfws_r<P>(problem: &P, k: usize) -> SearchResult<P::Action>
40where
41    P: RelaxedPlan,
42    P::State: Hash + Eq,
43{
44    search(
45        problem,
46        k,
47        Some(|s: &P::State, out: &mut Vec<u32>| problem.relaxed_plan_features(s, out)),
48    )
49}
50
51/// The `#g` and `#r` of a node: what its novelty is partitioned by.
52type Partition = (usize, Option<Relevance>);
53
54/// Computes `⟨w, #g⟩` of states, owning the novelty tables of every partition.
55struct Evaluator<'p, P, F> {
56    /// The problem being searched.
57    problem: &'p P,
58    /// Width bound; novelty above it is reported as `k + 1`.
59    k: usize,
60    /// One novelty table per `(#g, #r)` pair, created on first use.
61    tables: HashMap<(usize, usize), NoveltyTable>,
62    /// Relaxed-plan sets and the oracle that computes them.
63    tracker: RelevanceTracker<F>,
64    /// Reused buffer for the features of a state.
65    feats: Vec<u32>,
66}
67
68impl<P, F> Evaluator<'_, P, F>
69where
70    P: GoalCount,
71    F: FnMut(&P::State, &mut Vec<u32>),
72{
73    /// The novelty `w` of `state` and its partition. `parent` is the
74    /// parent's partition, `None` for the root. The relaxed plan is
75    /// recomputed at the root and wherever `#g` drops.
76    fn evaluate(&mut self, state: &P::State, parent: Option<&Partition>) -> (usize, Partition) {
77        self.feats.clear();
78        self.problem.features(state, &mut self.feats);
79        let g = self.problem.unsatisfied_goals(state);
80        let rel = match parent {
81            Some((pg, Some(rel))) if g >= *pg => Some(self.tracker.extend(rel, &self.feats)),
82            _ => self.tracker.recompute(state, &self.feats),
83        };
84
85        let r = rel.as_ref().map_or(0, |r| r.count);
86        let (num_features, k) = (self.problem.num_features(), self.k);
87        let table = self
88            .tables
89            .entry((g, r))
90            .or_insert_with(|| NoveltyTable::new(num_features, k));
91        let w = table.evaluate_and_insert(&self.feats).unwrap_or(k + 1);
92
93        (w, (g, rel))
94    }
95}
96
97/// The best-first search behind [`bfws`] and [`bfws_r`]: novelty tables are
98/// partitioned by `(#g, #r)`, and the open list is ordered by `⟨w, #g⟩` with
99/// ties broken by generation order. With `oracle == None`, `#r` is 0.
100fn search<P, F>(problem: &P, k: usize, oracle: Option<F>) -> SearchResult<P::Action>
101where
102    P: GoalCount,
103    P::State: Hash + Eq,
104    F: FnMut(&P::State, &mut Vec<u32>),
105{
106    // Checked up front, not only when the first novelty table is built, so a
107    // goal initial state does not hide the bad bound.
108    assert!(k >= 1, "width bound must be at least 1");
109    let mut eval = Evaluator {
110        problem,
111        k,
112        tables: HashMap::new(),
113        tracker: RelevanceTracker::new(oracle),
114        feats: Vec::new(),
115    };
116    let mut seen: HashSet<P::State> = HashSet::new();
117    let mut succ = Vec::new();
118    let mut result = SearchResult {
119        plan: None,
120        expanded: 0,
121        generated: 1,
122    };
123
124    let root = problem.initial_state();
125    if problem.is_goal(&root) {
126        result.plan = Some(Vec::new());
127        return result;
128    }
129
130    let (w, part) = eval.evaluate(&root, None);
131    let mut open = BinaryHeap::from([Reverse((w, part.0, 0usize))]);
132    seen.insert(root.clone());
133    let mut nodes = vec![Node {
134        state: root,
135        parent: None,
136        action: None,
137    }];
138    let mut parts = vec![part];
139
140    while let Some(Reverse((_, _, i))) = open.pop() {
141        result.expanded += 1;
142        succ.clear();
143        problem.successors(&nodes[i].state, &mut succ);
144        for (action, state) in succ.drain(..) {
145            result.generated += 1;
146            if !seen.insert(state.clone()) {
147                continue;
148            }
149
150            let goal = problem.is_goal(&state);
151            let (w, part) = eval.evaluate(&state, Some(&parts[i]));
152            open.push(Reverse((w, part.0, nodes.len())));
153            nodes.push(Node {
154                state,
155                parent: Some(i),
156                action: Some(action),
157            });
158            parts.push(part);
159            if goal {
160                result.plan = Some(extract_plan(&nodes, nodes.len() - 1));
161                return result;
162            }
163        }
164    }
165
166    result
167}