use proptest::collection::vec;
use proptest::prelude::*;
use task_allocation::cbba::{Agent, Replan};
use task_allocation::sim::{Network, Simulation};
use task_allocation::{AgentId, BestInsertion, PathScore, TaskId, Valuation, check_diminishing};
use crate::cbba::{MAX_TEAM, SETTLE_TICKS, network};
const REWARD: u64 = 100;
const FUEL: u64 = 10;
const MAX_TASKS: usize = 8;
const GRID: u64 = 8;
type Point = (u64, u64);
const fn distance(a: Point, b: Point) -> u64 {
a.0.abs_diff(b.0) + a.1.abs_diff(b.1)
}
#[derive(Clone, Debug)]
struct Route {
start: Point,
sites: Vec<Point>,
}
impl PathScore<TaskId> for Route {
fn path_score(&self, path: &[TaskId]) -> Option<u64> {
let (traveled, _) = path.iter().fold((0, self.start), |(traveled, at), task| {
let site = self.sites[task.index()];
(traveled + distance(at, site), site)
});
let earned = REWARD * u64::try_from(path.len()).expect("short path");
earned.checked_sub(FUEL * traveled)
}
}
#[derive(Clone, Debug)]
struct Instance {
agents: Vec<BestInsertion<Route>>,
tasks: usize,
capacity: usize,
}
impl Instance {
fn is_non_diminishing(&self) -> bool {
let tasks: Vec<TaskId> = (0..self.tasks).map(TaskId).collect();
self.agents
.iter()
.any(|agent| check_diminishing(agent, &tasks, self.capacity).is_err())
}
}
fn point() -> impl Strategy<Value = Point> {
(0..=GRID, 0..=GRID)
}
fn instance() -> impl Strategy<Value = Instance> {
(
vec(point(), 1..=MAX_TASKS),
vec(point(), 2..=MAX_TEAM),
2_usize..=4,
)
.prop_map(|(sites, starts, capacity)| Instance {
tasks: sites.len(),
agents: starts
.into_iter()
.map(|start| {
BestInsertion(Route {
start,
sites: sites.clone(),
})
})
.collect(),
capacity,
})
}
fn team<V: Valuation<TaskId> + Clone>(
agents: &[V],
tasks: usize,
capacity: usize,
replan: Replan,
warping: bool,
) -> Vec<Agent<V>> {
agents
.iter()
.cloned()
.enumerate()
.map(|(id, valuation)| {
let agent = Agent::new(AgentId(id), agents.len(), tasks, capacity, valuation)
.with_replan(replan);
if warping {
agent.with_bid_warping()
} else {
agent
}
})
.collect()
}
fn run<V: Valuation<TaskId>>(
agents: Vec<Agent<V>>,
network: Network,
) -> Option<Simulation<Agent<V>>> {
let healed = network
.partitions
.iter()
.map(|partition| partition.until)
.max()
.unwrap_or(0);
let mut simulation = Simulation::new(agents, network);
simulation.run_until_settled(healed + SETTLE_TICKS)?;
Some(simulation)
}
fn stable<V: Valuation<TaskId>>(
simulation: &Simulation<Agent<V>>,
capacity: usize,
) -> Result<(), TestCaseError> {
let assignment = simulation.assignment();
prop_assert!(assignment.is_conflict_free());
for agent in simulation.agents() {
let bids: Vec<u64> = agent.bundle().entries().map(|(_, bid)| bid).collect();
prop_assert!(bids.windows(2).all(|pair| pair[0] >= pair[1]), "{:?}", bids);
prop_assert!(agent.bundle().len() <= capacity);
for (task, winner) in agent.winners().enumerate() {
let task = TaskId(task);
prop_assert_eq!(winner, assignment.holder(task));
let recorded = winner.and_then(|holder| {
assignment
.bundle(holder)
.entries()
.find(|(held, _)| **held == task)
.map(|(_, bid)| bid)
});
prop_assert_eq!(agent.winning_bid(task), recorded.unwrap_or(0));
}
prop_assert!(agent.bundle().len() >= capacity || !agent.can_bid());
}
Ok(())
}
#[derive(Clone, Debug)]
struct Example2 {
first: TaskId,
}
impl Valuation<TaskId> for Example2 {
fn marginal_score(&self, path: &[TaskId], task: &TaskId) -> Option<u64> {
match (path.is_empty(), *task == self.first) {
(true, true) => Some(10),
(true, false) => Some(9),
(false, _) => Some(11),
}
}
}
fn example2(warping: bool) -> Vec<Agent<Example2>> {
let agents = [Example2 { first: TaskId(0) }, Example2 { first: TaskId(1) }];
team(&agents, 2, 2, Replan::Keep, warping)
}
#[test]
fn example2_settles_with_warping() {
let mut simulation = Simulation::new(example2(true), Network::default());
simulation.run_until_settled(100).expect("settles");
let first = &simulation.agents()[0];
assert_eq!(
first.bundle().entries().collect::<Vec<_>>(),
[(&TaskId(0), 10), (&TaskId(1), 10)]
);
assert!(simulation.agents()[1].bundle().is_empty());
}
#[test]
fn example2_settles_without_warping_with_growing_bids() {
let mut simulation = Simulation::new(example2(false), Network::default());
simulation.run_until_settled(100).expect("settles");
let first = &simulation.agents()[0];
assert_eq!(
first.bundle().entries().collect::<Vec<_>>(),
[(&TaskId(0), 10), (&TaskId(1), 11)]
);
}
fn two_couriers(replan: Replan, warping: bool) -> Simulation<Agent<BestInsertion<Route>>> {
let sites = vec![(3, 6), (6, 6)];
let agents: Vec<_> = [(3, 2), (4, 7)]
.into_iter()
.map(|start| {
BestInsertion(Route {
start,
sites: sites.clone(),
})
})
.collect();
Simulation::new(team(&agents, 2, 2, replan, warping), Network::default())
}
#[test]
fn two_couriers_cycle_without_warping() {
for replan in [Replan::Keep, Replan::Full] {
let mut simulation = two_couriers(replan, false);
assert_eq!(simulation.run_until_settled(1_000), None, "{replan:?}");
}
}
#[test]
fn two_couriers_settle_with_warping() {
for replan in [Replan::Keep, Replan::Full] {
let mut simulation = two_couriers(replan, true);
simulation.run_until_settled(100).expect("settles");
assert!(simulation.agents()[0].bundle().is_empty(), "{replan:?}");
assert_eq!(
simulation.agents()[1]
.bundle()
.entries()
.collect::<Vec<_>>(),
[(&TaskId(0), 80), (&TaskId(1), 70)],
"{replan:?}"
);
}
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn route_scores_settle(
(instance, network) in instance().prop_filter("gains diminish", Instance::is_non_diminishing)
.prop_flat_map(|instance| {
let agents = instance.agents.len();
(Just(instance), network(agents))
}),
full in any::<bool>(),
) {
let replan = if full { Replan::Full } else { Replan::Keep };
let agents = team(&instance.agents, instance.tasks, instance.capacity, replan, true);
let Some(simulation) = run(agents, network) else {
return Err(TestCaseError::fail("did not settle"));
};
stable(&simulation, instance.capacity)?;
}
}