Skip to main content

width_search/
sas.rs

1//! Adapter: run width-based search directly on a [`sas_plus::Task`].
2//! Features are the task's facts `var = value`; plans are operator ids.
3
4use sas_plus::{OpId, State, Task};
5
6use crate::{GoalCount, WidthProblem};
7
8/// A [`Task`] viewed as a [`WidthProblem`]: one feature per fact `var = value`,
9/// and the number of unsatisfied goal facts as `#g`.
10pub struct SasProblem<'a> {
11    /// The wrapped task.
12    task: &'a Task,
13    /// Feature id of `var = 0` for each variable; `var = v` is `offsets[var] + v`.
14    offsets: Vec<u32>,
15    /// Total number of facts, the sum of all domain sizes.
16    num_facts: usize,
17}
18
19impl<'a> SasProblem<'a> {
20    /// Wraps `task`, numbering its facts variable by variable.
21    #[must_use]
22    pub fn new(task: &'a Task) -> Self {
23        let mut offsets = Vec::with_capacity(task.num_variables());
24        let mut n = 0u32;
25        for v in &task.variables {
26            offsets.push(n);
27            n += v.domain_size;
28        }
29
30        Self {
31            task,
32            offsets,
33            num_facts: n as usize,
34        }
35    }
36
37    /// The wrapped task, for validating or printing plans.
38    #[must_use]
39    pub fn task(&self) -> &Task {
40        self.task
41    }
42}
43
44impl WidthProblem for SasProblem<'_> {
45    type State = State;
46    type Action = OpId;
47
48    fn initial_state(&self) -> State {
49        self.task.initial_state()
50    }
51    fn successors(&self, state: &State, out: &mut Vec<(OpId, State)>) {
52        out.extend(
53            self.task
54                .applicable_operators(state)
55                .map(|op| (op, self.task.apply(op, state))),
56        );
57    }
58    fn features(&self, state: &State, out: &mut Vec<u32>) {
59        out.extend(state.0.iter().zip(&self.offsets).map(|(&v, &o)| o + v));
60    }
61    fn num_features(&self) -> usize {
62        self.num_facts
63    }
64    fn is_goal(&self, state: &State) -> bool {
65        self.task.is_goal(state)
66    }
67}
68
69impl GoalCount for SasProblem<'_> {
70    fn unsatisfied_goals(&self, state: &State) -> usize {
71        self.task
72            .goal
73            .iter()
74            .filter(|f| state.0[f.var] != f.value)
75            .count()
76    }
77}