Skip to main content

width_search/
siw.rs

1use crate::iw::iw_from;
2use crate::{GoalCount, SearchResult};
3
4/// Serialized IW (SIW): reaches the goal one subgoal at a time.
5///
6/// From the current state it runs IW(1), IW(2), ... up to `max_k` until a
7/// state with fewer unsatisfied goals (`#g`) is found, or a goal state. The
8/// plans of these searches are concatenated; each search starts with an
9/// empty novelty table.
10///
11/// This is a simplified SIW. LAPKT's SIW (after Lipovetzky & Geffner,
12/// ECAI 2012) tracks goal atoms: a subgoal state must keep every goal achieved
13/// so far, and a newly achieved goal is accepted only if the full goal stays
14/// reachable in the delete relaxation without actions that delete achieved
15/// goals. [`GoalCount`] exposes only the number of unsatisfied goals, so here
16/// any drop in `#g` counts. A subgoal may then undo earlier goals or commit to
17/// one that must be undone later, which gives longer plans (blocksworld).
18///
19/// SIW is incomplete: it gives up (`plan: None`) when no subgoal is reachable
20/// within width `max_k`. That happens in dead ends left by earlier subplans,
21/// but also in live states whose next subgoal needs a width above `max_k`.
22/// Node counts add up over all IW runs, failed ones included.
23pub fn siw<P: GoalCount>(problem: &P, max_k: usize) -> SearchResult<P::Action> {
24    // The initial state counts once, even if no IW run is needed.
25    let mut total = SearchResult {
26        plan: None,
27        expanded: 0,
28        generated: 0,
29    };
30    let mut state = problem.initial_state();
31    if problem.is_goal(&state) {
32        total.generated = 1;
33    }
34
35    let mut plan = Vec::new();
36
37    while !problem.is_goal(&state) {
38        let Some((subplan, next)) = reach_subgoal(problem, &state, max_k, &mut total) else {
39            return total;
40        };
41        plan.extend(subplan);
42        state = next;
43    }
44
45    total.plan = Some(plan);
46    total
47}
48
49/// Iterated width from `state` until `#g` drops or the goal holds; returns
50/// the subplan and the state it reaches. Adds every run's counts to `total`.
51fn reach_subgoal<P: GoalCount>(
52    problem: &P,
53    state: &P::State,
54    max_k: usize,
55    total: &mut SearchResult<P::Action>,
56) -> Option<(Vec<P::Action>, P::State)> {
57    let g = problem.unsatisfied_goals(state);
58    let is_subgoal = |s: &P::State| problem.is_goal(s) || problem.unsatisfied_goals(s) < g;
59
60    for k in 1..=max_k {
61        let (r, end) = iw_from(problem, state.clone(), k, is_subgoal);
62        total.expanded += r.expanded;
63        total.generated += r.generated;
64        if let (Some(subplan), Some(end)) = (r.plan, end) {
65            return Some((subplan, end));
66        }
67    }
68
69    None
70}