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.
7pub fn iw<P: WidthProblem>(problem: &P, k: usize) -> SearchResult<P::Action> {
8    let mut table = NoveltyTable::new(problem.num_features(), k);
9    let mut feats = Vec::new();
10    let mut succ = Vec::new();
11    let mut result = SearchResult {
12        plan: None,
13        expanded: 0,
14        generated: 1,
15    };
16
17    let root = problem.initial_state();
18    problem.features(&root, &mut feats);
19    table.evaluate_and_insert(&feats);
20    if problem.is_goal(&root) {
21        result.plan = Some(Vec::new());
22        return result;
23    }
24    let mut nodes = vec![Node {
25        state: root,
26        parent: None,
27        action: None,
28    }];
29    let mut open = VecDeque::from([0usize]);
30
31    while let Some(i) = open.pop_front() {
32        result.expanded += 1;
33        succ.clear();
34        problem.successors(&nodes[i].state, &mut succ);
35        for (action, state) in succ.drain(..) {
36            result.generated += 1;
37            let goal = problem.is_goal(&state);
38            feats.clear();
39            problem.features(&state, &mut feats);
40            if table.evaluate_and_insert(&feats).is_none() && !goal {
41                continue;
42            }
43            nodes.push(Node {
44                state,
45                parent: Some(i),
46                action: Some(action),
47            });
48            let j = nodes.len() - 1;
49            if goal {
50                result.plan = Some(extract_plan(&nodes, j));
51                return result;
52            }
53            open.push_back(j);
54        }
55    }
56    result
57}
58
59/// Runs IW(1), IW(2), ... up to `max_k`; returns the width that succeeded
60/// (if any) and the accumulated statistics.
61pub fn iterated_width<P: WidthProblem>(
62    problem: &P,
63    max_k: usize,
64) -> (Option<usize>, SearchResult<P::Action>) {
65    let mut total = SearchResult {
66        plan: None,
67        expanded: 0,
68        generated: 0,
69    };
70    for k in 1..=max_k {
71        let r = iw(problem, k);
72        total.expanded += r.expanded;
73        total.generated += r.generated;
74        if r.plan.is_some() {
75            total.plan = r.plan;
76            return (Some(k), total);
77        }
78    }
79    (None, total)
80}