1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! Bounded real-time dynamic programming (BRTDP, McMahan, Likhachev and Gordon 2005):
//! gap-weighted successor sampling.
use Hash;
use crate;
use crate;
use crateConfig;
use crateError;
use crate;
use crateObserver;
use crateSolveResult;
use crateId;
/// Settings of [`brtdp`]: the shared [`Config`] and BRTDP's trial-end ratio.
///
/// Build one with [`BrtdpConfig::default`], or with [`BrtdpConfig::new`] (or `into`) from a
/// [`Config`], and adjust it with [`BrtdpConfig::with_tau`].
/// Solves an SSP from `initial` with bounded RTDP, keeping a lower and an upper bound on
/// every stored state's optimal value.
///
/// `lower` estimates the lower bound of a new state as the heuristic of
/// [`lrtdp`](crate::lrtdp()) does (admissible for the guarantee, `None` for a proven dead
/// end). `upper` estimates its upper bound: at least the optimal value, `None` if no finite
/// bound is known. Each trial starts at `initial`; at every state it backs up both bounds,
/// takes the action that is greedy on the lower bound, and samples a successor with
/// probability proportional to `P(s' | s, a) * (U(s') - L(s'))`, so trials go where the
/// bounds are far apart. A trial ends when that weight summed over the successors falls
/// below `(U(initial) - L(initial)) / tau` ([`BrtdpConfig::tau`]), at a goal or dead end, or
/// after [`Config::max_trial_length`] steps; then it backs up its states again, last first.
/// The run stops when `U(initial) - L(initial) <= epsilon` ([`Config::epsilon`]). After
/// convergence, a fill pass backs up every state that the upper-greedy policy reaches from
/// `initial` but no trial backed up, so the returned policy has an action wherever one
/// exists in its envelope (unless the budget runs out during the pass).
///
/// The returned [`Solution`](crate::Solution) has the lower bounds as [`Solution::value`](crate::Solution::value) and the upper
/// bounds as [`Solution::upper_bound`](crate::Solution::upper_bound). Its policy is greedy on the upper bound, as of each
/// state's last backup, as the paper prescribes (`greedy(v_u)`): only an upper-greedy policy
/// has a cost guarantee. [`frtdp`](crate::frtdp()) and [`vpi_rtdp`](crate::vpi_rtdp())
/// share everything in this documentation except how trials pick states.
///
/// # Dead ends
///
/// An infinite upper bound on a state with a finite optimal value never becomes finite: on a
/// cycle such as "retry until it works", a backup computes `c + p * 0 + (1 - p) * inf`.
/// BRTDP therefore requires a finite upper bound on every state it stores, except where the
/// lower bound already proves a dead end (then both bounds are infinite and the gap counts as
/// `0`, so trials never sample it):
///
/// - Under [`DeadEnds::Penalty`](crate::DeadEnds::Penalty)`(p)` this always holds: an upper
/// estimate of `None` or above `p` becomes `p`, since giving up is always possible. With
/// `upper` returning `None` everywhere, `p` is the initial upper bound of every state.
/// - Under [`DeadEnds::Infinite`](crate::DeadEnds::Infinite), the run fails with
/// [`Error::UnboundedUpper`] at the first stored state whose upper estimate is `None` or
/// infinite while its lower estimate is finite. Such a problem needs a lower bound that
/// recognizes its dead ends, a finite upper bound, or a penalty.
///
/// Since every stored state that may have a finite value has a finite upper bound, BRTDP
/// needs no dead-end proof: a state with a finite upper bound has a proper policy if the
/// bound is valid.
///
/// # Guarantee
///
/// If `lower` is admissible and `upper` is a valid upper bound (at least the optimal value
/// `V*` under the configured dead-end semantics), then at any time, in particular whatever
/// the [`Status`](crate::Status), every stored state `s` satisfies
/// `L(s) <= V*(s) <= U(s)` (up to floating-point rounding): Bellman backups of a lower bound
/// stay below `V*`, those of an upper bound stay above it. A run with
/// [`Status::Converged`](crate::Status::Converged) also has
/// `U(initial) - L(initial) <= epsilon`.
///
/// If, in addition, the upper bound is monotone (`U(s) >= min_a Q_U(s, a)` everywhere, as
/// for the constant penalty), backups keep it monotone, and every stored state with a policy
/// action `pi(s)` satisfies `U(s) >= Q_U(s, pi(s))`. Then following the policy from a state
/// whose policy successors all have actions costs at most `U` in expectation. After a
/// converged run and its fill pass, that holds from `initial`: following the policy costs at
/// most `U(initial)`. A run stopped by the budget may leave envelope states without an
/// action; [`Solution::action`](crate::Solution::action) is `None` there.
///
/// # Termination
///
/// With the default [`Limits`] budget the call always returns. With valid
/// bounds both converge to `V*` on the states trials keep visiting, so the gap at `initial`
/// shrinks to `epsilon` on finite problems.
///
/// # Events
///
/// [`Event::Progress`](crate::Event::Progress) as for [`lrtdp`](crate::lrtdp()), with the
/// lower bound as `initial_value` and the current gap `U(initial) - L(initial)` as
/// `residual`. No dead-end or divergence events.
///
/// # Cost
///
/// One backup updates both bounds and counts once in [`Stats::backups`](crate::Stats). The
/// upper bounds take 8 more bytes per stored state. The fill pass is not bounded by the
/// trials' work: it expands every state of the upper-greedy envelope, which under dense
/// noise is every state reachable from `initial`; the budget still caps it (and an exhausted
/// budget during the pass keeps the converged status). One seed gives identical results on
/// every run.
///
/// # Errors
///
/// Returns an [`Error`] for an invalid [`Config`] or `tau`, for invalid MDP output or estimates in the
/// states the run touches (see [`Error::InvalidHeuristic`] for the upper bound), and
/// [`Error::UnboundedUpper`] as described in "Dead ends".
///
/// # Panics
///
/// Panics if more than `u32::MAX` states, actions or outcomes are stored.
///
/// # Example
///
/// A sure route for cost 3, or a coin flip for cost 1 that retries on failure (expected
/// cost 2). The sure route bounds the value from above:
///
/// ```
/// use stochastic_search::{BrtdpConfig, Mdp, Zero, brtdp, heuristic_fn};
///
/// struct Routes;
///
/// impl Mdp for Routes {
/// type State = bool;
/// type Action = &'static str;
///
/// fn actions(&self, _done: &bool, mut emit: impl FnMut(&'static str, f64)) {
/// emit("sure", 3.0);
/// emit("flip", 1.0);
/// }
///
/// fn outcomes(&self, _done: &bool, action: &&'static str, mut emit: impl FnMut(bool, f64)) {
/// if *action == "sure" {
/// emit(true, 1.0);
/// } else {
/// emit(true, 0.5);
/// emit(false, 0.5);
/// }
/// }
/// }
///
/// let upper = heuristic_fn(|_: &bool| Some(3.0));
/// let config = BrtdpConfig::default();
/// let solution = brtdp(&Routes, false, &|done: &bool| *done, Zero, upper, config)?;
///
/// assert!(solution.is_converged());
/// let (lower, upper) = (solution.initial_value(), solution.initial_upper_bound().unwrap());
/// assert!(lower <= 2.0 && 2.0 <= upper && upper - lower <= 1e-6);
/// assert_eq!(solution.initial_action(), Some(&"flip"));
/// # Ok::<(), stochastic_search::Error<bool>>(())
/// ```