Skip to main content

decoupled_search/heuristic/
mas.rs

1//! A merge-and-shrink heuristic on decoupled states, from the
2//! [`merge_and_shrink`] crate (feature `merge-and-shrink`). See
3//! [`MasHeuristic`] for the evaluation and its admissibility proof.
4
5use alloc::vec;
6use alloc::vec::Vec;
7
8use merge_and_shrink::{Factor, MergeAndShrink, MergeStrategy, MergeTree, ShrinkStrategy};
9use sas_plus::{Fact, Task, VarId};
10
11use super::{DecoupledHeuristic, FactPrices};
12
13/// A price bound that no member state attains.
14const INFINITE: u64 = u64::MAX;
15
16/// A node of the merge tree, flattened in post-order.
17#[derive(Clone, Debug)]
18enum Node {
19    /// An atomic factor over one task variable.
20    Var {
21        /// The task variable.
22        var: VarId,
23        /// Abstract state per value of `var`; `None` if pruned.
24        table: Vec<Option<usize>>,
25    },
26    /// The product of two earlier nodes.
27    Product {
28        /// Index of the left child, whose state is the major index.
29        left: usize,
30        /// Index of the right child.
31        right: usize,
32        /// Number of abstract states of the right child.
33        right_size: usize,
34        /// Abstract state per `left * right_size + right`; `None` if pruned.
35        table: Vec<Option<usize>>,
36    },
37}
38
39/// A node's bounds during one evaluation.
40struct Evaluated {
41    /// The cheapest price bound per abstract state of the node.
42    cost: Vec<u64>,
43    /// The factors the node's variables touch, sorted: leaf indices, and
44    /// `usize::MAX` for the center.
45    factors: Vec<usize>,
46}
47
48/// A merge-and-shrink heuristic adapted to decoupled states; admissible, so
49/// it can drive [`crate::astar`].
50///
51/// A merge-and-shrink abstraction maps each explicit state through a merge
52/// tree of lookup tables to an abstract state with an admissible goal
53/// distance. A decoupled state stands for many explicit states at once, so
54/// the adapter evaluates the tree on [`FactPrices`] instead of on one state:
55/// bottom-up, every tree node gets the cheapest *price bound* of each of its
56/// abstract states, and the estimate is the cheapest `bound + distance` at
57/// the root.
58///
59/// # Admissibility
60///
61/// For a tree node `n`, let `F(n)` be the factors (the leaves, and the
62/// center as one more) that its variables touch, and for a member state
63/// `s` let `P_n(s)` be the sum of the prices `s` pays in the factors of
64/// `F(n)`. By induction, `cost_n(a) <= P_n(s)` for every member state `s`
65/// that `n` maps to `a`:
66///
67/// - at a variable `v`, `cost(a)` is the cheapest price of a fact `v = x`
68///   with `x` mapped to `a`, and the price of `v = s[v]` is at most what `s`
69///   pays in `v`'s factor, by the contract of [`FactPrices`];
70/// - at a product of children `l` and `r` that touch disjoint sets of
71///   factors, `P_n = P_l + P_r`, so the sum of the children's bounds is a
72///   bound;
73/// - if they share a factor, its price must not be counted twice (two
74///   variables of one leaf are bought with one leaf state), and
75///   `P_n >= max(P_l, P_r)` makes the larger bound a bound.
76///
77/// At the root `F` contains every factor, so a member state `s` mapped to
78/// `a` costs at least `cost(a)` to reach and at least `dist(a)` (the
79/// abstraction is admissible) to complete; the minimum over all abstract
80/// states is a lower bound on the cheapest completion through any member
81/// state. Pruned abstract states (`None` in a table) are dead ends or
82/// unreachable from the initial state; every member state of a decoupled
83/// state is reachable, so skipping them is safe.
84///
85/// # Construction
86///
87/// [`merge_and_shrink::MergeAndShrinkHeuristic`] keeps its merge tree
88/// private, so [`MasHeuristic::build`] re-runs the merge loop from the
89/// public parts of [`merge_and_shrink`]. Label reduction is not public
90/// either, so [`MergeAndShrink::label_reduction`] is ignored; that only
91/// weakens shrinking, never admissibility.
92///
93/// # Examples
94///
95/// ```
96/// use decoupled_search::{Factoring, MasHeuristic, astar};
97/// use merge_and_shrink::{Bisimulation, LinearMerge, MergeAndShrink};
98/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
99///
100/// let op = |pre: Vec<Fact>, eff: Fact| Operator {
101///     name: "op".into(),
102///     pre,
103///     eff: vec![Effect::new(eff)],
104///     cost: 2,
105/// };
106/// let task = Task {
107///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 3)],
108///     operators: vec![
109///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
110///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
111///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
112///     ],
113///     initial: State(vec![0, 0]),
114///     goal: vec![Fact::new(1, 1)],
115///     axioms: vec![],
116/// };
117///
118/// let merge = LinearMerge::in_variable_order(task.num_variables());
119/// let h = MasHeuristic::build(&task, MergeAndShrink::new(merge, Bisimulation));
120/// let plan = astar(&task, &Factoring::fork(&task), &h)?.expect("solvable");
121/// assert_eq!(plan.cost, 6);
122/// # Ok::<(), decoupled_search::Error>(())
123/// ```
124#[derive(Clone, Debug)]
125pub struct MasHeuristic {
126    /// The merge tree, children before parents; the last node is the root.
127    nodes: Vec<Node>,
128    /// The goal distance per abstract state of the root; `None` for dead
129    /// ends.
130    distances: Vec<Option<u64>>,
131}
132
133impl MasHeuristic {
134    /// Builds the merge-and-shrink abstraction of `task` with the merge
135    /// strategy, shrink strategy, size limit and pruning of `config`, as
136    /// [`MergeAndShrink::build`] would, except that label reduction is not
137    /// applied (see the module documentation).
138    ///
139    /// # Panics
140    ///
141    /// Panics if `task` has no variables, if `config.max_states` is 0, or if
142    /// the merge strategy picks the same factor twice or one already merged.
143    #[must_use]
144    pub fn build<M: MergeStrategy, S: ShrinkStrategy>(
145        task: &Task,
146        mut config: MergeAndShrink<M, S>,
147    ) -> Self {
148        assert!(config.max_states > 0, "max_states must be at least 1");
149        let costs = task.costs();
150        let mut factors: Vec<Option<Factor>> = (0..task.num_variables())
151            .map(|var| {
152                let mut factor = Factor::atomic(task, var);
153                if config.prune {
154                    factor.prune(&costs);
155                }
156
157                Some(factor)
158            })
159            .collect();
160
161        for _ in 1..factors.len() {
162            let product = merge_next(&mut config, &mut factors, &costs);
163            factors.push(Some(product));
164        }
165
166        let factor = factors
167            .into_iter()
168            .flatten()
169            .next()
170            .expect("the task has at least one variable");
171        Self::from_factor(task, &factor)
172    }
173
174    /// The heuristic of a finished merge-and-shrink factor over all
175    /// variables of `task`, whose labels are `task`'s operator ids.
176    #[must_use]
177    pub fn from_factor(task: &Task, factor: &Factor) -> Self {
178        let mut nodes = Vec::new();
179        flatten(&factor.tree, &mut nodes);
180
181        Self {
182            nodes,
183            distances: factor.lts.goal_distances(&task.costs()),
184        }
185    }
186
187    /// The number of abstract states of the root factor.
188    #[must_use]
189    pub fn num_abstract_states(&self) -> usize {
190        self.distances.len()
191    }
192
193    /// Evaluates node `index` from its children in `done`.
194    fn evaluate(&self, index: usize, done: &[Evaluated], facts: &FactPrices<'_>) -> Evaluated {
195        match &self.nodes[index] {
196            Node::Var { var, table } => {
197                let mut cost = vec![INFINITE; size_of(table)];
198                for (value, state) in table.iter().enumerate() {
199                    let fact = Fact::new(*var, u32::try_from(value).expect("values fit u32"));
200                    if let (Some(state), Some(price)) = (state, facts.get(fact)) {
201                        cost[*state] = cost[*state].min(price);
202                    }
203                }
204
205                Evaluated {
206                    cost,
207                    factors: vec![facts.leaf_of(*var).unwrap_or(usize::MAX)],
208                }
209            }
210            Node::Product {
211                left,
212                right,
213                right_size,
214                table,
215            } => product(&done[*left], &done[*right], *right_size, table),
216        }
217    }
218}
219
220impl DecoupledHeuristic for MasHeuristic {
221    fn estimate(&self, facts: &FactPrices<'_>) -> Option<u64> {
222        let mut done: Vec<Evaluated> = Vec::with_capacity(self.nodes.len());
223        for index in 0..self.nodes.len() {
224            let evaluated = self.evaluate(index, &done, facts);
225            done.push(evaluated);
226        }
227
228        let root = done.last().expect("the tree has a node");
229        root.cost
230            .iter()
231            .zip(&self.distances)
232            .filter(|&(&cost, _)| cost != INFINITE)
233            .filter_map(|(&cost, &distance)| distance.map(|d| cost.saturating_add(d)))
234            .min()
235    }
236}
237
238/// The bounds of a product node with children `l` and `r`: sums of the
239/// children's bounds if they touch disjoint factors, maxima otherwise.
240fn product(l: &Evaluated, r: &Evaluated, right_size: usize, table: &[Option<usize>]) -> Evaluated {
241    let disjoint = !l.factors.iter().any(|f| r.factors.binary_search(f).is_ok());
242    let mut cost = vec![INFINITE; size_of(table)];
243    for (index, state) in table.iter().enumerate() {
244        let Some(state) = *state else {
245            continue;
246        };
247
248        let (a, b) = (l.cost[index / right_size], r.cost[index % right_size]);
249        if a == INFINITE || b == INFINITE {
250            continue;
251        }
252
253        let combined = if disjoint {
254            a.saturating_add(b)
255        } else {
256            a.max(b)
257        };
258        cost[state] = cost[state].min(combined);
259    }
260
261    let mut factors = [l.factors.as_slice(), r.factors.as_slice()].concat();
262    factors.sort_unstable();
263    factors.dedup();
264
265    Evaluated { cost, factors }
266}
267
268/// The number of abstract states a table maps into.
269fn size_of(table: &[Option<usize>]) -> usize {
270    table.iter().flatten().max().map_or(0, |&s| s + 1)
271}
272
273/// Appends `tree` to `nodes` in post-order and returns the index of its root.
274fn flatten(tree: &MergeTree, nodes: &mut Vec<Node>) -> usize {
275    let node = match tree {
276        MergeTree::Leaf { var, table } => Node::Var {
277            var: *var,
278            table: table.clone(),
279        },
280        MergeTree::Node {
281            left,
282            right,
283            right_size,
284            table,
285        } => Node::Product {
286            left: flatten(left, nodes),
287            right: flatten(right, nodes),
288            right_size: *right_size,
289            table: table.clone(),
290        },
291    };
292    nodes.push(node);
293    nodes.len() - 1
294}
295
296/// Takes the two factors the merge strategy picks, shrinks both so that
297/// their product fits the size limit, and returns their product, pruned if
298/// enabled.
299///
300/// # Panics
301///
302/// Panics if the merge strategy picks the same factor twice or an inactive
303/// one.
304fn merge_next<M: MergeStrategy, S: ShrinkStrategy>(
305    config: &mut MergeAndShrink<M, S>,
306    factors: &mut [Option<Factor>],
307    costs: &[u64],
308) -> Factor {
309    let (i, j) = config.merge.next_pair(factors, costs);
310    assert_ne!(i, j, "merge strategy returned the same factor twice");
311    let mut a = factors[i]
312        .take()
313        .expect("merge strategy chose an inactive factor");
314    let mut b = factors[j]
315        .take()
316        .expect("merge strategy chose an inactive factor");
317
318    let (max_a, max_b) = shrink_sizes(a.lts.num_states, b.lts.num_states, config.max_states);
319    for (factor, max) in [(&mut a, max_a), (&mut b, max_b)] {
320        if let Some((map, n)) = config.shrink.compute(factor, costs, max) {
321            factor.apply_abstraction(&map, n);
322        }
323    }
324
325    let mut product = Factor::product(a, b);
326    if config.prune {
327        product.prune(costs);
328    }
329
330    product
331}
332
333/// Size limits for two factors of sizes `a` and `b` so that their product
334/// has at most `max_states` states, as in [`merge_and_shrink`]: each keeps
335/// its size if the product fits; otherwise the smaller one keeps as much as
336/// it can and the larger one gets the rest, and if neither fits within
337/// `isqrt(max_states)`, both get about that.
338fn shrink_sizes(a: usize, b: usize, max_states: usize) -> (usize, usize) {
339    let (a, b) = (a.min(max_states), b.min(max_states));
340    if a.saturating_mul(b) <= max_states {
341        return (a, b);
342    }
343
344    let balanced = max_states.isqrt();
345    if a <= balanced {
346        (a, max_states / a)
347    } else if b <= balanced {
348        (max_states / b, b)
349    } else {
350        (balanced, max_states / balanced)
351    }
352}