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 std::sync::OnceLock;
5
6use sas_plus::{Fact, OpId, State, Task};
7
8use crate::{GoalCount, RelaxedPlan, WidthProblem, sorted_set};
9
10/// A [`Task`] viewed as a [`WidthProblem`]: one feature per fact `var = value`,
11/// and the number of unsatisfied goal facts as `#g`.
12pub struct SasProblem<'a> {
13 /// The wrapped task.
14 task: &'a Task,
15 /// Feature id of `var = 0` for each variable; `var = v` is `offsets[var] + v`.
16 offsets: Vec<u32>,
17 /// Total number of facts, the sum of all domain sizes.
18 num_facts: usize,
19 /// The task's effects and axioms as delete-free rules, for relaxed plans.
20 /// Built on first use, so searches without relaxed plans never pay for it.
21 rules: OnceLock<Vec<Rule>>,
22}
23
24/// A delete-free rule `conditions → head`: one effect of an operator (its
25/// precondition plus the effect's conditions) or one axiom.
26struct Rule {
27 /// Feature ids that must all hold. Sorted ascending, no duplicates.
28 conditions: Vec<u32>,
29 /// The feature the rule makes true.
30 head: u32,
31 /// The operator the effect belongs to; `None` for an axiom.
32 op: Option<OpId>,
33 /// Cost of applying the rule: the operator cost, 0 for an axiom.
34 cost: u64,
35}
36
37impl<'a> SasProblem<'a> {
38 /// Wraps `task`, numbering its facts variable by variable.
39 #[must_use]
40 pub fn new(task: &'a Task) -> Self {
41 let mut offsets = Vec::with_capacity(task.num_variables());
42 let mut n = 0u32;
43 for v in &task.variables {
44 offsets.push(n);
45 n += v.domain_size;
46 }
47
48 Self {
49 task,
50 offsets,
51 num_facts: n as usize,
52 rules: OnceLock::new(),
53 }
54 }
55
56 /// The delete-free rules, built on the first call.
57 fn rules(&self) -> &[Rule] {
58 self.rules.get_or_init(|| self.build_rules())
59 }
60
61 /// One rule per operator effect (precondition plus effect conditions)
62 /// and one per axiom. Conditions are deduplicated: a fact that is both a
63 /// precondition and an effect condition counts once in `h_add`, not twice.
64 fn build_rules(&self) -> Vec<Rule> {
65 let fact = |f: &Fact| self.feature(f);
66 let effects = self
67 .task
68 .operators
69 .iter()
70 .enumerate()
71 .flat_map(|(id, op)| op.eff.iter().map(move |e| (id, op, e)));
72 let mut rules: Vec<Rule> = effects
73 .map(|(id, op, e)| Rule {
74 conditions: sorted_set(|out| {
75 out.extend(op.pre.iter().chain(&e.conditions).map(fact));
76 }),
77 head: fact(&e.fact),
78 op: Some(id),
79 cost: u64::from(op.cost),
80 })
81 .collect();
82 rules.extend(self.task.axioms.iter().map(|a| Rule {
83 conditions: sorted_set(|out| out.extend(a.conditions.iter().map(fact))),
84 head: fact(&a.head),
85 op: None,
86 cost: 0,
87 }));
88
89 rules
90 }
91
92 /// Feature id of `fact`.
93 fn feature(&self, fact: &Fact) -> u32 {
94 self.offsets[fact.var] + fact.value
95 }
96
97 /// The additive heuristic `h_add` of `state`: the sum, over all goal facts,
98 /// of the cheapest delete-relaxed cost of reaching that fact.
99 ///
100 /// Each fact true in `state` costs 0. A fact made true by a rule costs the
101 /// rule's cost plus the sum of its conditions' costs, minimised over all
102 /// rules. Operator effects become rules with the operator's precondition
103 /// and the effect's conditions; axioms become rules of cost 0. Derived
104 /// variables are read from `state` as given, so pass a state with axioms
105 /// evaluated, such as one from [`Task::initial_state`] or [`Task::apply`].
106 ///
107 /// Returns `None` when some goal fact is unreachable even under the delete
108 /// relaxation. On tasks without axioms this proves `state` a dead end.
109 /// With axioms it may not: no rule makes a derived variable's default
110 /// value true, so a default that does not hold in `state` is unreachable.
111 ///
112 /// `h_add` is not admissible: shared subgoals are counted once per goal
113 /// fact that needs them. The value saturates at `u64::MAX` instead of
114 /// overflowing.
115 ///
116 /// These are the costs whose best supporters
117 /// [`RelaxedPlan::relaxed_plan_features`] extracts its relaxed plan from.
118 ///
119 /// # Examples
120 ///
121 /// Picking up a key (cost 2) and then opening a door with it (cost 3),
122 /// with both "holding the key" and "door open" as goals:
123 ///
124 /// ```
125 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
126 /// use width_search::sas::SasProblem;
127 ///
128 /// let task = Task {
129 /// variables: vec![Variable::new("key", 2), Variable::new("door", 2)],
130 /// operators: vec![
131 /// Operator {
132 /// name: "pick-up-key".into(),
133 /// pre: vec![],
134 /// eff: vec![Effect::new(Fact::new(0, 1))],
135 /// cost: 2,
136 /// },
137 /// Operator {
138 /// name: "open-door".into(),
139 /// pre: vec![Fact::new(0, 1)],
140 /// eff: vec![Effect::new(Fact::new(1, 1))],
141 /// cost: 3,
142 /// },
143 /// ],
144 /// initial: State(vec![0, 0]),
145 /// goal: vec![Fact::new(0, 1), Fact::new(1, 1)],
146 /// axioms: vec![],
147 /// };
148 /// let problem = SasProblem::new(&task);
149 ///
150 /// // key: 2, door: 2 + 3. The key's cost is counted twice, so h_add (7)
151 /// // overestimates the optimal plan cost (5).
152 /// assert_eq!(problem.h_add(&task.initial_state()), Some(7));
153 /// assert_eq!(problem.h_add(&State(vec![1, 0])), Some(3));
154 /// assert_eq!(problem.h_add(&State(vec![1, 1])), Some(0));
155 /// ```
156 #[must_use]
157 pub fn h_add(&self, state: &State) -> Option<u64> {
158 let (cost, _) = self.relaxed_costs(state);
159
160 self.task.goal.iter().try_fold(0u64, |acc, f| {
161 cost[self.feature(f) as usize].map(|x| acc.saturating_add(x))
162 })
163 }
164
165 /// `h_add` cost of every fact from `state` and, for each fact reached by a
166 /// rule, the index of its cheapest supporting rule.
167 ///
168 /// Unreachable facts cost `None`. Costs saturate at `u64::MAX`: a rule sums
169 /// its conditions, so costs can double per layer and overflow on deep tasks.
170 /// Rules are relaxed until nothing
171 /// improves; shortcut: `O(facts · rules)` sweeps worst case, fine for the
172 /// task sizes this adapter targets, upgrade to a priority queue for large tasks.
173 fn relaxed_costs(&self, state: &State) -> (Vec<Option<u64>>, Vec<Option<usize>>) {
174 let mut cost = vec![None; self.num_facts];
175 let mut supporter = vec![None; self.num_facts];
176 for f in self.features_of(state) {
177 cost[f as usize] = Some(0);
178 }
179
180 let mut changed = true;
181 while changed {
182 changed = false;
183 for (i, rule) in self.rules().iter().enumerate() {
184 let Some(pre) = rule.conditions.iter().try_fold(0u64, |acc, &c| {
185 cost[c as usize].map(|x| acc.saturating_add(x))
186 }) else {
187 continue;
188 };
189 let total = pre.saturating_add(rule.cost);
190 let head = rule.head as usize;
191 if cost[head].is_none_or(|old| total < old) {
192 cost[head] = Some(total);
193 supporter[head] = Some(i);
194 changed = true;
195 }
196 }
197 }
198
199 (cost, supporter)
200 }
201
202 /// The feature ids true in `state`.
203 fn features_of<'s>(&'s self, state: &'s State) -> impl Iterator<Item = u32> + 's {
204 state.0.iter().zip(&self.offsets).map(|(&v, &o)| o + v)
205 }
206
207 /// The wrapped task, for validating or printing plans.
208 #[must_use]
209 pub fn task(&self) -> &Task {
210 self.task
211 }
212}
213
214impl WidthProblem for SasProblem<'_> {
215 type State = State;
216 type Action = OpId;
217
218 fn initial_state(&self) -> State {
219 self.task.initial_state()
220 }
221 fn successors(&self, state: &State, out: &mut Vec<(OpId, State)>) {
222 out.extend(
223 self.task
224 .applicable_operators(state)
225 .map(|op| (op, self.task.apply(op, state))),
226 );
227 }
228 fn features(&self, state: &State, out: &mut Vec<u32>) {
229 out.extend(self.features_of(state));
230 }
231 fn num_features(&self) -> usize {
232 self.num_facts
233 }
234 fn is_goal(&self, state: &State) -> bool {
235 self.task.is_goal(state)
236 }
237}
238
239impl GoalCount for SasProblem<'_> {
240 fn unsatisfied_goals(&self, state: &State) -> usize {
241 self.task
242 .goal
243 .iter()
244 .filter(|f| state.0[f.var] != f.value)
245 .count()
246 }
247}
248
249/// The relaxed plan is extracted from `h_add` best supporters, and its
250/// features are all effects of its operators, as in LAPKT. Axioms on the way
251/// are followed but contribute no features of their own.
252impl RelaxedPlan for SasProblem<'_> {
253 fn relaxed_plan_features(&self, state: &State, out: &mut Vec<u32>) {
254 let (cost, supporter) = self.relaxed_costs(state);
255 let goals: Vec<u32> = self.task.goal.iter().map(|f| self.feature(f)).collect();
256 if goals.iter().any(|&g| cost[g as usize].is_none()) {
257 return;
258 }
259
260 let mut ops = vec![false; self.task.operators.len()];
261 let mut done = vec![false; self.num_facts];
262 let mut stack = goals;
263 while let Some(f) = stack.pop() {
264 if std::mem::replace(&mut done[f as usize], true) {
265 continue;
266 }
267
268 // Facts true in `state` have no supporter and end the chain.
269 let Some(r) = supporter[f as usize] else {
270 continue;
271 };
272 let rule = &self.rules()[r];
273 if let Some(op) = rule.op {
274 ops[op] = true;
275 }
276
277 stack.extend(&rule.conditions);
278 }
279
280 for (op, _) in ops.iter().enumerate().filter(|&(_, &used)| used) {
281 out.extend(
282 self.task.operators[op]
283 .eff
284 .iter()
285 .map(|e| self.feature(&e.fact)),
286 );
287 }
288 }
289}