heuristic-search 0.2.0

Explicit-state heuristic graph search: A*, weighted and anytime, bounded-suboptimal, bidirectional, incremental and real-time search
Documentation
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Several starts for the incremental planners: [`LpaStarMulti`], [`DStarLiteMulti`] and
//! [`AdStarMulti`] search from a virtual super-start joined to every start by a zero-cost
//! edge, and strip it from the returned path.
//!
//! The starts are fixed for the planner's lifetime: the super-start's heuristic is the
//! minimum over the starts, so changing them would change keys already queued. Edge changes
//! are reported as for the single-start planners.

use alloc::vec::Vec;
use core::hash::Hash;

use search_core::{Budget, Cost};

use crate::cost::Weight;
use crate::dynamic::incremental::{Estimate, Incremental};
use crate::dynamic::{DynamicGraph, DynamicResult, assert_weight};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};

/// A vertex of the graph, or the virtual super-start.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) enum Rooted<V> {
    /// The super-start, with a zero-cost edge to every start.
    Root,
    /// A vertex of the graph.
    Vertex(V),
}

/// The graph with the super-start added: edges `Root -> start` of cost zero.
struct RootedGraph<'g, G, V> {
    /// The real graph.
    graph: &'g G,
    /// The starts the super-start joins.
    starts: &'g [V],
}

impl<G, V> DynamicGraph for RootedGraph<'_, G, V>
where
    G: DynamicGraph<Vertex = V>,
    V: Clone + Hash + Eq,
{
    type Vertex = Rooted<V>;
    type Cost = G::Cost;

    fn successors(&self, vertex: &Rooted<V>, mut emit: impl FnMut(Rooted<V>, G::Cost)) {
        match vertex {
            Rooted::Root => {
                for start in self.starts {
                    emit(Rooted::Vertex(start.clone()), G::Cost::ZERO);
                }
            }
            Rooted::Vertex(vertex) => self
                .graph
                .successors(vertex, |next, cost| emit(Rooted::Vertex(next), cost)),
        }
    }

    fn predecessors(&self, vertex: &Rooted<V>, mut emit: impl FnMut(Rooted<V>, G::Cost)) {
        if let Rooted::Vertex(vertex) = vertex {
            self.graph.predecessors(vertex, |previous, cost| {
                emit(Rooted::Vertex(previous), cost);
            });
            if self.starts.contains(vertex) {
                emit(Rooted::Root, G::Cost::ZERO);
            }
        }
    }
}

/// The heuristic with the super-start: from it, the minimum over the starts (consistent if
/// the heuristic is); towards it, zero.
struct RootedH<D, V> {
    /// The heuristic between real vertices.
    inner: D,
    /// The starts, for estimates from the super-start.
    starts: Vec<V>,
}

impl<V, C: Cost, D: FnMut(&V, &V) -> C> Estimate<Rooted<V>, C> for RootedH<D, V> {
    fn estimate(&mut self, from: &Rooted<V>, to: &Rooted<V>) -> C {
        match (from, to) {
            (Rooted::Vertex(from), Rooted::Vertex(to)) => (self.inner)(from, to),
            (Rooted::Root, Rooted::Vertex(to)) => {
                let inner = &mut self.inner;
                self.starts
                    .iter()
                    .map(|start| inner(start, to))
                    .min()
                    .unwrap_or(C::ZERO)
            }
            (_, Rooted::Root) => C::ZERO,
        }
    }
}

/// The incremental search over the rooted graph, shared by the three planners.
struct Rooting<V, C, D> {
    /// The search; its source or target is the super-start.
    core: Incremental<Rooted<V>, C, RootedH<D, V>>,
    /// The starts, deduplicated, in order of first appearance.
    starts: Vec<V>,
}

impl<V, C, D> Rooting<V, C, D>
where
    V: Clone + Hash + Eq,
    C: Cost,
    D: FnMut(&V, &V) -> C,
{
    /// Prepares the search: `forward` for LPA* (from the super-start), else D* Lite or
    /// AD* (towards it), with `weight` for AD*.
    fn new(
        forward: bool,
        starts: impl IntoIterator<Item = V>,
        goal: V,
        heuristic: D,
        weight: Option<Weight>,
    ) -> Self {
        let mut unique: Vec<V> = Vec::new();
        for start in starts {
            if !unique.contains(&start) {
                unique.push(start);
            }
        }

        let estimate = RootedH {
            inner: heuristic,
            starts: unique.clone(),
        };
        let goal = Rooted::Vertex(goal);
        let mut core = if forward {
            Incremental::new(true, Rooted::Root, goal, estimate, weight)
        } else {
            Incremental::new(false, goal, Rooted::Root, estimate, weight)
        };
        // The super-start's edges cost zero, so its key can tie with a start's.
        core.settle_ties = true;

        Self {
            core,
            starts: unique,
        }
    }

    /// Repairs the tree and returns a path from the best start.
    fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
        &mut self,
        graph: &G,
        budget: impl Budget<Stats>,
    ) -> DynamicResult<G> {
        let rooted = RootedGraph {
            graph,
            starts: &self.starts,
        };

        unroot(self.core.compute(&rooted, budget))
    }

    /// Reports a changed edge of the real graph.
    fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(&mut self, graph: &G, from: &V, to: &V) {
        let rooted = RootedGraph {
            graph,
            starts: &self.starts,
        };
        let (from, to) = (Rooted::Vertex(from.clone()), Rooted::Vertex(to.clone()));

        self.core.edge_changed(&rooted, &from, &to);
    }
}

