use alloc::rc::Rc;
use alloc::vec::Vec;
use super::cardinal::Cardinality;
use super::cover::{vertex_cover_bound, weighted_cover_bound};
use super::pairs::{Pair, is_dependent, pair_cost};
use super::{CbsHeuristic, Search};
use crate::conflict::Conflict;
use crate::constraint::{Constraint, ConstraintSet};
use crate::graph::Graph;
use crate::instance::AgentId;
use crate::mdd::Mdd;
use crate::path::{Path, path_cost};
pub(super) type PairKey = (AgentId, AgentId, [usize; 2], ConstraintSet, ConstraintSet);
impl<G: Graph> Search<'_, G> {
pub(super) fn heuristic(
&self,
tree: usize,
constraints: &[Constraint],
paths: &[Path],
found: &[Conflict],
classes: &[Cardinality],
mdds: &[Option<Rc<Mdd>>],
) -> Option<u32> {
let pairs = conflicting_pairs(found, classes);
match self.config.effective_heuristic() {
CbsHeuristic::None => Some(0),
CbsHeuristic::Cg => {
let cardinal: Vec<_> = pairs
.iter()
.filter(|&&(_, cardinal)| cardinal)
.map(|&(pair, _)| pair)
.collect();
Some(vertex_cover_bound(&cardinal))
}
CbsHeuristic::Dg => {
let dependent: Vec<_> = pairs
.iter()
.filter(|&&(pair, cardinal)| cardinal || dependent(pair, mdds))
.map(|&(pair, _)| pair)
.collect();
Some(vertex_cover_bound(&dependent))
}
CbsHeuristic::Wdg => {
let weighted = pairs
.iter()
.map(|&(pair, cardinal)| {
let weight =
self.pair_weight(tree, pair, cardinal, constraints, paths, mdds)?;
Some((pair.0, pair.1, weight))
})
.collect::<Option<Vec<_>>>()?;
Some(weighted_cover_bound(&weighted))
}
}
}
fn pair_weight(
&self,
tree: usize,
pair: (AgentId, AgentId),
cardinal: bool,
constraints: &[Constraint],
paths: &[Path],
mdds: &[Option<Rc<Mdd>>],
) -> Option<u32> {
let (a, b) = pair;
let sets = [a, b].map(|agent| ConstraintSet::for_agent(agent, constraints));
let goals = [a, b].map(|agent| self.trees[tree][agent]);
let key: PairKey = (a, b, goals, sets[0].clone(), sets[1].clone());
if let Some(&weight) = self.pair_weights.borrow().get(&key) {
return weight;
}
let weight = if cardinal || dependent(pair, mdds) {
let current = path_cost(&paths[a]) + path_cost(&paths[b]);
let problem = Pair {
graph: self.graph,
agents: [a, b].map(|agent| self.agent(tree, agent)),
distances: [a, b].map(|agent| self.distances(tree, agent)),
constraints: sets,
};
pair_cost(&problem).map(|optimum| optimum.saturating_sub(current).max(1))
} else {
Some(0)
};
self.pair_weights.borrow_mut().insert(key, weight);
weight
}
}
fn conflicting_pairs(
found: &[Conflict],
classes: &[Cardinality],
) -> Vec<((AgentId, AgentId), bool)> {
let mut pairs: Vec<((AgentId, AgentId), bool)> = found
.iter()
.zip(classes)
.map(|(conflict, &class)| (conflict.agents(), class == Cardinality::Cardinal))
.collect();
pairs.sort_unstable_by_key(|&(pair, cardinal)| (pair, !cardinal));
pairs.dedup_by_key(|&mut (pair, _)| pair);
pairs
}
fn dependent((a, b): (AgentId, AgentId), mdds: &[Option<Rc<Mdd>>]) -> bool {
let mdd = |agent: AgentId| mdds[agent].as_deref().expect("MDDs of conflicting agents");
is_dependent(mdd(a), mdd(b))
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use heuristic_search::{Limits, Stats};
use proptest::prelude::*;
use crate::cbs::cardinal::cardinality;
use crate::cbs::{CbsConfig, Entry, Node, Splitting};
use crate::conflict::conflicts;
use crate::graph::{Grid, Vertex};
use crate::instance::{Agent, Instance};
use crate::path::Objective;
use crate::solution::Outcome;
const NODES: usize = 12;
fn instance() -> impl Strategy<Value = Instance<Grid>> {
(
prop::collection::vec(prop::bool::weighted(0.12), 9),
2..=3_usize,
)
.prop_filter("enough free cells", |(blocked, agents)| {
blocked.iter().filter(|&&b| !b).count() >= *agents
})
.prop_flat_map(|(blocked, agents)| {
let free: Vec<Vertex> = (0..9).filter(|&v| !blocked[v]).collect();
let starts = Just(free.clone()).prop_shuffle();
let goals = Just(free).prop_shuffle();
(Just(blocked), Just(agents), starts, goals)
})
.prop_map(|(blocked, count, starts, goals)| {
let mut grid = Grid::new(3, 3);
for vertex in (0..9).filter(|&v| blocked[v]) {
let (x, y) = grid.cell(vertex);
grid.block(x, y);
}
let agents = starts
.iter()
.zip(&goals)
.take(count)
.map(|(&start, &goal)| Agent { start, goal })
.collect();
Instance::new(grid, agents).expect("distinct starts and goals")
})
}
fn tree(instance: &Instance<Grid>, splitting: Splitting) -> Vec<Node> {
let config = CbsConfig {
splitting,
..CbsConfig::plain(Objective::SumOfCosts)
};
let mut search = Search::new(instance, config);
let Some(root) = search.root(0) else {
return Vec::new();
};
search.push(root);
let mut nodes = Vec::new();
while let Some(Entry { node, .. }) = search.open.pop() {
if nodes.len() == NODES {
break;
}
nodes.push(node.clone());
if let Some(conflict) = node.conflict {
search.expand(node, conflict);
}
}
nodes
}
fn below(instance: &Instance<Grid>, node: &Node) -> Outcome {
let mut search = Search::new(instance, CbsConfig::plain(Objective::SumOfCosts));
search.push(node.clone());
search.stats = Stats::default();
search.run_open(&mut Limits::expansions(1_000))
}
fn value(instance: &Instance<Grid>, heuristic: CbsHeuristic, node: &Node) -> Option<u32> {
let config = CbsConfig {
heuristic,
..CbsConfig::plain(Objective::SumOfCosts)
};
let search = Search::new(instance, config);
let found = conflicts(&node.paths);
let mut mdds = vec![None; node.paths.len()];
search.fill_mdds(0, &node.constraints, &node.paths, &mut mdds, &found);
let classes: Vec<Cardinality> = found.iter().map(|c| cardinality(c, &mdds)).collect();
search.heuristic(0, &node.constraints, &node.paths, &found, &classes, &mdds)
}
proptest! {
#![proptest_config(ProptestConfig { cases: 24, ..ProptestConfig::default() })]
#[test]
fn heuristics_are_admissible(instance in instance(), disjoint in any::<bool>()) {
let splitting = if disjoint { Splitting::Disjoint } else { Splitting::Standard };
for node in tree(&instance, splitting) {
let [cg, dg, wdg] = [CbsHeuristic::Cg, CbsHeuristic::Dg, CbsHeuristic::Wdg]
.map(|heuristic| value(&instance, heuristic, &node));
let below = below(&instance, &node);
let Some(wdg) = wdg else {
prop_assert!(!matches!(below, Outcome::Solved(_)), "WDG killed a solvable node");
continue;
};
let (cg, dg) = (cg.expect("CG never kills"), dg.expect("DG never kills"));
prop_assert!(cg <= dg && dg <= wdg, "CG {cg}, DG {dg}, WDG {wdg}");
if let Outcome::Solved(solution) = below {
let optimum = solution.sum_of_costs;
prop_assert!(
node.sum_of_costs + wdg <= optimum,
"cost {} + WDG {wdg} over the optimum {optimum}",
node.sum_of_costs
);
}
}
}
}
}