multiobjective_search/bottleneck/ratio.rs
1//! Objectives derived from the minsum–maxmin front: the minimal
2//! cost/capacity ratio and the quickest path.
3
4use core::cmp::Ordering;
5
6use search_core::{Cost, ExactArith, ExactNumber, Heuristic, WideMul};
7
8use crate::bottleneck::{Bottleneck, minsum_maxmin};
9use crate::graph::Graph;
10use crate::output::Solution;
11
12/// A path with its cost and bottleneck capacity.
13pub type WidePath<S, C> = Solution<S, (C, Bottleneck<C>)>;
14
15/// The path from `start` to a goal with the smallest ratio of its cost (the
16/// sum of the edges' first components) to its bottleneck capacity (the
17/// smallest second component); `None` if no goal is reachable.
18///
19/// Martins 1984 (surveyed by Craveirinha et al., Algorithms 17(6):222,
20/// 2024, Section 2.2.3(a)): a path that another beats in both cost and
21/// capacity has no smaller ratio, so the optimum lies on the
22/// [`minsum_maxmin`] front, which is scanned with exact cross-multiplied
23/// comparisons. A zero capacity makes the ratio infinite; the empty path
24/// (start is a goal) has ratio zero. Ties go to the cheaper path.
25///
26/// Requirements as for [`minsum_maxmin`].
27///
28/// # Examples
29///
30/// ```
31/// use multiobjective_search::{Graph, heuristic_fn, min_cost_capacity_ratio};
32///
33/// /// Two routes from 0 to 1: (cost, capacity).
34/// struct Links;
35///
36/// impl Graph for Links {
37/// type State = u8;
38/// type Weight = (u32, u32);
39///
40/// fn successors(&self, state: &u8, out: &mut Vec<(u8, (u32, u32))>) {
41/// if *state == 0 {
42/// out.extend([(1, (2, 4)), (1, (5, 20))]);
43/// }
44/// }
45/// }
46///
47/// let best = min_cost_capacity_ratio(&Links, heuristic_fn(|_: &u8| Some(0)), 0, |s| *s == 1);
48/// assert_eq!(best.map(|s| s.cost), Some((5, Some(20)))); // 5/20 < 2/4
49/// ```
50pub fn min_cost_capacity_ratio<G, H, C, P>(
51 graph: &G,
52 heuristic: H,
53 start: G::State,
54 is_goal: P,
55) -> Option<WidePath<G::State, C>>
56where
57 G: Graph<Weight = (C, C)>,
58 H: Heuristic<G::State, C>,
59 C: Cost + WideMul,
60 P: Fn(&G::State) -> bool,
61{
62 let front = minsum_maxmin(graph, heuristic, start, is_goal).solutions;
63 front
64 .into_iter()
65 .min_by(|a, b| ratio_order(a.cost, b.cost).then(a.cost.0.cmp(&b.cost.0)))
66}
67
68/// Orders `sum / width` ratios exactly: `None` width is unbounded (ratio
69/// 0), zero width with a positive sum is infinite.
70fn ratio_order<C: Cost + WideMul>(a: (C, Bottleneck<C>), b: (C, Bottleneck<C>)) -> Ordering {
71 match (a.1, b.1) {
72 (None, None) => Ordering::Equal,
73 (None, Some(_)) => Ordering::Less,
74 (Some(_), None) => Ordering::Greater,
75 (Some(wa), Some(wb)) => a.0.wide_mul(wb).cmp(&b.0.wide_mul(wa)),
76 }
77}
78
79/// The quickest path for sending `sigma` units from `start` to a goal: the
80/// smallest transmission time `delay + sigma / capacity`, with the delay the
81/// sum of the edges' first components and the capacity the smallest second
82/// component; `None` if no goal is reachable.
83///
84/// The quickest path problem (Moore 1976; Chen and Chin 1990; surveyed by
85/// Craveirinha et al., Section 2.2.3(d)). Its optimum lies on the
86/// [`minsum_maxmin`] front (Pelegrín and Fernández 1998), which is scanned
87/// comparing `(d1 · c1 + σ) · c2` with `(d2 · c2 + σ) · c1` exactly through
88/// [`ExactArith`]. A zero capacity makes the time
89/// infinite unless `sigma` is zero; ties go to the smaller delay.
90///
91/// Requirements as for [`minsum_maxmin`].
92///
93/// # Examples
94///
95/// ```
96/// use multiobjective_search::{Graph, heuristic_fn, quickest_path};
97///
98/// /// A short thin link and a long fat one from 0 to 1: (delay, capacity).
99/// struct Links;
100///
101/// impl Graph for Links {
102/// type State = u8;
103/// type Weight = (u32, u32);
104///
105/// fn successors(&self, state: &u8, out: &mut Vec<(u8, (u32, u32))>) {
106/// if *state == 0 {
107/// out.extend([(1, (1, 1)), (1, (10, 100))]);
108/// }
109/// }
110/// }
111///
112/// let zero = heuristic_fn(|_: &u8| Some(0));
113/// // 5 units: 1 + 5/1 = 6 beats 10 + 5/100.
114/// assert_eq!(quickest_path(&Links, zero, 0, |s| *s == 1, 5).map(|s| s.cost.0), Some(1));
115/// // 1000 units: 10 + 10 = 20 beats 1 + 1000.
116/// assert_eq!(quickest_path(&Links, zero, 0, |s| *s == 1, 1000).map(|s| s.cost.0), Some(10));
117/// ```
118pub fn quickest_path<G, H, C, P>(
119 graph: &G,
120 heuristic: H,
121 start: G::State,
122 is_goal: P,
123 sigma: C,
124) -> Option<WidePath<G::State, C>>
125where
126 G: Graph<Weight = (C, C)>,
127 H: Heuristic<G::State, C>,
128 C: Cost + ExactArith,
129 P: Fn(&G::State) -> bool,
130{
131 let front = minsum_maxmin(graph, heuristic, start, is_goal).solutions;
132 front
133 .into_iter()
134 .min_by(|a, b| time_order(a.cost, b.cost, sigma).then(a.cost.0.cmp(&b.cost.0)))
135}
136
137/// Orders `d + σ / c` exactly; `None` capacity is unbounded, a zero one
138/// infinite unless `σ` is zero.
139fn time_order<C: Cost + ExactArith>(
140 a: (C, Bottleneck<C>),
141 b: (C, Bottleneck<C>),
142 sigma: C,
143) -> Ordering {
144 let infinite = |c: Bottleneck<C>| sigma > C::ZERO && c == Some(C::ZERO);
145 match (infinite(a.1), infinite(b.1)) {
146 (true, true) => return Ordering::Equal,
147 (true, false) => return Ordering::Greater,
148 (false, true) => return Ordering::Less,
149 (false, false) => {}
150 }
151
152 // The time as a fraction: d / 1, or (d · c + σ) / c.
153 let time = |(d, c): (C, Bottleneck<C>)| match c.filter(|_| sigma > C::ZERO) {
154 None => (d.exact(), C::Exact::one()),
155 Some(c) => (d.exact() * c.exact() + sigma.exact(), c.exact()),
156 };
157 let ((na, da), (nb, db)) = (time(a), time(b));
158
159 (na * db).cmp(&(nb * da))
160}
161
162#[cfg(test)]
163mod tests {
164 //! Unit tests for the exact time comparison.
165
166 use core::cmp::Ordering;
167
168 use super::time_order;
169
170 /// `1 + 5/1 = 6 < 10 + 5/100`, and the reverse for 1000 units; zero
171 /// capacities are infinite only with data to send; extreme values stay
172 /// exact.
173 #[test]
174 fn times_compare() {
175 assert_eq!(
176 time_order((1_u64, Some(1)), (10, Some(100)), 5),
177 Ordering::Less
178 );
179 assert_eq!(
180 time_order((1_u64, Some(1)), (10, Some(100)), 1000),
181 Ordering::Greater
182 );
183 assert_eq!(
184 time_order((0_u64, Some(0)), (1, None), 1),
185 Ordering::Greater
186 );
187 assert_eq!(
188 time_order((4_u64, Some(0)), (3, Some(7)), 0),
189 Ordering::Greater
190 );
191 let max = u128::MAX;
192 assert_eq!(
193 time_order((max, Some(max)), (max - 1, Some(max)), max),
194 Ordering::Greater
195 );
196 }
197}