use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
use heuristic_search::{Budget, Stats};
use super::planner::Planner;
use super::state::{Choice, Key};
use crate::graph::{Graph, Vertex};
use crate::instance::{AgentId, Instance};
use crate::path::Time;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct LimitReached;
pub(super) struct Context<'a, G> {
pub(super) instance: &'a Instance<G>,
pub(super) recursive: bool,
pub(super) decompose: bool,
pub(super) deadline: Option<Time>,
pub(super) distances: Vec<Vec<Option<u32>>>,
pub(super) policy: Vec<Vec<Option<Vertex>>>,
pub(super) planners: BTreeMap<Vec<AgentId>, Planner>,
pub(super) stats: Stats,
}
impl<G: Graph> Context<'_, G> {
pub(super) fn group_step(
&mut self,
group: &[AgentId],
key: Key,
budget: &mut impl Budget<Stats>,
) -> Result<Option<Key>, LimitReached> {
if key.is_goal() {
return Ok(Some(Key::standard(self.next_time(key.time), key.base)));
}
let mut planner = self
.planners
.remove(group)
.unwrap_or_else(|| Planner::new(group.to_vec()));
let step = planner.policy(self, key, budget);
self.planners.insert(group.to_vec(), planner);
step
}
pub(super) fn next_time(&self, time: Time) -> Time {
if self.deadline.is_some() { time + 1 } else { 0 }
}
pub(super) fn choices(
&self,
(here, finished): (Vertex, bool),
agent: AgentId,
branch: bool,
time: Time,
) -> Vec<Choice> {
let at_goal = here == self.instance.agents()[agent].goal;
if finished || (at_goal && !branch) {
return vec![Choice::finish(here)];
}
if !branch {
let next = self.policy[agent][here].expect("agents stay where the goal is reachable");
return vec![Choice::move_to(next)];
}
let next_time = self.next_time(time);
let mut choices = Vec::new();
let mut consider = |next: Vertex| {
if self.in_time(agent, (next, false), next_time) {
choices.push(Choice::move_to(next));
}
};
consider(here);
self.instance.graph().neighbors(here, consider);
if at_goal {
choices.push(Choice::finish(here));
}
choices
}
pub(super) fn in_time(
&self,
agent: AgentId,
(vertex, finished): (Vertex, bool),
time: Time,
) -> bool {
if finished {
return true;
}
self.distances[agent][vertex].is_some_and(|distance| {
self.deadline
.is_none_or(|deadline| time + distance <= deadline)
})
}
pub(super) fn heuristic(&self, agents: &[AgentId], key: &Key) -> Option<u32> {
let moved = key.moved.len();
let next_time = self.next_time(key.time);
agents
.iter()
.zip(key.positions())
.enumerate()
.try_fold(0, |sum, (index, (&agent, at))| {
let time = if index < moved { next_time } else { key.time };
if !self.in_time(agent, at, time) {
return None;
}
Some(
sum + if at.1 {
0
} else {
self.distances[agent][at.0]?
},
)
})
}
}