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
42/// A path from the start state to a goal state.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct Solution<S, A, C> {
45    /// The states along the path, from the start to the goal. Never empty: a start state that
46    /// already is a goal yields a single state.
47    pub states: Vec<S>,
48    /// The edge labels along the path; `actions[i]` leads from `states[i]` to
49    /// `states[i + 1]`. Always one shorter than [`Solution::states`].
50    pub actions: Vec<A>,
51    /// The sum of the edge costs along the path.
52    pub cost: C,
53}
54
55impl<S, A, C> Solution<S, A, C> {
56    /// The number of edges on the path.
57    #[must_use]
58    pub fn len(&self) -> usize {
59        self.actions.len()
60    }
61
62    /// Returns `true` if the start state is the goal, so the path has no edges.
63    #[must_use]
64    pub fn is_empty(&self) -> bool {
65        self.actions.is_empty()
66    }
67
68    /// The goal state the path ends in.
69    ///
70    /// # Panics
71    ///
72    /// Never panics for solutions returned by a search, whose [`Solution::states`] is never
73    /// empty.
74    #[must_use]
75    pub fn goal(&self) -> &S {
76        self.states
77            .last()
78            .expect("a solution has at least one state")
79    }
80}
81
82/// How a search ended.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub enum Outcome<S, A, C> {
85    /// A path to a goal was found.
86    Found(Solution<S, A, C>),
87    /// The search space was exhausted without reaching a goal, so no goal is reachable
88    /// (given a heuristic whose dead ends are real).
89    Unsolvable,
90    /// The [`Budget`] stopped the search before it could decide.
91    LimitReached,
92    /// A search with its own bound cut states off and found no goal within the bound: the
93    /// depth limit of [`depth_limited_dfs`](crate::depth_limited_dfs), the beam width of
94    /// [`beam_search`](crate::beam_search), or the memory of
95    /// [`sma_star`](crate::sma_star). A goal may lie beyond it; a larger bound may find it.
96    Cutoff,
97}
98
99/// The result of one search run.
100#[derive(Debug, Clone, PartialEq, Eq)]
101pub struct SearchResult<S, A, C> {
102    /// How the search ended.
103    pub outcome: Outcome<S, A, C>,
104    /// Counters collected until the search ended.
105    pub stats: Stats,
106}
107
108impl<S, A, C> SearchResult<S, A, C> {
109    /// The solution, if one was found.
110    #[must_use]
111    pub fn solution(&self) -> Option<&Solution<S, A, C>> {
112        match &self.outcome {
113            Outcome::Found(solution) => Some(solution),
114            Outcome::Unsolvable | Outcome::LimitReached | Outcome::Cutoff => None,
115        }
116    }
117
118    /// Consumes the result and returns the solution, if one was found.
119    #[must_use]
120    pub fn into_solution(self) -> Option<Solution<S, A, C>> {
121        match self.outcome {
122            Outcome::Found(solution) => Some(solution),
123            Outcome::Unsolvable | Outcome::LimitReached | Outcome::Cutoff => None,
124        }
125    }
126}
127
128/// Simple counter limits. The default is unlimited.
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
130pub struct Limits {
131    /// Stop once this many states have been expanded. `None` is unbounded.
132    pub max_expansions: Option<u64>,
133}
134
135impl Limits {
136    /// No limits: the search runs until it finds a goal or exhausts the space.
137    pub const NONE: Self = Self {
138        max_expansions: None,
139    };
140
141    /// Stops after `max` expansions.
142    #[must_use]
143    pub const fn expansions(max: u64) -> Self {
144        Self {
145            max_expansions: Some(max),
146        }
147    }
148}
149
150/// Asked before every expansion, with the counters so far, so a search stopped by
151/// [`Limits::max_expansions`] `= n` has expanded exactly `n` states. Closures
152/// `FnMut(&Stats) -> bool` are budgets too, which lets callers with a clock (this crate is
153/// `no_std`) add a time limit; annotate the argument (`|stats: &Stats| ...`).
154impl Budget<Stats> for Limits {
155    fn exhausted(&mut self, stats: &Stats) -> bool {
156        self.max_expansions.is_some_and(|max| stats.expanded >= max)
157    }
158}