Skip to main content

task_allocation/ccbba/
timed.rs

1//! CCBBA with temporal constraints: agents on timed routes, whose coupled tasks must start
2//! within limits of each other.
3//!
4//! A [`TimedAgent`] schedules its bundle on a [`Route`]. Every task it holds that depends on
5//! another task with a known start gets that task's window ([`Constraints::window`]): the
6//! route waits for the window to open and rejects a start after it closes. Messages carry
7//! the start of every winning bid, adopted whenever the conflict table takes the sender's
8//! claim. Each round, an agent also gives up tasks whose starts conflict with their
9//! partners', by the rules of Whitten, Choi, Johnson and How (2011); see the
10//! [module docs](super).
11
12use alloc::vec;
13use alloc::vec::Vec;
14use core::cell::RefCell;
15
16use super::{Agent, Constraints, Optimism};
17use crate::bundle::Bundle;
18use crate::cbba::{self, Action};
19use crate::id::{AgentId, TaskId};
20use crate::route::{Route, Timed, Visit};
21use crate::sim::Participant;
22use crate::valuation::BestInsertion;
23
24/// A route that keeps each task within a window imposed by the starts of its partners.
25#[derive(Clone, Debug)]
26pub struct Windowed<R> {
27    /// The agent's own route.
28    route: R,
29
30    /// For each task, the earliest and the latest start the partners allow; `None` for no
31    /// latest start.
32    windows: RefCell<Vec<(u64, Option<u64>)>>,
33}
34
35impl<R> Windowed<R> {
36    /// The agent's own route.
37    #[must_use]
38    pub const fn route(&self) -> &R {
39        &self.route
40    }
41}
42
43impl<R: Route> Route for Windowed<R> {
44    type Place = R::Place;
45
46    fn origin(&self) -> R::Place {
47        self.route.origin()
48    }
49
50    fn departure(&self) -> u64 {
51        self.route.departure()
52    }
53
54    fn place(&self, task: TaskId) -> R::Place {
55        self.route.place(task)
56    }
57
58    fn travel(&self, from: &R::Place, to: &R::Place) -> Option<u64> {
59        self.route.travel(from, to)
60    }
61
62    fn duration(&self, task: TaskId) -> u64 {
63        self.route.duration(task)
64    }
65
66    /// The route's own earliest start, or the partners' when later.
67    fn earliest_start(&self, task: TaskId) -> u64 {
68        let (earliest, _) = self.windows.borrow()[task.index()];
69
70        self.route.earliest_start(task).max(earliest)
71    }
72
73    /// The route's reward, or `None` when the task would start after its partners allow.
74    fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
75        let (_, latest) = self.windows.borrow()[task.index()];
76        let start = finish.saturating_sub(self.route.duration(task));
77        if latest.is_some_and(|latest| start > latest) {
78            return None;
79        }
80
81        self.route.reward(task, finish)
82    }
83}
84
85/// A [`TimedAgent`]'s broadcast: CBBA's message, plus the start of every winning bid the
86/// sender knows of.
87#[derive(Clone, Debug, PartialEq, Eq)]
88pub struct TimedMessage {
89    /// Winners, bids and freshness, as in CBBA.
90    claims: cbba::Message,
91
92    /// For each task, the start of its winning bid; `None` when unknown or unassigned.
93    starts: Vec<Option<u64>>,
94}
95
96impl TimedMessage {
97    /// The CBBA part: winners, bids and freshness.
98    #[must_use]
99    pub const fn claims(&self) -> &cbba::Message {
100        &self.claims
101    }
102
103    /// The start of `task`'s winning bid, as the sender knew it.
104    ///
105    /// # Panics
106    ///
107    /// Panics when `task` is not one of the message's tasks.
108    #[must_use]
109    pub fn start(&self, task: TaskId) -> Option<u64> {
110        self.starts[task.index()]
111    }
112}
113
114/// The valuation a [`TimedAgent`] bids with: its route, kept within its partners' windows,
115/// with each task inserted where it adds the most.
116type Scheduled<R> = BestInsertion<Timed<Windowed<R>>>;
117
118/// One CCBBA agent with temporal constraints, scheduling its bundle on a route.
119///
120/// # Examples
121///
122/// ```
123/// use task_allocation::ccbba::{Constraints, Optimism, TimedAgent};
124/// use task_allocation::route::{Route, rewards};
125/// use task_allocation::sim::{Network, Simulation};
126/// use task_allocation::{AgentId, TaskId};
127///
128/// /// An agent on a line at unit speed; both tasks are at position 10 and take 5.
129/// struct Line(u64);
130///
131/// impl Route for Line {
132///     type Place = u64;
133///     fn origin(&self) -> u64 { self.0 }
134///     fn place(&self, _task: TaskId) -> u64 { 10 }
135///     fn travel(&self, from: &u64, to: &u64) -> Option<u64> { Some(from.abs_diff(*to)) }
136///     fn duration(&self, _task: TaskId) -> u64 { 5 }
137///     fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
138///         rewards::deadline(10, finish, 100)
139///     }
140/// }
141///
142/// // Task 1 needs task 0, and must start 3 to 8 after it.
143/// let mut constraints = Constraints::new(2);
144/// constraints
145///     .add_timed_activity(
146///         &[TaskId(0), TaskId(1)],
147///         &[&[0, 1], &[0, 0]],
148///         &[&[Some(0), Some(-3)], &[Some(8), Some(0)]],
149///     )
150///     .unwrap();
151/// let optimism = Optimism { timeout: 5, solo_attempts: 2, any_attempts: 4 };
152///
153/// let agents = [Line(0), Line(12)]
154///     .into_iter()
155///     .enumerate()
156///     .map(|(id, line)| TimedAgent::new(AgentId(id), 2, 2, 1, line, constraints.clone(), optimism))
157///     .collect();
158/// let mut simulation = Simulation::new(agents, Network::default());
159///
160/// simulation.run_until_settled(100).expect("settles");
161/// let starts: Vec<_> = (0..2).map(|task| simulation.agents()[0].start(TaskId(task)).unwrap()).collect();
162/// assert!(starts[1] >= starts[0] + 3 && starts[1] <= starts[0] + 8);
163/// ```
164#[derive(Clone, Debug)]
165pub struct TimedAgent<R> {
166    /// The CCBBA agent, bidding with the windowed route.
167    agent: Agent<Scheduled<R>>,
168}
169
170impl<R: Route> TimedAgent<R> {
171    /// Agent `id` of a team of `agents`, scheduling tasks `0..tasks` on `route` under
172    /// `constraints`, and holding at most `capacity` of them.
173    ///
174    /// # Panics
175    ///
176    /// Panics when `id` is not below `agents`, or when `constraints` cover a different
177    /// number of tasks.
178    #[must_use]
179    pub fn new(
180        id: AgentId,
181        agents: usize,
182        tasks: usize,
183        capacity: usize,
184        route: R,
185        constraints: Constraints,
186        optimism: Optimism,
187    ) -> Self {
188        let windowed = Windowed {
189            route,
190            windows: RefCell::new(vec![(0, None); tasks]),
191        };
192        let valuation = BestInsertion(Timed(windowed));
193
194        Self {
195            agent: Agent::new(
196                id,
197                agents,
198                tasks,
199                capacity,
200                valuation,
201                constraints,
202                optimism,
203            ),
204        }
205    }
206
207    /// One round: gives up tasks whose constraints fail, timing included, runs the bundle
208    /// phase within the partners' windows, and records the starts of the tasks it holds.
209    /// Returns the number of tasks added.
210    pub fn build_bundle(&mut self) -> usize {
211        self.refresh_windows();
212        let added = self.agent.build_bundle();
213        self.record_own_starts();
214
215        added
216    }
217
218    /// The message this agent broadcasts now.
219    #[must_use]
220    pub fn message(&mut self) -> TimedMessage {
221        TimedMessage {
222            claims: self.agent.message(),
223            starts: self.view_starts(),
224        }
225    }
226
227    /// The consensus phase for one message: CBBA's, adopting the sender's start for every
228    /// task whose claim it takes. Returns whether anything changed.
229    pub fn receive(&mut self, message: &TimedMessage) -> bool {
230        let Some((changed, actions)) = self.agent.inner.receive_with_actions(&message.claims)
231        else {
232            return false;
233        };
234
235        {
236            let gate = self.agent.inner.valuation();
237            let mut view = gate.view.borrow_mut();
238            for (task, action) in actions.into_iter().enumerate() {
239                match action {
240                    Action::Update => {
241                        view.starts[task] = message.starts.get(task).copied().flatten();
242                    }
243                    Action::Reset => view.starts[task] = None,
244                    Action::Leave => {}
245                }
246            }
247        }
248
249        self.agent.refresh_view();
250        self.forget_unassigned_starts();
251
252        changed
253    }
254
255    /// Whether the next round would change anything: what [`Agent::can_bid`] checks, or the
256    /// starts of the tasks this agent holds would move.
257    #[must_use]
258    pub fn can_bid(&self) -> bool {
259        self.refresh_windows();
260
261        self.agent.can_bid() || self.own_starts_would_move()
262    }
263
264    /// Computes every task's window from its opening and the starts of the tasks it depends
265    /// on, as this agent knows them, and hands them to the route.
266    fn refresh_windows(&self) {
267        let gate = self.agent.inner.valuation();
268        let view = gate.view.borrow();
269        let constraints = &gate.constraints;
270        let claims = self.agent.inner.claims();
271        let mut windows = gate.inner.0.0.windows.borrow_mut();
272
273        for (index, window) in windows.iter_mut().enumerate() {
274            let task = TaskId(index);
275            let mut earliest = i128::from(constraints.opening(task));
276            let mut latest: Option<i128> = None;
277            for other in constraints.requirements(task) {
278                let (Some(_), Some(start)) =
279                    (claims[other.index()].winner, view.starts[other.index()])
280                else {
281                    continue;
282                };
283
284                let (from, until) = constraints.window(task, other, start);
285                earliest = earliest.max(from.unwrap_or(0));
286                latest = match (latest, until) {
287                    (Some(current), Some(until)) => Some(current.min(until)),
288                    (current, until) => current.or(until),
289                };
290            }
291
292            *window = clamp_window(earliest, latest);
293        }
294    }
295
296    /// The visits of this agent's bundle on its route, within the partners' windows, or,
297    /// when the windows make the bundle infeasible, without them; `None` when even the route
298    /// alone cannot execute it.
299    fn own_visits(&self) -> Option<Vec<Visit>> {
300        let timed = &self.agent.inner.valuation().inner.0;
301        let path = self.agent.bundle().path();
302
303        timed
304            .schedule(path)
305            .or_else(|| Timed(&timed.0.route).schedule(path))
306    }
307
308    /// Records the start of every task this agent holds, and forgets starts of tasks
309    /// without a winner.
310    fn record_own_starts(&mut self) {
311        if let Some(visits) = self.own_visits() {
312            let gate = self.agent.inner.valuation();
313            let mut view = gate.view.borrow_mut();
314            for visit in visits {
315                view.starts[visit.task.index()] = Some(visit.start);
316            }
317        }
318
319        self.forget_unassigned_starts();
320    }
321
322    /// Whether recomputing the starts of the tasks this agent holds would change them.
323    fn own_starts_would_move(&self) -> bool {
324        let Some(visits) = self.own_visits() else {
325            return false;
326        };
327
328        let view = self.agent.inner.valuation().view.borrow();
329
330        visits
331            .iter()
332            .any(|visit| view.starts[visit.task.index()] != Some(visit.start))
333    }
334
335    /// Forgets the start of every task without a known winner.
336    fn forget_unassigned_starts(&self) {
337        let gate = self.agent.inner.valuation();
338        let claims = self.agent.inner.claims();
339        let mut view = gate.view.borrow_mut();
340        for (start, claim) in view.starts.iter_mut().zip(claims) {
341            if claim.winner.is_none() {
342                *start = None;
343            }
344        }
345    }
346
347    /// The start of every task's winning bid, as this agent knows it.
348    fn view_starts(&self) -> Vec<Option<u64>> {
349        self.agent.inner.valuation().view.borrow().starts.clone()
350    }
351}
352
353/// A window from bounds that may be negative: the earliest start at least zero, and a
354/// latest start before zero made infeasible.
355fn clamp_window(earliest: i128, latest: Option<i128>) -> (u64, Option<u64>) {
356    let earliest = u64::try_from(earliest.max(0)).unwrap_or(u64::MAX);
357    match latest {
358        None => (earliest, None),
359        Some(latest) if latest < 0 => (u64::MAX, Some(0)),
360        Some(latest) => (earliest, Some(u64::try_from(latest).unwrap_or(u64::MAX))),
361    }
362}
363
364impl<R> TimedAgent<R> {
365    /// This agent's identifier.
366    #[must_use]
367    pub const fn id(&self) -> AgentId {
368        self.agent.id()
369    }
370
371    /// This agent's route.
372    #[must_use]
373    pub const fn route(&self) -> &R {
374        &self.agent.valuation().0.0.route
375    }
376
377    /// The constraints this agent bids under.
378    #[must_use]
379    pub const fn constraints(&self) -> &Constraints {
380        self.agent.constraints()
381    }
382
383    /// The tasks this agent holds, with the bid it placed on each.
384    #[must_use]
385    pub const fn bundle(&self) -> &Bundle<TaskId> {
386        self.agent.bundle()
387    }
388
389    /// The winner this agent believes in for `task`; `None` when it knows of no bid.
390    ///
391    /// # Panics
392    ///
393    /// Panics when `task` is not one of this agent's tasks.
394    #[must_use]
395    pub fn winner(&self, task: TaskId) -> Option<AgentId> {
396        self.agent.winner(task)
397    }
398
399    /// The start of `task`'s winning bid, as this agent knows it.
400    ///
401    /// # Panics
402    ///
403    /// Panics when `task` is not one of this agent's tasks.
404    #[must_use]
405    pub fn start(&self, task: TaskId) -> Option<u64> {
406        self.agent.inner.valuation().view.borrow().starts[task.index()]
407    }
408}
409
410impl<R: Route> Participant for TimedAgent<R> {
411    type Message = TimedMessage;
412
413    fn id(&self) -> AgentId {
414        self.agent.id()
415    }
416
417    fn bundle(&self) -> &Bundle<TaskId> {
418        self.agent.bundle()
419    }
420
421    /// Runs a round and broadcasts the full state, starts included.
422    fn act(&mut self, _now: u64, outbox: &mut Vec<TimedMessage>) {
423        self.build_bundle();
424        outbox.push(self.message());
425    }
426
427    /// Runs the consensus phase for `message`.
428    fn receive(&mut self, _now: u64, message: &TimedMessage, _outbox: &mut Vec<TimedMessage>) {
429        TimedAgent::receive(self, message);
430    }
431
432    /// CCBBA's settled check, plus agreement on every start, among agents and in flight.
433    fn is_settled(team: &[Self], in_flight: &[&TimedMessage]) -> bool {
434        let Some(first) = team.first() else {
435            return true;
436        };
437
438        let claims = first.agent.inner.claims();
439        let starts = first.view_starts();
440
441        team.iter().all(|agent| agent.agent.inner.is_consistent())
442            && !team.iter().any(TimedAgent::can_bid)
443            && team
444                .iter()
445                .all(|agent| agent.agent.inner.claims() == claims && agent.view_starts() == starts)
446            && in_flight
447                .iter()
448                .all(|message| message.claims.claims() == claims && message.starts == starts)
449    }
450}
451
452/// Unit tests for [`TimedAgent`].
453#[cfg(test)]
454mod tests {
455    use super::{Constraints, Optimism, TimedAgent};
456    use crate::id::{AgentId, TaskId};
457    use crate::route::Route;
458
459    /// One task at position 5 on a line, worth 1 by time 100.
460    struct Point;
461
462    impl Route for Point {
463        type Place = u64;
464
465        fn origin(&self) -> u64 {
466            0
467        }
468
469        fn place(&self, _task: TaskId) -> u64 {
470            5
471        }
472
473        fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
474            Some(from.abs_diff(*to))
475        }
476
477        fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
478            (finish <= 100).then_some(1)
479        }
480    }
481
482    /// An agent reports what it holds and when, and announces it.
483    #[test]
484    fn reports_and_announces_its_starts() {
485        let optimism = Optimism {
486            timeout: 1,
487            solo_attempts: 1,
488            any_attempts: 1,
489        };
490        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, Constraints::new(1), optimism);
491        agent.build_bundle();
492        let message = agent.message();
493
494        assert_eq!(agent.id(), AgentId(0));
495        assert_eq!(agent.constraints(), &Constraints::new(1));
496        assert_eq!(agent.route().origin(), 0);
497        assert_eq!(agent.start(TaskId(0)), Some(5));
498        assert_eq!(message.start(TaskId(0)), Some(5));
499        assert_eq!(message.claims().winner(TaskId(0)), Some(AgentId(0)));
500        assert!(!agent.can_bid());
501    }
502
503    /// A task never starts before the opening of its window.
504    #[test]
505    fn openings_hold_back_the_start() {
506        let optimism = Optimism {
507            timeout: 1,
508            solo_attempts: 1,
509            any_attempts: 1,
510        };
511        let mut constraints = Constraints::new(1);
512        constraints.set_opening(TaskId(0), 20);
513        let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, constraints, optimism);
514        agent.build_bundle();
515
516        assert_eq!(agent.start(TaskId(0)), Some(20));
517    }
518}