use alloc::vec;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, heuristic_fn};
use super::{Hierarchy, Regions};
use crate::best_first::{GraphResult, a_star_multi};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::Successors;
pub fn hierarchical_a_star<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
start: G::State,
goal: G::State,
distance: D,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
R: Regions<G::State>,
D: Fn(&G::State, &G::State) -> G::Cost,
{
hierarchical_a_star_multi(graph, hierarchy, [start], goal, distance, budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn hierarchical_a_star_multi<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
starts: impl IntoIterator<Item = G::State>,
goal: G::State,
distance: D,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
R: Regions<G::State>,
D: Fn(&G::State, &G::State) -> G::Cost,
{
match plan(graph, hierarchy, starts, goal, &distance, budget) {
Err(result) => result,
Ok((segments, stats, _)) => {
let refined = segments
.iter()
.map(|(from, to)| refine(graph, hierarchy, from, to, &distance))
.collect();
join(refined, stats)
}
}
}
#[cfg(feature = "parallel")]
pub fn hierarchical_a_star_par<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
start: G::State,
goal: G::State,
distance: D,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send + Sync,
G::Action: Clone + Send,
G::Cost: Send + Sync,
R: Regions<G::State> + Sync,
D: Fn(&G::State, &G::State) -> G::Cost + Sync,
{
hierarchical_a_star_par_multi(graph, hierarchy, [start], goal, distance, budget)
}
#[cfg(feature = "parallel")]
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn hierarchical_a_star_par_multi<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
starts: impl IntoIterator<Item = G::State>,
goal: G::State,
distance: D,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send + Sync,
G::Action: Clone + Send,
G::Cost: Send + Sync,
R: Regions<G::State> + Sync,
D: Fn(&G::State, &G::State) -> G::Cost + Sync,
{
let (segments, stats, per_search) =
match plan(graph, hierarchy, starts, goal, &distance, budget) {
Err(result) => return result,
Ok(plan) => plan,
};
let cores = || std::thread::available_parallelism().map_or(1, core::num::NonZeroUsize::get);
let refined = refine_par(
graph,
hierarchy,
&segments,
&distance,
per_search,
cores,
EXPANSIONS_PER_THREAD,
);
join(refined, stats)
}
#[cfg(feature = "parallel")]
const EXPANSIONS_PER_THREAD: u64 = 1000;
#[cfg(feature = "parallel")]
fn refine_par<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
segments: &[(G::State, G::State)],
distance: &D,
per_search: u64,
cores: impl FnOnce() -> usize,
per_thread: u64,
) -> Vec<Refined<G>>
where
G: Successors + Sync,
G::State: Clone + Hash + Eq + Send + Sync,
G::Action: Clone + Send,
G::Cost: Send + Sync,
R: Regions<G::State> + Sync,
D: Fn(&G::State, &G::State) -> G::Cost + Sync,
{
let refine_all = |part: &[(G::State, G::State)]| {
part.iter()
.map(|(from, to)| refine(graph, hierarchy, from, to, distance))
.collect::<Vec<_>>()
};
let regions = &hierarchy.regions;
let inside = segments
.iter()
.filter(|(from, to)| regions.region(from) == regions.region(to))
.count();
let estimate = per_search.saturating_mul(inside as u64);
let threads = segments
.len()
.min(usize::try_from(estimate / per_thread.max(1)).unwrap_or(usize::MAX));
let threads = if threads < 2 { 1 } else { threads.min(cores()) };
if threads < 2 {
return refine_all(segments);
}
let mut shares = segments.chunks(segments.len().div_ceil(threads));
let first = shares.next().unwrap_or_default();
std::thread::scope(|scope| {
let handles: Vec<_> = shares
.map(|part| scope.spawn(move || refine_all(part)))
.collect();
let mut refined = refine_all(first);
for handle in handles {
refined.extend(
handle
.join()
.unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
);
}
refined
})
}
type Plan<G> = Result<
(
Vec<(<G as Successors>::State, <G as Successors>::State)>,
Stats,
u64,
),
GraphResult<G>,
>;
fn plan<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
starts: impl IntoIterator<Item = G::State>,
goal: G::State,
distance: &D,
mut budget: impl Budget<Stats>,
) -> Plan<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
R: Regions<G::State>,
D: Fn(&G::State, &G::State) -> G::Cost,
{
let starts: Vec<G::State> = starts.into_iter().collect();
if starts.contains(&goal) {
let solution = Solution {
states: vec![goal],
actions: Vec::new(),
cost: G::Cost::ZERO,
};
return Err(ended(Outcome::Found(solution), Stats::default()));
}
let base = hierarchy.nodes.len();
let goal_id = base + starts.len();
let state = |id: usize| -> &G::State {
if id < base {
&hierarchy.nodes[id]
} else if id < goal_id {
&starts[id - base]
} else {
&goal
}
};
let mut graph_view = Abstract {
base: &hierarchy.edges,
added: vec![Vec::new(); goal_id + 1],
};
let mut counters = Stats::default();
let connections = connections(hierarchy, &starts, &goal, base);
for &(from, to) in &connections {
let inner = hierarchy.local(graph, state(from), state(to), distance, |inner: &Stats| {
budget.exhausted(&counters.plus(*inner))
});
counters = counters.plus(inner.stats);
match inner.outcome {
Outcome::Found(solution) => graph_view.added[from].push((to, solution.cost)),
Outcome::LimitReached => return Err(ended(Outcome::LimitReached, counters)),
Outcome::Unsolvable | Outcome::Cutoff => {}
}
}
let per_search = counters.expanded / (connections.len() as u64).max(1);
let h = heuristic_fn(|id: &usize| Some(distance(state(*id), &goal)));
let inner = a_star_multi(
&graph_view,
base..goal_id,
&|id: &usize| *id == goal_id,
h,
|inner: &Stats| budget.exhausted(&counters.plus(*inner)),
);
counters = counters.plus(inner.stats);
let path = match inner.outcome {
Outcome::Found(path) => path,
Outcome::LimitReached => return Err(ended(Outcome::LimitReached, counters)),
Outcome::Unsolvable | Outcome::Cutoff => {
return Err(ended(Outcome::Unsolvable, counters));
}
};
let segments = path
.states
.windows(2)
.map(|pair| (state(pair[0]).clone(), state(pair[1]).clone()))
.collect();
Ok((segments, counters, per_search))
}
fn connections<S, C, R: Regions<S>>(
hierarchy: &Hierarchy<S, C, R>,
starts: &[S],
goal: &S,
base: usize,
) -> Vec<(usize, usize)> {
let goal_id = base + starts.len();
let goal_region = hierarchy.regions.region(goal);
let members = |region: usize| {
hierarchy
.members
.get(®ion)
.map_or(&[][..], Vec::as_slice)
};
let mut pairs = Vec::new();
for (i, start) in starts.iter().enumerate() {
let region = hierarchy.regions.region(start);
pairs.extend(members(region).iter().map(|&to| (base + i, to)));
if region == goal_region {
pairs.push((base + i, goal_id));
}
}
pairs.extend(members(goal_region).iter().map(|&from| (from, goal_id)));
pairs
}
fn ended<S, A, C>(outcome: Outcome<S, A, C>, stats: Stats) -> SearchResult<S, A, C> {
SearchResult { outcome, stats }
}
type Refined<G> = (
Solution<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>,
Stats,
);
fn refine<G, R, D>(
graph: &G,
hierarchy: &Hierarchy<G::State, G::Cost, R>,
from: &G::State,
to: &G::State,
distance: &D,
) -> Refined<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
R: Regions<G::State>,
D: Fn(&G::State, &G::State) -> G::Cost,
{
const STALE: &str = "abstract edges refine in the graph the hierarchy was built from";
let regions = &hierarchy.regions;
if regions.region(from) == regions.region(to) {
let result = hierarchy.local(graph, from, to, distance, |_: &Stats| false);
let stats = result.stats;
return (result.into_solution().expect(STALE), stats);
}
let mut stats = Stats {
expanded: 1,
..Stats::default()
};
let mut best: Option<(G::Action, G::Cost)> = None;
graph.successors(from, |action, next, cost| {
stats.generated += 1;
if next == *to && best.as_ref().is_none_or(|(_, known)| cost < *known) {
best = Some((action, cost));
}
});
let (action, cost) = best.expect(STALE);
let solution = Solution {
states: vec![from.clone(), to.clone()],
actions: vec![action],
cost,
};
(solution, stats)
}
fn join<S, A, C: Cost>(
segments: Vec<(Solution<S, A, C>, Stats)>,
mut stats: Stats,
) -> SearchResult<S, A, C> {
let mut path = Solution {
states: Vec::new(),
actions: Vec::new(),
cost: C::ZERO,
};
for (segment, counters) in segments {
let skip = usize::from(!path.states.is_empty());
path.states.extend(segment.states.into_iter().skip(skip));
path.actions.extend(segment.actions);
path.cost = path.cost + segment.cost;
stats = stats.plus(counters);
}
ended(Outcome::Found(path), stats)
}
struct Abstract<'a, C> {
base: &'a [Vec<(usize, C)>],
added: Vec<Vec<(usize, C)>>,
}
impl<C: Cost> Successors for Abstract<'_, C> {
type State = usize;
type Action = ();
type Cost = C;
fn successors(&self, id: &usize, mut emit: impl FnMut((), usize, C)) {
let base = self.base.get(*id).map_or(&[][..], Vec::as_slice);
for &(to, cost) in base.iter().chain(&self.added[*id]) {
emit((), to, cost);
}
}
}
#[cfg(all(test, feature = "parallel"))]
mod tests {
use alloc::vec::Vec;
use crate::Limits;
use proptest::prelude::*;
use super::{Hierarchy, plan, refine, refine_par};
use crate::grid::{EightConnected, GridCell, Octile, UniformGrid};
struct Map {
walls: [u64; 3],
}
impl UniformGrid for Map {
fn width(&self) -> usize {
12
}
fn height(&self) -> usize {
12
}
fn is_passable(&self, x: usize, y: usize) -> bool {
let bit = y * 12 + x;
self.walls[bit / 64] & (1 << (bit % 64)) == 0
}
}
proptest! {
#[test]
fn threaded_refinement_matches_sequential(
walls in proptest::array::uniform3(any::<u64>().prop_map(|w| w & w.rotate_left(7))),
size in 1_usize..5,
cores in 2_usize..6,
start in (0_usize..12, 0_usize..12),
goal in (0_usize..12, 0_usize..12),
) {
let map = Map { walls };
let hierarchy = Hierarchy::grid(&map, size);
let graph = EightConnected(&map);
let distance = |a: &GridCell, b: &GridCell| Octile::between(*a, *b);
if let Ok((segments, _, _)) = plan(&graph, &hierarchy, [start], goal, &distance, Limits::NONE) {
let sequential: Vec<_> = segments
.iter()
.map(|(from, to)| refine(&graph, &hierarchy, from, to, &distance))
.collect();
let threaded = refine_par(&graph, &hierarchy, &segments, &distance, u64::MAX, || cores, 1);
prop_assert_eq!(threaded, sequential);
}
}
}
}