Skip to main content

task_allocation/
route.rs

1//! Timed routes: a ready-made path score for agents that travel between task sites.
2//!
3//! An agent leaves its origin at its departure time, travels to each task's place in path
4//! order, waits for the task's earliest start if it arrives early, works for the task's
5//! duration, and collects a reward that depends on when it finishes. Implement [`Route`] for
6//! the travel times, windows and rewards, and wrap it in [`Timed`] to get a [`PathScore`];
7//! wrap that in [`BestInsertion`](crate::BestInsertion) to get a [`Valuation`](crate::Valuation)
8//! that inserts each task where it adds the most.
9//!
10//! ```mermaid
11//! flowchart LR
12//!     origin --> travel[travel to the task's place]
13//!     travel --> wait[wait for the earliest start]
14//!     wait --> work[work for the duration]
15//!     work --> reward[reward for the finish time]
16//!     reward -->|next task| travel
17//! ```
18//!
19//! Whether gains diminish depends on the route: rewards that never grow with later finish
20//! times, and travel times that obey the triangle inequality, keep feasibility monotone, but
21//! decaying rewards can still let one task raise another's gain: once the path passes near a
22//! site, visiting it delays the rest less. In the plane, [`rewards::halving`] shows this
23//! within a handful of sites.
24//! Run [`check_diminishing`](crate::check_diminishing) on representative instances.
25//!
26//! [`rewards`] has common reward shapes.
27
28pub mod rewards;
29
30use alloc::vec::Vec;
31
32use crate::id::TaskId;
33use crate::valuation::PathScore;
34
35/// How an agent travels between task sites, and what each task is worth when.
36///
37/// Times are in a unit of the implementer's choice, the same everywhere: ticks, seconds or
38/// minutes.
39pub trait Route {
40    /// Where the agent can be: a node of a graph, a grid cell, a point.
41    type Place;
42
43    /// Where the agent starts.
44    fn origin(&self) -> Self::Place;
45
46    /// When the agent leaves its origin. The default is time zero.
47    fn departure(&self) -> u64 {
48        0
49    }
50
51    /// Where `task` is done.
52    fn place(&self, task: TaskId) -> Self::Place;
53
54    /// How long the agent takes from `from` to `to`; `None` when it cannot get there.
55    fn travel(&self, from: &Self::Place, to: &Self::Place) -> Option<u64>;
56
57    /// How long `task` takes once started. The default is zero.
58    fn duration(&self, task: TaskId) -> u64 {
59        let _ = task;
60
61        0
62    }
63
64    /// The earliest time `task` may start; an agent that arrives earlier waits. The default
65    /// is time zero.
66    fn earliest_start(&self, task: TaskId) -> u64 {
67        let _ = task;
68
69        0
70    }
71
72    /// What `task` is worth when finished at `finish`; `None` when that is too late. See
73    /// [`rewards`] for common shapes.
74    fn reward(&self, task: TaskId, finish: u64) -> Option<u64>;
75}
76
77impl<R: Route + ?Sized> Route for &R {
78    type Place = R::Place;
79
80    fn origin(&self) -> Self::Place {
81        (**self).origin()
82    }
83
84    fn departure(&self) -> u64 {
85        (**self).departure()
86    }
87
88    fn place(&self, task: TaskId) -> Self::Place {
89        (**self).place(task)
90    }
91
92    fn travel(&self, from: &Self::Place, to: &Self::Place) -> Option<u64> {
93        (**self).travel(from, to)
94    }
95
96    fn duration(&self, task: TaskId) -> u64 {
97        (**self).duration(task)
98    }
99
100    fn earliest_start(&self, task: TaskId) -> u64 {
101        (**self).earliest_start(task)
102    }
103
104    fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
105        (**self).reward(task, finish)
106    }
107}
108
109/// One task of a timed route: when the agent arrives, starts, finishes, and what it earns.
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111pub struct Visit {
112    /// The task.
113    pub task: TaskId,
114
115    /// When the agent arrives at the task's place.
116    pub arrival: u64,
117
118    /// When the agent starts the task: its arrival, or the task's earliest start if later.
119    pub start: u64,
120
121    /// When the agent finishes the task.
122    pub finish: u64,
123
124    /// What the task earns at that finish time.
125    pub reward: u64,
126}
127
128/// A [`PathScore`] from a [`Route`]: the sum of the rewards along the path, or `None` when a
129/// place is unreachable or a task finishes too late.
130///
131/// # Examples
132///
133/// ```
134/// use task_allocation::route::{Route, Timed, rewards};
135/// use task_allocation::{BestInsertion, PathScore, TaskId, Valuation};
136///
137/// /// A rover on a line, at one meter per second, with three sites.
138/// struct Line;
139///
140/// const SITES: [u64; 3] = [10, 40, 90];
141///
142/// impl Route for Line {
143///     type Place = u64;
144///
145///     fn origin(&self) -> u64 { 0 }
146///     fn place(&self, task: TaskId) -> u64 { SITES[task.index()] }
147///     fn travel(&self, from: &u64, to: &u64) -> Option<u64> { Some(from.abs_diff(*to)) }
148///     fn duration(&self, _task: TaskId) -> u64 { 5 }
149///
150///     /// Each site is worth 100 if done within 60 seconds.
151///     fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
152///         rewards::deadline(100, finish, 60)
153///     }
154/// }
155///
156/// let route = Timed(Line);
157/// let visits = route.schedule(&[TaskId(0), TaskId(1)]).unwrap();
158/// assert_eq!((visits[1].arrival, visits[1].finish), (45, 50));
159///
160/// // The third site is too far to make the deadline.
161/// assert_eq!(route.path_score(&[TaskId(2)]), None);
162///
163/// // Visiting the second site after the first still makes its deadline.
164/// let valuation = BestInsertion(Timed(Line));
165/// assert_eq!(valuation.marginal_score(&[TaskId(0)], &TaskId(1)), Some(100));
166/// ```
167#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
168pub struct Timed<R>(pub R);
169
170impl<R: Route> Timed<R> {
171    /// The visits of `path`, in order; `None` when a place is unreachable or a task finishes
172    /// too late. Times saturate at [`u64::MAX`].
173    #[must_use]
174    pub fn schedule(&self, path: &[TaskId]) -> Option<Vec<Visit>> {
175        let mut visits = Vec::with_capacity(path.len());
176        self.walk(path, |visit| visits.push(visit))?;
177
178        Some(visits)
179    }
180
181    /// Walks `path`, calling `visit` for each task in order; returns the total reward, or
182    /// `None` as soon as a place is unreachable or a task finishes too late.
183    fn walk(&self, path: &[TaskId], mut visit: impl FnMut(Visit)) -> Option<u64> {
184        let route = &self.0;
185        let mut at = route.origin();
186        let mut clock = route.departure();
187        let mut total: u64 = 0;
188
189        for &task in path {
190            let place = route.place(task);
191            let arrival = clock.saturating_add(route.travel(&at, &place)?);
192            let start = arrival.max(route.earliest_start(task));
193            let finish = start.saturating_add(route.duration(task));
194            let reward = route.reward(task, finish)?;
195
196            visit(Visit {
197                task,
198                arrival,
199                start,
200                finish,
201                reward,
202            });
203            total = total.saturating_add(reward);
204            at = place;
205            clock = finish;
206        }
207
208        Some(total)
209    }
210}
211
212impl<R: Route> PathScore<TaskId> for Timed<R> {
213    fn path_score(&self, path: &[TaskId]) -> Option<u64> {
214        self.walk(path, |_| {})
215    }
216}
217
218/// Unit tests for timed routes.
219#[cfg(test)]
220mod tests;