Skip to main content

merge_and_shrink/
lib.rs

1//! Merge-and-shrink abstractions (Helmert, Haslum, Hoffmann & Nissim 2014;
2//! Sievers & Helmert 2021).
3//!
4//! Start from one atomic transition system per variable, then repeatedly
5//! *shrink* two factors by a state equivalence and *merge* them into their
6//! synchronized product. Goal distances in the final factor are an admissible
7//! heuristic. With exact bisimulation and no size limit it is perfect, except
8//! on tasks with conditional effects or derived variables, which atomic
9//! factors over-approximate.
10//!
11//! Each step lets the [`MergeStrategy`] pick two factors ([`LinearMerge`],
12//! [`Dfp`], [`SccDfp`]), optionally reduces labels, shrinks both with the
13//! [`ShrinkStrategy`] so that their product fits [`MergeAndShrink::max_states`]
14//! ([`Bisimulation`], [`GreedyBisimulation`], [`NoShrink`]), builds the
15//! product and prunes it.
16
17#![no_std]
18
19extern crate alloc;
20
21mod factor;
22mod labels;
23mod merge;
24mod shrink;
25
26pub use factor::{Factor, MergeTree};
27pub use merge::{Dfp, LinearMerge, MergeStrategy, SccDfp};
28pub use shrink::{Bisimulation, GreedyBisimulation, NoShrink, ShrinkStrategy};
29
30use alloc::vec::Vec;
31
32use labels::Labels;
33use sas_plus::{Abstraction, LabeledTransitionSystem, State, Task};
34
35/// Builder for a merge-and-shrink heuristic: a merge strategy, a shrink
36/// strategy, a size limit and whether to prune.
37pub struct MergeAndShrink<M, S> {
38    /// Picks the next two factors to merge.
39    pub merge: M,
40    /// Shrinks the two factors of each merge right before the product is built.
41    pub shrink: S,
42    /// Remove unreachable and dead-end abstract states from each atomic factor
43    /// and each product.
44    pub prune: bool,
45    /// Largest number of states a product may have; at least 1. Before each
46    /// merge, the two factors are shrunk to sizes whose product stays within
47    /// it. `usize::MAX` means no limit.
48    pub max_states: usize,
49    /// Before shrinking, combine labels (operators) of equal cost that only
50    /// one factor can tell apart. This is exact and lets bisimulation shrink
51    /// more; the final abstraction is labeled with operator ids again.
52    pub label_reduction: bool,
53}
54
55impl<M: MergeStrategy, S: ShrinkStrategy> MergeAndShrink<M, S> {
56    /// A builder with pruning and label reduction enabled, and no size limit.
57    #[must_use]
58    pub fn new(merge: M, shrink: S) -> Self {
59        Self {
60            merge,
61            shrink,
62            prune: true,
63            max_states: usize::MAX,
64            label_reduction: true,
65        }
66    }
67
68    /// Merges the atomic factors of `task` into one and computes its goal distances.
69    ///
70    /// # Panics
71    ///
72    /// Panics if `task` has no variables, if `max_states` is 0, or if the merge
73    /// strategy picks the same factor twice or a factor that was already merged.
74    #[must_use]
75    pub fn build(mut self, task: &Task) -> MergeAndShrinkHeuristic {
76        assert!(self.max_states > 0, "max_states must be at least 1");
77        let costs = task.costs();
78        let mut factors = self.atomic_factors(task, &costs);
79        let mut labels = Labels::new(costs.len());
80
81        for _ in 1..factors.len() {
82            let product = self.merge_next(&mut factors, &mut labels, &costs);
83            factors.push(Some(product));
84        }
85
86        let mut factor = factors
87            .into_iter()
88            .flatten()
89            .next()
90            .expect("task has at least one variable");
91        labels.expand(&mut factor.lts);
92        let distances = factor.lts.goal_distances(&costs);
93
94        MergeAndShrinkHeuristic { factor, distances }
95    }
96
97    /// One atomic factor per variable of `task`, pruned if enabled.
98    fn atomic_factors(&self, task: &Task, costs: &[u64]) -> Vec<Option<Factor>> {
99        (0..task.num_variables())
100            .map(|v| {
101                let mut f = Factor::atomic(task, v);
102                if self.prune {
103                    f.prune(costs);
104                }
105
106                Some(f)
107            })
108            .collect()
109    }
110
111    /// Takes the two factors the merge strategy picks, reduces labels if
112    /// enabled, shrinks the factors to fit the size limit, and returns their
113    /// product, pruned.
114    fn merge_next(
115        &mut self,
116        factors: &mut [Option<Factor>],
117        labels: &mut Labels,
118        costs: &[u64],
119    ) -> Factor {
120        let (i, j) = self.merge.next_pair(factors, costs);
121        assert_ne!(i, j, "merge strategy returned the same factor twice");
122        assert!(
123            factors[i].is_some() && factors[j].is_some(),
124            "merge strategy chose an inactive factor"
125        );
126        if self.label_reduction {
127            labels.reduce(factors, i, costs);
128            labels.reduce(factors, j, costs);
129        }
130        let mut a = factors[i]
131            .take()
132            .expect("merge strategy chose an inactive factor");
133        let mut b = factors[j]
134            .take()
135            .expect("merge strategy chose an inactive factor");
136
137        // Factors are pruned when built, so they hold only live states, and a
138        // quotient of live states is live (see ShrinkStrategy::compute).
139        let (max_a, max_b) = shrink_sizes(a.lts.num_states, b.lts.num_states, self.max_states);
140        self.shrink_to(&mut a, costs, max_a);
141        self.shrink_to(&mut b, costs, max_b);
142
143        let mut product = Factor::product(a, b);
144        if self.prune {
145            product.prune(costs);
146        }
147
148        product
149    }
150
151    /// Shrinks `factor` with the shrink strategy, to at most `max_states` states.
152    fn shrink_to(&self, factor: &mut Factor, costs: &[u64], max_states: usize) {
153        if let Some((map, n)) = self.shrink.compute(factor, costs, max_states) {
154            factor.apply_abstraction(&map, n);
155        }
156    }
157}
158
159/// Size limits for two factors of sizes `a` and `b` so that their product has
160/// at most `max_states` states. Each keeps its size if the product fits;
161/// otherwise the smaller one keeps as much as it can and the larger one gets
162/// the rest, and if neither fits within `isqrt(max_states)`, both get about that.
163fn shrink_sizes(a: usize, b: usize, max_states: usize) -> (usize, usize) {
164    let (a, b) = (a.min(max_states), b.min(max_states));
165    if a.saturating_mul(b) <= max_states {
166        return (a, b);
167    }
168
169    let balanced = max_states.isqrt();
170    if a <= balanced {
171        (a, max_states / a)
172    } else if b <= balanced {
173        (max_states / b, b)
174    } else {
175        (balanced, max_states / balanced)
176    }
177}
178
179/// The heuristic: goal distances in the final factor, looked up through its merge tree.
180pub struct MergeAndShrinkHeuristic {
181    /// The single factor left after merging every atomic factor.
182    factor: Factor,
183    /// Goal distance per abstract state of `factor`; `None` for dead ends.
184    distances: Vec<Option<u64>>,
185}
186
187impl MergeAndShrinkHeuristic {
188    /// Admissible estimate of the cost to the goal.
189    ///
190    /// `None` means `state` is a dead end, or, with pruning, a state that is
191    /// unreachable from the task's initial state (even a goal state).
192    #[must_use]
193    pub fn value(&self, state: &State) -> Option<u64> {
194        self.factor
195            .tree
196            .lookup(state)
197            .and_then(|s| self.distances[s])
198    }
199
200    /// Number of states of the final factor: the size of the abstraction.
201    #[must_use]
202    pub fn num_abstract_states(&self) -> usize {
203        self.factor.lts.num_states
204    }
205}
206
207impl Abstraction for MergeAndShrinkHeuristic {
208    fn lts(&self) -> &LabeledTransitionSystem {
209        &self.factor.lts
210    }
211
212    fn abstract_state(&self, state: &State) -> Option<usize> {
213        self.factor.tree.lookup(state)
214    }
215}
216
217/// Doctests for the code examples in README.md (not part of the API).
218#[cfg(doctest)]
219#[doc = include_str!("../README.md")]
220mod readme_doctests {}