Skip to main content

heuristic_search/
outcome.rs

1//! What a search returns: [`SearchResult`] with an [`Outcome`] and [`Stats`], and the
2//! [`Limits`], the counter [`Budget`] that stops it early.
3
4use alloc::vec::Vec;
5
6use search_core::Budget;
7
8/// Counters collected during one search run.
9///
10/// Non-exhaustive: later algorithms may add counters. Start from [`Stats::default`] where
11/// a value is needed.
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct Stats {
15    /// States whose successors were generated. A goal state that ends the search is not
16    /// counted. A state reopened through a cheaper path counts once per expansion.
17    pub expanded: u64,
18    /// Edges reported by [`Successors::successors`](crate::Successors::successors), whether
19    /// or not their target was new.
20    pub generated: u64,
21    /// Closed states reopened because a cheaper path to them turned up. Always `0` for
22    /// breadth-first and greedy best-first search, and for A* with a consistent heuristic.
23    pub reopened: u64,
24    /// True edge costs computed by an expensive edge evaluator. Only
25    /// [`lazy_sp`](crate::lazy_sp) evaluates edges; `0` everywhere else.
26    pub evaluations: u64,
27}
28
29impl Stats {
30    /// The counters of `self` and `other` added up, for searches made of several runs.
31    #[must_use]
32    pub(crate) fn plus(self, other: Self) -> Self {
33        Self {
34            expanded: self.expanded + other.expanded,
35            generated: self.generated + other.generated,
36            reopened: self.reopened + other.reopened,
37            evaluations: self.evaluations + other.evaluations,
38        }
39    }
40
41    /// The counters of `self` beyond `earlier`, an earlier reading of the same counters.
42    #[cfg(feature = "parallel")]
43    #[must_use]
44    pub(crate) fn since(self, earlier: Self) -> Self {
45        Self {
46            expanded: self.expanded - earlier.expanded,
47            generated: self.generated - earlier.generated,
48            reopened: self.reopened - earlier.reopened,
49            evaluations: self.evaluations - earlier.evaluations,
50        }
51    }
52}
53
54/// A path from the start state to a goal state.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Solution<S, A, C> {
57    /// The states along the path, from the start to the goal. Never empty: a start state that
58    /// already is a goal yields a single state.
59    pub states: Vec<S>,
60    /// The edge labels along the path; `actions[i]` leads from `states[i]` to
61    /// `states[i + 1]`. Always one shorter than [`Solution::states`].
62    pub actions: Vec<A>,
63    /// The sum of the edge costs along the path.
64    pub cost: C,
65}
66
67impl<S, A, C> Solution<S, A, C> {
68    /// The number of edges on the path.
69    #[must_use]
70    pub fn len(&self) -> usize {
71        self.actions.len()
72    }
73
74    /// Returns `true` if the start state is the goal, so the path has no edges.
75    #[must_use]
76    pub fn is_empty(&self) -> bool {
77        self.actions.is_empty()
78    }
79
80    /// The goal state the path ends in.
81    ///
82    /// # Panics
83    ///
84    /// Never panics for solutions returned by a search, whose [`Solution::states`] is never
85    /// empty.
86    #[must_use]
87    pub fn goal(&self) -> &S {
88        self.states
89            .last()
90            .expect("a solution has at least one state")
91    }
92}
93
94/// How a search ended.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum Outcome<S, A, C> {
97    /// A path to a goal was found.
98    Found(Solution<S, A, C>),
99    /// The search space was exhausted without reaching a goal, so no goal is reachable
100    /// (given a heuristic whose dead ends are real).
101    Unsolvable,
102    /// The [`Budget`] stopped the search before it could decide.
103    LimitReached,
104    /// A search with its own bound cut states off and found no goal within the bound: the
105    /// depth limit of [`depth_limited_dfs`](crate::depth_limited_dfs), the beam width of
106    /// [`beam_search`](crate::beam_search), or the memory of
107    /// [`sma_star`](crate::sma_star). A goal may lie beyond it; a larger bound may find it.
108    Cutoff,
109}
110
111/// The result of one search run.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct SearchResult<S, A, C> {
114    /// How the search ended.
115    pub outcome: Outcome<S, A, C>,
116    /// Counters collected until the search ended.
117    pub stats: Stats,
118}
119
120impl<S, A, C> SearchResult<S, A, C> {
121    /// The solution, if one was found.
122    #[must_use]
123    pub fn solution(&self) -> Option<&Solution<S, A, C>> {
124        match &self.outcome {
125            Outcome::Found(solution) => Some(solution),
126            Outcome::Unsolvable | Outcome::LimitReached | Outcome::Cutoff => None,
127        }
128    }
129
130    /// Consumes the result and returns the solution, if one was found.
131    #[must_use]
132    pub fn into_solution(self) -> Option<Solution<S, A, C>> {
133        match self.outcome {
134            Outcome::Found(solution) => Some(solution),
135            Outcome::Unsolvable | Outcome::LimitReached | Outcome::Cutoff => None,
136        }
137    }
138}
139
140/// Simple counter limits. The default is unlimited.
141#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
142pub struct Limits {
143    /// Stop once this many states have been expanded. `None` is unbounded.
144    pub max_expansions: Option<u64>,
145}
146
147impl Limits {
148    /// No limits: the search runs until it finds a goal or exhausts the space.
149    pub const NONE: Self = Self {
150        max_expansions: None,
151    };
152
153    /// Stops after `max` expansions.
154    #[must_use]
155    pub const fn expansions(max: u64) -> Self {
156        Self {
157            max_expansions: Some(max),
158        }
159    }
160}
161
162/// Asked before every expansion, with the counters so far, so a search stopped by
163/// [`Limits::max_expansions`] `= n` has expanded exactly `n` states. Closures
164/// `FnMut(&Stats) -> bool` are budgets too, which lets callers with a clock (this crate is
165/// `no_std`) add a time limit; annotate the argument (`|stats: &Stats| ...`).
166impl Budget<Stats> for Limits {
167    fn exhausted(&mut self, stats: &Stats) -> bool {
168        self.max_expansions.is_some_and(|max| stats.expanded >= max)
169    }
170}