Skip to main content

decoupled_search/factoring/
scoring.rs

1//! Scoring factorings, and choosing among the strategies automatically.
2//!
3//! A leaf is *mobile* if it has at least one leaf action. This is Gnad,
4//! Poser and Hoffmann's (IJCAI 2017) definition: their flexibility of a
5//! leaf is the share of the actions affecting it that affect only it, and
6//! a leaf is mobile if that share is positive; for strict-star factorings
7//! the actions affecting only a leaf are exactly our leaf actions. Like
8//! their strategies (and Torralba, Gnad, Dubbert and Hoffmann 2016),
9//! [`Factoring::auto`] abstains, falling back to explicit search, when no
10//! candidate has two mobile leaves: the gain of decoupled search comes from
11//! not enumerating combinations of leaf states across leaves.
12//!
13//! The paper ranks the candidate factorings by one-second sample searches
14//! (expansions for optimal planning, heuristic improvement for satisficing
15//! planning). This crate has no clock (`no_std`) and `auto` does not know
16//! the search configuration, so it ranks by the static score instead: the
17//! leaf-action share, then mobile leaves, then the smaller largest leaf.
18//! That ranking is ours.
19
20use alloc::vec::Vec;
21use core::cmp::Reverse;
22
23use sas_plus::Task;
24
25use super::Factoring;
26use crate::Error;
27use crate::decoupled::DecoupledTask;
28use crate::search;
29
30/// A factoring strategy of [`Factoring`].
31#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub enum Strategy {
33    /// [`Factoring::fork`].
34    Fork,
35    /// [`Factoring::inverted_fork`].
36    InvertedFork,
37    /// [`Factoring::x_shape`].
38    XShape,
39    /// [`Factoring::incident_arcs`].
40    IncidentArcs,
41    /// [`Factoring::max_leaves`], the independent-set strategy.
42    MaxLeaves,
43    /// [`Factoring::generalized`]: leaves that may interact directly, around
44    /// a possibly empty center.
45    Generalized,
46}
47
48impl Strategy {
49    /// Every strategy, in the order [`Factoring::auto`] breaks ties by.
50    pub const ALL: [Self; 6] = [
51        Self::Fork,
52        Self::InvertedFork,
53        Self::XShape,
54        Self::IncidentArcs,
55        Self::MaxLeaves,
56        Self::Generalized,
57    ];
58}
59
60/// What [`Factoring::auto_by_sample`] selects for.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
62#[non_exhaustive]
63pub enum Objective {
64    /// Cost-optimal planning: samples run decoupled A* with `h^max`.
65    Optimal,
66    /// Satisficing planning: samples run greedy best-first search with
67    /// `h^FF`.
68    Satisficing,
69}
70
71/// The measurements of one sample search, compared by
72/// [`Factoring::auto_by_sample`].
73#[derive(Clone, Copy, Debug)]
74struct Sample {
75    /// Whether the sample finished within its budget: proved its result
76    /// (cost-optimal), or found a plan or proved there is none
77    /// (satisficing).
78    solved: bool,
79    /// Expansions made.
80    expanded: u64,
81    /// Work units spent, at least 1.
82    work: u64,
83    /// Heuristic value of the initial state.
84    initial_h: u64,
85    /// Least heuristic value seen.
86    best_h: u64,
87}
88
89impl Sample {
90    /// Runs the sample search of `objective` on `factoring` for at most
91    /// `expansions` expansions; `None` if the search rejects the factoring.
92    fn run(
93        task: &Task,
94        factoring: &Factoring,
95        objective: Objective,
96        expansions: u64,
97    ) -> Option<Self> {
98        let optimal = objective == Objective::Optimal;
99        let (probe, expanded) = search::sample(task, factoring, optimal, expansions).ok()?;
100        let solved = !probe.cut_off;
101        Some(Self {
102            solved,
103            expanded,
104            work: probe.work.max(1),
105            initial_h: probe.initial_h.unwrap_or(0),
106            best_h: probe.best_h.unwrap_or(0),
107        })
108    }
109
110    /// Whether this sample ranks strictly above `other` under `objective`:
111    /// finished samples first, the less work among them; then, for
112    /// cost-optimal planning, more expansions per work unit (the paper's
113    /// expansions within a time limit), and for satisficing planning, the
114    /// larger heuristic improvement `initial_h / best_h`, then less work.
115    fn beats(&self, other: &Self, objective: Objective) -> bool {
116        let wide = u128::from;
117        if self.solved != other.solved {
118            return self.solved;
119        }
120
121        if self.solved {
122            return self.work < other.work;
123        }
124
125        match objective {
126            Objective::Optimal => {
127                wide(self.expanded) * wide(other.work) > wide(other.expanded) * wide(self.work)
128            }
129            Objective::Satisficing => {
130                let ours = wide(self.initial_h) * wide(other.best_h.max(1));
131                let theirs = wide(other.initial_h) * wide(self.best_h.max(1));
132                ours > theirs || (ours == theirs && self.work < other.work)
133            }
134        }
135    }
136}
137
138/// How well a factoring decouples a task.
139///
140/// # Examples
141///
142/// ```
143/// use decoupled_search::Factoring;
144/// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
145///
146/// // A truck (variable 0) and two packages that ride along.
147/// let op = |pre: Vec<Fact>, eff: Fact| Operator {
148///     name: "op".into(),
149///     pre,
150///     eff: vec![Effect::new(eff)],
151///     cost: 1,
152/// };
153/// let task = Task {
154///     variables: vec![Variable::new("truck", 2), Variable::new("p", 3), Variable::new("q", 3)],
155///     operators: vec![
156///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
157///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
158///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
159///         op(vec![Fact::new(0, 0), Fact::new(2, 0)], Fact::new(2, 2)),
160///     ],
161///     initial: State(vec![0, 0, 0]),
162///     goal: vec![Fact::new(1, 1), Fact::new(2, 2)],
163///     axioms: vec![],
164/// };
165///
166/// let score = Factoring::fork(&task).score(&task)?;
167/// assert_eq!((score.leaves, score.mobile_leaves), (2, 2));
168/// assert_eq!((score.leaf_actions, score.global_actions), (3, 1));
169/// assert_eq!(score.leaf_action_share(), 0.75);
170/// assert_eq!((score.max_leaf_states, score.total_leaf_states), (3, 6));
171/// # Ok::<(), decoupled_search::Error>(())
172/// ```
173#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
174#[non_exhaustive]
175pub struct FactoringScore {
176    /// Number of leaves.
177    pub leaves: usize,
178    /// Number of mobile leaves: leaves with at least one leaf action, which
179    /// can move without a global action (Gnad, Poser and Hoffmann 2017:
180    /// flexibility above 0).
181    pub mobile_leaves: usize,
182    /// Operators priced inside a leaf.
183    pub leaf_actions: usize,
184    /// Operators searched explicitly.
185    pub global_actions: usize,
186    /// States of the largest leaf; 0 without leaves.
187    pub max_leaf_states: usize,
188    /// States of all leaves together.
189    pub total_leaf_states: usize,
190}
191
192impl FactoringScore {
193    /// The share of operators that are leaf actions, in `0.0..=1.0`; 0 for
194    /// a task without operators.
195    #[must_use]
196    pub fn leaf_action_share(&self) -> f64 {
197        let total = self.leaf_actions + self.global_actions;
198        if total == 0 {
199            return 0.0;
200        }
201
202        // Operator counts stay far below 2^52, so the conversion is exact.
203        #[expect(clippy::cast_precision_loss, reason = "operator counts are small")]
204        let share = self.leaf_actions as f64 / total as f64;
205        share
206    }
207
208    /// The ranking key of [`Factoring::auto`], greater is better: the
209    /// leaf-action share (compared exactly, as a fraction), then more
210    /// mobile leaves, then the smaller largest leaf.
211    fn key(&self) -> (Share, usize, Reverse<usize>) {
212        (
213            Share(self.leaf_actions, self.leaf_actions + self.global_actions),
214            self.mobile_leaves,
215            Reverse(self.max_leaf_states),
216        )
217    }
218}
219
220/// A fraction `numerator / denominator`, ordered by value; `0 / 0` counts
221/// as 0.
222#[derive(Clone, Copy, Debug)]
223struct Share(usize, usize);
224
225impl Share {
226    /// The value as a pair that cross-multiplies exactly.
227    fn parts(self) -> (u128, u128) {
228        let widen = |n: usize| u128::try_from(n).expect("usize fits in u128");
229        (widen(self.0), widen(self.1.max(1)))
230    }
231}
232
233impl PartialEq for Share {
234    fn eq(&self, other: &Self) -> bool {
235        self.cmp(other).is_eq()
236    }
237}
238
239impl Eq for Share {}
240
241impl PartialOrd for Share {
242    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
243        Some(self.cmp(other))
244    }
245}
246
247impl Ord for Share {
248    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
249        let ((a, b), (c, d)) = (self.parts(), other.parts());
250        (a * d).cmp(&(c * b))
251    }
252}
253
254impl Factoring {
255    /// The factoring that `strategy` computes for `task`.
256    #[must_use]
257    pub fn with_strategy(task: &Task, strategy: Strategy) -> Self {
258        match strategy {
259            Strategy::Fork => Self::fork(task),
260            Strategy::InvertedFork => Self::inverted_fork(task),
261            Strategy::XShape => Self::x_shape(task),
262            Strategy::IncidentArcs => Self::incident_arcs(task),
263            Strategy::MaxLeaves => Self::max_leaves(task),
264            Strategy::Generalized => Self::generalized(task),
265        }
266    }
267
268    /// `task` with every operator that is a leaf action under this
269    /// factoring at cost 0: the task whose heuristics are root heuristics
270    /// for [`crate::Config::anytime_astar`] (Gnad and Hoffmann's
271    /// leaves-for-free root estimate, ICAPS 2015, Definition 6).
272    ///
273    /// # Errors
274    ///
275    /// As [`Factoring::score`].
276    ///
277    /// # Examples
278    ///
279    /// ```
280    /// use decoupled_search::Factoring;
281    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
282    ///
283    /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
284    ///     name: "op".into(),
285    ///     pre,
286    ///     eff: vec![Effect::new(eff)],
287    ///     cost: 2,
288    /// };
289    /// let task = Task {
290    ///     variables: vec![Variable::new("truck", 2), Variable::new("pkg", 2)],
291    ///     operators: vec![
292    ///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
293    ///         op(vec![Fact::new(0, 1)], Fact::new(1, 1)),
294    ///     ],
295    ///     initial: State(vec![0, 0]),
296    ///     goal: vec![Fact::new(1, 1)],
297    ///     axioms: vec![],
298    /// };
299    ///
300    /// // The package moves by a leaf action, the truck by a global one.
301    /// let free = Factoring::fork(&task).with_free_leaf_actions(&task)?;
302    /// let costs: Vec<u32> = free.operators.iter().map(|o| o.cost).collect();
303    /// assert_eq!(costs, [2, 0]);
304    /// # Ok::<(), decoupled_search::Error>(())
305    /// ```
306    pub fn with_free_leaf_actions(&self, task: &Task) -> Result<Task, Error> {
307        let decoupled = DecoupledTask::new(task, self)?;
308        let mut free = task.clone();
309        for action in decoupled.leaves.iter().flat_map(|l| &l.actions) {
310            free.operators[action.op].cost = 0;
311        }
312
313        Ok(free)
314    }
315
316    /// Scores this factoring on `task`, classifying operators exactly as
317    /// the search does.
318    ///
319    /// # Errors
320    ///
321    /// Every error of [`crate::search()`] except
322    /// [`Error::ReachabilityNotOptimal`]: the factoring must be searchable.
323    pub fn score(&self, task: &Task) -> Result<FactoringScore, Error> {
324        let decoupled = DecoupledTask::new(task, self)?;
325        let leaves = &decoupled.leaves;
326
327        Ok(FactoringScore {
328            leaves: leaves.len(),
329            mobile_leaves: leaves.iter().filter(|l| !l.actions.is_empty()).count(),
330            leaf_actions: leaves.iter().map(|l| l.actions.len()).sum(),
331            global_actions: decoupled.globals.len(),
332            max_leaf_states: leaves.iter().map(|l| l.size).max().unwrap_or(0),
333            total_leaf_states: leaves.iter().map(|l| l.size).sum(),
334        })
335    }
336
337    /// The best factoring of every [`Strategy`] for `task` with at least two
338    /// mobile leaves, by score: the largest share of leaf actions, then more
339    /// mobile leaves, then the smaller largest leaf, then the earlier
340    /// strategy in [`Strategy::ALL`]. [`Strategy::Generalized`] comes last
341    /// there, so it wins only when it scores strictly better than every star
342    /// strategy; its leaves may then interact directly.
343    ///
344    /// Factorings that [`Factoring::score`] rejects (for example because
345    /// an axiom spans two of their leaves) are skipped. If no candidate has
346    /// two mobile leaves, the result is the factoring without leaves:
347    /// explicit search over the whole task. Gnad, Poser and Hoffmann (2017)
348    /// abstain in that case too, since decoupling gains by not combining
349    /// the states of several leaves; they rank candidates by short sample
350    /// searches, this ranking is static (see the module docs).
351    ///
352    /// # Examples
353    ///
354    /// ```
355    /// use decoupled_search::{Factoring, search};
356    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
357    ///
358    /// // A hub that both spokes read and that reads both spokes.
359    /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
360    ///     name: "op".into(),
361    ///     pre,
362    ///     eff: vec![Effect::new(eff)],
363    ///     cost: 1,
364    /// };
365    /// let task = Task {
366    ///     variables: vec![Variable::new("hub", 2), Variable::new("a", 2), Variable::new("b", 2)],
367    ///     operators: vec![
368    ///         op(vec![Fact::new(1, 1), Fact::new(2, 1)], Fact::new(0, 1)),
369    ///         op(vec![Fact::new(0, 0)], Fact::new(1, 1)),
370    ///         op(vec![Fact::new(0, 0)], Fact::new(2, 1)),
371    ///     ],
372    ///     initial: State(vec![0, 0, 0]),
373    ///     goal: vec![Fact::new(0, 1)],
374    ///     axioms: vec![],
375    /// };
376    ///
377    /// // The fork factoring finds no sink component; the star strategies do.
378    /// let factoring = Factoring::auto(&task);
379    /// assert_eq!(factoring.leaves(), &[vec![1], vec![2]]);
380    /// assert_eq!(search(&task, &factoring)?.map(|p| p.cost), Some(3));
381    /// # Ok::<(), decoupled_search::Error>(())
382    /// ```
383    #[must_use]
384    pub fn auto(task: &Task) -> Self {
385        Strategy::ALL
386            .iter()
387            .rev()
388            .filter_map(|&s| {
389                let factoring = Self::with_strategy(task, s);
390                factoring.score(task).ok().map(|score| (score, factoring))
391            })
392            .filter(|(score, _)| score.mobile_leaves >= 2)
393            .max_by_key(|(score, _)| score.key())
394            .map_or_else(
395                || Self::from_leaves(task, alloc::vec::Vec::new()),
396                |(_, f)| f,
397            )
398    }
399
400    /// The factoring of the strategy whose short sample search does best,
401    /// among those [`Factoring::auto`] would consider (two mobile leaves,
402    /// accepted by the search): Gnad, Poser and Hoffmann's (2017)
403    /// per-instance selection, with an expansion budget instead of a time
404    /// limit.
405    ///
406    /// Each distinct candidate runs a sample search of `objective` (see
407    /// [`Objective`]) for at most `expansions` expansions. A sample that
408    /// finishes (cost-optimal: proves its result; satisficing: finds a
409    /// plan) wins, the cheapest such one first; the paper would return its
410    /// plan, here the caller searches again. Otherwise, as in the paper,
411    /// satisficing planning prefers the larger heuristic improvement (the
412    /// initial state's `h^FF` over the least one seen), and cost-optimal
413    /// planning the faster expansion rate. With a budget of expansions
414    /// rather than of time, the rate is measured in deterministic work
415    /// units (per generated decoupled state, one plus the leaf states its
416    /// leaf closures range over), our proxy for time. Ties go to the earlier
417    /// strategy in [`Strategy::ALL`]. Without a candidate, the result is
418    /// the factoring without leaves; with one, no sample is run.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use decoupled_search::{Factoring, Objective, search};
424    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
425    ///
426    /// // A truck (0) and two packages that ride along.
427    /// let op = |pre: Vec<Fact>, eff: Fact| Operator {
428    ///     name: "op".into(),
429    ///     pre,
430    ///     eff: vec![Effect::new(eff)],
431    ///     cost: 1,
432    /// };
433    /// let task = Task {
434    ///     variables: vec![Variable::new("truck", 2), Variable::new("p", 3), Variable::new("q", 3)],
435    ///     operators: vec![
436    ///         op(vec![Fact::new(0, 0)], Fact::new(0, 1)),
437    ///         op(vec![Fact::new(0, 0), Fact::new(1, 0)], Fact::new(1, 2)),
438    ///         op(vec![Fact::new(0, 1), Fact::new(1, 2)], Fact::new(1, 1)),
439    ///         op(vec![Fact::new(0, 0), Fact::new(2, 0)], Fact::new(2, 2)),
440    ///         op(vec![Fact::new(0, 1), Fact::new(2, 2)], Fact::new(2, 1)),
441    ///     ],
442    ///     initial: State(vec![0, 0, 0]),
443    ///     goal: vec![Fact::new(1, 1), Fact::new(2, 1)],
444    ///     axioms: vec![],
445    /// };
446    ///
447    /// let factoring = Factoring::auto_by_sample(&task, Objective::Optimal, 100);
448    /// assert_eq!(factoring.leaves().len(), 2);
449    /// assert_eq!(search(&task, &factoring)?.map(|p| p.cost), Some(5));
450    /// # Ok::<(), decoupled_search::Error>(())
451    /// ```
452    #[must_use]
453    pub fn auto_by_sample(task: &Task, objective: Objective, expansions: u64) -> Self {
454        let mut candidates: Vec<Self> = Vec::new();
455        for &strategy in &Strategy::ALL {
456            let factoring = Self::with_strategy(task, strategy);
457            let usable = factoring
458                .score(task)
459                .is_ok_and(|score| score.mobile_leaves >= 2);
460            if usable && !candidates.contains(&factoring) {
461                candidates.push(factoring);
462            }
463        }
464
465        if candidates.len() <= 1 {
466            return candidates
467                .pop()
468                .unwrap_or_else(|| Self::from_leaves(task, Vec::new()));
469        }
470
471        let mut best: Option<(Sample, Self)> = None;
472        for factoring in candidates {
473            let Some(sample) = Sample::run(task, &factoring, objective, expansions) else {
474                continue;
475            };
476
477            if best
478                .as_ref()
479                .is_none_or(|(b, _)| sample.beats(b, objective))
480            {
481                best = Some((sample, factoring));
482            }
483        }
484
485        best.map_or_else(|| Self::from_leaves(task, Vec::new()), |(_, f)| f)
486    }
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492
493    /// A sample with the given measurements.
494    fn sample(solved: bool, expanded: u64, work: u64, (initial_h, best_h): (u64, u64)) -> Sample {
495        Sample {
496            solved,
497            expanded,
498            work,
499            initial_h,
500            best_h,
501        }
502    }
503
504    /// Finished samples win, the cheaper first; then the expansion rate
505    /// (optimal) or the heuristic improvement (satisficing).
506    #[test]
507    fn samples_rank_as_the_paper_does() {
508        let (optimal, satisficing) = (Objective::Optimal, Objective::Satisficing);
509        let done = sample(true, 5, 50, (4, 0));
510        let faster = sample(false, 100, 1_000, (4, 2));
511        let slower = sample(false, 100, 3_000, (8, 2));
512        assert!(done.beats(&faster, optimal) && !faster.beats(&done, optimal));
513        assert!(sample(true, 9, 40, (4, 0)).beats(&done, optimal));
514
515        assert!(faster.beats(&slower, optimal) && !slower.beats(&faster, optimal));
516        // 8 / 2 beats 4 / 2 although it is slower.
517        assert!(slower.beats(&faster, satisficing) && !faster.beats(&slower, satisficing));
518        assert!(!faster.beats(&faster, satisficing), "ties do not win");
519    }
520}