mod cardinal;
mod cover;
mod heuristic;
mod pairs;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::rc::Rc;
use alloc::vec;
use alloc::vec::Vec;
use core::cell::RefCell;
use core::cmp::{Ordering, Reverse};
use heuristic_search::{Budget, Stats};
use self::cardinal::{Cardinality, cardinality, forced};
use self::heuristic::PairKey;
use crate::conflict::{Conflict, conflicts};
use crate::conflict_table::ConflictTable;
use crate::constraint::{Constraint, ConstraintSet};
use crate::graph::Graph;
use crate::instance::{AgentId, Instance};
use crate::low_level::{distance_tables, plan, plan_avoiding};
use crate::mdd::Mdd;
use crate::path::{Objective, Path, makespan, path_cost, sum_of_costs};
use crate::solution::{MapfResult, Outcome, Solution};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CbsConfig {
pub objective: Objective,
pub prioritize_conflicts: bool,
pub bypass: bool,
pub splitting: Splitting,
pub heuristic: CbsHeuristic,
pub conflict_avoidance: bool,
}
impl CbsConfig {
#[must_use]
pub const fn plain(objective: Objective) -> Self {
Self {
objective,
prioritize_conflicts: false,
bypass: false,
splitting: Splitting::Standard,
heuristic: CbsHeuristic::None,
conflict_avoidance: false,
}
}
#[must_use]
pub const fn improved(objective: Objective) -> Self {
Self {
objective,
prioritize_conflicts: true,
bypass: true,
splitting: Splitting::Disjoint,
heuristic: CbsHeuristic::Dg,
conflict_avoidance: true,
}
}
fn needs_mdds(self) -> bool {
self.prioritize_conflicts || self.uses_heuristic()
}
fn effective_heuristic(self) -> CbsHeuristic {
match self.objective {
Objective::SumOfCosts => self.heuristic,
Objective::Makespan => CbsHeuristic::None,
}
}
fn uses_heuristic(self) -> bool {
self.effective_heuristic() != CbsHeuristic::None
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum Splitting {
#[default]
Standard,
Disjoint,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum CbsHeuristic {
#[default]
None,
Cg,
Dg,
Wdg,
}
pub fn cbs<G: Graph>(
instance: &Instance<G>,
objective: Objective,
budget: impl Budget<Stats>,
) -> MapfResult {
cbs_with(instance, CbsConfig::improved(objective), budget)
}
pub fn cbs_with<G: Graph>(
instance: &Instance<G>,
config: CbsConfig,
mut budget: impl Budget<Stats>,
) -> MapfResult {
let mut search = Search::new(instance, config);
let outcome = search.run(&mut budget);
MapfResult {
outcome,
stats: search.stats,
}
}
#[derive(Clone)]
struct Node {
constraints: Vec<Constraint>,
paths: Vec<Path>,
mdds: Vec<Option<Rc<Mdd>>>,
sum_of_costs: u32,
makespan: u32,
conflict: Option<Conflict>,
conflict_count: usize,
heuristic: u32,
}
struct Entry {
key: (u32, u32, usize, u64),
node: Node,
}
impl PartialEq for Entry {
fn eq(&self, other: &Self) -> bool {
self.key == other.key
}
}
impl Eq for Entry {}
impl PartialOrd for Entry {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Entry {
fn cmp(&self, other: &Self) -> Ordering {
Reverse(self.key).cmp(&Reverse(other.key))
}
}
struct Search<'a, G> {
instance: &'a Instance<G>,
config: CbsConfig,
distances: Vec<Vec<Option<u32>>>,
open: BinaryHeap<Entry>,
pair_weights: RefCell<BTreeMap<PairKey, Option<u32>>>,
stats: Stats,
}
impl<'a, G: Graph> Search<'a, G> {
fn new(instance: &'a Instance<G>, config: CbsConfig) -> Self {
Self {
instance,
config,
distances: distance_tables(instance.graph(), instance.agents()),
open: BinaryHeap::new(),
pair_weights: RefCell::new(BTreeMap::new()),
stats: Stats::default(),
}
}
fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
let Some(root) = self.root() else {
return Outcome::Unsolvable;
};
self.push(root);
self.run_open(budget)
}
fn run_open(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
while let Some(Entry { node, .. }) = self.open.pop() {
let Some(conflict) = node.conflict else {
return Outcome::Solved(Solution::new(node.paths));
};
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.expand(node, conflict);
}
Outcome::Unsolvable
}
fn root(&self) -> Option<Node> {
let agents = self.instance.agents().len();
let mut paths = Vec::with_capacity(agents);
for agent in 0..agents {
let path = self.replan(agent, &[], &paths)?;
paths.push(path);
}
self.node(Vec::new(), paths, vec![None; agents])
}
fn expand(&mut self, parent: Node, conflict: Conflict) {
self.stats.expanded += 1;
let children: Vec<Child> = self
.split(&parent, conflict)
.into_iter()
.filter_map(|constraint| self.child(&parent, constraint))
.collect();
if self.config.bypass {
if let Some(child) = children.iter().find(|child| is_bypass(&parent, child)) {
if let Some(adopted) = self.adopt(parent, child) {
self.push(adopted);
}
return;
}
}
for child in children {
self.push(child.node);
}
}
fn split(&self, parent: &Node, conflict: Conflict) -> [Constraint; 2] {
match self.config.splitting {
Splitting::Standard => Constraint::resolving(conflict),
Splitting::Disjoint => Constraint::disjoint(conflict, split_side(parent, &conflict)),
}
}
fn adopt(&self, parent: Node, child: &Child) -> Option<Node> {
let mut paths = parent.paths;
for &agent in &child.replanned {
paths[agent].clone_from(&child.node.paths[agent]);
}
self.node(parent.constraints, paths, parent.mdds)
}
fn child(&self, parent: &Node, constraint: Constraint) -> Option<Child> {
let mut constraints = parent.constraints.clone();
constraints.push(constraint);
let replanned = affected(constraint, &parent.paths);
let mut paths = parent.paths.clone();
let mut mdds = parent.mdds.clone();
for &agent in &replanned {
paths[agent] = self.replan(agent, &constraints, &paths)?;
mdds[agent] = None;
}
mdds[constraint.agent()] = None;
let node = self.node(constraints, paths, mdds)?;
Some(Child { node, replanned })
}
fn replan(&self, agent: AgentId, constraints: &[Constraint], paths: &[Path]) -> Option<Path> {
let set = ConstraintSet::for_agent(agent, constraints);
let (graph, distances) = (self.instance.graph(), &self.distances[agent]);
let start_and_goal = self.instance.agents()[agent];
if self.config.conflict_avoidance {
let table = ConflictTable::without(paths, agent);
plan_avoiding(graph, start_and_goal, &set, distances, &table)
} else {
plan(graph, start_and_goal, &set, distances)
}
}
fn node(
&self,
constraints: Vec<Constraint>,
paths: Vec<Path>,
mut mdds: Vec<Option<Rc<Mdd>>>,
) -> Option<Node> {
let found = conflicts(&paths);
let (conflict, heuristic) = if self.config.needs_mdds() {
self.fill_mdds(&constraints, &paths, &mut mdds, &found);
let classes: Vec<Cardinality> = found.iter().map(|c| cardinality(c, &mdds)).collect();
let heuristic = self.heuristic(&constraints, &paths, &found, &classes, &mdds)?;
(self.choose(&found, &classes), heuristic)
} else {
(found.first().copied(), 0)
};
Some(Node {
sum_of_costs: sum_of_costs(&paths),
makespan: makespan(&paths),
conflict,
conflict_count: found.len(),
heuristic,
constraints,
paths,
mdds,
})
}
fn fill_mdds(
&self,
constraints: &[Constraint],
paths: &[Path],
mdds: &mut [Option<Rc<Mdd>>],
found: &[Conflict],
) {
for conflict in found {
let (a, b) = conflict.agents();
for agent in [a, b] {
if mdds[agent].is_some() {
continue;
}
let set = ConstraintSet::for_agent(agent, constraints);
let mdd = Mdd::build(
self.instance.graph(),
self.instance.agents()[agent],
&set,
&self.distances[agent],
path_cost(&paths[agent]),
)
.expect("the agent's own path is in its MDD");
mdds[agent] = Some(Rc::new(mdd));
}
}
}
fn choose(&self, found: &[Conflict], classes: &[Cardinality]) -> Option<Conflict> {
if !self.config.prioritize_conflicts {
return found.first().copied();
}
let best = classes.iter().max()?;
found
.iter()
.zip(classes)
.find(|(_, class)| *class == best)
.map(|(conflict, _)| *conflict)
}
fn push(&mut self, node: Node) {
let (soc, makespan) = (node.sum_of_costs, node.makespan);
let (first, second) = match self.config.objective {
Objective::SumOfCosts => (soc + node.heuristic, makespan),
Objective::Makespan => (makespan, soc),
};
let key = (first, second, node.conflict_count, self.stats.generated);
self.stats.generated += 1;
self.open.push(Entry { key, node });
}
}
struct Child {
node: Node,
replanned: Vec<AgentId>,
}
fn is_bypass(parent: &Node, child: &Child) -> bool {
let same_cost = child
.replanned
.iter()
.all(|&agent| path_cost(&child.node.paths[agent]) == path_cost(&parent.paths[agent]));
same_cost && child.node.conflict_count < parent.conflict_count
}
fn affected(constraint: Constraint, paths: &[Path]) -> Vec<AgentId> {
if !constraint.is_positive() {
return Vec::from([constraint.agent()]);
}
(0..paths.len())
.filter(|&agent| agent != constraint.agent())
.filter(|&agent| {
constraint
.implied_for(agent)
.iter()
.any(|implied| implied.is_violated_by(&paths[agent]))
})
.collect()
}
fn split_side(parent: &Node, conflict: &Conflict) -> usize {
let (a, b) = conflict.agents();
if parent.mdds[a].is_none() || parent.mdds[b].is_none() {
return 0;
}
match forced(conflict, &parent.mdds) {
[false, true] => 1,
_ => 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::Grid;
use crate::instance::Agent;
type Route = ((usize, usize), (usize, usize));
fn instance(rows: &[&str], agents: &[Route]) -> Instance<Grid> {
let grid = Grid::parse(rows);
let agents = agents
.iter()
.map(|&((sx, sy), (gx, gy))| Agent {
start: grid.vertex(sx, sy),
goal: grid.vertex(gx, gy),
})
.collect();
Instance::new(grid, agents).expect("valid")
}
#[test]
fn crossing_on_a_plus_is_cardinal() {
let plus = instance(
&["@.@", "...", "@.@"],
&[((0, 1), (2, 1)), ((1, 0), (1, 2))],
);
let search = Search::new(&plus, CbsConfig::improved(Objective::SumOfCosts));
let root = search.root().expect("both reach their goals");
assert_eq!(root.heuristic, 1);
assert_eq!(root.sum_of_costs, 4);
let plain = Search::new(&plus, CbsConfig::plain(Objective::SumOfCosts));
assert_eq!(plain.root().expect("reachable").heuristic, 0);
}
#[test]
fn prioritizing_prefers_cardinal_conflicts() {
let grid = Grid::new(3, 2);
let mdd = |start, goal, depth| {
let distances = crate::graph::distances_to(&grid, goal);
let agent = Agent { start, goal };
Mdd::build(&grid, agent, &ConstraintSet::new(), &distances, depth).map(Rc::new)
};
let mdds = [mdd(0, 5, 3), mdd(2, 3, 3), mdd(4, 1, 1), mdd(0, 2, 2)];
let at_one = |agents| Conflict::Vertex {
agents,
vertex: 1,
time: 1,
};
let (wide, forced) = (at_one((0, 1)), at_one((2, 3)));
let any = instance(&["..."], &[((0, 0), (2, 0))]);
let improved = Search::new(&any, CbsConfig::improved(Objective::SumOfCosts));
let plain = Search::new(&any, CbsConfig::plain(Objective::SumOfCosts));
let found = [wide, forced];
let classes = found.map(|conflict| cardinality(&conflict, &mdds));
let heuristic = |search: &Search<'_, Grid>| {
let (constraints, paths) = (Vec::new(), Vec::new());
search.heuristic(&constraints, &paths, &found, &classes, &mdds)
};
assert_eq!(improved.choose(&found, &classes), Some(forced));
assert_eq!(heuristic(&improved), Some(1));
assert_eq!(plain.choose(&found, &classes), Some(wide));
assert_eq!(heuristic(&plain), Some(0));
}
#[test]
fn bypass_adopts_an_equally_cheap_child() {
let open = instance(
&["...", "...", "..."],
&[((0, 0), (2, 2)), ((2, 0), (0, 2))],
);
let mut config = CbsConfig::plain(Objective::SumOfCosts);
config.bypass = true;
let mut search = Search::new(&open, config);
let root = search.root().expect("reachable");
let conflict = root.conflict.expect("the diagonal paths meet");
search.expand(root, conflict);
let Entry { node, .. } = search.open.pop().expect("the adopted node");
assert!(search.open.is_empty(), "no children were opened");
assert!(
node.constraints.is_empty(),
"the parent keeps its constraints"
);
assert_eq!((node.sum_of_costs, node.conflict_count), (8, 0));
}
}