use alloc::vec::Vec;
use search_core::{Budget, Cost, Heuristic, WideMul};
use crate::anytime_boa::{AnytimeFront, ApproxFactor};
use crate::epsilon::Epsilon;
use crate::graph::Graph;
use crate::output::{Solution, Stats};
use crate::pp_a::pp_a_star;
#[expect(
clippy::needless_pass_by_value,
reason = "takes the start by value like every other search in the crate"
)]
pub fn pp_a_star_iterative<G, H, C, P>(
graph: &G,
mut heuristic: H,
start: G::State,
is_goal: P,
schedule: impl IntoIterator<Item = Epsilon>,
mut on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
mut budget: impl Budget<Stats>,
) -> AnytimeFront<G::State, C>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
let mut front = AnytimeFront {
solutions: Vec::new(),
factor: ApproxFactor::Infinite,
complete: false,
stats: Stats::default(),
};
let mut ran = false;
for eps in schedule {
if ran && budget.exhausted(&front.stats) {
return front;
}
let first = !ran;
ran = true;
let out = pp_a_star(graph, &mut heuristic, start.clone(), &is_goal, [eps; 2]);
front.stats.expanded += out.stats.expanded;
front.stats.generated += out.stats.generated;
front.complete = eps == Epsilon::ZERO;
let factor = as_factor(eps, &out.solutions);
if first || factor < front.factor {
front.solutions = out.solutions;
front.factor = factor;
on_front(&front.solutions, factor);
}
}
front
}
pub(crate) fn as_factor<S, C: Cost + WideMul, const N: usize>(
eps: Epsilon,
solutions: &[Solution<S, [C; N]>],
) -> ApproxFactor<C> {
let unit = solutions
.iter()
.flat_map(|s| s.cost)
.filter(|&c| c > C::ZERO)
.min();
match unit {
_ if eps.num() == 0 => ApproxFactor::Zero,
None => ApproxFactor::Zero,
Some(unit) => {
let den = unit.saturating_times(eps.den());
let num = unit.saturating_times(eps.num());
if den.saturating_add(den) == den || num.saturating_add(num) == num {
ApproxFactor::Infinite
} else {
ApproxFactor::Ratio { num, den }
}
}
}
}