use alloc::collections::VecDeque;
use alloc::vec;
use alloc::vec::Vec;
use core::hash::{BuildHasher, Hash};
use hashbrown::{DefaultHashBuilder, HashTable};
use search_core::{Budget, Cost};
use crate::cost::Weight;
use crate::dynamic::DynamicGraph;
use crate::keyed_set::KeyedSet;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
pub(super) trait Estimate<V, C> {
fn estimate(&mut self, from: &V, to: &V) -> C;
}
impl<V, C, F: FnMut(&V, &V) -> C> Estimate<V, C> for F {
fn estimate(&mut self, from: &V, to: &V) -> C {
self(from, to)
}
}
pub(super) trait Searched {
type Vertex: Clone + Hash + Eq;
type Cost: Cost;
fn successors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost));
fn predecessors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost));
const LOOKAHEAD: bool = false;
fn lookahead(
&self,
vertex: &Self::Vertex,
g: impl Fn(&Self::Vertex) -> Option<Self::Cost>,
) -> Option<Self::Cost> {
let _ = (vertex, g);
None
}
}
impl<G: DynamicGraph> Searched for G {
type Vertex = G::Vertex;
type Cost = G::Cost;
fn successors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost)) {
DynamicGraph::successors(self, vertex, emit);
}
fn predecessors(&self, vertex: &Self::Vertex, emit: impl FnMut(Self::Vertex, Self::Cost)) {
DynamicGraph::predecessors(self, vertex, emit);
}
}
type Key<C> = (C, C);
type VertexId = usize;
struct Anytime {
weight: Weight,
keyed: Weight,
rekey: bool,
closed: Vec<bool>,
closed_list: Vec<VertexId>,
incons: Vec<bool>,
incons_list: Vec<VertexId>,
}
pub(super) struct Incremental<V, C, D> {
forward: bool,
source: VertexId,
target: VertexId,
heuristic: D,
vertices: Vec<V>,
index: HashTable<VertexId>,
hasher: DefaultHashBuilder,
g: Vec<Option<C>>,
rhs: Vec<Option<C>>,
queue: KeyedSet<Key<C>>,
km: C,
anytime: Option<Anytime>,
pub(super) settle_ties: bool,
pub(super) total: Stats,
buffer: Vec<(V, C)>,
}
impl<V, C, D> Incremental<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: Estimate<V, C>,
{
pub(super) fn new(
forward: bool,
source: V,
target: V,
heuristic: D,
weight: Option<Weight>,
) -> Self {
let mut search = Self {
forward,
source: 0,
target: 0,
heuristic,
vertices: Vec::new(),
index: HashTable::new(),
hasher: DefaultHashBuilder::default(),
g: Vec::new(),
rhs: Vec::new(),
queue: KeyedSet::new(),
km: C::ZERO,
settle_ties: false,
anytime: weight.map(|weight| Anytime {
weight,
keyed: weight,
rekey: false,
closed: Vec::new(),
closed_list: Vec::new(),
incons: Vec::new(),
incons_list: Vec::new(),
}),
total: Stats::default(),
buffer: Vec::new(),
};
search.source = search.intern(source);
search.target = search.intern(target);
search.rhs[search.source] = Some(C::ZERO);
search.requeue(search.source);
search
}
pub(super) fn compute<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
budget: impl Budget<Stats>,
) -> SearchResult<V, (), C> {
let (settled, stats) = self.repair(graph, budget);
if !settled {
return SearchResult {
outcome: Outcome::LimitReached,
stats,
};
}
let outcome = match self.path(graph) {
Some(solution) => Outcome::Found(solution),
None => Outcome::Unsolvable,
};
SearchResult { outcome, stats }
}
pub(super) fn repair<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
mut budget: impl Budget<Stats>,
) -> (bool, Stats) {
let mut stats = Stats::default();
self.begin_iteration();
while let Some((&key, vertex)) = self.queue.first() {
if self.target_settled(key) {
break;
}
if budget.exhausted(&stats) {
self.total = self.total.plus(stats);
return (false, stats);
}
stats.expanded += 1;
stats.generated += self.process(graph, vertex, key);
}
self.total = self.total.plus(stats);
(true, stats)
}
#[cfg(feature = "float")]
pub(super) fn consistent_g(&self, vertex: &V) -> Option<C> {
let id = self.find(vertex)?;
self.g[id].filter(|_| self.g[id] == self.rhs[id])
}
pub(super) fn edge_changed<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
from: &V,
to: &V,
) {
let dependent = if self.forward { to } else { from };
let id = self.intern(dependent.clone());
self.update(graph, id);
}
pub(super) fn move_target(&mut self, target: V) {
let old = self.vertices[self.target].clone();
let moved = self.heuristic.estimate(&old, &target);
self.km = self
.km
.saturating_add(moved.saturating_times(self.weight().numerator()));
self.target = self.intern(target);
}
pub(super) fn set_weight(&mut self, weight: Weight) {
if let Some(anytime) = &mut self.anytime {
let keyed = anytime.keyed;
if weight.denominator() != keyed.denominator() || weight.numerator() < keyed.numerator()
{
anytime.rekey = true;
} else {
anytime.keyed = weight;
}
anytime.weight = weight;
}
}
pub(super) fn weight(&self) -> Weight {
self.anytime
.as_ref()
.map_or(Weight::ONE, |anytime| anytime.weight)
}
fn begin_iteration(&mut self) {
let Some(anytime) = &mut self.anytime else {
return;
};
for vertex in anytime.closed_list.drain(..) {
anytime.closed[vertex] = false;
}
let incons = core::mem::take(&mut anytime.incons_list);
for &vertex in &incons {
anytime.incons[vertex] = false;
}
if anytime.rekey {
anytime.rekey = false;
anytime.keyed = anytime.weight;
for vertex in 0..self.vertices.len() {
self.requeue(vertex);
}
} else {
for vertex in incons {
self.requeue(vertex);
}
}
}
fn target_settled(&mut self, top: Key<C>) -> bool {
let consistent = self.g[self.target] == self.rhs[self.target];
let ties = self.settle_ties;
consistent
&& self
.key(self.target)
.is_some_and(|key| if ties { top > key } else { top >= key })
}
fn process<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
vertex: VertexId,
old: Key<C>,
) -> u64 {
let new = self
.key(vertex)
.expect("queued vertices are inconsistent, so finite");
if old < new {
self.queue.insert(vertex, new);
return 0;
}
let overconsistent = match (self.g[vertex], self.rhs[vertex]) {
(None, _) => true,
(Some(g), Some(rhs)) => g.cmp(&rhs).is_gt(),
(Some(_), None) => false,
};
let dependents = self.away_from_source(graph, vertex);
if overconsistent {
self.g[vertex] = self.rhs[vertex];
self.queue.remove(vertex);
if let Some(anytime) = &mut self.anytime {
anytime.closed[vertex] = true;
anytime.closed_list.push(vertex);
}
} else {
self.g[vertex] = None;
self.update(graph, vertex);
}
let generated = dependents.len() as u64;
for id in dependents {
self.update(graph, id);
}
generated
}
fn update<G: Searched<Vertex = V, Cost = C>>(&mut self, graph: &G, vertex: VertexId) {
if vertex != self.source {
self.rhs[vertex] = if G::LOOKAHEAD {
let g = |other: &V| self.find(other).and_then(|id| self.g[id]);
graph.lookahead(&self.vertices[vertex], g)
} else {
self.towards_source(graph, vertex)
.into_iter()
.filter_map(|(id, cost)| self.g[id].map(|g| g + cost))
.reduce(|a, b| if b.cmp(&a).is_lt() { b } else { a })
};
}
self.requeue(vertex);
}
fn requeue(&mut self, vertex: VertexId) {
let consistent = self.g[vertex] == self.rhs[vertex];
if let Some(anytime) = self.anytime.as_mut().filter(|a| a.closed[vertex]) {
if !consistent && !anytime.incons[vertex] {
anytime.incons_list.push(vertex);
}
anytime.incons[vertex] = !consistent;
self.queue.remove(vertex);
return;
}
match self.key(vertex) {
Some(key) if !consistent => self.queue.insert(vertex, key),
_ => {
self.queue.remove(vertex);
}
}
}
fn key(&mut self, vertex: VertexId) -> Option<Key<C>> {
let (g, rhs) = (self.g[vertex], self.rhs[vertex]);
let overconsistent = match (g, rhs) {
(Some(g), Some(rhs)) => rhs.cmp(&g).is_lt(),
(None, rhs) => rhs.is_some(),
(Some(_), None) => false,
};
let best = if overconsistent { rhs } else { g }?;
let h = self.h(vertex);
let weight = self.weight();
let inflation = if overconsistent {
weight.numerator()
} else {
weight.denominator()
};
let first = best
.saturating_times(weight.denominator())
.saturating_add(h.saturating_times(inflation))
.saturating_add(self.km);
Some((first, best))
}
fn h(&mut self, vertex: VertexId) -> C {
let (vertex, target) = (&self.vertices[vertex], &self.vertices[self.target]);
if self.forward {
self.heuristic.estimate(vertex, target)
} else {
self.heuristic.estimate(target, vertex)
}
}
fn towards_source<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
vertex: VertexId,
) -> Vec<(VertexId, C)> {
self.neighbours(graph, vertex, !self.forward)
}
fn away_from_source<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
vertex: VertexId,
) -> Vec<VertexId> {
let forward = self.forward;
self.neighbours(graph, vertex, forward)
.into_iter()
.map(|(id, _)| id)
.collect()
}
fn neighbours<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
vertex: VertexId,
successors: bool,
) -> Vec<(VertexId, C)> {
let mut buffer = core::mem::take(&mut self.buffer);
let state = &self.vertices[vertex];
let mut emit = |other: V, cost: C| buffer.push((other, cost));
if successors {
graph.successors(state, &mut emit);
} else {
graph.predecessors(state, &mut emit);
}
let neighbours = buffer
.drain(..)
.map(|(other, cost)| (self.intern(other), cost))
.collect();
self.buffer = buffer;
neighbours
}
fn path<G: Searched<Vertex = V, Cost = C>>(&mut self, graph: &G) -> Option<Solution<V, (), C>> {
self.g[self.target]?;
let mut parent: Vec<Option<(VertexId, C)>> = vec![None; self.vertices.len()];
let mut seen = vec![false; self.vertices.len()];
let mut frontier = VecDeque::from([self.target]);
seen[self.target] = true;
while let Some(vertex) = frontier.pop_front() {
if vertex == self.source {
return Some(self.trace(&parent));
}
let g = self.g[vertex]?;
let neighbours = self.towards_source(graph, vertex);
for &(next, cost) in &neighbours {
let tight = self
.g
.get(next)
.copied()
.flatten()
.is_some_and(|g_next| g_next + cost == g);
if !tight || seen.get(next).copied().unwrap_or(false) {
continue;
}
if parent.len() <= next {
parent.resize(next + 1, None);
seen.resize(next + 1, false);
}
seen[next] = true;
parent[next] = Some((vertex, cheapest_edge(&neighbours, next)));
frontier.push_back(next);
}
}
debug_assert!(
self.anytime.is_some(),
"without inflation, tight edges always lead from the target to the source"
);
self.greedy_path(graph)
}
fn greedy_path<G: Searched<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
) -> Option<Solution<V, (), C>> {
let mut seen = vec![false; self.vertices.len()];
let mut steps = vec![(self.target, C::ZERO)];
let mut current = self.target;
seen[current] = true;
while current != self.source {
let (next, cost) = self
.towards_source(graph, current)
.into_iter()
.filter(|&(id, _)| !seen.get(id).copied().unwrap_or(false))
.filter_map(|(id, cost)| self.g[id].map(|g| (id, cost, g + cost)))
.reduce(|a, b| if b.2.cmp(&a.2).is_lt() { b } else { a })
.map(|(id, cost, _)| (id, cost))?;
if seen.len() <= next {
seen.resize(next + 1, false);
}
seen[next] = true;
steps.push((next, cost));
current = next;
}
let mut states: Vec<V> = steps
.iter()
.map(|&(id, _)| self.vertices[id].clone())
.collect();
let cost = steps.iter().fold(C::ZERO, |sum, &(_, cost)| sum + cost);
if self.forward {
states.reverse();
}
Some(Solution {
actions: vec![(); states.len() - 1],
states,
cost,
})
}
fn trace(&self, parent: &[Option<(VertexId, C)>]) -> Solution<V, (), C> {
let mut states = vec![self.vertices[self.source].clone()];
let mut cost = C::ZERO;
let mut current = self.source;
while let Some((next, edge)) = parent[current] {
states.push(self.vertices[next].clone());
cost = cost + edge;
current = next;
}
if !self.forward {
states.reverse();
}
Solution {
actions: vec![(); states.len() - 1],
states,
cost,
}
}
fn find(&self, vertex: &V) -> Option<VertexId> {
let hash = self.hasher.hash_one(vertex);
self.index
.find(hash, |&id| self.vertices[id] == *vertex)
.copied()
}
fn intern(&mut self, vertex: V) -> VertexId {
let hash = self.hasher.hash_one(&vertex);
let vertices = &self.vertices;
if let Some(&id) = self.index.find(hash, |&id| vertices[id] == vertex) {
return id;
}
let id = self.vertices.len();
let hasher = &self.hasher;
self.index
.insert_unique(hash, id, |&other| hasher.hash_one(&vertices[other]));
self.vertices.push(vertex);
self.g.push(None);
self.rhs.push(None);
if let Some(anytime) = &mut self.anytime {
anytime.closed.push(false);
anytime.incons.push(false);
}
id
}
}
fn cheapest_edge<C: Cost>(neighbours: &[(VertexId, C)], target: VertexId) -> C {
neighbours
.iter()
.filter(|&&(id, _)| id == target)
.map(|&(_, cost)| cost)
.min()
.expect("`target` is one of the neighbours")
}
#[cfg(test)]
mod tests {
use alloc::vec::Vec;
use proptest::prelude::*;
use super::Incremental;
use crate::cost::Weight;
use crate::dynamic::DynamicGraph;
struct Path(Vec<u32>);
impl DynamicGraph for Path {
type Vertex = usize;
type Cost = u32;
fn successors(&self, v: &usize, mut emit: impl FnMut(usize, u32)) {
if *v < self.0.len() {
emit(v + 1, self.0[*v]);
}
if *v > 0 {
emit(v - 1, self.0[v - 1]);
}
}
fn predecessors(&self, v: &usize, emit: impl FnMut(usize, u32)) {
self.successors(v, emit);
}
}
fn keys_are_lower_bounds(
search: &mut Incremental<usize, u32, fn(&usize, &usize) -> u32>,
) -> bool {
(0..search.vertices.len()).all(|vertex| match search.queue.key(vertex).copied() {
Some(queued) => search.key(vertex).is_some_and(|now| queued <= now),
None => true,
})
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "heuristics take vertices by reference"
)]
fn distance(a: &usize, b: &usize) -> u32 {
u32::try_from(a.abs_diff(*b)).expect("small graph")
}
proptest! {
#[test]
fn queued_keys_stay_lower_bounds(
steps in prop::collection::vec(
((1_u32..4, 0_u32..9), (1_u32..4, 0_u32..9), 0_usize..7, 1_u32..6, any::<bool>()),
1..10,
),
) {
let weight = |(den, extra): (u32, u32)| Weight::new(den + extra, den);
let mut graph = Path(alloc::vec![1; 7]);
let mut target = 7;
let mut search: Incremental<usize, u32, fn(&usize, &usize) -> u32> =
Incremental::new(false, 0, target, distance, Some(Weight::integer(2)));
for (during, solve, edge, cost, moves) in steps {
search.set_weight(weight(during));
if moves && target > 0 {
target -= 1;
search.move_target(target);
} else {
graph.0[edge] = cost;
search.edge_changed(&graph, &edge, &(edge + 1));
search.edge_changed(&graph, &(edge + 1), &edge);
}
search.set_weight(weight(solve));
search.begin_iteration();
prop_assert!(keys_are_lower_bounds(&mut search));
search.compute(&graph, crate::outcome::Limits::NONE);
}
}
}
}