Skip to main content

width_search/
iw.rs

1use std::collections::VecDeque;
2
3use crate::relevance::{Relevance, RelevanceTracker};
4use crate::{Node, NoveltyTable, SearchResult, WidthProblem, extract_plan};
5
6/// IW(k): breadth-first search that prunes every generated state whose
7/// novelty exceeds `k`. Runs in `O(n^k)` expansions for `n` features.
8///
9/// # Panics
10///
11/// Panics if `k` is 0.
12pub fn iw<P: WidthProblem>(problem: &P, k: usize) -> SearchResult<P::Action> {
13    iw_from(problem, problem.initial_state(), k, |s| problem.is_goal(s)).0
14}
15
16/// IW(k) from `root` towards the states accepted by `is_goal`.
17///
18/// Returns the result and, if a plan was found, the state it ends in. Goal
19/// states are never pruned, whatever their novelty.
20pub(crate) fn iw_from<P: WidthProblem>(
21    problem: &P,
22    root: P::State,
23    k: usize,
24    is_goal: impl Fn(&P::State) -> bool,
25) -> (SearchResult<P::Action>, Option<P::State>) {
26    iw_plus_from(
27        problem,
28        root,
29        k,
30        is_goal,
31        None::<fn(&P::State, &mut Vec<u32>)>,
32    )
33}
34
35/// IW(k) from `root`, with novelty computed separately for each `#r`
36/// (IW+ when `oracle` is set, plain IW otherwise).
37///
38/// `oracle` gives the relaxed-plan features of `root`, computed once per run;
39/// `#r` of a node counts those reached on its path, except those already
40/// true at `root`, as in [`bfws_r`](crate::bfws_r). Returns the result and, if a plan was found,
41/// the state it ends in. Goal states are never pruned.
42pub(crate) fn iw_plus_from<P, F>(
43    problem: &P,
44    root: P::State,
45    k: usize,
46    is_goal: impl Fn(&P::State) -> bool,
47    oracle: Option<F>,
48) -> (SearchResult<P::Action>, Option<P::State>)
49where
50    P: WidthProblem,
51    F: FnMut(&P::State, &mut Vec<u32>),
52{
53    let mut feats = Vec::new();
54    let mut succ = Vec::new();
55    let mut result = SearchResult {
56        plan: None,
57        expanded: 0,
58        generated: 1,
59    };
60
61    problem.features(&root, &mut feats);
62    let mut novelty = PartitionedNovelty::new(problem.num_features(), k, oracle);
63    let root_rel = novelty.start(&root, &feats);
64    if is_goal(&root) {
65        result.plan = Some(Vec::new());
66        return (result, Some(root));
67    }
68
69    let mut nodes = vec![Node {
70        state: root,
71        parent: None,
72        action: None,
73    }];
74    let mut rels = vec![root_rel];
75    let mut open = VecDeque::from([0usize]);
76
77    while let Some(i) = open.pop_front() {
78        result.expanded += 1;
79        succ.clear();
80        problem.successors(&nodes[i].state, &mut succ);
81        for (action, state) in succ.drain(..) {
82            result.generated += 1;
83            let goal = is_goal(&state);
84            feats.clear();
85            problem.features(&state, &mut feats);
86            let (novel, rel) = novelty.evaluate(rels[i].as_ref(), &feats);
87            if !novel && !goal {
88                continue;
89            }
90
91            nodes.push(Node {
92                state,
93                parent: Some(i),
94                action: Some(action),
95            });
96            rels.push(rel);
97            let j = nodes.len() - 1;
98            if goal {
99                result.plan = Some(extract_plan(&nodes, j));
100                return (result, Some(nodes.swap_remove(j).state));
101            }
102
103            open.push_back(j);
104        }
105    }
106
107    (result, None)
108}
109
110/// The novelty tables of one IW run, one per `#r` value, created on first use.
111struct PartitionedNovelty<F> {
112    /// Computes `#r`; disabled for plain IW, which then has one partition.
113    tracker: RelevanceTracker<F>,
114    /// Novelty table of each `#r`, indexed by it; `None` until first used.
115    tables: Vec<Option<NoveltyTable>>,
116    /// Number of features of the problem.
117    num_features: usize,
118    /// Width bound of every table.
119    k: usize,
120}
121
122impl<F> PartitionedNovelty<F> {
123    /// Empty tables for features `0..num_features` and width `k`.
124    fn new(num_features: usize, k: usize, oracle: Option<F>) -> Self {
125        Self {
126            tracker: RelevanceTracker::new(oracle),
127            tables: Vec::new(),
128            num_features,
129            k,
130        }
131    }
132
133    /// Computes the relevant set at the root, sizes the tables for it, and
134    /// records the root's tuples. Returns the root's `#r` bookkeeping.
135    fn start<S>(&mut self, root: &S, feats: &[u32]) -> Option<Relevance>
136    where
137        F: FnMut(&S, &mut Vec<u32>),
138    {
139        let rel = self.tracker.recompute(root, feats);
140        let partitions = rel.as_ref().map_or(1, |r| self.tracker.set_len(r) + 1);
141        self.tables = std::iter::repeat_with(|| None).take(partitions).collect();
142        self.evaluate(None, feats);
143
144        rel
145    }
146
147    /// Whether a state with `feats` is novel (width at most `k`) in its
148    /// partition, and its `#r` bookkeeping. `parent` is the parent's
149    /// bookkeeping; `None` for the root or when `#r` is disabled.
150    fn evaluate(&mut self, parent: Option<&Relevance>, feats: &[u32]) -> (bool, Option<Relevance>) {
151        let rel = parent.map(|p| self.tracker.extend(p, feats));
152        let r = rel.as_ref().map_or(0, |r| r.count);
153        let (num_features, k) = (self.num_features, self.k);
154        let table = self.tables[r].get_or_insert_with(|| NoveltyTable::new(num_features, k));
155
156        (table.evaluate_and_insert(feats).is_some(), rel)
157    }
158}
159
160/// Runs IW(1), IW(2), ... up to `max_k`; returns the width that succeeded
161/// (if any) and the accumulated statistics.
162pub fn iterated_width<P: WidthProblem>(
163    problem: &P,
164    max_k: usize,
165) -> (Option<usize>, SearchResult<P::Action>) {
166    let mut total = SearchResult {
167        plan: None,
168        expanded: 0,
169        generated: 0,
170    };
171    for k in 1..=max_k {
172        let r = iw(problem, k);
173        total.expanded += r.expanded;
174        total.generated += r.generated;
175        if r.plan.is_some() {
176            total.plan = r.plan;
177            return (Some(k), total);
178        }
179    }
180    (None, total)
181}