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
125/// A [`Valuation`] that tries every insertion position of a [`PathScore`] and keeps the best.
126///
127/// The marginal gain is the difference between the path's value with and without the new
128/// task. A task that lowers the path's value scores zero, which never wins a bid. Of equally
129/// good positions the earliest wins.
130///
131/// Each call scores `path.len() + 1` candidate paths and allocates one scratch path.
132///
133/// # Examples
134///
135/// ```
136/// use task_allocation::{BestInsertion, Insertion, PathScore, Valuation};
137///
138/// /// Visits points on a line, starting at 0: 50 per point, minus the distance traveled.
139/// struct Walker;
140///
141/// impl PathScore<i64> for Walker {
142///     fn path_score(&self, path: &[i64]) -> Option<u64> {
143///         let mut at: i64 = 0;
144///         let mut traveled = 0;
145///
146///         for &point in path {
147///             traveled += at.abs_diff(point);
148///             at = point;
149///         }
150///
151///         (50 * path.len() as u64).checked_sub(traveled)
152///     }
153/// }
154///
155/// let walker = BestInsertion(Walker);
156///
157/// // Visiting 5 on the way to 10 adds no travel, so it gains the full 50.
158/// assert_eq!(
159///     walker.best_insertion(&[10], &5),
160///     Some(Insertion { position: 0, gain: 50 })
161/// );
162/// ```
163#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
164pub struct BestInsertion<S>(pub S);
165
166impl<Task: Clone, S: PathScore<Task>> Valuation<Task> for BestInsertion<S> {
167    fn marginal_score(&self, bundle: &[Task], task: &Task) -> Option<u64> {
168        self.best_insertion(bundle, task)
169            .map(|insertion| insertion.gain)
170    }
171
172    fn best_insertion(&self, path: &[Task], task: &Task) -> Option<Insertion> {
173        let base = self.0.path_score(path)?;
174        let mut candidate: Vec<Task> = path.to_vec();
175        candidate.push(task.clone());
176
177        let mut best: Option<Insertion> = None;
178        for position in (0..=path.len()).rev() {
179            if position < path.len() {
180                candidate.swap(position, position + 1);
181            }
182
183            best = better_insertion(best, self.score_candidate(&candidate, base, position));
184        }
185
186        best
187    }
188}
189
190impl<S> BestInsertion<S> {
191    /// Scores `candidate`, the path with the new task at `position`, against the old path's
192    /// value `base`; `None` when the candidate is infeasible.
193    fn score_candidate<Task>(
194        &self,
195        candidate: &[Task],
196        base: u64,
197        position: usize,
198    ) -> Option<Insertion>
199    where
200        S: PathScore<Task>,
201    {
202        let value = self.0.path_score(candidate)?;
203
204        Some(Insertion {
205            position,
206            gain: value.saturating_sub(base),
207        })
208    }
209}
210
211/// The better of two insertions: the higher gain, then the earlier position.
212fn better_insertion(current: Option<Insertion>, candidate: Option<Insertion>) -> Option<Insertion> {
213    match (current, candidate) {
214        (Some(current), Some(candidate)) => {
215            let candidate_wins = candidate.gain > current.gain
216                || (candidate.gain == current.gain && candidate.position < current.position);
217
218            Some(if candidate_wins { candidate } else { current })
219        }
220        (current, None) => current,
221        (None, candidate) => candidate,
222    }
223}
224
225/// Unit tests for the valuation traits.
226#[cfg(test)]
227mod tests;