heuristic-search 0.2.1

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
//! Near-Optimal Bidirectional Search ([`nbs`], Chen, Holte, Zilles and Sturtevant 2017).

use core::cmp::Reverse;
use core::hash::Hash;

use alloc::vec::Vec;

use search_core::{Budget, Cost, Heuristic};

use crate::best_first::GraphResult;
use crate::bidirectional::mixed::{Both, Mixed, MixedGraph, Split, unmix};
use crate::bidirectional::{
    BidirectionalGraph, Core, Direction, Equality, MeetRelation, MeetResult, Meeting, Meets,
    RegressionGraph,
};
use crate::keyed_set::KeyedSet;
use crate::outcome::Stats;
use crate::problem::Predecessors;
use crate::problem::Successors;
use crate::space::NodeId;

/// Near-Optimal Bidirectional Search (NBS): expands pairs of states, one per side, and
/// never expands more than twice the states any admissible front-to-end bidirectional
/// search must.
///
/// The lower bound of a pair `(u, v)` is `lb(u, v) = max(f_F(u), f_B(v), g_F(u) + g_B(v))`.
/// NBS keeps a current lower bound `CLB` and expands both states of a pair with
/// `lb <= CLB`, choosing the smallest `g` among the states with `f <= CLB` on each side
/// (the paper's waiting and ready queues). When no such pair is left it raises `CLB`
/// to the smallest bound any pair can have, and it stops once `CLB` reaches the cheapest
/// meet. `forward` estimates the cost to the nearest goal and `backward` the cost from the
/// start; with admissible estimates the solution is optimal.
///
/// ```mermaid
/// flowchart TD
///     check{"a side empty, or CLB >= mu?"} -->|yes| done[best meet, or Unsolvable]
///     check -->|no| promote["move f <= CLB from waiting to ready, both sides"]
///     promote --> pair{"g_F + g_B of the ready minima <= CLB?"}
///     pair -->|yes| expand[expand both, queue children as waiting]
///     pair -->|no| raise["CLB = smallest waiting f or ready g sum"]
///     expand --> check
///     raise --> check
/// ```
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, heuristic_fn, nbs};
///
/// /// A line of integers; each step moves one to the left or right at cost 1.
/// struct Line;
///
/// impl Successors for Line {
///     type State = i32;
///     type Action = i32;
///     type Cost = u32;
///
///     fn successors(&self, state: &i32, mut emit: impl FnMut(i32, i32, u32)) {
///         emit(-1, state - 1, 1);
///         emit(1, state + 1, 1);
///     }
/// }
///
/// impl Predecessors for Line {
///     type Node = i32;
///     type Action = i32;
///     type Cost = u32;
///
///     fn predecessors(&self, state: &i32, mut emit: impl FnMut(i32, i32, u32)) {
///         emit(1, state - 1, 1);
///         emit(-1, state + 1, 1);
///     }
/// }
///
/// let to_goal = heuristic_fn(|s: &i32| Some(9_i32.abs_diff(*s)));
/// let from_start = heuristic_fn(|s: &i32| Some(0_i32.abs_diff(*s)));
/// let result = nbs(&Line, 0, [9], to_goal, from_start, Limits::NONE);
/// let solution = result.into_solution().expect("9 is reachable");
///
/// assert_eq!(solution.cost, 9);
/// assert_eq!(solution.actions, [1; 9]);
/// ```
pub fn nbs<G, HF, HB>(
    graph: &G,
    start: G::State,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    nbs_multi(graph, [start], goals, forward, backward, budget)
}

