heuristic-search 0.2.2

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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Simplified memory-bounded A* (SMA*, Russell 1992): [`sma_star`] and [`sma_star_multi`].
//!
//! SMA* runs A* on the search tree with at most `memory` nodes in memory. When a newly
//! generated child does not fit, the worst leaf (largest backed-up `f`, shallowest first)
//! is forgotten, and its parent remembers the forgotten child's position and backed-up
//! `f`. The smallest such value keeps the parent on the open list, so the best forgotten
//! child is regenerated, with its old value, once it is the most promising part of the
//! tree again. (Each node thus keeps one value per forgotten child; `memory` counts
//! nodes.) Values are backed up like in
//! [`rbfs`](fn@crate::rbfs): a node's `f` is the smallest `f` of its children in memory and of
//! the forgotten ones, never less than before.
//!
//! ```mermaid
//! flowchart TD
//!     pop[pop open node with smallest key, deepest first] -->|key infinite| done[Unsolvable or Cutoff]
//!     pop --> goal{goal?}
//!     goal -->|yes| found[Found]
//!     goal -->|no| generate[first time: all successors; later: best forgotten child]
//!     generate --> prune{over memory?}
//!     prune -->|yes| forget[forget worst leaf into its parent]
//!     forget --> prune
//!     prune -->|no| backup[back up f to the ancestors]
//!     backup --> pop
//! ```

use alloc::vec::Vec;
use core::cmp::Reverse;

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

use crate::best_first::GraphResult;
use crate::cost::Extended;
use crate::depth_first::{distinct, goal_root};
use crate::keyed_set::KeyedSet;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Successors, collect_successors};

