Skip to main content

width_search/
sketch.rs

1use std::cell::RefCell;
2use std::collections::HashSet;
3use std::hash::Hash;
4
5use crate::siw::{Subgoals, serialize};
6use crate::{SearchResult, WidthProblem};
7
8/// A condition of a sketch [`Rule`] on the feature values of the state a
9/// subproblem starts from. The `usize` is the feature's index.
10///
11/// Boolean features are 0 (false) or 1 (true), so `Zero` reads as ¬p and
12/// `Positive` as p.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Condition {
15    /// The feature is 0 (`n = 0`, or ¬p).
16    Zero(usize),
17    /// The feature is above 0 (`n > 0`, or p).
18    Positive(usize),
19}
20
21/// An effect of a sketch [`Rule`]: how a feature may change between the
22/// start state of a subproblem and its subgoal. The `usize` is the
23/// feature's index. Features no effect mentions must keep their value.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum Effect {
26    /// The feature ends above 0 (p).
27    Positive(usize),
28    /// The feature ends at 0 (¬p).
29    Zero(usize),
30    /// The feature ends higher than it started (`n↑`).
31    Increase(usize),
32    /// The feature ends lower than it started (`n↓`).
33    Decrease(usize),
34    /// The feature may take any value (`p?`, `n?`).
35    Any(usize),
36}
37
38impl Effect {
39    /// The index of the feature this effect is about.
40    fn feature(self) -> usize {
41        match self {
42            Self::Positive(f)
43            | Self::Zero(f)
44            | Self::Increase(f)
45            | Self::Decrease(f)
46            | Self::Any(f) => f,
47        }
48    }
49
50    /// Whether a change of its feature from `from` to `to` satisfies this effect.
51    fn allows(self, from: u64, to: u64) -> bool {
52        match self {
53            Self::Positive(_) => to > 0,
54            Self::Zero(_) => to == 0,
55            Self::Increase(_) => to > from,
56            Self::Decrease(_) => to < from,
57            Self::Any(_) => true,
58        }
59    }
60}
61
62/// A sketch rule `C ↦ E` (Bonet & Geffner): from a state that satisfies
63/// every condition in `C`, any state whose feature values changed as `E`
64/// says is a subgoal.
65#[derive(Clone, Debug, Default, PartialEq, Eq)]
66pub struct Rule {
67    /// Conditions on the start state; all must hold. Empty means always.
68    pub conditions: Vec<Condition>,
69    /// Allowed changes. Features not mentioned here must stay the same; a
70    /// feature mentioned twice must satisfy both effects.
71    pub effects: Vec<Effect>,
72}
73
74impl Rule {
75    /// Whether the pair of feature vectors `(from, to)` is compatible with
76    /// this rule.
77    ///
78    /// # Panics
79    ///
80    /// Panics if the rule names a feature index outside `from`.
81    fn allows(&self, from: &[u64], to: &[u64]) -> bool {
82        let conditions = self.conditions.iter().all(|c| match *c {
83            Condition::Zero(f) => value(from, f) == 0,
84            Condition::Positive(f) => value(from, f) > 0,
85        });
86        if !conditions {
87            return false;
88        }
89
90        let effects = self
91            .effects
92            .iter()
93            .all(|e| e.allows(value(from, e.feature()), value(to, e.feature())));
94        let others_unchanged = (0..from.len())
95            .filter(|&f| self.effects.iter().all(|e| e.feature() != f))
96            .all(|f| from[f] == to[f]);
97
98        effects && others_unchanged
99    }
100}
101
102/// The value of feature `f` in `values`.
103///
104/// # Panics
105///
106/// Panics if `f` is out of range, with a message naming the sketch.
107fn value(values: &[u64], f: usize) -> u64 {
108    *values.get(f).unwrap_or_else(|| {
109        panic!(
110            "sketch rule names feature {f}, but only {} features are defined",
111            values.len()
112        )
113    })
114}
115
116/// SIW-R (Drexler, Seipp & Geffner, KR 2021): serialized IW with subgoals
117/// given by a sketch.
118///
119/// `features` pushes the sketch feature values of a state, one `u64` per
120/// feature in a fixed order: 0 or 1 for Boolean features, counts for
121/// numerical ones. These are separate from the novelty features of
122/// [`WidthProblem::features`]. From the current state `s`, IW(1), IW(2), ...
123/// up to `max_k` run until they reach a goal state, or a state `s' != s` such
124/// that `(s, s')` is compatible with some rule in `rules`. The subplans are
125/// concatenated.
126///
127/// With one numerical feature `#g` (unsatisfied goals) and the single rule
128/// `{#g > 0} ↦ {#g↓}`, this is [`siw`](fn@crate::siw). Good sketches split a
129/// problem into subproblems of low width; with an empty sketch, only goal
130/// states are subgoals.
131///
132/// SIW-R is incomplete: it gives up (`plan: None`) when no subgoal is
133/// reachable within width `max_k`, and when it reaches a subgoal state it has
134/// already passed through, since the search is deterministic and would cycle
135/// (the sketch is not terminating). Node counts add up over all IW runs.
136///
137/// # Panics
138///
139/// Panics if a rule names a feature index that `features` does not produce,
140/// or if `features` pushes different numbers of values for different states.
141pub fn siw_r<P, F>(
142    problem: &P,
143    rules: &[Rule],
144    features: F,
145    max_k: usize,
146) -> SearchResult<P::Action>
147where
148    P: WidthProblem,
149    P::State: Hash + Eq,
150    F: Fn(&P::State, &mut Vec<u64>),
151{
152    let subgoals = SketchSubgoals {
153        problem,
154        rules,
155        features,
156        passed: HashSet::from([problem.initial_state()]),
157        buf: RefCell::new(Vec::new()),
158    };
159
160    serialize(
161        problem,
162        max_k,
163        None::<fn(&P::State, &mut Vec<u32>)>,
164        subgoals,
165    )
166}
167
168/// The subgoals of [`siw_r`]: goal states, and states a sketch rule allows.
169struct SketchSubgoals<'p, P: WidthProblem, F> {
170    /// The problem being searched, for its goal test.
171    problem: &'p P,
172    /// The sketch.
173    rules: &'p [Rule],
174    /// Computes the sketch feature values of a state.
175    features: F,
176    /// Every state a subproblem started from so far, the initial one included.
177    passed: HashSet<P::State>,
178    /// Reused buffer for the feature values of a candidate subgoal, so the
179    /// per-state test does not allocate.
180    buf: RefCell<Vec<u64>>,
181}
182
183impl<P, F> SketchSubgoals<'_, P, F>
184where
185    P: WidthProblem,
186    F: Fn(&P::State, &mut Vec<u64>),
187{
188    /// The sketch feature values of `state`, in a new vector.
189    fn values(&self, state: &P::State) -> Vec<u64> {
190        let mut out = Vec::new();
191        (self.features)(state, &mut out);
192        out
193    }
194
195    /// Whether some rule allows the change from `from_values` to the
196    /// feature values of `state`, computed into the reused buffer.
197    fn allows(&self, from_values: &[u64], state: &P::State) -> bool {
198        let mut buf = self.buf.borrow_mut();
199        buf.clear();
200        (self.features)(state, &mut buf);
201        allowed(self.rules, from_values, &buf)
202    }
203}
204
205impl<P, F> Subgoals<P::State> for SketchSubgoals<'_, P, F>
206where
207    P: WidthProblem,
208    P::State: Hash + Eq,
209    F: Fn(&P::State, &mut Vec<u64>),
210{
211    /// The start state and its sketch feature values.
212    type Anchor = (P::State, Vec<u64>);
213
214    fn anchor(&mut self, from: &P::State) -> Self::Anchor {
215        (from.clone(), self.values(from))
216    }
217
218    fn reached(&self, (from, from_values): &Self::Anchor, state: &P::State) -> bool {
219        self.problem.is_goal(state) || (state != from && self.allows(from_values, state))
220    }
221
222    /// A subgoal passed before means the deterministic search would cycle.
223    fn advance(&mut self, state: &P::State) -> bool {
224        self.passed.insert(state.clone())
225    }
226}
227
228/// Whether some rule allows the change from `from` to `to`.
229///
230/// # Panics
231///
232/// Panics if the two vectors differ in length, or a rule names a feature
233/// outside them.
234fn allowed(rules: &[Rule], from: &[u64], to: &[u64]) -> bool {
235    assert_eq!(
236        from.len(),
237        to.len(),
238        "sketch features must push the same number of values for every state"
239    );
240    rules.iter().any(|r| r.allows(from, to))
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use crate::test_problems::Line;
247
248    /// The position as the single sketch feature of a [`Line`].
249    #[expect(
250        clippy::trivially_copy_pass_by_ref,
251        reason = "matches the sketch feature closure signature"
252    )]
253    fn position(s: &u32, out: &mut Vec<u64>) {
254        out.push(u64::from(*s));
255    }
256
257    /// `{} ↦ {n↑}`: every step to the right is a subgoal, one IW(1) run each.
258    #[test]
259    fn an_increasing_sketch_steps_to_the_goal() {
260        let rules = [Rule {
261            conditions: vec![],
262            effects: vec![Effect::Increase(0)],
263        }];
264        let r = siw_r(&Line { len: 6 }, &rules, position, 1);
265
266        assert_eq!(r.plan.as_deref(), Some(&[1; 6][..]));
267    }
268
269    /// `{} ↦ {n?}` accepts any other state, so the search steps back and
270    /// forth between 0 and 1; it gives up when 0 comes around again.
271    #[test]
272    fn a_cycling_sketch_gives_up() {
273        let rules = [Rule {
274            conditions: vec![],
275            effects: vec![Effect::Any(0)],
276        }];
277        let r = siw_r(&Line { len: 6 }, &rules, position, 1);
278
279        assert!(r.plan.is_none());
280    }
281
282    /// A condition that never holds leaves only the goal as a subgoal.
283    #[test]
284    fn unmet_conditions_leave_only_the_goal() {
285        let rules = [Rule {
286            conditions: vec![Condition::Zero(0), Condition::Positive(0)],
287            effects: vec![Effect::Any(0)],
288        }];
289        let r = siw_r(&Line { len: 4 }, &rules, position, 1);
290
291        assert_eq!(r.plan.as_deref(), Some(&[1; 4][..]));
292    }
293
294    /// The effect kinds on single values, and unmentioned features.
295    #[test]
296    fn rule_compatibility() {
297        let rule = |effects| Rule {
298            conditions: vec![],
299            effects,
300        };
301
302        assert!(rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 5]));
303        assert!(!rule(vec![Effect::Positive(0)]).allows(&[0, 5], &[2, 6]));
304        assert!(rule(vec![Effect::Zero(0)]).allows(&[3], &[0]));
305        assert!(rule(vec![Effect::Decrease(0)]).allows(&[3], &[2]));
306        assert!(!rule(vec![Effect::Decrease(0)]).allows(&[3], &[3]));
307        assert!(rule(vec![]).allows(&[3, 1], &[3, 1]));
308    }
309
310    /// A rule naming a feature that does not exist is a sketch bug.
311    #[test]
312    #[should_panic(expected = "names feature 3")]
313    fn rejects_unknown_features() {
314        let rules = [Rule {
315            conditions: vec![Condition::Positive(3)],
316            effects: vec![],
317        }];
318        siw_r(&Line { len: 2 }, &rules, position, 1);
319    }
320}