Skip to main content

multiobjective_search/
ranking.rs

1//! The ranking method for bi-objective shortest paths: enumerate loopless
2//! paths in order of the first objective and keep the efficient ones.
3//!
4//! ClĂ­maco and Martins, "A bicriterion shortest path algorithm", EJOR 1982;
5//! the ranking class of Craveirinha et al., Algorithms 17(6):222, 2024
6//! (Algorithm 2 there, "Generic biobjective ranking method").
7
8use alloc::collections::BinaryHeap;
9use alloc::vec::Vec;
10use core::cmp::Reverse;
11
12use search_core::{Cost, Heuristic};
13
14use crate::anytime_boa::lex::lex_first;
15use crate::constrained::rebuild;
16use crate::cost::add;
17use crate::graph::Graph;
18use crate::output::{Output, Stats};
19
20/// Finds one path for every Pareto-optimal cost vector by ranking: loopless
21/// paths from `start` to a goal are generated in lexicographic `(c1, c2)`
22/// order (a best-first k-shortest-path enumeration), and a path is kept when
23/// its second cost is below every kept one. The enumeration stops after the
24/// first cost of the lexicographically `(c2, c1)`-optimal path, beyond
25/// which nothing is efficient.
26///
27/// This is the classic ranking approach, exponential in the worst case and
28/// much slower than [`boa_star`](crate::boa_star); it is here as the
29/// reference the survey describes and for comparison. Goal states end a
30/// path.
31///
32/// Requirements, not checked at run time: non-negative costs and a
33/// `heuristic` consistent in both objectives and zero on every goal.
34///
35/// # Examples
36///
37/// ```
38/// use multiobjective_search::{Graph, ZeroHeuristic, boa_star, ranking};
39///
40/// /// A diamond: two routes from 0 to 3.
41/// struct Diamond;
42///
43/// impl Graph for Diamond {
44///     type State = u8;
45///     type Weight = [u32; 2];
46///
47///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
48///         match state {
49///             0 => out.extend([(1, [1, 3]), (2, [3, 1])]),
50///             1 | 2 => out.push((3, [1, 1])),
51///             _ => {}
52///         }
53///     }
54/// }
55///
56/// let ranked = ranking(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
57/// let exact = boa_star(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
58/// assert_eq!(ranked.solutions, exact.solutions);
59/// ```
60pub fn ranking<G, H, C, P>(
61    graph: &G,
62    mut heuristic: H,
63    start: G::State,
64    is_goal: P,
65) -> Output<G::State, [C; 2]>
66where
67    G: Graph<Weight = [C; 2]>,
68    H: Heuristic<G::State, [C; 2]>,
69    C: Cost,
70    P: Fn(&G::State) -> bool,
71{
72    let mut stats = Stats::default();
73    let mut solutions = Vec::new();
74    let Some(last) = lex_first(graph, &mut heuristic, &start, &is_goal, 1, &mut stats) else {
75        return Output { solutions, stats };
76    };
77    let bound = last.cost[0];
78
79    let mut nodes: Vec<(G::State, [C; 2], Option<usize>)> = Vec::new();
80    let mut open = BinaryHeap::new();
81    let mut best_c2: Option<C> = None;
82    let mut successors = Vec::new();
83
84    if let Some(h) = heuristic.estimate(&start) {
85        nodes.push((start, [C::ZERO; 2], None));
86        open.push(Reverse((h, 0)));
87        stats.generated += 1;
88    }
89
90    while let Some(Reverse((f, index))) = open.pop() {
91        if f[0] > bound {
92            break;
93        }
94
95        let (here, g, _) = nodes[index].clone();
96        if is_goal(&here) {
97            if best_c2.is_none_or(|b| g[1] < b) {
98                best_c2 = Some(g[1]);
99                solutions.push(rebuild(&nodes, index));
100            }
101
102            continue;
103        }
104
105        stats.expanded += 1;
106        graph.successors(&here, &mut successors);
107        for (next, weight) in successors.drain(..) {
108            if on_path(&nodes, index, &next) {
109                continue;
110            }
111
112            let Some(h) = heuristic.estimate(&next) else {
113                continue;
114            };
115
116            let g_next = add(g, weight);
117            nodes.push((next, g_next, Some(index)));
118            open.push(Reverse((add(g_next, h), nodes.len() - 1)));
119            stats.generated += 1;
120        }
121    }
122
123    Output { solutions, stats }
124}
125
126/// Returns `true` if `state` already lies on the path ending in `index`.
127fn on_path<S: PartialEq, C>(nodes: &[(S, [C; 2], Option<usize>)], index: usize, state: &S) -> bool {
128    let mut current = Some(index);
129    while let Some(i) = current {
130        if nodes[i].0 == *state {
131            return true;
132        }
133
134        current = nodes[i].2;
135    }
136
137    false
138}