Skip to main content

stochastic_search/
error.rs

1//! Errors for invalid input ([`Error`]).
2
3use core::fmt;
4
5/// The tolerance on the sum of an action's outcome probabilities.
6///
7/// The probabilities emitted by [`Mdp::outcomes`](crate::Mdp::outcomes) must sum to 1 within
8/// this absolute tolerance. Wide enough for decimal probabilities such as `0.1` summed in
9/// binary floating point, narrow enough to catch a missing outcome.
10pub const PROBABILITY_TOLERANCE: f64 = 1e-9;
11
12/// Invalid input found while solving. Each variant names the state where it was found.
13///
14/// Implements [`core::error::Error`] when the state is [`fmt::Debug`]. The enum is
15/// `#[non_exhaustive]`: new kinds of invalid input can be added without a breaking change,
16/// so a `match` outside this crate needs a wildcard arm.
17#[non_exhaustive]
18#[derive(Debug, Clone, PartialEq)]
19pub enum Error<S> {
20    /// An action cost is negative, NaN or infinite.
21    InvalidCost {
22        /// The state whose action has the cost.
23        state: S,
24        /// The offending cost.
25        cost: f64,
26    },
27    /// An outcome probability is NaN or outside `(0, 1]`.
28    InvalidProbability {
29        /// The state whose action has the outcome.
30        state: S,
31        /// The offending probability.
32        probability: f64,
33    },
34    /// The outcome probabilities of an action do not sum to 1 within
35    /// [`PROBABILITY_TOLERANCE`]. An action without outcomes sums to 0.
36    ProbabilitySum {
37        /// The state whose action has the outcomes.
38        state: S,
39        /// The sum of the outcome probabilities.
40        sum: f64,
41    },
42    /// The heuristic estimated NaN or negative infinity, a POMDP upper bound (see
43    /// [`despot`](crate::despot())) is NaN, or a [`brtdp`](crate::brtdp()) upper estimate is
44    /// NaN, negative infinity or below the lower estimate of the same state.
45    InvalidHeuristic {
46        /// The state that was estimated.
47        state: S,
48    },
49    /// Under [`DeadEnds::Infinite`](crate::DeadEnds::Infinite), the upper bound of
50    /// [`brtdp`](crate::brtdp()) estimated no finite value (`None` or infinity) for a state
51    /// the lower bound does not prove to be a dead end.
52    ///
53    /// The bounded algorithms need a finite upper bound wherever the optimal value is finite: an infinite
54    /// one on a cycle never becomes finite through backups. Give a finite upper estimate,
55    /// return `None` from the lower bound too where the state is a dead end, or use
56    /// [`DeadEnds::Penalty`](crate::DeadEnds::Penalty), whose penalty bounds every value.
57    UnboundedUpper {
58        /// The state that was estimated.
59        state: S,
60    },
61    /// A [`Pomdp::step`](crate::Pomdp::step) returned a NaN or infinite reward.
62    InvalidReward {
63        /// The state the step started from.
64        state: S,
65        /// The offending reward.
66        reward: f64,
67    },
68    /// A [`Pomdp`](crate::Pomdp) emitted no actions.
69    NoActions,
70    /// A POMDP planner was given a belief without particles.
71    EmptyBelief,
72    /// [`Despot::advance`](crate::Despot::advance) met an action and observation the tree
73    /// never produced; the planner needs [`Despot::reset`](crate::Despot::reset).
74    UnseenHistory,
75    /// [`update_belief`](crate::update_belief()) accepted no particle: the observation is
76    /// impossible under the belief, or too rare for the attempt budget.
77    BeliefDepleted {
78        /// The steps simulated before giving up.
79        attempts: usize,
80    },
81    /// A configuration setting is out of range.
82    InvalidConfig {
83        /// Which setting, and the valid range.
84        reason: &'static str,
85    },
86}
87
88impl<S: fmt::Debug> fmt::Display for Error<S> {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        match self {
91            Self::InvalidCost { state, cost } => {
92                write!(f, "invalid action cost {cost} in state {state:?}")
93            }
94            Self::InvalidProbability { state, probability } => {
95                write!(
96                    f,
97                    "invalid outcome probability {probability} in state {state:?}"
98                )
99            }
100            Self::ProbabilitySum { state, sum } => {
101                write!(
102                    f,
103                    "outcome probabilities sum to {sum}, not 1, in state {state:?}"
104                )
105            }
106            Self::InvalidHeuristic { state } => {
107                write!(
108                    f,
109                    "the heuristic or bound estimated an invalid value for state {state:?}"
110                )
111            }
112            Self::UnboundedUpper { state } => {
113                write!(
114                    f,
115                    "no finite upper bound for state {state:?}, which is not a known dead end"
116                )
117            }
118            Self::InvalidReward { state, reward } => {
119                write!(f, "invalid reward {reward} from state {state:?}")
120            }
121            Self::NoActions => f.write_str("the POMDP has no actions"),
122            Self::EmptyBelief => f.write_str("the belief has no particles"),
123            Self::UnseenHistory => {
124                f.write_str("the planner's tree has no node for this action and observation")
125            }
126            Self::BeliefDepleted { attempts } => write!(
127                f,
128                "no particle matched the observation in {attempts} attempts"
129            ),
130            Self::InvalidConfig { reason } => write!(f, "invalid configuration: {reason}"),
131        }
132    }
133}
134
135impl<S: fmt::Debug> core::error::Error for Error<S> {}