decoupled_search/factoring/star.rs
1//! Strict-star factorings of Gnad, Poser and Hoffmann (IJCAI 2017,
2//! Section 4): the incident-arcs strategy (their Figure 2) and the
3//! independent-set strategy that maximises the number of leaves (their
4//! Figure 1, in [`independent_set`]).
5//!
6//! Both build leaves that no causal-graph arc connects, so every result
7//! passes [`Factoring::check_star`]. Beyond the paper, which has no axioms,
8//! both also treat the inputs of a derived variable as adjacent, so that
9//! no derived variable depends on two leaves. Both rank their candidates by the
10//! number of *mobile* leaves, leaves with at least one leaf action (the
11//! paper's flexibility `|A^L[F^L] \ A^C| / |A^L[F^L]|` above 0). The paper
12//! abstains below two mobile leaves; these functions return their best
13//! candidate anyway, and [`Factoring::auto`] abstains.
14//!
15//! ```mermaid
16//! graph LR
17//! order[variables by incident arcs] --> grow[move the next one to the center]
18//! grow --> comps[small weakly connected components are the leaves]
19//! comps --> count[count mobile leaves]
20//! count --> grow
21//! count --> best[keep the first candidate with the most]
22//! ```
23
24mod independent_set;
25
26use alloc::vec;
27use alloc::vec::Vec;
28
29use core::cmp::Reverse;
30
31use sas_plus::{Task, VarId};
32
33use super::graph::FactorGraph;
34use super::{Factoring, leaf_states};
35use crate::decoupled::mobile_leaves;
36
37impl Factoring {
38 /// The incident-arcs star factoring (Gnad, Poser and Hoffmann 2017,
39 /// Figure 2): orders the variables by decreasing number of incident
40 /// causal-graph arcs, moves them into the center one at a time, and
41 /// keeps the candidate with the most mobile leaves.
42 ///
43 /// A candidate's leaves are the weakly connected components of the
44 /// causal graph without the center that have at most
45 /// [`crate::MAX_LEAF_STATES`] states; the other variables form the
46 /// center. No arc connects two leaves, so the result always passes
47 /// [`Factoring::check_star`]. A variable's incident arcs are its
48 /// incoming plus its outgoing arcs, counted once on the full causal
49 /// graph. Ties are ours, the paper leaves them open: in the order, the
50 /// smaller variable first; between candidates, the smaller center. As
51 /// in the paper, the center has at least one variable. The paper
52 /// abstains below two mobile leaves; this returns the best
53 /// candidate anyway, possibly without leaves.
54 ///
55 /// # Examples
56 ///
57 /// ```
58 /// use decoupled_search::Factoring;
59 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
60 ///
61 /// // A hub (variable 0) that both spokes read and that reads both spokes.
62 /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
63 /// name: "op".into(),
64 /// pre,
65 /// eff: vec![Effect::new(eff)],
66 /// cost: 1,
67 /// };
68 /// let task = Task {
69 /// variables: vec![Variable::new("hub", 2), Variable::new("a", 2), Variable::new("b", 2)],
70 /// operators: vec![
71 /// op(vec![Fact::new(1, 1), Fact::new(2, 1)], Fact::new(0, 1)),
72 /// op(vec![Fact::new(0, 0)], Fact::new(1, 1)),
73 /// op(vec![Fact::new(0, 0)], Fact::new(2, 1)),
74 /// ],
75 /// initial: State(vec![0, 0, 0]),
76 /// goal: vec![Fact::new(0, 1)],
77 /// axioms: vec![],
78 /// };
79 ///
80 /// let factoring = Factoring::incident_arcs(&task);
81 /// assert_eq!(factoring.center(), &[0]);
82 /// assert_eq!(factoring.leaves(), &[vec![1], vec![2]]);
83 /// assert_eq!(factoring.check_star(&task), Ok(()));
84 /// ```
85 #[must_use]
86 pub fn incident_arcs(task: &Task) -> Self {
87 let graph = FactorGraph::new(task);
88 let neighbours = neighbours(&graph, task.num_variables());
89 // Derived variables have no arcs and stay in the center.
90 let mut in_center: Vec<bool> = task
91 .variables
92 .iter()
93 .map(sas_plus::Variable::is_derived)
94 .collect();
95 let mut best: Option<Candidate> = None;
96 for v in incident_arc_order(&graph, task.num_variables()) {
97 in_center[v] = true;
98 let candidate = Candidate::new(task, small_components(task, &neighbours, &in_center));
99 if best.as_ref().is_none_or(|b| candidate.mobile > b.mobile) {
100 best = Some(candidate);
101 }
102 }
103
104 Self::from_leaves(task, best.map(|b| b.leaves).unwrap_or_default())
105 }
106
107 /// The independent-set star factoring, which maximises the number of
108 /// leaves (Gnad, Poser and Hoffmann 2017, Figure 1): every maximum
109 /// independent set of the causal graph seeds one leaf per variable;
110 /// then variables adjacent to exactly one leaf join it while that gains
111 /// mobile leaves, frozen (immobile) leaves go back to the center, and
112 /// leaves grow once more. The result is the candidate with the most
113 /// mobile leaves.
114 ///
115 /// Variables that cannot be leaves (derived, or with more than
116 /// [`crate::MAX_LEAF_STATES`] values) are left out of the independent
117 /// sets. The paper enumerates maximum independent sets for up to ten
118 /// seconds; this enumerates at most 16 of them with a
119 /// deterministic search budget, after which the best set found so far
120 /// is used. Always passes
121 /// [`Factoring::check_star`]. The paper abstains below two mobile
122 /// leaves; this returns the best candidate anyway.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use decoupled_search::Factoring;
128 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
129 ///
130 /// // A chain a - b - c: putting b into the center leaves a and c apart.
131 /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
132 /// name: "op".into(),
133 /// pre,
134 /// eff: vec![Effect::new(eff)],
135 /// cost: 1,
136 /// };
137 /// let var = |name: &str| Variable::new(name, 2);
138 /// let task = Task {
139 /// variables: vec![var("a"), var("b"), var("c")],
140 /// operators: vec![
141 /// op(vec![Fact::new(0, 1)], Fact::new(1, 1)),
142 /// op(vec![Fact::new(1, 1)], Fact::new(2, 1)),
143 /// op(vec![], Fact::new(0, 1)),
144 /// ],
145 /// initial: State(vec![0, 0, 0]),
146 /// goal: vec![Fact::new(2, 1)],
147 /// axioms: vec![],
148 /// };
149 ///
150 /// let factoring = Factoring::max_leaves(&task);
151 /// assert_eq!(factoring.center(), &[1]);
152 /// assert_eq!(factoring.leaves(), &[vec![0], vec![2]]);
153 /// ```
154 #[must_use]
155 pub fn max_leaves(task: &Task) -> Self {
156 Self::from_leaves(task, independent_set::factoring(task).leaves)
157 }
158}
159
160/// A candidate factoring's leaves and how many of them are mobile.
161struct Candidate {
162 /// The number of mobile leaves.
163 mobile: usize,
164 /// The leaves, each sorted.
165 leaves: Vec<Vec<VarId>>,
166}
167
168impl Candidate {
169 /// Scores `leaves`; a factoring the search would reject (an axiom across
170 /// two leaves) has no mobile leaves.
171 fn new(task: &Task, leaves: Vec<Vec<VarId>>) -> Self {
172 let mobile = mobility(task, &leaves).iter().filter(|&&m| m).count();
173 Self { mobile, leaves }
174 }
175}
176
177/// Per leaf, whether it has a leaf action; all `false` if the factoring
178/// would be rejected. `leaves` must contain no derived variables, or leaves
179/// of only derived variables would shift the indices.
180pub(super) fn mobility(task: &Task, leaves: &[Vec<VarId>]) -> Vec<bool> {
181 let factoring = Factoring::from_leaves(task, leaves.to_vec());
182 mobile_leaves(task, &factoring).unwrap_or_else(|_| vec![false; factoring.leaves.len()])
183}
184
185/// The variables by decreasing number of incident causal-graph arcs
186/// (incoming plus outgoing), the smaller variable first on ties.
187fn incident_arc_order(graph: &FactorGraph, n: usize) -> Vec<VarId> {
188 let mut order: Vec<VarId> = (0..n).collect();
189 order.sort_by_key(|&v| {
190 (
191 Reverse(graph.successors(v).len() + graph.predecessors(v).len()),
192 v,
193 )
194 });
195 order
196}
197
198/// Per variable of the `n` in `graph`, its distinct neighbours in either
199/// direction, sorted.
200///
201/// [`FactorGraph`] joins the inputs of every derived variable, so this
202/// keeps them in one factor: the search rejects a derived variable that
203/// depends on two leaves ([`crate::Error::AxiomAcrossLeaves`]). The paper
204/// has no axioms; without them this is the causal graph's undirected
205/// neighbourhood.
206fn neighbours(graph: &FactorGraph, n: usize) -> Vec<Vec<VarId>> {
207 (0..n)
208 .map(|v| {
209 let mut list: Vec<VarId> = graph
210 .successors(v)
211 .iter()
212 .chain(graph.predecessors(v))
213 .copied()
214 .collect();
215 list.sort_unstable();
216 list.dedup();
217 list
218 })
219 .collect()
220}
221
222/// The weakly connected components of the non-center variables under
223/// [`neighbours`] with at most [`crate::MAX_LEAF_STATES`] states.
224fn small_components(task: &Task, neighbours: &[Vec<VarId>], in_center: &[bool]) -> Vec<Vec<VarId>> {
225 weak_components(neighbours, in_center)
226 .into_iter()
227 .filter(|c| leaf_states(task, c).is_some())
228 .collect()
229}
230
231/// The weakly connected components of the non-center variables under
232/// [`neighbours`], each sorted, in order of their smallest variable.
233fn weak_components(neighbours: &[Vec<VarId>], in_center: &[bool]) -> Vec<Vec<VarId>> {
234 let mut seen = in_center.to_vec();
235 let mut components = Vec::new();
236 for start in 0..in_center.len() {
237 if seen[start] {
238 continue;
239 }
240
241 seen[start] = true;
242 let mut component = vec![start];
243 let mut stack = vec![start];
244 while let Some(v) = stack.pop() {
245 for &u in &neighbours[v] {
246 if !seen[u] {
247 seen[u] = true;
248 component.push(u);
249 stack.push(u);
250 }
251 }
252 }
253
254 component.sort_unstable();
255 components.push(component);
256 }
257
258 components
259}
260
261#[cfg(test)]
262mod tests {
263 use alloc::vec::Vec;
264
265 use sas_plus::random::{RandomTaskParams, random_task};
266
267 use super::*;
268
269 /// The cheap mobility count the strategies rank by agrees with
270 /// [`Factoring::score`] whenever the search accepts the factoring.
271 #[test]
272 fn mobility_matches_the_score() {
273 let mut compared = 0;
274 for seed in 0..200 {
275 let task = random_task(seed, RandomTaskParams::default());
276 let n = task.num_variables();
277 let partitions: [Vec<Vec<VarId>>; 3] = [
278 (0..n).map(|v| vec![v]).collect(),
279 (0..n).step_by(2).map(|v| vec![v]).collect(),
280 vec![(0..n / 2).collect()],
281 ];
282 for leaves in partitions {
283 let leaves: Vec<Vec<VarId>> = leaves
284 .into_iter()
285 .filter(|l| !l.is_empty() && leaf_states(&task, l).is_some())
286 .collect();
287 let Ok(score) = Factoring::from_leaves(&task, leaves.clone()).score(&task) else {
288 continue;
289 };
290
291 let mobile = mobility(&task, &leaves).iter().filter(|&&m| m).count();
292 assert_eq!(mobile, score.mobile_leaves, "seed {seed}: {leaves:?}");
293 compared += 1;
294 }
295 }
296
297 assert!(compared > 300, "only {compared} comparisons");
298 }
299}