Skip to main content

width_search/
iw.rs

1use std::collections::VecDeque;
2
3use crate::{Node, NoveltyTable, SearchResult, WidthProblem, extract_plan};
4
5/// IW(k): breadth-first search that prunes every generated state whose
6/// novelty exceeds `k`. Runs in `O(n^k)` expansions for `n` features.
7///
8/// # Panics
9///
10/// Panics if `k` is 0.
11pub fn iw<P: WidthProblem>(problem: &P, k: usize) -> SearchResult<P::Action> {
12    iw_from(problem, problem.initial_state(), k, |s| problem.is_goal(s)).0
13}
14
15/// IW(k) from `root` towards the states accepted by `is_goal`.
16///
17/// Returns the result and, if a plan was found, the state it ends in. Goal
18/// states are never pruned, whatever their novelty.
19pub(crate) fn iw_from<P: WidthProblem>(
20    problem: &P,
21    root: P::State,
22    k: usize,
23    is_goal: impl Fn(&P::State) -> bool,
24) -> (SearchResult<P::Action>, Option<P::State>) {
25    let mut table = NoveltyTable::new(problem.num_features(), k);
26    let mut feats = Vec::new();
27    let mut succ = Vec::new();
28    let mut result = SearchResult {
29        plan: None,
30        expanded: 0,
31        generated: 1,
32    };
33
34    problem.features(&root, &mut feats);
35    table.evaluate_and_insert(&feats);
36    if is_goal(&root) {
37        result.plan = Some(Vec::new());
38        return (result, Some(root));
39    }
40
41    let mut nodes = vec![Node {
42        state: root,
43        parent: None,
44        action: None,
45    }];
46    let mut open = VecDeque::from([0usize]);
47
48    while let Some(i) = open.pop_front() {
49        result.expanded += 1;
50        succ.clear();
51        problem.successors(&nodes[i].state, &mut succ);
52        for (action, state) in succ.drain(..) {
53            result.generated += 1;
54            let goal = is_goal(&state);
55            feats.clear();
56            problem.features(&state, &mut feats);
57            if table.evaluate_and_insert(&feats).is_none() && !goal {
58                continue;
59            }
60
61            nodes.push(Node {
62                state,
63                parent: Some(i),
64                action: Some(action),
65            });
66            let j = nodes.len() - 1;
67            if goal {
68                result.plan = Some(extract_plan(&nodes, j));
69                return (result, Some(nodes.swap_remove(j).state));
70            }
71
72            open.push_back(j);
73        }
74    }
75
76    (result, None)
77}
78
79/// Runs IW(1), IW(2), ... up to `max_k`; returns the width that succeeded
80/// (if any) and the accumulated statistics.
81pub fn iterated_width<P: WidthProblem>(
82    problem: &P,
83    max_k: usize,
84) -> (Option<usize>, SearchResult<P::Action>) {
85    let mut total = SearchResult {
86        plan: None,
87        expanded: 0,
88        generated: 0,
89    };
90    for k in 1..=max_k {
91        let r = iw(problem, k);
92        total.expanded += r.expanded;
93        total.generated += r.generated;
94        if r.plan.is_some() {
95            total.plan = r.plan;
96            return (Some(k), total);
97        }
98    }
99    (None, total)
100}