Skip to main content

multiobjective_search/
graph.rs

1//! The search-space interface: successor generation and the zero heuristic
2//! for cost vectors.
3
4use alloc::vec::Vec;
5
6use search_core::{Cost, Heuristic};
7
8/// An implicit graph with vector-valued edge weights.
9///
10/// Successors are generated on demand, so the graph never needs to be
11/// materialized.
12pub trait Graph {
13    /// A search state. `Ord` keys the per-state bookkeeping (a `BTreeMap`,
14    /// since the crate is `no_std`).
15    type State: Clone + Ord;
16
17    /// The cost vector of one edge, for example `[u32; 2]`.
18    type Weight;
19
20    /// Appends every outgoing edge of `state` to `out` as
21    /// `(successor, weight)`.
22    ///
23    /// `out` is empty on entry; the caller clears and reuses it between
24    /// calls. Parallel edges and self-loops are allowed.
25    fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, Self::Weight)>);
26}
27
28/// A [`Graph`] that can also enumerate incoming edges, for bidirectional
29/// search.
30///
31/// The predecessors must mirror the successors exactly: `(p, w)` is
32/// reported by `predecessors(s)` once for every `(s, w)` that
33/// `successors(p)` reports, parallel edges included.
34pub trait ReverseGraph: Graph {
35    /// Appends every incoming edge of `state` to `out` as
36    /// `(predecessor, weight)`, where `weight` is the cost of the edge from
37    /// `predecessor` to `state`.
38    ///
39    /// `out` is empty on entry; the caller clears and reuses it between
40    /// calls.
41    fn predecessors(&self, state: &Self::State, out: &mut Vec<(Self::State, Self::Weight)>);
42}
43
44/// A [`Graph`] whose edges have identities, for problems that must tell
45/// parallel edges apart: disjoint and dissimilar paths.
46///
47/// An additive extension: graphs that only implement [`Graph`] keep working
48/// with every other search. `edges` must report the same edges as
49/// [`Graph::successors`], each with an identity unique in the graph.
50pub trait EdgeGraph: Graph {
51    /// An edge identity, unique over the whole graph.
52    type Edge: Clone + Ord;
53
54    /// Appends every outgoing edge of `state` to `out` as
55    /// `(edge, successor, weight)`. `out` is empty on entry.
56    fn edges(&self, state: &Self::State, out: &mut Vec<(Self::Edge, Self::State, Self::Weight)>);
57}
58
59/// The zero heuristic for cost vectors: no estimate, the search is
60/// uninformed.
61///
62/// Consistent for any graph with non-negative costs. `search_core::Zero`
63/// covers scalar costs only, so cost vectors `[C; N]` get this local one.
64#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
65pub struct ZeroHeuristic;
66
67impl<S, C: Cost, const N: usize> Heuristic<S, [C; N]> for ZeroHeuristic {
68    fn estimate(&mut self, _state: &S) -> Option<[C; N]> {
69        Some([C::ZERO; N])
70    }
71}