use alloc::vec::Vec;
use core::cmp::Reverse;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::GraphResult;
use crate::cost::Extended;
use crate::depth_first::{distinct, goal_root};
use crate::keyed_set::KeyedSet;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
use crate::problem::{Successors, collect_successors};
pub fn sma_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
heuristic: H,
memory: usize,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
sma_star_multi(graph, [start], goal, heuristic, memory, budget)
}
pub fn sma_star_multi<G, T, H>(
graph: &G,
starts: impl IntoIterator<Item = G::State>,
goal: &T,
heuristic: H,
memory: usize,
budget: impl Budget<Stats>,
) -> GraphResult<G>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let roots = distinct(starts);
if let Some(solution) = goal_root(&roots, goal) {
return SearchResult {
outcome: Outcome::Found(solution),
stats: Stats::default(),
};
}
let mut search = Sma {
graph,
goal,
heuristic,
memory,
roots: roots.len(),
nodes: Vec::new(),
free: Vec::new(),
open: KeyedSet::new(),
leaves: KeyedSet::new(),
live: 0,
created: 0,
cut: false,
stats: Stats::default(),
};
let outcome = if roots.len() > memory {
Outcome::Cutoff
} else {
search.run(roots, budget)
};
SearchResult {
outcome,
stats: search.stats,
}
}
struct Node<S, A, C> {
state: S,
via: Option<(A, C)>,
parent: Option<usize>,
edge: usize,
depth: usize,
g: C,
value: Extended<C>,
children: Vec<usize>,
forgotten: Vec<(usize, Extended<C>)>,
expanded: bool,
seq: u64,
}
type GraphNode<G> =
Node<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;
type OpenKey<C> = (Extended<C>, Reverse<usize>, u64);
type LeafKey<C> = (Reverse<Extended<C>>, usize, u64);
struct Sma<'a, G: Successors, T: ?Sized, H> {
graph: &'a G,
goal: &'a T,
heuristic: H,
memory: usize,
roots: usize,
nodes: Vec<Option<GraphNode<G>>>,
free: Vec<usize>,
open: KeyedSet<OpenKey<G::Cost>>,
leaves: KeyedSet<LeafKey<G::Cost>>,
live: usize,
created: u64,
cut: bool,
stats: Stats,
}
impl<G, T, H> Sma<'_, G, T, H>
where
G: Successors,
G::State: Clone + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
fn run(
&mut self,
roots: Vec<G::State>,
mut budget: impl Budget<Stats>,
) -> Outcome<G::State, G::Action, G::Cost> {
for (edge, state) in roots.into_iter().enumerate() {
let value = Extended::f(G::Cost::ZERO, self.heuristic.estimate(&state));
let id = self.create(Node {
state,
via: None,
parent: None,
edge,
depth: 0,
g: G::Cost::ZERO,
value,
children: Vec::new(),
forgotten: Vec::new(),
expanded: false,
seq: 0,
});
self.refresh(id);
}
loop {
let Some((&(key, _, _), id)) = self.open.first() else {
return self.exhausted();
};
if key == Extended::Infinite {
return self.exhausted();
}
if self.goal.is_goal(&self.node(id).state) {
return Outcome::Found(self.solution(id));
}
if budget.exhausted(&self.stats) {
return Outcome::LimitReached;
}
self.generate(id, key);
self.back_up(id);
self.prune();
}
}
fn exhausted(&self) -> Outcome<G::State, G::Action, G::Cost> {
if self.cut {
Outcome::Cutoff
} else {
Outcome::Unsolvable
}
}
fn generate(&mut self, id: usize, bound: Extended<G::Cost>) {
let mut edges = Vec::new();
self.stats.expanded += 1;
self.stats.generated += collect_successors(self.graph, &self.node(id).state, &mut edges);
let node = self.node_mut(id);
let wanted = if node.expanded {
let best = (0..node.forgotten.len())
.min_by_key(|&index| node.forgotten[index].1)
.expect("an expanded node is open only with forgotten children");
Some(node.forgotten.swap_remove(best))
} else {
node.expanded = true;
None
};
for (edge, (action, state, cost)) in edges.into_iter().enumerate() {
let value = match wanted {
Some((forgotten, value)) if forgotten == edge => value,
Some(_) => continue,
None => bound,
};
self.add_child(id, edge, action, state, cost, value);
}
self.refresh(id);
}
fn add_child(
&mut self,
id: usize,
edge: usize,
action: G::Action,
state: G::State,
cost: G::Cost,
bound: Extended<G::Cost>,
) {
if self.on_path(id, &state) {
return;
}
let (g, depth) = (self.node(id).g + cost, self.node(id).depth + 1);
let needed = self.roots + depth;
if needed > self.memory || (needed == self.memory && !self.goal.is_goal(&state)) {
self.cut = true;
return;
}
let Some(h) = self.heuristic.estimate(&state) else {
return;
};
let child = self.create(Node {
state,
via: Some((action, cost)),
parent: Some(id),
edge,
depth,
g,
value: bound.max(Extended::Finite(g.saturating_add(h))),
children: Vec::new(),
forgotten: Vec::new(),
expanded: false,
seq: 0,
});
self.node_mut(id).children.push(child);
self.refresh(child);
}
fn prune(&mut self) {
while self.live > self.memory {
let (_, leaf) = self
.leaves
.first()
.expect("only starts are not prunable, and they fit");
self.forget(leaf);
}
}
fn forget(&mut self, id: usize) {
self.open.remove(id);
self.leaves.remove(id);
let node = self.nodes[id].take().expect("a live node");
self.free.push(id);
self.live -= 1;
let parent = node.parent.expect("starts are never forgotten");
let entry = self.node_mut(parent);
entry.children.retain(|&child| child != id);
entry.forgotten.push((node.edge, node.value));
self.refresh(parent);
}
fn back_up(&mut self, mut id: usize) {
loop {
let node = self.node(id);
let best = node
.children
.iter()
.map(|&child| self.node(child).value)
.fold(smallest_forgotten(node), Extended::min);
let value = node.value.max(best);
if value == node.value {
return;
}
self.node_mut(id).value = value;
self.refresh(id);
match self.node(id).parent {
Some(parent) => id = parent,
None => return,
}
}
}
fn refresh(&mut self, id: usize) {
let node = self.node(id);
let leaf = node.children.is_empty();
let key = if leaf {
Some(node.value)
} else {
Some(smallest_forgotten(node)).filter(|&f| f != Extended::Infinite)
};
let (depth, seq, value, prunable) = (
node.depth,
node.seq,
node.value,
leaf && node.parent.is_some(),
);
match key {
Some(key) => self.open.insert(id, (key, Reverse(depth), seq)),
None => {
self.open.remove(id);
}
}
if prunable {
self.leaves.insert(id, (Reverse(value), depth, seq));
} else {
self.leaves.remove(id);
}
}
fn on_path(&self, mut id: usize, state: &G::State) -> bool {
loop {
let node = self.node(id);
if node.state == *state {
return true;
}
match node.parent {
Some(parent) => id = parent,
None => return false,
}
}
}
fn create(&mut self, mut node: Node<G::State, G::Action, G::Cost>) -> usize {
node.seq = self.created;
self.created += 1;
self.live += 1;
if let Some(id) = self.free.pop() {
self.nodes[id] = Some(node);
return id;
}
self.nodes.push(Some(node));
self.nodes.len() - 1
}
fn solution(&self, id: usize) -> Solution<G::State, G::Action, G::Cost> {
let mut states = Vec::new();
let mut actions = Vec::new();
let mut cost = G::Cost::ZERO;
let mut at = Some(id);
while let Some(current) = at {
let node = self.node(current);
states.push(node.state.clone());
if let Some((action, edge_cost)) = &node.via {
actions.push(action.clone());
cost = cost + *edge_cost;
}
at = node.parent;
}
states.reverse();
actions.reverse();
Solution {
states,
actions,
cost,
}
}
fn node(&self, id: usize) -> &Node<G::State, G::Action, G::Cost> {
self.nodes[id].as_ref().expect("a live node")
}
fn node_mut(&mut self, id: usize) -> &mut Node<G::State, G::Action, G::Cost> {
self.nodes[id].as_mut().expect("a live node")
}
}
fn smallest_forgotten<S, A, C: Cost>(node: &Node<S, A, C>) -> Extended<C> {
node.forgotten
.iter()
.map(|&(_, value)| value)
.min()
.unwrap_or(Extended::Infinite)
}