/// [`nbs`] from several start states at once.
///
/// Every start has path cost zero on the forward side, just as every goal has on the
/// backward side. Repeated starts count once, an empty set of starts finds nothing, and a
/// start that is a goal is returned as a zero-cost path. The backward heuristic must estimate
/// the cost back to the nearest start, which a heuristic towards one start overestimates.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, heuristic_fn, nbs_multi};
///
/// /// Counting up by one at cost 1, and back down for the backward search.
/// struct Up;
///
/// impl Successors for Up {
///     type State = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         emit((), n + 1, 1);
///     }
/// }
///
/// impl Predecessors for Up {
///     type Node = u32;
///     type Action = ();
///     type Cost = u32;
///
///     fn predecessors(&self, n: &u32, mut emit: impl FnMut((), u32, u32)) {
///         if let Some(previous) = n.checked_sub(1) {
///             emit((), previous, 1);
///         }
///     }
/// }
///
/// let h = heuristic_fn(|n: &u32| 8_u32.checked_sub(*n));
/// let result = nbs_multi(&Up, [0, 6, 3], [8], h, Zero, Limits::NONE);
///
/// assert_eq!(result.solution().map(|s| s.cost), Some(2));
/// ```
pub fn nbs_multi<G, HF, HB>(
    graph: &G,
    starts: impl IntoIterator<Item = G::State>,
    goals: impl IntoIterator<Item = G::State>,
    forward: HF,
    backward: HB,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
{
    let core = Core::new(
        graph,
        starts,
        goals,
        forward,
        backward,
        None::<Meeting<G, Equality>>,
    );

    Nbs::new(core).run(budget)
}

/// [`nbs()`](crate::nbs()) that meets by a [`MeetRelation`] instead of state equality, from several
/// starts at once.
///
/// `goals` are backward nodes of the graph's [`Predecessors::Node`](crate::Predecessors)
/// type, such as subgoals (partial states), and `meet` decides which forward states meet
/// which backward nodes (see [`MeetRelation`] for the contract). The returned path is
/// rebuilt from the meeting state by replaying the backward actions forwards, through the
/// first successor edge with an equal label, so every state on it is a real state and its
/// cost the true cost.
///
/// Both heuristics are evaluated on states and on backward nodes, so they implement
/// [`Heuristic`] for both types ([`Zero`](crate::Zero) does). On a backward node such as a subgoal,
/// each must keep its guarantee (admissible, and consistent where the search needs it)
/// when read as the cheapest value over the states that satisfy the node.
///
/// # Errors
///
/// [`ReplayError`](crate::ReplayError) if a replay step finds no successor edge with the backward action's
/// label: the relation or the predecessors disagree with the successors.
///
/// The backward heuristic estimates the cost from the starts to a backward node.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Predecessors, Successors, Zero, meet_fn, nbs_meet};
///
/// /// Three facts as bits; action `k` makes fact `k` true at cost 1.
/// struct Facts;
///
/// impl Successors for Facts {
///     type State = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn successors(&self, state: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if state & (1 << k) == 0 {
///                 emit(k, state | (1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // Regression: a subgoal is a set of facts that must hold; action `k` achieves fact `k`.
/// impl Predecessors for Facts {
///     type Node = u8;
///     type Action = u8;
///     type Cost = u32;
///
///     fn predecessors(&self, subgoal: &u8, mut emit: impl FnMut(u8, u8, u32)) {
///         for k in 0..3 {
///             if subgoal & (1 << k) != 0 {
///                 emit(k, subgoal & !(1 << k), 1);
///             }
///         }
///     }
/// }
///
/// // A state meets a subgoal it satisfies.
/// let satisfies = meet_fn(|state: &u8, subgoal: &u8| state & subgoal == *subgoal);
/// let result = nbs_meet(&Facts, [0], [0b110], Zero, Zero, satisfies, Limits::NONE);
///
/// let solution = result.expect("the model replays").into_solution().expect("facts 1 and 2 are reachable");
/// assert_eq!(solution.cost, 2);
/// assert_eq!(solution.states.len(), 3);
/// assert_eq!(solution.goal() & 0b110, 0b110);
/// ```
pub fn nbs_meet<G, HF, HB, M>(
    graph: &G,
    starts: impl IntoIterator<Item = <G as Successors>::State>,
    goals: impl IntoIterator<Item = <G as Predecessors>::Node>,
    forward: HF,
    backward: HB,
    meet: M,
    budget: impl Budget<Stats>,
) -> MeetResult<G>
where
    G: RegressionGraph,
    <G as Successors>::State: Clone + Hash + Eq,
    <G as Predecessors>::Node: Clone + Hash + Eq,
    <G as Successors>::Action: Clone + PartialEq,
    HF: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    HB: Heuristic<<G as Successors>::State, <G as Successors>::Cost>
        + Heuristic<<G as Predecessors>::Node, <G as Successors>::Cost>,
    M: MeetRelation<<G as Successors>::State, <G as Predecessors>::Node>,
{
    let mixed = MixedGraph(graph);
    let core = Core::new(
        &mixed,
        starts.into_iter().map(Mixed::State),
        goals.into_iter().map(Mixed::Node),
        Both(forward),
        Both(backward),
        Some(Meeting::new(Split(meet))),
    );

    unmix(Nbs::new(core).run(budget))
}

/// A queue order: smallest primary value, then the secondary value reversed, then node id.
type Key<C> = (C, Reverse<C>);

/// The state of one NBS run.
struct Nbs<'a, G: BidirectionalGraph, HF, HB, M> {
    /// Both sides, the heuristics, the counters and the best meet.
    core: Core<'a, G, HF, HB, M>,
    /// Per side, open states with `f > CLB`, by `f` (ties: larger `g`).
    waiting: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
    /// Per side, open states with `f <= CLB`, by `g` (ties: larger `f`).
    ready: [KeyedSet<Key<<G as Successors>::Cost>>; 2],
    /// The current lower bound on the cost of any path not found yet.
    clb: <G as Successors>::Cost,
}

