Skip to main content

multiobjective_search/
two_phase.rs

1//! The two-phase method for bi-objective shortest paths: the supported
2//! solutions by weighted sums first, then the non-supported ones between
3//! them.
4//!
5//! Ulungu and Teghem 1995; Raith and Ehrgott 2009 ("A comparison of
6//! solution strategies for biobjective shortest path problems"), as
7//! surveyed by Craveirinha et al., Algorithms 17(6):222, 2024, Section
8//! 2.2.1.
9
10use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
11use alloc::vec::Vec;
12use core::cmp::{Ordering, Reverse};
13
14use search_core::{Cost, Heuristic, WideMul};
15
16use crate::anytime_boa::lex::lex_first;
17use crate::constrained::rebuild;
18use crate::cost::add;
19use crate::graph::Graph;
20use crate::output::{Output, Solution, Stats};
21
22/// Phase 1: the extreme supported solutions, those whose costs are the
23/// vertices of the convex hull of the Pareto-optimal front, sorted by
24/// cost.
25///
26/// Dichotomic search (Aneja and Nair 1979): starting from the two
27/// lexicographic optima, for two neighbours `a` and `b` minimize the
28/// weighted sum `(a2 - b2) · c1 + (b1 - a1) · c2`, whose level line runs
29/// through `a` and `b`, and keep the minimizer if it lies strictly below
30/// that line. Weighted sums are compared exactly with [`WideMul`], ties
31/// broken lexicographically, so a minimizer is always a hull vertex.
32///
33/// Requirements, not checked at run time: non-negative costs and a
34/// `heuristic` consistent in both objectives and zero on every goal.
35///
36/// # Examples
37///
38/// ```
39/// use multiobjective_search::{Graph, ZeroHeuristic, supported_solutions};
40///
41/// /// Four routes from 0 to 1; (5, 5) lies above the hull of the others.
42/// struct Routes;
43///
44/// impl Graph for Routes {
45///     type State = u8;
46///     type Weight = [u32; 2];
47///
48///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
49///         if *state == 0 {
50///             out.extend([(1, [1, 9]), (1, [3, 3]), (1, [5, 5]), (1, [9, 1])]);
51///         }
52///     }
53/// }
54///
55/// let out = supported_solutions(&Routes, ZeroHeuristic, 0, |s| *s == 1);
56/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
57/// assert_eq!(costs, [[1, 9], [3, 3], [9, 1]]);
58/// ```
59#[expect(
60    clippy::needless_pass_by_value,
61    reason = "takes the start by value like every other search in the crate"
62)]
63pub fn supported_solutions<G, H, C, P>(
64    graph: &G,
65    mut heuristic: H,
66    start: G::State,
67    is_goal: P,
68) -> Output<G::State, [C; 2]>
69where
70    G: Graph<Weight = [C; 2]>,
71    H: Heuristic<G::State, [C; 2]>,
72    C: Cost + WideMul,
73    P: Fn(&G::State) -> bool,
74{
75    let mut stats = Stats::default();
76    let solutions = phase_one(graph, &mut heuristic, &start, &is_goal, &mut stats);
77
78    Output { solutions, stats }
79}
80
81/// The two-phase method: every Pareto-optimal cost, one path each, sorted
82/// by cost.
83///
84/// Phase 1 is [`supported_solutions`]. Phase 2 searches each triangle
85/// between two neighbouring supported solutions `a` and `b`: every other
86/// Pareto-optimal cost lies strictly inside the box `a1 < c1 < b1`,
87/// `b2 < c2 < a2`, found by BOA*'s label setting restricted to that box,
88/// with `a`'s second cost as the initial bound.
89///
90/// Same requirements as [`supported_solutions`]; the result equals
91/// [`boa_star`](crate::boa_star)'s.
92///
93/// # Examples
94///
95/// ```
96/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star, two_phase};
97///
98/// /// Four routes from 0 to 1; (5, 5) is non-supported.
99/// struct Routes;
100///
101/// impl Graph for Routes {
102///     type State = u8;
103///     type Weight = [u32; 2];
104///
105///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
106///         if *state == 0 {
107///             out.extend([(1, [1, 9]), (1, [2, 8]), (1, [5, 5]), (1, [9, 1])]);
108///         }
109///     }
110/// }
111///
112/// let both = two_phase(&Routes, ZeroHeuristic, 0, |s| *s == 1);
113/// let exact = boa_star(&Routes, ZeroHeuristic, 0, |s| *s == 1);
114/// assert_eq!(both.solutions, exact.solutions);
115/// ```
116#[expect(
117    clippy::needless_pass_by_value,
118    reason = "takes the start by value like every other search in the crate"
119)]
120pub fn two_phase<G, H, C, P>(
121    graph: &G,
122    mut heuristic: H,
123    start: G::State,
124    is_goal: P,
125) -> Output<G::State, [C; 2]>
126where
127    G: Graph<Weight = [C; 2]>,
128    H: Heuristic<G::State, [C; 2]>,
129    C: Cost + WideMul,
130    P: Fn(&G::State) -> bool,
131{
132    let mut stats = Stats::default();
133    let supported = phase_one(graph, &mut heuristic, &start, &is_goal, &mut stats);
134
135    let mut solutions = Vec::new();
136    for pair in supported.windows(2) {
137        let (a, b) = (pair[0].cost, pair[1].cost);
138        solutions.extend(in_box(
139            graph,
140            &mut heuristic,
141            &start,
142            &is_goal,
143            a,
144            b,
145            &mut stats,
146        ));
147    }
148
149    solutions.extend(supported);
150    solutions.sort_by_key(|s| s.cost);
151
152    Output { solutions, stats }
153}
154
155/// The dichotomic search of phase 1.
156fn phase_one<G, H, C, P>(
157    graph: &G,
158    heuristic: &mut H,
159    start: &G::State,
160    is_goal: &P,
161    stats: &mut Stats,
162) -> Vec<Solution<G::State, [C; 2]>>
163where
164    G: Graph<Weight = [C; 2]>,
165    H: Heuristic<G::State, [C; 2]>,
166    C: Cost + WideMul,
167    P: Fn(&G::State) -> bool,
168{
169    let Some(left) = lex_first(graph, heuristic, start, is_goal, 0, stats) else {
170        return Vec::new();
171    };
172    let right = lex_first(graph, heuristic, start, is_goal, 1, stats)
173        .expect("reachable in one order, reachable in the other");
174    if left.cost == right.cost {
175        return alloc::vec![left];
176    }
177
178    let mut found = alloc::vec![left];
179    let mut pending = alloc::vec![right];
180    while let Some(b) = pending.pop() {
181        let a = found.last().expect("starts with the left optimum").cost;
182        let weights = [a[1].abs_diff(b.cost[1]), b.cost[0].abs_diff(a[0])];
183        let best = weighted_best(graph, heuristic, start, is_goal, weights, stats)
184            .expect("a solution exists");
185
186        if weighted_cmp(weights, best.cost, a) == Ordering::Less {
187            pending.push(b);
188            pending.push(best);
189        } else {
190            found.push(b);
191        }
192    }
193
194    found
195}
196
197/// Compares `w1 · x1 + w2 · x2` with `w1 · y1 + w2 · y2` exactly.
198fn weighted_cmp<C: Cost + WideMul>(w: [C; 2], x: [C; 2], y: [C; 2]) -> Ordering {
199    let part = |i: usize| (x[i].cmp(&y[i]), w[i].wide_mul(x[i].abs_diff(y[i])));
200    let ((s1, m1), (s2, m2)) = (part(0), part(1));
201
202    match (s1, s2) {
203        (Ordering::Equal, s) | (s, Ordering::Equal) => s,
204        (left, right) if left == right => left,
205        // Opposite signs: the larger magnitude decides.
206        (Ordering::Greater, _) => m1.cmp(&m2),
207        (Ordering::Less, _) => m2.cmp(&m1),
208    }
209}
210
211/// A* on the weighted sum `w · f`, ties broken lexicographically on `f`:
212/// the goal path with the smallest weighted cost.
213fn weighted_best<G, H, C, P>(
214    graph: &G,
215    heuristic: &mut H,
216    start: &G::State,
217    is_goal: &P,
218    weights: [C; 2],
219    stats: &mut Stats,
220) -> Option<Solution<G::State, [C; 2]>>
221where
222    G: Graph<Weight = [C; 2]>,
223    H: Heuristic<G::State, [C; 2]>,
224    C: Cost + WideMul,
225    P: Fn(&G::State) -> bool,
226{
227    let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
228    let mut open = BinaryHeap::new();
229    let mut closed = BTreeSet::new();
230    let mut successors = Vec::new();
231
232    let h = heuristic.estimate(start)?;
233    nodes.push((start.clone(), [C::ZERO; 2], None));
234    open.push(Reverse(Weighted {
235        weights,
236        f: h,
237        index: 0,
238    }));
239    stats.generated += 1;
240
241    while let Some(Reverse(Weighted { index, .. })) = open.pop() {
242        let (here, g, _) = nodes[index].clone();
243        if !closed.insert(here.clone()) {
244            continue;
245        }
246
247        if is_goal(&here) {
248            return Some(rebuild(&nodes, index));
249        }
250
251        stats.expanded += 1;
252        graph.successors(&here, &mut successors);
253        for (next, weight) in successors.drain(..) {
254            if closed.contains(&next) {
255                continue;
256            }
257
258            let Some(h) = heuristic.estimate(&next) else {
259                continue;
260            };
261
262            let g_next = add(g, weight);
263            nodes.push((next, g_next, Some(index)));
264            open.push(Reverse(Weighted {
265                weights,
266                f: add(g_next, h),
267                index: nodes.len() - 1,
268            }));
269            stats.generated += 1;
270        }
271    }
272
273    None
274}
275
276/// An open-list entry ordered by its weighted `f`, then by `f`, then by
277/// arena index.
278struct Weighted<C> {
279    /// The scalarization weights, the same for every entry.
280    weights: [C; 2],
281    /// `g + h`.
282    f: [C; 2],
283    /// Arena index.
284    index: usize,
285}
286
287impl<C: Cost + WideMul> PartialEq for Weighted<C> {
288    fn eq(&self, other: &Self) -> bool {
289        self.cmp(other) == Ordering::Equal
290    }
291}
292
293impl<C: Cost + WideMul> Eq for Weighted<C> {}
294
295impl<C: Cost + WideMul> PartialOrd for Weighted<C> {
296    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
297        Some(self.cmp(other))
298    }
299}
300
301impl<C: Cost + WideMul> Ord for Weighted<C> {
302    fn cmp(&self, other: &Self) -> Ordering {
303        weighted_cmp(self.weights, self.f, other.f)
304            .then(self.f.cmp(&other.f))
305            .then(self.index.cmp(&other.index))
306    }
307}
308
309/// Phase 2 for one triangle: the Pareto-optimal solutions strictly inside
310/// the box between neighbouring supported solutions `a` and `b`, by BOA*'s
311/// pruning with `f1 < b1` and `a2` as the initial solution bound.
312fn in_box<G, H, C, P>(
313    graph: &G,
314    heuristic: &mut H,
315    start: &G::State,
316    is_goal: &P,
317    left: [C; 2],
318    right: [C; 2],
319    stats: &mut Stats,
320) -> Vec<Solution<G::State, [C; 2]>>
321where
322    G: Graph<Weight = [C; 2]>,
323    H: Heuristic<G::State, [C; 2]>,
324    C: Cost,
325    P: Fn(&G::State) -> bool,
326{
327    let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
328    let mut open = BinaryHeap::new();
329    let mut g2_min: BTreeMap<G::State, C> = BTreeMap::new();
330    let mut bound = left[1];
331    let mut found = Vec::new();
332    let mut successors = Vec::new();
333    let outside = |f: [C; 2], bound: C| f[0] >= right[0] || f[1] >= bound;
334
335    let Some(h) = heuristic.estimate(start) else {
336        return found;
337    };
338    nodes.push((start.clone(), [C::ZERO; 2], None));
339    open.push(Reverse((h, 0)));
340    stats.generated += 1;
341
342    while let Some(Reverse((f, index))) = open.pop() {
343        let (here, g, _) = nodes[index].clone();
344        if outside(f, bound) || g2_min.get(&here).is_some_and(|&m| g[1] >= m) {
345            continue;
346        }
347
348        g2_min.insert(here.clone(), g[1]);
349        if is_goal(&here) {
350            bound = g[1];
351            found.push(rebuild(&nodes, index));
352            continue;
353        }
354
355        stats.expanded += 1;
356        graph.successors(&here, &mut successors);
357        for (next, weight) in successors.drain(..) {
358            let g_next = add(g, weight);
359            if g2_min.get(&next).is_some_and(|&m| g_next[1] >= m) {
360                continue;
361            }
362
363            let Some(h) = heuristic.estimate(&next) else {
364                continue;
365            };
366
367            let f = add(g_next, h);
368            if !outside(f, bound) {
369                nodes.push((next, g_next, Some(index)));
370                open.push(Reverse((f, nodes.len() - 1)));
371                stats.generated += 1;
372            }
373        }
374    }
375
376    // Pareto-optimality of `a` and `b` already keeps every solution found
377    // strictly inside; the filter only documents the box.
378    found.retain(|s| s.cost[0] > left[0] && s.cost[1] > right[1]);
379    found
380}