use heuristic_search::{Limits, Successors, a_star, heuristic_fn};
use search_core::Lexicographic;
use crate::conflict_table::ConflictTable;
use crate::graph::{Graph, Vertex};
use crate::instance::Agent;
use crate::path::{Path, Time, trim_trailing_waits};
type State = (Vertex, Time, bool);
type Cost = Lexicographic<u32, u32>;
pub(super) fn fewest_collisions<G: Graph>(
graph: &G,
agent: Agent,
distances: &[Option<u32>],
table: &ConflictTable,
last: Time,
) -> Option<Path> {
distances[agent.start]?;
let vertices = Time::try_from(graph.vertex_count()).unwrap_or(Time::MAX);
let space = Soft {
graph,
goal: agent.goal,
table,
horizon: last.saturating_add(vertices),
};
let goal = |&(_, _, finished): &State| finished;
let heuristic = heuristic_fn(|&(vertex, _, finished): &State| {
let steps = if finished { 0 } else { distances[vertex]? };
Some(Lexicographic {
primary: 0,
secondary: steps,
})
});
let result = a_star(
&space,
(agent.start, 0, false),
&goal,
heuristic,
Limits::NONE,
);
let solution = result.into_solution()?;
let mut path: Path = solution
.states
.into_iter()
.filter(|&(_, _, finished)| !finished)
.map(|(vertex, _, _)| vertex)
.collect();
trim_trailing_waits(&mut path);
Some(path)
}
struct Soft<'a, G> {
graph: &'a G,
goal: Vertex,
table: &'a ConflictTable,
horizon: Time,
}
impl<G: Graph> Successors for Soft<'_, G> {
type State = State;
type Action = ();
type Cost = Cost;
fn successors(&self, &(vertex, time, finished): &State, mut emit: impl FnMut((), State, Cost)) {
if finished {
return;
}
if vertex == self.goal {
let cost = Lexicographic {
primary: self.table.after(vertex, time),
secondary: 0,
};
emit((), (vertex, time, true), cost);
}
if time >= self.horizon {
return;
}
let mut step = |next: Vertex| {
let cost = Lexicographic {
primary: self.table.count(vertex, next, time),
secondary: 1,
};
emit((), (next, time + 1, false), cost);
};
step(vertex);
self.graph.neighbors(vertex, step);
}
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::vec;
use alloc::vec::Vec;
use crate::graph::{Grid, distances_to};
fn plan(grid: &Grid, agent: Agent, others: &[Path]) -> Option<Path> {
let table = ConflictTable::of(others);
let last = others.iter().map(Vec::len).max().unwrap_or(0);
let last = Time::try_from(last).expect("short paths");
fewest_collisions(grid, agent, &distances_to(grid, agent.goal), &table, last)
}
#[test]
fn passes_a_parked_agent_when_it_must() {
let grid = Grid::parse(&["...", ".@."]);
let path = plan(&grid, Agent { start: 3, goal: 5 }, &[vec![1]]).expect("reachable");
assert_eq!(path, [3, 0, 1, 2, 5]);
}
#[test]
fn detours_around_a_parked_agent() {
let grid = Grid::new(3, 2);
let path = plan(&grid, Agent { start: 0, goal: 2 }, &[vec![1]]).expect("reachable");
assert_eq!(path, [0, 3, 4, 5, 2]);
}
#[test]
fn waits_for_a_passing_agent() {
let grid = Grid::new(3, 2);
let other = vec![2, 1, 0, 3];
let path = plan(
&grid,
Agent { start: 4, goal: 1 },
core::slice::from_ref(&other),
)
.expect("reachable");
assert_eq!(
crate::conflict::first_conflict(&[path.clone(), other]),
None
);
assert_eq!(path.first(), Some(&4));
assert_eq!(path.last(), Some(&1));
}
#[test]
fn finishing_counts_later_visits() {
let grid = Grid::new(3, 1);
let path = plan(&grid, Agent { start: 0, goal: 1 }, &[vec![2, 2, 1, 0]]);
assert!(path.is_some_and(|path| path.last() == Some(&1)));
}
#[test]
fn unreachable_goal_has_no_path() {
let grid = Grid::parse(&[".@."]);
assert_eq!(plan(&grid, Agent { start: 0, goal: 2 }, &[]), None);
}
}