Skip to main content

sas_plus/
lib.rs

1//! Minimal SAS+ planning tasks, labeled transition systems, and the
2//! [`Abstraction`] trait for abstraction heuristics.
3//!
4//! SAS+ (*Simplified Action Structures*, extended; Bäckström & Nebel 1995)
5//! describes planning tasks with finite-domain state variables, operators
6//! with preconditions and effects, and partial goals.
7//!
8//! Tasks may also use Fast Downward's two extensions of SAS+: conditional
9//! effects and axioms (derived variables).
10//!
11//! Tasks come from Fast Downward's translator via `fdr::SasFile` (the
12//! `output.sas` format, feature `fdr`), from your own grounder, or from
13//! `random` for tests (feature `random`).
14//!
15//! ```mermaid
16//! flowchart LR
17//!     pddl[PDDL] -->|Fast Downward translator| sas[output.sas]
18//!     sas -->|SasFile::parse| file[fdr::SasFile]
19//!     file -->|to_task| task[Task]
20//!     grounder[your grounder] --> task
21//!     random[random::random_task] --> task
22//!     task -->|Projection::new| proj[Projection]
23//!     proj -->|Abstraction::lts| lts[LabeledTransitionSystem]
24//!     lts -->|goal_distances| h[admissible estimates]
25//!     task -->|perfect_heuristic| hstar[exact h*]
26//! ```
27
28#![no_std]
29#![forbid(unsafe_code)]
30
31extern crate alloc;
32
33mod causal_graph;
34#[cfg(feature = "fdr")]
35pub mod fdr;
36mod lts;
37mod projection;
38#[cfg(feature = "random")]
39pub mod random;
40mod ranking;
41
42/// Doctests for the code examples in README.md (not part of the API).
43#[cfg(all(doctest, feature = "fdr"))]
44#[doc = include_str!("../README.md")]
45mod readme_doctests {}
46
47pub use causal_graph::CausalGraph;
48pub use lts::{LabeledTransitionSystem, Transition};
49pub use projection::Projection;
50
51use alloc::string::String;
52use alloc::vec;
53use alloc::vec::Vec;
54use core::fmt;
55
56/// Index of a variable in [`Task::variables`].
57pub type VarId = usize;
58
59/// A value of a variable, in `0..domain_size` ([`Variable::domain_size`]).
60pub type Value = u32;
61
62/// Index of an operator in [`Task::operators`]; also the label of its
63/// transitions in a [`LabeledTransitionSystem`].
64pub type OpId = usize;
65
66/// A variable/value assignment `var = value`.
67#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
68#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
69pub struct Fact {
70    /// The variable the fact assigns.
71    pub var: VarId,
72    /// The value it assigns, in `0..domain_size` of `var` in a valid task.
73    pub value: Value,
74}
75
76impl Fact {
77    /// The fact `var = value`.
78    #[must_use]
79    pub fn new(var: VarId, value: Value) -> Self {
80        Self { var, value }
81    }
82}
83
84/// A finite-domain variable of a [`Task`].
85#[derive(Clone, Debug, PartialEq, Eq)]
86#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
87pub struct Variable {
88    /// A name for diagnostics, e.g. `var3` from the translator; not required
89    /// to be unique.
90    pub name: String,
91    /// The number of values, `0..domain_size`. At least 1 in a valid task.
92    pub domain_size: u32,
93    /// `None` for state variables, `Some(layer)` for derived variables, which
94    /// only axioms set. Axioms of lower layers are evaluated first.
95    pub axiom_layer: Option<u32>,
96}
97
98impl Variable {
99    /// A state variable (not derived).
100    pub fn new(name: impl Into<String>, domain_size: u32) -> Self {
101        Self {
102            name: name.into(),
103            domain_size,
104            axiom_layer: None,
105        }
106    }
107
108    /// Whether the variable is derived, i.e. set only by axioms.
109    #[must_use]
110    pub fn is_derived(&self) -> bool {
111        self.axiom_layer.is_some()
112    }
113}
114
115/// An effect `fact` that fires when all `conditions` hold in the state the
116/// operator is applied in. Unconditional effects have no conditions.
117#[derive(Clone, Debug, PartialEq, Eq)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
119pub struct Effect {
120    /// Conditions on the state the operator is applied in; empty for an
121    /// unconditional effect.
122    pub conditions: Vec<Fact>,
123    /// The assignment the effect makes when it fires.
124    pub fact: Fact,
125}
126
127impl Effect {
128    /// An unconditional effect.
129    #[must_use]
130    pub fn new(fact: Fact) -> Self {
131        Self {
132            conditions: Vec::new(),
133            fact,
134        }
135    }
136}
137
138/// A ground action: applicable where its precondition holds, it applies its
139/// effects at a cost.
140#[derive(Clone, Debug, PartialEq, Eq)]
141#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
142pub struct Operator {
143    /// The ground action name, e.g. `pick ball1 rooma left`.
144    pub name: String,
145    /// The precondition, a partial state; at most one value per variable in a
146    /// valid task.
147    pub pre: Vec<Fact>,
148    /// Applied in order, so a later effect on the same variable wins.
149    pub eff: Vec<Effect>,
150    /// The cost of applying the operator, the label cost of its transitions.
151    pub cost: u32,
152}
153
154/// A rule `conditions → head` that sets the derived variable `head.var`.
155#[derive(Clone, Debug, PartialEq, Eq)]
156#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
157pub struct Axiom {
158    /// The facts that must all hold for the rule to fire.
159    pub conditions: Vec<Fact>,
160    /// The derived fact the rule sets; `head.var` is a derived variable.
161    pub head: Fact,
162}
163
164/// A complete assignment: `state.0[var]` is the value of `var`.
165#[derive(Clone, Debug, PartialEq, Eq, Hash)]
166#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
167pub struct State(pub Vec<Value>);
168
169/// A SAS+ planning task with Fast Downward's extensions: conditional effects
170/// and axioms (derived variables).
171///
172/// The fields are public and unchecked; [`Task::validate`] checks that they
173/// are consistent.
174#[derive(Clone, Debug, PartialEq, Eq)]
175#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
176pub struct Task {
177    /// The variables, indexed by [`VarId`].
178    pub variables: Vec<Variable>,
179    /// The operators, indexed by [`OpId`].
180    pub operators: Vec<Operator>,
181    /// As in Fast Downward, the values of derived variables here are their
182    /// defaults, which hold unless an axiom derives otherwise. Use
183    /// [`Task::initial_state`] for the state with axioms evaluated.
184    pub initial: State,
185    /// The goal, a partial state.
186    pub goal: Vec<Fact>,
187    /// The axiom rules that compute the derived variables.
188    pub axioms: Vec<Axiom>,
189}
190
191/// Why [`Task::validate`] rejected a task.
192#[derive(Debug, Clone, PartialEq, Eq)]
193#[non_exhaustive]
194pub enum TaskError {
195    /// The initial state does not have one value per variable.
196    InitialStateArity,
197    /// A fact assigns a value outside its variable's domain.
198    ValueOutOfRange {
199        /// The offending fact.
200        fact: Fact,
201    },
202    /// A fact names a variable the task does not have.
203    UnknownVariable {
204        /// The offending fact.
205        fact: Fact,
206    },
207    /// An operator has two unconditional effects on one variable.
208    DuplicateEffect {
209        /// The operator.
210        op: OpId,
211        /// The variable it sets twice.
212        var: VarId,
213    },
214    /// An operator requires two values of one variable.
215    ContradictoryPrecondition {
216        /// The operator.
217        op: OpId,
218        /// The variable with two required values.
219        var: VarId,
220    },
221    /// The goal requires two values of one variable.
222    ContradictoryGoal {
223        /// The variable with two required values.
224        var: VarId,
225    },
226    /// An operator sets a derived variable.
227    DerivedVariableEffect {
228        /// The operator.
229        op: OpId,
230        /// The derived variable it sets.
231        var: VarId,
232    },
233    /// An axiom sets a state variable.
234    AxiomHeadNotDerived {
235        /// Index of the axiom in [`Task::axioms`].
236        axiom: usize,
237    },
238    /// An axiom depends on a derived variable of a higher layer, or on one of
239    /// its own layer being at its default (negation needs a lower layer).
240    AxiomLayer {
241        /// Index of the axiom in [`Task::axioms`].
242        axiom: usize,
243    },
244}
245
246impl fmt::Display for TaskError {
247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
248        match self {
249            Self::InitialStateArity => write!(f, "initial state has the wrong number of variables"),
250            Self::ValueOutOfRange { fact } => write!(f, "value out of range in {fact:?}"),
251            Self::UnknownVariable { fact } => write!(f, "unknown variable in {fact:?}"),
252            Self::DuplicateEffect { op, var } => {
253                write!(f, "operator {op} has two effects on variable {var}")
254            }
255            Self::ContradictoryPrecondition { op, var } => {
256                write!(f, "operator {op} requires two values of variable {var}")
257            }
258            Self::ContradictoryGoal { var } => {
259                write!(f, "the goal requires two values of variable {var}")
260            }
261            Self::DerivedVariableEffect { op, var } => {
262                write!(f, "operator {op} sets derived variable {var}")
263            }
264            Self::AxiomHeadNotDerived { axiom } => {
265                write!(f, "axiom {axiom} sets a state variable")
266            }
267            Self::AxiomLayer { axiom } => {
268                write!(
269                    f,
270                    "axiom {axiom} depends on a higher axiom layer or negates its own layer"
271                )
272            }
273        }
274    }
275}
276
277impl core::error::Error for TaskError {}
278
279/// Something that maps concrete states onto an abstract transition system
280/// whose labels are operator ids. Goal distances in the abstract system are
281/// admissible estimates for the concrete task.
282pub trait Abstraction {
283    /// The abstract transition system; its labels are the task's [`OpId`]s.
284    fn lts(&self) -> &LabeledTransitionSystem;
285    /// `None` means the state was pruned (provably a dead end or unreachable).
286    fn abstract_state(&self, state: &State) -> Option<usize>;
287}
288
289impl<A: Abstraction + ?Sized> Abstraction for &A {
290    fn lts(&self) -> &LabeledTransitionSystem {
291        (**self).lts()
292    }
293
294    fn abstract_state(&self, state: &State) -> Option<usize> {
295        (**self).abstract_state(state)
296    }
297}
298
299impl Task {
300    /// Checks that the task is consistent, so the other methods can index
301    /// it without panicking.
302    ///
303    /// # Errors
304    ///
305    /// Returns the first problem found, checking the initial state, the goal,
306    /// the operators and then the axioms, in order:
307    ///
308    /// - [`TaskError::InitialStateArity`] if `initial` has the wrong length;
309    /// - [`TaskError::UnknownVariable`] or [`TaskError::ValueOutOfRange`] for
310    ///   a fact outside the variables or their domains;
311    /// - [`TaskError::ContradictoryGoal`] and
312    ///   [`TaskError::ContradictoryPrecondition`] for two required values of
313    ///   one variable;
314    /// - [`TaskError::DerivedVariableEffect`] for an operator that sets a
315    ///   derived variable, and [`TaskError::DuplicateEffect`] for two
316    ///   unconditional effects on one variable;
317    /// - [`TaskError::AxiomHeadNotDerived`] and [`TaskError::AxiomLayer`] for
318    ///   axioms that break the layering.
319    pub fn validate(&self) -> Result<(), TaskError> {
320        if self.initial.0.len() != self.variables.len() {
321            return Err(TaskError::InitialStateArity);
322        }
323
324        for (var, &value) in self.initial.0.iter().enumerate() {
325            self.check_fact(&Fact::new(var, value))?;
326        }
327
328        self.goal.iter().try_for_each(|f| self.check_fact(f))?;
329        if let Some(var) = contradiction(&self.goal) {
330            return Err(TaskError::ContradictoryGoal { var });
331        }
332
333        for (id, op) in self.operators.iter().enumerate() {
334            self.validate_operator(id, op)?;
335        }
336
337        for (id, axiom) in self.axioms.iter().enumerate() {
338            self.validate_axiom(id, axiom)?;
339        }
340
341        Ok(())
342    }
343
344    /// Checks that `fact` names an existing variable and a value in its domain.
345    fn check_fact(&self, fact: &Fact) -> Result<(), TaskError> {
346        let var = self
347            .variables
348            .get(fact.var)
349            .ok_or(TaskError::UnknownVariable { fact: *fact })?;
350        if fact.value >= var.domain_size {
351            return Err(TaskError::ValueOutOfRange { fact: *fact });
352        }
353
354        Ok(())
355    }
356
357    /// The operator part of [`Task::validate`], for operator `id`.
358    fn validate_operator(&self, id: OpId, op: &Operator) -> Result<(), TaskError> {
359        op.pre.iter().try_for_each(|f| self.check_fact(f))?;
360        if let Some(var) = contradiction(&op.pre) {
361            return Err(TaskError::ContradictoryPrecondition { op: id, var });
362        }
363
364        for e in &op.eff {
365            e.conditions.iter().try_for_each(|f| self.check_fact(f))?;
366            self.check_fact(&e.fact)?;
367            if self.variables[e.fact.var].is_derived() {
368                return Err(TaskError::DerivedVariableEffect {
369                    op: id,
370                    var: e.fact.var,
371                });
372            }
373        }
374
375        // Conditional effects on one variable may coexist; the last firing one wins.
376        let mut vars: Vec<_> = op
377            .eff
378            .iter()
379            .filter(|e| e.conditions.is_empty())
380            .map(|e| e.fact.var)
381            .collect();
382        vars.sort_unstable();
383        if let Some(w) = vars.windows(2).find(|w| w[0] == w[1]) {
384            return Err(TaskError::DuplicateEffect { op: id, var: w[0] });
385        }
386
387        Ok(())
388    }
389
390    /// The axiom part of [`Task::validate`], for axiom `id`.
391    fn validate_axiom(&self, id: usize, axiom: &Axiom) -> Result<(), TaskError> {
392        axiom
393            .conditions
394            .iter()
395            .try_for_each(|f| self.check_fact(f))?;
396        self.check_fact(&axiom.head)?;
397        let Some(layer) = self.variables[axiom.head.var].axiom_layer else {
398            return Err(TaskError::AxiomHeadNotDerived { axiom: id });
399        };
400
401        if axiom.conditions.iter().any(|c| {
402            self.variables[c.var]
403                .axiom_layer
404                .is_some_and(|l| l > layer || (l == layer && c.value == self.initial.0[c.var]))
405        }) {
406            return Err(TaskError::AxiomLayer { axiom: id });
407        }
408
409        Ok(())
410    }
411
412    /// The number of variables, state and derived.
413    #[must_use]
414    pub fn num_variables(&self) -> usize {
415        self.variables.len()
416    }
417
418    /// Whether operator `op`'s precondition holds in `state`.
419    ///
420    /// # Panics
421    ///
422    /// If `op` is not an operator of the task, or `state` lacks a variable
423    /// the precondition mentions.
424    #[must_use]
425    pub fn is_applicable(&self, op: OpId, state: &State) -> bool {
426        holds(&self.operators[op].pre, state)
427    }
428
429    /// The successor state. Effect conditions are evaluated in `state`;
430    /// derived variables are then re-evaluated.
431    ///
432    /// Like [`Task::is_applicable`] and [`Task::is_goal`], this reads derived
433    /// variables from `state` as given, so `state` must have them evaluated:
434    /// start from [`Task::initial_state`] (not [`Task::initial`]) or call
435    /// [`Task::evaluate_axioms`] first. States returned by `apply` are.
436    ///
437    /// # Panics
438    ///
439    /// If `op` is not an operator of the task, or `state` has fewer values
440    /// than the task has variables.
441    #[must_use]
442    pub fn apply(&self, op: OpId, state: &State) -> State {
443        let mut next = state.clone();
444        for e in &self.operators[op].eff {
445            if holds(&e.conditions, state) {
446                next.0[e.fact.var] = e.fact.value;
447            }
448        }
449
450        self.evaluate_axioms(&mut next);
451        next
452    }
453
454    /// Recomputes all derived variables of `state` from its state variables:
455    /// each derived variable is reset to its default (its value in
456    /// [`Task::initial`]), then the axioms fire layer by layer until nothing
457    /// changes, as in Fast Downward. A variable keeps the first non-default
458    /// value derived for it.
459    ///
460    /// This allocates nothing but rescans the rules of a layer until none
461    /// fires; search code that needs speed on axiom-heavy tasks should index
462    /// the rules itself.
463    ///
464    /// # Panics
465    ///
466    /// If `state` has fewer values than the task has variables.
467    pub fn evaluate_axioms(&self, state: &mut State) {
468        // Reset first: a derived variable without rules still holds its default.
469        for (var, v) in self.variables.iter().enumerate() {
470            if v.is_derived() {
471                state.0[var] = self.initial.0[var];
472            }
473        }
474
475        if self.axioms.is_empty() {
476            return;
477        }
478
479        let mut done: Option<u32> = None;
480        // Layers in ascending order, without collecting them.
481        while let Some(layer) = self
482            .variables
483            .iter()
484            .filter_map(|v| v.axiom_layer)
485            .filter(|&l| done.is_none_or(|d| l > d))
486            .min()
487        {
488            done = Some(layer);
489            while self.fire_layer(layer, state) {}
490        }
491    }
492
493    /// One pass over the rules of axiom layer `layer`, setting the head of
494    /// each rule that fires. Returns whether any variable changed.
495    fn fire_layer(&self, layer: u32, state: &mut State) -> bool {
496        let mut changed = false;
497        for a in &self.axioms {
498            if self.variables[a.head.var].axiom_layer != Some(layer) {
499                continue;
500            }
501
502            // Only a variable still at its default is derived, so the fixpoint is reached.
503            let default = self.initial.0[a.head.var];
504            if state.0[a.head.var] == default
505                && a.head.value != default
506                && holds(&a.conditions, state)
507            {
508                state.0[a.head.var] = a.head.value;
509                changed = true;
510            }
511        }
512
513        changed
514    }
515
516    /// The initial state with derived variables evaluated.
517    #[must_use]
518    pub fn initial_state(&self) -> State {
519        let mut state = self.initial.clone();
520        self.evaluate_axioms(&mut state);
521        state
522    }
523
524    /// The operators applicable in `state`, in id order.
525    pub fn applicable_operators<'a>(&'a self, state: &'a State) -> impl Iterator<Item = OpId> + 'a {
526        (0..self.operators.len()).filter(move |&op| self.is_applicable(op, state))
527    }
528
529    /// Whether the goal holds in `state`.
530    ///
531    /// # Panics
532    ///
533    /// If `state` lacks a variable the goal mentions.
534    #[must_use]
535    pub fn is_goal(&self, state: &State) -> bool {
536        holds(&self.goal, state)
537    }
538
539    /// Operator costs indexed by operator id (the label cost function).
540    #[must_use]
541    pub fn costs(&self) -> Vec<u64> {
542        self.operators.iter().map(|o| u64::from(o.cost)).collect()
543    }
544
545    /// Checks that `plan` is applicable from the initial state and reaches the goal.
546    /// Returns the plan cost, or `None` if an operator is not applicable where
547    /// the plan uses it or the plan does not end in a goal state.
548    ///
549    /// # Panics
550    ///
551    /// If `plan` names an operator the task does not have.
552    #[must_use]
553    pub fn validate_plan(&self, plan: &[OpId]) -> Option<u64> {
554        let mut state = self.initial_state();
555        let mut cost = 0;
556        for &op in plan {
557            if !self.is_applicable(op, &state) {
558                return None;
559            }
560            state = self.apply(op, &state);
561            cost += u64::from(self.operators[op].cost);
562        }
563
564        self.is_goal(&state).then_some(cost)
565    }
566
567    /// Optimal plan cost from `state` (with derived variables evaluated),
568    /// by building the full state space over all state variables.
569    /// Exponential; intended for tests on tiny tasks.
570    ///
571    /// The returned function gives `None` for states from which no goal is
572    /// reachable.
573    ///
574    /// # Panics
575    ///
576    /// If the state space over the state variables has more than
577    /// `usize::MAX` states. The returned function panics on states with
578    /// fewer values than the task has variables.
579    pub fn perfect_heuristic(&self) -> impl Fn(&State) -> Option<u64> + '_ {
580        let vars = (0..self.num_variables())
581            .filter(|&v| !self.variables[v].is_derived())
582            .collect();
583        let ranking = ranking::Ranking::new(self, vars);
584        let mut state = self.initial.clone();
585        let mut transitions = Vec::new();
586        for (label, op) in self.operators.iter().enumerate() {
587            // Preconditions on state variables pick the candidates; derived ones are checked after.
588            for src in ranking.matching(&op.pre) {
589                ranking.unrank(src, &mut state);
590                self.evaluate_axioms(&mut state);
591                if self.is_applicable(label, &state) {
592                    let dst = ranking.rank(&self.apply(label, &state));
593                    transitions.push(Transition { src, label, dst });
594                }
595            }
596        }
597
598        let mut goal = vec![false; ranking.num_states];
599        for index in ranking.matching(&self.goal) {
600            ranking.unrank(index, &mut state);
601            self.evaluate_axioms(&mut state);
602            goal[index] = self.is_goal(&state);
603        }
604
605        let lts = LabeledTransitionSystem {
606            num_states: ranking.num_states,
607            num_labels: self.operators.len(),
608            transitions,
609            goal,
610            initial: Some(ranking.rank(&self.initial)),
611        };
612        let h = lts.goal_distances(&self.costs());
613        move |s| h[ranking.rank(s)]
614    }
615}
616
617/// A variable that `facts` assign two different values, if any.
618fn contradiction(facts: &[Fact]) -> Option<VarId> {
619    let mut sorted = facts.to_vec();
620    sorted.sort_unstable();
621    sorted.dedup();
622    sorted
623        .windows(2)
624        .find(|w| w[0].var == w[1].var)
625        .map(|w| w[0].var)
626}
627
628/// Whether all `facts` hold in `state`.
629fn holds(facts: &[Fact], state: &State) -> bool {
630    facts.iter().all(|f| state.0[f.var] == f.value)
631}