stochastic_search/config.rs
1//! Run configuration ([`Config`]) and dead-end semantics ([`DeadEnds`]).
2
3use crate::budget::{Budget, Limits, Stats};
4use crate::error::Error;
5use crate::observer::Observer;
6
7/// How states without a proper policy are valued.
8///
9/// See `docs/design.md`, section "Dead ends".
10#[derive(Debug, Clone, Copy, Default, PartialEq)]
11pub enum DeadEnds {
12 /// Dead ends cost infinity (the "fragile" SSP semantics).
13 ///
14 /// Exact when a proper policy exists from the initial state. If none exists, the run
15 /// ends with [`Status::Unsolvable`](crate::Status::Unsolvable) (or with an exhausted
16 /// budget, if a heuristic search cannot prove it in time); see [`lrtdp`](crate::lrtdp())'s
17 /// termination notes.
18 #[default]
19 Infinite,
20 /// Every non-goal state may give up at this finite, non-negative cost.
21 ///
22 /// Values are capped at the penalty, every policy is proper, and the algorithms converge
23 /// on any input. A state valued at the penalty has no action in the policy.
24 Penalty(f64),
25}
26
27impl DeadEnds {
28 /// The value of a dead end, which is also the cap on every value.
29 pub(crate) fn cap(self) -> f64 {
30 match self {
31 Self::Infinite => f64::INFINITY,
32 Self::Penalty(penalty) => penalty,
33 }
34 }
35}
36
37/// Settings shared by all algorithms.
38///
39/// Build one with [`Config::default`] and the `with_*` methods, which swap one setting
40/// each; [`Config::with_budget`] and [`Config::with_observer`] also change the type. The
41/// struct is `#[non_exhaustive]`, so new settings can be added without a breaking change;
42/// outside this crate, the fields can be read and assigned but not listed in a struct
43/// expression.
44///
45/// ```
46/// use stochastic_search::{Config, DeadEnds, Stats};
47///
48/// let config = Config::default()
49/// .with_epsilon(1e-4)
50/// .with_dead_ends(DeadEnds::Penalty(100.0))
51/// .with_budget(|stats: &Stats| stats.backups >= 1_000_000);
52/// # let _ = config;
53/// ```
54#[non_exhaustive]
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Config<B = Limits, O = ()> {
57 /// Convergence threshold on Bellman residuals. Must be finite and greater than zero.
58 ///
59 /// Default `1e-6`.
60 pub epsilon: f64,
61 /// Dead-end semantics. Default [`DeadEnds::Infinite`].
62 pub dead_ends: DeadEnds,
63 /// Seed of the successor sampler used by LRTDP, RTDP, BRTDP and VPI-RTDP trials (and FRTDP's
64 /// fallback trials). A seed reproduces a run
65 /// exactly.
66 ///
67 /// Default `0`.
68 pub seed: u64,
69 /// LRTDP, RTDP and the bounded algorithms cut a trial off after this many steps and start the next one.
70 /// At least `1`.
71 ///
72 /// Guards against trials that circle a dead-end trap forever. Default `10_000`.
73 pub max_trial_length: usize,
74 /// Stops a run early. Default [`Limits::DEFAULT`] (`10^8` backups, `10^6` stored states,
75 /// about 250 MB for typical states), which is finite, so a run with the default
76 /// configuration always returns. Raise a cap with
77 /// `Config::default().with_budget(Limits { max_states: Some(n), ..Limits::DEFAULT })`;
78 /// [`Limits`] documents the memory per stored state.
79 pub budget: B,
80 /// Receives [`Event`](crate::Event)s during the run. Default `()`, which ignores them
81 /// at no cost.
82 pub observer: O,
83 /// Emit [`Event::Progress`](crate::Event::Progress) every this many backups. `None`
84 /// never emits it. Default `Some(1_000_000)`; ignored by the default observer.
85 pub progress_interval: Option<u64>,
86 /// The number of consecutive LRTDP or RTDP trials (iLAO* passes, LAO* expansion steps) over which
87 /// [`Event::SuspectedDivergence`](crate::Event::SuspectedDivergence) looks for steady
88 /// growth of the initial value. At least `1`. Default `16`; ignored by the default
89 /// observer.
90 pub divergence_window: usize,
91}
92
93impl Default for Config {
94 fn default() -> Self {
95 Self {
96 epsilon: 1e-6,
97 dead_ends: DeadEnds::Infinite,
98 seed: 0,
99 max_trial_length: 10_000,
100 budget: Limits::DEFAULT,
101 observer: (),
102 progress_interval: Some(1_000_000),
103 divergence_window: 16,
104 }
105 }
106}
107
108impl<B, O> Config<B, O> {
109 /// Returns the same configuration with another [`Config::epsilon`].
110 #[must_use]
111 pub fn with_epsilon(self, epsilon: f64) -> Self {
112 Self { epsilon, ..self }
113 }
114
115 /// Returns the same configuration with other [`Config::dead_ends`] semantics.
116 #[must_use]
117 pub fn with_dead_ends(self, dead_ends: DeadEnds) -> Self {
118 Self { dead_ends, ..self }
119 }
120
121 /// Returns the same configuration with another [`Config::seed`].
122 #[must_use]
123 pub fn with_seed(self, seed: u64) -> Self {
124 Self { seed, ..self }
125 }
126
127 /// Returns the same configuration with another [`Config::max_trial_length`].
128 #[must_use]
129 pub fn with_max_trial_length(self, max_trial_length: usize) -> Self {
130 Self {
131 max_trial_length,
132 ..self
133 }
134 }
135
136 /// Returns the same configuration with another [`Config::progress_interval`].
137 #[must_use]
138 pub fn with_progress_interval(self, progress_interval: Option<u64>) -> Self {
139 Self {
140 progress_interval,
141 ..self
142 }
143 }
144
145 /// Returns the same configuration with another [`Config::divergence_window`].
146 #[must_use]
147 pub fn with_divergence_window(self, divergence_window: usize) -> Self {
148 Self {
149 divergence_window,
150 ..self
151 }
152 }
153
154 /// Returns the same configuration with another budget.
155 #[must_use]
156 pub fn with_budget<B2: Budget<Stats>>(self, budget: B2) -> Config<B2, O> {
157 Config {
158 epsilon: self.epsilon,
159 dead_ends: self.dead_ends,
160 seed: self.seed,
161 max_trial_length: self.max_trial_length,
162 budget,
163 observer: self.observer,
164 progress_interval: self.progress_interval,
165 divergence_window: self.divergence_window,
166 }
167 }
168
169 /// Returns the same configuration with another observer.
170 #[must_use]
171 pub fn with_observer<O2: Observer>(self, observer: O2) -> Config<B, O2> {
172 Config {
173 epsilon: self.epsilon,
174 dead_ends: self.dead_ends,
175 seed: self.seed,
176 max_trial_length: self.max_trial_length,
177 budget: self.budget,
178 observer,
179 progress_interval: self.progress_interval,
180 divergence_window: self.divergence_window,
181 }
182 }
183
184 /// Checks the numeric settings.
185 ///
186 /// # Errors
187 ///
188 /// Returns [`Error::InvalidConfig`] for an epsilon that is not finite and positive, a
189 /// penalty that is not finite and non-negative, a zero trial length, a zero progress
190 /// interval or a zero divergence window.
191 pub(crate) fn validate<S>(&self) -> Result<(), Error<S>> {
192 if !(self.epsilon.is_finite() && self.epsilon > 0.0) {
193 return Err(Error::InvalidConfig {
194 reason: "epsilon must be finite and greater than zero",
195 });
196 }
197
198 if matches!(self.dead_ends, DeadEnds::Penalty(penalty) if !(penalty.is_finite() && penalty >= 0.0))
199 {
200 return Err(Error::InvalidConfig {
201 reason: "the dead-end penalty must be finite and non-negative",
202 });
203 }
204
205 if self.progress_interval == Some(0) || self.divergence_window == 0 {
206 return Err(Error::InvalidConfig {
207 reason: "progress_interval and divergence_window must be at least 1",
208 });
209 }
210
211 if self.max_trial_length == 0 {
212 return Err(Error::InvalidConfig {
213 reason: "max_trial_length must be at least 1",
214 });
215 }
216
217 Ok(())
218 }
219}