Skip to main content

decoupled_search/factoring/
generalized.rs

1//! Generalized factorings (Gnad, Torralba and Fišer, ICAPS 2022): leaves
2//! that may interact directly and a center that may be empty. Operators that
3//! are not leaf-only actions are global actions, so the strategy only has to
4//! choose leaves that are mobile under the search's own classification
5//! (derived variables attached to the leaf they depend on).
6
7use alloc::vec::Vec;
8
9use sas_plus::{Task, VarId};
10
11use super::star::mobility;
12use super::{Factoring, leaf_states};
13
14impl Factoring {
15    /// A generalized factoring: leaves chosen among the effect variable sets
16    /// of the operators (the paper's potential leaves), as many mutually
17    /// disjoint mobile ones as a greedy pass finds; every other variable is
18    /// the center, which may end up empty.
19    ///
20    /// Gnad, Torralba and Fišer (ICAPS 2022) select the leaves with an
21    /// integer program maximizing the number of mobile leaves; this is a
22    /// greedy approximation of that objective. Candidates go smallest first,
23    /// then by how few other candidates they overlap, then by how many
24    /// operators set exactly that variable set. A leaf is
25    /// *mobile* if the search would compile some operator as its leaf
26    /// action: the operator sets only the leaf's variables and reads only
27    /// the leaf and the center, with each derived variable counted in the
28    /// leaf it depends on. A candidate is kept if it is disjoint from the
29    /// leaves so far, the search accepts the leaves (no derived variable
30    /// depends on two of them), and it and every earlier leaf stay mobile (a
31    /// new leaf takes its variables out of the center, which can strand
32    /// another leaf), so every leaf of the result is mobile. Candidates with
33    /// a derived variable or more than [`crate::MAX_LEAF_STATES`] states are
34    /// skipped.
35    ///
36    /// Leaves may read and write each other: those operators become global
37    /// actions, which the search branches over (their Theorem 1 shows that
38    /// this is decoupled search on a star factoring of a slightly extended
39    /// task, so it stays sound, complete and optimal).
40    ///
41    /// # Examples
42    ///
43    /// ```
44    /// use decoupled_search::{Factoring, search};
45    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
46    ///
47    /// // Two counters that each step on their own, and a swap that touches
48    /// // both: no star factoring has two leaves, a generalized one has.
49    /// let op = |name: &str, pre: Vec<Fact>, eff: Vec<Fact>| Operator {
50    ///     name: name.into(),
51    ///     pre,
52    ///     eff: eff.into_iter().map(Effect::new).collect(),
53    ///     cost: 1,
54    /// };
55    /// let task = Task {
56    ///     variables: vec![Variable::new("a", 2), Variable::new("b", 2)],
57    ///     operators: vec![
58    ///         op("a", vec![Fact::new(0, 0)], vec![Fact::new(0, 1)]),
59    ///         op("b", vec![Fact::new(1, 0)], vec![Fact::new(1, 1)]),
60    ///         op("swap", vec![Fact::new(0, 1)], vec![Fact::new(0, 0), Fact::new(1, 0)]),
61    ///     ],
62    ///     initial: State(vec![0, 0]),
63    ///     goal: vec![Fact::new(0, 1), Fact::new(1, 1)],
64    ///     axioms: vec![],
65    /// };
66    ///
67    /// let factoring = Factoring::generalized(&task);
68    /// assert!(factoring.center().is_empty());
69    /// assert_eq!(factoring.leaves(), &[vec![0], vec![1]]);
70    /// assert_eq!(search(&task, &factoring)?.map(|p| p.cost), Some(2));
71    /// # Ok::<(), decoupled_search::Error>(())
72    /// ```
73    #[must_use]
74    pub fn generalized(task: &Task) -> Self {
75        let mut leaves: Vec<Vec<VarId>> = Vec::new();
76        for candidate in candidates(task) {
77            let free = candidate
78                .iter()
79                .all(|v| leaves.iter().all(|leaf| !leaf.contains(v)));
80            if !free {
81                continue;
82            }
83
84            leaves.push(candidate);
85            if !mobility(task, &leaves).iter().all(|&m| m) {
86                leaves.pop();
87            }
88        }
89
90        leaves.sort_unstable();
91        Self::from_leaves(task, leaves)
92    }
93}
94
95/// The potential leaves: every operator's effect variables, without
96/// derived variables and leaves above `MAX_LEAF_STATES`. Ordered smallest
97/// first, then by how few other candidates they overlap (the usual greedy
98/// rule for packing many disjoint sets), then by how many operators have
99/// exactly that effect set.
100fn candidates(task: &Task) -> Vec<Vec<VarId>> {
101    let mut counted: Vec<(Vec<VarId>, usize)> = Vec::new();
102    for op in &task.operators {
103        let mut vars: Vec<VarId> = op.eff.iter().map(|e| e.fact.var).collect();
104        vars.sort_unstable();
105        vars.dedup();
106        if vars.is_empty()
107            || vars.iter().any(|&v| task.variables[v].is_derived())
108            || leaf_states(task, &vars).is_none()
109        {
110            continue;
111        }
112
113        match counted.iter_mut().find(|(c, _)| *c == vars) {
114            Some((_, n)) => *n += 1,
115            None => counted.push((vars, 1)),
116        }
117    }
118
119    let overlaps = |a: &[VarId]| {
120        counted
121            .iter()
122            .filter(|(b, _)| b.as_slice() != a && b.iter().any(|v| a.contains(v)))
123            .count()
124    };
125    let mut keyed: Vec<_> = counted
126        .iter()
127        .map(|(vars, n)| {
128            (
129                vars.len(),
130                overlaps(vars),
131                core::cmp::Reverse(*n),
132                vars.clone(),
133            )
134        })
135        .collect();
136    keyed.sort_unstable();
137    keyed.into_iter().map(|(.., vars)| vars).collect()
138}