multiobjective_search/pp_a.rs
1//! PP-A*: approximate bi-objective search over path pairs.
2//!
3//! Goldin and Salzman: "Approximate Bi-Criteria Search by Efficient
4//! Representation of Subsets of the Pareto-Optimal Frontier", ICAPS 2021
5//! (arXiv 2006.10302).
6//!
7//! A *path pair* at a state holds two paths to it: the top-left path `tl`
8//! with the smallest first cost and the bottom-right path `br` with the
9//! smallest second cost. Its *apex* `(c1(tl), c2(br))` is component-wise no
10//! worse than every path the pair stands for. A pair is *bounded* when
11//! `c1(br) <= (1 + ε1) · c1(tl)`: then `br`, extended by any suffix, is
12//! within the tolerance of every path whose cost is at or above the apex.
13//! The search is BOA* over path pairs, ordered by the apex `f`, with two
14//! additions:
15//!
16//! - a new pair merges into an open pair at the same state when the merged
17//! pair is still bounded, so near-equal paths share one open entry;
18//! - a goal pair merges into the last solution when the result is bounded.
19//!
20//! ```mermaid
21//! graph TD
22//! pop[Pop min apex f] --> pruned{"(1+ε2) f2(br) >= last solution c2,<br/>or g2(br) >= g2_min(state)?"}
23//! pruned -- yes --> pop
24//! pruned -- no --> record[g2_min of state = g2 of br]
25//! record --> goal{Goal?}
26//! goal -- yes --> sol[Merge into last solution if bounded, else add] --> pop
27//! goal -- no --> expand[Extend tl and br, prune] --> merge[Merge into an open pair<br/>at the state if bounded, else push] --> pop
28//! ```
29//!
30//! Differences from the paper, all of which keep its guarantee:
31//!
32//! - The bounded test is one-sided, on the first objective only, and the
33//! search returns `br` (the paper bounds both objectives and returns
34//! `tl`). The second objective is relaxed only by the solution pruning, so
35//! each tolerance is spent once: a pruned or merged path is covered by a
36//! returned one relative to its own apex, never through a chain of
37//! approximations. See [`pp_a_star`] for the argument.
38//! - Several goal states are allowed, through a predicate.
39//! - Merged pairs re-enter the open list as new entries; the old entry is
40//! skipped when popped.
41
42pub(crate) mod iterative;
43
44use alloc::collections::{BTreeMap, BinaryHeap};
45use alloc::vec::Vec;
46use core::cmp::Reverse;
47use core::mem;
48
49pub use iterative::pp_a_star_iterative;
50
51use search_core::{Cost, Heuristic};
52
53use crate::cost::add;
54use crate::epsilon::Epsilon;
55use crate::graph::Graph;
56use crate::output::{Output, Solution, Stats};
57
58/// PP-A*: finds a set of solutions that covers the Pareto-optimal front
59/// within a factor `1 + eps[i]` in each objective `i`.
60///
61/// Requirements, not checked at run time:
62///
63/// - edge costs are non-negative;
64/// - `heuristic` is consistent in both objectives and zero on every goal.
65///
66/// Guarantees:
67///
68/// - for every Pareto-optimal cost vector `s` some returned solution `r`
69/// has `r[0] <= (1 + eps[0]) · s[0]` and `r[1] <= (1 + eps[1]) · s[1]`;
70/// - the returned solutions are real paths with their exact costs, mutually
71/// non-dominated, sorted by the first objective strictly ascending and so
72/// by the second strictly descending. Unlike [`boa_star_eps`](crate::boa_star_eps),
73/// a returned solution need not be Pareto-optimal itself;
74/// - `eps = [Epsilon::ZERO; 2]` returns exactly the cost vectors of
75/// [`boa_star`](crate::boa_star).
76///
77/// # Why the guarantee holds
78///
79/// Call a pair *covered* when, for every path `p` at its state whose cost is
80/// at or above its apex `a` and every suffix to a goal, some returned
81/// solution is within the tolerances of the completed path. Pop order keeps
82/// apex `f1` non-decreasing (merging only lowers the apex to that of one of
83/// the two pairs, both still open). Then:
84///
85/// - a bounded pair that reaches a goal is covered by its `br`: `c1(br) <=
86/// (1 + ε1) · a1` and `c2(br) = a2`; extending both by a suffix keeps the
87/// bound, since `b + c <= (1 + ε1) · a + c <= (1 + ε1) · (a + c)`;
88/// - merging lowers the apex component-wise, so the merged pair covers
89/// both;
90/// - a pair dropped by the solution test is covered by the last solution
91/// `r`: `r[0] <= (1 + ε1) · ` its apex `f1`, which is at most the dropped
92/// pair's `f1`, and `r[1] <= (1 + ε2) · f2`;
93/// - a pair dropped by the per-state test has its apex at or above that of
94/// a pair already expanded there.
95///
96/// Every bound is relative to an apex, which only goes down along these
97/// steps, so the tolerances never compound.
98///
99/// # Examples
100///
101/// ```
102/// use multiobjective_search::{Epsilon, Graph, ZeroHeuristic, boa_star, pp_a_star};
103///
104/// /// Four routes from 0 to 1 on a convex front.
105/// struct Routes;
106///
107/// impl Graph for Routes {
108/// type State = u8;
109/// type Weight = [u32; 2];
110///
111/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
112/// if *state == 0 {
113/// out.extend([(1, [100, 40]), (1, [105, 30]), (1, [150, 20]), (1, [200, 19])]);
114/// }
115/// }
116/// }
117///
118/// let eps = [Epsilon::new(1, 10), Epsilon::new(1, 10)];
119/// let out = pp_a_star(&Routes, ZeroHeuristic, 0, |s| *s == 1, eps);
120/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
121/// // [105, 30] covers [100, 40]; [150, 20] covers [200, 19].
122/// assert_eq!(costs, [[105, 30], [150, 20]]);
123///
124/// let exact = pp_a_star(&Routes, ZeroHeuristic, 0, |s| *s == 1, [Epsilon::ZERO; 2]);
125/// assert_eq!(exact.solutions.len(), boa_star(&Routes, ZeroHeuristic, 0, |s| *s == 1).solutions.len());
126/// ```
127pub fn pp_a_star<G, H, C, P>(
128 graph: &G,
129 heuristic: H,
130 start: G::State,
131 is_goal: P,
132 eps: [Epsilon; 2],
133) -> Output<G::State, [C; 2]>
134where
135 G: Graph<Weight = [C; 2]>,
136 H: Heuristic<G::State, [C; 2]>,
137 C: Cost,
138 P: Fn(&G::State) -> bool,
139{
140 let mut search = Search {
141 graph,
142 heuristic,
143 is_goal,
144 eps,
145 paths: Vec::new(),
146 pairs: Vec::new(),
147 open: BinaryHeap::new(),
148 states: BTreeMap::new(),
149 solutions: Vec::new(),
150 successors: Vec::new(),
151 stats: Stats::default(),
152 };
153
154 search.push_start(start);
155 while let Some(Reverse((_, index))) = search.open.pop() {
156 search.process(index);
157 }
158
159 search.into_output()
160}
161
162/// One path in the path arena: its last state, its cost and its parent.
163struct PathNode<S, C> {
164 /// The state this path ends in.
165 state: S,
166 /// Cost vector of the path from the start.
167 g: [C; 2],
168 /// Arena index of the path without its last edge; `None` for the start.
169 parent: Option<usize>,
170}
171
172/// A path pair: two paths to the same state.
173#[derive(Clone, Copy)]
174struct Pair<C> {
175 /// Path arena index of the top-left path, which has the smallest first
176 /// cost of the pair.
177 tl: usize,
178 /// Path arena index of the bottom-right path, which has the smallest
179 /// second cost. Equal to `tl` for a pair of one path.
180 br: usize,
181 /// Heuristic estimate at the pair's state.
182 h: [C; 2],
183 /// `false` once the pair was merged into another; its open-list entry
184 /// is then skipped.
185 alive: bool,
186}
187
188/// Per-state bookkeeping.
189struct StateInfo<C> {
190 /// Second cost of the `br` path of the last pair expanded here, the
191 /// smallest so far; `None` before the first.
192 g2_min: Option<C>,
193 /// Pair arena indices of this state's pairs on the open list.
194 open: Vec<usize>,
195}
196
197/// Mutable state of one PP-A* run.
198struct Search<'a, G: Graph, H, C, P> {
199 /// The graph being searched.
200 graph: &'a G,
201 /// Per-objective lower bounds on the remaining cost.
202 heuristic: H,
203 /// Goal test.
204 is_goal: P,
205 /// Tolerances per objective.
206 eps: [Epsilon; 2],
207 /// Every path that is part of some pair; pairs and parents index into
208 /// it.
209 paths: Vec<PathNode<G::State, C>>,
210 /// Every pair ever pushed; open-list entries index into it.
211 pairs: Vec<Pair<C>>,
212 /// Open list as a min-heap on `(apex f, pair index)`, compared
213 /// lexicographically.
214 open: BinaryHeap<Reverse<([C; 2], usize)>>,
215 /// Per-state bookkeeping. Absent means "not reached yet".
216 states: BTreeMap<G::State, StateInfo<C>>,
217 /// Solution pairs as `(tl, br)` path indices, in the order found; their
218 /// `br` second costs strictly descend.
219 solutions: Vec<(usize, usize)>,
220 /// Reused successor buffer, empty between expansions.
221 successors: Vec<(G::State, [C; 2])>,
222 /// Effort counters.
223 stats: Stats,
224}
225
226impl<G, H, C, P> Search<'_, G, H, C, P>
227where
228 G: Graph<Weight = [C; 2]>,
229 H: Heuristic<G::State, [C; 2]>,
230 C: Cost,
231 P: Fn(&G::State) -> bool,
232{
233 /// Pushes the start pair, unless the heuristic reports a dead end.
234 fn push_start(&mut self, start: G::State) {
235 if let Some(h) = self.heuristic.estimate(&start) {
236 let path = self.new_path(start, [C::ZERO; 2], None);
237 self.push(Pair {
238 tl: path,
239 br: path,
240 h,
241 alive: true,
242 });
243 }
244 }
245
246 /// Handles one pair taken from the open list: skip it if merged away,
247 /// prune it, record a solution, or expand it.
248 fn process(&mut self, index: usize) {
249 let pair = self.pairs[index];
250 if !pair.alive {
251 return;
252 }
253
254 let state = self.paths[pair.br].state.clone();
255 let info = self.info_mut(&state);
256 info.open.retain(|&i| i != index);
257
258 let g2 = self.paths[pair.br].g[1];
259 if self.is_dominated(&state, g2, g2 + pair.h[1]) {
260 return;
261 }
262
263 self.info_mut(&state).g2_min = Some(g2);
264
265 if (self.is_goal)(&state) {
266 self.add_solution(pair);
267 } else {
268 self.expand(pair);
269 }
270 }
271
272 /// Returns `true` if a pair at `state` whose `br` has second cost `g2`
273 /// and second estimate `f2` is covered by the last solution or by a
274 /// pair already expanded at `state`.
275 fn is_dominated(&self, state: &G::State, g2: C, f2: C) -> bool {
276 self.best_g2()
277 .is_some_and(|best| self.eps[1].within(best, f2))
278 || self
279 .states
280 .get(state)
281 .and_then(|info| info.g2_min)
282 .is_some_and(|min| g2 >= min)
283 }
284
285 /// Second cost of the last solution, the smallest so far.
286 fn best_g2(&self) -> Option<C> {
287 self.solutions.last().map(|&(_, br)| self.paths[br].g[1])
288 }
289
290 /// Records a goal pair: merges it into the last solution if the merged
291 /// pair is bounded, else adds it as a new solution.
292 fn add_solution(&mut self, pair: Pair<C>) {
293 if let Some(last) = self.solutions.last_mut() {
294 // The last solution's tl has the smaller first cost (pop order),
295 // the new br the smaller second cost (it passed the solution test).
296 if self.eps[0].within(self.paths[pair.br].g[0], self.paths[last.0].g[0]) {
297 last.1 = pair.br;
298 return;
299 }
300 }
301
302 self.solutions.push((pair.tl, pair.br));
303 }
304
305 /// Extends both paths of `pair` along every outgoing edge and inserts
306 /// the surviving pairs.
307 fn expand(&mut self, pair: Pair<C>) {
308 self.stats.expanded += 1;
309
310 let mut successors = mem::take(&mut self.successors);
311 let from = self.paths[pair.br].state.clone();
312 self.graph.successors(&from, &mut successors);
313
314 for (state, weight) in successors.drain(..) {
315 let Some(h) = self.heuristic.estimate(&state) else {
316 continue;
317 };
318
319 let g_br = add(self.paths[pair.br].g, weight);
320 if self.is_dominated(&state, g_br[1], g_br[1] + h[1]) {
321 continue;
322 }
323
324 let br = self.new_path(state.clone(), g_br, Some(pair.br));
325 let tl = if pair.tl == pair.br {
326 br
327 } else {
328 let g_tl = add(self.paths[pair.tl].g, weight);
329 self.new_path(state, g_tl, Some(pair.tl))
330 };
331
332 self.insert(Pair {
333 tl,
334 br,
335 h,
336 alive: true,
337 });
338 }
339
340 self.successors = successors;
341 }
342
343 /// Merges `pair` into the first open pair at its state for which the
344 /// merged pair is bounded, or pushes it as is.
345 fn insert(&mut self, pair: Pair<C>) {
346 let state = self.paths[pair.br].state.clone();
347 let open = self
348 .states
349 .get(&state)
350 .map_or(&[][..], |info| &info.open[..]);
351 let found = open.iter().enumerate().find_map(|(position, &other)| {
352 let merged = self.merge(pair, self.pairs[other]);
353 self.is_bounded(merged).then_some((position, other, merged))
354 });
355
356 if let Some((position, other, merged)) = found {
357 self.pairs[other].alive = false;
358 self.info_mut(&state).open.swap_remove(position);
359 self.push(merged);
360 return;
361 }
362
363 self.push(pair);
364 }
365
366 /// The pair made of the smaller-first-cost `tl` and the
367 /// smaller-second-cost `br` of `a` and `b`; ties go to `a`.
368 fn merge(&self, a: Pair<C>, b: Pair<C>) -> Pair<C> {
369 let first = |i: usize| self.paths[i].g[0];
370 let second = |i: usize| self.paths[i].g[1];
371
372 Pair {
373 tl: if first(b.tl) < first(a.tl) {
374 b.tl
375 } else {
376 a.tl
377 },
378 br: if second(b.br) < second(a.br) {
379 b.br
380 } else {
381 a.br
382 },
383 h: a.h,
384 alive: true,
385 }
386 }
387
388 /// Returns `true` if `c1(br) <= (1 + ε1) · c1(tl)`.
389 fn is_bounded(&self, pair: Pair<C>) -> bool {
390 self.eps[0].within(self.paths[pair.br].g[0], self.paths[pair.tl].g[0])
391 }
392
393 /// Adds a pair to the pair arena, the open list and its state's open
394 /// pairs.
395 fn push(&mut self, pair: Pair<C>) {
396 let index = self.pairs.len();
397 let apex = [
398 self.paths[pair.tl].g[0] + pair.h[0],
399 self.paths[pair.br].g[1] + pair.h[1],
400 ];
401 let state = self.paths[pair.br].state.clone();
402
403 self.pairs.push(pair);
404 self.open.push(Reverse((apex, index)));
405 self.info_mut(&state).open.push(index);
406 self.stats.generated += 1;
407 }
408
409 /// Adds a path to the path arena and returns its index.
410 fn new_path(&mut self, state: G::State, g: [C; 2], parent: Option<usize>) -> usize {
411 self.paths.push(PathNode { state, g, parent });
412 self.paths.len() - 1
413 }
414
415 /// The bookkeeping of `state`, created on first use.
416 fn info_mut(&mut self, state: &G::State) -> &mut StateInfo<C> {
417 self.states
418 .entry(state.clone())
419 .or_insert_with(|| StateInfo {
420 g2_min: None,
421 open: Vec::new(),
422 })
423 }
424
425 /// Consumes the search and returns the non-dominated `br` paths of the
426 /// solution pairs, sorted, with the counters.
427 fn into_output(self) -> Output<G::State, [C; 2]> {
428 let mut costs: Vec<_> = self
429 .solutions
430 .iter()
431 .map(|&(_, br)| (self.paths[br].g, br))
432 .collect();
433 costs.sort_unstable();
434
435 let mut solutions: Vec<Solution<G::State, [C; 2]>> = Vec::new();
436 for (cost, br) in costs {
437 // Sorted by first cost: keep a point only if it strictly lowers
438 // the second cost, which drops every dominated or equal one.
439 if solutions.last().is_none_or(|last| cost[1] < last.cost[1]) {
440 solutions.push(self.solution(br, cost));
441 }
442 }
443
444 Output {
445 solutions,
446 stats: self.stats,
447 }
448 }
449
450 /// Rebuilds the path ending in path node `index`.
451 fn solution(&self, index: usize, cost: [C; 2]) -> Solution<G::State, [C; 2]> {
452 let mut path = Vec::new();
453 let mut current = Some(index);
454
455 while let Some(i) = current {
456 path.push(self.paths[i].state.clone());
457 current = self.paths[i].parent;
458 }
459
460 path.reverse();
461
462 Solution { cost, path }
463 }
464}