multiobjective_search/encode.rs
1//! Graphs that encode other problems as additive multi-objective paths:
2//! multi-objective knapsacks and the minimum-label path objective.
3//!
4//! Both are classes surveyed by Craveirinha et al., Algorithms 17(6):222,
5//! 2024 (Sections 2.2.2 and 2.2.3: Captivo et al. 2003, Pascoal et al.
6//! 2013). Every search of the crate then solves them.
7
8use alloc::collections::BTreeSet;
9use alloc::vec::Vec;
10
11use search_core::Cost;
12
13use crate::cost::add;
14use crate::graph::Graph;
15
16/// A multi-objective, multi-constraint 0/1 knapsack as a layered graph.
17///
18/// State `(i, used, took)`: items `0..i` decided, `used` the resources
19/// they take, `took` whether item `i - 1` was taken. From each state an edge skips item `i` at cost `values[i]` (the
20/// value lost) and, if the item fits every capacity, an edge takes it at
21/// cost zero. A path from [`KnapsackGraph::start`] to a goal
22/// ([`KnapsackGraph::is_goal`]) is a feasible selection, and minimizing the
23/// lost values maximizes the kept ones (Captivo et al. 2003 solve the
24/// bi-objective knapsack this way). [`KnapsackGraph::taken`] reads the
25/// selection off a path.
26///
27/// # Examples
28///
29/// ```
30/// use multiobjective_search::{KnapsackGraph, ZeroHeuristic, namoa_star};
31///
32/// // Three items with weights and two values; capacity 5.
33/// let knapsack = KnapsackGraph::new(vec![([3_u32], [5, 1]), ([3], [1, 5]), ([2], [2, 2])], [5]);
34/// let out = namoa_star(&knapsack, ZeroHeuristic, knapsack.start(), |s| knapsack.is_goal(s));
35/// let picks: Vec<_> = out.solutions.iter().map(|s| knapsack.taken(&s.path)).collect();
36/// assert_eq!(picks, [vec![0, 2], vec![1, 2]]); // values (7, 3) and (3, 7)
37/// ```
38#[derive(Debug, Clone)]
39pub struct KnapsackGraph<C, const N: usize, const M: usize> {
40 /// Per item: resource use and values.
41 items: Vec<([C; M], [C; N])>,
42 /// Capacity per resource.
43 capacity: [C; M],
44}
45
46impl<C: Cost, const N: usize, const M: usize> KnapsackGraph<C, N, M> {
47 /// A knapsack with `items` as `(weights, values)` and `capacity` per
48 /// resource.
49 #[must_use]
50 pub const fn new(items: Vec<([C; M], [C; N])>, capacity: [C; M]) -> Self {
51 Self { items, capacity }
52 }
53
54 /// The start state: nothing decided, nothing used.
55 #[must_use]
56 pub const fn start(&self) -> (usize, [C; M], bool) {
57 (0, [C::ZERO; M], false)
58 }
59
60 /// Returns `true` once every item is decided.
61 #[must_use]
62 pub fn is_goal(&self, state: &(usize, [C; M], bool)) -> bool {
63 state.0 == self.items.len()
64 }
65
66 /// The indices of the items a path takes.
67 #[must_use]
68 pub fn taken(&self, path: &[(usize, [C; M], bool)]) -> Vec<usize> {
69 path.iter().filter(|s| s.2).map(|s| s.0 - 1).collect()
70 }
71}
72
73impl<C: Cost, const N: usize, const M: usize> Graph for KnapsackGraph<C, N, M> {
74 type State = (usize, [C; M], bool);
75 type Weight = [C; N];
76
77 fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, [C; N])>) {
78 let (i, used, _) = *state;
79 let Some(&(weights, values)) = self.items.get(i) else {
80 return;
81 };
82
83 out.push(((i + 1, used, false), values));
84 let after = add(used, weights);
85 if (0..M).all(|r| after[r] <= self.capacity[r]) {
86 out.push(((i + 1, after, true), [C::ZERO; N]));
87 }
88 }
89}
90
91/// A graph whose objective `slot` counts the distinct labels a path uses:
92/// the minimum-label path objective (Pascoal et al. 2013), made additive by
93/// carrying the set of labels seen in the state.
94///
95/// `label` names each edge `(from, to, weight)`; the edge's cost in `slot`
96/// is replaced by one if its label is new on the path, else zero. The
97/// other objectives are kept. States are `(state, labels)`, so the search
98/// space grows with the label combinations reached; use it for few labels.
99/// Goals are the pairs whose state is a goal.
100///
101/// # Examples
102///
103/// ```
104/// use multiobjective_search::{Graph, LabelCount, ZeroHeuristic, namoa_star};
105///
106/// /// Two routes from 0 to 2: one short with two operators, one long
107/// /// with one. The second objective is a placeholder for the count.
108/// struct Lines;
109///
110/// impl Graph for Lines {
111/// type State = u8;
112/// type Weight = [u32; 2];
113///
114/// fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
115/// match state {
116/// 0 => out.extend([(1, [1, 0]), (2, [9, 0])]),
117/// 1 => out.push((2, [1, 0])),
118/// _ => {}
119/// }
120/// }
121/// }
122///
123/// // Operator: "a" from 0, "b" from 1.
124/// let counted = LabelCount::new(&Lines, 1, |from: &u8, _: &u8, _: &[u32; 2]| *from);
125/// let out = namoa_star(&counted, ZeroHeuristic, counted.start(0), |s: &(u8, _)| s.0 == 2);
126/// let costs: Vec<_> = out.solutions.iter().map(|s| s.cost).collect();
127/// assert_eq!(costs, [[2, 2], [9, 1]]);
128/// ```
129pub struct LabelCount<'a, G, F> {
130 /// The underlying graph.
131 graph: &'a G,
132 /// The objective that counts labels.
133 slot: usize,
134 /// The label of an edge.
135 label: F,
136}
137
138impl<'a, G, F> LabelCount<'a, G, F> {
139 /// Counts the labels given by `label` in objective `slot` of `graph`.
140 pub const fn new(graph: &'a G, slot: usize, label: F) -> Self {
141 Self { graph, slot, label }
142 }
143
144 /// The start pair: `start` with no labels seen.
145 pub const fn start<S, L>(&self, start: S) -> (S, BTreeSet<L>) {
146 (start, BTreeSet::new())
147 }
148}
149
150impl<G, F, L, C, const N: usize> Graph for LabelCount<'_, G, F>
151where
152 G: Graph<Weight = [C; N]>,
153 F: Fn(&G::State, &G::State, &[C; N]) -> L,
154 L: Clone + Ord,
155 C: Cost + From<u8>,
156{
157 type State = (G::State, BTreeSet<L>);
158 type Weight = [C; N];
159
160 fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, [C; N])>) {
161 let (from, seen) = state;
162 let mut edges = Vec::new();
163 self.graph.successors(from, &mut edges);
164
165 for (to, mut weight) in edges {
166 let label = (self.label)(from, &to, &weight);
167 let mut labels = seen.clone();
168 let new = labels.insert(label);
169 weight[self.slot] = C::from(u8::from(new));
170 out.push(((to, labels), weight));
171 }
172 }
173}