mod query;
use alloc::vec::Vec;
use core::hash::Hash;
use hashbrown::HashMap;
use search_core::{Budget, Cost, heuristic_fn};
pub use query::{hierarchical_a_star, hierarchical_a_star_multi};
#[cfg(feature = "parallel")]
pub use query::{hierarchical_a_star_par, hierarchical_a_star_par_multi};
use crate::best_first::{GraphResult, a_star};
use crate::grid::{EightConnected, GridCell, Octile, UniformGrid, is_open};
use crate::outcome::Stats;
use crate::problem::Successors;
pub trait Regions<S> {
fn region(&self, state: &S) -> usize;
}
impl<S, F: Fn(&S) -> usize> Regions<S> for F {
fn region(&self, state: &S) -> usize {
self(state)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GridClusters {
size: usize,
columns: usize,
}
impl GridClusters {
#[must_use]
pub const fn size(&self) -> usize {
self.size
}
}
impl Regions<GridCell> for GridClusters {
fn region(&self, &(x, y): &GridCell) -> usize {
(y / self.size) * self.columns + x / self.size
}
}
#[derive(Debug, Clone)]
pub struct Hierarchy<S, C, R> {
regions: R,
nodes: Vec<S>,
index: HashMap<S, usize>,
members: HashMap<usize, Vec<usize>>,
edges: Vec<Vec<(usize, C)>>,
}
impl<S, C, R> Hierarchy<S, C, R>
where
S: Clone + Hash + Eq,
C: Cost,
R: Regions<S>,
{
pub fn new<G, D>(
graph: &G,
regions: R,
states: impl IntoIterator<Item = S>,
distance: D,
) -> Self
where
G: Successors<State = S, Cost = C>,
G::Action: Clone,
D: Fn(&S, &S) -> C,
{
let mut entrances = Vec::new();
for state in states {
let region = regions.region(&state);
let before = entrances.len();
graph.successors(&state, |_, next, _| {
if regions.region(&next) != region {
entrances.push(next);
}
});
if entrances.len() > before {
entrances.push(state);
}
}
Self::from_entrances(graph, regions, entrances, &distance)
}
fn from_entrances<G, D>(graph: &G, regions: R, entrances: Vec<S>, distance: &D) -> Self
where
G: Successors<State = S, Cost = C>,
G::Action: Clone,
D: Fn(&S, &S) -> C,
{
let mut hierarchy = Self {
regions,
nodes: Vec::new(),
index: HashMap::new(),
members: HashMap::new(),
edges: Vec::new(),
};
for state in entrances {
if !hierarchy.index.contains_key(&state) {
let id = hierarchy.nodes.len();
let region = hierarchy.regions.region(&state);
hierarchy.members.entry(region).or_default().push(id);
hierarchy.index.insert(state.clone(), id);
hierarchy.nodes.push(state);
}
}
for from in 0..hierarchy.nodes.len() {
let edges = hierarchy.edges_from(graph, from, distance);
hierarchy.edges.push(edges);
}
hierarchy
}
fn edges_from<G, D>(&self, graph: &G, from: usize, distance: &D) -> Vec<(usize, C)>
where
G: Successors<State = S, Cost = C>,
G::Action: Clone,
D: Fn(&S, &S) -> C,
{
let state = &self.nodes[from];
let region = self.regions.region(state);
let mut edges = Vec::new();
graph.successors(state, |_, next, cost| {
if self.regions.region(&next) != region {
if let Some(&to) = self.index.get(&next) {
edges.push((to, cost));
}
}
});
for &to in &self.members[®ion] {
if to == from {
continue;
}
let local = self.local(graph, state, &self.nodes[to], distance, |_: &Stats| false);
if let Some(solution) = local.into_solution() {
edges.push((to, solution.cost));
}
}
edges
}
pub(crate) fn local<G, D>(
&self,
graph: &G,
from: &S,
to: &S,
distance: &D,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors<State = S, Cost = C>,
G::Action: Clone,
D: Fn(&S, &S) -> C,
{
let within = Within {
graph,
regions: &self.regions,
region: self.regions.region(from),
};
let h = heuristic_fn(|state: &S| Some(distance(state, to)));
a_star(&within, from.clone(), &|state: &S| state == to, h, budget)
}
}
impl Hierarchy<GridCell, Octile, GridClusters> {
#[must_use]
pub fn grid<G: UniformGrid>(grid: &G, size: usize) -> Self {
assert!(size > 0, "clusters need at least one cell");
let clusters = GridClusters {
size,
columns: grid.width().div_ceil(size),
};
let mut entrances = Vec::new();
for x in (size..grid.width()).step_by(size) {
transitions(
grid,
size,
|y| ((x - 1, y), (x, y)),
grid.height(),
&mut entrances,
);
}
for y in (size..grid.height()).step_by(size) {
transitions(
grid,
size,
|x| ((x, y - 1), (x, y)),
grid.width(),
&mut entrances,
);
}
let distance = |a: &GridCell, b: &GridCell| Octile::between(*a, *b);
Self::from_entrances(&EightConnected(grid), clusters, entrances, &distance)
}
}
fn transitions<G: UniformGrid>(
grid: &G,
size: usize,
pair: impl Fn(usize) -> (GridCell, GridCell),
length: usize,
entrances: &mut Vec<GridCell>,
) {
const WIDE: usize = 6;
let open = |i: usize| {
let (a, b) = pair(i);
is_open(grid, a) && is_open(grid, b)
};
let mut push = |i: usize| {
let (a, b) = pair(i);
entrances.push(a);
entrances.push(b);
};
let mut i = 0;
while i < length {
if !open(i) {
i += 1;
continue;
}
let cluster_end = (i / size + 1) * size;
let start = i;
while i < length.min(cluster_end) && open(i) {
i += 1;
}
if i - start >= WIDE {
push(start);
push(i - 1);
} else {
push(start + (i - start) / 2);
}
}
}
struct Within<'a, G, R> {
graph: &'a G,
regions: &'a R,
region: usize,
}
impl<G: Successors, R: Regions<G::State>> Successors for Within<'_, G, R> {
type State = G::State;
type Action = G::Action;
type Cost = G::Cost;
fn successors(&self, state: &G::State, mut emit: impl FnMut(G::Action, G::State, G::Cost)) {
self.graph.successors(state, |action, next, cost| {
if self.regions.region(&next) == self.region {
emit(action, next, cost);
}
});
}
}