use alloc::vec::Vec;
use heuristic_search::{Budget, Stats};
use super::{CbsConfig, Search};
use crate::assignment::Ranked;
use crate::graph::{Graph, Vertex, distances_to};
use crate::instance::TaskInstance;
use crate::path::Objective;
use crate::solution::{MapfResult, Outcome};
pub fn cbs_ta<G: Graph>(
instance: &TaskInstance<G>,
objective: Objective,
budget: impl Budget<Stats>,
) -> MapfResult {
cbs_ta_with(instance, CbsConfig::improved(objective), budget)
}
pub fn cbs_ta_with<G: Graph>(
instance: &TaskInstance<G>,
config: CbsConfig,
mut budget: impl Budget<Stats>,
) -> MapfResult {
let graph = instance.graph();
let starts: Vec<Vertex> = instance.agents().iter().map(|agent| agent.start).collect();
let goals = candidate_goals(instance);
let distances: Vec<Vec<Option<u32>>> = goals
.iter()
.map(|&goal| distances_to(graph, goal))
.collect();
let costs = cost_matrix(instance, &goals, &distances);
let ranked = Ranked::new(&costs, config.objective);
if ranked.peek().is_none() {
return MapfResult {
outcome: Outcome::Unsolvable,
stats: Stats::default(),
};
}
let mut search = Search::forest(graph, starts, goals, distances, Some(ranked), config);
let outcome = search.run(&mut budget);
MapfResult {
outcome,
stats: search.stats,
}
}
fn candidate_goals<G: Graph>(instance: &TaskInstance<G>) -> Vec<Vertex> {
let mut goals: Vec<Vertex> = instance
.agents()
.iter()
.flat_map(|agent| agent.goals.iter().copied())
.collect();
goals.sort_unstable();
goals.dedup();
goals
}
fn cost_matrix<G: Graph>(
instance: &TaskInstance<G>,
goals: &[Vertex],
distances: &[Vec<Option<u32>>],
) -> Vec<Vec<Option<u32>>> {
instance
.agents()
.iter()
.map(|agent| {
goals
.iter()
.zip(distances)
.map(|(goal, table)| {
agent
.goals
.contains(goal)
.then(|| table[agent.start])
.flatten()
})
.collect()
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use heuristic_search::Limits;
use proptest::prelude::*;
use crate::cbs::{CbsConfig, cbs_with};
use crate::graph::Grid;
use crate::instance::{Agent, Instance, TaskAgent};
use crate::solution::Solution;
const BUDGET: u64 = 2_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Expected {
Cost(u32),
Unsolvable,
Unknown,
}
fn brute_force(instance: &TaskInstance<Grid>, config: CbsConfig) -> Expected {
let mut best: Option<u32> = None;
for goals in injective(instance) {
let agents = instance
.agents()
.iter()
.zip(&goals)
.map(|(agent, &goal)| Agent {
start: agent.start,
goal,
})
.collect();
let fixed = Instance::new(instance.graph().clone(), agents).expect("distinct goals");
match cbs_with(&fixed, config, Limits::expansions(BUDGET)).outcome {
Outcome::Solved(solution) => {
let cost = solution.cost(config.objective);
best = Some(best.map_or(cost, |b| b.min(cost)));
}
Outcome::Unsolvable => {}
Outcome::LimitReached | Outcome::Exhausted => return Expected::Unknown,
}
}
best.map_or(Expected::Unsolvable, Expected::Cost)
}
fn injective(instance: &TaskInstance<Grid>) -> Vec<Vec<Vertex>> {
let mut choices = vec![Vec::new()];
for agent in instance.agents() {
let mut extended = Vec::new();
for chosen in &choices {
for &goal in &agent.goals {
if !chosen.contains(&goal) {
let mut next: Vec<Vertex> = chosen.clone();
next.push(goal);
extended.push(next);
}
}
}
choices = extended;
}
choices
}
fn instance() -> impl Strategy<Value = TaskInstance<Grid>> {
let walls = prop::collection::vec(0_usize..9, 0..=2);
let agents = prop::collection::vec(
(0_usize..9, prop::collection::vec(0_usize..9, 1..=3)),
1..=3,
);
(walls, agents).prop_map(|(walls, agents)| {
let mut rows = [*b"...", *b"...", *b"..."];
for wall in walls {
rows[wall / 3][wall % 3] = b'@';
}
let rows: Vec<&str> = rows
.iter()
.map(|row| core::str::from_utf8(row).expect("ascii"))
.collect();
let grid = Grid::parse(&rows);
let mut seen = Vec::new();
let agents = agents
.into_iter()
.filter(|(start, _)| {
let fresh = !seen.contains(start);
seen.push(*start);
fresh
})
.map(|(start, goals)| TaskAgent { start, goals })
.collect();
TaskInstance::new(grid, agents).expect("distinct starts on the grid")
})
}
fn assigns_candidates(instance: &TaskInstance<Grid>, solution: &Solution) -> bool {
let ends: Vec<Vertex> = solution
.paths
.iter()
.map(|path| *path.last().expect("non-empty"))
.collect();
let distinct = ends
.iter()
.enumerate()
.all(|(i, end)| !ends[..i].contains(end));
distinct
&& instance
.agents()
.iter()
.zip(&ends)
.zip(&solution.paths)
.all(|((agent, end), path)| {
agent.goals.contains(end) && path.first() == Some(&agent.start)
})
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(64))]
#[test]
fn matches_cbs_over_every_assignment(
instance in instance(),
makespan in any::<bool>(),
improved in any::<bool>(),
) {
let objective = if makespan { Objective::Makespan } else { Objective::SumOfCosts };
let config = if improved { CbsConfig::improved(objective) } else { CbsConfig::plain(objective) };
let expected = brute_force(&instance, config);
if expected == Expected::Unknown {
return Ok(());
}
let result = cbs_ta_with(&instance, config, Limits::expansions(BUDGET * 64));
match (&result.outcome, expected) {
(Outcome::Solved(solution), Expected::Cost(cost)) => {
prop_assert_eq!(solution.cost(objective), cost);
prop_assert!(assigns_candidates(&instance, solution));
prop_assert_eq!(crate::conflict::first_conflict(&solution.paths), None);
}
(Outcome::Unsolvable | Outcome::LimitReached, Expected::Unsolvable) => {}
(outcome, expected) => prop_assert!(false, "{outcome:?}, expected {expected:?}"),
}
}
}
#[test]
fn single_candidates_are_cbs() {
let grid = Grid::parse(&["...", "@.@"]);
let agents = vec![Agent { start: 0, goal: 2 }, Agent { start: 2, goal: 0 }];
let fixed = Instance::new(grid.clone(), agents.clone()).expect("valid");
let tasks = TaskInstance::new(
grid,
agents
.iter()
.map(|agent| TaskAgent {
start: agent.start,
goals: vec![agent.goal],
})
.collect(),
)
.expect("valid");
for objective in [Objective::SumOfCosts, Objective::Makespan] {
let config = CbsConfig::improved(objective);
let ta = cbs_ta_with(&tasks, config, Limits::expansions(BUDGET));
let plain = cbs_with(&fixed, config, Limits::expansions(BUDGET));
assert_eq!(ta.outcome, plain.outcome);
assert_eq!(ta.stats, plain.stats);
}
}
#[test]
fn no_agents_is_the_empty_plan() {
let tasks = TaskInstance::new(Grid::new(2, 1), Vec::new()).expect("valid");
let fixed = Instance::new(Grid::new(2, 1), Vec::new()).expect("valid");
for objective in [Objective::SumOfCosts, Objective::Makespan] {
let ta = cbs_ta(&tasks, objective, Limits::NONE);
let plain = crate::cbs::cbs(&fixed, objective, Limits::NONE);
assert_eq!(ta.outcome, Outcome::Solved(Solution::new(Vec::new())));
assert_eq!(ta.outcome, plain.outcome);
}
}
#[test]
fn too_few_goals_is_unsolvable() {
let grid = Grid::new(3, 1);
let agents = vec![
TaskAgent {
start: 0,
goals: vec![1],
},
TaskAgent {
start: 2,
goals: vec![1],
},
];
let instance = TaskInstance::new(grid, agents).expect("valid");
let result = cbs_ta(&instance, Objective::SumOfCosts, Limits::NONE);
assert_eq!(result.outcome, Outcome::Unsolvable);
assert_eq!(result.stats, Stats::default());
}
}