mod update;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::cost::CostExt;
use crate::open_list::OpenList;
use crate::outcome::{Limits, Stats};
use crate::problem::{Successors, collect_successors};
use crate::real_time::{End, LearnedHeuristic, Trajectory, TrialResult, TrialStats};
use crate::space::{NodeId, Reach, SearchSpace};
type GraphTrial<G> =
TrialResult<<G as Successors>::State, <G as Successors>::Action, <G as Successors>::Cost>;
pub fn lss_lrta_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
lookahead: usize,
budget: impl Budget<Stats>,
) -> GraphTrial<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let search = Lookahead::new(graph, goal, lookahead);
search.trial(start, table, budget, update::dijkstra)
}
pub fn lhb_lrta_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
lookahead: usize,
budget: impl Budget<Stats>,
) -> GraphTrial<G>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let search = Lookahead::new(graph, goal, lookahead);
search.trial(start, table, budget, update::limited_horizon)
}
pub fn rtaa_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
lookahead: usize,
budget: impl Budget<Stats>,
) -> GraphTrial<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>,
{
let search = Lookahead::new(graph, goal, lookahead);
search.trial(start, table, budget, update::rtaa)
}
pub fn lhb_update<G, T, H>(
graph: &G,
sample: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
expansions: usize,
) -> u64
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
if goal.is_goal(&sample) {
return u64::from(table.set(sample, Some(G::Cost::ZERO)));
}
let mut search = Lookahead::new(graph, goal, expansions);
let mut stats = Stats::default();
let mut unlimited = Limits::NONE;
let frontier = search.search(sample, table, &mut unlimited, &mut stats);
update::limited_horizon(&search, frontier, table)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Frontier {
Target(NodeId),
Exhausted,
Limit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Open,
Closed,
Dead,
}
struct Lookahead<'a, G: Successors, T: ?Sized> {
graph: &'a G,
goal: &'a T,
limit: usize,
space: SearchSpace<G::State, G::Action, G::Cost>,
h: Vec<Option<G::Cost>>,
status: Vec<Status>,
children: Vec<bool>,
edges: Vec<(NodeId, NodeId, G::Cost)>,
open: OpenList<G::Cost>,
buffer: Vec<(G::Action, G::State, G::Cost)>,
}
impl<'a, G, T> Lookahead<'a, G, T>
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
{
fn new(graph: &'a G, goal: &'a T, limit: usize) -> Self {
Self {
graph,
goal,
limit,
space: SearchSpace::seed([], goal).0,
h: Vec::new(),
status: Vec::new(),
children: Vec::new(),
edges: Vec::new(),
open: OpenList::new(),
buffer: Vec::new(),
}
}
fn trial<H: Heuristic<G::State, G::Cost>>(
mut self,
start: G::State,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
mut budget: impl Budget<Stats>,
update: impl Fn(&Self, Frontier, &mut LearnedHeuristic<G::State, G::Cost, H>) -> u64,
) -> GraphTrial<G> {
assert!(
self.limit > 0,
"a real-time lookahead needs at least one expansion"
);
let mut path = Trajectory::new(start);
let mut stats = Stats::default();
let mut trial = TrialStats::default();
let end = loop {
if self.goal.is_goal(path.current()) {
break End::Goal;
}
let before = stats.expanded;
let frontier = self.search(path.current().clone(), table, &mut budget, &mut stats);
if frontier == Frontier::Limit {
break End::Limit;
}
let changed = update(&self, frontier, table);
trial.record_step(stats.expanded - before, changed);
let Frontier::Target(target) = frontier else {
break End::Unsolvable;
};
trial.moves += self.travel(target, &mut path);
};
path.finish(end, stats, trial)
}
fn search<H: Heuristic<G::State, G::Cost>>(
&mut self,
start: G::State,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
budget: &mut impl Budget<Stats>,
stats: &mut Stats,
) -> Frontier {
self.reset(start, table);
let mut expansions = 0;
loop {
let Some(node) = self.peek() else {
return Frontier::Exhausted;
};
if self.goal.is_goal(self.space.state(node)) || expansions == self.limit {
return Frontier::Target(node);
}
if budget.exhausted(stats) {
return Frontier::Limit;
}
self.expand(node, table, stats);
expansions += 1;
}
}
fn reset<H: Heuristic<G::State, G::Cost>>(
&mut self,
start: G::State,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
) {
self.h.clear();
self.status.clear();
self.children.clear();
self.edges.clear();
self.open.clear();
let h = table.get(&start);
self.space = SearchSpace::seed([start], self.goal).0;
self.create(0, h);
}
fn peek(&mut self) -> Option<NodeId> {
let (statuses, space) = (&self.status, &self.space);
self.open
.peek_where(|node, g| statuses[node] == Status::Open && g == space.g(node))
.map(|(node, _)| node)
}
fn expand<H: Heuristic<G::State, G::Cost>>(
&mut self,
node: NodeId,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
stats: &mut Stats,
) {
let (statuses, space) = (&self.status, &self.space);
self.open
.pop_where(|node, g| statuses[node] == Status::Open && g == space.g(node));
self.status[node] = Status::Closed;
stats.expanded += 1;
stats.generated += collect_successors(self.graph, self.space.state(node), &mut self.buffer);
self.children[node] = !self.buffer.is_empty();
let mut buffer = core::mem::take(&mut self.buffer);
for (action, next, cost) in buffer.drain(..) {
self.generate(node, action, next, cost, table, stats);
}
self.buffer = buffer;
}
fn generate<H: Heuristic<G::State, G::Cost>>(
&mut self,
parent: NodeId,
action: G::Action,
next: G::State,
cost: G::Cost,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
stats: &mut Stats,
) {
let id = if let Some(id) = self.space.find(&next) {
if let Reach::Improved(_) = self.space.reach(next, parent, action, cost, true) {
self.reopen(id, stats);
}
id
} else {
let h = table.get(&next);
let Reach::New(id) = self.space.reach(next, parent, action, cost, true) else {
unreachable!("the state is not known yet");
};
self.create(id, h);
id
};
self.edges.push((parent, id, cost));
}
fn create(&mut self, id: NodeId, h: Option<G::Cost>) {
let status = if h.is_some() {
Status::Open
} else {
Status::Dead
};
self.h.push(h);
self.status.push(status);
self.children.push(false);
self.push_open(id);
}
fn reopen(&mut self, id: NodeId, stats: &mut Stats) {
match self.status[id] {
Status::Dead => return,
Status::Closed => {
stats.reopened += 1;
self.status[id] = Status::Open;
}
Status::Open => {}
}
self.push_open(id);
}
fn push_open(&mut self, id: NodeId) {
if let Some(h) = self.h[id] {
let g = self.space.g(id);
self.open.push(id, g.saturating_add(h), g);
}
}
fn travel(&self, target: NodeId, path: &mut Trajectory<G::State, G::Action, G::Cost>) -> u64 {
let mut links = Vec::new();
let mut node = target;
while let Some((parent, action, cost)) = self.space.parent(node) {
links.push((action.clone(), node, cost));
node = parent;
}
let moves = links.len() as u64;
for (action, node, cost) in links.into_iter().rev() {
path.travel(action, self.space.state(node).clone(), cost);
}
moves
}
}