use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::{Weight, within};
use crate::open_list::OpenList;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MhaWeights {
pub heuristic: Weight,
pub anchor: Weight,
}
impl MhaWeights {
pub const ONE: Self = Self {
heuristic: Weight::ONE,
anchor: Weight::ONE,
};
}
pub fn mha_star<G, T, H0, H>(
graph: &G,
start: G::State,
goal: &T,
anchor: H0,
heuristics: impl IntoIterator<Item = H>,
weights: MhaWeights,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H0: Heuristic<G::State, G::Cost>,
H: Heuristic<G::State, G::Cost>,
{
mha_star_multi(graph, [start], goal, anchor, heuristics, weights, budget)
}
pub fn mha_star_multi<G, T, H0, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
anchor: H0,
heuristics: impl IntoIterator<Item = H>,
weights: MhaWeights,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H0: Heuristic<G::State, G::Cost>,
H: Heuristic<G::State, G::Cost>,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let heuristics: Vec<H> = heuristics.into_iter().collect();
let queues = (0..=heuristics.len()).map(|_| OpenList::new()).collect();
let search = Mha {
graph,
goal,
anchor,
heuristics,
weights,
space,
queues,
stats: Stats::default(),
h: Vec::new(),
in_anchor: Vec::new(),
in_inadmissible: Vec::new(),
closed_anchor: Vec::new(),
closed_inadmissible: Vec::new(),
incumbent: start_goal,
buffer: Vec::new(),
};
if start_goal.is_some() {
return search.finish(true);
}
search.run(budget)
}
const ANCHOR: usize = 0;
enum Turn {
Expand(usize, NodeId),
Done,
}
struct Mha<'a, G: Successors, T: ?Sized, H0, H> {
graph: &'a G,
goal: &'a T,
anchor: H0,
heuristics: Vec<H>,
weights: MhaWeights,
space: SearchSpace<G::State, G::Action, G::Cost>,
queues: Vec<OpenList<G::Cost>>,
stats: Stats,
h: Vec<Option<Vec<Option<G::Cost>>>>,
in_anchor: Vec<bool>,
in_inadmissible: Vec<bool>,
closed_anchor: Vec<bool>,
closed_inadmissible: Vec<bool>,
incumbent: Option<NodeId>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, T, H0, H> Mha<'_, G, T, H0, H>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H0: Heuristic<G::State, G::Cost>,
H: Heuristic<G::State, G::Cost>,
{
fn run(mut self, mut budget: impl Budget<Stats>) -> GraphResult<G> {
for start in 0..self.space.len() {
self.add_node(start);
}
let rounds = self.heuristics.len().max(1);
for queue in (1..=rounds).cycle() {
let Some(Turn::Expand(queue, node)) = self.turn(queue) else {
return self.finish(true);
};
if budget.exhausted(&self.stats) {
return self.finish(false);
}
self.expand(queue, node);
}
unreachable!("the round robin never ends on its own")
}
fn turn(&mut self, queue: usize) -> Option<Turn> {
let (_, anchor_key) = self.peek(ANCHOR)?;
let chosen = match self.peek(queue) {
Some((node, key)) if within(key, self.weights.anchor, anchor_key) => (queue, node, key),
_ => {
let (node, key) = self.peek(ANCHOR).expect("the anchor is not empty");
(ANCHOR, node, key)
}
};
let (queue, node, key) = chosen;
let done = self.incumbent.is_some_and(|goal| {
let g = self
.space
.g(goal)
.saturating_times(self.weights.heuristic.denominator());
g.cmp(&key).is_le()
});
Some(if done {
Turn::Done
} else {
Turn::Expand(queue, node)
})
}
fn peek(&mut self, queue: usize) -> Option<(NodeId, G::Cost)> {
let (space, flags) = if queue == ANCHOR {
(&self.space, &self.in_anchor)
} else {
(&self.space, &self.in_inadmissible)
};
self.queues
.get_mut(queue)?
.peek_where(|node, g| flags[node] && g.cmp(&space.g(node)).is_eq())
}
fn expand(&mut self, queue: usize, node: NodeId) {
self.stats.expanded += 1;
self.in_anchor[node] = false;
self.in_inadmissible[node] = false;
if queue == ANCHOR {
self.closed_anchor[node] = true;
} else {
self.closed_inadmissible[node] = true;
}
self.stats.generated +=
collect_successors(self.graph, self.space.state(node), &mut self.buffer);
let mut buffer = core::mem::take(&mut self.buffer);
for (action, state, cost) in buffer.drain(..) {
match self.space.reach(state, node, action, cost, true) {
Reach::New(id) => self.add_node(id),
Reach::Improved(id) => self.improved(id),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn add_node(&mut self, id: NodeId) {
let state = self.space.state(id);
let values = self.anchor.estimate(state).map(|anchor| {
let mut values = Vec::with_capacity(self.heuristics.len() + 1);
values.push(Some(anchor));
values.extend(self.heuristics.iter_mut().map(|h| h.estimate(state)));
values
});
self.h.push(values);
self.in_anchor.push(false);
self.in_inadmissible.push(false);
self.closed_anchor.push(false);
self.closed_inadmissible.push(false);
self.improved(id);
}
fn improved(&mut self, id: NodeId) {
if self.goal.is_goal(self.space.state(id)) {
let cheaper = self
.incumbent
.is_none_or(|goal| goal == id || self.space.g(id).cmp(&self.space.g(goal)).is_lt());
if cheaper {
self.incumbent = Some(id);
}
return;
}
if self.h[id].is_none() {
return;
}
let was_closed = self.closed_anchor[id] || self.closed_inadmissible[id];
let requeued = !(self.closed_anchor[id] && self.closed_inadmissible[id]);
if was_closed && requeued {
self.stats.reopened += 1;
}
if !self.closed_anchor[id] {
self.push(ANCHOR, id);
self.in_anchor[id] = true;
}
if !self.closed_inadmissible[id] {
let anchor_key = self
.key(ANCHOR, id)
.expect("live nodes have an anchor value");
for queue in 1..self.queues.len() {
if self
.key(queue, id)
.is_some_and(|key| within(key, self.weights.anchor, anchor_key))
{
self.push(queue, id);
self.in_inadmissible[id] = true;
}
}
}
}
fn key(&self, queue: usize, id: NodeId) -> Option<G::Cost> {
let h = self.h[id].as_ref()?[queue]?;
let weight = self.weights.heuristic;
Some(
self.space
.g(id)
.saturating_times(weight.denominator())
.saturating_add(h.saturating_times(weight.numerator())),
)
}
fn push(&mut self, queue: usize, id: NodeId) {
if let Some(key) = self.key(queue, id) {
self.queues[queue].push(id, key, self.space.g(id));
}
}
fn finish(self, decided: bool) -> GraphResult<G> {
let outcome = match (decided, self.incumbent) {
(false, _) => Outcome::LimitReached,
(true, Some(goal)) => Outcome::Found(self.space.solution(goal)),
(true, None) => Outcome::Unsolvable,
};
SearchResult {
outcome,
stats: self.stats,
}
}
}