stochastic_search/solution.rs
1//! The result of a run: a value function and a greedy policy ([`Solution`]).
2
3use core::fmt;
4use core::hash::Hash;
5
6use alloc::vec::Vec;
7
8use crate::budget::Stats;
9use crate::error::Error;
10use crate::model::Mdp;
11use crate::space::{Id, Space};
12
13/// The result of solving the MDP `M`: a [`Solution`] or the [`Error`] that stopped the run.
14pub type SolveResult<M> =
15 Result<Solution<<M as Mdp>::State, <M as Mdp>::Action>, Error<<M as Mdp>::State>>;
16
17/// How a run ended.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum Status {
20 /// The convergence criterion holds: for LRTDP, RTDP, LAO* and iLAO*, the initial state is
21 /// labeled solved by the solved check; for value iteration, the last sweep's largest
22 /// residual was below epsilon; for BRTDP, FRTDP and VPI-RTDP, the initial state's bounds are at most
23 /// epsilon
24 /// apart.
25 Converged,
26 /// The [`Budget`](crate::Budget) stopped the run first. Values and policy are the ones
27 /// reached so far and carry no guarantee, except that the bounds of BRTDP, FRTDP and VPI-RTDP still bracket the
28 /// optimal values.
29 BudgetExhausted,
30 /// Proven: no policy reaches a goal with probability 1 from the initial state, so under
31 /// [`DeadEnds::Infinite`](crate::DeadEnds::Infinite) its value is infinite and it has no
32 /// policy action. Never returned under a finite penalty, where giving up is always
33 /// possible.
34 Unsolvable,
35}
36
37/// A value function and a greedy policy over the states a run touched.
38///
39/// See `docs/design.md`, section "Convergence criterion", for what a converged solution
40/// guarantees.
41pub struct Solution<S, A> {
42 /// The states, values and policy actions.
43 space: Space<S, A>,
44 /// The id of the initial state.
45 initial: Id,
46 /// How the run ended.
47 status: Status,
48 /// Counters of the run.
49 stats: Stats,
50 /// The upper bounds of BRTDP, FRTDP and VPI-RTDP, indexed by [`Id`]; empty for the other
51 /// algorithms.
52 upper: Vec<f64>,
53}
54
55impl<S, A> Solution<S, A> {
56 /// Wraps the state space of a finished run.
57 ///
58 /// A run whose initial value is infinite becomes [`Status::Unsolvable`], even if the
59 /// budget ran out: infinity only enters values through proven dead ends (states without
60 /// actions, heuristic dead ends, the dead-end proof) and spreads only through backups,
61 /// where it means every action risks a proven dead end.
62 pub(crate) fn new(space: Space<S, A>, initial: Id, status: Status, counters: Stats) -> Self {
63 let status = if space.node(initial).value.is_infinite() {
64 Status::Unsolvable
65 } else {
66 status
67 };
68
69 Self {
70 space,
71 initial,
72 status,
73 stats: counters,
74 upper: Vec::new(),
75 }
76 }
77
78 /// Attaches the upper bounds of a bounded run, one per stored state, indexed by [`Id`].
79 pub(crate) fn with_upper(mut self, upper: Vec<f64>) -> Self {
80 debug_assert_eq!(upper.len(), self.space.len(), "one upper bound per state");
81 self.upper = upper;
82
83 self
84 }
85
86 /// How the run ended.
87 #[must_use]
88 pub fn status(&self) -> Status {
89 self.status
90 }
91
92 /// Returns `true` if the run met its convergence criterion with a finite initial value.
93 #[must_use]
94 pub fn is_converged(&self) -> bool {
95 self.status == Status::Converged
96 }
97
98 /// Counters of the run.
99 #[must_use]
100 pub fn stats(&self) -> &Stats {
101 &self.stats
102 }
103
104 /// The initial state.
105 #[must_use]
106 pub fn initial_state(&self) -> &S {
107 self.space.state(self.initial)
108 }
109
110 /// The value of the initial state: the expected cost to reach a goal.
111 ///
112 /// Infinite exactly when the status is [`Status::Unsolvable`] (which relies on the
113 /// heuristic returning `None` only for real dead ends).
114 #[must_use]
115 pub fn initial_value(&self) -> f64 {
116 self.space.node(self.initial).value
117 }
118
119 /// The upper bound on the initial state's optimal value, for [`brtdp`](crate::brtdp());
120 /// `None` for the other algorithms, which keep no upper bound.
121 #[must_use]
122 pub fn initial_upper_bound(&self) -> Option<f64> {
123 self.upper.get(self.initial as usize).copied()
124 }
125
126 /// The policy's action in the initial state; see [`Solution::action`].
127 #[must_use]
128 pub fn initial_action(&self) -> Option<&A> {
129 self.policy_of(self.initial)
130 }
131
132 /// The policy action stored for `id`.
133 fn policy_of(&self, id: Id) -> Option<&A> {
134 let index = self.space.node(id).policy?;
135
136 Some(&self.space.action(index).action)
137 }
138}
139
140impl<S: Hash + Eq, A> Solution<S, A> {
141 /// The value of `state`, or `None` if the run never touched it.
142 ///
143 /// For LRTDP, RTDP, LAO* and iLAO*, values outside the policy's reachable states are only
144 /// bounds (lower bounds with an admissible heuristic), not converged values. For the bounded algorithms this is the lower
145 /// bound; see [`Solution::upper_bound`].
146 #[must_use]
147 pub fn value(&self, state: &S) -> Option<f64> {
148 self.space.find(state).map(|id| self.space.node(id).value)
149 }
150
151 /// The upper bound on the optimal value of `state`, for [`brtdp`](crate::brtdp()).
152 ///
153 /// `None` if the run never touched `state`, and always for the other algorithms. With
154 /// [`Solution::value`] as the lower bound, the bounded algorithms bracket the optimal value of every
155 /// stored state; see [`brtdp`](crate::brtdp()), section "Guarantee".
156 #[must_use]
157 pub fn upper_bound(&self, state: &S) -> Option<f64> {
158 self.space
159 .find(state)
160 .and_then(|id| self.upper.get(id as usize).copied())
161 }
162
163 /// The policy's action in `state`.
164 ///
165 /// `None` at goals, dead ends, states where giving up is cheaper (under
166 /// [`DeadEnds::Penalty`](crate::DeadEnds::Penalty)) and states the run never backed up.
167 /// Every state reachable from the initial state under the policy of a converged run has
168 /// an action unless it is one of the first three. The policy of BRTDP, FRTDP and VPI-RTDP
169 /// is greedy on the upper bound; their fill pass gives a converged run the same
170 /// coverage (see [`brtdp`](crate::brtdp())).
171 #[must_use]
172 pub fn action(&self, state: &S) -> Option<&A> {
173 self.space.find(state).and_then(|id| self.policy_of(id))
174 }
175}
176
177impl<S: fmt::Debug, A> fmt::Debug for Solution<S, A> {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.debug_struct("Solution")
180 .field("initial_state", self.initial_state())
181 .field("initial_value", &self.initial_value())
182 .field("status", &self.status)
183 .field("stats", &self.stats)
184 .finish_non_exhaustive()
185 }
186}