decoupled_search/factoring.rs
1//! Center/leaf partitions of a task's variables, and strategies that derive
2//! them from the causal graph.
3//!
4//! Every strategy and [`Factoring::check_star`] read "the causal graph" as
5//! the search sees it: derived variables are replaced by the state
6//! variables they depend on ([`graph::FactorGraph`]). Without axioms that
7//! is the causal graph itself.
8
9mod generalized;
10mod graph;
11mod scoring;
12mod star;
13
14use alloc::vec;
15use alloc::vec::Vec;
16
17use sas_plus::{Task, VarId};
18
19use graph::FactorGraph;
20pub use scoring::{FactoringScore, Objective, Strategy};
21
22use crate::{Error, MAX_LEAF_STATES};
23
24/// A partition of a task's variables into one center and any number of
25/// leaves.
26///
27/// Every partition is valid: operators that would break the star topology
28/// (for example by reading one leaf and writing another) are searched
29/// explicitly as global actions. The factoring only decides how much of the
30/// task is priced in the leaves instead of searched.
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct Factoring {
33 /// Center variables, sorted ascending.
34 center: Vec<VarId>,
35 /// Leaf variables, each leaf non-empty. No variable appears twice.
36 leaves: Vec<Vec<VarId>>,
37}
38
39impl Factoring {
40 /// A factoring with the given leaves; all other variables form the center.
41 ///
42 /// # Errors
43 ///
44 /// - [`Error::UnknownVariable`] if a leaf names a variable `task` lacks.
45 /// - [`Error::DuplicateVariable`] if a variable appears twice.
46 /// - [`Error::DerivedInLeaf`] if a leaf names a derived variable.
47 /// - [`Error::EmptyLeaf`] if a leaf has no variables.
48 ///
49 /// Leaves of any size are accepted; searching with explicit leaves
50 /// rejects one with more than [`MAX_LEAF_STATES`] states
51 /// ([`Error::LeafTooLarge`]), symbolic leaves
52 /// ([`crate::Config::symbolic_leaves`]) do not.
53 pub fn new(task: &Task, leaves: Vec<Vec<VarId>>) -> Result<Self, Error> {
54 let mut in_leaf = vec![false; task.num_variables()];
55 for (index, leaf) in leaves.iter().enumerate() {
56 if leaf.is_empty() {
57 return Err(Error::EmptyLeaf { leaf: index });
58 }
59
60 for &var in leaf {
61 let seen = in_leaf.get_mut(var).ok_or(Error::UnknownVariable { var })?;
62 if *seen {
63 return Err(Error::DuplicateVariable { var });
64 }
65
66 if task.variables[var].is_derived() {
67 return Err(Error::DerivedInLeaf { var });
68 }
69
70 *seen = true;
71 }
72 }
73
74 Ok(Self::from_leaves(task, leaves))
75 }
76
77 /// A factoring with the given, already checked leaves; all other
78 /// variables form the center. Derived variables are moved to the center,
79 /// and leaves left empty by that are dropped.
80 fn from_leaves(task: &Task, mut leaves: Vec<Vec<VarId>>) -> Self {
81 for leaf in &mut leaves {
82 leaf.retain(|&v| !task.variables[v].is_derived());
83 }
84
85 leaves.retain(|leaf| !leaf.is_empty());
86 let mut in_leaf = vec![false; task.num_variables()];
87 for &v in leaves.iter().flatten() {
88 in_leaf[v] = true;
89 }
90
91 let center = (0..task.num_variables()).filter(|&v| !in_leaf[v]).collect();
92 Self { center, leaves }
93 }
94
95 /// The fork factoring: every sink strongly connected component of the
96 /// causal graph (one no arc leaves) with at most [`MAX_LEAF_STATES`]
97 /// states is a leaf, everything else is the center.
98 ///
99 /// Operators on a sink component read only the center and that component,
100 /// so all of them are priced in the leaf. A task whose causal graph is one
101 /// small component becomes one leaf with an empty center.
102 #[must_use]
103 pub fn fork(task: &Task) -> Self {
104 let graph = FactorGraph::new(task);
105 Self::from_components(
106 task,
107 sink_components(task.num_variables(), |v| graph.successors(v)),
108 )
109 }
110
111 /// The inverted-fork factoring: every source strongly connected component
112 /// of the causal graph (one no arc enters) with at most
113 /// [`MAX_LEAF_STATES`] states is a leaf, everything else is the center.
114 ///
115 /// Operators on a source component read and write only that component,
116 /// and the center may read it. Such operators are leaf actions unless they
117 /// also touch the center.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// use decoupled_search::Factoring;
123 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
124 ///
125 /// // A switch (variable 0) that a lamp (variable 1) depends on.
126 /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
127 /// name: "op".into(),
128 /// pre,
129 /// eff: vec![Effect::new(eff)],
130 /// cost: 1,
131 /// };
132 /// let task = Task {
133 /// variables: vec![Variable::new("switch", 2), Variable::new("lamp", 2)],
134 /// operators: vec![
135 /// op(vec![], Fact::new(0, 1)),
136 /// op(vec![Fact::new(0, 1)], Fact::new(1, 1)),
137 /// ],
138 /// initial: State(vec![0, 0]),
139 /// goal: vec![Fact::new(1, 1)],
140 /// axioms: vec![],
141 /// };
142 ///
143 /// let factoring = Factoring::inverted_fork(&task);
144 /// assert_eq!(factoring.leaves(), &[vec![0]]);
145 /// assert_eq!(factoring.center(), &[1]);
146 /// ```
147 #[must_use]
148 pub fn inverted_fork(task: &Task) -> Self {
149 let graph = FactorGraph::new(task);
150 Self::from_components(
151 task,
152 sink_components(task.num_variables(), |v| graph.predecessors(v)),
153 )
154 }
155
156 /// The X-shape factoring (Gnad, Hoffmann and Domshlak, `SoCS` 2015): the
157 /// fork factoring, plus every small source strongly connected component
158 /// of the rest of the causal graph that has no arc into a fork leaf.
159 ///
160 /// The paper runs the fork strategy and then the inverted-fork strategy
161 /// on the fork center, putting back into the center every inverted-fork
162 /// leaf with an arc into a fork leaf. Fork leaves have no outgoing arcs,
163 /// so the source components of the fork center are source components
164 /// of the whole causal graph. Every leaf then touches only the center:
165 /// fork leaves receive arcs from it, inverted-fork leaves send arcs to
166 /// it, so the result passes [`Factoring::check_star`]. Leaves keep the
167 /// [`MAX_LEAF_STATES`] bound of the other strategies.
168 ///
169 /// # Examples
170 ///
171 /// ```
172 /// use decoupled_search::Factoring;
173 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
174 ///
175 /// // A switch (0) enables a truck (1) that moves a package (2).
176 /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
177 /// name: "op".into(),
178 /// pre,
179 /// eff: vec![Effect::new(eff)],
180 /// cost: 1,
181 /// };
182 /// let var = |name: &str| Variable::new(name, 2);
183 /// let task = Task {
184 /// variables: vec![var("switch"), var("truck"), var("package")],
185 /// operators: vec![
186 /// op(vec![], Fact::new(0, 1)),
187 /// op(vec![Fact::new(0, 1)], Fact::new(1, 1)),
188 /// op(vec![Fact::new(1, 1)], Fact::new(2, 1)),
189 /// ],
190 /// initial: State(vec![0, 0, 0]),
191 /// goal: vec![Fact::new(2, 1)],
192 /// axioms: vec![],
193 /// };
194 ///
195 /// let factoring = Factoring::x_shape(&task);
196 /// assert_eq!(factoring.center(), &[1]);
197 /// assert_eq!(factoring.leaves(), &[vec![2], vec![0]]);
198 /// assert_eq!(factoring.check_star(&task), Ok(()));
199 /// ```
200 #[must_use]
201 pub fn x_shape(task: &Task) -> Self {
202 let n = task.num_variables();
203 let graph = FactorGraph::new(task);
204 let mut leaves: Vec<Vec<VarId>> = sink_components(n, |v| graph.successors(v))
205 .into_iter()
206 .filter(|c| leaf_states(task, c).is_some())
207 .collect();
208 let mut in_fork_leaf = vec![false; n];
209 for &v in leaves.iter().flatten() {
210 in_fork_leaf[v] = true;
211 }
212
213 let inverted = sink_components(n, |v| graph.predecessors(v))
214 .into_iter()
215 .filter(|c| c.iter().all(|&v| !in_fork_leaf[v]))
216 .filter(|c| leaf_states(task, c).is_some())
217 .filter(|c| {
218 c.iter()
219 .all(|&v| graph.successors(v).iter().all(|&u| !in_fork_leaf[u]))
220 });
221 leaves.extend(inverted);
222
223 Self::from_leaves(task, leaves)
224 }
225
226 /// A factoring whose leaves are the given disjoint, non-empty components
227 /// that have at most [`MAX_LEAF_STATES`] states; larger components join
228 /// the center.
229 fn from_components(task: &Task, components: Vec<Vec<VarId>>) -> Self {
230 let leaves = components
231 .into_iter()
232 .filter(|c| leaf_states(task, c).is_some())
233 .collect();
234
235 Self::from_leaves(task, leaves)
236 }
237
238 /// Checks that the factoring is a strict star: no causal-graph arc
239 /// connects variables of two different leaves, so leaves interact only
240 /// through the center. A derived variable counts as the state variables
241 /// it depends on (the search evaluates it with them), and those must lie
242 /// in one factor.
243 ///
244 /// Search does not require this, since an operator that couples two
245 /// leaves becomes a global action. In a star factoring no operator writes
246 /// one leaf while reading or writing another, which keeps the leaves
247 /// independent. An operator may still read several leaves and write only
248 /// the center. All strategies of this type except
249 /// [`Factoring::new`] produce star factorings.
250 ///
251 /// # Errors
252 ///
253 /// [`Error::NotStar`] with the first offending arc `from -> to` (in
254 /// variable order; through a derived variable, `from` is one of its
255 /// inputs), and [`Error::FactoringMismatch`] if the factoring does not
256 /// partition exactly the variables of `task`.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// use decoupled_search::{Error, Factoring};
262 /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
263 ///
264 /// // One operator reads variable 0 and writes variable 1.
265 /// let task = Task {
266 /// variables: vec![Variable::new("a", 2), Variable::new("b", 2)],
267 /// operators: vec![Operator {
268 /// name: "op".into(),
269 /// pre: vec![Fact::new(0, 1)],
270 /// eff: vec![Effect::new(Fact::new(1, 1))],
271 /// cost: 1,
272 /// }],
273 /// initial: State(vec![0, 0]),
274 /// goal: vec![Fact::new(1, 1)],
275 /// axioms: vec![],
276 /// };
277 ///
278 /// let split = Factoring::new(&task, vec![vec![0], vec![1]])?;
279 /// assert_eq!(split.check_star(&task), Err(Error::NotStar { from: 0, to: 1 }));
280 /// assert_eq!(Factoring::fork(&task).check_star(&task), Ok(()));
281 /// # Ok::<(), Error>(())
282 /// ```
283 pub fn check_star(&self, task: &Task) -> Result<(), Error> {
284 let leaf_of = self.leaf_of(task)?;
285 let graph = FactorGraph::new(task);
286 for from in 0..task.num_variables() {
287 let Some(leaf) = leaf_of[from] else {
288 continue;
289 };
290
291 if let Some(&to) = graph
292 .successors(from)
293 .iter()
294 .find(|&&to| leaf_of[to].is_some_and(|other| other != leaf))
295 {
296 return Err(Error::NotStar { from, to });
297 }
298 }
299
300 Ok(())
301 }
302
303 /// The leaf of every variable of `task`, `None` for center variables.
304 ///
305 /// # Errors
306 ///
307 /// [`Error::FactoringMismatch`] if the factoring does not partition
308 /// exactly the variables of `task`.
309 pub(crate) fn leaf_of(&self, task: &Task) -> Result<Vec<Option<usize>>, Error> {
310 let mut leaf_of = vec![None; task.num_variables()];
311 let mut seen = vec![false; task.num_variables()];
312 let center = self.center.iter().map(|&v| (v, None));
313 let leaves = self
314 .leaves
315 .iter()
316 .enumerate()
317 .flat_map(|(leaf, vars)| vars.iter().map(move |&v| (v, Some(leaf))));
318 for (var, leaf) in center.chain(leaves) {
319 let slot = seen.get_mut(var).ok_or(Error::FactoringMismatch)?;
320 if core::mem::replace(slot, true) {
321 return Err(Error::FactoringMismatch);
322 }
323
324 leaf_of[var] = leaf;
325 }
326
327 if seen.contains(&false) {
328 return Err(Error::FactoringMismatch);
329 }
330
331 Ok(leaf_of)
332 }
333
334 /// The center variables, sorted ascending. May be empty.
335 #[must_use]
336 pub fn center(&self) -> &[VarId] {
337 &self.center
338 }
339
340 /// The leaves, each a non-empty list of variables.
341 #[must_use]
342 pub fn leaves(&self) -> &[Vec<VarId>] {
343 &self.leaves
344 }
345}
346
347/// The number of states of a leaf over `vars`, or `None` if it exceeds
348/// [`MAX_LEAF_STATES`].
349fn leaf_states(task: &Task, vars: &[VarId]) -> Option<usize> {
350 vars.iter().try_fold(1_usize, |size, &v| {
351 let domain = usize::try_from(task.variables[v].domain_size).ok()?;
352 size.checked_mul(domain).filter(|&s| s <= MAX_LEAF_STATES)
353 })
354}
355
356/// The sink strongly connected components of the graph over `n` vertices
357/// with arcs `v -> successors(v)`, each sorted, in order of their smallest
358/// vertex.
359///
360/// A vertex's component is a sink iff every vertex it reaches reaches it back.
361///
362/// shortcut: one depth-first search per vertex, `O(n * (n + arcs))` time and
363/// `O(n^2)` memory; switch to Tarjan if tasks with thousands of variables
364/// show up.
365fn sink_components<'g>(
366 n: usize,
367 successors: impl Fn(VarId) -> &'g [VarId] + Copy,
368) -> Vec<Vec<VarId>> {
369 let reach: Vec<Vec<bool>> = (0..n).map(|v| reachable(n, successors, v)).collect();
370 let mut assigned = vec![false; n];
371 let mut sinks = Vec::new();
372 for v in 0..n {
373 if assigned[v] {
374 continue;
375 }
376
377 let reached: Vec<VarId> = (0..n).filter(|&u| reach[v][u]).collect();
378 for &u in &reached {
379 assigned[u] |= reach[u][v];
380 }
381
382 if reached.iter().all(|&u| reach[u][v]) {
383 sinks.push(reached);
384 }
385 }
386
387 sinks
388}
389
390/// The vertices reachable from `start` over arcs `v -> successors(v)`,
391/// including `start`.
392fn reachable<'g>(n: usize, successors: impl Fn(VarId) -> &'g [VarId], start: VarId) -> Vec<bool> {
393 let mut seen = vec![false; n];
394 let mut stack = vec![start];
395 seen[start] = true;
396 while let Some(v) = stack.pop() {
397 for &w in successors(v) {
398 if !seen[w] {
399 seen[w] = true;
400 stack.push(w);
401 }
402 }
403 }
404
405 seen
406}