/// The result without the super-start at the head of the path.
fn unroot<V, C>(result: SearchResult<Rooted<V>, (), C>) -> SearchResult<V, (), C> {
    let outcome = match result.outcome {
        Outcome::Found(solution) => {
            let states: Vec<V> = solution
                .states
                .into_iter()
                .filter_map(|vertex| match vertex {
                    Rooted::Vertex(vertex) => Some(vertex),
                    Rooted::Root => None,
                })
                .collect();

            Outcome::Found(Solution {
                actions: alloc::vec![(); states.len().saturating_sub(1)],
                states,
                cost: solution.cost,
            })
        }
        Outcome::Unsolvable => Outcome::Unsolvable,
        Outcome::LimitReached => Outcome::LimitReached,
        Outcome::Cutoff => Outcome::Cutoff,
    };

    SearchResult {
        outcome,
        stats: result.stats,
    }
}

/// Generates a multi-start planner type over [`Rooting`]; `$forward` picks LPA*.
macro_rules! multi_planner {
    ($(#[$doc:meta])* $name:ident, $single:literal, $forward:expr) => {
        $(#[$doc])*
        pub struct $name<V, C, D> {
            /// The rooted search.
            rooting: Rooting<V, C, D>,
        }

        impl<V, C, D> $name<V, C, D>
        where
            V: Clone + Hash + Eq,
            C: Cost,
            D: FnMut(&V, &V) -> C,
        {
            #[doc = concat!("Repairs the tree after the latest changes and returns a path from the best start, as [`", $single, "`] does for one.")]
            pub fn compute<G: DynamicGraph<Vertex = V, Cost = C>>(
                &mut self,
                graph: &G,
                budget: impl Budget<Stats>,
            ) -> DynamicResult<G> {
                self.rooting.compute(graph, budget)
            }

            /// Reports that the edge `from -> to` changed its cost, appeared or disappeared
            /// in `graph`, which must already show the new state.
            pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
                &mut self,
                graph: &G,
                from: &V,
                to: &V,
            ) {
                self.rooting.edge_changed(graph, from, to);
            }

            /// Counters over every `compute` so far.
            #[must_use]
            pub fn stats(&self) -> Stats {
                self.rooting.core.total
            }

            /// The starts, deduplicated, in order of first appearance.
            #[must_use]
            pub fn starts(&self) -> &[V] {
                &self.rooting.starts
            }
        }
    };
}

multi_planner!(
    /// [`LpaStar`](crate::LpaStar) from several fixed starts to one goal: the cheapest path
    /// from any start, repaired after edge changes.
    ///
    /// # Examples
    ///
    /// ```
    /// use heuristic_search::{DynamicGraph, Limits, LpaStarMulti};
    ///
    /// /// A line `0 - 1 - ... - 9` with unit edges both ways.
    /// struct Line;
    ///
    /// impl DynamicGraph for Line {
    ///     type Vertex = u8;
    ///     type Cost = u32;
    ///
    ///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
    ///         if *v < 9 {
    ///             emit(v + 1, 1);
    ///         }
    ///         if *v > 0 {
    ///             emit(v - 1, 1);
    ///         }
    ///     }
    ///
    ///     fn predecessors(&self, v: &u8, emit: impl FnMut(u8, u32)) {
    ///         self.successors(v, emit);
    ///     }
    /// }
    ///
    /// let distance = |a: &u8, b: &u8| u32::from(a.abs_diff(*b));
    /// let mut planner = LpaStarMulti::new(&Line, [0, 7, 2], 9, distance);
    /// let path = planner.compute(&Line, Limits::NONE).into_solution().expect("reachable");
    ///
    /// assert_eq!(path.states, [7, 8, 9]);
    /// assert_eq!(path.cost, 2);
    /// ```
    LpaStarMulti,
    "crate::LpaStar::compute",
    true
);

multi_planner!(
    /// [`DStarLite`](crate::DStarLite) from several fixed starts: the search runs from the
    /// goal towards a super-start joined to every start, so it repairs the cheapest path
    /// from any start after edge changes. The starts cannot move.
    ///
    /// # Examples
    ///
    /// ```
    /// use heuristic_search::{DStarLiteMulti, DynamicGraph, Limits};
    ///
    /// /// A line `0 - 1 - ... - 9` with unit edges both ways.
    /// struct Line;
    ///
    /// impl DynamicGraph for Line {
    ///     type Vertex = u8;
    ///     type Cost = u32;
    ///
    ///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
    ///         if *v < 9 {
    ///             emit(v + 1, 1);
    ///         }
    ///         if *v > 0 {
    ///             emit(v - 1, 1);
    ///         }
    ///     }
    ///
    ///     fn predecessors(&self, v: &u8, emit: impl FnMut(u8, u32)) {
    ///         self.successors(v, emit);
    ///     }
    /// }
    ///
    /// let distance = |a: &u8, b: &u8| u32::from(a.abs_diff(*b));
    /// let mut planner = DStarLiteMulti::new(&Line, [0, 4], 6, distance);
    /// let path = planner.compute(&Line, Limits::NONE).into_solution().expect("reachable");
    ///
    /// assert_eq!(path.states, [4, 5, 6]);
    /// ```
    DStarLiteMulti,
    "crate::DStarLite::compute",
    false
);

multi_planner!(
    /// [`AdStar`](crate::AdStar) from several fixed starts: each `compute` returns a path
    /// from the best start within the current weight of the optimum. The starts cannot
    /// move.
    ///
    /// # Examples
    ///
    /// ```
    /// use heuristic_search::{AdStarMulti, DynamicGraph, Limits, Weight};
    ///
    /// /// A line `0 - 1 - ... - 9` with unit edges both ways.
    /// struct Line;
    ///
    /// impl DynamicGraph for Line {
    ///     type Vertex = u8;
    ///     type Cost = u32;
    ///
    ///     fn successors(&self, v: &u8, mut emit: impl FnMut(u8, u32)) {
    ///         if *v < 9 {
    ///             emit(v + 1, 1);
    ///         }
    ///         if *v > 0 {
    ///             emit(v - 1, 1);
    ///         }
    ///     }
    ///
    ///     fn predecessors(&self, v: &u8, emit: impl FnMut(u8, u32)) {
    ///         self.successors(v, emit);
    ///     }
    /// }
    ///
    /// let distance = |a: &u8, b: &u8| u32::from(a.abs_diff(*b));
    /// let mut planner = AdStarMulti::new(&Line, [0, 4], 6, distance, Weight::integer(2));
    /// assert!(planner.compute(&Line, Limits::NONE).solution().is_some());
    ///
    /// planner.set_weight(Weight::ONE);
    /// let path = planner.compute(&Line, Limits::NONE).into_solution().expect("reachable");
    /// assert_eq!(path.cost, 2);
    /// ```
    AdStarMulti,
    "crate::AdStar::compute",
    false
);

impl<V, C, D> LpaStarMulti<V, C, D>
where
    V: Clone + Hash + Eq,
    C: Cost,
    D: FnMut(&V, &V) -> C,
{
    /// Prepares a search from `starts` to `goal`. Nothing is expanded until
    /// [`LpaStarMulti::compute`]. No starts means the goal is unreachable.
    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
        _graph: &G,
        starts: impl IntoIterator<Item = V>,
        goal: V,
        heuristic: D,
    ) -> Self {
        Self {
            rooting: Rooting::new(true, starts, goal, heuristic, None),
        }
    }
}

