use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::CostExt;
use crate::cost::{Weight, within};
use crate::keyed_set::KeyedSet;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub fn dps<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
dps_multi(graph, [start], goal, heuristic, weight, budget)
}
pub fn dps_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
assert!(
weight.numerator() >= weight.denominator(),
"DPS weight must be at least 1"
);
let (space, start_goal) = SearchSpace::seed(starts, goal);
let search = Dps {
graph,
heuristic,
weight,
space,
by_f: KeyedSet::new(),
groups: BTreeMap::new(),
stats: Stats::default(),
h: Vec::new(),
closed: Vec::new(),
buffer: Vec::new(),
};
if let Some(found) = start_goal {
let solution = search.space.solution(found);
return search.finish(Outcome::Found(solution));
}
search.run(goal, budget)
}
type Pair<C> = (C, C);
struct Dps<'a, G: Successors, H> {
graph: &'a G,
heuristic: H,
weight: Weight,
space: SearchSpace<G::State, G::Action, G::Cost>,
by_f: KeyedSet<Pair<G::Cost>>,
groups: BTreeMap<Pair<G::Cost>, BTreeSet<NodeId>>,
stats: Stats,
h: Vec<Option<G::Cost>>,
closed: Vec<bool>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, H> Dps<'_, G, H>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
G::Cost: CostExt,
H: Heuristic<G::State, G::Cost>,
{
fn run<T: Goal<G::State> + ?Sized>(
mut self,
goal: &T,
mut budget: impl Budget<Stats>,
) -> GraphResult<G> {
for start in 0..self.space.len() {
self.add_node(start);
}
while let Some(node) = self.select() {
self.close(node);
if goal.is_goal(self.space.state(node)) {
let solution = self.space.solution(node);
return self.finish(Outcome::Found(solution));
}
if budget.exhausted(&self.stats) {
return self.finish(Outcome::LimitReached);
}
self.expand(node);
}
self.finish(Outcome::Unsolvable)
}
fn select(&self) -> Option<NodeId> {
let (key, _) = self.by_f.first()?;
let f_min = key.0;
let budget = f_min.to_f64() * f64::from(self.weight.numerator())
/ f64::from(self.weight.denominator());
let mut best: Option<(f64, NodeId)> = None;
for (&(g, h), nodes) in self.groups.iter().rev() {
if !within(g + h, self.weight, f_min) {
continue;
}
let potential = potential(budget, g, h);
if best.is_none_or(|(top, _)| potential > top) {
best = nodes.first().map(|&node| (potential, node));
}
}
best.map(|(_, node)| node)
}
fn close(&mut self, node: NodeId) {
let Some((_, g)) = self.by_f.remove(node) else {
return;
};
let h = self.h[node].expect("open nodes are live");
let pair = (g, h);
if let Some(group) = self.groups.get_mut(&pair) {
group.remove(&node);
if group.is_empty() {
self.groups.remove(&pair);
}
}
}
fn expand(&mut self, node: NodeId) {
self.stats.expanded += 1;
self.closed[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.reopen(id),
Reach::Stale => {}
}
}
self.buffer = buffer;
}
fn add_node(&mut self, id: NodeId) {
let h = self.heuristic.estimate(self.space.state(id));
self.h.push(h);
self.closed.push(false);
self.open(id);
}
fn reopen(&mut self, id: NodeId) {
if self.h[id].is_some() && self.closed[id] && self.by_f.key(id).is_none() {
self.stats.reopened += 1;
}
self.close(id);
self.open(id);
}
fn open(&mut self, id: NodeId) {
let Some(h) = self.h[id] else {
return;
};
let g = self.space.g(id);
self.by_f.insert(id, (g + h, g));
self.groups.entry((g, h)).or_default().insert(id);
}
fn finish(self, outcome: Outcome<G::State, G::Action, G::Cost>) -> GraphResult<G> {
SearchResult {
outcome,
stats: self.stats,
}
}
}
fn potential<C: CostExt>(budget: f64, g: C, h: C) -> f64 {
let h = h.to_f64();
if h > 0.0 {
(budget - g.to_f64()) / h
} else {
f64::INFINITY
}
}