use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use super::{Agent, Constraints, Optimism};
use crate::bundle::Bundle;
use crate::cbba::{self, Action};
use crate::id::{AgentId, TaskId};
use crate::route::{Route, Timed, Visit};
use crate::sim::Participant;
use crate::valuation::{BestInsertion, PathScore};
#[derive(Clone, Debug)]
pub struct Windowed<R> {
route: R,
windows: RefCell<Vec<(u64, Option<u64>)>>,
}
impl<R> Windowed<R> {
#[must_use]
pub const fn route(&self) -> &R {
&self.route
}
}
impl<R: Route> Route for Windowed<R> {
type Place = R::Place;
fn origin(&self) -> R::Place {
self.route.origin()
}
fn departure(&self) -> u64 {
self.route.departure()
}
fn place(&self, task: TaskId) -> R::Place {
self.route.place(task)
}
fn travel(&self, from: &R::Place, to: &R::Place) -> Option<u64> {
self.route.travel(from, to)
}
fn duration(&self, task: TaskId) -> u64 {
self.route.duration(task)
}
fn earliest_start(&self, task: TaskId) -> u64 {
let (earliest, _) = self.windows.borrow()[task.index()];
self.route.earliest_start(task).max(earliest)
}
fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
let (_, latest) = self.windows.borrow()[task.index()];
let start = finish.saturating_sub(self.route.duration(task));
if latest.is_some_and(|latest| start > latest) {
return None;
}
self.route.reward(task, finish)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TimedMessage {
claims: cbba::Message,
starts: Vec<Option<u64>>,
}
impl TimedMessage {
#[must_use]
pub const fn claims(&self) -> &cbba::Message {
&self.claims
}
#[must_use]
pub fn start(&self, task: TaskId) -> Option<u64> {
self.starts[task.index()]
}
}
type Scheduled<R> = BestInsertion<Coordinated<R>>;
#[derive(Clone, Debug)]
struct Coordinated<R> {
timed: Timed<Windowed<R>>,
constraints: Constraints,
}
impl<R: Route> Coordinated<R> {
fn links(&self, path: &[TaskId], task: Option<TaskId>) -> bool {
let tasks = || path.iter().copied().chain(task);
tasks().any(|member| {
self.constraints
.activity_tasks(member)
.any(|partner| tasks().any(|other| other == partner))
})
}
}
impl<R: Route> PathScore<TaskId> for Coordinated<R> {
fn path_score(&self, path: &[TaskId]) -> Option<u64> {
if !self.links(path, None) {
return self.timed.path_score(path);
}
let visits = self.timed.schedule(path)?;
let agree = visits.iter().enumerate().all(|(index, visit)| {
visits[index + 1..].iter().all(|other| {
self.constraints
.starts_agree(visit.task, visit.start, other.task, other.start)
})
});
agree.then(|| {
visits
.iter()
.fold(0, |total: u64, visit| total.saturating_add(visit.reward))
})
}
fn insertion_scores(
&self,
path: &[TaskId],
task: &TaskId,
each: &mut dyn FnMut(usize, Option<u64>),
) {
if !self.links(path, Some(*task)) {
return self.timed.insertion_scores(path, task, each);
}
let mut candidate = Vec::with_capacity(path.len() + 1);
candidate.extend_from_slice(path);
candidate.push(*task);
for position in (0..=path.len()).rev() {
if position < path.len() {
candidate.swap(position, position + 1);
}
each(position, self.path_score(&candidate));
}
}
}
#[derive(Clone, Debug)]
pub struct TimedAgent<R> {
agent: Agent<Scheduled<R>>,
actions: Vec<(TaskId, Action)>,
}
impl<R: Route> TimedAgent<R> {
#[must_use]
pub fn new(
id: AgentId,
agents: usize,
tasks: usize,
capacity: usize,
route: R,
constraints: Constraints,
optimism: Optimism,
) -> Self {
let windowed = Windowed {
route,
windows: RefCell::new(vec![(0, None); tasks]),
};
let valuation = BestInsertion(Coordinated {
timed: Timed(windowed),
constraints: constraints.clone(),
});
Self {
agent: Agent::new(
id,
agents,
tasks,
capacity,
valuation,
constraints,
optimism,
),
actions: Vec::with_capacity(tasks),
}
}
pub fn build_bundle(&mut self) -> usize {
self.refresh_windows();
let added = self.agent.build_bundle();
self.record_own_starts();
added
}
#[must_use]
pub fn message(&mut self) -> TimedMessage {
TimedMessage {
claims: self.agent.message(),
starts: self.view_starts(),
}
}
pub fn receive(&mut self, message: &TimedMessage) -> bool {
let actions = &mut self.actions;
actions.clear();
let Some(changed) = self
.agent
.inner
.receive_with_actions(&message.claims, |task, action| actions.push((task, action)))
else {
return false;
};
{
let gate = self.agent.inner.valuation();
let mut view = gate.view.borrow_mut();
for &(task, action) in &self.actions {
let start = &mut view.starts[task.index()];
match action {
Action::Update => *start = message.starts.get(task.index()).copied().flatten(),
Action::Reset => *start = None,
Action::Leave => {}
}
}
}
self.agent.refresh_view();
self.forget_unassigned_starts();
changed
}
#[must_use]
pub fn can_bid(&self) -> bool {
self.refresh_windows();
self.agent.can_bid() || self.own_starts_would_move()
}
fn refresh_windows(&self) {
let gate = self.agent.inner.valuation();
let view = gate.view.borrow();
let constraints = &gate.constraints;
let claims = self.agent.inner.claims();
let mut windows = gate.inner.0.timed.0.windows.borrow_mut();
for (index, window) in windows.iter_mut().enumerate() {
let task = TaskId(index);
let mut earliest = i128::from(constraints.opening(task));
let mut latest: Option<i128> = None;
for other in constraints.requirements(task) {
let (Some(_), Some(start)) =
(claims[other.index()].winner, view.starts[other.index()])
else {
continue;
};
let (from, until) = constraints.window(task, other, start);
earliest = earliest.max(from.unwrap_or(0));
latest = match (latest, until) {
(Some(current), Some(until)) => Some(current.min(until)),
(current, until) => current.or(until),
};
}
*window = clamp_window(earliest, latest);
}
}
fn own_visits(&self) -> Option<Vec<Visit>> {
let timed = &self.agent.inner.valuation().inner.0.timed;
let path = self.agent.bundle().path();
timed
.schedule(path)
.or_else(|| Timed(&timed.0.route).schedule(path))
}
fn record_own_starts(&mut self) {
if let Some(visits) = self.own_visits() {
let gate = self.agent.inner.valuation();
let mut view = gate.view.borrow_mut();
for visit in visits {
view.starts[visit.task.index()] = Some(visit.start);
}
}
self.forget_unassigned_starts();
}
fn own_starts_would_move(&self) -> bool {
let Some(visits) = self.own_visits() else {
return false;
};
let view = self.agent.inner.valuation().view.borrow();
visits
.iter()
.any(|visit| view.starts[visit.task.index()] != Some(visit.start))
}
fn forget_unassigned_starts(&self) {
let gate = self.agent.inner.valuation();
let claims = self.agent.inner.claims();
let mut view = gate.view.borrow_mut();
for (start, claim) in view.starts.iter_mut().zip(claims) {
if claim.winner.is_none() {
*start = None;
}
}
}
fn view_starts(&self) -> Vec<Option<u64>> {
self.agent.inner.valuation().view.borrow().starts.clone()
}
}
fn clamp_window(earliest: i128, latest: Option<i128>) -> (u64, Option<u64>) {
let earliest = u64::try_from(earliest.max(0)).unwrap_or(u64::MAX);
match latest {
None => (earliest, None),
Some(latest) if latest < 0 => (u64::MAX, Some(0)),
Some(latest) => (earliest, Some(u64::try_from(latest).unwrap_or(u64::MAX))),
}
}
impl<R> TimedAgent<R> {
#[must_use]
pub const fn id(&self) -> AgentId {
self.agent.id()
}
#[must_use]
pub const fn route(&self) -> &R {
&self.agent.valuation().0.timed.0.route
}
#[must_use]
pub const fn constraints(&self) -> &Constraints {
self.agent.constraints()
}
#[must_use]
pub const fn bundle(&self) -> &Bundle<TaskId> {
self.agent.bundle()
}
#[must_use]
pub fn winner(&self, task: TaskId) -> Option<AgentId> {
self.agent.winner(task)
}
#[must_use]
pub fn start(&self, task: TaskId) -> Option<u64> {
self.agent.inner.valuation().view.borrow().starts[task.index()]
}
}
impl<R: Route> Participant for TimedAgent<R> {
type Message = TimedMessage;
fn id(&self) -> AgentId {
self.agent.id()
}
fn bundle(&self) -> &Bundle<TaskId> {
self.agent.bundle()
}
fn act(&mut self, _now: u64, outbox: &mut Vec<TimedMessage>) {
self.build_bundle();
outbox.push(self.message());
}
fn receive(
&mut self,
_now: u64,
message: &TimedMessage,
_outbox: &mut Vec<TimedMessage>,
) -> bool {
TimedAgent::receive(self, message)
}
fn message_bytes(message: &TimedMessage) -> u64 {
let starts = u64::try_from(message.starts.len()).unwrap_or(u64::MAX);
message.claims.bytes() + 4 + 9 * starts
}
fn is_settled(team: &[Self], in_flight: &[&TimedMessage]) -> bool {
let Some(first) = team.first() else {
return true;
};
let claims = first.agent.inner.claims();
let starts = first.view_starts();
team.iter().all(|agent| agent.agent.inner.is_consistent())
&& !team.iter().any(TimedAgent::can_bid)
&& team
.iter()
.all(|agent| agent.agent.inner.claims() == claims && agent.view_starts() == starts)
&& in_flight
.iter()
.all(|message| message.claims.claims() == claims && message.starts == starts)
}
}
#[cfg(test)]
mod tests {
use alloc::vec;
use core::cell::RefCell;
use super::{Constraints, Coordinated, Optimism, TimedAgent, Windowed};
use crate::id::{AgentId, TaskId};
use crate::route::{Route, Timed};
use crate::valuation::PathScore;
struct Point;
impl Route for Point {
type Place = u64;
fn origin(&self) -> u64 {
0
}
fn place(&self, _task: TaskId) -> u64 {
5
}
fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
Some(from.abs_diff(*to))
}
fn reward(&self, _task: TaskId, finish: u64) -> Option<u64> {
(finish <= 100).then_some(1)
}
}
#[test]
fn reports_and_announces_its_starts() {
let optimism = Optimism {
timeout: 1,
solo_attempts: 1,
any_attempts: 1,
};
let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, Constraints::new(1), optimism);
agent.build_bundle();
let message = agent.message();
assert_eq!(agent.id(), AgentId(0));
assert_eq!(agent.constraints(), &Constraints::new(1));
assert_eq!(agent.route().origin(), 0);
assert_eq!(agent.start(TaskId(0)), Some(5));
assert_eq!(message.start(TaskId(0)), Some(5));
assert_eq!(message.claims().winner(TaskId(0)), Some(AgentId(0)));
assert!(!agent.can_bid());
}
#[test]
fn openings_hold_back_the_start() {
let optimism = Optimism {
timeout: 1,
solo_attempts: 1,
any_attempts: 1,
};
let mut constraints = Constraints::new(1);
constraints.set_opening(TaskId(0), 20);
let mut agent = TimedAgent::new(AgentId(0), 1, 1, 1, Point, constraints, optimism);
agent.build_bundle();
assert_eq!(agent.start(TaskId(0)), Some(20));
}
struct Busy;
impl Route for Busy {
type Place = u64;
fn origin(&self) -> u64 {
Point.origin()
}
fn place(&self, task: TaskId) -> u64 {
Point.place(task)
}
fn travel(&self, from: &u64, to: &u64) -> Option<u64> {
Point.travel(from, to)
}
fn duration(&self, _task: TaskId) -> u64 {
4
}
fn reward(&self, task: TaskId, finish: u64) -> Option<u64> {
Point.reward(task, finish)
}
}
#[test]
fn own_tasks_keep_their_timing_limits() {
let coordinated = |limit: i64| {
let mut constraints = Constraints::new(2);
constraints
.add_timed_activity(
&[TaskId(0), TaskId(1)],
&[&[0, 1], &[1, 0]],
&[&[Some(0), Some(limit)], &[Some(limit), Some(0)]],
)
.expect("a well-formed pair");
Coordinated {
timed: Timed(Windowed {
route: Busy,
windows: RefCell::new(vec![(0, None); 2]),
}),
constraints,
}
};
let together = coordinated(0);
assert_eq!(together.path_score(&[TaskId(0)]), Some(1));
assert_eq!(together.path_score(&[TaskId(0), TaskId(1)]), None);
assert_eq!(coordinated(4).path_score(&[TaskId(0), TaskId(1)]), Some(2));
}
}