impl<V, C, D> DStarLiteMulti<V, C, D>
where
    V: Clone + Hash + Eq,
    C: Cost,
    D: FnMut(&V, &V) -> C,
{
    /// Prepares a search from `starts` to `goal`. Nothing is expanded until
    /// [`DStarLiteMulti::compute`]. No starts means the goal is unreachable.
    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
        _graph: &G,
        starts: impl IntoIterator<Item = V>,
        goal: V,
        heuristic: D,
    ) -> Self {
        Self {
            rooting: Rooting::new(false, starts, goal, heuristic, None),
        }
    }
}

impl<V, C, D> AdStarMulti<V, C, D>
where
    V: Clone + Hash + Eq,
    C: Cost,
    D: FnMut(&V, &V) -> C,
{
    /// Prepares a search from `starts` to `goal` with initial inflation `weight`.
    ///
    /// # Panics
    ///
    /// Panics if `weight` is below `1`.
    pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
        _graph: &G,
        starts: impl IntoIterator<Item = V>,
        goal: V,
        heuristic: D,
        weight: Weight,
    ) -> Self {
        assert_weight(weight);

        Self {
            rooting: Rooting::new(false, starts, goal, heuristic, Some(weight)),
        }
    }

    /// Sets the inflation for the next iterations.
    ///
    /// # Panics
    ///
    /// Panics if `weight` is below `1`.
    pub fn set_weight(&mut self, weight: Weight) {
        assert_weight(weight);
        self.rooting.core.set_weight(weight);
    }

    /// The current inflation.
    #[must_use]
    pub fn weight(&self) -> Weight {
        self.rooting.core.weight()
    }
}