Skip to main content

planning_heuristics/
set_additive.rs

1//! The set-additive heuristic `h_sa` (Keyder & Geffner 2008).
2
3use alloc::borrow::Cow;
4use alloc::vec::Vec;
5
6use sas_plus::{OpId, State, Task};
7
8use crate::{Heuristic, Relaxation};
9
10/// Bits per word of an operator set.
11const WORD: usize = 64;
12
13/// The set-additive heuristic `h_sa` (Keyder & Geffner 2008): like `h_add`, but each fact
14/// carries a relaxed plan, a *set* of operators, instead of a cost, so an operator shared by
15/// two subgoals is counted once.
16///
17/// A rule `conditions → head` offers the union of its conditions' plans plus its operator;
18/// the head keeps the cheapest offer (by summed operator cost). The offers are swept until no
19/// plan gets cheaper (Bellman-Ford), and the estimate is the cost of the union of the goal
20/// facts' plans. Each offer costs at most `h_add`'s sum, so `h_sa <= h_add`. Without
21/// conditional effects the union is a relaxed plan, so `h_max <= h_sa`; with them, a relaxed
22/// plan may need one operator twice (before and after an effect condition holds), which the
23/// set counts once, so `h_sa` can fall below `h_max`. Not admissible.
24///
25/// One sweep is `O(rules × operators / 64)`; sweeps repeat until nothing improves.
26///
27/// # Examples
28///
29/// ```
30/// use planning_heuristics::{HAdd, HSetAdd, Heuristic};
31/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
32///
33/// // `tool` (cost 3) is needed for both goals: h_add counts it twice, h_sa once.
34/// let op = |name: &str, pre: Vec<Fact>, eff: Fact, cost: u32| Operator {
35///     name: name.into(),
36///     pre,
37///     eff: vec![Effect::new(eff)],
38///     cost,
39/// };
40/// let task = Task {
41///     variables: vec![Variable::new("tool", 2), Variable::new("a", 2), Variable::new("b", 2)],
42///     operators: vec![
43///         op("tool", vec![], Fact::new(0, 1), 3),
44///         op("a", vec![Fact::new(0, 1)], Fact::new(1, 1), 1),
45///         op("b", vec![Fact::new(0, 1)], Fact::new(2, 1), 1),
46///     ],
47///     initial: State(vec![0, 0, 0]),
48///     goal: vec![Fact::new(1, 1), Fact::new(2, 1)],
49///     axioms: vec![],
50/// };
51/// let state = task.initial_state();
52///
53/// assert_eq!(HAdd::new(&task).estimate(&state), Some(8));
54/// let mut h_sa = HSetAdd::new(&task);
55/// assert_eq!(h_sa.estimate(&state), Some(5));
56/// assert_eq!(h_sa.plan(&state).unwrap(), [0, 1, 2]);
57/// ```
58#[derive(Clone, Debug)]
59pub struct HSetAdd<'r> {
60    /// The relaxation of the task, owned or shared.
61    relaxation: Cow<'r, Relaxation>,
62    /// The cost of each operator.
63    costs: Vec<u64>,
64    /// Words per operator set.
65    words: usize,
66    /// Per fact, its plan as an operator bit set; valid only where [`HSetAdd::cost`] is set.
67    sets: Vec<u64>,
68    /// Per fact, the cost of its plan; `None` if unreached.
69    cost: Vec<Option<u64>>,
70    /// The offer being built.
71    offer: Vec<u64>,
72}
73
74impl HSetAdd<'static> {
75    /// Builds `h_sa` for `task`, owning its relaxation.
76    #[must_use]
77    pub fn new(task: &Task) -> Self {
78        Self::from_cow(Cow::Owned(Relaxation::new(task)))
79    }
80}
81
82impl<'r> HSetAdd<'r> {
83    /// Builds `h_sa` over a shared `relaxation`.
84    #[must_use]
85    pub fn with_relaxation(relaxation: &'r Relaxation) -> Self {
86        Self::from_cow(Cow::Borrowed(relaxation))
87    }
88
89    /// The heuristic over `relaxation` with empty buffers.
90    fn from_cow(relaxation: Cow<'r, Relaxation>) -> Self {
91        let costs: Vec<u64> = (0..relaxation.num_operators())
92            .map(|op| relaxation.op_rules(op).first().map_or(0, |r| r.cost))
93            .collect();
94        let words = costs.len().div_ceil(WORD);
95
96        Self {
97            relaxation,
98            costs,
99            words,
100            sets: Vec::new(),
101            cost: Vec::new(),
102            offer: Vec::new(),
103        }
104    }
105
106    /// `h_sa` of `state`; `None` if the goal is relaxed-unreachable.
107    ///
108    /// # Panics
109    ///
110    /// Panics if `state` has fewer values than the task has variables.
111    #[must_use]
112    pub fn value(&mut self, state: &State) -> Option<u64> {
113        self.compute(state)?;
114
115        Some(self.set_cost(&self.offer))
116    }
117
118    /// The relaxed plan behind [`HSetAdd::value`], as operators ascending; `None` for a dead
119    /// end. Applying them repeatedly under the delete relaxation reaches the goal.
120    ///
121    /// # Panics
122    ///
123    /// Panics if `state` has fewer values than the task has variables.
124    #[must_use]
125    pub fn plan(&mut self, state: &State) -> Option<Vec<OpId>> {
126        self.compute(state)?;
127
128        Some(
129            (0..self.costs.len())
130                .filter(|&op| self.offer[op / WORD] & (1 << (op % WORD)) != 0)
131                .collect(),
132        )
133    }
134
135    /// Sweeps the rules to the fixpoint and leaves the union of the goal plans in
136    /// [`HSetAdd::offer`]; `None` if a goal fact is unreached.
137    fn compute(&mut self, state: &State) -> Option<()> {
138        let relaxation = &*self.relaxation;
139        let facts = relaxation.num_facts();
140        self.sets.clear();
141        self.sets.resize(facts * self.words, 0);
142        self.cost.clear();
143        self.cost.resize(facts, None);
144        self.offer.clear();
145        self.offer.resize(self.words, 0);
146        for f in relaxation
147            .state_facts(state)
148            .chain(relaxation.free_facts().iter().copied())
149        {
150            self.cost[f as usize] = Some(0);
151        }
152
153        let rules = relaxation.rules().len();
154        let mut changed = true;
155        while changed {
156            changed = false;
157            for r in 0..rules {
158                changed |= self.offer_rule(r);
159            }
160        }
161
162        self.offer.fill(0);
163        for &g in self.relaxation.goal_facts() {
164            self.cost[g]?;
165            let set = &self.sets[g * self.words..(g + 1) * self.words];
166            for (o, &s) in self.offer.iter_mut().zip(set) {
167                *o |= s;
168            }
169        }
170
171        Some(())
172    }
173
174    /// Lets rule `r` offer its plan to its head; returns whether the head's plan got cheaper.
175    fn offer_rule(&mut self, r: usize) -> bool {
176        let rule = &self.relaxation.rules()[r];
177        if rule.conditions.iter().any(|&c| self.cost[c].is_none()) {
178            return false;
179        }
180
181        self.offer.fill(0);
182        for &c in &rule.conditions {
183            let set = &self.sets[c * self.words..(c + 1) * self.words];
184            for (o, &s) in self.offer.iter_mut().zip(set) {
185                *o |= s;
186            }
187        }
188
189        if let Some(op) = rule.op {
190            self.offer[op / WORD] |= 1 << (op % WORD);
191        }
192
193        let cost = self.set_cost(&self.offer);
194        let head = rule.head;
195        if self.cost[head].is_some_and(|old| old <= cost) {
196            return false;
197        }
198
199        self.cost[head] = Some(cost);
200        self.sets[head * self.words..(head + 1) * self.words].copy_from_slice(&self.offer);
201
202        true
203    }
204
205    /// The summed cost of the operators in `set`.
206    fn set_cost(&self, set: &[u64]) -> u64 {
207        let mut total = 0_u64;
208        for (w, &word) in set.iter().enumerate() {
209            let mut word = word;
210            while word != 0 {
211                let op = w * WORD + word.trailing_zeros() as usize;
212                total = total.saturating_add(self.costs[op]);
213                word &= word - 1;
214            }
215        }
216
217        total
218    }
219}
220
221impl Heuristic<State> for HSetAdd<'_> {
222    fn estimate(&mut self, state: &State) -> Option<u32> {
223        self.value(state)
224            .map(|v| u32::try_from(v).unwrap_or(u32::MAX))
225    }
226}