mod factor;
pub(crate) mod lex;
use alloc::collections::{BTreeMap, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::Reverse;
use core::mem;
use search_core::{Budget, Cost, Heuristic, WideMul};
use crate::cost::add;
use crate::graph::Graph;
use crate::output::{Solution, Stats};
pub use factor::ApproxFactor;
#[derive(Debug, Clone)]
pub struct AnytimeFront<S, C, const N: usize = 2> {
pub solutions: Vec<Solution<S, [C; N]>>,
pub factor: ApproxFactor<C>,
pub complete: bool,
pub stats: Stats,
}
#[derive(Debug, Clone, Copy)]
pub struct WeightedSum<W> {
pub weight: u32,
pub heuristic: W,
}
pub fn boa_star_anytime<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
d: u32,
on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
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 variant = Variant::<NoSum> {
reuse: true,
weighted: None,
};
run(
graph, heuristic, start, is_goal, d, variant, on_front, budget,
)
}
#[expect(
clippy::too_many_arguments,
reason = "the paper's inputs plus the anytime callback and budget, as in boa_star_anytime"
)]
pub fn boa_star_anytime_ws<G, H, W, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
d: u32,
weighted: WeightedSum<W>,
on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
budget: impl Budget<Stats>,
) -> AnytimeFront<G::State, C>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
W: Heuristic<G::State, C>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
let variant = Variant {
reuse: true,
weighted: Some(weighted),
};
run(
graph, heuristic, start, is_goal, d, variant, on_front, budget,
)
}
pub fn boa_star_anytime_basic<G, H, C, P>(
graph: &G,
heuristic: H,
start: G::State,
is_goal: P,
d: u32,
on_front: impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
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 variant = Variant::<NoSum> {
reuse: false,
weighted: None,
};
run(
graph, heuristic, start, is_goal, d, variant, on_front, budget,
)
}
struct Variant<W> {
reuse: bool,
weighted: Option<WeightedSum<W>>,
}
struct NoSum;
impl<S, C: Cost> Heuristic<S, C> for NoSum {
fn estimate(&mut self, _state: &S) -> Option<C> {
Some(C::ZERO)
}
}
#[expect(
clippy::too_many_arguments,
reason = "the public entry points' arguments plus the variant"
)]
fn run<G, H, W, C, P>(
graph: &G,
mut heuristic: H,
start: G::State,
is_goal: P,
d: u32,
variant: Variant<W>,
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]>,
W: Heuristic<G::State, C>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
assert!(d >= 2, "the divisor d must be at least 2");
let mut stats = Stats::default();
let Some(tl) = lex::lex_first(graph, &mut heuristic, &start, &is_goal, 0, &mut stats) else {
return AnytimeFront {
solutions: Vec::new(),
factor: ApproxFactor::Zero,
complete: true,
stats,
};
};
let br = lex::lex_first(graph, &mut heuristic, &start, &is_goal, 1, &mut stats)
.expect("a goal reachable in one order is reachable in the other");
if tl.cost == br.cost {
let solutions = alloc::vec![tl];
on_front(&solutions, ApproxFactor::Zero);
return AnytimeFront {
solutions,
factor: ApproxFactor::Zero,
complete: true,
stats,
};
}
let mut search = Anytime {
graph,
heuristic,
is_goal,
weighted: variant.weighted,
start,
nodes: Vec::new(),
solutions: alloc::vec![tl, br],
intervals: Vec::new(),
successors: Vec::new(),
stats,
};
search.intervals = alloc::vec![search.seed_interval()];
let complete = search.iterate(d, variant.reuse, &mut on_front, &mut budget);
search.into_front(complete)
}
struct Node<S, C> {
state: S,
g: [C; 2],
f: [C; 2],
sum: Option<C>,
parent: Option<usize>,
}
struct Interval<C> {
tl: usize,
br: usize,
paths: Vec<usize>,
factor: ApproxFactor<C>,
}
struct Anytime<'a, G: Graph, H, W, C, P> {
graph: &'a G,
heuristic: H,
is_goal: P,
weighted: Option<WeightedSum<W>>,
start: G::State,
nodes: Vec<Node<G::State, C>>,
solutions: Vec<Solution<G::State, [C; 2]>>,
intervals: Vec<Interval<C>>,
successors: Vec<(G::State, [C; 2])>,
stats: Stats,
}
struct Refine<S, C> {
eps: ApproxFactor<C>,
tl: [C; 2],
br: [C; 2],
last: [C; 2],
g2_min: BTreeMap<S, C>,
kept: Vec<usize>,
}
impl<G, H, W, C, P> Anytime<'_, G, H, W, C, P>
where
G: Graph<Weight = [C; 2]>,
H: Heuristic<G::State, [C; 2]>,
W: Heuristic<G::State, C>,
C: Cost + WideMul,
P: Fn(&G::State) -> bool,
{
fn seed_interval(&mut self) -> Interval<C> {
let start = self.start.clone();
let paths: Vec<usize> = self
.new_node(start, [C::ZERO; 2], None)
.into_iter()
.collect();
self.stats.generated += paths.len();
self.interval(0, 1, paths)
}
fn iterate(
&mut self,
d: u32,
reuse: bool,
on_front: &mut impl FnMut(&[Solution<G::State, [C; 2]>], ApproxFactor<C>),
budget: &mut impl Budget<Stats>,
) -> bool {
let mut reported = self.factor();
on_front(&self.front(), reported);
loop {
let (index, factor) = self.widest();
if factor.is_zero() {
return true;
}
let eps = self.target(factor, d);
let finished = if reuse {
let interval = self.intervals.remove(index);
let (parts, finished) = self.refine(&interval, eps, budget);
self.intervals.splice(index..index, parts);
finished
} else {
let seed = self.seed_interval();
let (parts, finished) = self.refine(&seed, eps, budget);
self.intervals = parts;
finished
};
let now = self.factor();
if now < reported {
reported = now;
on_front(&self.front(), reported);
}
if !finished {
return false;
}
}
}
fn target(&self, factor: ApproxFactor<C>, d: u32) -> ApproxFactor<C> {
match factor {
ApproxFactor::Infinite => {
let one = self.solutions[1].cost[0];
ApproxFactor::Ratio { num: one, den: one }
}
finite => finite.divided(d),
}
}
fn refine(
&mut self,
interval: &Interval<C>,
eps: ApproxFactor<C>,
budget: &mut impl Budget<Stats>,
) -> (Vec<Interval<C>>, bool) {
let tl = self.solutions[interval.tl].cost;
let mut refine = Refine {
eps,
tl,
br: self.solutions[interval.br].cost,
last: tl,
g2_min: BTreeMap::new(),
kept: Vec::new(),
};
let mut open: BinaryHeap<_> = interval
.paths
.iter()
.map(|&i| Reverse((self.nodes[i].f, i)))
.collect();
let mut parts = Vec::new();
let mut top_left = interval.tl;
let mut best: Option<C> = None;
while let Some(Reverse((_, index))) = open.pop() {
if budget.exhausted(&self.stats) {
refine.kept.push(index);
refine.kept.extend(open.drain().map(|Reverse((_, i))| i));
parts.push(self.interval(top_left, interval.br, refine.kept));
return (parts, false);
}
if self.is_dominated(index, best, &mut refine) {
continue;
}
let node = &self.nodes[index];
refine.g2_min.insert(node.state.clone(), node.g[1]);
if (self.is_goal)(&self.nodes[index].state) {
let solution = self.record(index);
parts.push(self.interval(top_left, solution, mem::take(&mut refine.kept)));
top_left = solution;
refine.last = self.nodes[index].g;
best = Some(self.nodes[index].g[1]);
continue;
}
self.expand(index, best, &mut refine, &mut open);
}
parts.push(self.interval(top_left, interval.br, refine.kept));
(parts, true)
}
fn expand(
&mut self,
index: usize,
best: Option<C>,
refine: &mut Refine<G::State, C>,
open: &mut BinaryHeap<Reverse<([C; 2], usize)>>,
) {
self.stats.expanded += 1;
let mut successors = mem::take(&mut self.successors);
let g = self.nodes[index].g;
self.graph
.successors(&self.nodes[index].state, &mut successors);
for (state, weight) in successors.drain(..) {
let Some(child) = self.new_node(state, add(g, weight), Some(index)) else {
continue;
};
if !self.is_dominated(child, best, refine) {
open.push(Reverse((self.nodes[child].f, child)));
self.stats.generated += 1;
}
}
self.successors = successors;
}
fn is_dominated(
&self,
index: usize,
best: Option<C>,
refine: &mut Refine<G::State, C>,
) -> bool {
let node = &self.nodes[index];
let (g, f) = (node.g, node.f);
if f[0] >= refine.br[0] || f[1] >= refine.tl[1] || self.below_line(node, refine) {
return true;
}
let exact = refine.g2_min.get(&node.state).is_some_and(|&m| g[1] >= m)
|| best.is_some_and(|b| f[1] >= b);
let tolerated = best.is_some_and(|b| refine.eps.covers(b, f[1]));
if exact || tolerated {
if !exact {
refine.kept.push(index);
}
return true;
}
false
}
fn below_line(&self, node: &Node<G::State, C>, refine: &Refine<G::State, C>) -> bool {
let Some(weighted) = &self.weighted else {
return false;
};
let Some(sum) = node.sum else {
return true;
};
let w = weighted.weight;
let line = refine.br[0].saturating_add(refine.last[1].saturating_times(w));
if line.saturating_add(line) == line && line != C::ZERO {
return false;
}
let reach = node.g[0]
.saturating_add(node.g[1].saturating_times(w))
.saturating_add(sum);
reach >= line
}
fn new_node(&mut self, state: G::State, g: [C; 2], parent: Option<usize>) -> Option<usize> {
let h = self.heuristic.estimate(&state)?;
let sum = match &mut self.weighted {
Some(weighted) => weighted.heuristic.estimate(&state),
None => None,
};
self.nodes.push(Node {
state,
g,
f: add(g, h),
sum,
parent,
});
Some(self.nodes.len() - 1)
}
fn record(&mut self, index: usize) -> usize {
let mut path = Vec::new();
let mut current = Some(index);
while let Some(i) = current {
path.push(self.nodes[i].state.clone());
current = self.nodes[i].parent;
}
path.reverse();
self.solutions.push(Solution {
cost: self.nodes[index].g,
path,
});
self.solutions.len() - 1
}
fn interval(&self, tl: usize, br: usize, paths: Vec<usize>) -> Interval<C> {
let (tl_cost, br_cost) = (self.solutions[tl].cost, self.solutions[br].cost);
let factor = paths
.iter()
.map(|&i| {
let f = self.nodes[i].f;
ApproxFactor::domination(tl_cost, f).min(ApproxFactor::domination(br_cost, f))
})
.max()
.unwrap_or(ApproxFactor::Zero);
Interval {
tl,
br,
paths,
factor,
}
}
fn widest(&self) -> (usize, ApproxFactor<C>) {
self.intervals
.iter()
.enumerate()
.fold((0, ApproxFactor::Zero), |acc, (i, interval)| {
if interval.factor > acc.1 {
(i, interval.factor)
} else {
acc
}
})
}
fn factor(&self) -> ApproxFactor<C> {
self.widest().1
}
fn front(&self) -> Vec<Solution<G::State, [C; 2]>> {
let first = self.intervals.first().map(|interval| interval.tl);
first
.into_iter()
.chain(self.intervals.iter().map(|interval| interval.br))
.map(|i| self.solutions[i].clone())
.collect()
}
fn into_front(self, complete: bool) -> AnytimeFront<G::State, C> {
AnytimeFront {
solutions: self.front(),
factor: self.factor(),
complete,
stats: self.stats,
}
}
}