mod dps;
mod ees;
pub use dps::{dps, dps_multi};
pub use ees::{EesEstimates, ees, ees_multi};
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::Weight;
use crate::focal::FocalList;
use crate::outcome::{Outcome, SearchResult, Stats};
use crate::problem::{Successors, collect_successors};
use crate::space::{NodeId, Reach, SearchSpace};
pub trait FocalKey<S, A, C> {
type Key: Ord + Clone;
fn start(&mut self, state: &S) -> Self::Key;
fn extend(
&mut self,
parent_key: &Self::Key,
parent: &S,
action: &A,
cost: C,
state: &S,
) -> Self::Key;
}
impl<S, A, C, F: FocalKey<S, A, C> + ?Sized> FocalKey<S, A, C> for &mut F {
type Key = F::Key;
fn start(&mut self, state: &S) -> Self::Key {
(**self).start(state)
}
fn extend(
&mut self,
parent_key: &Self::Key,
parent: &S,
action: &A,
cost: C,
state: &S,
) -> Self::Key {
(**self).extend(parent_key, parent, action, cost, state)
}
}
pub fn focal_fn<S, K: Ord + Clone, F: FnMut(&S) -> K>(f: F) -> FocalFn<F> {
FocalFn(f)
}
#[derive(Debug, Clone, Copy)]
pub struct FocalFn<F>(F);
impl<S, A, C, K: Ord + Clone, F: FnMut(&S) -> K> FocalKey<S, A, C> for FocalFn<F> {
type Key = K;
fn start(&mut self, state: &S) -> K {
(self.0)(state)
}
fn extend(&mut self, _: &K, _: &S, _: &A, _: C, state: &S) -> K {
(self.0)(state)
}
}
pub fn focal_search<G, T, H, F>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
focal: F,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
F: FocalKey<G::State, G::Action, G::Cost>,
{
focal_search_multi(graph, [start], goal, heuristic, focal, weight, budget)
}
pub fn focal_search_multi<G, T, H, F>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
focal: F,
weight: Weight,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
F: FocalKey<G::State, G::Action, G::Cost>,
{
let (space, start_goal) = SearchSpace::seed(starts, goal);
let search = FocalSearch {
graph,
heuristic,
focal,
space,
list: FocalList::new(weight),
stats: Stats::default(),
h: Vec::new(),
keys: 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)
}
struct FocalSearch<'a, G: Successors, H, F: FocalKey<G::State, G::Action, G::Cost>> {
graph: &'a G,
heuristic: H,
focal: F,
space: SearchSpace<G::State, G::Action, G::Cost>,
list: FocalList<G::Cost, F::Key>,
stats: Stats,
h: Vec<Option<G::Cost>>,
keys: Vec<Option<F::Key>>,
closed: Vec<bool>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<G, H, F> FocalSearch<'_, G, H, F>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
H: Heuristic<G::State, G::Cost>,
F: FocalKey<G::State, G::Action, 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.list.pop() {
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 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.keys.push(None);
self.closed.push(false);
if h.is_some() {
self.open(id);
}
}
fn reopen(&mut self, id: NodeId) {
if self.h[id].is_none() {
return;
}
if self.closed[id] && !self.list.contains(id) {
self.stats.reopened += 1;
}
self.open(id);
}
fn open(&mut self, id: NodeId) {
let state = self.space.state(id);
let key = match self.space.parent(id) {
None => self.focal.start(state),
Some((parent, action, cost)) => {
let parent_key = self.keys[parent]
.as_ref()
.expect("expanded nodes have keys");
self.focal
.extend(parent_key, self.space.state(parent), action, cost, state)
}
};
let g = self.space.g(id);
let h = self.h[id].expect("only live nodes are opened");
self.list.push(id, g + h, g, key.clone());
self.keys[id] = Some(key);
}
fn finish(self, outcome: Outcome<G::State, G::Action, G::Cost>) -> GraphResult<G> {
SearchResult {
outcome,
stats: self.stats,
}
}
}