Skip to main content

width_search/hiw/
incremental.rs

1use std::collections::HashSet;
2
3use super::run;
4use crate::rng::SplitMix64;
5use crate::{Node, SearchResult, WidthProblem, sorted_set};
6
7/// Incremental HIW, IHIW(`w_high`, `w_low`) (Junyent, Jonsson & Gómez,
8/// ICAPS 2021, Algorithms 1 and 2): [`hiw`](super::hiw) that picks its own
9/// high-level features from the problem's features.
10///
11/// It runs a series of HIW searches. The first has no high-level features,
12/// so it is IW(`w_low`). After a failed search, its pruned states join a
13/// pool. IHIW draws pruned states from the pool at random until one yields
14/// candidate features, then promotes one random candidate to a high-level
15/// feature and searches again. A high-level feature `f` here means "feature
16/// `f` is true", so the high-level features of a state are its features that
17/// were promoted so far.
18///
19/// The candidates of a pruned state `n` with parent `p` (Algorithm 1) are the
20/// features true in both `n` and `p` that are true in no state on the path
21/// above `p`, the root included: a feature that changed once, just before
22/// the branch was pruned, likely splits the state space (like picking up a
23/// key). `p` must not be the root, and `n` must differ from `p` in some
24/// feature; otherwise `n` has no candidates.
25///
26/// The search returns the first plan found and gives up (`plan: None`) when
27/// the pool runs out of states with new candidates. It promotes at most one
28/// feature per round, so it runs at most `num_features() + 1` searches. The
29/// paper restructures the previous search tree to reuse it; this version
30/// starts every search afresh, which costs nodes but finds the same plans.
31/// Node counts add up over all searches, and every search's tree is kept
32/// until the end, since pruned states from any round may be drawn. `seed`
33/// fixes the random draws.
34///
35/// # Panics
36///
37/// Panics if `w_high` or `w_low` is 0.
38pub fn ihiw<P: WidthProblem>(
39    problem: &P,
40    w_high: usize,
41    w_low: usize,
42    seed: u64,
43) -> SearchResult<P::Action> {
44    assert!(w_high >= 1, "width bound must be at least 1");
45    let mut rng = SplitMix64::new(seed);
46    let mut chosen = vec![false; problem.num_features()];
47    let mut total = SearchResult {
48        plan: None,
49        expanded: 0,
50        generated: 0,
51    };
52    let mut trees = Vec::new();
53    let mut pool = Vec::new();
54    let mut candidates = Vec::new();
55
56    loop {
57        let high = |s: &P::State, out: &mut Vec<u32>| {
58            problem.features(s, out);
59            out.retain(|&f| chosen[f as usize]);
60        };
61        let run = run(problem, high, chosen.len(), w_high, w_low, true);
62        total.expanded += run.result.expanded;
63        total.generated += run.result.generated;
64        if run.result.plan.is_some() {
65            total.plan = run.result.plan;
66            return total;
67        }
68
69        let round = trees.len();
70        pool.extend(
71            run.pruned
72                .into_iter()
73                .map(|(parent, state)| (round, parent, state)),
74        );
75        trees.push(run.nodes);
76
77        let Some(feature) = next_feature(
78            problem,
79            &trees,
80            &mut pool,
81            &mut candidates,
82            &chosen,
83            &mut rng,
84        ) else {
85            return total;
86        };
87        chosen[feature as usize] = true;
88    }
89}
90
91/// Algorithm 2's choice of the next high-level feature: a random candidate
92/// not chosen yet, refilling the candidates from random pruned states of the
93/// `pool` (round, parent index, state) while none is left. `None` once the
94/// pool is empty too.
95fn next_feature<P: WidthProblem>(
96    problem: &P,
97    trees: &[Vec<Node<P::State, P::Action>>],
98    pool: &mut Vec<(usize, usize, P::State)>,
99    candidates: &mut Vec<u32>,
100    chosen: &[bool],
101    rng: &mut SplitMix64,
102) -> Option<u32> {
103    loop {
104        candidates.retain(|&f| !chosen[f as usize]);
105        if !candidates.is_empty() {
106            return Some(candidates.swap_remove(rng.below(candidates.len())));
107        }
108
109        if pool.is_empty() {
110            return None;
111        }
112
113        let (round, parent, state) = pool.swap_remove(rng.below(pool.len()));
114        *candidates = feature_candidates(problem, &trees[round], parent, &state);
115    }
116}
117
118/// Algorithm 1: the candidate high-level features of a pruned `state` whose
119/// parent is `nodes[parent]`, sorted.
120fn feature_candidates<P: WidthProblem>(
121    problem: &P,
122    nodes: &[Node<P::State, P::Action>],
123    parent: usize,
124    state: &P::State,
125) -> Vec<u32> {
126    // The paper's `Depth(n) > 2` counts the nodes on the branch, root
127    // included: the parent must not be the root.
128    if nodes[parent].parent.is_none() {
129        return Vec::new();
130    }
131
132    let own = sorted_set(|out| problem.features(state, out));
133    let from_parent = sorted_set(|out| problem.features(&nodes[parent].state, out));
134    let mut common: Vec<u32> = own
135        .iter()
136        .copied()
137        .filter(|f| from_parent.binary_search(f).is_ok())
138        .collect();
139    if common.len() == own.len() {
140        return Vec::new();
141    }
142
143    let mut above = HashSet::new();
144    let mut i = nodes[parent].parent;
145    while let Some(n) = i {
146        above.extend(sorted_set(|out| problem.features(&nodes[n].state, out)));
147        i = nodes[n].parent;
148    }
149
150    common.retain(|f| !above.contains(f));
151    common
152}
153
154#[cfg(test)]
155mod tests {
156    use super::*;
157    use crate::hiw::tests::Corridor;
158
159    /// The paper's corridor, with holding the key as a feature of its own.
160    fn corridor(len: u32) -> Corridor {
161        Corridor {
162            key_feature: true,
163            ..Corridor::new(len)
164        }
165    }
166
167    /// IW(1) fails on the corridor; IHIW(1, 1) finds the key feature in the
168    /// first failed search and solves it in the second, for every seed.
169    #[test]
170    fn discovers_the_key_as_high_level_feature() {
171        let problem = corridor(5);
172        assert!(crate::iw(&problem, 1).plan.is_none());
173
174        for seed in 0..20 {
175            let r = ihiw(&problem, 1, 1, seed);
176            assert_eq!(
177                r.plan.as_deref(),
178                Some(&[1, 1, 1, 1, 1, -1, -1, -1, -1, -1][..]),
179                "seed {seed}"
180            );
181        }
182    }
183
184    /// Only the state pruned after picking up the key has a candidate: the
185    /// key, true in it and its parent but nowhere above.
186    #[test]
187    fn candidates_are_features_that_changed_once_before_the_prune() {
188        let problem = corridor(5);
189        let run = run(
190            &problem,
191            |_: &(u32, bool), _: &mut Vec<u32>| {},
192            7,
193            1,
194            1,
195            true,
196        );
197        let found: Vec<Vec<u32>> = run
198            .pruned
199            .iter()
200            .map(|(parent, state)| feature_candidates(&problem, &run.nodes, *parent, state))
201            .collect();
202
203        assert_eq!(found.iter().filter(|c| !c.is_empty()).count(), 1);
204        assert!(found.contains(&vec![6]), "the key feature, id len + 1");
205    }
206
207    /// Without any splitting feature to find, IHIW gives up once the pool
208    /// is empty instead of looping.
209    #[test]
210    fn gives_up_without_candidates() {
211        let r = ihiw(&Corridor::new(5), 1, 1, 0);
212
213        assert!(r.plan.is_none());
214    }
215}