Skip to main content

multiobjective_search/bottleneck/
multi.rs

1//! Several additive costs together with several bottleneck capacities.
2
3use alloc::collections::{BTreeMap, BinaryHeap};
4use alloc::vec::Vec;
5use core::cmp::Reverse;
6
7use search_core::{Cost, Heuristic};
8
9use crate::bottleneck::{Bottleneck, Width};
10use crate::cost::{add, weakly_dominates};
11use crate::graph::Graph;
12use crate::output::{Output, Solution, Stats};
13
14/// The costs of a path in [`minsum_maxmin_multi`]: `N` sums and `M`
15/// bottlenecks.
16pub type SumsAndWidths<C, K, const N: usize, const M: usize> = ([C; N], [Bottleneck<K>; M]);
17
18/// Finds one path for every Pareto-optimal cost from `start` to a state
19/// that satisfies `is_goal`, with `N` additive costs to minimize and `M`
20/// bottleneck capacities to maximize (edge weights `(sums, capacities)`).
21///
22/// This generalizes [`minsum_maxmin`](crate::minsum_maxmin) to the
23/// problems with several maxmin objectives surveyed by Craveirinha et al.
24/// (Algorithms 17(6):222, 2024; Pinto et al. 2009, Gandibleux et al.
25/// 2006, Bornstein et al. 2012). Labels leave the open list in
26/// lexicographic `f` order, wider bottlenecks first among equal ones, and
27/// are dropped when an earlier label at their state, or an earlier
28/// solution against `f`, is no worse in every sum and every bottleneck.
29/// That keeps one path per non-dominated cost (the minimal complete set):
30/// with bottlenecks, an efficient path may run through a weakly efficient
31/// sub-path, which is why the dominance test compares whole labels rather
32/// than truncated ones.
33///
34/// Requirements, not checked at run time: non-negative costs and a
35/// `heuristic` on the sums that is consistent and zero on every goal.
36///
37/// Solutions are sorted lexicographically by their sums.
38///
39/// # Examples
40///
41/// ```
42/// use multiobjective_search::{Graph, ZeroHeuristic, minsum_maxmin_multi};
43///
44/// /// Two links from 0 to 1: one wide in bandwidth, one in reliability.
45/// struct Links;
46///
47/// impl Graph for Links {
48///     type State = u8;
49///     type Weight = ([u32; 1], [u32; 2]);
50///
51///     fn successors(&self, state: &u8, out: &mut Vec<(u8, ([u32; 1], [u32; 2]))>) {
52///         if *state == 0 {
53///             out.extend([(1, ([5], [100, 1])), (1, ([5], [1, 100])), (1, ([9], [1, 1]))]);
54///         }
55///     }
56/// }
57///
58/// let out = minsum_maxmin_multi(&Links, ZeroHeuristic, 0, |s| *s == 1);
59/// assert_eq!(out.solutions.len(), 2); // the third link is dominated
60/// ```
61pub fn minsum_maxmin_multi<G, H, C, K, P, const N: usize, const M: usize>(
62    graph: &G,
63    mut heuristic: H,
64    start: G::State,
65    is_goal: P,
66) -> Output<G::State, SumsAndWidths<C, K, N, M>>
67where
68    G: Graph<Weight = ([C; N], [K; M])>,
69    H: Heuristic<G::State, [C; N]>,
70    C: Cost,
71    K: Copy + Ord,
72    P: Fn(&G::State) -> bool,
73{
74    let mut nodes: Vec<Node<G::State, C, K, N, M>> = Vec::new();
75    let mut open = BinaryHeap::new();
76    let mut closed: BTreeMap<G::State, Vec<Label<C, K, N, M>>> = BTreeMap::new();
77    let mut found: Vec<Label<C, K, N, M>> = Vec::new();
78    let mut solutions = Vec::new();
79    let mut successors = Vec::new();
80    let mut stats = Stats::default();
81
82    if let Some(h) = heuristic.estimate(&start) {
83        nodes.push(Node {
84            state: start,
85            label: ([C::ZERO; N], [None; M]),
86            parent: None,
87        });
88        open.push(Reverse((h, Reverse([Width(None); M]), 0)));
89        stats.generated += 1;
90    }
91
92    while let Some(Reverse((f, _, index))) = open.pop() {
93        let (here, label) = (nodes[index].state.clone(), nodes[index].label);
94        if covered(&found, &(f, label.1)) || closed.get(&here).is_some_and(|c| covered(c, &label)) {
95            continue;
96        }
97
98        closed.entry(here.clone()).or_default().push(label);
99        if is_goal(&here) {
100            found.push(label);
101            solutions.push(rebuild(&nodes, index));
102            continue;
103        }
104
105        stats.expanded += 1;
106        graph.successors(&here, &mut successors);
107        for (next, (sums, capacities)) in successors.drain(..) {
108            let child: Label<C, K, N, M> = (
109                add(label.0, sums),
110                core::array::from_fn(|i| {
111                    Some(label.1[i].map_or(capacities[i], |w| w.min(capacities[i])))
112                }),
113            );
114            if closed.get(&next).is_some_and(|c| covered(c, &child)) {
115                continue;
116            }
117
118            let Some(h) = heuristic.estimate(&next) else {
119                continue;
120            };
121
122            let f = add(child.0, h);
123            if covered(&found, &(f, child.1)) {
124                continue;
125            }
126
127            nodes.push(Node {
128                state: next,
129                label: child,
130                parent: Some(index),
131            });
132            open.push(Reverse((f, Reverse(child.1.map(Width)), nodes.len() - 1)));
133            stats.generated += 1;
134        }
135    }
136
137    Output { solutions, stats }
138}
139
140/// Sums and bottlenecks of a label.
141type Label<C, K, const N: usize, const M: usize> = SumsAndWidths<C, K, N, M>;
142
143/// One label in the arena.
144struct Node<S, C, K, const N: usize, const M: usize> {
145    /// The state the path ends in.
146    state: S,
147    /// Its sums and bottlenecks.
148    label: Label<C, K, N, M>,
149    /// Arena index of the path without its last edge.
150    parent: Option<usize>,
151}
152
153/// Returns `true` if some label in `known` is no worse than `label`: no
154/// larger in every sum, no narrower in every bottleneck.
155fn covered<C: Cost, K: Copy + Ord, const N: usize, const M: usize>(
156    known: &[Label<C, K, N, M>],
157    label: &Label<C, K, N, M>,
158) -> bool {
159    known.iter().any(|k| {
160        weakly_dominates(&k.0, &label.0) && (0..M).all(|i| Width(k.1[i]) >= Width(label.1[i]))
161    })
162}
163
164/// Rebuilds the solution ending in node `index`.
165fn rebuild<S: Clone, C: Copy, K: Copy, const N: usize, const M: usize>(
166    nodes: &[Node<S, C, K, N, M>],
167    index: usize,
168) -> Solution<S, Label<C, K, N, M>> {
169    let mut path = Vec::new();
170    let mut current = Some(index);
171
172    while let Some(i) = current {
173        path.push(nodes[i].state.clone());
174        current = nodes[i].parent;
175    }
176
177    path.reverse();
178
179    Solution {
180        cost: nodes[index].label,
181        path,
182    }
183}