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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! # Heuristic search
//!
//! Explicit-state heuristic graph search: A*, weighted and anytime, bounded-suboptimal,
//! bidirectional, incremental and real-time search.
//!
//! A problem is described by small capability traits instead of one universal problem
//! trait: a graph implements [`Successors`], the goal test is a [`Goal`] and the estimate a
//! [`Heuristic`]. Goal tests can be closures; [`heuristic_fn`] wraps a closure as a
//! heuristic. Searches own their heuristic; pass `&mut h` to lend one and keep its
//! workspace. Every search returns a [`SearchResult`] with an [`Outcome`] (a [`Solution`]
//! path, unsolvable, or limit reached) and [`Stats`]. A [`Budget`] (such as [`Limits`], or a
//! closure that checks a clock) stops a search early.
//!
//! The crate is `no_std` and needs only `alloc` (feature `parallel` adds `std`).
//!
//! ## Algorithms
//!
//! - [`bfs()`]: breadth-first search, fewest edges.
//! - [`dijkstra`]: uniform-cost search, cheapest path.
//! - [`a_star`]: A*, cheapest path with an admissible heuristic.
//! - [`weighted_a_star`]: Weighted A*, at most `w` times the cheapest cost.
//! - [`gbfs`]: greedy best-first search, fast and unbounded.
//! - [`fringe_search`]: fringe search, cheapest path with an admissible heuristic through
//! `f` threshold iterations over a cache of every state, without a priority queue.
//!
//! Each has a `*_multi` variant ([`a_star_multi`] and so on) that searches from several
//! start states at once. So does every other search below; the incremental planners have
//! multi-start types ([`LpaStarMulti`] and so on) with fixed starts.
//!
//! Many queries on one graph share work:
//!
//! - [`Workspace`] keeps the memory of a best-first search for the next one. The `*_in`
//! variants ([`a_star_in`], [`dijkstra_in`], [`a_star_multi_in`] and so on) search in a
//! caller's workspace and return the same result as the search without one, reusing the
//! workspace's allocations.
//! - [`AStarSearch`]: A* that stops when its budget runs out and continues where it stopped
//! on the next call, to spread one search over several frames.
//! - [`FlowField`]: one backward Dijkstra search from a goal set over [`Predecessors`] that
//! gives every state its cost to the nearest goal and its next step, for any number of
//! agents heading there.
//! - `solve_batch` (feature `parallel`): independent queries solved on several threads,
//! with one state such as a [`Workspace`] per thread, answered in input order.
//!
//! Graphs, heuristics, planners, workspaces and results are `Send` and `Sync` whenever
//! their type parameters are.
//!
//! Depth-first searches need memory only for the current path (except [`dfs`]):
//!
//! - [`dfs`]: graph depth-first search, some path.
//! - [`depth_limited_dfs`] and [`iddfs`]: depth-limited and iterative deepening, fewest
//! edges.
//! - [`ida_star`]: IDA*, cheapest path with an admissible heuristic; [`ida_star_tt`] adds
//! a bounded transposition table for graphs with many paths to each state.
//! - [`rbfs()`]: recursive best-first search (RBFS), cheapest path with an admissible
//! heuristic, in best-first order with memory linear in the depth.
//!
//! [`sma_star`] (SMA*) is A* within a fixed number of nodes: it forgets its worst leaves
//! and regenerates them when needed, and returns the cheapest path among those that fit in
//! memory, or [`Outcome::Cutoff`] when none does.
//!
//! Anytime searches report each improved solution and return an [`AnytimeResult`]:
//!
//! - [`ara_star`]: ARA*, Weighted A* with a falling weight schedule.
//! - [`ana_star`]: ANA*, anytime without parameters.
//! - [`beam_stack_search`]: beam-stack search, a beam of fixed width that backtracks over
//! what it pruned; optimal once complete, in memory bounded by the width per layer.
//!
//! [`beam_search`] is breadth-first beam search: a fixed number of states per layer, fast
//! but incomplete ([`Outcome::Cutoff`] when the width may have pruned the goal away).
//!
//! Bounded-suboptimal searches return a solution within `w` times the optimum:
//!
//! - [`focal_search`]: expands by a free [`FocalKey`] among `f <= w * f_min`. Its open list,
//! [`FocalList`], is public for searches with their own loop; it can admit items to focal
//! by a value apart from `f` ([`FocalList::push_with_value`]).
//! - [`ees`]: Explicit Estimation Search, guided by inadmissible estimates.
//! - [`dps`]: Dynamic Potential Search, needs only `h`.
//!
//! Bidirectional searches need [`Predecessors`] as well (a [`BidirectionalGraph`]) and
//! explicit goal states:
//!
//! - [`bidirectional_bfs`] and [`bidirectional_dijkstra`]: blind baselines.
//! - [`nbs`]: Near-Optimal Bidirectional Search, pairs of expansions.
//! - [`dibbs`] and [`bae_star`]: DIBBS and BAE*, ordered by `2g + h - h_opposite`.
//! - [`mm`]: MM, ordered by `max(f, 2g)`, never expands past half the optimal cost on
//! either side; MM0 with zero heuristics.
//!
//! The frontiers meet by state equality. The `*_meet` variants ([`nbs_meet`],
//! [`bidirectional_bfs_meet`] and so on) meet by a [`MeetRelation`] instead, such as a
//! state satisfying a subgoal for regression over partial states of their own type (a
//! [`RegressionGraph`]), and replay the backward actions to return a path of real states
//! or a [`ReplayError`].
//!
//! Grid searches work on a [`UniformGrid`], 8-connected without corner cutting (see
//! [`UniformGrid`]), with the exact octile cost [`Octile`]:
//!
//! - [`jps`]: Jump Point Search, cheapest path, expanding only jump points.
//! - `theta_star` and `lazy_theta_star` (feature `float`): Theta* and Lazy Theta*,
//! any-angle paths between cell centres on a [`LineOfSight`] grid, with Euclidean
//! float costs; never longer than the cheapest 8-connected path (Theta*).
//!
//! [`EightConnected`] makes a grid a plain graph for the other searches.
//!
//! [`hierarchical_a_star`] (HPA*) plans over a [`Hierarchy`] built once: a graph split
//! into [`Regions`] (rooms of a floor plan, or the square [`GridClusters`] of a grid with a
//! few entrance cells per border), searched first on the small graph of entrances, then
//! refined by A* inside each region. `hierarchical_a_star_par` (feature `parallel`) runs
//! the refinements across threads.
//!
//! [`mha_star`] (shared multi-heuristic A*) combines one consistent anchor heuristic with
//! any number of inadmissible ones, within `w1 * w2` times the optimum.
//!
//! `hda_star` (feature `parallel`) is hash-distributed A* (HDA*): one A* search over
//! several threads, each owning the states that hash to it; the same cost as [`a_star`].
//!
//! [`Landmarks`] precomputes ALT lower bounds (A*, landmarks, triangle inequality) for
//! many queries on one graph: exact distances to and from a few landmark states, picked
//! farthest-first or by avoidance ([`LandmarkSelection`]). Its [`LandmarkHeuristic`]s
//! are admissible and consistent on directed graphs, towards a target for any search and
//! from a source for the backward side of the bidirectional searches.
//!
//! [`ContractionHierarchy`] (contraction hierarchies) preprocesses a finite graph with
//! static edge costs once, adding shortcuts in an order of importance, and then answers
//! many exact cheapest-path queries with a bidirectional Dijkstra that only climbs the
//! hierarchy; solutions carry the graph's own actions. Its ranks and upward search spaces
//! are readable for visualisation.
//!
//! [`lazy_sp`] (`LazySP`) finds cheapest paths when true edge costs are expensive, evaluating
//! them through an [`EdgeEvaluator`] only on candidate paths.
//!
//! Incremental planners keep their search tree while edge costs of a [`DynamicGraph`]
//! change, and repair only what the changes affect:
//!
//! - [`LpaStar`]: Lifelong Planning A*, fixed start and goal.
//! - [`DStarLite`]: D* Lite, fixed goal and a moving start.
//! - [`AdStar`]: Anytime D*, D* Lite with an inflated heuristic the caller lowers.
//! - `FieldDStar` (feature `float`): Field D*, D* Lite over the corners of a `CostGrid`
//! with per-cell costs, whose paths cross cells at any angle through points on cell
//! edges.
//! - [`RealTimeDStar`]: Real-time D*, D* Lite under a fixed number of expansions per move,
//! with LSS-LRTA* steps until its search reaches the agent (see the real-time searches).
//!
//! Real-time searches plan a bounded amount, move, and learn values in a
//! [`LearnedHeuristic`] the caller keeps across trials; each call runs one trial and
//! returns a [`TrialResult`]:
//!
//! - [`lrta_star`] and [`rta_star`]: LRTA* and RTA*, a lookahead of one expansion.
//! - [`lss_lrta_star`]: LSS-LRTA*, an A* lookahead of `n` expansions and a Dijkstra update.
//! - [`lhb_lrta_star`]: the same agent with the limited-horizon Bellman update of Hadar et
//! al.; [`lhb_gbfs`] and [`lhb_bwa_star`] run it after a GBFS or a batch weighted A*
//! (BWAS) search phase; [`lhb_update`] is that update on its own, for offline learning.
//! - [`rtaa_star`]: RTAA*, the A* lookahead with a cheaper update.
//!
//! [`RealTimeDStar`] (Real-time D*) is a real-time agent for graphs whose edge costs change:
//! each [`RealTimeDStar::step`] splits a per-move expansion limit between D* Lite from the
//! goal and an LSS-LRTA* lookahead from the agent, and moves one edge, along a cheapest path
//! once D* Lite has reached the agent. [`RealTimeDStar::into_trial`] reports the run as a
//! [`TrialResult`].
//!
//! Costs are generic over [`Cost`]. For planning, `u32` is the intended default: action
//! costs are small integers and heuristics over them stay exact. [`Cost`], [`Heuristic`],
//! [`Goal`] and [`Budget`] come from `search-core` and are re-exported here; [`CostExt`]
//! adds the subtraction and float conversion a few searches need.
//!
//! ## Features
//!
//! - `float`: re-exports the checked float cost `NonNegF64` from `search-core`, and enables
//! the any-angle grid searches `theta_star` and `lazy_theta_star` and the Field D*
//! planner `FieldDStar` with its `CostGrid`, whose Euclidean costs are floats.
//! - `parallel`: multi-threaded searches; needs `std`. Enables hash-distributed A*,
//! `hda_star`, batches of independent queries on several threads, `solve_batch`, and
//! `hierarchical_a_star_par` and `hierarchical_a_star_par_multi`, which refine across
//! threads.
//!
//! ## Example
//!
//! ```
//! use heuristic_search::{Limits, Successors, dijkstra};
//!
//! /// A directed graph as adjacency lists of `(target, cost)` pairs.
//! struct Graph(Vec<Vec<(usize, u32)>>);
//!
//! impl Successors for Graph {
//! type State = usize;
//! type Action = usize;
//! type Cost = u32;
//!
//! fn successors(&self, state: &usize, mut emit: impl FnMut(usize, usize, u32)) {
//! for &(target, cost) in &self.0[*state] {
//! emit(target, target, cost);
//! }
//! }
//! }
//!
//! let graph = Graph(vec![vec![(1, 5), (2, 1)], vec![(3, 1)], vec![(1, 1)], vec![]]);
//! let result = dijkstra(&graph, 0, &|state: &usize| *state == 3, Limits::NONE);
//! let solution = result.solution().expect("3 is reachable");
//!
//! assert_eq!(solution.states, [0, 2, 1, 3]);
//! assert_eq!(solution.cost, 3);
//! ```
//!
//! ## Naming
//!
//! Searches are snake-case functions; every A* variant ends in `_star` ([`a_star`],
//! [`weighted_a_star`], [`ida_star`], [`ara_star`], [`ana_star`], [`mha_star`],
//! [`bae_star`]). Suffixes compose in this order: `_tt` (a variant of the algorithm),
//! `_par` (refinement across threads), `_multi` (several starts), `_meet` (a meet relation,
//! always with several starts), `_in` (in a caller's [`Workspace`]). Incremental planners
//! and other searches that keep state between calls are types ([`LpaStar`], [`DStarLite`],
//! [`AdStar`], `FieldDStar`, [`RealTimeDStar`], [`AStarSearch`], [`FlowField`]).
//!
//! See `docs/design.md` in the repository for the design.
//!
//! Repository: <https://github.com/sunsided/heuristic-search>
extern crate alloc;
extern crate std;
/// Doctests for the code examples in README.md (not part of the API).
pub use ;
pub use solve_batch;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use FlowField;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use NonNegF64;
pub use ;
pub use ;