multiobjective_search/heuristics.rs
1//! Heuristic builders: the ideal-point heuristic and differential
2//! heuristics, as used across the multi-objective search literature
3//! (Salzman, Hernández Ulloa, Felner, Koenig, "Multi-Objective Search:
4//! Algorithms, Applications, and Emerging Directions", arXiv 2510.25504,
5//! Section 3.2).
6
7use alloc::collections::{BTreeMap, BinaryHeap};
8use alloc::vec::Vec;
9use core::cmp::Reverse;
10
11use search_core::{Cost, Heuristic, WideMul};
12
13use crate::graph::ReverseGraph;
14
15/// The ideal-point heuristic `h_ideal(v) = (h_1(v), ..., h_N(v))`, with
16/// `h_i` the exact shortest distance from `v` to a goal in objective `i`
17/// alone. Consistent and zero on goals; a state that reaches no goal has no
18/// estimate (a dead end).
19///
20/// Built by one backward Dijkstra per objective from the goal set, so the
21/// graph's reachable part must be finite.
22///
23/// # Examples
24///
25/// ```
26/// use multiobjective_search::{Graph, Heuristic, IdealPoint, ReverseGraph};
27///
28/// /// 0 → 1 → 2 and 0 → 2 directly.
29/// struct Line;
30///
31/// const EDGES: [(u8, u8, [u32; 2]); 3] = [(0, 1, [1, 5]), (1, 2, [1, 5]), (0, 2, [9, 1])];
32///
33/// impl Graph for Line {
34/// type State = u8;
35/// type Weight = [u32; 2];
36///
37/// fn successors(&self, s: &u8, out: &mut Vec<(u8, [u32; 2])>) {
38/// out.extend(EDGES.iter().filter(|e| e.0 == *s).map(|e| (e.1, e.2)));
39/// }
40/// }
41///
42/// impl ReverseGraph for Line {
43/// fn predecessors(&self, s: &u8, out: &mut Vec<(u8, [u32; 2])>) {
44/// out.extend(EDGES.iter().filter(|e| e.1 == *s).map(|e| (e.0, e.2)));
45/// }
46/// }
47///
48/// let mut h = IdealPoint::new(&Line, [2]);
49/// assert_eq!(h.estimate(&0), Some([2, 1])); // the best of each objective
50/// assert_eq!(h.estimate(&2), Some([0, 0]));
51/// ```
52#[derive(Debug, Clone)]
53pub struct IdealPoint<S, C, const N: usize> {
54 /// The estimate per state that reaches a goal.
55 table: BTreeMap<S, [C; N]>,
56}
57
58impl<S: Clone + Ord, C: Cost, const N: usize> IdealPoint<S, C, N> {
59 /// Computes the heuristic toward `goals` on `graph`.
60 pub fn new<G>(graph: &G, goals: impl IntoIterator<Item = S>) -> Self
61 where
62 G: ReverseGraph<State = S, Weight = [C; N]>,
63 {
64 let goals: Vec<S> = goals.into_iter().collect();
65 let per_objective: Vec<BTreeMap<S, C>> = (0..N)
66 .map(|i| {
67 dijkstra(
68 goals.iter().cloned(),
69 |s, out| graph.predecessors(s, out),
70 i,
71 )
72 })
73 .collect();
74
75 let table = per_objective[0]
76 .keys()
77 .map(|s| (s.clone(), core::array::from_fn(|i| per_objective[i][s])))
78 .collect();
79
80 Self { table }
81 }
82}
83
84impl<S: Ord, C: Cost, const N: usize> Heuristic<S, [C; N]> for IdealPoint<S, C, N> {
85 fn estimate(&mut self, state: &S) -> Option<[C; N]> {
86 self.table.get(state).copied()
87 }
88}
89
90impl<S: Ord, C: Cost, const N: usize> Heuristic<S, [C; N]> for &IdealPoint<S, C, N> {
91 fn estimate(&mut self, state: &S) -> Option<[C; N]> {
92 self.table.get(state).copied()
93 }
94}
95
96/// Single-objective Dijkstra from `sources` over `edges` in objective
97/// `objective`: the distance to every state reached.
98fn dijkstra<S: Clone + Ord, C: Cost, const N: usize>(
99 sources: impl IntoIterator<Item = S>,
100 edges: impl Fn(&S, &mut Vec<(S, [C; N])>),
101 objective: usize,
102) -> BTreeMap<S, C> {
103 let mut dist = BTreeMap::new();
104 let mut heap: BinaryHeap<Reverse<(C, S)>> =
105 sources.into_iter().map(|s| Reverse((C::ZERO, s))).collect();
106 let mut buffer = Vec::new();
107
108 while let Some(Reverse((d, s))) = heap.pop() {
109 if dist.contains_key(&s) {
110 continue;
111 }
112
113 edges(&s, &mut buffer);
114 for (t, w) in buffer.drain(..) {
115 if !dist.contains_key(&t) {
116 heap.push(Reverse((d + w[objective], t)));
117 }
118 }
119
120 dist.insert(s, d);
121 }
122
123 dist
124}
125
126/// Differential heuristics (Goldberg and Harrelson 2005) per objective:
127/// exact distances from and to a few landmark states, giving for any goal
128/// `g` the consistent lower bound
129/// `h_i(v) = max_L max(d_i(L, g) - d_i(L, v), d_i(v, L) - d_i(g, L), 0)`
130/// by the triangle inequality. It is consistent along every edge whose
131/// head can reach the goal (a term undefined for lack of a path is left
132/// out).
133///
134/// The memory-based heuristics the survey discusses for multi-objective
135/// search; Zhang et al. 2023 extend them to multi-valued bi-objective
136/// forms. Build once per graph with [`DifferentialHeuristic::new`], then
137/// aim at a goal with [`DifferentialHeuristic::towards`].
138///
139/// # Examples
140///
141/// ```
142/// use multiobjective_search::{DifferentialHeuristic, Graph, Heuristic, ReverseGraph};
143///
144/// /// A path 0 - 1 - 2 - 3 in both directions, unit costs.
145/// struct Path;
146///
147/// impl Graph for Path {
148/// type State = u8;
149/// type Weight = [u32; 1];
150///
151/// fn successors(&self, s: &u8, out: &mut Vec<(u8, [u32; 1])>) {
152/// if *s > 0 { out.push((s - 1, [1])); }
153/// if *s < 3 { out.push((s + 1, [1])); }
154/// }
155/// }
156///
157/// impl ReverseGraph for Path {
158/// fn predecessors(&self, s: &u8, out: &mut Vec<(u8, [u32; 1])>) {
159/// self.successors(s, out);
160/// }
161/// }
162///
163/// let dh = DifferentialHeuristic::new(&Path, [0]);
164/// let mut h = dh.towards(&3);
165/// assert_eq!(h.estimate(&1), Some([2])); // exact here: the landmark is an end
166/// ```
167#[derive(Debug, Clone)]
168pub struct DifferentialHeuristic<S, C, const N: usize> {
169 /// Per landmark and objective: distances from the landmark.
170 from: Vec<Vec<BTreeMap<S, C>>>,
171 /// Per landmark and objective: distances to the landmark.
172 to: Vec<Vec<BTreeMap<S, C>>>,
173}
174
175impl<S: Clone + Ord, C: Cost + WideMul, const N: usize> DifferentialHeuristic<S, C, N> {
176 /// Computes the landmark distances: two Dijkstras per landmark and
177 /// objective, over the finite reachable graph.
178 pub fn new<G>(graph: &G, landmarks: impl IntoIterator<Item = S>) -> Self
179 where
180 G: ReverseGraph<State = S, Weight = [C; N]>,
181 {
182 let (mut from, mut to) = (Vec::new(), Vec::new());
183 for landmark in landmarks {
184 from.push(
185 (0..N)
186 .map(|i| dijkstra([landmark.clone()], |s, out| graph.successors(s, out), i))
187 .collect(),
188 );
189 to.push(
190 (0..N)
191 .map(|i| dijkstra([landmark.clone()], |s, out| graph.predecessors(s, out), i))
192 .collect(),
193 );
194 }
195
196 Self { from, to }
197 }
198
199 /// The heuristic toward `goal`.
200 #[must_use]
201 pub fn towards(&self, goal: &S) -> Towards<'_, S, C, N> {
202 Towards {
203 landmarks: self,
204 goal: goal.clone(),
205 }
206 }
207}
208
209/// [`DifferentialHeuristic`] aimed at one goal.
210#[derive(Debug, Clone)]
211pub struct Towards<'a, S, C, const N: usize> {
212 /// The landmark distances.
213 landmarks: &'a DifferentialHeuristic<S, C, N>,
214 /// The goal.
215 goal: S,
216}
217
218impl<S: Ord, C: Cost + WideMul, const N: usize> Heuristic<S, [C; N]> for Towards<'_, S, C, N> {
219 fn estimate(&mut self, state: &S) -> Option<[C; N]> {
220 let lm = self.landmarks;
221 let bound = |i: usize| {
222 let mut best = C::ZERO;
223 for l in 0..lm.from.len() {
224 // d(L, g) - d(L, v) and d(v, L) - d(g, L), where defined.
225 let pairs = [
226 (lm.from[l][i].get(&self.goal), lm.from[l][i].get(state)),
227 (lm.to[l][i].get(state), lm.to[l][i].get(&self.goal)),
228 ];
229 for (big, small) in pairs {
230 if let (Some(&big), Some(&small)) = (big, small) {
231 if big > small {
232 best = best.max(big.abs_diff(small));
233 }
234 }
235 }
236 }
237
238 best
239 };
240
241 Some(core::array::from_fn(bound))
242 }
243}