1mod big;
9
10use alloc::collections::BTreeMap;
11use alloc::vec::Vec;
12use core::cmp::Ordering;
13use core::ops::{AddAssign, SubAssign};
14
15use search_core::{BigInt, BigUint, Cost};
16
17use crate::graph::Graph;
18use crate::output::Solution;
19
20use big::Big;
21
22pub fn min_ratio_path<G, C, P>(
65 graph: &G,
66 start: G::State,
67 is_goal: P,
68) -> Option<Solution<G::State, [C; 2]>>
69where
70 G: Graph<Weight = [C; 2]>,
71 C: Cost + Into<u64>,
72 P: Fn(&G::State) -> bool,
73{
74 let net = Explicit::explore(graph, start, &is_goal);
75 dinkelbach(&net, false).map(|path| net.solution(&path))
76}
77
78fn dinkelbach<S: Clone + Ord, C: Cost + Into<u64>>(
81 net: &Explicit<S, C>,
82 exact_only: bool,
83) -> Option<Vec<usize>> {
84 let (mut num, mut den) = (1_u128, 0_u128);
87 let mut best: Option<Vec<usize>> = None;
88
89 loop {
90 let small = if exact_only {
91 None
92 } else {
93 net.small_weights(num, den)
94 };
95 let found = match small {
96 Some(weights) => net.minimum(&weights).map(|(v, path)| (v < 0, path)),
97 None => net
98 .minimum(&net.exact_weights(num, den))
99 .map(|(v, path)| (v.is_negative(), path)),
100 };
101 let (negative, path) = found?;
102 if !negative {
103 break;
104 }
105
106 let [c1, c2] = net.totals(&path);
107 if c2 == 0 {
108 break;
109 }
110
111 (num, den) = (c1, c2);
112 best = Some(path);
113 }
114
115 best
116}
117
118trait Weight:
121 Clone + Ord + Default + for<'a> AddAssign<&'a Self> + for<'a> SubAssign<&'a Self>
122{
123}
124
125impl<W> Weight for W where
126 W: Clone + Ord + Default + for<'a> AddAssign<&'a W> + for<'a> SubAssign<&'a W>
127{
128}
129
130enum Relaxed<W> {
132 Done(Option<(W, Vec<usize>)>),
134 NegativeCycle,
136}
137
138struct Explicit<S, C> {
140 states: Vec<S>,
142 goal: Vec<bool>,
144 edges: Vec<(usize, usize, [C; 2])>,
146}
147
148impl<S: Clone + Ord, C: Cost + Into<u64>> Explicit<S, C> {
149 fn explore<G: Graph<State = S, Weight = [C; 2]>>(
151 graph: &G,
152 start: S,
153 is_goal: &impl Fn(&S) -> bool,
154 ) -> Self {
155 let mut index = BTreeMap::from([(start.clone(), 0)]);
156 let mut net = Self {
157 states: alloc::vec![start],
158 goal: Vec::new(),
159 edges: Vec::new(),
160 };
161 let mut buffer = Vec::new();
162 let mut i = 0;
163
164 while i < net.states.len() {
165 let here = net.states[i].clone();
166 let goal = is_goal(&here);
167 net.goal.push(goal);
168 if !goal {
169 graph.successors(&here, &mut buffer);
170 for (to, w) in buffer.drain(..) {
171 let j = *index.entry(to.clone()).or_insert_with(|| {
172 net.states.push(to);
173 net.states.len() - 1
174 });
175 net.edges.push((i, j, w));
176 }
177 }
178
179 i += 1;
180 }
181
182 net
183 }
184
185 fn small_weights(&self, num: u128, den: u128) -> Option<Vec<i128>> {
193 let term = |a: u128, c: C| {
194 a.checked_mul(u128::from(c.into()))
195 .and_then(|t| i128::try_from(t).ok())
196 };
197 let weights = self
198 .edges
199 .iter()
200 .map(|e| term(den, e.2[0])?.checked_sub(term(num, e.2[1])?))
201 .collect::<Option<Vec<i128>>>()?;
202 let widest = weights.iter().map(|w| w.unsigned_abs()).max().unwrap_or(0);
203 let steps = u128::try_from(self.edges.len())
204 .ok()?
205 .checked_mul(u128::try_from(self.states.len()).ok()? + 2)?;
206 let bound = widest.checked_mul(steps)?;
207 i128::try_from(bound).is_ok().then_some(weights)
208 }
209
210 fn exact_weights(&self, num: u128, den: u128) -> Vec<BigInt> {
212 let term =
213 |a: u128, c: C| BigInt::from(BigUint::from(a) * BigUint::from(u128::from(c.into())));
214 self.edges
215 .iter()
216 .map(|e| term(den, e.2[0]) - term(num, e.2[1]))
217 .collect()
218 }
219
220 fn minimum<W: Weight>(&self, weights: &[W]) -> Option<(W, Vec<usize>)> {
223 match self.bellman_ford(weights) {
224 Relaxed::Done(found) => found,
225 Relaxed::NegativeCycle => self.exhaustive(weights),
226 }
227 }
228
229 fn bellman_ford<W: Weight>(&self, weights: &[W]) -> Relaxed<W> {
232 let n = self.states.len();
233 let mut dist: Vec<Option<W>> = alloc::vec![None; n];
234 let mut parent: Vec<Option<usize>> = alloc::vec![None; n];
235 dist[0] = Some(W::default());
236 let mut candidate = W::default();
239
240 for round in 0..=n {
241 let mut changed = false;
242 for (k, &(from, to, _)) in self.edges.iter().enumerate() {
243 let Some(d) = &dist[from] else { continue };
244 candidate.clone_from(d);
245 candidate += &weights[k];
246 if dist[to].as_ref().is_none_or(|current| candidate < *current) {
247 if round == n {
248 return Relaxed::NegativeCycle;
249 }
250
251 match &mut dist[to] {
252 Some(current) => core::mem::swap(current, &mut candidate),
253 slot @ None => *slot = Some(candidate.clone()),
254 }
255
256 parent[to] = Some(k);
257 changed = true;
258 }
259 }
260
261 if !changed {
262 break;
263 }
264 }
265
266 let best = (0..n)
267 .filter(|&v| self.goal[v])
268 .filter_map(|v| dist[v].clone().map(|d| (d, v)))
269 .min_by(|a, b| a.0.cmp(&b.0));
270 Relaxed::Done(best.map(|(d, v)| {
271 let mut path = Vec::new();
272 let mut at = v;
273 while let Some(k) = parent[at] {
274 path.push(k);
275 at = self.edges[k].0;
276 }
277
278 path.reverse();
279 (d, path)
280 }))
281 }
282
283 fn exhaustive<W: Weight>(&self, weights: &[W]) -> Option<(W, Vec<usize>)> {
286 let mut best: Option<(W, Vec<usize>)> = None;
287 let mut visited = alloc::vec![false; self.states.len()];
288 let mut path = Vec::new();
289 let mut sum = W::default();
290 self.descend(0, &mut sum, weights, &mut visited, &mut path, &mut best);
291 best
292 }
293
294 fn descend<W: Weight>(
297 &self,
298 at: usize,
299 sum: &mut W,
300 weights: &[W],
301 visited: &mut [bool],
302 path: &mut Vec<usize>,
303 best: &mut Option<(W, Vec<usize>)>,
304 ) {
305 if self.goal[at] {
306 if best.as_ref().is_none_or(|(b, _)| *sum < *b) {
307 *best = Some((sum.clone(), path.clone()));
308 }
309
310 return;
311 }
312
313 visited[at] = true;
314 for (k, &(from, to, _)) in self.edges.iter().enumerate() {
315 if from == at && !visited[to] {
316 path.push(k);
317 *sum += &weights[k];
318 self.descend(to, sum, weights, visited, path, best);
319 *sum -= &weights[k];
320 path.pop();
321 }
322 }
323
324 visited[at] = false;
325 }
326
327 fn totals(&self, path: &[usize]) -> [u128; 2] {
329 path.iter().fold([0, 0], |s, &k| {
330 let w = self.edges[k].2;
331 [
332 s[0] + u128::from(w[0].into()),
333 s[1] + u128::from(w[1].into()),
334 ]
335 })
336 }
337
338 fn solution(&self, path: &[usize]) -> Solution<S, [C; 2]> {
340 let states = core::iter::once(0).chain(path.iter().map(|&k| self.edges[k].1));
341 let cost = path.iter().fold([C::ZERO; 2], |s, &k| {
342 [s[0] + self.edges[k].2[0], s[1] + self.edges[k].2[1]]
343 });
344
345 Solution {
346 cost,
347 path: states.map(|i| self.states[i].clone()).collect(),
348 }
349 }
350}
351
352pub type ExactReliability = (Vec<u32>, Vec<u32>);
355
356type Found<S, C> = (Solution<S, C>, Label<C>);
358
359pub type Reliability = (u32, u32);
361
362pub fn min_cost_reliability_ratio<G, C, P>(
403 graph: &G,
404 start: G::State,
405 is_goal: P,
406) -> Option<(Solution<G::State, C>, ExactReliability)>
407where
408 G: Graph<Weight = (C, Reliability)>,
409 C: Cost + Into<u64>,
410 P: Fn(&G::State) -> bool,
411{
412 let front = reliability_front(graph, start, &is_goal);
413 let ratio = |(c, num, den): &(C, Big, Big)| (Big::from((*c).into()).times(den), num.clone());
414 front
415 .into_iter()
416 .min_by(|a, b| {
417 let ((ca, na), (cb, nb)) = (ratio(&a.1), ratio(&b.1));
418 ca.times(&nb).cmp(&cb.times(&na)).then(a.1.0.cmp(&b.1.0))
419 })
420 .map(|(solution, (_, num, den))| (solution, (num.limbs(), den.limbs())))
421}
422
423type Label<C> = (C, Big, Big);
425
426fn reliability_front<G, C, P>(graph: &G, start: G::State, is_goal: &P) -> Vec<Found<G::State, C>>
428where
429 G: Graph<Weight = (C, Reliability)>,
430 C: Cost,
431 P: Fn(&G::State) -> bool,
432{
433 let mut nodes: Vec<(G::State, Label<C>, Option<usize>)> =
434 alloc::vec![(start, (C::ZERO, Big::from(1), Big::from(1)), None)];
435 let mut open: Vec<usize> = alloc::vec![0];
436 let mut closed: BTreeMap<G::State, Vec<Label<C>>> = BTreeMap::new();
437 let mut found: Vec<Found<G::State, C>> = Vec::new();
438 let mut buffer = Vec::new();
439 let order = |a: &Label<C>, b: &Label<C>| {
440 a.0.cmp(&b.0)
441 .then_with(|| b.1.times(&a.2).cmp(&a.1.times(&b.2)))
442 };
443
444 while !open.is_empty() {
445 let pick = (0..open.len())
447 .min_by(|&i, &j| order(&nodes[open[i]].1, &nodes[open[j]].1))
448 .expect("non-empty");
449 let index = open.swap_remove(pick);
450 let (here, label) = (nodes[index].0.clone(), nodes[index].1.clone());
451 let known = found
452 .iter()
453 .map(|(_, l)| l)
454 .chain(closed.get(&here).into_iter().flatten());
455 if known.into_iter().any(|k| covers(k, &label)) {
456 continue;
457 }
458
459 closed.entry(here.clone()).or_default().push(label.clone());
460 if is_goal(&here) {
461 let mut path = Vec::new();
462 let mut at = Some(index);
463 while let Some(i) = at {
464 path.push(nodes[i].0.clone());
465 at = nodes[i].2;
466 }
467
468 path.reverse();
469 found.push((
470 Solution {
471 cost: label.0,
472 path,
473 },
474 label,
475 ));
476 continue;
477 }
478
479 graph.successors(&here, &mut buffer);
480 for (to, (c, (num, den))) in buffer.drain(..) {
481 assert!(num > 0 && num <= den, "reliabilities must lie in (0, 1]");
482 let child = (
483 label.0 + c,
484 label.1.times(&Big::from(u64::from(num))),
485 label.2.times(&Big::from(u64::from(den))),
486 );
487 nodes.push((to, child, Some(index)));
488 open.push(nodes.len() - 1);
489 }
490 }
491
492 found
493}
494
495fn covers<C: Ord>(k: &Label<C>, label: &Label<C>) -> bool {
498 k.0 <= label.0 && k.1.times(&label.2).cmp(&label.1.times(&k.2)) != Ordering::Less
499}
500
501#[cfg(test)]
502mod tests {
503 use alloc::vec::Vec;
507
508 use proptest::prelude::*;
509 use search_core::BigUint;
510
511 use super::{Explicit, dinkelbach};
512 use crate::graph::Graph;
513
514 struct Edges(Vec<(u8, u8, [u64; 2])>);
516
517 impl Graph for Edges {
518 type State = u8;
519 type Weight = [u64; 2];
520
521 fn successors(&self, state: &u8, out: &mut Vec<(u8, [u64; 2])>) {
522 out.extend(self.0.iter().filter(|e| e.0 == *state).map(|e| (e.1, e.2)));
523 }
524 }
525
526 fn net(edges: Vec<(u8, u8, [u64; 2])>) -> Explicit<u8, u64> {
528 Explicit::explore(&Edges(edges), 0, &|s: &u8| *s == 3)
529 }
530
531 fn ratio(net: &Explicit<u8, u64>, path: &[usize]) -> (BigUint, BigUint) {
533 let [a, b] = net.totals(path);
534 (BigUint::from(a), BigUint::from(b))
535 }
536
537 #[test]
540 fn large_costs_fall_back_to_exact() {
541 let max = u64::MAX;
542 let net = net(alloc::vec![(0, 3, [max, max]), (0, 3, [max - 1, max])]);
543 let big = u128::from(max);
544 assert!(net.small_weights(big, big).is_none());
545 assert!(net.small_weights(1, 0).is_some());
546
547 let path = dinkelbach(&net, false).expect("a path");
548 assert_eq!(net.solution(&path).cost, [max - 1, max]);
549 assert_eq!(dinkelbach(&net, true), Some(path));
550 }
551
552 fn cost() -> impl Strategy<Value = u64> {
554 prop_oneof![0..20_u64, (u64::MAX - 20)..=u64::MAX]
555 }
556
557 proptest! {
558 #[test]
561 fn fast_path_matches_exact(
562 edges in proptest::collection::vec((0..4_u8, 0..4_u8, [cost(), cost()]), 1..9),
563 ) {
564 let net = net(edges);
565 let (fast, exact) = (dinkelbach(&net, false), dinkelbach(&net, true));
566 prop_assert_eq!(fast.is_some(), exact.is_some());
567 if let (Some(fast), Some(exact)) = (fast, exact) {
568 let ((n1, d1), (n2, d2)) = (ratio(&net, &fast), ratio(&net, &exact));
569 prop_assert_eq!(n1 * d2, n2 * d1);
570 }
571 }
572 }
573}