use proptest::collection::vec;
use proptest::prelude::*;
use task_allocation::{AgentId, BestInsertion, Insertion, PathScore, TaskId, Valuation};
pub const MAX_TASKS: usize = 6;
pub const MAX_AGENTS: usize = 3;
#[derive(Clone, Copy, Debug)]
pub struct Site {
pub position: u64,
pub duration: u64,
pub deadline: u64,
}
#[derive(Clone, Debug)]
pub struct Coverage {
pub covers: Vec<u16>,
pub weights: Vec<u64>,
pub allowed: u32,
}
impl Valuation<TaskId> for Coverage {
fn marginal_score(&self, bundle: &[TaskId], task: &TaskId) -> Option<u64> {
if self.allowed & (1 << task.index()) == 0 {
return None;
}
let covered = bundle
.iter()
.fold(0_u16, |mask, held| mask | self.covers[held.index()]);
let fresh = self.covers[task.index()] & !covered;
Some(
self.weights
.iter()
.enumerate()
.filter(|(item, _)| fresh & (1 << item) != 0)
.map(|(_, weight)| weight)
.sum(),
)
}
}
#[derive(Clone, Debug)]
pub struct Courier {
pub start: u64,
pub sites: Vec<Site>,
pub rewards: Vec<u64>,
}
impl PathScore<TaskId> for Courier {
fn path_score(&self, path: &[TaskId]) -> Option<u64> {
let mut at = self.start;
let mut clock = 0;
let mut total = 0;
for task in path {
let site = self.sites[task.index()];
clock += at.abs_diff(site.position) + site.duration;
if clock > site.deadline {
return None;
}
at = site.position;
total += self.rewards[task.index()];
}
Some(total)
}
}
#[derive(Clone, Debug)]
pub enum Agent {
Coverage(Coverage),
Courier(BestInsertion<Courier>),
}
impl Valuation<TaskId> for Agent {
fn marginal_score(&self, bundle: &[TaskId], task: &TaskId) -> Option<u64> {
match self {
Self::Coverage(coverage) => coverage.marginal_score(bundle, task),
Self::Courier(courier) => courier.marginal_score(bundle, task),
}
}
fn best_insertion(&self, path: &[TaskId], task: &TaskId) -> Option<Insertion> {
match self {
Self::Coverage(coverage) => coverage.best_insertion(path, task),
Self::Courier(courier) => courier.best_insertion(path, task),
}
}
}
#[derive(Clone, Debug)]
pub struct Instance {
pub agents: Vec<Agent>,
pub tasks: usize,
pub capacity: usize,
}
impl Instance {
pub fn task_ids(&self) -> Vec<TaskId> {
(0..self.tasks).map(TaskId).collect()
}
}
fn coverage(tasks: usize) -> impl Strategy<Value = Coverage> {
(
vec(any::<u16>().prop_map(|mask| mask & 0xff), tasks),
vec(1_u64..20, 8),
any::<u32>(),
)
.prop_map(|(covers, weights, allowed)| Coverage {
covers,
weights,
allowed: allowed | 1,
})
}
fn courier(sites: Vec<Site>) -> impl Strategy<Value = BestInsertion<Courier>> {
let tasks = sites.len();
(0_u64..100, vec(1_u64..30, tasks)).prop_map(move |(start, rewards)| {
BestInsertion(Courier {
start,
sites: sites.clone(),
rewards,
})
})
}
fn sites(tasks: usize) -> impl Strategy<Value = Vec<Site>> {
vec(
(0_u64..100, 1_u64..20, 20_u64..300).prop_map(|(position, duration, deadline)| Site {
position,
duration,
deadline,
}),
tasks,
)
}
fn agent(sites: Vec<Site>) -> impl Strategy<Value = Agent> {
let tasks = sites.len();
prop_oneof![
coverage(tasks).prop_map(Agent::Coverage),
courier(sites).prop_map(Agent::Courier),
]
}
pub fn coverage_instance() -> impl Strategy<Value = Instance> {
(1..=MAX_TASKS, 1..=MAX_AGENTS)
.prop_flat_map(|(tasks, agents)| (Just(tasks), Just(agents), 1..=tasks))
.prop_flat_map(|(tasks, agents, capacity)| {
(
vec(coverage(tasks).prop_map(Agent::Coverage), agents),
Just(tasks),
Just(capacity),
)
})
.prop_map(|(agents, tasks, capacity)| Instance {
agents,
tasks,
capacity,
})
}
pub fn instance() -> impl Strategy<Value = Instance> {
instance_with(MAX_AGENTS)
}
pub fn instance_with(max_agents: usize) -> impl Strategy<Value = Instance> {
instance_sized(max_agents, MAX_TASKS)
}
pub fn instance_sized(max_agents: usize, max_tasks: usize) -> impl Strategy<Value = Instance> {
(1..=max_tasks, 1..=max_agents)
.prop_flat_map(|(tasks, agents)| (Just(tasks), Just(agents), 1..=tasks))
.prop_flat_map(|(tasks, agents, capacity)| {
sites(tasks).prop_flat_map(move |sites| {
(vec(agent(sites), agents), Just(tasks), Just(capacity))
})
})
.prop_map(|(agents, tasks, capacity)| Instance {
agents,
tasks,
capacity,
})
}
pub fn is_greedy_outcome(instance: &Instance, holders: &[Option<AgentId>]) -> bool {
let mut paths: Vec<Vec<TaskId>> = vec![Vec::new(); instance.agents.len()];
greedy_run_exists(instance, holders, &mut paths)
}
fn greedy_run_exists(
instance: &Instance,
holders: &[Option<AgentId>],
paths: &mut [Vec<TaskId>],
) -> bool {
let picks = best_picks(instance, paths);
let Some(&(_, _, gain)) = picks.first() else {
return (0..instance.tasks).all(|task| {
let held_by = paths.iter().position(|path| path.contains(&TaskId(task)));
held_by.map(AgentId) == holders[task]
});
};
debug_assert!(gain > 0);
picks
.into_iter()
.filter(|&(agent, task, _)| holders[task.index()] == Some(agent))
.any(|(agent, task, _)| {
let insertion = instance.agents[agent.index()]
.best_insertion(&paths[agent.index()], &task)
.expect("picks are feasible");
paths[agent.index()].insert(insertion.position, task);
let found = greedy_run_exists(instance, holders, paths);
paths[agent.index()].retain(|held| *held != task);
found
})
}
fn best_picks(instance: &Instance, paths: &[Vec<TaskId>]) -> Vec<(AgentId, TaskId, u64)> {
let assigned = |task: TaskId| paths.iter().any(|path| path.contains(&task));
let mut picks = Vec::new();
let mut best = 0;
for (index, agent) in instance.agents.iter().enumerate() {
let path = &paths[index];
if path.len() >= instance.capacity {
continue;
}
for task in (0..instance.tasks)
.map(TaskId)
.filter(|&task| !assigned(task))
{
let Some(insertion) = agent.best_insertion(path, &task) else {
continue;
};
if insertion.gain > best {
best = insertion.gain;
picks.clear();
}
if insertion.gain == best && best > 0 {
picks.push((AgentId(index), task, insertion.gain));
}
}
}
picks
}