Skip to main content

multiobjective_search/
fractional.rs

1//! Ratio objectives that do not lie on an additive Pareto front: the
2//! linear fractional path and the cost/reliability path.
3//!
4//! Surveyed by Craveirinha et al., Algorithms 17(6):222, 2024, Section
5//! 2.2.3(b) and (c): Ahuja 1988 (minimum cost–reliability ratio) and
6//! Soroush 2008 (linear fractional path problem).
7
8mod 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
22/// The path from `start` to a goal that minimizes `Σ c1 / Σ c2` among
23/// those with `Σ c2 > 0`; `None` if there is no such path. Goal states end
24/// paths, and paths are simple.
25///
26/// Dinkelbach's parametric method: with `λ = num / den` the ratio of the
27/// best path so far, find the simple path minimizing
28/// `den · c1 - num · c2`; if that is negative, its ratio is smaller and
29/// becomes the next `λ`, else `λ` is optimal. The first round uses `-c2`
30/// alone to find some path with a positive denominator. The weights are
31/// signed. A round sums them in `i128` when a bound on every sum it can
32/// form fits, and as search-core [`BigInt`]s otherwise, so the result is
33/// exact without a width limit.
34/// Each round is a Bellman-Ford pass over the reachable graph when the
35/// weights have no negative cycle, and an exhaustive search over simple
36/// paths when they do (the inner problem is then NP-hard, as Soroush
37/// notes). `λ` strictly falls, so the rounds are finitely many.
38///
39/// Requirements: non-negative costs that convert into `u64`, and a finite
40/// reachable graph.
41///
42/// # Examples
43///
44/// ```
45/// use multiobjective_search::{Graph, min_ratio_path};
46///
47/// /// Two routes from 0 to 1: (cost, benefit).
48/// struct Routes;
49///
50/// impl Graph for Routes {
51///     type State = u8;
52///     type Weight = [u32; 2];
53///
54///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
55///         if *state == 0 {
56///             out.extend([(1, [2, 3]), (1, [5, 10])]);
57///         }
58///     }
59/// }
60///
61/// let best = min_ratio_path(&Routes, 0, |s| *s == 1).unwrap();
62/// assert_eq!(best.cost, [5, 10]); // 1/2 < 2/3
63/// ```
64pub 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
78/// Dinkelbach's rounds over `net`: the best path, as edge indices. With
79/// `exact_only`, every round uses [`BigInt`] weights (for tests).
80fn dinkelbach<S: Clone + Ord, C: Cost + Into<u64>>(
81    net: &Explicit<S, C>,
82    exact_only: bool,
83) -> Option<Vec<usize>> {
84    // λ = num / den; the first round, den = 0, maximizes c2. Path totals
85    // sum fewer than 2^64 costs below 2^64, so they fit `u128`.
86    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
118/// A signed weight of the inner problem: `i128` when no sum can
119/// overflow it, else [`BigInt`]. `Default` is zero.
120trait 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
130/// The outcome of a Bellman-Ford pass.
131enum Relaxed<W> {
132    /// No negative cycle: the best goal path, if any.
133    Done(Option<(W, Vec<usize>)>),
134    /// A negative cycle is reachable.
135    NegativeCycle,
136}
137
138/// The explicit reachable graph, with dense indices (the start is 0).
139struct Explicit<S, C> {
140    /// States by index.
141    states: Vec<S>,
142    /// Goal flags.
143    goal: Vec<bool>,
144    /// Edges `(from, to, [c1, c2])`.
145    edges: Vec<(usize, usize, [C; 2])>,
146}
147
148impl<S: Clone + Ord, C: Cost + Into<u64>> Explicit<S, C> {
149    /// Explores everything reachable from `start`; goals are not expanded.
150    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    /// The edge weights `den · c1 - num · c2` in `i128`, or `None` if a
186    /// weight or a sum the searches below can form might not fit.
187    ///
188    /// A Bellman-Ford distance or candidate is a walk of at most
189    /// `(n + 2) · |edges|` edges (one per relaxation), and an exhaustive
190    /// sum a subset of the edges, so `widest · |edges| · (n + 2)` bounds
191    /// every sum.
192    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    /// The edge weights `den · c1 - num · c2`, exactly.
211    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    /// The simple goal path of smallest total weight, as edge indices,
221    /// with its weight; `None` if no goal is reachable.
222    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    /// Bellman-Ford from the start; `None` if a negative cycle is
230    /// reachable, else the best goal path.
231    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        // Candidates are built here and swapped in, so a relaxation reuses
237        // limbs instead of allocating.
238        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    /// Exhaustive search over simple paths, for weights with negative
284    /// cycles.
285    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    /// One step of [`Explicit::exhaustive`]; `sum` is the weight of
295    /// `path`, updated in place and restored on return.
296    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    /// The summed costs of a simple path, as `u128`.
328    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    /// The solution for a path of edge indices.
339    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
352/// A path reliability as an exact fraction `(num, den)`, each as 32-bit
353/// limbs, least significant first.
354pub type ExactReliability = (Vec<u32>, Vec<u32>);
355
356/// A goal path of the reliability front with its label.
357type Found<S, C> = (Solution<S, C>, Label<C>);
358
359/// An edge reliability `num / den`, a probability in `(0, 1]`.
360pub type Reliability = (u32, u32);
361
362/// The path from `start` to a goal that minimizes its cost divided by its
363/// reliability, the cost being the sum of the edges' first components and
364/// the reliability the product of their second components; `None` if no
365/// goal is reachable. Returns the solution with its reliability as an
366/// exact product `(num, den)` of 32-bit limbs.
367///
368/// Ahuja 1988: a path beaten in both cost and reliability has no smaller
369/// ratio, so the optimum is on the Pareto front of (cost, reliability).
370/// The front is found by label setting in increasing cost, more reliable
371/// labels first, with whole-label dominance per state (reliability only
372/// falls along a path, like a bottleneck), and scanned comparing
373/// `c1 · den1 · num2` with `c2 · den2 · num1` in exact multi-precision
374/// arithmetic. Reliabilities must have `0 < num <= den`.
375///
376/// # Examples
377///
378/// ```
379/// use multiobjective_search::{Graph, min_cost_reliability_ratio};
380///
381/// /// A cheap shaky link and a dearer safe one from 0 to 1.
382/// struct Links;
383///
384/// impl Graph for Links {
385///     type State = u8;
386///     type Weight = (u32, (u32, u32));
387///
388///     fn successors(&self, state: &u8, out: &mut Vec<(u8, (u32, (u32, u32)))>) {
389///         if *state == 0 {
390///             out.extend([(1, (2, (1, 4))), (1, (5, (9, 10)))]);
391///         }
392///     }
393/// }
394///
395/// let (best, _) = min_cost_reliability_ratio(&Links, 0, |s| *s == 1).unwrap();
396/// assert_eq!(best.cost, 5); // 5 / 0.9 < 2 / 0.25
397/// ```
398///
399/// # Panics
400///
401/// Panics if a reliability has `num == 0` or `num > den`.
402pub 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
423/// A label of the reliability front: cost and reliability `num / den`.
424type Label<C> = (C, Big, Big);
425
426/// The non-dominated (cost, reliability) goal paths, by label setting.
427fn 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        // The smallest cost, the most reliable among equal ones.
446        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
495/// Returns `true` if label `k` is no worse than `label`: no dearer, no
496/// less reliable.
497fn 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    //! Both weight representations of [`super::dinkelbach`]: the `i128`
504    //! fast path and the exact [`BigInt`](search_core::BigInt) fallback.
505
506    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    /// An edge list over small states.
515    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    /// The reachable graph from 0 with goal 3.
527    fn net(edges: Vec<(u8, u8, [u64; 2])>) -> Explicit<u8, u64> {
528        Explicit::explore(&Edges(edges), 0, &|s: &u8| *s == 3)
529    }
530
531    /// The ratio `Σc1 / Σc2` of a path, as an exact fraction.
532    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    /// Costs near `u64::MAX` overflow the `i128` weights, so the second
538    /// round falls back to exact weights and still finds the better route.
539    #[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    /// A cost: small, or near `u64::MAX` to force the exact fallback.
553    fn cost() -> impl Strategy<Value = u64> {
554        prop_oneof![0..20_u64, (u64::MAX - 20)..=u64::MAX]
555    }
556
557    proptest! {
558        /// The mixed rounds (`i128` where it fits) find a path of the same
559        /// ratio as exact-only rounds, on graphs with cycles.
560        #[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}