task_allocation/auction/combinatorial.rs
1//! Combinatorial auctions: bids on whole bundles, and exact winner determination.
2
3use alloc::collections::{BTreeMap, BTreeSet};
4use alloc::vec;
5use alloc::vec::Vec;
6
7use crate::assignment::Assignment;
8use crate::bundle::Bundle;
9use crate::id::{AgentId, TaskId};
10use crate::valuation::Valuation;
11
12/// One agent's bid on a bundle of tasks: the bundle, built in its best order, and its value.
13///
14/// Bids of one agent are exclusive (*XOR bids*): the agent wins at most one of them.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct BundleBid {
17 /// The bidding agent.
18 pub agent: AgentId,
19
20 /// The tasks bid on, with their path and recorded gains. The bid's value is
21 /// [`Bundle::value`].
22 pub bundle: Bundle<TaskId>,
23}
24
25impl BundleBid {
26 /// The bid's value: what the bundle is worth to the agent.
27 #[must_use]
28 pub fn value(&self) -> u64 {
29 self.bundle.value()
30 }
31}
32
33/// The `limit` most valuable bundles of at most `max_size` tasks out of `0..tasks`, as bids of
34/// `agent`, most valuable first.
35///
36/// A bundle's value is the best total gain over every order in which the agent can build it,
37/// inserting each task where [`Valuation::best_insertion`] puts it. Bundles worth nothing are
38/// left out. Of equally valuable bundles, the one with the smaller tasks comes first.
39///
40/// The search tries every build order of up to `max_size` tasks: about `tasks^max_size`
41/// calls to the valuation. Keep `max_size` small when there are many tasks.
42///
43/// # Examples
44///
45/// ```
46/// use task_allocation::{AgentId, TaskId, Valuation, auction::bundle_bids};
47///
48/// /// Tasks 0 and 1 are worth 3 alone and 10 together; task 2 is worth 4.
49/// struct Pair;
50///
51/// impl Valuation<TaskId> for Pair {
52/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
53/// let partner = TaskId(1 - task.index().min(1));
54/// Some(match task.index() {
55/// 2 => 4,
56/// _ if path.contains(&partner) => 7,
57/// _ => 3,
58/// })
59/// }
60/// }
61///
62/// let bids = bundle_bids(AgentId(0), &Pair, 3, 2, 2);
63///
64/// assert_eq!(bids[0].bundle.path(), [TaskId(0), TaskId(1)]);
65/// assert_eq!(bids[0].value(), 10);
66/// assert_eq!(bids[1].value(), 7);
67/// ```
68#[must_use]
69pub fn bundle_bids<V>(
70 agent: AgentId,
71 valuation: &V,
72 tasks: usize,
73 max_size: usize,
74 limit: usize,
75) -> Vec<BundleBid>
76where
77 V: Valuation<TaskId> + ?Sized,
78{
79 let mut best: BTreeMap<Vec<TaskId>, Bundle<TaskId>> = BTreeMap::new();
80 let mut bundle = Bundle::new();
81 record_bundles(valuation, tasks, max_size, &mut bundle, &mut best);
82
83 let mut bundles: Vec<(Vec<TaskId>, Bundle<TaskId>)> = best
84 .into_iter()
85 .filter(|(_, bundle)| bundle.value() > 0)
86 .collect();
87 bundles.sort_by(|(left_tasks, left), (right_tasks, right)| {
88 right
89 .value()
90 .cmp(&left.value())
91 .then_with(|| left_tasks.cmp(right_tasks))
92 });
93
94 bundles
95 .into_iter()
96 .take(limit)
97 .map(|(_, bundle)| BundleBid { agent, bundle })
98 .collect()
99}
100
101/// Records `bundle` as the best for its task set if it beats what is recorded, then tries
102/// every task that extends it, up to `max_size` tasks.
103fn record_bundles<V>(
104 valuation: &V,
105 tasks: usize,
106 max_size: usize,
107 bundle: &mut Bundle<TaskId>,
108 best: &mut BTreeMap<Vec<TaskId>, Bundle<TaskId>>,
109) where
110 V: Valuation<TaskId> + ?Sized,
111{
112 let mut key: Vec<TaskId> = bundle.path().to_vec();
113 key.sort_unstable();
114 let beats_best = best
115 .get(&key)
116 .is_none_or(|current| bundle.value() > current.value());
117 if beats_best {
118 best.insert(key, bundle.clone());
119 }
120
121 if bundle.len() >= max_size {
122 return;
123 }
124
125 for task in (0..tasks).map(TaskId) {
126 if bundle.contains(&task) {
127 continue;
128 }
129
130 let Some(insertion) = valuation.best_insertion(bundle.path(), &task) else {
131 continue;
132 };
133
134 let index = bundle.len();
135 bundle.insert(task, insertion);
136 record_bundles(valuation, tasks, max_size, bundle, best);
137 bundle.release_from(index);
138 }
139}
140
141/// The winning bids: at most one per agent, no task in two of them, with the highest total
142/// value; returned as the assignment of `agents` agents they make up.
143///
144/// Agents without a winning bid get an empty bundle. Bids of agents outside `0..agents` are
145/// ignored. Of equally valuable selections, the first found wins, preferring each agent's
146/// bids in the order given.
147///
148/// This is exact winner determination by depth-first branch and bound over agents, pruned
149/// with each remaining agent's best bid. It is NP-hard in general: plan for at most a few
150/// dozen bids.
151///
152/// # Examples
153///
154/// ```
155/// use task_allocation::{AgentId, Bundle, Insertion, TaskId, auction::{BundleBid, winner_determination}};
156///
157/// /// A bid of `agent` on `tasks`, worth `value` in all.
158/// fn bid(agent: usize, tasks: &[usize], value: u64) -> BundleBid {
159/// let mut bundle = Bundle::new();
160/// for (position, &task) in tasks.iter().enumerate() {
161/// let gain = if position == 0 { value } else { 0 };
162/// bundle.insert(TaskId(task), Insertion { position, gain });
163/// }
164/// BundleBid { agent: AgentId(agent), bundle }
165/// }
166///
167/// let bids = [bid(0, &[0, 1], 10), bid(1, &[0], 6), bid(2, &[1], 6)];
168/// let assignment = winner_determination(&bids, 3);
169///
170/// // Agents 1 and 2 together beat agent 0's pair.
171/// assert_eq!(assignment.value(), 12);
172/// assert_eq!(assignment.holder(TaskId(1)), Some(AgentId(2)));
173/// ```
174#[must_use]
175pub fn winner_determination(bids: &[BundleBid], agents: usize) -> Assignment {
176 let mut by_agent: Vec<Vec<&BundleBid>> = vec![Vec::new(); agents];
177 for bid in bids.iter().filter(|bid| bid.agent.index() < agents) {
178 by_agent[bid.agent.index()].push(bid);
179 }
180
181 let mut search = Search::new(by_agent);
182 search.explore(0, 0);
183
184 let bundles = search
185 .best_choice
186 .iter()
187 .zip(&search.by_agent)
188 .map(|(choice, bids)| choice.map_or_else(Bundle::new, |index| bids[index].bundle.clone()))
189 .collect();
190
191 Assignment::from_bundles(bundles)
192}
193
194/// The combinatorial auction of tasks `0..tasks` among `agents`: each agent bids on its
195/// `bids_per_agent` most valuable bundles of at most `capacity` tasks (see [`bundle_bids`]),
196/// and [`winner_determination`] picks the winners.
197///
198/// With enough bids per agent, this finds the optimal assignment; with few, it trades
199/// quality for a smaller search.
200///
201/// # Examples
202///
203/// ```
204/// use task_allocation::{TaskId, Valuation, auction::combinatorial};
205///
206/// /// Values each task at a fixed reward, for at most one task.
207/// struct Single([u64; 2]);
208///
209/// impl Valuation<TaskId> for Single {
210/// fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
211/// path.is_empty().then_some(self.0[task.index()])
212/// }
213/// }
214///
215/// let agents = [Single([5, 0]), Single([6, 5])];
216///
217/// assert_eq!(combinatorial(&agents, 2, 1, 2).value(), 10);
218/// ```
219#[must_use]
220pub fn combinatorial<V>(
221 agents: &[V],
222 tasks: usize,
223 capacity: usize,
224 bids_per_agent: usize,
225) -> Assignment
226where
227 V: Valuation<TaskId>,
228{
229 let bids: Vec<BundleBid> = agents
230 .iter()
231 .enumerate()
232 .flat_map(|(index, valuation)| {
233 bundle_bids(AgentId(index), valuation, tasks, capacity, bids_per_agent)
234 })
235 .collect();
236
237 winner_determination(&bids, agents.len())
238}
239
240/// The state of the branch-and-bound search over one bid per agent.
241struct Search<'a> {
242 /// Each agent's bids.
243 by_agent: Vec<Vec<&'a BundleBid>>,
244
245 /// For each agent, the total of the best bid of it and every later agent: the most the
246 /// remaining agents can add.
247 bound_from: Vec<u64>,
248
249 /// The tasks the current selection already uses.
250 taken: BTreeSet<TaskId>,
251
252 /// The bid index chosen for each agent so far; `None` for no bid.
253 choice: Vec<Option<usize>>,
254
255 /// The best selection found, by bid index per agent.
256 best_choice: Vec<Option<usize>>,
257
258 /// The value of the best selection; `None` before the first complete one.
259 best_value: Option<u64>,
260}
261
262impl<'a> Search<'a> {
263 /// A search over `by_agent`, with nothing chosen yet.
264 fn new(by_agent: Vec<Vec<&'a BundleBid>>) -> Self {
265 let agents = by_agent.len();
266 let mut bound_from: Vec<u64> = vec![0; agents + 1];
267 for agent in (0..agents).rev() {
268 let best = by_agent[agent]
269 .iter()
270 .map(|bid| bid.value())
271 .max()
272 .unwrap_or(0);
273 bound_from[agent] = bound_from[agent + 1].saturating_add(best);
274 }
275
276 Self {
277 by_agent,
278 bound_from,
279 taken: BTreeSet::new(),
280 choice: vec![None; agents],
281 best_choice: vec![None; agents],
282 best_value: None,
283 }
284 }
285
286 /// Chooses a bid, or none, for `agent` and every later agent, given the earlier choices
287 /// worth `value`.
288 fn explore(&mut self, agent: usize, value: u64) {
289 let hopeless = self
290 .best_value
291 .is_some_and(|best| value.saturating_add(self.bound_from[agent]) <= best);
292 if hopeless {
293 return;
294 }
295
296 if agent == self.by_agent.len() {
297 self.best_value = Some(value);
298 self.best_choice.clone_from(&self.choice);
299 return;
300 }
301
302 for index in 0..self.by_agent[agent].len() {
303 let bid = self.by_agent[agent][index];
304 if bid.bundle.tasks().any(|task| self.taken.contains(task)) {
305 continue;
306 }
307
308 self.mark(bid, true);
309 self.choice[agent] = Some(index);
310 self.explore(agent + 1, value.saturating_add(bid.value()));
311 self.choice[agent] = None;
312 self.mark(bid, false);
313 }
314
315 self.explore(agent + 1, value);
316 }
317
318 /// Marks the tasks of `bid` as taken or free.
319 fn mark(&mut self, bid: &BundleBid, taken: bool) {
320 for &task in bid.bundle.tasks() {
321 if taken {
322 self.taken.insert(task);
323 } else {
324 self.taken.remove(&task);
325 }
326 }
327 }
328}