use alloc::collections::BTreeSet;
use alloc::vec;
use alloc::vec::Vec;
use heuristic_search::{Budget, Stats};
use crate::conflict::{Conflict, first_conflict};
use crate::constraint::{Constraint, ConstraintSet};
use crate::graph::{Graph, Vertex};
use crate::instance::{AgentId, Instance};
use crate::low_level::{distance_tables, plan};
use crate::path::{Objective, Path, Time, makespan, sum_of_costs};
use crate::solution::{MapfResult, Outcome, Solution};
pub fn pbs<G: Graph>(
instance: &Instance<G>,
objective: Objective,
mut budget: impl Budget<Stats>,
) -> MapfResult {
let mut search = Search {
instance,
objective,
distances: distance_tables(instance.graph(), instance.agents()),
stats: Stats::default(),
};
let outcome = search.run(&mut budget);
MapfResult {
outcome,
stats: search.stats,
}
}
#[derive(Debug, Clone)]
struct Node {
higher: Vec<BTreeSet<AgentId>>,
paths: Vec<Path>,
cost: (u32, u32),
}
struct Search<'a, G> {
instance: &'a Instance<G>,
objective: Objective,
distances: Vec<Vec<Option<u32>>>,
stats: Stats,
}
impl<G: Graph> Search<'_, G> {
fn run(&mut self, budget: &mut impl Budget<Stats>) -> Outcome {
let Some(root) = self.root() else {
return Outcome::Unsolvable;
};
self.stats.generated += 1;
let mut stack = Vec::from([root]);
while let Some(node) = stack.pop() {
let Some(conflict) = first_conflict(&node.paths) else {
return Outcome::Solved(Solution::new(node.paths));
};
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.stats.expanded += 1;
let mut children = self.children(&node, conflict);
self.stats.generated += children.len() as u64;
children.sort_by_key(|child| core::cmp::Reverse(child.cost));
stack.extend(children);
}
Outcome::Exhausted
}
fn root(&self) -> Option<Node> {
let count = self.instance.agents().len();
let paths = (0..count)
.map(|agent| self.replan(agent, &[]))
.collect::<Option<Vec<_>>>()?;
Some(Node {
higher: vec![BTreeSet::new(); count],
cost: self.cost(&paths),
paths,
})
}
fn children(&self, node: &Node, conflict: Conflict) -> Vec<Node> {
let (a, b) = conflict.agents();
[(a, b), (b, a)]
.into_iter()
.filter_map(|(high, low)| self.child(node, high, low))
.collect()
}
fn child(&self, node: &Node, high: AgentId, low: AgentId) -> Option<Node> {
if node.higher[high].contains(&low) {
return None;
}
let mut child = node.clone();
let above: Vec<AgentId> = node.higher[high].iter().copied().chain([high]).collect();
let affected = below_or_equal(&node.higher, low);
for &agent in &affected {
child.higher[agent].extend(above.iter().copied());
}
self.replan_below(&mut child, low, affected)?;
child.cost = self.cost(&child.paths);
Some(child)
}
fn replan_below(
&self,
node: &mut Node,
low: AgentId,
mut affected: Vec<AgentId>,
) -> Option<()> {
affected.sort_by_key(|&agent| node.higher[agent].len());
for agent in affected {
let higher: Vec<&Path> = node.higher[agent].iter().map(|&h| &node.paths[h]).collect();
let collides = higher
.iter()
.any(|path| first_conflict(&[path.as_slice(), &node.paths[agent]]).is_some());
if agent == low || collides {
node.paths[agent] = self.replan(agent, &higher)?;
}
}
Some(())
}
fn cost(&self, paths: &[Path]) -> (u32, u32) {
let (soc, makespan) = (sum_of_costs(paths), makespan(paths));
match self.objective {
Objective::SumOfCosts => (soc, makespan),
Objective::Makespan => (makespan, soc),
}
}
fn replan(&self, agent: AgentId, higher: &[&Path]) -> Option<Path> {
let mut constraints = ConstraintSet::new();
for path in higher {
avoid(&mut constraints, agent, path);
}
plan(
self.instance.graph(),
self.instance.agents()[agent],
&constraints,
&self.distances[agent],
)
}
}
fn below_or_equal(higher: &[BTreeSet<AgentId>], low: AgentId) -> Vec<AgentId> {
(0..higher.len())
.filter(|&agent| agent == low || higher[agent].contains(&low))
.collect()
}
fn avoid(constraints: &mut ConstraintSet, agent: AgentId, path: &[Vertex]) {
let last = path.len() - 1;
let time = |index: usize| Time::try_from(index).expect("path lengths fit in u32");
for (index, &vertex) in path[..last].iter().enumerate() {
constraints.insert(&Constraint::Vertex {
agent,
vertex,
time: time(index),
});
}
for (index, step) in path.windows(2).enumerate() {
if step[0] != step[1] {
constraints.insert(&Constraint::Edge {
agent,
from: step[1],
to: step[0],
time: time(index),
});
}
}
constraints.block_from(path[last], time(last));
}