use core::hash::Hash;
use search_core::{Cost, Zero, heuristic_fn};
use super::lookahead::lss_lrta_step;
use crate::cost::Weight;
use crate::dynamic::{DynamicGraph, Incremental};
use crate::outcome::{Limits, Stats};
use crate::problem::Successors;
use crate::real_time::{End, LearnedHeuristic, Trajectory, TrialResult, TrialStats};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentStep {
Arrived,
Informed,
Partial,
Waiting,
}
pub struct RealTimeDStar<V, C, D> {
core: Incremental<V, C, D>,
goal: V,
local_share: Weight,
table: LearnedHeuristic<V, C, Zero>,
path: Trajectory<V, (), C>,
stats: Stats,
trial: TrialStats,
waiting: bool,
changed: bool,
}
impl<V, C, D> RealTimeDStar<V, C, D>
where
V: Clone + Hash + Eq,
C: Cost,
D: FnMut(&V, &V) -> C,
{
pub fn new<G: DynamicGraph<Vertex = V, Cost = C>>(
_graph: &G,
start: V,
goal: V,
heuristic: D,
local_share: Weight,
) -> Self {
assert!(
local_share.numerator() <= local_share.denominator(),
"the local share is a fraction of the expansions, at most 1"
);
Self {
core: Incremental::new(false, goal.clone(), start.clone(), heuristic, None),
goal,
local_share,
table: LearnedHeuristic::new(Zero),
path: Trajectory::new(start),
stats: Stats::default(),
trial: TrialStats::default(),
waiting: false,
changed: false,
}
}
pub fn step<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
expansions: usize,
) -> AgentStep {
assert!(
expansions > 0,
"a real-time step needs at least one expansion"
);
let position = self.path.current().clone();
if position == self.goal {
return AgentStep::Arrived;
}
let (global, local) = self.split(expansions);
let limit = Limits::expansions(u64::try_from(global).unwrap_or(u64::MAX));
let (reached, mut stats) = self.core.repair(graph, limit);
let mut updates = 0;
let choice = if reached {
self.informed_step(graph, &position)
.map(|edge| (edge, AgentStep::Informed))
} else {
let (edge, changed) = self.local_step(graph, position, local, &mut stats);
updates = changed;
edge.map(|edge| (edge, AgentStep::Partial))
};
self.stats = self.stats.plus(stats);
self.trial.record_step(stats.expanded, updates);
self.waiting = choice.is_none();
let Some(((next, cost), kind)) = choice else {
return AgentStep::Waiting;
};
self.path.travel((), next.clone(), cost);
self.trial.moves += 1;
self.core.move_target(next);
kind
}
pub fn edge_changed<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
from: &V,
to: &V,
) {
self.core.edge_changed(graph, from, to);
self.changed = true;
}
#[must_use]
pub fn position(&self) -> &V {
self.path.current()
}
#[must_use]
pub fn stats(&self) -> Stats {
self.stats
}
#[must_use]
pub fn into_trial(self) -> TrialResult<V, (), C> {
let end = if *self.path.current() == self.goal {
End::Goal
} else if self.waiting {
End::Unsolvable
} else {
End::Limit
};
self.path.finish(end, self.stats, self.trial)
}
fn split(&self, expansions: usize) -> (usize, usize) {
let numerator = u128::from(self.local_share.numerator());
let denominator = u128::from(self.local_share.denominator());
let local = expansions as u128 * numerator / denominator;
let local = usize::try_from(local)
.expect("the share is at most 1")
.max(1);
(expansions - local, local)
}
fn informed_step<G: DynamicGraph<Vertex = V, Cost = C>>(
&self,
graph: &G,
position: &V,
) -> Option<(V, C)> {
let mut best: Option<(V, C, C)> = None;
graph.successors(position, |next, cost| {
let Some(g) = self.core.g(&next) else {
return;
};
let value = cost.saturating_add(g);
if best.as_ref().is_none_or(|&(_, _, old)| value < old) {
best = Some((next, cost, value));
}
});
best.map(|(next, cost, _)| (next, cost))
}
fn local_step<G: DynamicGraph<Vertex = V, Cost = C>>(
&mut self,
graph: &G,
position: V,
local: usize,
stats: &mut Stats,
) -> (Option<(V, C)>, u64) {
if core::mem::take(&mut self.changed) {
self.table.forget_dead_ends();
}
let goal = &self.goal;
let heuristic = self.core.heuristic();
let table = core::mem::replace(&mut self.table, LearnedHeuristic::new(Zero));
let mut table = table.rebase(heuristic_fn(|state: &V| Some(heuristic(state, goal))));
let is_goal = |state: &V| state == goal;
let (edge, changed) = lss_lrta_step(
&Forward(graph),
position,
&is_goal,
&mut table,
local,
stats,
);
self.table = table.rebase(Zero);
(edge.map(|((), next, cost)| (next, cost)), changed)
}
}
struct Forward<'a, G>(&'a G);
impl<G: DynamicGraph> Successors for Forward<'_, G> {
type State = G::Vertex;
type Action = ();
type Cost = G::Cost;
fn successors(
&self,
state: &Self::State,
mut emit: impl FnMut(Self::Action, Self::State, Self::Cost),
) {
self.0.successors(state, |to, cost| emit((), to, cost));
}
}