mod update;
use alloc::vec::Vec;
use core::hash::Hash;
use search_core::{Budget, Cost, Goal, Heuristic};
use crate::best_first::Order;
use crate::cost::{CostExt, Weight};
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 lhb_gbfs<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).phase(Order::H, 1);
search.trial(start, table, budget, update::limited_horizon)
}
#[expect(
clippy::too_many_arguments,
reason = "the lookahead agents' arguments plus BWAS's weight and batch size"
)]
pub fn lhb_bwa_star<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
lookahead: usize,
weight: Weight,
batch: 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>,
{
assert!(batch > 0, "a batch needs at least one state");
let search = Lookahead::new(graph, goal, lookahead).phase(Order::Weighted(weight), batch);
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)
}
type Edge<G> = (
<G as Successors>::Action,
<G as Successors>::State,
<G as Successors>::Cost,
);
pub(super) fn lss_lrta_step<G, T, H>(
graph: &G,
start: G::State,
goal: &T,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
lookahead: usize,
stats: &mut Stats,
) -> (Option<Edge<G>>, u64)
where
G: Successors,
G::State: Clone + Hash + Eq,
G::Action: Clone,
T: Goal<G::State> + ?Sized,
H: Heuristic<G::State, G::Cost>,
{
let mut search = Lookahead::new(graph, goal, lookahead);
let mut unlimited = Limits::NONE;
let frontier = search.search(start, table, &mut unlimited, stats);
let changed = update::dijkstra(&search, frontier, table);
let Frontier::Target(target) = frontier else {
return (None, changed);
};
let mut first = None;
let mut node = target;
while let Some((parent, action, cost)) = search.space.parent(node) {
first = Some((action.clone(), node, cost));
node = parent;
}
let first = first.map(|(action, node, cost)| (action, search.space.state(node).clone(), cost));
(first, changed)
}
#[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,
order: Order,
batch: usize,
selected: Vec<NodeId>,
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,
order: Order::Weighted(Weight::ONE),
batch: 1,
selected: Vec::new(),
space: SearchSpace::seed([], goal).0,
h: Vec::new(),
status: Vec::new(),
children: Vec::new(),
edges: Vec::new(),
open: OpenList::new(),
buffer: Vec::new(),
}
}
fn phase(self, order: Order, batch: usize) -> Self {
Self {
order,
batch,
..self
}
}
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 expansions == self.limit {
return Frontier::Target(node);
}
let mut selected = core::mem::take(&mut self.selected);
selected.clear();
while selected.len() < self.batch && expansions + selected.len() < self.limit {
let Some(node) = self.peek() else {
break;
};
if self.goal.is_goal(self.space.state(node)) {
self.selected = selected;
return Frontier::Target(node);
}
self.pop();
selected.push(node);
}
for &node in &selected {
if budget.exhausted(stats) {
self.selected = selected;
return Frontier::Limit;
}
self.expand(node, table, stats);
expansions += 1;
}
self.selected = selected;
}
}
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 pop(&mut self) {
let (statuses, space) = (&self.status, &self.space);
self.open
.pop_where(|node, g| statuses[node] == Status::Open && g == space.g(node));
}
fn expand<H: Heuristic<G::State, G::Cost>>(
&mut self,
node: NodeId,
table: &mut LearnedHeuristic<G::State, G::Cost, H>,
stats: &mut Stats,
) {
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) {
let improve = self.order.reopens();
if let Reach::Improved(_) = self.space.reach(next, parent, action, cost, improve) {
self.reopen(id, stats);
}
id
} else {
let h = table.get(&next);
let Reach::New(id) = self.space.reach(next, parent, action, cost, false) 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, self.order.key(g, 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
}
}