Skip to main content

multiobjective_search/
bottleneck.rs

1//! Minsum–maxmin paths: one additive cost to minimize and one bottleneck
2//! capacity to maximize.
3//!
4//! Martins, "On a special class of bicriterion path problems", EJOR 1984;
5//! Gandibleux, Beugnies, Randriamasy, "Martins' algorithm revisited for
6//! multi-objective shortest path problems with a `MaxMin` cost function",
7//! 4OR 2006. Surveyed by Craveirinha et al., Algorithms 17(6):222, 2024.
8
9mod multi;
10mod ratio;
11
12use alloc::collections::{BTreeMap, BinaryHeap};
13use alloc::vec::Vec;
14use core::cmp::Reverse;
15
16use search_core::{Cost, Heuristic};
17
18use crate::graph::Graph;
19use crate::output::{Output, Solution, Stats};
20
21pub use multi::{SumsAndWidths, minsum_maxmin_multi};
22pub use ratio::{WidePath, min_cost_capacity_ratio, quickest_path};
23
24/// The capacity of a path: the smallest capacity of its edges, or `None`
25/// (unbounded) for the empty path.
26pub type Bottleneck<K> = Option<K>;
27
28/// Finds one path for every Pareto-optimal `(cost, bottleneck)` pair from
29/// `start` to a state that satisfies `is_goal`: the cost (the sum of the
30/// edges' first components) as small as possible, the bottleneck (the
31/// smallest of their second components) as large as possible.
32///
33/// Labels leave the open list in increasing `cost + heuristic`, and among
34/// equal ones in decreasing bottleneck. A label is then dominated exactly
35/// when an earlier label at its state, or an earlier solution, has a
36/// bottleneck at least as large, as in BOA*: one value per state suffices.
37/// A min–max objective (a largest delay to minimize) is the same problem
38/// with `K = core::cmp::Reverse<_>`.
39///
40/// Requirements, not checked at run time: non-negative costs and a
41/// `heuristic` on the cost that is consistent and zero on every goal.
42///
43/// Solutions are sorted by cost ascending, bottleneck strictly descending,
44/// as `(cost, bottleneck)`; a start that is a goal gives the unbounded
45/// bottleneck `None`.
46///
47/// # Examples
48///
49/// ```
50/// use multiobjective_search::{Graph, heuristic_fn, minsum_maxmin};
51///
52/// /// Two routes from 0 to 2: cheap and narrow, or dear and wide.
53/// struct Links;
54///
55/// impl Graph for Links {
56///     type State = u8;
57///     type Weight = (u32, u32);
58///
59///     fn successors(&self, state: &u8, out: &mut Vec<(u8, (u32, u32))>) {
60///         match state {
61///             0 => out.extend([(1, (1, 10)), (2, (5, 100))]),
62///             1 => out.push((2, (1, 100))),
63///             _ => {}
64///         }
65///     }
66/// }
67///
68/// let out = minsum_maxmin(&Links, heuristic_fn(|_: &u8| Some(0)), 0, |s| *s == 2);
69/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
70/// assert_eq!(costs, [(2, Some(10)), (5, Some(100))]);
71/// ```
72pub fn minsum_maxmin<G, H, C, K, P>(
73    graph: &G,
74    mut heuristic: H,
75    start: G::State,
76    is_goal: P,
77) -> Output<G::State, (C, Bottleneck<K>)>
78where
79    G: Graph<Weight = (C, K)>,
80    H: Heuristic<G::State, C>,
81    C: Cost,
82    K: Copy + Ord,
83    P: Fn(&G::State) -> bool,
84{
85    let mut nodes: Vec<Node<G::State, C, K>> = Vec::new();
86    let mut open = BinaryHeap::new();
87    let mut best: BTreeMap<G::State, Bottleneck<K>> = BTreeMap::new();
88    let mut solved: Option<Bottleneck<K>> = None;
89    let mut solutions = Vec::new();
90    let mut successors = Vec::new();
91    let mut stats = Stats::default();
92
93    if let Some(h) = heuristic.estimate(&start) {
94        nodes.push(Node {
95            state: start,
96            cost: C::ZERO,
97            width: None,
98            parent: None,
99        });
100        open.push(Reverse((h, Reverse(Width(None)), 0)));
101        stats.generated += 1;
102    }
103
104    while let Some(Reverse((_, _, index))) = open.pop() {
105        let (here, cost, width) = {
106            let node = &nodes[index];
107            (node.state.clone(), node.cost, node.width)
108        };
109
110        if covers(solved, width) || best.get(&here).is_some_and(|&b| covers(Some(b), width)) {
111            continue;
112        }
113
114        best.insert(here.clone(), width);
115        if is_goal(&here) {
116            solved = Some(width);
117            solutions.push(rebuild(&nodes, index));
118            continue;
119        }
120
121        stats.expanded += 1;
122        graph.successors(&here, &mut successors);
123        for (next, (edge_cost, capacity)) in successors.drain(..) {
124            let narrowed = Some(width.map_or(capacity, |w| w.min(capacity)));
125            if covers(solved, narrowed)
126                || best.get(&next).is_some_and(|&b| covers(Some(b), narrowed))
127            {
128                continue;
129            }
130
131            let Some(h) = heuristic.estimate(&next) else {
132                continue;
133            };
134
135            let g = cost + edge_cost;
136            nodes.push(Node {
137                state: next,
138                cost: g,
139                width: narrowed,
140                parent: Some(index),
141            });
142            open.push(Reverse((g + h, Reverse(Width(narrowed)), nodes.len() - 1)));
143            stats.generated += 1;
144        }
145    }
146
147    Output { solutions, stats }
148}
149
150/// One label in the arena.
151struct Node<S, C, K> {
152    /// The state the path ends in.
153    state: S,
154    /// Sum of the edge costs.
155    cost: C,
156    /// Smallest edge capacity; `None` for the empty path.
157    width: Bottleneck<K>,
158    /// Arena index of the path without its last edge.
159    parent: Option<usize>,
160}
161
162/// A bottleneck ordered with `None` (unbounded) as the largest value.
163#[derive(Clone, Copy, PartialEq, Eq)]
164struct Width<K>(Bottleneck<K>);
165
166impl<K: Ord> PartialOrd for Width<K> {
167    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
168        Some(self.cmp(other))
169    }
170}
171
172impl<K: Ord> Ord for Width<K> {
173    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
174        match (&self.0, &other.0) {
175            (None, None) => core::cmp::Ordering::Equal,
176            (None, Some(_)) => core::cmp::Ordering::Greater,
177            (Some(_), None) => core::cmp::Ordering::Less,
178            (Some(a), Some(b)) => a.cmp(b),
179        }
180    }
181}
182
183/// Returns `true` if an earlier label with bottleneck `known` (and no
184/// larger cost) makes one with bottleneck `width` redundant: `known`
185/// is at least as wide. `None` for `known` means "no such label".
186fn covers<K: Ord + Copy>(known: Option<Bottleneck<K>>, width: Bottleneck<K>) -> bool {
187    known.is_some_and(|k| Width(k) >= Width(width))
188}
189
190/// Rebuilds the solution ending in node `index`.
191fn rebuild<S: Clone, C: Copy, K: Copy>(
192    nodes: &[Node<S, C, K>],
193    index: usize,
194) -> Solution<S, (C, Bottleneck<K>)> {
195    let mut path = Vec::new();
196    let mut current = Some(index);
197
198    while let Some(i) = current {
199        path.push(nodes[i].state.clone());
200        current = nodes[i].parent;
201    }
202
203    path.reverse();
204
205    Solution {
206        cost: (nodes[index].cost, nodes[index].width),
207        path,
208    }
209}