multiobjective_search/mvh/table.rs
1//! Building multi-valued heuristics: backward A*pex and the Bellman-Ford
2//! consistency fix of Wolff, Felner, Salzman (arXiv 2606.20644, Section 6).
3
4use alloc::collections::{BTreeMap, BTreeSet};
5use alloc::vec::Vec;
6
7use search_core::{Cost, WideMul};
8
9use crate::apex::expanded_apexes;
10use crate::cost::add;
11use crate::epsilon::Epsilon;
12use crate::graph::{Graph, ReverseGraph};
13use crate::mvh::MvHeuristic;
14use crate::pareto::Front;
15
16/// A multi-valued heuristic stored as a table: per state, a set of
17/// mutually non-dominated estimates. A state without an entry is a dead
18/// end.
19///
20/// Build one with [`apex_mvh`], and make it consistent with
21/// [`MvhTable::make_consistent`] for
22/// [`namoa_star_dr_mvh`](crate::namoa_star_dr_mvh).
23///
24/// # Examples
25///
26/// ```
27/// use multiobjective_search::{Epsilon, Graph, MvHeuristic, ReverseGraph, apex_mvh};
28///
29/// /// Two routes from 0 to the goal 1.
30/// struct Routes;
31///
32/// impl Graph for Routes {
33/// type State = u8;
34/// type Weight = [u32; 2];
35///
36/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
37/// if *state == 0 {
38/// out.extend([(1, [1, 5]), (1, [4, 2])]);
39/// }
40/// }
41/// }
42///
43/// impl ReverseGraph for Routes {
44/// fn predecessors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
45/// if *state == 1 {
46/// out.extend([(0, [1, 5]), (0, [4, 2])]);
47/// }
48/// }
49/// }
50///
51/// let mut h = apex_mvh(&Routes, [1], [Epsilon::ZERO; 2]);
52/// let mut out = Vec::new();
53/// h.estimates(&0, &mut out);
54/// assert_eq!(out, [[1, 5], [4, 2]]); // exact with zero tolerance
55/// ```
56#[derive(Debug, Clone)]
57pub struct MvhTable<S, C, const N: usize> {
58 /// The estimates per state; never an empty set.
59 sets: BTreeMap<S, Front<C, N>>,
60}
61
62impl<S: Ord, C: Cost, const N: usize> MvhTable<S, C, N> {
63 /// The estimates of `state`, sorted lexicographically; empty for a
64 /// dead end.
65 #[must_use]
66 pub fn get(&self, state: &S) -> &[[C; N]] {
67 self.sets.get(state).map_or(&[], Front::as_slice)
68 }
69
70 /// The total number of estimates over all states.
71 #[must_use]
72 pub fn size(&self) -> usize {
73 self.sets.values().map(Front::len).sum()
74 }
75
76 /// Makes the table consistent in the monotone sense (see
77 /// [`MvHeuristic`]) by Bellman-Ford label updates: while some edge
78 /// `(s, t)` with cost `c` has an estimate `h'` of `t` such that no
79 /// estimate of `s` weakly dominates `c + h'`, add `c + h'` to `s` and
80 /// drop the estimates it dominates.
81 ///
82 /// Only lower bounds are added, so an admissible table stays
83 /// admissible. Wolff et al. add `c + h'` when it strictly dominates an
84 /// estimate of `s`; adding it whenever it is not covered is what
85 /// guarantees the monotone form. The fix-point exists on finite graphs:
86 /// every added vector is an original estimate plus a path cost, and one
87 /// that runs around a cycle is weakly dominated by the vector without
88 /// the cycle. States whose estimates change are revisited through
89 /// their predecessors.
90 pub fn make_consistent<G>(&mut self, graph: &G)
91 where
92 S: Clone,
93 G: ReverseGraph<State = S, Weight = [C; N]>,
94 {
95 let mut work: Vec<S> = self.sets.keys().cloned().collect();
96 let mut queued: BTreeSet<S> = work.iter().cloned().collect();
97 let mut edges = Vec::new();
98
99 while let Some(target) = work.pop() {
100 queued.remove(&target);
101 let estimates = self.get(&target).to_vec();
102 graph.predecessors(&target, &mut edges);
103
104 for (source, weight) in edges.drain(..) {
105 if self.lower(&source, weight, &estimates) && queued.insert(source.clone()) {
106 work.push(source);
107 }
108 }
109 }
110 }
111
112 /// Adds `weight + h'` to `source` for every `h'` in `estimates` that
113 /// no estimate of `source` covers; returns `true` if any was added.
114 fn lower(&mut self, source: &S, weight: [C; N], estimates: &[[C; N]]) -> bool
115 where
116 S: Clone,
117 {
118 let set = self.sets.entry(source.clone()).or_default();
119 let mut changed = false;
120 for &h in estimates {
121 let bound = add(weight, h);
122 if !set.weakly_dominates(&bound) {
123 set.insert(bound);
124 changed = true;
125 }
126 }
127
128 changed
129 }
130}
131
132impl<S: Ord, C: Cost, const N: usize> MvHeuristic<S, [C; N]> for MvhTable<S, C, N> {
133 fn estimates(&mut self, state: &S, out: &mut Vec<[C; N]>) {
134 out.extend_from_slice(self.get(state));
135 }
136}
137
138impl<S: Ord, C: Cost, const N: usize> MvHeuristic<S, [C; N]> for &MvhTable<S, C, N> {
139 fn estimates(&mut self, state: &S, out: &mut Vec<[C; N]>) {
140 out.extend_from_slice(self.get(state));
141 }
142}
143
144/// Builds an admissible multi-valued heuristic by A*pex backwards from
145/// `goals` with tolerances `eps` (Wolff et al., Section 6, "A*pex-MVH").
146///
147/// The estimates of a state are the apexes of the pairs A*pex expands
148/// there on the reversed graph. Each apex weakly dominates the cost of
149/// every path it stands for, so every path from the state to a goal is
150/// bounded by one of them: the table is admissible. It is generally not
151/// consistent; see [`MvhTable::make_consistent`]. Larger `eps` merges more
152/// paths, which gives fewer and looser estimates; `eps = 0` gives the exact
153/// Pareto sets of the remaining cost. States that reach no goal get no
154/// entry.
155///
156/// Requires non-negative edge costs.
157pub fn apex_mvh<G, C, const N: usize>(
158 graph: &G,
159 goals: impl IntoIterator<Item = G::State>,
160 eps: [Epsilon; N],
161) -> MvhTable<G::State, C, N>
162where
163 G: ReverseGraph<Weight = [C; N]>,
164 C: Cost + WideMul,
165{
166 MvhTable {
167 sets: expanded_apexes(&Reversed(graph), goals, eps),
168 }
169}
170
171/// `G` with its edges reversed.
172struct Reversed<'a, G>(&'a G);
173
174impl<G: ReverseGraph> Graph for Reversed<'_, G> {
175 type State = G::State;
176 type Weight = G::Weight;
177
178 fn successors(&self, state: &G::State, out: &mut Vec<(G::State, G::Weight)>) {
179 self.0.predecessors(state, out);
180 }
181}