pub(crate) mod backup;
mod dead_ends;
pub(crate) mod expand;
use core::hash::{BuildHasher, Hash};
use alloc::vec::Vec;
use hashbrown::{DefaultHashBuilder, HashTable};
use crate::error::Error;
use crate::model::{Goal, Heuristic};
pub(crate) type Id = u32;
pub(crate) struct Problem<'a, M, G, H> {
pub(crate) mdp: &'a M,
pub(crate) goal: &'a G,
pub(crate) heuristic: H,
pub(crate) cap: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Kind {
Goal,
DeadEnd,
Open,
}
#[derive(Debug, Clone)]
pub(crate) struct Node {
pub(crate) kind: Kind,
pub(crate) value: f64,
pub(crate) solved: bool,
pub(crate) policy: Option<u32>,
pub(crate) expanded: bool,
pub(crate) actions: (u32, u32),
pub(crate) mark: u32,
}
#[derive(Debug, Clone)]
pub(crate) struct ActionEntry<A> {
pub(crate) action: A,
pub(crate) cost: f64,
pub(crate) outcomes: (u32, u32),
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Outcome {
pub(crate) target: Id,
pub(crate) probability: f64,
}
pub(crate) struct Space<S, A> {
states: Vec<S>,
nodes: Vec<Node>,
index: HashTable<Id>,
hasher: DefaultHashBuilder,
actions: Vec<ActionEntry<A>>,
outcomes: Vec<Outcome>,
cap: f64,
expanded: u64,
scratch_actions: Vec<(A, f64)>,
scratch_outcomes: Vec<(S, f64)>,
}
impl<S, A> Space<S, A> {
pub(crate) fn new(cap: f64) -> Self {
Self {
states: Vec::new(),
nodes: Vec::new(),
index: HashTable::new(),
hasher: DefaultHashBuilder::default(),
actions: Vec::new(),
outcomes: Vec::new(),
cap,
expanded: 0,
scratch_actions: Vec::new(),
scratch_outcomes: Vec::new(),
}
}
pub(crate) fn len(&self) -> usize {
self.nodes.len()
}
pub(crate) fn expanded(&self) -> u64 {
self.expanded
}
pub(crate) fn node(&self, id: Id) -> &Node {
&self.nodes[id as usize]
}
pub(crate) fn node_mut(&mut self, id: Id) -> &mut Node {
&mut self.nodes[id as usize]
}
pub(crate) fn nodes_mut(&mut self) -> &mut [Node] {
&mut self.nodes
}
pub(crate) fn state(&self, id: Id) -> &S {
&self.states[id as usize]
}
pub(crate) fn action(&self, index: u32) -> &ActionEntry<A> {
&self.actions[index as usize]
}
pub(crate) fn actions_of(&self, id: Id) -> impl Iterator<Item = (u32, &ActionEntry<A>)> {
let (start, end) = self.node(id).actions;
(start..end).zip(&self.actions[start as usize..end as usize])
}
pub(crate) fn outcomes(&self, index: u32) -> &[Outcome] {
let (start, end) = self.action(index).outcomes;
&self.outcomes[start as usize..end as usize]
}
pub(crate) fn action_count(&self) -> usize {
self.actions.len()
}
pub(crate) fn outcome_count(&self) -> usize {
self.outcomes.len()
}
pub(crate) fn cap(&self) -> f64 {
self.cap
}
}
impl<S: Hash + Eq, A> Space<S, A> {
pub(crate) fn find(&self, state: &S) -> Option<Id> {
let hash = self.hasher.hash_one(state);
self.index
.find(hash, |&id| self.states[id as usize] == *state)
.copied()
}
}
impl<S: Hash + Eq + Clone, A> Space<S, A> {
pub(crate) fn intern<M, G, H>(
&mut self,
problem: &mut Problem<'_, M, G, H>,
state: S,
) -> Result<Id, Error<S>>
where
G: Goal<S>,
H: Heuristic<S, f64>,
{
let hash = self.hasher.hash_one(&state);
if let Some(&id) = self
.index
.find(hash, |&id| self.states[id as usize] == state)
{
return Ok(id);
}
let node = initial_node(problem, &state)?;
let id = Id::try_from(self.nodes.len()).expect("at most u32::MAX states fit an id");
let (states, hasher) = (&self.states, &self.hasher);
self.index
.insert_unique(hash, id, |&other| hasher.hash_one(&states[other as usize]));
self.states.push(state);
self.nodes.push(node);
Ok(id)
}
}
fn initial_node<M, G, H, S>(problem: &mut Problem<'_, M, G, H>, state: &S) -> Result<Node, Error<S>>
where
S: Clone,
G: Goal<S>,
H: Heuristic<S, f64>,
{
let (kind, value) = if problem.goal.is_goal(state) {
(Kind::Goal, 0.0)
} else {
match problem.heuristic.estimate(state) {
Some(h) if is_invalid_estimate(h) => {
return Err(Error::InvalidHeuristic {
state: state.clone(),
});
}
Some(h) if h < f64::INFINITY => (Kind::Open, h.min(problem.cap)),
_ => (Kind::DeadEnd, problem.cap),
}
};
Ok(Node {
kind,
value,
solved: kind != Kind::Open,
policy: None,
expanded: false,
actions: (0, 0),
mark: 0,
})
}
fn is_invalid_estimate(h: f64) -> bool {
h.is_nan() || (h.is_infinite() && h < 0.0)
}
#[cfg(test)]
mod tests {
use super::{Node, Outcome};
#[test]
fn per_state_sizes_match_the_docs() {
assert_eq!(size_of::<Node>(), 32);
assert_eq!(size_of::<Outcome>(), 16);
}
}