Skip to main content

decoupled_search/
plan.rs

1//! Sequential plans for the original task and their validation.
2
3use alloc::vec::Vec;
4use core::fmt;
5
6use sas_plus::{OpId, Task, TaskError};
7
8/// A sequential plan for the original task.
9#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct Plan {
11    /// Operators in execution order, applicable from the initial state.
12    pub ops: Vec<OpId>,
13    /// Sum of the operator costs.
14    pub cost: u64,
15}
16
17/// Why [`Plan::validate`] rejected a plan.
18#[derive(Clone, Debug, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum PlanError {
21    /// The task failed [`Task::validate`], so plans for it cannot be checked.
22    InvalidTask(TaskError),
23    /// Step `step` names operator `op`, which the task does not have.
24    UnknownOperator {
25        /// Index of the offending step in [`Plan::ops`].
26        step: usize,
27        /// The operator id it names.
28        op: OpId,
29    },
30    /// The preconditions of operator `op` do not hold before step `step`.
31    NotApplicable {
32        /// Index of the offending step in [`Plan::ops`].
33        step: usize,
34        /// The operator applied at that step.
35        op: OpId,
36    },
37    /// Every step applies, but the goal does not hold at the end.
38    GoalNotReached,
39    /// The plan is valid, but its operators cost `actual`, not the
40    /// [`Plan::cost`] it claims.
41    CostMismatch {
42        /// The cost stored in [`Plan::cost`].
43        claimed: u64,
44        /// The sum of the operator costs.
45        actual: u64,
46    },
47}
48
49impl fmt::Display for PlanError {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match self {
52            Self::InvalidTask(e) => write!(f, "invalid task: {e}"),
53            Self::UnknownOperator { step, op } => {
54                write!(f, "step {step} names unknown operator {op}")
55            }
56            Self::NotApplicable { step, op } => {
57                write!(f, "operator {op} at step {step} is not applicable")
58            }
59            Self::GoalNotReached => write!(f, "the plan does not reach the goal"),
60            Self::CostMismatch { claimed, actual } => {
61                write!(f, "the plan claims cost {claimed} but costs {actual}")
62            }
63        }
64    }
65}
66
67impl core::error::Error for PlanError {
68    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
69        match self {
70            Self::InvalidTask(e) => Some(e),
71            _ => None,
72        }
73    }
74}
75
76impl Plan {
77    /// Checks the plan against `task` with explicit-state semantics,
78    /// independent of decoupled search: starting from the initial state
79    /// with derived variables evaluated, every operator must be applicable,
80    /// conditional effects fire on the state before the operator, derived
81    /// variables are re-evaluated after it, the goal must hold at the end,
82    /// and [`Plan::cost`] must be the sum of the operator costs.
83    ///
84    /// # Errors
85    ///
86    /// - [`PlanError::InvalidTask`] if `task` fails [`Task::validate`].
87    /// - [`PlanError::UnknownOperator`] for the first step naming an
88    ///   operator the task lacks.
89    /// - [`PlanError::NotApplicable`] for the first step whose operator is
90    ///   not applicable.
91    /// - [`PlanError::GoalNotReached`] if the final state misses the goal.
92    /// - [`PlanError::CostMismatch`] if the plan is valid but
93    ///   [`Plan::cost`] is wrong.
94    ///
95    /// # Examples
96    ///
97    /// ```
98    /// use decoupled_search::{Plan, PlanError};
99    /// use sas_plus::{Effect, Fact, Operator, State, Task, Variable};
100    ///
101    /// let task = Task {
102    ///     variables: vec![Variable::new("x", 2)],
103    ///     operators: vec![Operator {
104    ///         name: "set".into(),
105    ///         pre: vec![Fact::new(0, 0)],
106    ///         eff: vec![Effect::new(Fact::new(0, 1))],
107    ///         cost: 3,
108    ///     }],
109    ///     initial: State(vec![0]),
110    ///     goal: vec![Fact::new(0, 1)],
111    ///     axioms: vec![],
112    /// };
113    ///
114    /// assert_eq!(Plan { ops: vec![0], cost: 3 }.validate(&task), Ok(()));
115    /// assert_eq!(
116    ///     Plan { ops: vec![0, 0], cost: 6 }.validate(&task),
117    ///     Err(PlanError::NotApplicable { step: 1, op: 0 })
118    /// );
119    /// assert_eq!(
120    ///     Plan { ops: vec![], cost: 0 }.validate(&task),
121    ///     Err(PlanError::GoalNotReached)
122    /// );
123    /// ```
124    pub fn validate(&self, task: &Task) -> Result<(), PlanError> {
125        task.validate().map_err(PlanError::InvalidTask)?;
126
127        let mut state = task.initial_state();
128        let mut actual = 0_u64;
129        for (step, &op) in self.ops.iter().enumerate() {
130            let Some(operator) = task.operators.get(op) else {
131                return Err(PlanError::UnknownOperator { step, op });
132            };
133
134            if !task.is_applicable(op, &state) {
135                return Err(PlanError::NotApplicable { step, op });
136            }
137
138            state = task.apply(op, &state);
139            actual = actual.saturating_add(u64::from(operator.cost));
140        }
141
142        if !task.is_goal(&state) {
143            return Err(PlanError::GoalNotReached);
144        }
145
146        if actual != self.cost {
147            return Err(PlanError::CostMismatch {
148                claimed: self.cost,
149                actual,
150            });
151        }
152
153        Ok(())
154    }
155}