decoupled_search/lib.rs
1//! # Decoupled search
2//!
3//! Decoupled (star-topology) search for factored SAS+ planning tasks from
4//! [`sas_plus`] (Gnad & Hoffmann, ICAPS 2015 and AIJ 2018).
5//!
6//! A [`Factoring`] splits the variables into a *center* and *leaves*.
7//! [`search()`], [`astar`] and [`gbfs`] then explore paths of *global
8//! actions* (operators that are not confined to one leaf) and keep, for
9//! every leaf, the price of each leaf state reachable along the current
10//! path. They return a sequential [`Plan`] for the original task,
11//! cost-optimal for the first two; [`Plan::validate`] checks one
12//! independently. [`Config`] chooses the dominance criterion ([`Pruning`])
13//! and whether leaves keep prices at all ([`Leaves`]).
14//!
15//! ```mermaid
16//! graph LR
17//! task[sas_plus::Task] --> factoring[Factoring: auto, fork, star, explicit]
18//! factoring --> search[search / astar / gbfs over decoupled states]
19//! task --> search
20//! config[Config: pruning, leaves] --> search
21//! heuristic[HMax / HFf / MasHeuristic] --> search
22//! search --> plan[Plan: sequential, validated]
23//! ```
24//!
25//! ## Scope
26//!
27//! Fork, inverted-fork, X-shape, incident-arcs
28//! and independent-set star factorings (Gnad, Poser and Hoffmann, IJCAI
29//! 2017) and explicit ones, scored and chosen by [`Factoring::auto`];
30//! uniform-cost, A*, anytime A* and greedy search with basic, frontier,
31//! effective-price, simulation and adaptive dominance pruning and
32//! simulation-based leaf reduction; decoupled strong stubborn sets
33//! (Gnad, Hoffmann and Wehrle, JAIR 2019); symbolic leaves behind the
34//! `symbolic-leaves` feature (Gnad, Torralba and Hoffmann 2017);
35//! reachability-only
36//! leaves for greedy search; `h^max` and `h^FF` on decoupled states, a
37//! merge-and-shrink adapter behind the `merge-and-shrink` feature, and an
38//! LM-cut adapter behind the `lm-cut` feature.
39//! Conditional effects and axioms are supported where the decoupled
40//! semantics can express them and rejected with precise errors otherwise.
41//!
42//! Repository: <https://github.com/sunsided/decoupled-search>
43
44#![no_std]
45#![forbid(unsafe_code)]
46
47extern crate alloc;
48
49mod decoupled;
50mod factoring;
51mod heuristic;
52mod plan;
53mod search;
54#[cfg(feature = "symbolic-leaves")]
55mod symbolic;
56
57use core::fmt;
58
59use sas_plus::{OpId, TaskError, VarId};
60
61pub use factoring::{Factoring, FactoringScore, Objective, Strategy};
62#[cfg(feature = "lm-cut")]
63pub use heuristic::LmCutHeuristic;
64#[cfg(feature = "merge-and-shrink")]
65pub use heuristic::MasHeuristic;
66pub use heuristic::{DecoupledHeuristic, FactPrices, HFf, HMax};
67pub use plan::{Plan, PlanError};
68pub use search::{Config, Leaves, Outcome, Pruning, Statistics, astar, gbfs, search};
69
70/// The largest number of states a leaf may have. Leaf reachability works on
71/// dense price vectors of this size, and stored leaf-state ranks fit in
72/// `u16`.
73pub const MAX_LEAF_STATES: usize = 1 << 16;
74
75/// Why a task or factoring cannot be searched.
76#[derive(Clone, Debug, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum Error {
79 /// The task failed [`sas_plus::Task::validate`].
80 InvalidTask(TaskError),
81 /// Effect `effect` of operator `op` sets a center variable under a
82 /// condition on a leaf variable. The successor's center would then
83 /// depend on which leaf state the operator is applied in, which a single
84 /// decoupled successor cannot express.
85 CenterEffectReadsLeaf {
86 /// The offending operator.
87 op: OpId,
88 /// Index of the offending effect in the operator's effect list.
89 effect: usize,
90 },
91 /// Effect `effect` of operator `op` sets a variable of one leaf under a
92 /// condition on another leaf, which would couple the two leaves' states.
93 EffectConditionAcrossLeaves {
94 /// The offending operator.
95 op: OpId,
96 /// Index of the offending effect in the operator's effect list.
97 effect: usize,
98 },
99 /// Derived variable `var` depends (directly or through other derived
100 /// variables) on the state variables of two leaves, so its value is not
101 /// a function of the center and one leaf state.
102 AxiomAcrossLeaves {
103 /// The offending derived variable.
104 var: VarId,
105 /// Two of the leaves it depends on, smaller index first.
106 leaves: (usize, usize),
107 },
108 /// A leaf names derived variable `var`. Derived variables are never
109 /// leaf variables: they stay in the center of a factoring and are
110 /// evaluated with the factor they depend on.
111 DerivedInLeaf {
112 /// The offending derived variable.
113 var: VarId,
114 },
115 /// Leaf prices without costs ([`Leaves::Reachability`]) were requested
116 /// for a cost-optimal search, which needs the prices.
117 ReachabilityNotOptimal,
118 /// A leaf names variable `var`, which the task does not have.
119 UnknownVariable {
120 /// The offending variable.
121 var: VarId,
122 },
123 /// Variable `var` appears in two leaves, or twice in one.
124 DuplicateVariable {
125 /// The offending variable.
126 var: VarId,
127 },
128 /// Leaf `leaf` has no variables.
129 EmptyLeaf {
130 /// Index of the offending leaf.
131 leaf: usize,
132 },
133 /// Leaf `leaf` has more than [`MAX_LEAF_STATES`] states, too many to
134 /// enumerate as explicit leaves.
135 LeafTooLarge {
136 /// Index of the offending leaf.
137 leaf: usize,
138 },
139 /// The factoring does not partition exactly the task's variables, so it
140 /// was built for a different task.
141 FactoringMismatch,
142 /// The causal graph has an arc `from -> to` between two different
143 /// leaves, so the factoring is not a strict star; see
144 /// [`Factoring::check_star`]. Through a derived variable, the arc runs
145 /// from one of its inputs (or joins two of them).
146 NotStar {
147 /// Source variable of the arc.
148 from: VarId,
149 /// Target variable of the arc.
150 to: VarId,
151 },
152 /// [`Config::symbolic_leaves`] was combined with `option`, which
153 /// symbolic leaves do not support.
154 SymbolicUnsupported {
155 /// What is not supported.
156 option: &'static str,
157 },
158 /// Symbolic leaves ran out of nodes in the largest BDD node table.
159 OutOfNodes,
160}
161
162impl fmt::Display for Error {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 match self {
165 Self::InvalidTask(e) => write!(f, "invalid task: {e}"),
166 Self::CenterEffectReadsLeaf { op, effect } => write!(
167 f,
168 "effect {effect} of operator {op} sets the center under a leaf condition"
169 ),
170 Self::EffectConditionAcrossLeaves { op, effect } => write!(
171 f,
172 "effect {effect} of operator {op} sets one leaf under a condition on another"
173 ),
174 Self::AxiomAcrossLeaves {
175 var,
176 leaves: (a, b),
177 } => write!(f, "derived variable {var} depends on leaves {a} and {b}"),
178 Self::DerivedInLeaf { var } => {
179 write!(f, "derived variable {var} cannot be a leaf variable")
180 }
181 Self::ReachabilityNotOptimal => {
182 write!(f, "reachability-only leaves need a greedy search")
183 }
184 Self::UnknownVariable { var } => write!(f, "unknown variable {var} in a leaf"),
185 Self::DuplicateVariable { var } => write!(f, "variable {var} appears twice"),
186 Self::EmptyLeaf { leaf } => write!(f, "leaf {leaf} is empty"),
187 Self::LeafTooLarge { leaf } => {
188 write!(f, "leaf {leaf} has more than {MAX_LEAF_STATES} states")
189 }
190 Self::FactoringMismatch => write!(f, "the factoring belongs to a different task"),
191 Self::NotStar { from, to } => {
192 write!(f, "causal-graph arc {from} -> {to} connects two leaves")
193 }
194 Self::SymbolicUnsupported { option } => {
195 write!(f, "symbolic leaves do not support {option}")
196 }
197 Self::OutOfNodes => write!(f, "symbolic leaves ran out of BDD nodes"),
198 }
199 }
200}
201
202impl core::error::Error for Error {
203 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
204 match self {
205 Self::InvalidTask(e) => Some(e),
206 _ => None,
207 }
208 }
209}
210
211/// Doctests for the code examples in README.md (not part of the API).
212#[cfg(doctest)]
213#[doc = include_str!("../README.md")]
214mod readme_doctests {}