Skip to main content

heuristic_search/
dynamic.rs

1//! Incremental search on graphs whose edge costs change: [`LpaStar`] (Lifelong Planning
2//! A*), [`DStarLite`] and [`AdStar`] (Anytime D*), over a [`DynamicGraph`].
3//!
4//! Both keep their search tree between calls. After the caller changes edge costs in the
5//! graph, it reports each changed edge (`edge_changed`) and asks for a new path
6//! (`compute`); only the part of the tree the changes affect is repaired. Edges are
7//! identified by their endpoints; parallel edges count with their cheapest cost.
8//!
9//! | Planner        | Searches          | Fixed       | Can move     |
10//! | -------------- | ----------------- | ----------- | ------------ |
11//! | [`LpaStar`]    | start to goal     | both ends   | nothing      |
12//! | [`DStarLite`]  | goal to start     | the goal    | the start    |
13//! | [`AdStar`]     | goal to start     | the goal    | the start    |
14//!
15//! [`AdStar`] is the anytime variant of [`DStarLite`]: it inflates the heuristic by a
16//! weight the caller lowers over time. [`LpaStarMulti`], [`DStarLiteMulti`] and
17//! [`AdStarMulti`] take several fixed starts, through a virtual super-start.
18//!
19//! `FieldDStar` (feature `float`) is D* Lite over the corners of a grid with per-cell costs
20//! rather than over a [`DynamicGraph`]: its `rhs` interpolates along cell edges, and its
21//! paths run through points on them.
22//!
23//! Both need strictly positive edge costs, as in the papers: a zero-cost cycle can keep
24//! supporting its own stale distances after the edge that made them real disappears. And
25//! both need a consistent heuristic `h(a, b)` that estimates the cost from `a` to `b`, for
26//! the costs at every point in time; `|_, _| 0` always works.
27
28#[cfg(feature = "float")]
29mod field;
30mod incremental;
31mod multi;
32
33use core::hash::Hash;
34
35use search_core::{Budget, Cost};
36
37use crate::cost::Weight;
38use crate::outcome::{SearchResult, Stats};
39#[cfg(feature = "float")]
40pub use field::{FieldDStar, FieldResult};
41use incremental::Incremental;
42pub use multi::{AdStarMulti, DStarLiteMulti, LpaStarMulti};
43
44/// A graph with stable vertices whose edge costs may change between searches.
45///
46/// Both directions must agree and reflect the current costs: `to` is reported as a
47/// successor of `from` with cost `c` exactly when `from` is reported as a predecessor of
48/// `to` with cost `c`.
49pub trait DynamicGraph {
50    /// A vertex. Cloned and hashed into the planner's tables.
51    type Vertex: Clone + Hash + Eq;
52    /// An edge cost. Must be strictly positive: [`LpaStar`] and [`DStarLite`] can keep
53    /// stale distances alive around a zero-cost cycle.
54    type Cost: Cost;
55
56    /// Calls `emit(to, cost)` for every edge leaving `vertex`.
57    fn successors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost));
58
59    /// Calls `emit(from, cost)` for every edge entering `vertex`.
60    fn predecessors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost));
61}
62
63/// The result of an incremental search: a path of vertices. Edges carry no labels, so the
64/// solution's actions are `()`.
65pub type DynamicResult<G> =
66    SearchResult<<G as DynamicGraph>::Vertex, (), <G as DynamicGraph>::Cost>;
67
68/// Lifelong Planning A* (LPA*, Koenig, Likhachev and Furcy 2004): A* that repairs its
69/// search tree after edge-cost changes instead of starting over.
70///
71/// The first [`LpaStar::compute`] costs about as much as A*. After the caller changes the
72/// graph and reports every changed edge with [`LpaStar::edge_changed`], the next
73/// `compute` re-expands only vertices whose distance from the start may have changed.
74/// Returns cheapest paths with a consistent `heuristic`, where `heuristic(v, goal)`
75/// estimates the cost from `v` to the goal.
76///
77/// # Examples
78///
79/// ```
80/// use heuristic_search::{DynamicGraph, Limits, LpaStar};
81///
82/// /// A directed graph as `(from, to, cost)` triples.
83/// struct Edges(Vec<(u8, u8, u32)>);
84///
85/// impl DynamicGraph for Edges {
86///     type Vertex = u8;
87///     type Cost = u32;
88///
89///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
90///         self.0.iter().filter(|e| e.0 == *v).for_each(|e| emit(e.1, e.2));
91///     }
92///
93///     fn predecessors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
94///         self.0.iter().filter(|e| e.1 == *v).for_each(|e| emit(e.0, e.2));
95///     }
96/// }
97///
98/// let mut graph = Edges(vec![(0, 1, 1), (1, 3, 1), (0, 2, 2), (2, 3, 2)]);
99/// let mut planner = LpaStar::new(&graph, 0, 3, |_: &u8, _: &u8| 0);
100/// assert_eq!(planner.compute(&graph, Limits::NONE).solution().map(|s| s.cost), Some(2));
101///
102/// // The edge 1 -> 3 gets expensive; report it and repair.
103/// graph.0[1].2 = 10;
104/// planner.edge_changed(&graph, &1, &3);
105/// let solution = planner.compute(&graph, Limits::NONE).into_solution().expect("3 is reachable");
106/// assert_eq!(solution.states, [0, 2, 3]);
107/// assert_eq!(solution.cost, 4);
108/// ```
109pub struct LpaStar<V, C, D> {
110    /// The incremental search from the start.
111    core: Incremental<V, C, D>,
112}
113
114impl<V, C, D> LpaStar<V, C, D>
115where
116    V: Clone + Hash + Eq,
117    C: Cost,
118    D: FnMut(&V, &V) -> C,
119{
120    /// Prepares a search from `start` to `goal`. Nothing is expanded until
121    /// [`LpaStar::compute`].
122    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
123        _graph: &G,
124        start: V,
125        goal: V,
126        heuristic: D,
127    ) -> Self {
128        Self {
129            core: Incremental::new(true, start, goal, heuristic, None),
130        }
131    }
132
133    /// Repairs the search tree after the latest changes and returns a cheapest path, or
134    /// [`Outcome::Unsolvable`](crate::Outcome::Unsolvable) if the goal is unreachable.
135    ///
136    /// The budget and the returned stats cover this call only; see [`LpaStar::stats`] for
137    /// the totals. A search stopped by its budget continues where it stopped on the next
138    /// call.
139    pub fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
140        &mut self,
141        graph: &G,
142        budget: impl Budget<Stats>,
143    ) -> DynamicResult<G> {
144        self.core.compute(graph, budget)
145    }
146
147    /// Reports that the edge `from -> to` changed its cost, appeared or disappeared in
148    /// `graph`, which must already show the new state.
149    pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
150        &mut self,
151        graph: &G,
152        from: &V,
153        to: &V,
154    ) {
155        self.core.edge_changed(graph, from, to);
156    }
157
158    /// Counters over every [`LpaStar::compute`] so far.
159    #[must_use]
160    pub fn stats(&self) -> Stats {
161        self.core.total
162    }
163}
164
165/// D* Lite (Koenig and Likhachev 2002): incremental search towards a fixed goal from a
166/// start that moves, as when a robot replans while it drives and discovers obstacles.
167///
168/// Searches backwards from the goal, so the tree stays valid as the start moves. Move the
169/// start with [`DStarLite::move_start`], report changed edges with
170/// [`DStarLite::edge_changed`], then [`DStarLite::compute`] a path from the current start.
171/// Returns cheapest paths with a consistent `heuristic`, where `heuristic(start, v)`
172/// estimates the cost from the start to `v`.
173///
174/// # Examples
175///
176/// ```
177/// use heuristic_search::{DStarLite, DynamicGraph, Limits};
178///
179/// /// A directed graph as `(from, to, cost)` triples.
180/// struct Edges(Vec<(u8, u8, u32)>);
181///
182/// impl DynamicGraph for Edges {
183///     type Vertex = u8;
184///     type Cost = u32;
185///
186///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
187///         self.0.iter().filter(|e| e.0 == *v).for_each(|e| emit(e.1, e.2));
188///     }
189///
190///     fn predecessors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
191///         self.0.iter().filter(|e| e.1 == *v).for_each(|e| emit(e.0, e.2));
192///     }
193/// }
194///
195/// let mut graph = Edges(vec![(0, 1, 1), (1, 2, 1), (2, 3, 1), (1, 3, 5)]);
196/// let mut planner = DStarLite::new(&graph, 0, 3, |_: &u8, _: &u8| 0);
197/// assert_eq!(planner.compute(&graph, Limits::NONE).solution().map(|s| s.cost), Some(3));
198///
199/// // Drive to 1, then find 2 -> 3 blocked.
200/// planner.move_start(1);
201/// graph.0.remove(2);
202/// planner.edge_changed(&graph, &2, &3);
203/// let solution = planner.compute(&graph, Limits::NONE).into_solution().expect("3 is reachable");
204/// assert_eq!(solution.states, [1, 3]);
205/// assert_eq!(solution.cost, 5);
206/// ```
207pub struct DStarLite<V, C, D> {
208    /// The incremental search from the goal.
209    core: Incremental<V, C, D>,
210}
211
212impl<V, C, D> DStarLite<V, C, D>
213where
214    V: Clone + Hash + Eq,
215    C: Cost,
216    D: FnMut(&V, &V) -> C,
217{
218    /// Prepares a search from `start` to `goal`. Nothing is expanded until
219    /// [`DStarLite::compute`].
220    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
221        _graph: &G,
222        start: V,
223        goal: V,
224        heuristic: D,
225    ) -> Self {
226        Self {
227            core: Incremental::new(false, goal, start, heuristic, None),
228        }
229    }
230
231    /// Repairs the search tree after the latest changes and returns a cheapest path from
232    /// the current start, or [`Outcome::Unsolvable`](crate::Outcome::Unsolvable).
233    ///
234    /// The budget and the returned stats cover this call only; see [`DStarLite::stats`]
235    /// for the totals.
236    pub fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
237        &mut self,
238        graph: &G,
239        budget: impl Budget<Stats>,
240    ) -> DynamicResult<G> {
241        self.core.compute(graph, budget)
242    }
243
244    /// Moves the start to `start`, typically one step along the last path.
245    pub fn move_start(&mut self, start: V) {
246        self.core.move_target(start);
247    }
248
249    /// Reports that the edge `from -> to` changed its cost, appeared or disappeared in
250    /// `graph`, which must already show the new state.
251    pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
252        &mut self,
253        graph: &G,
254        from: &V,
255        to: &V,
256    ) {
257        self.core.edge_changed(graph, from, to);
258    }
259
260    /// Counters over every [`DStarLite::compute`] so far.
261    #[must_use]
262    pub fn stats(&self) -> Stats {
263        self.core.total
264    }
265}
266
267/// Anytime Dynamic A* (AD*, Likhachev, Ferguson, Gordon, Stentz and Thrun 2005): D* Lite
268/// with an inflated heuristic, so a first path comes fast and improves as time allows,
269/// while the start moves and edges change.
270///
271/// Each [`AdStar::compute`] is one iteration: it returns a path that costs at most the
272/// current weight times the optimum (with a consistent `heuristic`). Lower the weight with
273/// [`AdStar::set_weight`] between calls to improve the path, ending with
274/// [`Weight::ONE`](crate::Weight::ONE) for an optimal one; move the start and report
275/// changed edges as with [`DStarLite`]. After large changes, raising the weight again
276/// gets a new path faster. Vertices that become inconsistent after their expansion in an
277/// iteration wait for the next one (AD*'s `INCONS`). Start moves shift keys by D* Lite's
278/// `km`; only lowering the weight re-keys the whole queue, which is linear in the vertices
279/// seen so far.
280///
281/// # Panics
282///
283/// [`AdStar::new`] and [`AdStar::set_weight`] panic if the weight is below `1`.
284///
285/// # Examples
286///
287/// ```
288/// use heuristic_search::{AdStar, DynamicGraph, Limits, Weight};
289///
290/// /// A line `0..=9`; each step moves one to the left or right at cost 1.
291/// struct Line;
292///
293/// impl DynamicGraph for Line {
294///     type Vertex = u8;
295///     type Cost = u32;
296///
297///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
298///         if *v > 0 {
299///             emit(v - 1, 1);
300///         }
301///         if *v < 9 {
302///             emit(v + 1, 1);
303///         }
304///     }
305///
306///     fn predecessors(&self, v: &u8, emit: impl FnMut(u8, u32)) {
307///         self.successors(v, emit);
308///     }
309/// }
310///
311/// let distance = |a: &u8, b: &u8| u32::from(a.abs_diff(*b));
312/// let mut planner = AdStar::new(&Line, 2, 9, distance, Weight::integer(3));
313/// assert_eq!(planner.compute(&Line, Limits::NONE).solution().map(|s| s.cost), Some(7));
314///
315/// planner.set_weight(Weight::ONE);
316/// assert_eq!(planner.compute(&Line, Limits::NONE).solution().map(|s| s.cost), Some(7));
317/// ```
318pub struct AdStar<V, C, D> {
319    /// The incremental search from the goal, with AD*'s anytime state.
320    core: Incremental<V, C, D>,
321}
322
323impl<V, C, D> AdStar<V, C, D>
324where
325    V: Clone + Hash + Eq,
326    C: Cost,
327    D: FnMut(&V, &V) -> C,
328{
329    /// Prepares a search from `start` to `goal` with initial inflation `weight`. Nothing
330    /// is expanded until [`AdStar::compute`].
331    ///
332    /// # Panics
333    ///
334    /// Panics if `weight` is below `1`.
335    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
336        _graph: &G,
337        start: V,
338        goal: V,
339        heuristic: D,
340        weight: Weight,
341    ) -> Self {
342        assert_weight(weight);
343
344        Self {
345            core: Incremental::new(false, goal, start, heuristic, Some(weight)),
346        }
347    }
348
349    /// Runs one iteration with the current weight and returns a path from the current
350    /// start within that weight of the optimum, or
351    /// [`Outcome::Unsolvable`](crate::Outcome::Unsolvable).
352    ///
353    /// The budget and the returned stats cover this call only; see [`AdStar::stats`] for
354    /// the totals.
355    pub fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
356        &mut self,
357        graph: &G,
358        budget: impl Budget<Stats>,
359    ) -> DynamicResult<G> {
360        self.core.compute(graph, budget)
361    }
362
363    /// Sets the inflation for the next iterations.
364    ///
365    /// # Panics
366    ///
367    /// Panics if `weight` is below `1`.
368    pub fn set_weight(&mut self, weight: Weight) {
369        assert_weight(weight);
370        self.core.set_weight(weight);
371    }
372
373    /// The current inflation.
374    #[must_use]
375    pub fn weight(&self) -> Weight {
376        self.core.weight()
377    }
378
379    /// Moves the start to `start`, typically one step along the last path.
380    pub fn move_start(&mut self, start: V) {
381        self.core.move_target(start);
382    }
383
384    /// Reports that the edge `from -> to` changed its cost, appeared or disappeared in
385    /// `graph`, which must already show the new state.
386    pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
387        &mut self,
388        graph: &G,
389        from: &V,
390        to: &V,
391    ) {
392        self.core.edge_changed(graph, from, to);
393    }
394
395    /// Counters over every [`AdStar::compute`] so far.
396    #[must_use]
397    pub fn stats(&self) -> Stats {
398        self.core.total
399    }
400}
401
402/// Panics unless `weight` is at least `1`.
403pub(crate) fn assert_weight(weight: Weight) {
404    assert!(
405        weight.numerator() >= weight.denominator(),
406        "AD* weight must be at least 1"
407    );
408}