Skip to main content

multiobjective_search/disjoint/
pairs.rs

1//! Exact bi-objective fronts of path pairs, by label setting over the
2//! space of partial pairs.
3
4use alloc::collections::BTreeSet;
5use alloc::vec::Vec;
6
7use search_core::Cost;
8
9use crate::boa::boa_star;
10use crate::disjoint::{CostedPair, Disjointness, PathPair};
11use crate::graph::{EdgeGraph, Graph, ZeroHeuristic};
12use crate::output::Solution;
13
14/// The full Pareto-optimal front of disjoint path pairs from `start` to
15/// `target`, the costs `(c1, c2)` summed over both paths: one pair per
16/// non-dominated total, sorted by cost.
17///
18/// The bicriteria disjoint path pair problem of Clímaco and Pascoal
19/// (2009), supported and non-supported pairs alike. A pair is built as a
20/// path in the space of partial pairs: the first path from `start` to
21/// `target`, then the second, each state remembering the edges (or, for
22/// [`Disjointness::States`], the states) already used, so that a pair is a
23/// path there and its cost is the sum of both. Both paths are kept simple,
24/// which loses nothing: cutting a cycle never raises a cost. BOA* over that space returns
25/// exactly the non-dominated totals. The space grows exponentially with
26/// the graph, as every exact method for this NP-hard problem does; use it
27/// on small graphs, and [`supported_disjoint_pairs`](crate::supported_disjoint_pairs)
28/// for the polynomial supported part.
29///
30/// Requirements: non-negative costs, a finite graph, `start != target`.
31///
32/// # Examples
33///
34/// ```
35/// use multiobjective_search::{Disjointness, EdgeGraph, Graph, disjoint_pair_front};
36///
37/// /// Three parallel routes from 0 to 1.
38/// struct Routes;
39///
40/// const EDGES: [[u32; 2]; 3] = [[1, 9], [5, 5], [9, 1]];
41///
42/// impl Graph for Routes {
43///     type State = u8;
44///     type Weight = [u32; 2];
45///
46///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
47///         if *state == 0 {
48///             out.extend(EDGES.iter().map(|&w| (1, w)));
49///         }
50///     }
51/// }
52///
53/// impl EdgeGraph for Routes {
54///     type Edge = usize;
55///
56///     fn edges(&self, state: &u8, out: &mut Vec<(usize, u8, [u32; 2])>) {
57///         if *state == 0 {
58///             out.extend(EDGES.iter().enumerate().map(|(i, &w)| (i, 1, w)));
59///         }
60///     }
61/// }
62///
63/// let front = disjoint_pair_front(&Routes, &0, &1, Disjointness::Edges);
64/// let costs: Vec<_> = front.iter().map(|(_, c)| *c).collect();
65/// assert_eq!(costs, [[6, 14], [10, 10], [14, 6]]); // (10, 10) is not extreme
66/// ```
67pub fn disjoint_pair_front<G, C>(
68    graph: &G,
69    start: &G::State,
70    target: &G::State,
71    kind: Disjointness,
72) -> Vec<CostedPair<G::State, G::Edge, [C; 2]>>
73where
74    G: EdgeGraph<Weight = [C; 2]>,
75    C: Cost,
76{
77    let mode = match kind {
78        Disjointness::Edges => Mode::Edges,
79        Disjointness::States => Mode::States,
80    };
81
82    solve(graph, start, target, mode, |w: &[C; 2]| *w, C::ZERO)
83}
84
85/// The maximally disjoint pairs: the Pareto-optimal trade-offs between the
86/// total cost of two paths from `start` to `target` and the number of
87/// edges they share, as `(pair, total cost, shared edges)` sorted by cost.
88///
89/// The relaxed maximally disjoint path pair problem (Pascoal and Clímaco
90/// 2020) is a bi-objective two-unit flow: every edge carries one unit at
91/// its cost, or two units at twice its cost and one shared edge. The
92/// shared-edge count is small and integral, so the front is solved exactly
93/// as an ε-constraint family over it at once: BOA* over the space of
94/// partial pairs with objectives `(cost, shared)`, the first path edge-
95/// simple, the second allowed onto the first's edges at a count of one each.
96/// The pair with zero shared edges, if any, is
97/// [`disjoint_pair`](crate::disjoint_pair)'s.
98///
99/// Requirements: non-negative `cost`, a finite graph, `start != target`.
100///
101/// # Examples
102///
103/// ```
104/// use multiobjective_search::{EdgeGraph, Graph, maximally_disjoint_pairs};
105///
106/// /// A bridge 0 → 1 that both paths must cross, then two ways to 2.
107/// struct Bridge;
108///
109/// const EDGES: [(u8, u8, u32); 3] = [(0, 1, 1), (1, 2, 1), (1, 2, 3)];
110///
111/// impl Graph for Bridge {
112///     type State = u8;
113///     type Weight = u32;
114///
115///     fn successors(&self, state: &u8, out: &mut Vec<(u8, u32)>) {
116///         out.extend(EDGES.iter().filter(|e| e.0 == *state).map(|e| (e.1, e.2)));
117///     }
118/// }
119///
120/// impl EdgeGraph for Bridge {
121///     type Edge = usize;
122///
123///     fn edges(&self, state: &u8, out: &mut Vec<(usize, u8, u32)>) {
124///         out.extend(EDGES.iter().enumerate().filter(|(_, e)| e.0 == *state).map(|(i, e)| (i, e.1, e.2)));
125///     }
126/// }
127///
128/// let front = maximally_disjoint_pairs(&Bridge, &0, &2, |w: &u32| *w);
129/// let trade: Vec<_> = front.iter().map(|(_, c, s)| (*c, *s)).collect();
130/// assert_eq!(trade, [(4, 2), (6, 1)]); // share both edges, or only the bridge
131/// ```
132pub fn maximally_disjoint_pairs<G, C, F>(
133    graph: &G,
134    start: &G::State,
135    target: &G::State,
136    cost: F,
137) -> Vec<SharedPair<G::State, G::Edge, C>>
138where
139    G: EdgeGraph,
140    C: Cost + From<u8>,
141    F: Fn(&G::Weight) -> C,
142{
143    let pairs = solve(
144        graph,
145        start,
146        target,
147        Mode::Shared,
148        |w| [cost(w), C::ZERO],
149        C::from(1),
150    );
151    pairs
152        .into_iter()
153        .map(|(pair, [total, _])| {
154            let shared = pair
155                .first_edges
156                .iter()
157                .filter(|e| pair.second_edges.contains(e))
158                .count();
159            (pair, total, shared)
160        })
161        .collect()
162}
163
164/// A pair with its total cost and its number of shared edges.
165pub type SharedPair<S, E, C> = (PathPair<S, E>, C, usize);
166
167/// What the second path may share with the first.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169enum Mode {
170    /// No edge.
171    Edges,
172    /// No state but the ends.
173    States,
174    /// Edges, each counted in the second objective.
175    Shared,
176}
177
178/// A partial pair: the first path so far, or the whole first path and the
179/// second so far.
180#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
181struct Partial<S, E> {
182    /// `false` while the first path is built.
183    second: bool,
184    /// The current end.
185    at: S,
186    /// The edges of the first path.
187    first_edges: BTreeSet<E>,
188    /// The edges of the second path.
189    second_edges: BTreeSet<E>,
190    /// The states of the first path.
191    first_states: BTreeSet<S>,
192    /// The states of the second path.
193    second_states: BTreeSet<S>,
194    /// The edge that led here; `None` at either start.
195    via: Option<E>,
196}
197
198/// The graph of partial pairs.
199struct Pairs<'a, G: Graph, F, C> {
200    /// The underlying graph.
201    graph: &'a G,
202    /// Where both paths start.
203    start: G::State,
204    /// Where both paths end.
205    target: G::State,
206    /// The sharing rule.
207    mode: Mode,
208    /// Edge cost vectors.
209    cost: F,
210    /// One shared edge in the second objective.
211    one: C,
212}
213
214impl<G, F, C> Graph for Pairs<'_, G, F, C>
215where
216    G: EdgeGraph,
217    F: Fn(&G::Weight) -> [C; 2],
218    C: Cost,
219{
220    type State = Partial<G::State, G::Edge>;
221    type Weight = [C; 2];
222
223    fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, [C; 2])>) {
224        if state.at == self.target {
225            if !state.second {
226                let mut next = state.clone();
227                next.second = true;
228                next.at = self.start.clone();
229                next.via = None;
230                next.second_states.insert(self.start.clone());
231                out.push((next, [C::ZERO; 2]));
232            }
233
234            return;
235        }
236
237        let mut edges = Vec::new();
238        self.graph.edges(&state.at, &mut edges);
239        for (edge, to, weight) in edges {
240            let mut cost = (self.cost)(&weight);
241            let mut next = state.clone();
242
243            if state.second {
244                // Each path is simple: removing a cycle never costs more
245                // and never adds a shared element.
246                if next.second_states.contains(&to) {
247                    continue;
248                }
249
250                let inner = to != self.target && to != self.start;
251                let blocked = match self.mode {
252                    Mode::Edges => next.first_edges.contains(&edge),
253                    Mode::States => {
254                        next.first_edges.contains(&edge)
255                            || (inner && next.first_states.contains(&to))
256                    }
257                    Mode::Shared => false,
258                };
259                if blocked {
260                    continue;
261                }
262
263                if self.mode == Mode::Shared && next.first_edges.contains(&edge) {
264                    cost[1] = self.one;
265                }
266
267                next.second_edges.insert(edge.clone());
268                next.second_states.insert(to.clone());
269            } else {
270                if next.first_states.contains(&to) {
271                    continue;
272                }
273
274                next.first_edges.insert(edge.clone());
275                next.first_states.insert(to.clone());
276            }
277
278            next.at = to;
279            next.via = Some(edge);
280            out.push((next, cost));
281        }
282    }
283}
284
285/// Runs BOA* over the partial pairs and maps the solutions back.
286fn solve<G, F, C>(
287    graph: &G,
288    start: &G::State,
289    target: &G::State,
290    mode: Mode,
291    cost: F,
292    one: C,
293) -> Vec<CostedPair<G::State, G::Edge, [C; 2]>>
294where
295    G: EdgeGraph,
296    F: Fn(&G::Weight) -> [C; 2],
297    C: Cost,
298{
299    if start == target {
300        return Vec::new();
301    }
302
303    let pairs = Pairs {
304        graph,
305        start: start.clone(),
306        target: target.clone(),
307        mode,
308        cost,
309        one,
310    };
311    let root = Partial {
312        second: false,
313        at: start.clone(),
314        first_edges: BTreeSet::new(),
315        second_edges: BTreeSet::new(),
316        first_states: BTreeSet::from([start.clone()]),
317        second_states: BTreeSet::new(),
318        via: None,
319    };
320    let goal = |s: &Partial<G::State, G::Edge>| s.second && s.at == *target;
321
322    boa_star(&pairs, ZeroHeuristic, root, goal)
323        .solutions
324        .into_iter()
325        .map(|solution| (unpack(&solution), solution.cost))
326        .collect()
327}
328
329/// The two paths of a pair-space solution.
330fn unpack<S: Clone, E: Clone, C>(solution: &Solution<Partial<S, E>, C>) -> PathPair<S, E> {
331    let mut pair = PathPair {
332        first: Vec::new(),
333        second: Vec::new(),
334        first_edges: Vec::new(),
335        second_edges: Vec::new(),
336    };
337
338    for state in &solution.path {
339        let (states, edges) = if state.second {
340            (&mut pair.second, &mut pair.second_edges)
341        } else {
342            (&mut pair.first, &mut pair.first_edges)
343        };
344
345        states.push(state.at.clone());
346        edges.extend(state.via.clone());
347    }
348
349    pair
350}