Skip to main content

decoupled_search/
heuristic.rs

1//! Heuristics on decoupled states.
2//!
3//! A decoupled state stands for every explicit state that combines its
4//! center with one reached leaf state per leaf, each leaf state bought at its
5//! price. A heuristic sees this through [`FactPrices`]: the cheapest price at
6//! which each fact holds in some member state (0 for center facts). Seeding a
7//! delete relaxation with those prices instead of a single state gives
8//! [`HMax`] (admissible) and [`HFf`] (inadmissible, for greedy search),
9//! implemented here without a dependency on a heuristics crate.
10//!
11//! ```mermaid
12//! graph LR
13//!     state[decoupled state] --> facts[FactPrices: cheapest price per fact]
14//!     facts --> relaxed[relaxed exploration over all operators]
15//!     relaxed --> hmax[HMax: max over goal costs]
16//!     relaxed --> hff[HFf: relaxed plan cost]
17//! ```
18
19#[cfg(feature = "lm-cut")]
20mod lm_cut;
21#[cfg(feature = "merge-and-shrink")]
22mod mas;
23mod relaxed;
24
25use alloc::borrow::Cow;
26use alloc::vec;
27use alloc::vec::Vec;
28
29use sas_plus::{Fact, State, Task, VarId};
30
31use crate::{Error, Factoring};
32#[cfg(feature = "lm-cut")]
33pub use lm_cut::LmCutHeuristic;
34#[cfg(feature = "merge-and-shrink")]
35pub use mas::MasHeuristic;
36use relaxed::Relaxation;
37
38/// The cheapest price at which each fact holds in some member state of a
39/// decoupled state.
40///
41/// Center facts that hold have price 0. A leaf fact has the cheapest price
42/// of a reached leaf state containing it. Facts no member state contains
43/// have no price.
44///
45/// Each variable also records its factor ([`FactPrices::leaf_of`]). A
46/// member state costs at least the sum, over the factors (the center counts
47/// as one), of the largest price of its facts in that factor: two facts of
48/// one leaf are bought together with one leaf state, facts of different
49/// leaves with different ones. Heuristics may rely on that bound.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct FactPrices<'a> {
52    /// Index of each variable's first value in [`FactPrices::prices`], plus
53    /// a final entry with the number of facts.
54    pub(crate) offsets: Cow<'a, [usize]>,
55    /// The leaf of each variable, `None` for center variables.
56    pub(crate) leaves: Cow<'a, [Option<usize>]>,
57    /// The price of every fact, by `offsets[var] + value`; `u64::MAX` for
58    /// facts without a price.
59    pub(crate) prices: Vec<u64>,
60}
61
62impl FactPrices<'_> {
63    /// The same facts with every price set to 0: what a root heuristic of
64    /// anytime A* sees, since it estimates only the remaining global cost.
65    pub(crate) fn reached_for_free(mut self) -> Self {
66        for price in &mut self.prices {
67            if *price != u64::MAX {
68                *price = 0;
69            }
70        }
71
72        self
73    }
74}
75
76impl FactPrices<'static> {
77    /// Fact prices for `task` under `factoring`, with `price(fact)` as the
78    /// price of every fact (`None` for facts no member state contains).
79    ///
80    /// Meant for testing heuristics without running a search. The caller
81    /// is responsible for the prices being consistent with some decoupled
82    /// state, in the sense of the bound described on [`FactPrices`].
83    /// `Some(u64::MAX)` counts as no price.
84    ///
85    /// # Errors
86    ///
87    /// [`Error::FactoringMismatch`] if `factoring` does not partition exactly
88    /// the variables of `task`.
89    ///
90    /// # Examples
91    ///
92    /// ```
93    /// use decoupled_search::{DecoupledHeuristic, FactPrices, Factoring, HMax};
94    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
95    ///
96    /// let task = Task {
97    ///     variables: vec![Variable::new("x", 2)],
98    ///     operators: vec![Operator {
99    ///         name: "set".into(),
100    ///         pre: vec![Fact::new(0, 0)],
101    ///         eff: vec![Effect::new(Fact::new(0, 1))],
102    ///         cost: 3,
103    ///     }],
104    ///     initial: State(vec![0]),
105    ///     goal: vec![Fact::new(0, 1)],
106    ///     axioms: vec![],
107    /// };
108    /// let leaf = Factoring::new(&task, vec![vec![0]])?;
109    ///
110    /// // x = 0 costs 2 to reach in some member state, x = 1 is not reached.
111    /// let prices = FactPrices::new(&task, &leaf, |f| (f.value == 0).then_some(2))?;
112    /// assert_eq!(prices.get(Fact::new(0, 0)), Some(2));
113    /// assert_eq!(prices.leaf_of(0), Some(0));
114    /// assert_eq!(HMax::new(&task).estimate(&prices), Some(5));
115    /// # Ok::<(), decoupled_search::Error>(())
116    /// ```
117    pub fn new(
118        task: &Task,
119        factoring: &Factoring,
120        mut price: impl FnMut(Fact) -> Option<u64>,
121    ) -> Result<Self, Error> {
122        let leaves = factoring.leaf_of(task)?;
123        let offsets = fact_offsets(task);
124        let prices = task
125            .variables
126            .iter()
127            .enumerate()
128            .flat_map(|(var, v)| (0..v.domain_size).map(move |value| Fact::new(var, value)))
129            .map(|fact| price(fact).unwrap_or(u64::MAX))
130            .collect();
131
132        Ok(Self {
133            offsets: Cow::Owned(offsets),
134            leaves: Cow::Owned(leaves),
135            prices,
136        })
137    }
138
139    /// The fact prices of a single explicit state: its facts at price 0, all
140    /// variables in the center.
141    ///
142    /// # Panics
143    ///
144    /// Panics if `state` does not have one value per variable of `task`.
145    #[must_use]
146    pub fn from_state(task: &Task, state: &State) -> Self {
147        assert_eq!(
148            state.0.len(),
149            task.num_variables(),
150            "the state must assign every variable of the task"
151        );
152        Self {
153            offsets: Cow::Owned(fact_offsets(task)),
154            leaves: Cow::Owned(vec![None; task.num_variables()]),
155            prices: task
156                .variables
157                .iter()
158                .zip(&state.0)
159                .flat_map(|(v, &value)| {
160                    (0..v.domain_size).map(move |d| if d == value { 0 } else { u64::MAX })
161                })
162                .collect(),
163        }
164    }
165}
166
167impl FactPrices<'_> {
168    /// The cheapest price at which `fact` holds in a member state; `None` if
169    /// none contains it or the fact is out of range.
170    #[must_use]
171    pub fn get(&self, fact: Fact) -> Option<u64> {
172        let value = usize::try_from(fact.value).ok()?;
173        let index = self.offsets.get(fact.var)? + value;
174        let next = self.offsets.get(fact.var + 1)?;
175        (index < *next)
176            .then(|| self.prices[index])
177            .filter(|&p| p != u64::MAX)
178    }
179
180    /// The leaf that variable `var` belongs to, as an index into
181    /// [`Factoring::leaves`]; `None` for center variables and for variables
182    /// out of range.
183    #[must_use]
184    pub fn leaf_of(&self, var: VarId) -> Option<usize> {
185        self.leaves.get(var).copied().flatten()
186    }
187
188    /// The number of variables these prices cover.
189    #[must_use]
190    pub fn num_variables(&self) -> usize {
191        self.leaves.len()
192    }
193}
194
195/// The index of every variable's first value in a vector over all facts of
196/// `task`, plus a final entry with the number of facts.
197pub(crate) fn fact_offsets(task: &Task) -> Vec<usize> {
198    let mut offsets = Vec::with_capacity(task.num_variables() + 1);
199    let mut next = 0;
200    offsets.push(next);
201    for v in &task.variables {
202        next += usize::try_from(v.domain_size).expect("a u32 fits in usize");
203        offsets.push(next);
204    }
205
206    offsets
207}
208
209/// A heuristic on decoupled states.
210pub trait DecoupledHeuristic {
211    /// An estimate of the cost still to pay from a decoupled state beyond
212    /// the cost of its global actions: leaf prices plus all further
213    /// operators. `None` declares that no goal is reachable from it; the
214    /// search then prunes the state.
215    ///
216    /// For [`crate::astar`] to stay optimal, the estimate must not exceed
217    /// the true remaining cost of the cheapest completion through any member
218    /// state, and `None` must only be returned when none exists.
219    fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64>;
220}
221
222impl<H: DecoupledHeuristic + ?Sized> DecoupledHeuristic for &H {
223    fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64> {
224        (**self).estimate(facts)
225    }
226}
227
228/// The max heuristic `h^max` (Bonet and Geffner 2001) seeded with fact
229/// prices: admissible on decoupled states.
230///
231/// A completion through a member state pays the prices of its leaf states,
232/// at least the largest price of any fact it uses, and then at least `h^max`
233/// of that state; seeding every fact with its price can only lower the
234/// estimate. The relaxation runs over all operators of the original task,
235/// leaf actions included.
236///
237/// # Examples
238///
239/// ```
240/// use decoupled_search::{Factoring, HMax, astar};
241/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
242///
243/// let op = |pre: Vec<Fact>, eff: Fact| Operator {
244///     name: "op".into(),
245///     pre,
246///     eff: vec![Effect::new(eff)],
247///     cost: 2,
248/// };
249/// let task = Task {
250///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
251///     operators: vec![
252///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
253///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
254///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
255///     ],
256///     initial: State(vec![0, 0]),
257///     goal: vec![Fact::new(1, 1)],
258///     axioms: vec![],
259/// };
260///
261/// let plan = astar(&task, &Factoring::fork(&task), &HMax::new(&task))?.expect("solvable");
262/// assert_eq!(plan.cost, 6);
263/// # Ok::<(), decoupled_search::Error>(())
264/// ```
265#[derive(Clone, Debug)]
266pub struct HMax(Relaxation);
267
268impl HMax {
269    /// Prepares `h^max` for `task`.
270    ///
271    /// # Panics
272    ///
273    /// Panics if `task` fails [`Task::validate`].
274    #[must_use]
275    pub fn new(task: &Task) -> Self {
276        Self(Relaxation::new(task))
277    }
278}
279
280impl DecoupledHeuristic for HMax {
281    fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64> {
282        self.0.h_max(facts)
283    }
284}
285
286/// The FF heuristic `h^FF` (Hoffmann and Nebel 2001) seeded with fact
287/// prices: the cost of a relaxed plan built from `h^add` best supporters,
288/// plus the largest price of a seed fact it uses. Not admissible; meant for
289/// [`crate::gbfs`].
290///
291/// # Examples
292///
293/// ```
294/// use decoupled_search::{Factoring, HFf, gbfs};
295/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
296///
297/// let op = |pre: Vec<Fact>, eff: Fact| Operator {
298///     name: "op".into(),
299///     pre,
300///     eff: vec![Effect::new(eff)],
301///     cost: 1,
302/// };
303/// let task = Task {
304///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
305///     operators: vec![
306///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
307///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
308///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
309///     ],
310///     initial: State(vec![0, 0]),
311///     goal: vec![Fact::new(1, 1)],
312///     axioms: vec![],
313/// };
314///
315/// let plan = gbfs(&task, &Factoring::fork(&task), &HFf::new(&task))?.expect("solvable");
316/// assert_eq!(task.validate_plan(&plan.ops), Some(plan.cost));
317/// # Ok::<(), decoupled_search::Error>(())
318/// ```
319#[derive(Clone, Debug)]
320pub struct HFf(Relaxation);
321
322impl HFf {
323    /// Prepares `h^FF` for `task`.
324    ///
325    /// # Panics
326    ///
327    /// Panics if `task` fails [`Task::validate`].
328    #[must_use]
329    pub fn new(task: &Task) -> Self {
330        Self(Relaxation::new(task))
331    }
332}
333
334impl DecoupledHeuristic for HFf {
335    fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64> {
336        self.0.h_ff(facts)
337    }
338}
339
340#[cfg(test)]
341mod tests {
342    use alloc::collections::VecDeque;
343    use alloc::vec;
344    use alloc::vec::Vec;
345
346    use sas_plus::random::{RandomTaskParams, random_task};
347
348    use super::*;
349    use crate::decoupled::DecoupledTask;
350
351    /// Checks on up to 40 decoupled states of `task` under `factoring`
352    /// (breadth-first from the initial state) that `heuristic` never
353    /// exceeds the cheapest completion through a member state, and declares
354    /// dead ends only where no member state can reach the goal. Returns the
355    /// number of states with a finite estimate above 0.
356    fn check_admissible(
357        task: &Task,
358        factoring: &Factoring,
359        heuristic: &dyn DecoupledHeuristic,
360    ) -> u64 {
361        let decoupled = DecoupledTask::new(task, factoring).expect("supported");
362        let perfect = task.perfect_heuristic();
363        let mut informative = 0;
364        let mut queue = VecDeque::from([decoupled.initial()]);
365        let mut seen = Vec::new();
366        while let Some(state) = queue.pop_front() {
367            if seen.len() >= 40 || seen.contains(&state) {
368                continue;
369            }
370
371            let truth = decoupled
372                .member_states(task, &state)
373                .iter()
374                .filter_map(|(member, price)| perfect(member).map(|h| h + price))
375                .min();
376            let estimate = heuristic.estimate(&decoupled.fact_prices(&state));
377            match (estimate, truth) {
378                (None, None) => {}
379                (None, Some(t)) => panic!("dead end declared, but {t} is reachable"),
380                (Some(h), None) => assert!(h < u64::MAX),
381                (Some(h), Some(t)) => assert!(h <= t, "{h} > {t} on {state:?}"),
382            }
383
384            informative += u64::from(estimate.is_some_and(|h| h > 0));
385            queue.extend(decoupled.successors(&state).into_iter().map(|(_, s)| s));
386            seen.push(state);
387        }
388
389        informative
390    }
391
392    /// The factorings to check on `task`: fork, single-variable leaves and
393    /// pairs of state variables.
394    fn factorings(task: &Task) -> Vec<Factoring> {
395        let vars: Vec<usize> = (0..task.num_variables())
396            .filter(|&v| !task.variables[v].is_derived())
397            .collect();
398        let singles = vars.iter().map(|&v| vec![v]).collect();
399        let pairs = vars.chunks(2).map(<[usize]>::to_vec).collect();
400        [singles, pairs]
401            .into_iter()
402            .filter_map(|leaves| Factoring::new(task, leaves).ok())
403            .chain([Factoring::fork(task)])
404            .collect()
405    }
406
407    /// Random tasks, with derived variables in half of them.
408    fn tasks() -> impl Iterator<Item = Task> {
409        (0..60).map(|seed| {
410            let params = RandomTaskParams {
411                num_derived: usize::from(seed % 2 == 0),
412                ..RandomTaskParams::default()
413            };
414            random_task(seed, params)
415        })
416    }
417
418    /// `h^max` on fact prices is admissible on decoupled states.
419    #[test]
420    fn h_max_is_admissible_on_member_states() {
421        let mut informative = 0;
422        for task in tasks() {
423            let h = HMax::new(&task);
424            for factoring in factorings(&task) {
425                if DecoupledTask::new(&task, &factoring).is_ok() {
426                    informative += check_admissible(&task, &factoring, &h);
427                }
428            }
429        }
430
431        assert!(
432            informative > 100,
433            "only {informative} informative estimates"
434        );
435    }
436
437    /// The merge-and-shrink adapter is admissible on decoupled states, with
438    /// exact bisimulation, a lossy size limit, and no shrinking at all.
439    #[cfg(feature = "merge-and-shrink")]
440    #[test]
441    fn merge_and_shrink_is_admissible_on_member_states() {
442        use merge_and_shrink::{Bisimulation, LinearMerge, MergeAndShrink, NoShrink};
443
444        let mut informative = 0;
445        for task in tasks() {
446            let linear = || LinearMerge::in_variable_order(task.num_variables());
447            let heuristics = [
448                MasHeuristic::build(&task, MergeAndShrink::new(linear(), Bisimulation)),
449                MasHeuristic::build(
450                    &task,
451                    MergeAndShrink {
452                        max_states: 4,
453                        ..MergeAndShrink::new(linear(), Bisimulation)
454                    },
455                ),
456                MasHeuristic::build(
457                    &task,
458                    MergeAndShrink {
459                        prune: false,
460                        ..MergeAndShrink::new(linear(), NoShrink)
461                    },
462                ),
463            ];
464            for factoring in factorings(&task) {
465                if DecoupledTask::new(&task, &factoring).is_err() {
466                    continue;
467                }
468
469                for h in &heuristics {
470                    informative += check_admissible(&task, &factoring, h);
471                }
472            }
473        }
474
475        assert!(
476            informative > 100,
477            "only {informative} informative estimates"
478        );
479    }
480
481    /// Both LM-cut evaluations are admissible on decoupled states (with
482    /// derived variables in half of the tasks), never below `h^max`, and
483    /// above it at least once.
484    #[cfg(feature = "lm-cut")]
485    #[test]
486    fn lm_cut_is_admissible_on_member_states() {
487        let (mut informative, mut stronger) = (0, [0; 2]);
488        for task in tasks() {
489            let h_max = HMax::new(&task);
490            let heuristics = [
491                LmCutHeuristic::new(&task),
492                LmCutHeuristic::with_price_levels(&task),
493            ];
494            for factoring in factorings(&task) {
495                let Ok(decoupled) = DecoupledTask::new(&task, &factoring) else {
496                    continue;
497                };
498
499                for (index, lm_cut) in heuristics.iter().enumerate() {
500                    informative += check_admissible(&task, &factoring, lm_cut);
501                    let mut state = decoupled.initial();
502                    for _ in 0..3 {
503                        let facts = decoupled.fact_prices(&state);
504                        let (lm, max) = (lm_cut.estimate(&facts), h_max.estimate(&facts));
505                        assert_eq!(lm.is_none(), max.is_none(), "dead ends agree");
506                        assert!(lm >= max, "{lm:?} < {max:?}");
507                        stronger[index] += u64::from(lm > max);
508                        let Some((_, next)) = decoupled.successors(&state).pop() else {
509                            break;
510                        };
511                        state = next;
512                    }
513                }
514            }
515        }
516
517        assert!(
518            informative > 100,
519            "only {informative} informative estimates"
520        );
521        assert!(
522            stronger.iter().all(|&s| s > 0),
523            "LM-cut never beat h^max: {stronger:?}"
524        );
525    }
526}