Skip to main content

task_allocation/
valuation.rs

1//! How agents value tasks: marginal gains given the tasks they already hold.
2//!
3//! An agent's *path* is its tasks in the order it will execute them. A [`Valuation`] scores
4//! what one more task adds to that path. Allocation algorithms build bundles by repeatedly
5//! adding the task with the highest marginal gain, so the gains of a bundle add up to its
6//! value:
7//!
8//! ```text
9//! value(path) = sum of the gains recorded while the path was built
10//! ```
11//!
12//! Two ways to write a valuation:
13//!
14//! - implement [`Valuation::marginal_score`] directly, when a new task always goes at the
15//!   end of the path (or when the valuation decides on its own where it goes and only the
16//!   gain matters to the caller);
17//! - implement [`PathScore`] for a whole path and wrap it in [`BestInsertion`], which tries
18//!   every insertion position and keeps the best.
19//!
20//! Consensus algorithms such as CBBA come with performance guarantees only when gains
21//! *diminish*: a task never becomes more valuable to an agent because the agent took on more
22//! work. [`check_diminishing`] tests that on a small task set.
23
24mod diminishing;
25
26pub use diminishing::{Violation, check_diminishing};
27
28use alloc::vec::Vec;
29
30/// An agent's valuation of tasks, used to place bids.
31///
32/// # Contract
33///
34/// - Higher scores are better. A score is a marginal gain: how much the agent's value grows
35///   when it adds `task` to `path`.
36/// - `None` means the agent cannot take the task on top of `path`, for example because it
37///   would miss a deadline or exceed a capacity. An agent places no bid on such a task.
38/// - [`best_insertion`](Valuation::best_insertion) and
39///   [`marginal_score`](Valuation::marginal_score) agree: the insertion's gain is the
40///   marginal score.
41/// - Valuations are deterministic: the same path and task always give the same score.
42///   Agents that disagree on scores cannot agree on winners.
43///
44/// # Examples
45///
46/// A rover that collects a fixed reward for each task it finishes before the task's
47/// deadline, working through its path in order:
48///
49/// ```
50/// use task_allocation::Valuation;
51///
52/// struct Task { duration: u64, deadline: u64, reward: u64 }
53/// struct Rover;
54///
55/// impl Valuation<Task> for Rover {
56///     fn marginal_score(&self, path: &[Task], task: &Task) -> Option<u64> {
57///         let busy_until: u64 = path.iter().map(|held| held.duration).sum();
58///
59///         (busy_until + task.duration <= task.deadline).then_some(task.reward)
60///     }
61/// }
62///
63/// let late = Task { duration: 50, deadline: 60, reward: 4 };
64/// let early = Task { duration: 20, deadline: 40, reward: 9 };
65///
66/// assert_eq!(Rover.marginal_score(&[], &early), Some(9));
67/// assert_eq!(Rover.marginal_score(&[late], &early), None);
68/// ```
69pub trait Valuation<Task> {
70    /// The score of adding `task` to the agent's current bundle; higher is better, and
71    /// `None` means the agent cannot take the task.
72    ///
73    /// `bundle` is the agent's path: the tasks it holds, in execution order.
74    fn marginal_score(&self, bundle: &[Task], task: &Task) -> Option<u64>;
75
76    /// Where `task` goes in `path`, and what it adds there; `None` when the agent cannot
77    /// take it.
78    ///
79    /// The default appends the task to the end of the path and scores it with
80    /// [`marginal_score`](Valuation::marginal_score). Override it when the position matters,
81    /// or use [`BestInsertion`].
82    fn best_insertion(&self, path: &[Task], task: &Task) -> Option<Insertion> {
83        let gain = self.marginal_score(path, task)?;
84
85        Some(Insertion {
86            position: path.len(),
87            gain,
88        })
89    }
90}
91
92impl<Task, V: Valuation<Task> + ?Sized> Valuation<Task> for &V {
93    fn marginal_score(&self, bundle: &[Task], task: &Task) -> Option<u64> {
94        (**self).marginal_score(bundle, task)
95    }
96
97    fn best_insertion(&self, path: &[Task], task: &Task) -> Option<Insertion> {
98        (**self).best_insertion(path, task)
99    }
100}
101
102/// Where a task goes in an agent's path, and what it adds there.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
104pub struct Insertion {
105    /// Index in the path at which the task is inserted; at most the path's length, which
106    /// appends it. Tasks at this index and after shift back by one.
107    pub position: usize,
108
109    /// The marginal gain of the insertion, as [`Valuation::marginal_score`] reports it.
110    pub gain: u64,
111}
112
113/// The value of a whole path: the tasks an agent holds, in execution order.
114///
115/// Wrap a path score in [`BestInsertion`] to get a [`Valuation`] that inserts each new task
116/// where it adds the most.
117pub trait PathScore<Task> {
118    /// The value of executing `path` in order; `None` when the agent cannot execute it,
119    /// for example because a task would miss its deadline.
120    ///
121    /// The empty path must be feasible.
122    fn path_score(&self, path: &[Task]) -> Option<u64>;
123
124    /// Calls `each` with every insertion position of `task` into `path`, from `path.len()`
125    /// down to zero, and the [`path_score`](PathScore::path_score) of `path` with `task` at
126    /// that position.
127    ///
128    /// The default builds one scratch path and moves `task` through it. Override it when
129    /// the score can be computed without materializing the path, as
130    /// [`Timed`](crate::route::Timed) does, to avoid the allocation.
131    fn insertion_scores(&self, path: &[Task], task: &Task, each: &mut dyn FnMut(usize, Option<u64>))
132    where
133        Task: Clone,
134    {
135        let mut candidate: Vec<Task> = path.to_vec();
136        candidate.push(task.clone());
137
138        for position in (0..=path.len()).rev() {
139            if position < path.len() {
140                candidate.swap(position, position + 1);
141            }
142
143            each(position, self.path_score(&candidate));
144        }
145    }
146}
147
148/// A [`Valuation`] that tries every insertion position of a [`PathScore`] and keeps the best.
149///
150/// The marginal gain is the difference between the path's value with and without the new
151/// task. A task that lowers the path's value scores zero, which never wins a bid. Of equally
152/// good positions the earliest wins.
153///
154/// Each call scores `path.len() + 1` candidate paths through
155/// [`PathScore::insertion_scores`], which allocates one scratch path unless the path score
156/// overrides it.
157///
158/// # Examples
159///
160/// ```
161/// use task_allocation::{BestInsertion, Insertion, PathScore, Valuation};
162///
163/// /// Visits points on a line, starting at 0: 50 per point, minus the distance traveled.
164/// struct Walker;
165///
166/// impl PathScore<i64> for Walker {
167///     fn path_score(&self, path: &[i64]) -> Option<u64> {
168///         let mut at: i64 = 0;
169///         let mut traveled = 0;
170///
171///         for &point in path {
172///             traveled += at.abs_diff(point);
173///             at = point;
174///         }
175///
176///         (50 * path.len() as u64).checked_sub(traveled)
177///     }
178/// }
179///
180/// let walker = BestInsertion(Walker);
181///
182/// // Visiting 5 on the way to 10 adds no travel, so it gains the full 50.
183/// assert_eq!(
184///     walker.best_insertion(&[10], &5),
185///     Some(Insertion { position: 0, gain: 50 })
186/// );
187/// ```
188#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
189pub struct BestInsertion<S>(pub S);
190
191impl<Task: Clone, S: PathScore<Task>> Valuation<Task> for BestInsertion<S> {
192    fn marginal_score(&self, bundle: &[Task], task: &Task) -> Option<u64> {
193        self.best_insertion(bundle, task)
194            .map(|insertion| insertion.gain)
195    }
196
197    fn best_insertion(&self, path: &[Task], task: &Task) -> Option<Insertion> {
198        let base = self.0.path_score(path)?;
199
200        let mut best: Option<Insertion> = None;
201        self.0.insertion_scores(path, task, &mut |position, score| {
202            let candidate = score.map(|value| Insertion {
203                position,
204                gain: value.saturating_sub(base),
205            });
206            best = better_insertion(best, candidate);
207        });
208
209        best
210    }
211}
212
213/// The better of two insertions: the higher gain, then the earlier position.
214fn better_insertion(current: Option<Insertion>, candidate: Option<Insertion>) -> Option<Insertion> {
215    match (current, candidate) {
216        (Some(current), Some(candidate)) => {
217            let candidate_wins = candidate.gain > current.gain
218                || (candidate.gain == current.gain && candidate.position < current.position);
219
220            Some(if candidate_wins { candidate } else { current })
221        }
222        (current, None) => current,
223        (None, candidate) => candidate,
224    }
225}
226
227/// Unit tests for the valuation traits.
228#[cfg(test)]
229mod tests;