impl<'a, G, HF, HB, M> Nbs<'a, G, HF, HB, M>
where
    G: BidirectionalGraph,
    G::State: Clone + Hash + Eq,
    <G as Successors>::Action: Clone,
    HF: Heuristic<G::State, <G as Successors>::Cost>,
    HB: Heuristic<G::State, <G as Successors>::Cost>,
    M: Meets<G::State>,
{
    /// Queues the live seeds of both sides.
    fn new(core: Core<'a, G, HF, HB, M>) -> Self {
        let mut search = Self {
            core,
            waiting: [KeyedSet::new(), KeyedSet::new()],
            ready: [KeyedSet::new(), KeyedSet::new()],
            clb: <G as Successors>::Cost::ZERO,
        };

        for direction in [Direction::Forward, Direction::Backward] {
            for id in 0..search.core.side(direction).space.len() {
                search.queue(direction, id);
            }
        }

        search
    }

    /// Expands pairs until `CLB` reaches the best meet, a side runs empty or the budget is
    /// used up.
    fn run(mut self, mut budget: impl Budget<Stats>) -> GraphResult<G> {
        let mut touched = Vec::new();
        while !self.side_exhausted() && !self.core.proven(self.clb) {
            self.promote(Direction::Forward);
            self.promote(Direction::Backward);

            let Some((u, v)) = self.ready_pair() else {
                self.raise_clb();
                continue;
            };

            for (direction, node) in [(Direction::Forward, u), (Direction::Backward, v)] {
                // Asked before each of the two expansions, so a limit of `n` stops at `n`.
                if budget.exhausted(&self.core.stats) {
                    return self.core.finish(false);
                }

                self.ready[direction.index()].remove(node);
                self.core.expand(direction, node, true, &mut touched);
                for id in touched.drain(..) {
                    self.queue(direction, id);
                }
            }
        }

        self.core.finish(true)
    }

    /// Returns `true` if either side has nothing open.
    fn side_exhausted(&self) -> bool {
        (0..2).any(|side| self.waiting[side].is_empty() && self.ready[side].is_empty())
    }

    /// Moves every waiting state with `f <= CLB` on `direction`'s side to the ready queue.
    fn promote(&mut self, direction: Direction) {
        let side = direction.index();
        while let Some((&(f, Reverse(g)), id)) = self.waiting[side].first() {
            if f.cmp(&self.clb).is_gt() {
                break;
            }

            self.waiting[side].remove(id);
            self.ready[side].insert(id, (g, Reverse(f)));
        }
    }

    /// The ready pair of smallest `g` on each side, if their `g` sum is within `CLB`.
    fn ready_pair(&self) -> Option<(NodeId, NodeId)> {
        let (forward, u) = self.ready[0].first()?;
        let (backward, v) = self.ready[1].first()?;

        (forward.0 + backward.0)
            .cmp(&self.clb)
            .is_le()
            .then_some((u, v))
    }

    /// Raises `CLB` to the smallest lower bound any pair can have now: the smallest waiting
    /// `f` of either side, or the smallest ready `g` sum.
    fn raise_clb(&mut self) {
        let waiting = self
            .waiting
            .iter()
            .filter_map(|queue| queue.first().map(|(key, _)| key.0));
        let ready = match (self.ready[0].first(), self.ready[1].first()) {
            (Some((forward, _)), Some((backward, _))) => Some(forward.0 + backward.0),
            _ => None,
        };

        let next = waiting
            .chain(ready)
            .reduce(|a, b| if b.cmp(&a).is_lt() { b } else { a })
            .expect("both sides have open states");
        debug_assert!(next.cmp(&self.clb).is_gt(), "CLB must grow");

        self.clb = next;
    }

    /// Queues the live node `id` on `direction`'s side as waiting, replacing any earlier
    /// entry; [`Nbs::promote`] moves it on if `f <= CLB`.
    fn queue(&mut self, direction: Direction, id: NodeId) {
        let Some((h, _)) = self.core.h(direction, id) else {
            return;
        };

        let g = self.core.g(direction, id);
        let side = direction.index();
        self.ready[side].remove(id);
        self.waiting[side].insert(id, (g + h, Reverse(g)));
    }
}