multiobjective_search/label_correcting.rs
1//! The multi-objective label-correcting algorithm.
2//!
3//! Guerriero and Musmanno, "Label correcting methods to solve
4//! multicriteria shortest path problems", JOTA 2001; the first of the two
5//! classic approaches the survey of Salzman et al. (arXiv 2510.25504,
6//! Section 3.1) names, beside the A*-based label setting.
7
8use alloc::collections::{BTreeMap, BTreeSet, VecDeque};
9use alloc::vec::Vec;
10
11use search_core::Cost;
12
13use crate::cost::{add, weakly_dominates};
14use crate::graph::Graph;
15use crate::output::{Output, Solution, Stats};
16use crate::pareto::Front;
17
18/// Finds one path for every Pareto-optimal cost vector from `start` to a
19/// state that satisfies `is_goal`, by label correcting.
20///
21/// Every state keeps its set of non-dominated labels. A FIFO queue holds
22/// the states whose set changed; taking one, the labels added since its
23/// last visit are extended along every edge and merged into the successors'
24/// sets, which drops the labels they dominate and enqueues the successors
25/// that changed. Unlike label setting, a label can be replaced after it
26/// was extended. Search at a goal are kept but not extended, and a label
27/// weakly dominated by a goal label is not extended either. The result is
28/// the non-dominated goal labels.
29///
30/// Requirements: non-negative edge costs (no heuristic is used).
31///
32/// # Panics
33///
34/// Never: every queued state has a label set.
35///
36/// # Examples
37///
38/// ```
39/// use multiobjective_search::{Graph, ZeroHeuristic, label_correcting, namoa_star};
40///
41/// /// A diamond: two routes from 0 to 3.
42/// struct Diamond;
43///
44/// impl Graph for Diamond {
45/// type State = u8;
46/// type Weight = [u32; 2];
47///
48/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
49/// match state {
50/// 0 => out.extend([(1, [1, 3]), (2, [3, 1])]),
51/// 1 | 2 => out.push((3, [1, 1])),
52/// _ => {}
53/// }
54/// }
55/// }
56///
57/// let a = label_correcting(&Diamond, 0, |s| *s == 3);
58/// let b = namoa_star(&Diamond, ZeroHeuristic, 0, |s| *s == 3);
59/// assert_eq!(a.solutions, b.solutions);
60/// ```
61pub fn label_correcting<G, C, P, const N: usize>(
62 graph: &G,
63 start: G::State,
64 is_goal: P,
65) -> Output<G::State, [C; N]>
66where
67 G: Graph<Weight = [C; N]>,
68 C: Cost,
69 P: Fn(&G::State) -> bool,
70{
71 let mut search = Search::new(start);
72 let mut goal_costs: Front<C, N> = Front::new();
73 let mut buffer = Vec::new();
74
75 while let Some(state) = search.queue.pop_front() {
76 search.queued.remove(&state);
77 let fresh = core::mem::take(
78 &mut search
79 .sets
80 .get_mut(&state)
81 .expect("queued states have labels")
82 .1,
83 );
84 if is_goal(&state) {
85 for &l in &fresh {
86 goal_costs.insert(search.labels[l].1);
87 }
88
89 continue;
90 }
91
92 graph.successors(&state, &mut buffer);
93 let edges = core::mem::take(&mut buffer);
94 for &l in &fresh {
95 // Skip labels replaced since they were added, or beaten by a goal.
96 let live = search.sets[&state].0.contains(&l);
97 if !live || goal_costs.weakly_dominates(&search.labels[l].1) {
98 continue;
99 }
100
101 search.stats.expanded += 1;
102 for (next, weight) in &edges {
103 search.extend(l, next, *weight);
104 }
105 }
106 }
107
108 search.into_output(&is_goal)
109}
110
111/// The labels, per-state label sets and FIFO queue of a label-correcting
112/// search.
113struct Search<S, C, const N: usize> {
114 /// Every label ever created as `(state, cost, parent label)`; indices
115 /// are stable, replaced labels stay as parents of others.
116 labels: Vec<(S, [C; N], Option<usize>)>,
117 /// Per state: the live label indices, and those not yet extended.
118 sets: BTreeMap<S, (Vec<usize>, Vec<usize>)>,
119 /// States whose label set changed since their last visit.
120 queue: VecDeque<S>,
121 /// The states currently in `queue`, so none is queued twice.
122 queued: BTreeSet<S>,
123 /// Expansion and generation counters.
124 stats: Stats,
125}
126
127impl<S: Clone + Ord, C: Cost, const N: usize> Search<S, C, N> {
128 /// The search state before the first step: one zero-cost label at
129 /// `start`, which is queued.
130 fn new(start: S) -> Self {
131 Self {
132 labels: alloc::vec![(start.clone(), [C::ZERO; N], None)],
133 sets: BTreeMap::from([(start.clone(), (alloc::vec![0], alloc::vec![0]))]),
134 queue: VecDeque::from([start]),
135 queued: BTreeSet::new(),
136 stats: Stats {
137 expanded: 0,
138 generated: 1,
139 },
140 }
141 }
142
143 /// Extends label `l` along an edge to `next` with cost `weight`, and
144 /// merges the new label into `next`'s set unless a live label there
145 /// weakly dominates it; labels it dominates leave the set, and `next`
146 /// is queued if it is not already.
147 fn extend(&mut self, l: usize, next: &S, weight: [C; N]) {
148 let cost = add(self.labels[l].1, weight);
149 let labels = &self.labels;
150 let entry = self.sets.entry(next.clone()).or_default();
151 if entry
152 .0
153 .iter()
154 .any(|&k| weakly_dominates(&labels[k].1, &cost))
155 {
156 return;
157 }
158
159 entry.0.retain(|&k| !weakly_dominates(&cost, &labels[k].1));
160 entry.1.retain(|&k| !weakly_dominates(&cost, &labels[k].1));
161 let id = self.labels.len();
162 entry.0.push(id);
163 entry.1.push(id);
164 self.labels.push((next.clone(), cost, Some(l)));
165 self.stats.generated += 1;
166 if self.queued.insert(next.clone()) {
167 self.queue.push_back(next.clone());
168 }
169 }
170
171 /// The non-dominated live labels at goal states, in lexicographic cost
172 /// order, with their paths traced back to the start.
173 fn into_output(self, is_goal: impl Fn(&S) -> bool) -> Output<S, [C; N]> {
174 let labels = self.labels;
175 let mut ends: Vec<usize> = self
176 .sets
177 .iter()
178 .filter(|(s, _)| is_goal(s))
179 .flat_map(|(_, (live, _))| live.iter().copied())
180 .collect();
181 ends.sort_by_key(|&l| labels[l].1);
182
183 let mut front = Front::new();
184 let solutions = ends
185 .into_iter()
186 .filter(|&l| front.insert(labels[l].1))
187 .map(|l| {
188 let mut path = Vec::new();
189 let mut at = Some(l);
190 while let Some(i) = at {
191 path.push(labels[i].0.clone());
192 at = labels[i].2;
193 }
194
195 path.reverse();
196 Solution {
197 cost: labels[l].1,
198 path,
199 }
200 })
201 .collect();
202
203 Output {
204 solutions,
205 stats: self.stats,
206 }
207 }
208}