1use alloc::vec;
16use alloc::vec::Vec;
17use core::cell::RefCell;
18
19use super::{Agent, Constraints, Optimism};
20use crate::bundle::Bundle;
21use crate::cbba::{self, Action};
22use crate::id::{AgentId, TaskId};
23use crate::route::{Route, Timed, Visit};
24use crate::sim::Participant;
25use crate::valuation::{BestInsertion, PathScore};
26
27#[derive(Clone, Debug)]
29pub struct Windowed<R> {
30 route: R,
32
33 windows: RefCell<Vec<(u64, Option<u64>)>>,
36}
37
38impl<R> Windowed<R> {
39 #[must_use]
41 pub const fn route(&self) -> &R {
42 &self.route
43 }
44}
45
46impl<R: Route> Route for Windowed<R> {
47 type Place = R::Place;
48
49 fn origin(&self) -> R::Place {
50 self.route.origin()
51 }
52
53 fn departure(&self) -> u64 {
54 self.route.departure()
55 }
56
57 fn place(&self, task: TaskId) -> R::Place {
58 self.route.place(task)
59 }
60
61 fn travel(&self, from: &R::Place, to: &R::Place) -> Option<u64> {
62 self.route.travel(from, to)
63 }
64
65 fn duration(&self, task: TaskId) -> u64 {
66 self.route.duration(task)
67 }
68
69 fn earliest_start(&self, task: TaskId) -> u64 {
71 let (earliest, _) = self.windows.borrow()[task.index()];
72
73 self.route.earliest_start(task).max(earliest)
74 }
75
76 fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
78 let (_, latest) = self.windows.borrow()[task.index()];
79 let start = finish.saturating_sub(self.route.duration(task));
80 if latest.is_some_and(|latest| start > latest) {
81 return None;
82 }
83
84 self.route.reward(task, finish)
85 }
86}
87
88#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct TimedMessage {
92 claims: cbba::Message,
94
95 starts: Vec<Option<u64>>,
97}
98
99impl TimedMessage {
100 #[must_use]
102 pub const fn claims(&self) -> &cbba::Message {
103 &self.claims
104 }
105
106 #[must_use]
112 pub fn start(&self, task: TaskId) -> Option<u64> {
113 self.starts[task.index()]
114 }
115}
116
117type Scheduled<R> = BestInsertion<Coordinated<R>>;
121
122#[derive(Clone, Debug)]
129struct Coordinated<R> {
130 timed: Timed<Windowed<R>>,
132
133 constraints: Constraints,
135}
136
137impl<R: Route> Coordinated<R> {
138 fn links(&self, path: &[TaskId], task: Option<TaskId>) -> bool {
141 let tasks = || path.iter().copied().chain(task);
142
143 tasks().any(|member| {
144 self.constraints
145 .activity_tasks(member)
146 .any(|partner| tasks().any(|other| other == partner))
147 })
148 }
149}
150
151impl<R: Route> PathScore<TaskId> for Coordinated<R> {
152 fn path_score(&self, path: &[TaskId]) -> Option<u64> {
155 if !self.links(path, None) {
156 return self.timed.path_score(path);
157 }
158
159 let visits = self.timed.schedule(path)?;
160 let agree = visits.iter().enumerate().all(|(index, visit)| {
161 visits[index + 1..].iter().all(|other| {
162 self.constraints
163 .starts_agree(visit.task, visit.start, other.task, other.start)
164 })
165 });
166
167 agree.then(|| {
168 visits
169 .iter()
170 .fold(0, |total: u64, visit| total.saturating_add(visit.reward))
171 })
172 }
173
174 fn insertion_scores(
177 &self,
178 path: &[TaskId],
179 task: &TaskId,
180 each: &mut dyn FnMut(usize, Option<u64>),
181 ) {
182 if !self.links(path, Some(*task)) {
183 return self.timed.insertion_scores(path, task, each);
184 }
185
186 let mut candidate = Vec::with_capacity(path.len() + 1);
187 candidate.extend_from_slice(path);
188 candidate.push(*task);
189 for position in (0..=path.len()).rev() {
190 if position < path.len() {
191 candidate.swap(position, position + 1);
192 }
193
194 each(position, self.path_score(&candidate));
195 }
196 }
197}
198
199#[derive(Clone, Debug)]
246pub struct TimedAgent<R> {
247 agent: Agent<Scheduled<R>>,
249
250 actions: Vec<(TaskId, Action)>,
253}
254
255impl<R: Route> TimedAgent<R> {
256 #[must_use]
264 pub fn new(
265 id: AgentId,
266 agents: usize,
267 tasks: usize,
268 capacity: usize,
269 route: R,
270 constraints: Constraints,
271 optimism: Optimism,
272 ) -> Self {
273 let windowed = Windowed {
274 route,
275 windows: RefCell::new(vec![(0, None); tasks]),
276 };
277 let valuation = BestInsertion(Coordinated {
278 timed: Timed(windowed),
279 constraints: constraints.clone(),
280 });
281
282 Self {
283 agent: Agent::new(
284 id,
285 agents,
286 tasks,
287 capacity,
288 valuation,
289 constraints,
290 optimism,
291 ),
292 actions: Vec::with_capacity(tasks),
293 }
294 }
295
296 pub fn build_bundle(&mut self) -> usize {
300 self.refresh_windows();
301 let added = self.agent.build_bundle();
302 self.record_own_starts();
303
304 added
305 }
306
307 #[must_use]
309 pub fn message(&mut self) -> TimedMessage {
310 TimedMessage {
311 claims: self.agent.message(),
312 starts: self.view_starts(),
313 }
314 }
315
316 pub fn receive(&mut self, message: &TimedMessage) -> bool {
319 let actions = &mut self.actions;
320 actions.clear();
321 let Some(changed) = self
322 .agent
323 .inner
324 .receive_with_actions(&message.claims, |task, action| actions.push((task, action)))
325 else {
326 return false;
327 };
328
329 {
330 let gate = self.agent.inner.valuation();
331 let mut view = gate.view.borrow_mut();
332 for &(task, action) in &self.actions {
333 let start = &mut view.starts[task.index()];
334 match action {
335 Action::Update => *start = message.starts.get(task.index()).copied().flatten(),
336 Action::Reset => *start = None,
337 Action::Leave => {}
338 }
339 }
340 }
341
342 self.agent.refresh_view();
343 self.forget_unassigned_starts();
344
345 changed
346 }
347
348 #[must_use]
351 pub fn can_bid(&self) -> bool {
352 self.refresh_windows();
353
354 self.agent.can_bid() || self.own_starts_would_move()
355 }
356
357 fn refresh_windows(&self) {
360 let gate = self.agent.inner.valuation();
361 let view = gate.view.borrow();
362 let constraints = &gate.constraints;
363 let claims = self.agent.inner.claims();
364 let mut windows = gate.inner.0.timed.0.windows.borrow_mut();
365
366 for (index, window) in windows.iter_mut().enumerate() {
367 let task = TaskId(index);
368 let mut earliest = i128::from(constraints.opening(task));
369 let mut latest: Option<i128> = None;
370 for other in constraints.requirements(task) {
371 let (Some(_), Some(start)) =
372 (claims[other.index()].winner, view.starts[other.index()])
373 else {
374 continue;
375 };
376
377 let (from, until) = constraints.window(task, other, start);
378 earliest = earliest.max(from.unwrap_or(0));
379 latest = match (latest, until) {
380 (Some(current), Some(until)) => Some(current.min(until)),
381 (current, until) => current.or(until),
382 };
383 }
384
385 *window = clamp_window(earliest, latest);
386 }
387 }
388
389 fn own_visits(&self) -> Option<Vec<Visit>> {
393 let timed = &self.agent.inner.valuation().inner.0.timed;
394 let path = self.agent.bundle().path();
395
396 timed
397 .schedule(path)
398 .or_else(|| Timed(&timed.0.route).schedule(path))
399 }
400
401 fn record_own_starts(&mut self) {
404 if let Some(visits) = self.own_visits() {
405 let gate = self.agent.inner.valuation();
406 let mut view = gate.view.borrow_mut();
407 for visit in visits {
408 view.starts[visit.task.index()] = Some(visit.start);
409 }
410 }
411
412 self.forget_unassigned_starts();
413 }
414
415 fn own_starts_would_move(&self) -> bool {
417 let Some(visits) = self.own_visits() else {
418 return false;
419 };
420
421 let view = self.agent.inner.valuation().view.borrow();
422
423 visits
424 .iter()
425 .any(|visit| view.starts[visit.task.index()] != Some(visit.start))
426 }
427
428 fn forget_unassigned_starts(&self) {
430 let gate = self.agent.inner.valuation();
431 let claims = self.agent.inner.claims();
432 let mut view = gate.view.borrow_mut();
433 for (start, claim) in view.starts.iter_mut().zip(claims) {
434 if claim.winner.is_none() {
435 *start = None;
436 }
437 }
438 }
439
440 fn view_starts(&self) -> Vec<Option<u64>> {
442 self.agent.inner.valuation().view.borrow().starts.clone()
443 }
444}
445
446fn clamp_window(earliest: i128, latest: Option<i128>) -> (u64, Option<u64>) {
449 let earliest = u64::try_from(earliest.max(0)).unwrap_or(u64::MAX);
450 match latest {
451 None => (earliest, None),
452 Some(latest) if latest < 0 => (u64::MAX, Some(0)),
453 Some(latest) => (earliest, Some(u64::try_from(latest).unwrap_or(u64::MAX))),
454 }
455}
456
457impl<R> TimedAgent<R> {
458 #[must_use]
460 pub const fn id(&self) -> AgentId {
461 self.agent.id()
462 }
463
464 #[must_use]
466 pub const fn route(&self) -> &R {
467 &self.agent.valuation().0.timed.0.route
468 }
469
470 #[must_use]
472 pub const fn constraints(&self) -> &Constraints {
473 self.agent.constraints()
474 }
475
476 #[must_use]
478 pub const fn bundle(&self) -> &Bundle<TaskId> {
479 self.agent.bundle()
480 }
481
482 #[must_use]
488 pub fn winner(&self, task: TaskId) -> Option<AgentId> {
489 self.agent.winner(task)
490 }
491
492 #[must_use]
498 pub fn start(&self, task: TaskId) -> Option<u64> {
499 self.agent.inner.valuation().view.borrow().starts[task.index()]
500 }
501}
502
503impl<R: Route> Participant for TimedAgent<R> {
504 type Message = TimedMessage;
505
506 fn id(&self) -> AgentId {
507 self.agent.id()
508 }
509
510 fn bundle(&self) -> &Bundle<TaskId> {
511 self.agent.bundle()
512 }
513
514 fn act(&mut self, _now: u64, outbox: &mut Vec<TimedMessage>) {
516 self.build_bundle();
517 outbox.push(self.message());
518 }
519
520 fn receive(
522 &mut self,
523 _now: u64,
524 message: &TimedMessage,
525 _outbox: &mut Vec<TimedMessage>,
526 ) -> bool {
527 TimedAgent::receive(self, message)
528 }
529
530 fn message_bytes(message: &TimedMessage) -> u64 {
532 let starts = u64::try_from(message.starts.len()).unwrap_or(u64::MAX);
533
534 message.claims.bytes() + 4 + 9 * starts
535 }
536
537 fn is_settled(team: &[Self], in_flight: &[&TimedMessage]) -> bool {
539 let Some(first) = team.first() else {
540 return true;
541 };
542
543 let claims = first.agent.inner.claims();
544 let starts = first.view_starts();
545
546 team.iter().all(|agent| agent.agent.inner.is_consistent())
547 && !team.iter().any(TimedAgent::can_bid)
548 && team
549 .iter()
550 .all(|agent| agent.agent.inner.claims() == claims && agent.view_starts() == starts)
551 && in_flight
552 .iter()
553 .all(|message| message.claims.claims() == claims && message.starts == starts)
554 }
555}
556
557#[cfg(test)]
559mod tests {
560 use alloc::vec;
561 use core::cell::RefCell;
562
563 use super::{Constraints, Coordinated, Optimism, TimedAgent, Windowed};
564 use crate::id::{AgentId, TaskId};
565 use crate::route::{Route, Timed};
566 use crate::valuation::PathScore;
567
568 struct Point;
570
571 impl Route for Point {
572 type Place = u64;
573
574 fn origin(&self) -> u64 {
575 0
576 }
577
578 fn place(&self, _task: TaskId) -> u64 {
579 5
580 }
581
582 fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
583 Some(from.abs_diff(*to))
584 }
585
586 fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
587 (finish <= 100).then_some(1)
588 }
589 }
590
591 #[test]
593 fn reports_and_announces_its_starts() {
594 let optimism = Optimism {
595 timeout: 1,
596 solo_attempts: 1,
597 any_attempts: 1,
598 };
599 let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, Constraints::new(1), optimism);
600 agent.build_bundle();
601 let message = agent.message();
602
603 assert_eq!(agent.id(), AgentId(0));
604 assert_eq!(agent.constraints(), &Constraints::new(1));
605 assert_eq!(agent.route().origin(), 0);
606 assert_eq!(agent.start(TaskId(0)), Some(5));
607 assert_eq!(message.start(TaskId(0)), Some(5));
608 assert_eq!(message.claims().winner(TaskId(0)), Some(AgentId(0)));
609 assert!(!agent.can_bid());
610 }
611
612 #[test]
614 fn openings_hold_back_the_start() {
615 let optimism = Optimism {
616 timeout: 1,
617 solo_attempts: 1,
618 any_attempts: 1,
619 };
620 let mut constraints = Constraints::new(1);
621 constraints.set_opening(TaskId(0), 20);
622 let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, constraints, optimism);
623 agent.build_bundle();
624
625 assert_eq!(agent.start(TaskId(0)), Some(20));
626 }
627
628 struct Busy;
630
631 impl Route for Busy {
632 type Place = u64;
633
634 fn origin(&self) -> u64 {
635 Point.origin()
636 }
637
638 fn place(&self, task: TaskId) -> u64 {
639 Point.place(task)
640 }
641
642 fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
643 Point.travel(from, to)
644 }
645
646 fn duration(&self, _task: TaskId) -> u64 {
647 4
648 }
649
650 fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
651 Point.reward(task, finish)
652 }
653 }
654
655 #[test]
658 fn own_tasks_keep_their_timing_limits() {
659 let coordinated = |limit: i64| {
660 let mut constraints = Constraints::new(2);
661 constraints
662 .add_timed_activity(
663 &[TaskId(0), TaskId(1)],
664 &[&[0, 1], &[1, 0]],
665 &[&[Some(0), Some(limit)], &[Some(limit), Some(0)]],
666 )
667 .expect("a well-formed pair");
668
669 Coordinated {
670 timed: Timed(Windowed {
671 route: Busy,
672 windows: RefCell::new(vec![(0, None); 2]),
673 }),
674 constraints,
675 }
676 };
677
678 let together = coordinated(0);
679 assert_eq!(together.path_score(&[TaskId(0)]), Some(1));
680 assert_eq!(together.path_score(&[TaskId(0), TaskId(1)]), None);
681 assert_eq!(coordinated(4).path_score(&[TaskId(0), TaskId(1)]), Some(2));
682 }
683}