heuristic_search/lazy.rs
1//! Lazy shortest paths for graphs whose true edge costs are expensive to compute
2//! ([`lazy_sp`], Dellin and Srinivasa 2016), with an [`EdgeEvaluator`] for the true costs.
3
4use alloc::vec::Vec;
5use core::hash::{BuildHasher, Hash};
6
7use hashbrown::{DefaultHashBuilder, HashTable};
8
9use search_core::{Budget, Goal, Heuristic};
10
11use crate::best_first::{GraphResult, a_star_multi};
12use crate::outcome::{Outcome, SearchResult, Solution, Stats};
13use crate::problem::Successors;
14
15/// Computes the true cost of an edge, which is expensive (a collision check, a
16/// simulation).
17///
18/// An edge is identified by its source state and its action, so the action must tell the
19/// outgoing edges of a state apart. [`lazy_sp`] evaluates each edge at most once.
20pub trait EdgeEvaluator<S, A, C> {
21 /// The true cost of the edge `from --action--> to`, or `None` if the edge is not
22 /// traversable after all.
23 fn evaluate(&mut self, from: &S, action: &A, to: &S) -> Option<C>;
24}
25
26impl<S, A, C, F: FnMut(&S, &A, &S) -> Option<C>> EdgeEvaluator<S, A, C> for F {
27 fn evaluate(&mut self, from: &S, action: &A, to: &S) -> Option<C> {
28 self(from, action, to)
29 }
30}
31
32/// Which unevaluated edges of a candidate path [`lazy_sp`] evaluates next.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
34pub enum EdgeSelector {
35 /// The first unevaluated edge from the start. Good when obstacles are near the start.
36 #[default]
37 Forward,
38 /// The last unevaluated edge, nearest the goal.
39 Reverse,
40 /// Forward and reverse in turn.
41 Alternate,
42 /// The unevaluated edge in the middle of the unevaluated ones; splits long uncertain
43 /// stretches first.
44 Bisection,
45 /// Every unevaluated edge of the path at once (lazy weighted A* in effect).
46 All,
47}
48
49/// Lazy shortest path (LazySP): the cheapest path while evaluating as few true edge costs
50/// as possible.
51///
52/// The graph's [`Successors`] report a cheap *lazy* cost for every edge. `LazySP` repeatedly
53/// finds the cheapest path with A*, using the true cost for edges already evaluated
54/// (dropping infeasible ones) and the lazy cost for the rest. If every edge on that path
55/// is evaluated, it is the answer. Otherwise the `selector` picks unevaluated edges of the
56/// path, `evaluator` computes their true costs, and the search repeats.
57///
58/// The solution is optimal if every lazy cost is at most the edge's true cost and the
59/// `heuristic` is admissible for the true costs. [`Stats::evaluations`] counts the true
60/// costs computed; the other counters add up all inner A* runs. The budget sees those
61/// running totals.
62///
63/// # Examples
64///
65/// ```
66/// use heuristic_search::{EdgeSelector, Limits, Successors, Zero, lazy_sp};
67///
68/// /// A diamond: `0 -> 1 -> 3` and `0 -> 2 -> 3`, every edge lazily costing 1.
69/// struct Diamond;
70///
71/// impl Successors for Diamond {
72/// type State = u8;
73/// type Action = u8;
74/// type Cost = u32;
75///
76/// fn successors(&self, n: &u8, mut emit: impl FnMut(u8, u8, u32)) {
77/// let targets: &[u8] = match n {
78/// 0 => &[1, 2],
79/// 1 | 2 => &[3],
80/// _ => &[],
81/// };
82/// for &target in targets {
83/// emit(target, target, 1);
84/// }
85/// }
86/// }
87///
88/// // The edge 0 -> 1 is blocked; everything else costs 1.
89/// let evaluate = |from: &u8, to: &u8, _: &u8| ((*from, *to) != (0, 1)).then_some(1);
90/// let result = lazy_sp(&Diamond, 0, &|n: &u8| *n == 3, Zero, evaluate, EdgeSelector::Forward, Limits::NONE);
91///
92/// assert_eq!(result.solution().map(|s| s.states.clone()), Some(vec![0, 2, 3]));
93/// assert_eq!(result.stats.evaluations, 3);
94/// ```
95pub fn lazy_sp<G, T, H, E>(
96 graph: &G,
97 start: G::State,
98 goal: &T,
99 heuristic: H,
100 evaluator: E,
101 selector: EdgeSelector,
102 budget: impl Budget<Stats>,
103) -> GraphResult<G>
104where
105 G: Successors,
106 G::State: Clone + Hash + Eq,
107 G::Action: Clone + Hash + Eq,
108 T: Goal<G::State> + ?Sized,
109 H: Heuristic<G::State, G::Cost>,
110 E: EdgeEvaluator<G::State, G::Action, G::Cost>,
111{
112 lazy_sp_multi(graph, [start], goal, heuristic, evaluator, selector, budget)
113}
114
115/// [`lazy_sp`] from several start states at once.
116///
117/// Every start has path cost zero; each round runs [`a_star_multi`] from
118/// all of them over the lazily evaluated graph. Repeated starts count once, an empty set of
119/// starts finds nothing, and a start that is a goal is returned without any evaluation.
120///
121/// # Examples
122///
123/// ```
124/// use heuristic_search::{Limits, Successors, Zero, lazy_sp_multi, EdgeSelector};
125///
126/// /// Counting up by one or two; lazily every edge costs 1.
127/// struct Up;
128///
129/// impl Successors for Up {
130/// type State = u32;
131/// type Action = u32;
132/// type Cost = u32;
133///
134/// fn successors(&self, n: &u32, mut emit: impl FnMut(u32, u32, u32)) {
135/// emit(1, n + 1, 1);
136/// emit(2, n + 2, 1);
137/// }
138/// }
139///
140/// // Every edge out of 6 truly costs 10; the others cost 1. Start 6 looks closest, but
141/// // the cheapest path starts at 3 and jumps over 6.
142/// let evaluate = |from: &u32, _: &u32, _: &u32| Some(if *from == 6 { 10 } else { 1 });
143/// let result = lazy_sp_multi(&Up, [6, 3], &|n: &u32| *n == 8, Zero, evaluate, EdgeSelector::All, Limits::NONE);
144///
145/// assert_eq!(result.solution().map(|s| s.cost), Some(3));
146/// assert_eq!(result.solution().map(|s| s.states[0]), Some(3));
147/// ```
148#[expect(
149 clippy::similar_names,
150 reason = "`starts` is the parameter name of every `*_multi` search"
151)]
152pub fn lazy_sp_multi<G, T, H, E>(
153 graph: &G,
154 starts: impl IntoIterator<Item = G::State>,
155 goal: &T,
156 mut heuristic: H,
157 mut evaluator: E,
158 selector: EdgeSelector,
159 mut budget: impl Budget<Stats>,
160) -> GraphResult<G>
161where
162 G: Successors,
163 G::State: Clone + Hash + Eq,
164 G::Action: Clone + Hash + Eq,
165 T: Goal<G::State> + ?Sized,
166 H: Heuristic<G::State, G::Cost>,
167 E: EdgeEvaluator<G::State, G::Action, G::Cost>,
168{
169 let starts: Vec<G::State> = starts.into_iter().collect();
170 let mut view = Evaluated {
171 graph,
172 edges: HashTable::new(),
173 hasher: DefaultHashBuilder::default(),
174 };
175 let mut stats = Stats::default();
176
177 for round in 0_usize.. {
178 let inner = a_star_multi(
179 &view,
180 starts.iter().cloned(),
181 goal,
182 &mut heuristic,
183 |inner: &Stats| budget.exhausted(&stats.plus(*inner)),
184 );
185 stats = stats.plus(inner.stats);
186
187 let solution = match inner.outcome {
188 Outcome::Found(solution) => solution,
189 outcome => return SearchResult { outcome, stats },
190 };
191
192 let pending = view.unevaluated(&solution);
193 if pending.is_empty() {
194 return SearchResult {
195 outcome: Outcome::Found(solution),
196 stats,
197 };
198 }
199
200 for index in select(selector, &pending, round) {
201 let (from, action, to) = (
202 &solution.states[index],
203 &solution.actions[index],
204 &solution.states[index + 1],
205 );
206 let cost = evaluator.evaluate(from, action, to);
207 stats.evaluations += 1;
208 view.record(from.clone(), action.clone(), cost);
209 }
210 }
211
212 unreachable!("the rounds never run out")
213}
214
215/// The indices into `pending` (edge indices along the path, ascending, never empty) that
216/// `selector` evaluates in round `round`.
217fn select(selector: EdgeSelector, pending: &[usize], round: usize) -> Vec<usize> {
218 let from_start = match selector {
219 EdgeSelector::Forward => true,
220 EdgeSelector::Reverse => false,
221 EdgeSelector::Alternate => round % 2 == 0,
222 EdgeSelector::Bisection => return alloc::vec![pending[pending.len() / 2]],
223 EdgeSelector::All => return pending.to_vec(),
224 };
225
226 let end = if from_start {
227 pending.first()
228 } else {
229 pending.last()
230 };
231
232 end.copied().into_iter().collect()
233}
234
235/// An evaluated edge: source, action and true cost (`None` if infeasible).
236type Evaluation<G> = (
237 <G as Successors>::State,
238 <G as Successors>::Action,
239 Option<<G as Successors>::Cost>,
240);
241
242/// What is known about an edge's cost.
243enum Known<C> {
244 /// Not evaluated yet; only the lazy cost is known.
245 Lazy,
246 /// Evaluated with this true cost.
247 True(C),
248 /// Evaluated and not traversable.
249 Infeasible,
250}
251
252/// The graph as `LazySP`'s inner A* sees it: true costs for evaluated edges, lazy costs for
253/// the rest, and no infeasible edges.
254struct Evaluated<'a, G: Successors> {
255 /// The graph with lazy costs.
256 graph: &'a G,
257 /// Every evaluated edge as `(source, action, true cost)`; `None` marks an infeasible
258 /// edge. Hashed by `(source, action)`.
259 edges: HashTable<Evaluation<G>>,
260 /// Hashes `(source, action)` pairs for [`Evaluated::edges`].
261 hasher: DefaultHashBuilder,
262}
263
264impl<G> Evaluated<'_, G>
265where
266 G: Successors,
267 G::State: Hash + Eq,
268 G::Action: Hash + Eq,
269{
270 /// What is known about the cost of the edge `(from, action)`.
271 fn lookup(&self, from: &G::State, action: &G::Action) -> Known<G::Cost> {
272 let hash = self.hasher.hash_one((from, action));
273 let found = self.edges.find(hash, |(s, a, _)| s == from && a == action);
274
275 match found {
276 None => Known::Lazy,
277 Some((_, _, Some(cost))) => Known::True(*cost),
278 Some((_, _, None)) => Known::Infeasible,
279 }
280 }
281
282 /// Records the true cost of the edge `(from, action)`.
283 fn record(&mut self, from: G::State, action: G::Action, cost: Option<G::Cost>) {
284 let hash = self.hasher.hash_one((&from, &action));
285 let hasher = &self.hasher;
286
287 self.edges
288 .insert_unique(hash, (from, action, cost), |(s, a, _)| {
289 hasher.hash_one((s, a))
290 });
291 }
292
293 /// The indices of the edges of `path` that are not evaluated yet, ascending.
294 fn unevaluated(&self, path: &Solution<G::State, G::Action, G::Cost>) -> Vec<usize> {
295 path.actions
296 .iter()
297 .enumerate()
298 .filter(|(index, action)| {
299 matches!(self.lookup(&path.states[*index], action), Known::Lazy)
300 })
301 .map(|(index, _)| index)
302 .collect()
303 }
304}
305
306impl<G> Successors for Evaluated<'_, G>
307where
308 G: Successors,
309 G::State: Hash + Eq,
310 G::Action: Hash + Eq,
311{
312 type State = G::State;
313 type Action = G::Action;
314 type Cost = G::Cost;
315
316 fn successors(&self, state: &G::State, mut emit: impl FnMut(G::Action, G::State, G::Cost)) {
317 self.graph.successors(state, |action, next, lazy| {
318 match self.lookup(state, &action) {
319 Known::Lazy => emit(action, next, lazy),
320 Known::True(cost) => emit(action, next, cost),
321 Known::Infeasible => {}
322 }
323 });
324 }
325}