use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
use alloc::rc::Rc;
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Reverse;
use crate::graph::{Graph, Vertex};
use crate::instance::Agent;
use crate::path::{Path, Reservation, Time, reservations};
const FOREVER: Time = Time::MAX;
pub(super) struct Obstacles {
visits: BTreeMap<Vertex, Vec<Time>>,
parked: BTreeMap<Vertex, Time>,
swaps: BTreeSet<(Vertex, Vertex, Time)>,
}
impl Obstacles {
pub(super) fn of<'p>(paths: impl IntoIterator<Item = &'p Path>) -> Self {
let mut obstacles = Self {
visits: BTreeMap::new(),
parked: BTreeMap::new(),
swaps: BTreeSet::new(),
};
for reservation in paths.into_iter().flat_map(|path| reservations(path)) {
obstacles.add(reservation);
}
for steps in obstacles.visits.values_mut() {
steps.sort_unstable();
}
obstacles
}
fn add(&mut self, reservation: Reservation) {
match reservation {
Reservation::Visit { vertex, time } => {
self.visits.entry(vertex).or_default().push(time);
}
Reservation::Move { from, to, time } => {
self.swaps.insert((to, from, time + 1));
}
Reservation::Park { vertex, time } => {
let since = self.parked.entry(vertex).or_insert(time);
*since = (*since).min(time);
}
}
}
fn intervals(&self, vertex: Vertex) -> Vec<Interval> {
let parked = self.parked.get(&vertex).copied();
let mut dirty: Vec<Time> = self.visits.get(&vertex).cloned().unwrap_or_default();
dirty.retain(|&step| parked.is_none_or(|since| step < since));
dirty.dedup();
let mut intervals = Vec::new();
let mut at = 0;
let mut index = 0;
while index < dirty.len() {
let start = dirty[index];
let mut end = start + 1;
index += 1;
while index < dirty.len() && dirty[index] == end {
end += 1;
index += 1;
}
if at < start {
intervals.push(Interval::new(at, start, false));
}
intervals.push(Interval::new(start, end, true));
at = end;
}
match parked {
Some(since) if at < since => {
intervals.push(Interval::new(at, since, false));
intervals.push(Interval::new(since, FOREVER, true));
}
Some(_) => match intervals.last_mut() {
Some(last) if last.dirty && last.high == at => last.high = FOREVER,
_ => intervals.push(Interval::new(at, FOREVER, true)),
},
None => intervals.push(Interval::new(at, FOREVER, false)),
}
intervals
}
fn touches(&self, vertex: Vertex) -> bool {
self.visits.contains_key(&vertex) || self.parked.contains_key(&vertex)
}
fn after(&self, vertex: Vertex, time: Time) -> u32 {
let visits = self
.visits
.get(&vertex)
.map_or(0, |steps| steps.iter().filter(|&&step| step > time).count());
let parked = self.parked.get(&vertex).is_some_and(|&since| since > time);
u32::try_from(visits).unwrap_or(u32::MAX) + u32::from(parked)
}
fn clear_from(&self, vertex: Vertex) -> Time {
self.visits
.get(&vertex)
.and_then(|steps| steps.last())
.map_or(0, |&step| step + 1)
}
fn swaps(&self, from: Vertex, to: Vertex, arrival: Time) -> bool {
from != to && self.swaps.contains(&(from, to, arrival))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Interval {
low: Time,
high: Time,
dirty: bool,
}
impl Interval {
fn new(low: Time, high: Time, dirty: bool) -> Self {
Self { low, high, dirty }
}
}
#[derive(Debug, Clone)]
struct Node {
vertex: Vertex,
interval: usize,
low: Time,
high: Time,
goal: bool,
collisions: u32,
h: Time,
parent: Option<usize>,
pruned: bool,
}
impl Node {
fn identity(&self) -> (Vertex, usize, bool) {
(self.vertex, self.interval, self.goal)
}
}
pub(super) fn sipps<G: Graph>(
graph: &G,
agent: Agent,
distances: &[Option<u32>],
obstacles: &Obstacles,
) -> Option<Path> {
distances[agent.start]?;
let mut search = Search {
graph,
agent,
distances,
obstacles,
clear_from: obstacles.clear_from(agent.goal),
intervals: BTreeMap::new(),
clean: Rc::from([Interval::new(0, FOREVER, false)]),
nodes: Vec::new(),
twins: BTreeMap::new(),
open: BinaryHeap::new(),
};
search.run()
}
struct Search<'a, G> {
graph: &'a G,
agent: Agent,
distances: &'a [Option<u32>],
obstacles: &'a Obstacles,
clear_from: Time,
intervals: BTreeMap<Vertex, Rc<[Interval]>>,
clean: Rc<[Interval]>,
nodes: Vec<Node>,
twins: BTreeMap<(Vertex, usize, bool), Vec<usize>>,
open: BinaryHeap<Reverse<(u32, Time, Time, usize)>>,
}
impl<G: Graph> Search<'_, G> {
fn run(&mut self) -> Option<Path> {
let first = self.interval(self.agent.start, 0);
let root = Node {
vertex: self.agent.start,
interval: 0,
low: 0,
high: first.high,
goal: false,
collisions: u32::from(first.dirty),
h: 0,
parent: None,
pruned: false,
};
self.insert(root);
while let Some(Reverse((_, _, _, id))) = self.open.pop() {
if self.nodes[id].pruned {
continue;
}
if self.nodes[id].goal {
return Some(self.path(id));
}
if self.nodes[id].vertex == self.agent.goal {
let future = self.obstacles.after(self.agent.goal, self.nodes[id].low);
if future == 0 {
return Some(self.path(id));
}
let mut finished = self.nodes[id].clone();
finished.goal = true;
finished.collisions += future;
finished.parent = Some(id);
self.insert(finished);
}
self.expand(id);
}
None
}
fn expand(&mut self, id: usize) {
let Node {
vertex,
interval,
low,
high,
..
} = self.nodes[id];
let mut neighbors = Vec::new();
self.graph.neighbors(vertex, |next| neighbors.push(next));
for next in neighbors
.into_iter()
.filter(|&next| self.distances[next].is_some())
{
let earliest = low + 1;
let latest = high.saturating_add(1);
for (index, &safe) in self.intervals_of(next).iter().enumerate() {
let arrival = earliest.max(safe.low);
if arrival < safe.high.min(latest) {
self.arrive(id, next, index, arrival, safe, latest);
}
}
}
let next = interval + 1;
let intervals = self.intervals_of(vertex);
if let Some(&safe) = intervals.get(next) {
if safe.low == high {
self.arrive(id, vertex, next, safe.low, safe, FOREVER);
}
}
}
fn arrive(
&mut self,
parent: usize,
vertex: Vertex,
index: usize,
arrival: Time,
safe: Interval,
latest: Time,
) {
let from = self.nodes[parent].vertex;
let collisions = self.nodes[parent].collisions + u32::from(safe.dirty);
let end = safe.high.min(latest);
let clean = (arrival..end).find(|&time| !self.obstacles.swaps(from, vertex, time));
let node = |low: Time, high: Time, collisions: u32| Node {
vertex,
interval: index,
low,
high,
goal: false,
collisions,
h: 0,
parent: Some(parent),
pruned: false,
};
match clean {
Some(clean) if clean > arrival => {
self.insert(node(arrival, clean, collisions + 1));
self.insert(node(clean, safe.high, collisions));
}
Some(_) => self.insert(node(arrival, safe.high, collisions)),
None => self.insert(node(arrival, safe.high, collisions + 1)),
}
}
fn insert(&mut self, mut node: Node) {
node.h = self.heuristic(&node);
let identity = node.identity();
let mut twins = self.twins.remove(&identity).unwrap_or_default();
for &twin in &twins {
let other = &self.nodes[twin];
if other.pruned {
continue;
}
if other.low <= node.low && other.collisions <= node.collisions {
self.twins.insert(identity, twins);
return;
}
if node.low <= other.low && node.collisions <= other.collisions {
self.nodes[twin].pruned = true;
} else if node.low < other.high && other.low < node.high {
if node.low < other.low {
node.high = other.low;
} else {
self.nodes[twin].high = node.low;
}
}
}
let id = self.nodes.len();
let key = (node.collisions, node.low + node.h, node.h, id);
self.nodes.push(node);
twins.retain(|&twin| !self.nodes[twin].pruned);
twins.push(id);
self.twins.insert(identity, twins);
self.open.push(Reverse(key));
}
fn heuristic(&self, node: &Node) -> Time {
if node.goal {
return 0;
}
let distance = self.distances[node.vertex].expect("only vertices that reach the goal");
if node.collisions == 0 {
distance.max(self.clear_from.saturating_sub(node.low))
} else {
distance
}
}
fn interval(&mut self, vertex: Vertex, index: usize) -> Interval {
self.intervals_of(vertex)[index]
}
fn intervals_of(&mut self, vertex: Vertex) -> Rc<[Interval]> {
let obstacles = self.obstacles;
if !obstacles.touches(vertex) {
return Rc::clone(&self.clean);
}
Rc::clone(
self.intervals
.entry(vertex)
.or_insert_with(|| obstacles.intervals(vertex).into()),
)
}
fn path(&self, id: usize) -> Path {
let mut chain = Vec::new();
let mut at = Some(id);
while let Some(id) = at {
chain.push(id);
at = self.nodes[id].parent;
}
chain.reverse();
let mut path = vec![self.agent.start];
for &id in &chain[1..] {
let Node { vertex, low, .. } = self.nodes[id];
let arrival = usize::try_from(low).expect("steps fit in usize");
while path.len() < arrival {
path.push(*path.last().expect("non-empty"));
}
if path.len() == arrival {
path.push(vertex);
}
}
path
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use crate::conflict_table::ConflictTable;
use crate::graph::{Grid, distances_to};
use crate::lns2::low_level::fewest_collisions;
use crate::path::path_cost;
fn collisions(path: &[Vertex], table: &ConflictTable) -> u32 {
let moves: u32 = path
.windows(2)
.enumerate()
.map(|(time, step)| table.count(step[0], step[1], Time::try_from(time).expect("short")))
.sum();
let goal = *path.last().expect("non-empty");
moves + table.after(goal, path_cost(path))
}
fn case() -> impl Strategy<Value = (Grid, Vec<Path>, Agent)> {
let blocked = prop::collection::vec(0_usize..16, 0..=3);
let walks = prop::collection::vec(
(0_usize..16, prop::collection::vec(0_usize..5, 0..10)),
0..=3,
);
(blocked, walks, 0_usize..16, 0_usize..16).prop_filter_map(
"free, distinct starts and ends",
|(walls, walks, start, goal)| {
let mut grid = Grid::new(4, 4);
for &wall in &walls {
let (x, y) = grid.cell(wall);
grid.block(x, y);
}
let free = |vertex: Vertex| !walls.contains(&vertex);
if !free(start)
|| !free(goal)
|| walks.iter().any(|(from, _)| *from == start || !free(*from))
{
return None;
}
let paths: Vec<Path> = walks
.iter()
.map(|(from, turns)| walk(&grid, *from, turns))
.collect();
let ends: Vec<Vertex> = paths.iter().map(|path| path[path.len() - 1]).collect();
let distinct = ends
.iter()
.enumerate()
.all(|(i, end)| *end != goal && !ends[..i].contains(end));
distinct.then_some((grid, paths, Agent { start, goal }))
},
)
}
fn walk(grid: &Grid, from: Vertex, turns: &[usize]) -> Path {
let mut path = vec![from];
for &turn in turns {
let here = *path.last().expect("non-empty");
let mut neighbors = Vec::new();
grid.neighbors(here, |next| neighbors.push(next));
let next = turn
.checked_sub(1)
.and_then(|index| neighbors.get(index))
.copied()
.unwrap_or(here);
path.push(next);
}
path
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(512))]
#[test]
fn agrees_with_space_time_astar((grid, others, agent) in case()) {
let distances = distances_to(&grid, agent.goal);
let table = ConflictTable::of(&others);
let last = others.iter().map(Vec::len).max().unwrap_or(0);
let exact = fewest_collisions(&grid, agent, &distances, &table, Time::try_from(last).expect("short"));
let found = sipps(&grid, agent, &distances, &Obstacles::of(&others));
prop_assert_eq!(found.is_some(), exact.is_some());
let (Some(found), Some(exact)) = (found, exact) else {
return Ok(());
};
prop_assert_eq!(found.first(), Some(&agent.start));
prop_assert_eq!(found.last(), Some(&agent.goal));
for step in found.windows(2) {
let ((x0, y0), (x1, y1)) = (grid.cell(step[0]), grid.cell(step[1]));
prop_assert!(x0.abs_diff(x1) + y0.abs_diff(y1) <= 1, "a jump in {found:?}");
prop_assert!(step[0] == step[1] || !grid.is_blocked(step[1]));
}
let (best, got) = (collisions(&exact, &table), collisions(&found, &table));
prop_assert!(got >= best);
if best == 0 {
prop_assert_eq!(got, 0, "{:?} against {:?}", found, exact);
prop_assert_eq!(path_cost(&found), path_cost(&exact));
}
}
}
#[test]
fn builds_safe_intervals() {
let obstacles = Obstacles::of(&[vec![9, 9, 5, 5, 9], vec![9, 9, 9, 9, 9, 9, 5, 9, 5]]);
let intervals = obstacles.intervals(5);
assert_eq!(
intervals,
[
Interval::new(0, 2, false),
Interval::new(2, 4, true),
Interval::new(4, 6, false),
Interval::new(6, 7, true),
Interval::new(7, 8, false),
Interval::new(8, FOREVER, true),
]
);
assert_eq!(obstacles.intervals(4), [Interval::new(0, FOREVER, false)]);
}
}