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