mod low_level;
mod node;
mod split;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::RefCell;
use heuristic_search::{Budget, Stats};
use multiobjective_search::{Dominates, weakly_dominates};
use self::low_level::{Heuristic, Problem, pareto_paths};
use self::node::{Combinations, Node, ParetoSet};
use crate::cbs::Splitting;
use crate::conflict::Conflict;
use crate::constraint::{Constraint, ConstraintSet};
use crate::graph::{Graph, Vertex};
use crate::instance::{AgentId, Instance};
use crate::mstar::{MStarConfig, mstar_with};
use crate::path::{Objective, Path};
use crate::solution::Outcome;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LowLevel {
#[default]
Auto,
NamoaDr,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[expect(
clippy::struct_excessive_bools,
reason = "independent on-off switches, each documented, as in CbsConfig"
)]
pub struct MoCbsConfig {
pub tree_by_tree: bool,
pub low_level: LowLevel,
pub feasibility_check: bool,
pub prioritize_conflicts: bool,
pub bypass: bool,
pub splitting: Splitting,
}
impl MoCbsConfig {
#[must_use]
pub const fn plain() -> Self {
Self {
tree_by_tree: false,
low_level: LowLevel::Auto,
feasibility_check: false,
prioritize_conflicts: false,
bypass: false,
splitting: Splitting::Standard,
}
}
#[must_use]
pub const fn tree_by_tree() -> Self {
Self {
tree_by_tree: true,
..Self::plain()
}
}
#[must_use]
pub const fn improved() -> Self {
Self {
tree_by_tree: true,
low_level: LowLevel::Auto,
feasibility_check: true,
prioritize_conflicts: true,
bypass: true,
splitting: Splitting::Disjoint,
}
}
}
impl Default for MoCbsConfig {
fn default() -> Self {
Self::improved()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParetoSolution<const N: usize> {
pub paths: Vec<Path>,
pub cost: [u32; N],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ParetoOutcome {
Complete,
Unsolvable,
LimitReached,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParetoResult<const N: usize> {
pub outcome: ParetoOutcome,
pub front: Vec<ParetoSolution<N>>,
pub stats: Stats,
}
pub fn mo_cbs<G: Graph, const N: usize>(
instance: &Instance<G>,
costs: &impl Fn(Vertex, Vertex) -> [u32; N],
budget: impl Budget<Stats>,
) -> ParetoResult<N> {
mo_cbs_with(instance, costs, MoCbsConfig::improved(), budget)
}
pub fn mo_cbs_with<G: Graph, const N: usize>(
instance: &Instance<G>,
costs: &impl Fn(Vertex, Vertex) -> [u32; N],
config: MoCbsConfig,
budget: impl Budget<Stats>,
) -> ParetoResult<N> {
mo_cbs_per_agent(instance, &|_, from, to| costs(from, to), config, budget)
}
pub fn mo_cbs_per_agent<G: Graph, const N: usize>(
instance: &Instance<G>,
costs: &impl Fn(AgentId, Vertex, Vertex) -> [u32; N],
config: MoCbsConfig,
mut budget: impl Budget<Stats>,
) -> ParetoResult<N> {
let mut search = Search::new(instance, costs, config, &mut budget);
let outcome = search.run();
let mut front = search.front;
front.sort_by_key(|plan| plan.cost);
ParetoResult {
outcome,
front,
stats: search.stats,
}
}
struct Interrupted;
struct Child<const N: usize> {
constraints: Vec<Constraint>,
replanned: Vec<(AgentId, ParetoSet<N>)>,
}
struct Search<'a, G, F, const N: usize> {
instance: &'a Instance<G>,
costs: &'a F,
config: MoCbsConfig,
heuristics: Vec<Heuristic<N>>,
budget: RefCell<&'a mut dyn Budget<Stats>>,
open: BTreeMap<([u32; N], u64), Node<N>>,
front: Vec<ParetoSolution<N>>,
stats: Stats,
}
impl<'a, G: Graph, F: Fn(AgentId, Vertex, Vertex) -> [u32; N], const N: usize> Search<'a, G, F, N> {
fn new(
instance: &'a Instance<G>,
costs: &'a F,
config: MoCbsConfig,
budget: &'a mut dyn Budget<Stats>,
) -> Self {
let graph = instance.graph();
let heuristics = instance
.agents()
.iter()
.enumerate()
.map(|(id, agent)| Heuristic::new(graph, &|u, v| costs(id, u, v), agent.goal))
.collect();
Self {
instance,
costs,
config,
heuristics,
budget: RefCell::new(budget),
open: BTreeMap::new(),
front: Vec::new(),
stats: Stats::default(),
}
}
fn run(&mut self) -> ParetoOutcome {
if self.config.feasibility_check && self.is_proven_infeasible() {
return ParetoOutcome::Unsolvable;
}
let mut roots = match self.roots() {
Ok(Some(roots)) => roots,
Ok(None) => return ParetoOutcome::Unsolvable,
Err(Interrupted) => return ParetoOutcome::LimitReached,
};
if !self.config.tree_by_tree {
for root in roots.by_ref() {
if self.is_exhausted() {
return ParetoOutcome::LimitReached;
}
self.push(root);
}
}
loop {
if self.run_open().is_err() {
return ParetoOutcome::LimitReached;
}
let Some(root) = roots.next() else { break };
self.push(root);
}
if self.front.is_empty() {
ParetoOutcome::Unsolvable
} else {
ParetoOutcome::Complete
}
}
fn is_proven_infeasible(&self) -> bool {
let config = MStarConfig::recursive(Objective::SumOfCosts);
let budget = |stats: &Stats| self.budget.borrow_mut().exhausted(stats);
mstar_with(self.instance, config, budget).outcome == Outcome::Unsolvable
}
fn is_exhausted(&self) -> bool {
self.budget.borrow_mut().exhausted(&self.stats)
}
fn roots(&self) -> Result<Option<Combinations<N>>, Interrupted> {
let mut sets = Vec::new();
for agent in 0..self.instance.agents().len() {
let set = self.replan(agent, &[])?;
if set.is_empty() {
return Ok(None);
}
sets.push(set);
}
Ok(Some(Combinations::roots(sets)))
}
fn run_open(&mut self) -> Result<(), Interrupted> {
while let Some((_, node)) = self.open.pop_first() {
if self.is_filtered(&node.cost) {
continue;
}
let Some(conflict) = split::choose(&node, self.config.prioritize_conflicts) else {
self.record(&node);
continue;
};
if self.is_exhausted() {
return Err(Interrupted);
}
self.expand(&node, conflict)?;
}
Ok(())
}
fn is_filtered(&self, cost: &[u32; N]) -> bool {
self.front
.iter()
.any(|plan| weakly_dominates(&plan.cost, cost))
}
fn record(&mut self, node: &Node<N>) {
self.front.retain(|plan| !node.cost.dominates(&plan.cost));
self.front.push(ParetoSolution {
paths: node.paths.iter().map(|path| path.to_vec()).collect(),
cost: node.cost,
});
}
fn expand(&mut self, node: &Node<N>, conflict: Conflict) -> Result<(), Interrupted> {
let mut children = Vec::new();
for constraint in split::constraints(node, conflict, self.config.splitting) {
if let Some(child) = self.child(node, constraint)? {
children.push(child);
}
}
self.stats.expanded += 1;
if self.config.bypass {
if let Some(adopted) = children.iter().find_map(|child| split::bypass(node, child)) {
self.push(adopted);
return Ok(());
}
}
for child in children {
for grandchild in Combinations::children(node, child) {
self.push(grandchild);
}
}
Ok(())
}
fn child(
&self,
node: &Node<N>,
constraint: Constraint,
) -> Result<Option<Child<N>>, Interrupted> {
let mut constraints = node.constraints.clone();
constraints.push(constraint);
let mut replanned = Vec::new();
for agent in split::affected(constraint, &node.paths) {
let set = self.replan(agent, &constraints)?;
if set.is_empty() {
return Ok(None);
}
replanned.push((agent, set));
}
Ok(Some(Child {
constraints,
replanned,
}))
}
fn replan(
&self,
agent: AgentId,
constraints: &[Constraint],
) -> Result<ParetoSet<N>, Interrupted> {
let costs = |from, to| (self.costs)(agent, from, to);
let problem = Problem {
graph: self.instance.graph(),
costs: &costs,
agent: self.instance.agents()[agent],
heuristic: &self.heuristics[agent],
low_level: self.config.low_level,
};
let set = ConstraintSet::for_agent(agent, constraints);
let paths = pareto_paths(&problem, &set, &mut || self.is_exhausted()).ok_or(Interrupted)?;
Ok(paths
.into_iter()
.map(|(path, cost)| (Rc::from(path), cost))
.collect())
}
fn push(&mut self, node: Node<N>) {
let order = self.stats.generated;
self.stats.generated += 1;
if !self.is_filtered(&node.cost) {
self.open.insert((node.cost, order), node);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::AdjacencyList;
use crate::instance::Agent;
#[test]
fn record_drops_dominated_solutions() {
let graph = AdjacencyList::undirected(2, &[(0, 1)]);
let instance =
Instance::new(graph, alloc::vec![Agent { start: 0, goal: 1 }]).expect("valid");
let costs = |_: AgentId, _: Vertex, _: Vertex| [1, 1];
let mut budget = |_: &Stats| false;
let mut search = Search::new(&instance, &costs, MoCbsConfig::default(), &mut budget);
let node = |cost: [u32; 2]| {
let path: Rc<[Vertex]> = Rc::from(alloc::vec![0, 1]);
Node::new(Vec::new(), alloc::vec![path], alloc::vec![cost], Vec::new())
};
search.record(&node([3, 3]));
search.record(&node([1, 5]));
search.record(&node([2, 2]));
let front: Vec<_> = search.front.iter().map(|plan| plan.cost).collect();
assert_eq!(front, [[1, 5], [2, 2]]);
assert!(search.is_filtered(&[2, 2]));
assert!(search.is_filtered(&[3, 4]));
assert!(!search.is_filtered(&[1, 4]));
}
}