Skip to main content

task_allocation/centralized/
exact.rs

1//! The optimal assignment, by exhaustive search over build orders and task partitions.
2
3use alloc::vec;
4use alloc::vec::Vec;
5
6use crate::assignment::Assignment;
7use crate::bundle::Bundle;
8use crate::id::TaskId;
9use crate::valuation::Valuation;
10
11/// The most tasks [`optimal`] accepts.
12///
13/// With ten tasks and no capacity limit, the build orders alone come to almost ten million
14/// per agent. Beyond that, the search would run for hours.
15pub const MAX_OPTIMAL_TASKS: usize = 10;
16
17/// The assignment of tasks `0..tasks` to `agents`, each holding at most `capacity` tasks,
18/// with the highest [`Assignment::value`].
19///
20/// Tasks may stay unassigned. A task set's value for an agent is the best total gain over
21/// every order in which the agent can build it, inserting each task where
22/// [`Valuation::best_insertion`] puts it. The search tries every build order of every task
23/// set for every agent, then every split of the tasks among the agents. Use it as a
24/// reference on small instances. Of equally good assignments, the first one found is
25/// returned.
26///
27/// With `n` tasks and capacity `c`, each agent explores the `n! / (n - k)!` build orders of
28/// every length `k` up to `c`. The split takes `3^n` steps per agent. In an optimized build
29/// with three agents, eight tasks take tens of milliseconds and ten about a second.
30///
31/// # Panics
32///
33/// Panics when `tasks` exceeds [`MAX_OPTIMAL_TASKS`].
34///
35/// # Examples
36///
37/// ```
38/// use task_allocation::{AgentId, TaskId, Valuation, centralized::{optimal, sequential_greedy}};
39///
40/// /// Values every task at `reward`, for at most one task.
41/// struct Single { reward: [u64; 2] }
42///
43/// impl Valuation<TaskId> for Single {
44///     fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
45///         path.is_empty().then_some(self.reward[task.index()])
46///     }
47/// }
48///
49/// let agents = [Single { reward: [5, 0] }, Single { reward: [6, 5] }];
50///
51/// // Greedy gives task 0 to agent 1, and agent 0 gains nothing from task 1.
52/// assert_eq!(sequential_greedy(&agents, 2, 1).value(), 6);
53///
54/// // The optimum gives task 0 to agent 0 and task 1 to agent 1.
55/// let best = optimal(&agents, 2, 1);
56/// assert_eq!(best.value(), 10);
57/// assert_eq!(best.holder(TaskId(0)), Some(AgentId(0)));
58/// ```
59#[must_use]
60pub fn optimal<V>(agents: &[V], tasks: usize, capacity: usize) -> Assignment
61where
62    V: Valuation<TaskId>,
63{
64    assert!(
65        tasks <= MAX_OPTIMAL_TASKS,
66        "optimal() searches at most {MAX_OPTIMAL_TASKS} tasks, got {tasks}"
67    );
68
69    let best_bundles: Vec<Vec<Option<Bundle<TaskId>>>> = agents
70        .iter()
71        .map(|valuation| best_bundle_per_set(valuation, tasks, capacity))
72        .collect();
73
74    let splits = best_splits(&best_bundles, tasks);
75    reconstruct(&best_bundles, &splits, tasks)
76}
77
78/// For each task set, as a bit mask over tasks, the most valuable bundle the agent can build
79/// from exactly that set; `None` for sets it cannot build.
80fn best_bundle_per_set<V>(
81    valuation: &V,
82    tasks: usize,
83    capacity: usize,
84) -> Vec<Option<Bundle<TaskId>>>
85where
86    V: Valuation<TaskId>,
87{
88    let mut best = vec![None; 1 << tasks];
89    let mut bundle = Bundle::new();
90    record_builds(valuation, tasks, capacity, 0, &mut bundle, &mut best);
91
92    best
93}
94
95/// Records `bundle`, built from the tasks in `mask`, if it beats the best bundle for that
96/// set, then tries every task that extends it.
97fn record_builds<V>(
98    valuation: &V,
99    tasks: usize,
100    capacity: usize,
101    mask: usize,
102    bundle: &mut Bundle<TaskId>,
103    best: &mut [Option<Bundle<TaskId>>],
104) where
105    V: Valuation<TaskId>,
106{
107    let beats_best = best[mask]
108        .as_ref()
109        .is_none_or(|current| bundle.value() > current.value());
110    if beats_best {
111        best[mask] = Some(bundle.clone());
112    }
113
114    if bundle.len() >= capacity {
115        return;
116    }
117
118    for task in (0..tasks).filter(|task| mask & (1 << task) == 0) {
119        let Some(insertion) = valuation.best_insertion(bundle.path(), &TaskId(task)) else {
120            continue;
121        };
122
123        let index = bundle.len();
124        bundle.insert(TaskId(task), insertion);
125        record_builds(valuation, tasks, capacity, mask | (1 << task), bundle, best);
126        bundle.release_from(index);
127    }
128}
129
130/// The best split of task sets among agents, built agent by agent.
131///
132/// `splits[agent][mask]` is the set the agent takes, out of `mask`, in the best assignment of
133/// `mask` to agents `0..=agent`, together with that assignment's value; `None` when no
134/// assignment of agents `0..=agent` covers exactly `mask`.
135fn best_splits(
136    best_bundles: &[Vec<Option<Bundle<TaskId>>>],
137    tasks: usize,
138) -> Vec<Vec<Option<(usize, u64)>>> {
139    let sets = 1_usize << tasks;
140    let mut previous: Vec<Option<u64>> = vec![None; sets];
141    previous[0] = Some(0);
142
143    let mut splits = Vec::with_capacity(best_bundles.len());
144    for bundles in best_bundles {
145        let layer: Vec<Option<(usize, u64)>> = (0..sets)
146            .map(|mask| best_share(bundles, &previous, mask))
147            .collect();
148
149        previous = layer
150            .iter()
151            .map(|entry| entry.map(|(_, value)| value))
152            .collect();
153        splits.push(layer);
154    }
155
156    splits
157}
158
159/// The set this agent takes out of `mask`, and the total value, that maximizes the agent's
160/// bundle plus the best assignment of the rest to the previous agents.
161fn best_share(
162    bundles: &[Option<Bundle<TaskId>>],
163    previous: &[Option<u64>],
164    mask: usize,
165) -> Option<(usize, u64)> {
166    let mut best: Option<(usize, u64)> = None;
167    let mut share = mask;
168    loop {
169        let candidate = bundles[share]
170            .as_ref()
171            .zip(previous[mask & !share])
172            .map(|(bundle, rest)| (share, rest.saturating_add(bundle.value())));
173        let improves =
174            candidate.is_some_and(|(_, value)| best.is_none_or(|(_, current)| value > current));
175        if improves {
176            best = candidate;
177        }
178
179        if share == 0 {
180            break;
181        }
182
183        share = (share - 1) & mask;
184    }
185
186    best
187}
188
189/// Walks the splits back from the agent to the first, picking the best covered task set
190/// overall, and collects each agent's bundle.
191fn reconstruct(
192    best_bundles: &[Vec<Option<Bundle<TaskId>>>],
193    splits: &[Vec<Option<(usize, u64)>>],
194    tasks: usize,
195) -> Assignment {
196    let Some(last) = splits.last() else {
197        return Assignment::empty(0);
198    };
199
200    let mut mask = (0..1_usize << tasks)
201        .filter(|&mask| last[mask].is_some())
202        .max_by_key(|&mask| (last[mask].map(|(_, value)| value), core::cmp::Reverse(mask)))
203        .unwrap_or(0);
204
205    let mut bundles: Vec<Bundle<TaskId>> = Vec::with_capacity(splits.len());
206    for (agent, layer) in splits.iter().enumerate().rev() {
207        let (share, _) = layer[mask].expect("every reachable set has a split");
208        let bundle = best_bundles[agent][share]
209            .clone()
210            .expect("splits only use buildable sets");
211        bundles.push(bundle);
212        mask &= !share;
213    }
214
215    bundles.reverse();
216    Assignment::from_bundles(bundles)
217}