Skip to main content

stochastic_search/
lib.rs

1//! # Stochastic search
2//!
3//! Planning under probabilistic outcomes: value iteration, RTDP, labeled RTDP, BRTDP, FRTDP,
4//! VPI-RTDP, LAO*, iLAO* and CG-iLAO* for
5//! fully observable problems, MOLAO*, iMOLAO* and MOLRTDP for multi-objective ones; POMCP and DESPOT for partially observable ones.
6//!
7//! A problem is a stochastic shortest path (SSP) problem: reach a goal state with minimal
8//! expected total cost, where every action has a cost and a probability distribution over
9//! successor states. It is described by small capability traits instead of one universal
10//! problem trait: the MDP implements [`Mdp`], the goal test is a [`Goal`] and the initial
11//! value estimate a [`Heuristic`]. Closures work for both (wrap heuristic closures in
12//! [`heuristic_fn`]). Every algorithm takes
13//! a [`Config`] and returns a [`Solution`]: a value function and a greedy policy, plus a
14//! [`Status`] and [`Stats`].
15//!
16//! Partially observable problems are generative models ([`Pomdp`]): a step samples successor,
17//! observation and reward from a `rand_core` generator. The online planners [`pomcp()`] and
18//! [`despot()`] take a particle belief and return a [`Plan`] for one decision.
19//!
20//! The crate is `no_std` and needs only `alloc`.
21//!
22//! ## Algorithms
23//!
24//! - [`lrtdp()`]: labeled real-time dynamic programming (Bonet and Geffner 2003). Explores only
25//!   the states a good policy visits; epsilon-consistent on them when it converges.
26//! - [`rtdp()`]: plain RTDP (Barto, Bradtke and Singh 1995), with LRTDP's solved check as
27//!   its stopping rule. The classic baseline.
28//! - [`brtdp()`]: bounded RTDP (McMahan, Likhachev and Gordon 2005). Keeps a lower and an
29//!   upper bound and samples where they are far apart; anytime, with a known gap.
30//! - [`frtdp()`]: focused RTDP (Smith and Simmons 2006). The same bounds; trials follow the
31//!   successor of highest priority with an adaptive depth limit.
32//! - [`vpi_rtdp()`]: VPI-RTDP (Sanner et al. 2009). The same bounds; trials follow the value
33//!   of perfect information about successors where the bounds are informative.
34//! - [`lao_star()`]: classic LAO* (Hansen and Zilberstein 2001), one tip per expansion
35//!   step with value iteration on its ancestors. The paper's original; slower than iLAO*.
36//! - [`cg_ilao_star()`]: CG-iLAO* (Schmalz and Trevizan 2024). iLAO* over a partial SSP that
37//!   adds an action only when constraint generation finds it necessary.
38//! - [`ilao_star()`]: improved LAO* (Hansen and Zilberstein 2001). Grows the best partial
39//!   solution graph in depth-first passes; no sampling.
40//! - [`value_iteration()`]: value iteration over every reachable state. The exact reference.
41//! - [`pomcp()`]: partially observable Monte-Carlo planning (Silver and Veness 2010). UCT
42//!   over action-observation histories with rollouts.
43//! - [`despot()`]: anytime regularized DESPOT (Somani et al. 2013, Ye et al. 2017). Bound
44//!   guided search over a tree of `K` determinized scenarios.
45//! - [`molrtdp()`], [`molao_star()`], [`imolao_star()`] and [`mo_value_iteration()`]:
46//!   multi-objective SSPs (Chen, Trevizan and Thiébaux 2023) over an [`MoMdp`] with cost
47//!   vectors. They return an [`MoSolution`], a convex coverage set of deterministic
48//!   policies; heuristics are [`ZeroVector`], [`IdealPoint`] and [`Abstraction`] (also over
49//!   [`Determinized`]).
50//! - [`Pomcp`] and [`Despot`]: the same planners kept between decisions, reusing the subtree
51//!   after the action taken and the observation received; [`update_belief`] is POMCP's
52//!   particle filter with reinvigoration.
53//!
54//! ## The heuristic contract
55//!
56//! [`Goal`], [`Heuristic`], [`heuristic_fn`] and [`Budget`] are re-exported from
57//! `search-core`, shared with the other planning crates. The algorithms here use
58//! `Heuristic<S, f64>` (closures infer `f64`) under this contract:
59//!
60//! - `estimate` is called once per state, when the state is first stored; never for goals.
61//!   It takes `&mut self`, so a heuristic can keep a workspace; algorithms take it by value,
62//!   pass `&mut h` to keep `h`.
63//! - `None` (or an infinite estimate) means no proper policy exists from the state, a proven
64//!   dead end that is never expanded. Return it only when that is certain.
65//! - NaN and negative infinity are rejected with [`Error::InvalidHeuristic`].
66//! - The optimality guarantees need an admissible heuristic (never above the optimal
67//!   expected cost). Inadmissible ones never panic; they only void the guarantee.
68//!
69//! [`Zero`], the blind heuristic, is `search-core`'s too; it estimates `0.0` for `f64`.
70//! The multi-objective algorithms take cost-vector sets and use [`ZeroVector`] instead.
71//!
72//! ## Dead ends
73//!
74//! States from which no policy reaches a goal with probability 1 are valued per
75//! [`DeadEnds`]: at infinity (the default, exact SSP semantics), or at a finite give-up
76//! penalty that makes every input solvable. The bounded algorithms ([`brtdp()`], [`frtdp()`],
77//! [`vpi_rtdp()`]) need finite upper bounds, so under infinite dead ends their lower bound
78//! must prove the dead ends they meet.
79//!
80//! ## Events
81//!
82//! An [`Observer`] set with [`Config::with_observer`] receives [`Event`]s while a run
83//! progresses: progress, proven dead ends, and suspected divergence (a heuristic signal,
84//! never a verdict). The default observer `()` costs nothing.
85//!
86//! ## Example
87//!
88//! ```
89//! use stochastic_search::{Config, Mdp, heuristic_fn, lrtdp};
90//!
91//! /// A die roll: action `roll` (cost 1) ends on a six; action `pay` (cost 4) ends always.
92//! struct Dice;
93//!
94//! impl Mdp for Dice {
95//!     type State = bool;
96//!     type Action = &'static str;
97//!
98//!     fn actions(&self, _done: &bool, mut emit: impl FnMut(&'static str, f64)) {
99//!         emit("roll", 1.0);
100//!         emit("pay", 4.0);
101//!     }
102//!
103//!     fn outcomes(&self, _done: &bool, action: &&'static str, mut emit: impl FnMut(bool, f64)) {
104//!         match *action {
105//!             "roll" => {
106//!                 emit(true, 1.0 / 6.0);
107//!                 emit(false, 5.0 / 6.0);
108//!             }
109//!             _ => emit(true, 1.0),
110//!         }
111//!     }
112//! }
113//!
114//! let heuristic = heuristic_fn(|_: &bool| Some(1.0));
115//! let solution = lrtdp(&Dice, false, &|done: &bool| *done, heuristic, Config::default())?;
116//!
117//! // Rolling takes 6 attempts in expectation, so paying 4 is cheaper.
118//! assert_eq!(solution.initial_action(), Some(&"pay"));
119//! assert!((solution.initial_value() - 4.0).abs() < 1e-5);
120//! # Ok::<(), stochastic_search::Error<bool>>(())
121//! ```
122//!
123//! See `docs/design.md` in the repository for the design.
124//!
125//! Repository: <https://github.com/sunsided/stochastic-search>
126
127#![no_std]
128#![forbid(unsafe_code)]
129
130extern crate alloc;
131
132mod belief;
133mod bounds;
134mod budget;
135mod cg_ilao;
136mod config;
137mod despot;
138mod error;
139mod ilao;
140mod lao;
141mod lrtdp;
142mod meter;
143pub mod mo;
144mod model;
145mod observer;
146mod pomcp;
147mod pomdp;
148mod rng;
149mod rtdp;
150mod solution;
151mod space;
152mod value_iteration;
153
154/// Doctests for the code examples in README.md (not part of the API).
155#[cfg(doctest)]
156#[doc = include_str!("../README.md")]
157mod readme_doctests {}
158
159pub use belief::{BeliefFilter, BeliefUpdate, update_belief};
160pub use bounds::brtdp::{BrtdpConfig, brtdp};
161pub use bounds::frtdp::{FrtdpConfig, frtdp};
162pub use bounds::vpi::{VpiRtdpConfig, vpi_rtdp};
163pub use budget::{Budget, Limits, Stats, TreeStats};
164pub use cg_ilao::cg_ilao_star;
165pub use config::{Config, DeadEnds};
166pub use despot::{Despot, DespotConfig, despot};
167pub use error::{Error, PROBABILITY_TOLERANCE};
168pub use ilao::ilao_star;
169pub use lao::lao_star;
170pub use lrtdp::lrtdp;
171pub use mo::{
172    Abstraction, Determinized, IdealPoint, MoMdp, MoPolicy, MoSolution, MoSolveResult, Objectives,
173    ZeroVector, imolao_star, mo_value_iteration, molao_star, molrtdp,
174};
175pub use model::{Goal, Heuristic, HeuristicFn, Mdp, Zero, heuristic_fn};
176pub use observer::{Event, Observer, ObserverFn, observer_fn};
177pub use pomcp::{Pomcp, PomcpConfig, pomcp, pomcp_exploration};
178pub use pomdp::{Plan, Pomdp, RolloutPolicy, Step, UniformRandom};
179pub use rng::{SplitMix64, unit_interval};
180pub use rtdp::rtdp;
181pub use solution::{Solution, SolveResult, Status};
182pub use value_iteration::value_iteration;