use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Budget, Goal, Heuristic};
use crate::best_first::{GraphResult, a_star_multi};
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::Successors;
pub trait EdgeEvaluator<S, A, C> {
fn evaluate(&mut self, from: &S, action: &A, to: &S) -> Option<C>;
}
impl<S, A, C, F: FnMut(&S, &A, &S) -> Option<C>> EdgeEvaluator<S, A, C> for F {
fn evaluate(&mut self, from: &S, action: &A, to: &S) -> Option<C> {
self(from, action, to)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum EdgeSelector {
#[default]
Forward,
Reverse,
Alternate,
Bisection,
All,
}
pub fn lazy_sp<G, T, H, E>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
evaluator: E,
selector: EdgeSelector,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone + Hash + Eq,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
E: EdgeEvaluator<G::State, G::Action, G::Cost>,
{
lazy_sp_multi(graph, [start], goal, heuristic, evaluator, selector, budget)
}
#[expect(
clippy::similar_names,
reason = "`starts` is the parameter name of every `*_multi` search"
)]
pub fn lazy_sp_multi<G, T, H, E>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
mut heuristic: H,
mut evaluator: E,
selector: EdgeSelector,
mut budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone + Hash + Eq,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
E: EdgeEvaluator<G::State, G::Action, G::Cost>,
{
let starts: Vec<G::State> = starts.into_iter().collect();
let mut view = Evaluated {
graph,
edges: HashTable::new(),
hasher: DefaultHashBuilder::default(),
};
let mut stats = Stats::default();
for round in 0_usize.. {
let inner = a_star_multi(
&view,
starts.iter().cloned(),
goal,
&mut heuristic,
|inner: &Stats| budget.exhausted(&stats.plus(*inner)),
);
stats = stats.plus(inner.stats);
let solution = match inner.outcome {
Outcome::Found(solution) => solution,
outcome => return SearchResult { outcome, stats },
};
let pending = view.unevaluated(&solution);
if pending.is_empty() {
return SearchResult {
outcome: Outcome::Found(solution),
stats,
};
}
for index in select(selector, &pending, round) {
let (from, action, to) = (
&solution.states[index],
&solution.actions[index],
&solution.states[index + 1],
);
let cost = evaluator.evaluate(from, action, to);
stats.evaluations += 1;
view.record(from.clone(), action.clone(), cost);
}
}
unreachable!("the rounds never run out")
}
fn select(selector: EdgeSelector, pending: &[usize], round: usize) -> Vec<usize> {
let from_start = match selector {
EdgeSelector::Forward => true,
EdgeSelector::Reverse => false,
EdgeSelector::Alternate => round % 2 == 0,
EdgeSelector::Bisection => return alloc::vec![pending[pending.len() / 2]],
EdgeSelector::All => return pending.to_vec(),
};
let end = if from_start {
pending.first()
} else {
pending.last()
};
end.copied().into_iter().collect()
}
type Evaluation<G> = (
<G as Successors>::State,
<G as Successors>::Action,
Option<<G as Successors>::Cost>,
);
enum Known<C> {
Lazy,
True(C),
Infeasible,
}
struct Evaluated<'a, G: Successors> {
graph: &'a G,
edges: HashTable<Evaluation<G>>,
hasher: DefaultHashBuilder,
}
impl<G> Evaluated<'_, G>
where
G: Successors,
G::State: Hash + Eq,
G::Action: Hash + Eq,
{
fn lookup(&self, from: &G::State, action: &G::Action) -> Known<G::Cost> {
let hash = self.hasher.hash_one((from, action));
let found = self.edges.find(hash, |(s, a, _)| s == from && a == action);
match found {
None => Known::Lazy,
Some((_, _, Some(cost))) => Known::True(*cost),
Some((_, _, None)) => Known::Infeasible,
}
}
fn record(&mut self, from: G::State, action: G::Action, cost: Option<G::Cost>) {
let hash = self.hasher.hash_one((&from, &action));
let hasher = &self.hasher;
self.edges
.insert_unique(hash, (from, action, cost), |(s, a, _)| {
hasher.hash_one((s, a))
});
}
fn unevaluated(&self, path: &Solution<G::State, G::Action, G::Cost>) -> Vec<usize> {
path.actions
.iter()
.enumerate()
.filter(|(index, action)| {
matches!(self.lookup(&path.states[*index], action), Known::Lazy)
})
.map(|(index, _)| index)
.collect()
}
}
impl<G> Successors for Evaluated<'_, G>
where
G: Successors,
G::State: Hash + Eq,
G::Action: Hash + Eq,
{
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, lazy| {
match self.lookup(state, &action) {
Known::Lazy => emit(action, next, lazy),
Known::True(cost) => emit(action, next, cost),
Known::Infeasible => {}
}
});
}
}