use alloc::vec;
use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Cost, CostExt, Heuristic};
use crate::bidirectional::BidirectionalGraph;
use crate::cost::Extended;
use crate::open_list::OpenList;
use crate::problem::{Successors, collect_predecessors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum LandmarkSelection {
#[default]
Farthest,
Avoidance,
}
#[derive(Debug, Clone)]
pub struct Landmarks<S, C> {
table: StateTable<S>,
picked: Vec<usize>,
rows: Vec<Distances<C>>,
}
#[derive(Debug, Clone, Copy)]
struct Distances<C> {
from_landmark: Option<C>,
to_landmark: Option<C>,
}
impl<C> Distances<C> {
const NONE: Self = Self {
from_landmark: None,
to_landmark: None,
};
}
impl<S, C> Landmarks<S, C>
where
S: Clone + Hash + Eq,
C: CostExt,
{
pub fn build<G>(graph: &G, start: S, count: usize, selection: LandmarkSelection) -> Self
where
G: BidirectionalGraph + Successors<State = S, Cost = C>,
{
let mut builder = Builder::new(graph, start);
while builder.landmarks.len() < count {
let next = match selection {
LandmarkSelection::Farthest => builder.farthest(),
LandmarkSelection::Avoidance => builder.avoidance().or_else(|| builder.farthest()),
};
let Some(next) = next else {
break;
};
builder.add_landmark(next);
}
builder.finish()
}
pub fn landmarks(&self) -> impl ExactSizeIterator<Item = &S> {
self.picked.iter().map(|&id| &self.table.states[id])
}
#[must_use]
pub fn lower_bound(&self, from: &S, to: &S) -> Option<C> {
self.bound(
self.table.find(from),
self.table.find(to),
0..self.picked.len(),
)
}
#[must_use]
pub fn heuristic_to(&self, target: &S) -> LandmarkHeuristic<'_, S, C> {
LandmarkHeuristic::new(self, self.table.find(target), Toward::Endpoint)
}
#[must_use]
pub fn heuristic_from(&self, source: &S) -> LandmarkHeuristic<'_, S, C> {
LandmarkHeuristic::new(self, self.table.find(source), Toward::State)
}
fn distances(&self, id: Option<usize>, l: usize) -> Distances<C> {
id.map_or(Distances::NONE, |id| self.rows[id * self.picked.len() + l])
}
fn bound(
&self,
from: Option<usize>,
to: Option<usize>,
active: impl IntoIterator<Item = usize>,
) -> Option<C> {
bound(
active
.into_iter()
.map(|l| (self.distances(from, l), self.distances(to, l))),
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Toward {
Endpoint,
State,
}
#[derive(Debug, Clone)]
pub struct LandmarkHeuristic<'a, S, C> {
landmarks: &'a Landmarks<S, C>,
endpoint: Option<usize>,
toward: Toward,
active: Vec<usize>,
}
impl<'a, S, C> LandmarkHeuristic<'a, S, C>
where
S: Clone + Hash + Eq,
C: CostExt,
{
fn new(landmarks: &'a Landmarks<S, C>, endpoint: Option<usize>, toward: Toward) -> Self {
Self {
landmarks,
endpoint,
toward,
active: (0..landmarks.picked.len()).collect(),
}
}
#[must_use]
pub fn active(mut self, other: &S, count: usize) -> Self {
let other = self.landmarks.table.find(other);
let (from, to) = self.ordered(other);
let bound_of = |l: usize| {
landmark_bound(
self.landmarks.distances(from, l),
self.landmarks.distances(to, l),
)
};
let mut ranked: Vec<(Extended<C>, usize)> = self
.active
.iter()
.map(|&l| (bound_of(l).map_or(Extended::Infinite, Extended::Finite), l))
.collect();
ranked.sort_by_key(|&(bound, _)| core::cmp::Reverse(bound));
self.active = ranked.into_iter().take(count).map(|(_, l)| l).collect();
self
}
fn ordered(&self, state: Option<usize>) -> (Option<usize>, Option<usize>) {
match self.toward {
Toward::Endpoint => (state, self.endpoint),
Toward::State => (self.endpoint, state),
}
}
}
impl<S, C> Heuristic<S, C> for LandmarkHeuristic<'_, S, C>
where
S: Clone + Hash + Eq,
C: CostExt,
{
fn estimate(&mut self, state: &S) -> Option<C> {
let (from, to) = self.ordered(self.landmarks.table.find(state));
self.landmarks.bound(from, to, self.active.iter().copied())
}
}
fn bound<C: CostExt>(pairs: impl IntoIterator<Item = (Distances<C>, Distances<C>)>) -> Option<C> {
pairs.into_iter().try_fold(C::ZERO, |best, (from, to)| {
landmark_bound(from, to).map(|bound| best.max(bound))
})
}
fn landmark_bound<C: CostExt>(u: Distances<C>, w: Distances<C>) -> Option<C> {
let mut best = C::ZERO;
match (u.from_landmark, w.from_landmark) {
(Some(lu), Some(lw)) => best = best.max(lw.saturating_sub(lu)),
(Some(_), None) => return None,
(None, _) => {}
}
match (u.to_landmark, w.to_landmark) {
(Some(ul), Some(wl)) => best = best.max(ul.saturating_sub(wl)),
(None, Some(_)) => return None,
(_, None) => {}
}
Some(best)
}
#[derive(Debug, Clone)]
struct StateTable<S> {
states: Vec<S>,
index: HashTable<usize>,
hasher: DefaultHashBuilder,
}
impl<S: Hash + Eq> StateTable<S> {
fn new() -> Self {
Self {
states: Vec::new(),
index: HashTable::new(),
hasher: DefaultHashBuilder::default(),
}
}
fn find(&self, state: &S) -> Option<usize> {
let hash = self.hasher.hash_one(state);
self.index
.find(hash, |&id| self.states[id] == *state)
.copied()
}
fn intern(&mut self, state: &S) -> usize
where
S: Clone,
{
if let Some(id) = self.find(state) {
return id;
}
let id = self.states.len();
let hash = self.hasher.hash_one(state);
let (states, hasher) = (&self.states, &self.hasher);
self.index
.insert_unique(hash, id, |&other| hasher.hash_one(&states[other]));
self.states.push(state.clone());
id
}
}
struct Tree<S, C> {
space: SearchSpace<S, (), C>,
order: Vec<NodeId>,
ids: Vec<usize>,
}
fn settle<G, S, C>(graph: &G, source: S, backward: bool) -> Tree<S, C>
where
G: BidirectionalGraph + Successors<State = S, Cost = C>,
S: Clone + Hash + Eq,
C: Cost,
{
let (mut space, _) = SearchSpace::seed([source], &|_: &S| false);
let mut open: OpenList<C> = OpenList::new();
open.push(0, space.g(0), space.g(0));
let mut order = Vec::new();
let mut buffer = Vec::new();
while let Some((node, _)) = open.pop_where(|id, g| g.cmp(&space.g(id)).is_eq()) {
order.push(node);
if backward {
collect_predecessors(graph, space.state(node), &mut buffer);
} else {
collect_successors(graph, space.state(node), &mut buffer);
}
for (_, state, cost) in buffer.drain(..) {
match space.reach(state, node, (), cost, true) {
Reach::New(id) | Reach::Improved(id) => open.push(id, space.g(id), space.g(id)),
Reach::Stale => {}
}
}
}
Tree {
space,
order,
ids: Vec::new(),
}
}
struct Builder<'a, G, S, C> {
graph: &'a G,
table: StateTable<S>,
landmarks: Vec<usize>,
columns: Vec<Vec<Distances<C>>>,
nearest: Vec<Extended<C>>,
is_landmark: Vec<bool>,
start_tree: Option<Tree<S, C>>,
}
impl<'a, G, S, C> Builder<'a, G, S, C>
where
G: BidirectionalGraph + Successors<State = S, Cost = C>,
S: Clone + Hash + Eq,
C: CostExt,
{
fn new(graph: &'a G, start: S) -> Self {
let mut builder = Self {
graph,
table: StateTable::new(),
landmarks: Vec::new(),
columns: Vec::new(),
nearest: Vec::new(),
is_landmark: Vec::new(),
start_tree: None,
};
let (forward, backward) = builder.explore(start);
let column = builder.column(&forward, &backward);
builder.nearest = column.iter().map(round_trip).collect();
builder.start_tree = Some(forward);
builder
}
fn explore(&mut self, source: S) -> (Tree<S, C>, Tree<S, C>) {
let mut forward = settle(self.graph, source.clone(), false);
let mut backward = settle(self.graph, source, true);
for tree in [&mut forward, &mut backward] {
tree.ids = (0..tree.space.len())
.map(|node| self.table.intern(tree.space.state(node)))
.collect();
}
let len = self.table.states.len();
self.nearest.resize(len, Extended::Infinite);
self.is_landmark.resize(len, false);
(forward, backward)
}
fn column(&self, forward: &Tree<S, C>, backward: &Tree<S, C>) -> Vec<Distances<C>> {
let mut column = vec![Distances::NONE; self.table.states.len()];
for node in 0..forward.space.len() {
column[forward.ids[node]].from_landmark = Some(forward.space.g(node));
}
for node in 0..backward.space.len() {
column[backward.ids[node]].to_landmark = Some(backward.space.g(node));
}
column
}
fn add_landmark(&mut self, id: usize) {
let (forward, backward) = self.explore(self.table.states[id].clone());
let column = self.column(&forward, &backward);
let first = self.landmarks.is_empty();
for (nearest, distances) in self.nearest.iter_mut().zip(&column) {
let trip = round_trip(distances);
*nearest = if first { trip } else { (*nearest).min(trip) };
}
self.is_landmark[id] = true;
self.landmarks.push(id);
self.columns.push(column);
}
fn farthest(&self) -> Option<usize> {
let mut best: Option<usize> = None;
for id in (0..self.nearest.len()).filter(|&id| !self.is_landmark[id]) {
if best.is_none_or(|best| self.nearest[id] > self.nearest[best]) {
best = Some(id);
}
}
best
}
fn avoidance(&self) -> Option<usize> {
let tree = self.start_tree.as_ref()?;
let root = tree.ids[0];
let len = tree.space.len();
let mut size = vec![C::ZERO; len];
let mut has_landmark = vec![false; len];
let mut heaviest_child: Vec<Option<NodeId>> = vec![None; len];
for &node in tree.order.iter().rev() {
let id = tree.ids[node];
has_landmark[node] |= self.is_landmark[id];
if has_landmark[node] {
size[node] = C::ZERO;
} else {
let bound = self.bound(root, id).unwrap_or(C::ZERO);
let weight = tree.space.g(node).saturating_sub(bound);
size[node] = size[node].saturating_add(weight);
}
if let Some((parent, (), _)) = tree.space.parent(node) {
has_landmark[parent] |= has_landmark[node];
size[parent] = size[parent].saturating_add(size[node]);
if heaviest_child[parent].is_none_or(|child| size[node] > size[child]) {
heaviest_child[parent] = Some(node);
}
}
}
let mut node = (0..len).fold(None, |best: Option<NodeId>, node| match best {
Some(best) if size[best] >= size[node] => Some(best),
_ => Some(node),
})?;
if size[node] == C::ZERO {
return None;
}
while let Some(child) = heaviest_child[node] {
node = child;
}
Some(tree.ids[node])
}
fn bound(&self, from: usize, to: usize) -> Option<C> {
let at =
|column: &[Distances<C>], id: usize| column.get(id).copied().unwrap_or(Distances::NONE);
bound(
self.columns
.iter()
.map(|column| (at(column, from), at(column, to))),
)
}
fn finish(self) -> Landmarks<S, C> {
let mut rows = Vec::with_capacity(self.table.states.len() * self.landmarks.len());
for id in 0..self.table.states.len() {
for column in &self.columns {
rows.push(column.get(id).copied().unwrap_or(Distances::NONE));
}
}
Landmarks {
table: self.table,
picked: self.landmarks,
rows,
}
}
}
fn round_trip<C: Cost>(distances: &Distances<C>) -> Extended<C> {
match (distances.from_landmark, distances.to_landmark) {
(Some(from), Some(to)) => Extended::Finite(from.saturating_add(to)),
_ => Extended::Infinite,
}
}