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 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/// 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.
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.
63    fn build_rules(&self) -> Vec<Rule> {
64        let fact = |f: &Fact| self.feature(f);
65        let effects = self
66            .task
67            .operators
68            .iter()
69            .enumerate()
70            .flat_map(|(id, op)| op.eff.iter().map(move |e| (id, op, e)));
71        let mut rules: Vec<Rule> = effects
72            .map(|(id, op, e)| Rule {
73                conditions: op.pre.iter().chain(&e.conditions).map(fact).collect(),
74                head: fact(&e.fact),
75                op: Some(id),
76                cost: u64::from(op.cost),
77            })
78            .collect();
79        rules.extend(self.task.axioms.iter().map(|a| Rule {
80            conditions: a.conditions.iter().map(fact).collect(),
81            head: fact(&a.head),
82            op: None,
83            cost: 0,
84        }));
85
86        rules
87    }
88
89    /// Feature id of `fact`.
90    fn feature(&self, fact: &Fact) -> u32 {
91        self.offsets[fact.var] + fact.value
92    }
93
94    /// `h_add` cost of every fact from `state` and, for each fact reached by a
95    /// rule, the index of its cheapest supporting rule.
96    ///
97    /// Unreachable facts cost `None`. Rules are relaxed until nothing
98    /// improves; shortcut: `O(facts · rules)` sweeps worst case, fine for the
99    /// task sizes this adapter targets, upgrade to a priority queue for large tasks.
100    fn h_add(&self, state: &State) -> (Vec<Option<u64>>, Vec<Option<usize>>) {
101        let mut cost = vec![None; self.num_facts];
102        let mut supporter = vec![None; self.num_facts];
103        for f in self.features_of(state) {
104            cost[f as usize] = Some(0);
105        }
106
107        let mut changed = true;
108        while changed {
109            changed = false;
110            for (i, rule) in self.rules().iter().enumerate() {
111                let Some(pre) = rule
112                    .conditions
113                    .iter()
114                    .try_fold(0u64, |acc, &c| cost[c as usize].map(|x| acc + x))
115                else {
116                    continue;
117                };
118                let total = pre + rule.cost;
119                let head = rule.head as usize;
120                if cost[head].is_none_or(|old| total < old) {
121                    cost[head] = Some(total);
122                    supporter[head] = Some(i);
123                    changed = true;
124                }
125            }
126        }
127
128        (cost, supporter)
129    }
130
131    /// The feature ids true in `state`.
132    fn features_of<'s>(&'s self, state: &'s State) -> impl Iterator<Item = u32> + 's {
133        state.0.iter().zip(&self.offsets).map(|(&v, &o)| o + v)
134    }
135
136    /// The wrapped task, for validating or printing plans.
137    #[must_use]
138    pub fn task(&self) -> &Task {
139        self.task
140    }
141}
142
143impl WidthProblem for SasProblem<'_> {
144    type State = State;
145    type Action = OpId;
146
147    fn initial_state(&self) -> State {
148        self.task.initial_state()
149    }
150    fn successors(&self, state: &State, out: &mut Vec<(OpId, State)>) {
151        out.extend(
152            self.task
153                .applicable_operators(state)
154                .map(|op| (op, self.task.apply(op, state))),
155        );
156    }
157    fn features(&self, state: &State, out: &mut Vec<u32>) {
158        out.extend(self.features_of(state));
159    }
160    fn num_features(&self) -> usize {
161        self.num_facts
162    }
163    fn is_goal(&self, state: &State) -> bool {
164        self.task.is_goal(state)
165    }
166}
167
168impl GoalCount for SasProblem<'_> {
169    fn unsatisfied_goals(&self, state: &State) -> usize {
170        self.task
171            .goal
172            .iter()
173            .filter(|f| state.0[f.var] != f.value)
174            .count()
175    }
176}
177
178/// The relaxed plan is extracted from `h_add` best supporters, and its
179/// features are all effects of its operators, as in LAPKT. Axioms on the way
180/// are followed but contribute no features of their own.
181impl RelaxedPlan for SasProblem<'_> {
182    fn relaxed_plan_features(&self, state: &State, out: &mut Vec<u32>) {
183        let (cost, supporter) = self.h_add(state);
184        let goals: Vec<u32> = self.task.goal.iter().map(|f| self.feature(f)).collect();
185        if goals.iter().any(|&g| cost[g as usize].is_none()) {
186            return;
187        }
188
189        let mut ops = vec![false; self.task.operators.len()];
190        let mut done = vec![false; self.num_facts];
191        let mut stack = goals;
192        while let Some(f) = stack.pop() {
193            if std::mem::replace(&mut done[f as usize], true) {
194                continue;
195            }
196
197            // Facts true in `state` have no supporter and end the chain.
198            let Some(r) = supporter[f as usize] else {
199                continue;
200            };
201            let rule = &self.rules()[r];
202            if let Some(op) = rule.op {
203                ops[op] = true;
204            }
205
206            stack.extend(&rule.conditions);
207        }
208
209        for (op, _) in ops.iter().enumerate().filter(|&(_, &used)| used) {
210            out.extend(
211                self.task.operators[op]
212                    .eff
213                    .iter()
214                    .map(|e| self.feature(&e.fact)),
215            );
216        }
217    }
218}