use alloc::collections::{BTreeMap, BTreeSet};
use alloc::rc::Rc;
use alloc::vec::Vec;
use heuristic_search::{Budget, Stats};
use crate::constraint::ConstraintSet;
use crate::graph::Graph;
use crate::instance::{AgentId, Instance};
use crate::low_level::distance_tables;
use crate::mdd::{Mdd, joint_paths};
use crate::path::{Objective, Path, Time};
use crate::solution::{MapfResult, Outcome, Solution};
pub fn icts<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()),
mdds: BTreeMap::new(),
stats: Stats::default(),
};
let outcome = search.run(&mut budget);
MapfResult {
outcome,
stats: search.stats,
}
}
struct Search<'a, G> {
instance: &'a Instance<G>,
objective: Objective,
distances: Vec<Vec<Option<u32>>>,
mdds: BTreeMap<(AgentId, Time), Rc<Mdd>>,
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;
};
let mut open = BTreeSet::from([(root.iter().sum::<u32>(), root.clone())]);
let mut seen = BTreeSet::from([root]);
self.stats.generated += 1;
while let Some((_, costs)) = open.pop_first() {
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.stats.expanded += 1;
if let Some(paths) = self.evaluate(&costs) {
return Outcome::Solved(Solution::new(paths));
}
for child in self.children(&costs) {
if seen.insert(child.clone()) {
self.stats.generated += 1;
open.insert((child.iter().sum(), child));
}
}
}
unreachable!("the cost tree is infinite")
}
fn children(&self, costs: &[Time]) -> Vec<Vec<Time>> {
match self.objective {
Objective::SumOfCosts => (0..costs.len())
.map(|agent| {
let mut child = costs.to_vec();
child[agent] += 1;
child
})
.collect(),
Objective::Makespan => Vec::from([costs.iter().map(|cost| cost + 1).collect()]),
}
}
fn root(&self) -> Option<Vec<Time>> {
let alone = self.individual_costs()?;
Some(match self.objective {
Objective::SumOfCosts => alone,
Objective::Makespan => {
let makespan = alone.iter().copied().max().unwrap_or(0);
alloc::vec![makespan; alone.len()]
}
})
}
fn individual_costs(&self) -> Option<Vec<Time>> {
self.instance
.agents()
.iter()
.zip(&self.distances)
.map(|(agent, distances)| distances[agent.start])
.collect()
}
fn evaluate(&mut self, costs: &[Time]) -> Option<Vec<Path>> {
let mdds: Vec<Rc<Mdd>> = (0..costs.len())
.map(|agent| self.mdd(agent, costs[agent]))
.collect();
for (i, a) in mdds.iter().enumerate() {
for b in &mdds[i + 1..] {
joint_paths(&[a, b])?;
}
}
let all: Vec<&Mdd> = mdds.iter().map(Rc::as_ref).collect();
joint_paths(&all)
}
fn mdd(&mut self, agent: AgentId, cost: Time) -> Rc<Mdd> {
let (instance, distances) = (self.instance, &self.distances);
Rc::clone(self.mdds.entry((agent, cost)).or_insert_with(|| {
let mdd = Mdd::build(
instance.graph(),
instance.agents()[agent],
&ConstraintSet::new(),
&distances[agent],
cost,
)
.expect("every cost from the individual optimum on has paths");
Rc::new(mdd)
}))
}
}