heuristic_search/lib.rs
1//! # Heuristic search
2//!
3//! Explicit-state heuristic graph search: A*, weighted and anytime, bounded-suboptimal,
4//! bidirectional, incremental and real-time search.
5//!
6//! A problem is described by small capability traits instead of one universal problem
7//! trait: a graph implements [`Successors`], the goal test is a [`Goal`] and the estimate a
8//! [`Heuristic`]. Goal tests can be closures; [`heuristic_fn`] wraps a closure as a
9//! heuristic. Searches own their heuristic; pass `&mut h` to lend one and keep its
10//! workspace. Every search returns a [`SearchResult`] with an [`Outcome`] (a [`Solution`]
11//! path, unsolvable, or limit reached) and [`Stats`]. A [`Budget`] (such as [`Limits`], or a
12//! closure that checks a clock) stops a search early.
13//!
14//! The crate is `no_std` and needs only `alloc`.
15//!
16//! ## Algorithms
17//!
18//! - [`bfs()`]: breadth-first search, fewest edges.
19//! - [`dijkstra`]: uniform-cost search, cheapest path.
20//! - [`a_star`]: A*, cheapest path with an admissible heuristic.
21//! - [`weighted_a_star`]: Weighted A*, at most `w` times the cheapest cost.
22//! - [`gbfs`]: greedy best-first search, fast and unbounded.
23//! - [`fringe_search`]: fringe search, cheapest path with an admissible heuristic through
24//! `f` threshold iterations over a cache of every state, without a priority queue.
25//!
26//! Each has a `*_multi` variant ([`a_star_multi`] and so on) that searches from several
27//! start states at once. So does every other search below; the incremental planners have
28//! multi-start types ([`LpaStarMulti`] and so on) with fixed starts.
29//!
30//! Depth-first searches need memory only for the current path (except [`dfs`]):
31//!
32//! - [`dfs`]: graph depth-first search, some path.
33//! - [`depth_limited_dfs`] and [`iddfs`]: depth-limited and iterative deepening, fewest
34//! edges.
35//! - [`ida_star`]: IDA*, cheapest path with an admissible heuristic; [`ida_star_tt`] adds
36//! a bounded transposition table for graphs with many paths to each state.
37//! - [`rbfs()`]: recursive best-first search (RBFS), cheapest path with an admissible
38//! heuristic, in best-first order with memory linear in the depth.
39//!
40//! [`sma_star`] (SMA*) is A* within a fixed number of nodes: it forgets its worst leaves
41//! and regenerates them when needed, and returns the cheapest path among those that fit in
42//! memory, or [`Outcome::Cutoff`] when none does.
43//!
44//! Anytime searches report each improved solution and return an [`AnytimeResult`]:
45//!
46//! - [`ara_star`]: ARA*, Weighted A* with a falling weight schedule.
47//! - [`ana_star`]: ANA*, anytime without parameters.
48//! - [`beam_stack_search`]: beam-stack search, a beam of fixed width that backtracks over
49//! what it pruned; optimal once complete, in memory bounded by the width per layer.
50//!
51//! [`beam_search`] is breadth-first beam search: a fixed number of states per layer, fast
52//! but incomplete ([`Outcome::Cutoff`] when the width may have pruned the goal away).
53//!
54//! Bounded-suboptimal searches return a solution within `w` times the optimum:
55//!
56//! - [`focal_search`]: expands by a free [`FocalKey`] among `f <= w * f_min`. Its open list,
57//! [`FocalList`], is public for searches with their own loop.
58//! - [`ees`]: Explicit Estimation Search, guided by inadmissible estimates.
59//! - [`dps`]: Dynamic Potential Search, needs only `h`.
60//!
61//! Bidirectional searches need [`Predecessors`] as well (a [`BidirectionalGraph`]) and
62//! explicit goal states:
63//!
64//! - [`bidirectional_bfs`] and [`bidirectional_dijkstra`]: blind baselines.
65//! - [`nbs`]: Near-Optimal Bidirectional Search, pairs of expansions.
66//! - [`dibbs`] and [`bae_star`]: DIBBS and BAE*, ordered by `2g + h - h_opposite`.
67//!
68//! The frontiers meet by state equality. The `*_meet` variants ([`nbs_meet`],
69//! [`bidirectional_bfs_meet`] and so on) meet by a [`MeetRelation`] instead, such as a
70//! state satisfying a subgoal for regression over partial states of their own type (a
71//! [`RegressionGraph`]), and replay the backward actions to return a path of real states
72//! or a [`ReplayError`].
73//!
74//! Grid searches work on a [`UniformGrid`], 8-connected without corner cutting (see
75//! [`UniformGrid`]), with the exact octile cost [`Octile`]:
76//!
77//! - [`jps`]: Jump Point Search, cheapest path, expanding only jump points.
78//! - `theta_star` and `lazy_theta_star` (feature `float`): Theta* and Lazy Theta*,
79//! any-angle paths between cell centres on a [`LineOfSight`] grid, with Euclidean
80//! float costs; never longer than the cheapest 8-connected path (Theta*).
81//!
82//! [`EightConnected`] makes a grid a plain graph for the other searches.
83//!
84//! [`mha_star`] (shared multi-heuristic A*) combines one consistent anchor heuristic with
85//! any number of inadmissible ones, within `w1 * w2` times the optimum.
86//!
87//! [`lazy_sp`] (`LazySP`) finds cheapest paths when true edge costs are expensive, evaluating
88//! them through an [`EdgeEvaluator`] only on candidate paths.
89//!
90//! Incremental planners keep their search tree while edge costs of a [`DynamicGraph`]
91//! change, and repair only what the changes affect:
92//!
93//! - [`LpaStar`]: Lifelong Planning A*, fixed start and goal.
94//! - [`DStarLite`]: D* Lite, fixed goal and a moving start.
95//! - [`AdStar`]: Anytime D*, D* Lite with an inflated heuristic the caller lowers.
96//! - `FieldDStar` (feature `float`): Field D*, D* Lite over the corners of a `CostGrid`
97//! with per-cell costs, whose paths cross cells at any angle through points on cell
98//! edges.
99//!
100//! Real-time searches plan a bounded amount, move, and learn values in a
101//! [`LearnedHeuristic`] the caller keeps across trials; each call runs one trial and
102//! returns a [`TrialResult`]:
103//!
104//! - [`lrta_star`] and [`rta_star`]: LRTA* and RTA*, a lookahead of one expansion.
105//! - [`lss_lrta_star`]: LSS-LRTA*, an A* lookahead of `n` expansions and a Dijkstra update.
106//! - [`lhb_lrta_star`]: the same agent with the limited-horizon Bellman update of Hadar et
107//! al.; [`lhb_update`] is that update on its own, for offline learning.
108//! - [`rtaa_star`]: RTAA*, the A* lookahead with a cheaper update.
109//!
110//! Costs are generic over [`Cost`]. For planning, `u32` is the intended default: action
111//! costs are small integers and heuristics over them stay exact. [`Cost`], [`Heuristic`],
112//! [`Goal`] and [`Budget`] come from `search-core` and are re-exported here; [`CostExt`]
113//! adds the subtraction and float conversion a few searches need.
114//!
115//! ## Features
116//!
117//! - `float`: re-exports the checked float cost `NonNegF64` from `search-core`, and enables
118//! the any-angle grid searches `theta_star` and `lazy_theta_star` and the Field D*
119//! planner `FieldDStar` with its `CostGrid`, whose Euclidean costs are floats.
120//!
121//! ## Example
122//!
123//! ```
124//! use heuristic_search::{Limits, Successors, dijkstra};
125//!
126//! /// A directed graph as adjacency lists of `(target, cost)` pairs.
127//! struct Graph(Vec<Vec<(usize, u32)>>);
128//!
129//! impl Successors for Graph {
130//! type State = usize;
131//! type Action = usize;
132//! type Cost = u32;
133//!
134//! fn successors(&self, state: &usize, mut emit: impl FnMut(usize, usize, u32)) {
135//! for &(target, cost) in &self.0[*state] {
136//! emit(target, target, cost);
137//! }
138//! }
139//! }
140//!
141//! let graph = Graph(vec![vec![(1, 5), (2, 1)], vec![(3, 1)], vec![(1, 1)], vec![]]);
142//! let result = dijkstra(&graph, 0, &|state: &usize| *state == 3, Limits::NONE);
143//! let solution = result.solution().expect("3 is reachable");
144//!
145//! assert_eq!(solution.states, [0, 2, 1, 3]);
146//! assert_eq!(solution.cost, 3);
147//! ```
148//!
149//! ## Naming
150//!
151//! Searches are snake-case functions; every A* variant ends in `_star` ([`a_star`],
152//! [`weighted_a_star`], [`ida_star`], [`ara_star`], [`ana_star`], [`mha_star`],
153//! [`bae_star`]). Suffixes compose in this order: `_tt` (a variant of the algorithm),
154//! `_multi` (several starts), `_meet` (a meet relation, always with several starts).
155//! Incremental planners keep state between calls, so they are types ([`LpaStar`],
156//! [`DStarLite`], [`AdStar`], `FieldDStar`).
157//!
158//! See `docs/design.md` in the repository for the design.
159//!
160//! Repository: <https://github.com/sunsided/heuristic-search>
161
162#![no_std]
163#![forbid(unsafe_code)]
164
165extern crate alloc;
166
167/// Doctests for the code examples in README.md (not part of the API).
168#[cfg(doctest)]
169#[doc = include_str!("../README.md")]
170mod readme_doctests {}
171
172mod anytime;
173mod beam;
174mod best_first;
175mod bfs;
176mod bidirectional;
177mod bounded;
178mod cost;
179mod depth_first;
180mod dynamic;
181mod focal;
182mod fringe;
183mod grid;
184mod indexed_heap;
185mod keyed_set;
186mod lazy;
187mod mha;
188mod open_list;
189mod outcome;
190mod problem;
191mod rbfs;
192mod real_time;
193mod sma;
194mod space;
195
196pub use anytime::{
197 AnytimeGraphResult, AnytimeResult, ana_star, ana_star_multi, ara_star, ara_star_multi,
198};
199pub use beam::{beam_search, beam_search_multi, beam_stack_search, beam_stack_search_multi};
200pub use best_first::{
201 GraphResult, a_star, a_star_multi, dijkstra, dijkstra_multi, gbfs, gbfs_multi, weighted_a_star,
202 weighted_a_star_multi,
203};
204pub use bfs::{bfs, bfs_multi};
205pub use bidirectional::{
206 BidirectionalGraph, MeetFn, MeetRelation, MeetResult, RegressionGraph, ReplayError, bae_star,
207 bae_star_meet, bae_star_multi, bidirectional_bfs, bidirectional_bfs_meet,
208 bidirectional_bfs_multi, bidirectional_dijkstra, bidirectional_dijkstra_meet,
209 bidirectional_dijkstra_multi, dibbs, dibbs_meet, dibbs_multi, meet_fn, nbs, nbs_meet,
210 nbs_multi,
211};
212pub use bounded::{
213 EesEstimates, FocalFn, FocalKey, dps, dps_multi, ees, ees_multi, focal_fn, focal_search,
214 focal_search_multi,
215};
216pub use cost::{CostExt, Weight};
217pub use depth_first::{
218 depth_limited_dfs, depth_limited_dfs_multi, dfs, dfs_multi, ida_star, ida_star_multi,
219 ida_star_tt, ida_star_tt_multi, iddfs, iddfs_multi,
220};
221pub use dynamic::{
222 AdStar, AdStarMulti, DStarLite, DStarLiteMulti, DynamicGraph, DynamicResult, LpaStar,
223 LpaStarMulti,
224};
225#[cfg(feature = "float")]
226pub use dynamic::{FieldDStar, FieldResult};
227pub use focal::{FocalList, TieBreak};
228pub use fringe::{fringe_search, fringe_search_multi};
229#[cfg(feature = "float")]
230pub use grid::{
231 AnyAngleResult, CostGrid, lazy_theta_star, lazy_theta_star_multi, theta_star, theta_star_multi,
232};
233pub use grid::{
234 EightConnected, GridCell, GridStep, LineOfSight, Octile, OctileDistance, UniformGrid, jps,
235 jps_multi,
236};
237pub use lazy::{EdgeEvaluator, EdgeSelector, lazy_sp, lazy_sp_multi};
238pub use mha::{MhaWeights, mha_star, mha_star_multi};
239pub use outcome::{Limits, Outcome, SearchResult, Solution, Stats};
240pub use problem::{Predecessors, Successors};
241pub use rbfs::{rbfs, rbfs_multi};
242pub use real_time::{
243 LearnedHeuristic, TrialResult, TrialStats, lhb_lrta_star, lhb_update, lrta_star, lss_lrta_star,
244 rta_star, rtaa_star,
245};
246#[cfg(feature = "float")]
247pub use search_core::NonNegF64;
248pub use search_core::{Budget, Cost, Decimal, Goal, Heuristic, HeuristicFn, Zero, heuristic_fn};
249pub use sma::{sma_star, sma_star_multi};