/// SMA* from `start` with at most `memory` search nodes in memory: A* that forgets its
/// worst leaves when memory runs out and regenerates them when needed.
///
/// A tree search like [`ida_star`](crate::ida_star): states need only `Eq`, and successors
/// already on a node's path are skipped. Successors must be reported in the same order
/// every time, since forgotten children are regenerated by their position.
///
/// `memory` counts nodes in memory between expansions. While a node is expanded for the
/// first time all its successors are created before the worst leaves are forgotten, so the
/// count briefly exceeds `memory` by up to the branching factor; and each node also keeps
/// one value per forgotten child.
///
/// The search returns the cheapest path among those with at most `memory - 1` edges, for
/// an admissible `heuristic` (consistency is not needed; `None` marks a dead end). Longer
/// paths do not fit: each node on a path stays in memory while its subtree is searched,
/// plus one child. So the solution is optimal whenever some optimal path has at most
/// `memory - 1` edges. If memory is too small for any solution, the outcome is
/// [`Outcome::Cutoff`]: a larger `memory` may find one. [`Outcome::Unsolvable`] means no
/// goal is reachable at all (no path was cut off by memory). Goals are tested when a node
/// is taken from the open list. [`Stats::expanded`] counts every expansion, also
/// regenerations of forgotten children.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Outcome, Successors, Zero, sma_star};
///
/// /// `0 -> 3` directly costs 10; `0 -> 1 -> 2 -> 3` costs 3.
/// struct Shortcut;
///
/// impl Successors for Shortcut {
///     type State = u8;
///     type Action = ();
///     type Cost = u32;
///
///     fn successors(&self, n: &u8, mut emit: impl FnMut((), u8, u32)) {
///         match n {
///             0 => {
///                 emit((), 3, 10);
///                 emit((), 1, 1);
///             }
///             1 => emit((), 2, 1),
///             2 => emit((), 3, 1),
///             _ => {}
///         }
///     }
/// }
///
/// let is_three = |n: &u8| *n == 3;
/// let roomy = sma_star(&Shortcut, 0, &is_three, Zero, 4, Limits::NONE);
/// let tight = sma_star(&Shortcut, 0, &is_three, Zero, 2, Limits::NONE);
/// let tiny = sma_star(&Shortcut, 0, &is_three, Zero, 1, Limits::NONE);
///
/// assert_eq!(roomy.solution().map(|s| s.cost), Some(3));
/// // Two nodes hold paths of one edge only.
/// assert_eq!(tight.solution().map(|s| s.cost), Some(10));
/// assert_eq!(tiny.outcome, Outcome::Cutoff);
/// ```
pub fn sma_star<G, T, H>(
    graph: &G,
    start: G::State,
    goal: &T,
    heuristic: H,
    memory: usize,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: Successors,
    G::State: Clone + Eq,
    G::Action: Clone,
    T: Goal<G::State> + ?Sized,
    H: Heuristic<G::State, G::Cost>,
{
    sma_star_multi(graph, [start], goal, heuristic, memory, budget)
}

/// [`sma_star`] from several start states at once.
///
/// Every distinct start stays in memory and counts against `memory`, so with `k` starts
/// the paths that fit have at most `memory - k` edges; with more starts than `memory` the
/// outcome is [`Outcome::Cutoff`]. Repeated starts count once, an empty set of starts is
/// [`Outcome::Unsolvable`], and a start that is a goal is returned as a zero-cost path.
///
/// # Examples
///
/// ```
/// use heuristic_search::{Limits, Successors, heuristic_fn, sma_star_multi};
///
/// /// Counting up by one, at cost 1.
/// 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)) {
///         if *n < 8 {
///             emit((), n + 1, 1);
///         }
///     }
/// }
///
/// let h = heuristic_fn(|n: &u32| 8_u32.checked_sub(*n));
/// let result = sma_star_multi(&Up, [0, 6, 3], &|n: &u32| *n == 8, h, 6, Limits::NONE);
///
/// assert_eq!(result.solution().map(|s| s.states.clone()), Some(vec![6, 7, 8]));
/// ```
pub fn sma_star_multi<G, T, H>(
    graph: &G,
    starts: impl IntoIterator<Item = G::State>,
    goal: &T,
    heuristic: H,
    memory: usize,
    budget: impl Budget<Stats>,
) -> GraphResult<G>
where
    G: Successors,
    G::State: Clone + Eq,
    G::Action: Clone,
    T: Goal<G::State> + ?Sized,
    H: Heuristic<G::State, G::Cost>,
{
    let roots = distinct(starts);
    if let Some(solution) = goal_root(&roots, goal) {
        return SearchResult {
            outcome: Outcome::Found(solution),
            stats: Stats::default(),
        };
    }

    let mut search = Sma {
        graph,
        goal,
        heuristic,
        memory,
        roots: roots.len(),
        nodes: Vec::new(),
        free: Vec::new(),
        open: KeyedSet::new(),
        leaves: KeyedSet::new(),
        live: 0,
        created: 0,
        cut: false,
        stats: Stats::default(),
    };
    let outcome = if roots.len() > memory {
        Outcome::Cutoff
    } else {
        search.run(roots, budget)
    };

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

/// A node of the search tree in memory.
struct Node<S, A, C> {
    /// The state.
    state: S,
    /// The edge label and cost from the parent; `None` for a start.
    via: Option<(A, C)>,
    /// The parent's slot; `None` for a start.
    parent: Option<usize>,
    /// The position of this node among its parent's successors, as the graph reports them.
    edge: usize,
    /// The number of edges from the start.
    depth: usize,
    /// The path cost from the start.
    g: C,
    /// The backed-up value `F`: a lower bound on the cost of any solution below this node.
    value: Extended<C>,
    /// The slots of the children in memory.
    children: Vec<usize>,
    /// The position and backed-up value of every forgotten child, so a regenerated child
    /// gets its value back.
    forgotten: Vec<(usize, Extended<C>)>,
    /// Whether the node has been expanded, so its children were generated once.
    expanded: bool,
    /// Creation counter, for deterministic tie-breaking.
    seq: u64,
}

/// A node over graph `G`.
type GraphNode<G> =
    Node<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;

/// Open-list key: smallest value first, then deepest, then oldest.
type OpenKey<C> = (Extended<C>, Reverse<usize>, u64);

/// Pruning key: largest value first, then shallowest, then oldest (so a child that was
/// just regenerated is not the first to go among equals).
type LeafKey<C> = (Reverse<Extended<C>>, usize, u64);

/// One SMA* run.
struct Sma<'a, G: Successors, T: ?Sized, H> {
    /// The graph being searched.
    graph: &'a G,
    /// The goal test.
    goal: &'a T,
    /// The heuristic, owned for the run.
    heuristic: H,
    /// The most nodes in memory at once.
    memory: usize,
    /// The number of distinct starts, which never leave memory.
    roots: usize,
    /// Node slots; `None` for free slots.
    nodes: Vec<Option<GraphNode<G>>>,
    /// Free slots for reuse.
    free: Vec<usize>,
    /// Nodes that can be expanded: leaves, and nodes with forgotten children.
    open: KeyedSet<OpenKey<G::Cost>>,
    /// Leaves that may be forgotten (every leaf except the starts).
    leaves: KeyedSet<LeafKey<G::Cost>>,
    /// The number of nodes in memory.
    live: usize,
    /// Nodes created so far.
    created: u64,
    /// Whether memory has cut off a path, so a goal may lie beyond it.
    cut: bool,
    /// Counters for the result.
    stats: Stats,
}

impl<G, T, H> Sma<'_, G, T, H>
where
    G: Successors,
    G::State: Clone + Eq,
    G::Action: Clone,
    T: Goal<G::State> + ?Sized,
    H: Heuristic<G::State, G::Cost>,
{
    /// Searches from `roots`, none of which is a goal and no more than `memory` of them.
    ///
    /// Values are backed up before pruning: forgetting a leaf moves its value into the
    /// parent's forgotten value, which leaves every backed-up value as it was.
    fn run(
        &mut self,
        roots: Vec<G::State>,
        mut budget: impl Budget<Stats>,
    ) -> Outcome<G::State, G::Action, G::Cost> {
        for (edge, state) in roots.into_iter().enumerate() {
            let value = Extended::f(G::Cost::ZERO, self.heuristic.estimate(&state));
            let id = self.create(Node {
                state,
                via: None,
                parent: None,
                edge,
                depth: 0,
                g: G::Cost::ZERO,
                value,
                children: Vec::new(),
                forgotten: Vec::new(),
                expanded: false,
                seq: 0,
            });
            self.refresh(id);
        }

        loop {
            let Some((&(key, _, _), id)) = self.open.first() else {
                return self.exhausted();
            };

            if key == Extended::Infinite {
                return self.exhausted();
            }

            if self.goal.is_goal(&self.node(id).state) {
                return Outcome::Found(self.solution(id));
            }

            if budget.exhausted(&self.stats) {
                return Outcome::LimitReached;
            }

            self.generate(id, key);
            self.back_up(id);
            self.prune();
        }
    }

    /// The outcome once nothing below infinity is left to expand.
    fn exhausted(&self) -> Outcome<G::State, G::Action, G::Cost> {
        if self.cut {
            Outcome::Cutoff
        } else {
            Outcome::Unsolvable
        }
    }

    /// Expands `id`: generates all its successors on the first expansion, each valued at
    /// least `bound` (the key `id` was taken with), and later regenerates only its
    /// forgotten child with the smallest remembered value, which it gets back.
    fn generate(&mut self, id: usize, bound: Extended<G::Cost>) {
        let mut edges = Vec::new();
        self.stats.expanded += 1;
        self.stats.generated += collect_successors(self.graph, &self.node(id).state, &mut edges);

        let node = self.node_mut(id);
        let wanted = if node.expanded {
            let best = (0..node.forgotten.len())
                .min_by_key(|&index| node.forgotten[index].1)
                .expect("an expanded node is open only with forgotten children");

            Some(node.forgotten.swap_remove(best))
        } else {
            node.expanded = true;
            None
        };

        for (edge, (action, state, cost)) in edges.into_iter().enumerate() {
            let value = match wanted {
                Some((forgotten, value)) if forgotten == edge => value,
                Some(_) => continue,
                None => bound,
            };

            self.add_child(id, edge, action, state, cost, value);
        }

        self.refresh(id);
    }

    /// Adds the successor `state` at position `edge` of `id` as a child valued at least
    /// `bound`, unless it is on the path, a dead end, or does not fit in memory.
    fn add_child(
        &mut self,
        id: usize,
        edge: usize,
        action: G::Action,
        state: G::State,
        cost: G::Cost,
        bound: Extended<G::Cost>,
    ) {
        if self.on_path(id, &state) {
            return;
        }

        // The child must fit next to its path and the other starts, and a non-goal child
        // also needs room for a child of its own.
        let (g, depth) = (self.node(id).g + cost, self.node(id).depth + 1);
        let needed = self.roots + depth;
        if needed > self.memory || (needed == self.memory && !self.goal.is_goal(&state)) {
            self.cut = true;
            return;
        }

        let Some(h) = self.heuristic.estimate(&state) else {
            return;
        };

        let child = self.create(Node {
            state,
            via: Some((action, cost)),
            parent: Some(id),
            edge,
            depth,
            g,
            value: bound.max(Extended::Finite(g.saturating_add(h))),
            children: Vec::new(),
            forgotten: Vec::new(),
            expanded: false,
            seq: 0,
        });
        self.node_mut(id).children.push(child);
        self.refresh(child);
    }

    /// Forgets the worst leaves until the nodes fit in memory.
    fn prune(&mut self) {
        while self.live > self.memory {
            let (_, leaf) = self
                .leaves
                .first()
                .expect("only starts are not prunable, and they fit");
            self.forget(leaf);
        }
    }

    /// Removes the leaf `id`; its parent remembers its value.
    fn forget(&mut self, id: usize) {
        self.open.remove(id);
        self.leaves.remove(id);
        let node = self.nodes[id].take().expect("a live node");
        self.free.push(id);
        self.live -= 1;

        let parent = node.parent.expect("starts are never forgotten");
        let entry = self.node_mut(parent);
        entry.children.retain(|&child| child != id);
        entry.forgotten.push((node.edge, node.value));
        self.refresh(parent);
    }

    /// Recomputes the value of `id` from its children and forgotten children, and those of
    /// its ancestors while they change.
    fn back_up(&mut self, mut id: usize) {
        loop {
            let node = self.node(id);
            let best = node
                .children
                .iter()
                .map(|&child| self.node(child).value)
                .fold(smallest_forgotten(node), Extended::min);
            let value = node.value.max(best);
            if value == node.value {
                return;
            }

            self.node_mut(id).value = value;
            self.refresh(id);
            match self.node(id).parent {
                Some(parent) => id = parent,
                None => return,
            }
        }
    }

    /// Puts `id` into the open list and the leaf set as its children and values say.
    fn refresh(&mut self, id: usize) {
        let node = self.node(id);
        let leaf = node.children.is_empty();
        let key = if leaf {
            Some(node.value)
        } else {
            Some(smallest_forgotten(node)).filter(|&f| f != Extended::Infinite)
        };
        let (depth, seq, value, prunable) = (
            node.depth,
            node.seq,
            node.value,
            leaf && node.parent.is_some(),
        );

        match key {
            Some(key) => self.open.insert(id, (key, Reverse(depth), seq)),
            None => {
                self.open.remove(id);
            }
        }

        if prunable {
            self.leaves.insert(id, (Reverse(value), depth, seq));
        } else {
            self.leaves.remove(id);
        }
    }

    /// Returns `true` if `state` is the state of `id` or of one of its ancestors.
    fn on_path(&self, mut id: usize, state: &G::State) -> bool {
        loop {
            let node = self.node(id);
            if node.state == *state {
                return true;
            }

            match node.parent {
                Some(parent) => id = parent,
                None => return false,
            }
        }
    }

    /// Stores `node` in a free slot and returns the slot.
    fn create(&mut self, mut node: Node<G::State, G::Action, G::Cost>) -> usize {
        node.seq = self.created;
        self.created += 1;
        self.live += 1;
        if let Some(id) = self.free.pop() {
            self.nodes[id] = Some(node);
            return id;
        }

        self.nodes.push(Some(node));

        self.nodes.len() - 1
    }

    /// The path from a start to `id`.
    fn solution(&self, id: usize) -> Solution<G::State, G::Action, G::Cost> {
        let mut states = Vec::new();
        let mut actions = Vec::new();
        let mut cost = G::Cost::ZERO;
        let mut at = Some(id);
        while let Some(current) = at {
            let node = self.node(current);
            states.push(node.state.clone());
            if let Some((action, edge_cost)) = &node.via {
                actions.push(action.clone());
                cost = cost + *edge_cost;
            }

            at = node.parent;
        }

        states.reverse();
        actions.reverse();

        Solution {
            states,
            actions,
            cost,
        }
    }

    /// The live node in slot `id`.
    fn node(&self, id: usize) -> &Node<G::State, G::Action, G::Cost> {
        self.nodes[id].as_ref().expect("a live node")
    }

    /// The live node in slot `id`, mutably.
    fn node_mut(&mut self, id: usize) -> &mut Node<G::State, G::Action, G::Cost> {
        self.nodes[id].as_mut().expect("a live node")
    }
}

/// The smallest value among the forgotten children of `node`; infinite if there are none.
fn smallest_forgotten<S, A, C: Cost>(node: &Node<S, A, C>) -> Extended<C> {
    node.forgotten
        .iter()
        .map(|&(_, value)| value)
        .min()
        .unwrap_or(Extended::Infinite)
}