use core::hash::Hash;
use alloc::vec::Vec;
use crate::bounds::{Explorer, Run, solve};
use crate::budget::{Budget, Limits, Stats};
use crate::config::Config;
use crate::error::Error;
use crate::model::{Goal, Heuristic, Mdp};
use crate::observer::Observer;
use crate::solution::SolveResult;
use crate::space::Id;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrtdpConfig<B = Limits, O = ()> {
pub base: Config<B, O>,
pub initial_depth: f64,
pub depth_factor: f64,
}
impl Default for FrtdpConfig {
fn default() -> Self {
Self::new(Config::default())
}
}
impl<B, O> FrtdpConfig<B, O> {
#[must_use]
pub fn new(base: Config<B, O>) -> Self {
Self {
base,
initial_depth: 10.0,
depth_factor: 1.1,
}
}
#[must_use]
pub fn with_depth(self, initial_depth: f64, depth_factor: f64) -> Self {
Self {
initial_depth,
depth_factor,
..self
}
}
fn validate<S>(&self) -> Result<(), Error<S>> {
let valid = |x: f64| x.is_finite() && x >= 1.0;
if valid(self.initial_depth) && valid(self.depth_factor) {
Ok(())
} else {
Err(Error::InvalidConfig {
reason: "initial_depth and depth_factor must be finite and at least 1",
})
}
}
}
impl<B, O> From<Config<B, O>> for FrtdpConfig<B, O> {
fn from(base: Config<B, O>) -> Self {
Self::new(base)
}
}
pub fn frtdp<M, G, L, U, B, O>(
mdp: &M,
initial: M::State,
goal: &G,
lower: L,
upper: U,
config: FrtdpConfig<B, O>,
) -> SolveResult<M>
where
M: Mdp,
M::State: Clone + Eq + Hash,
G: Goal<M::State>,
L: Heuristic<M::State, f64>,
U: Heuristic<M::State, f64>,
B: Budget<Stats>,
O: Observer,
{
config.validate()?;
let explorer = Explorer::Frtdp(Focus::new(config.initial_depth, config.depth_factor));
solve((mdp, initial, goal), lower, upper, config.base, explorer)
}
pub(crate) struct Focus {
pub(crate) priority: Vec<f64>,
depth_limit: f64,
depth_factor: f64,
path_probability: f64,
early: (f64, u32),
late: (f64, u32),
}
impl Focus {
fn new(initial_depth: f64, depth_factor: f64) -> Self {
Self {
priority: Vec::new(),
depth_limit: initial_depth,
depth_factor,
path_probability: 1.0,
early: (0.0, 0),
late: (0.0, 0),
}
}
pub(crate) fn start_trial(&mut self) {
self.path_probability = 1.0;
self.early = (0.0, 0);
self.late = (0.0, 0);
}
pub(crate) fn end_trial(&mut self) {
let average = |(sum, count): (f64, u32)| {
if count == 0 {
0.0
} else {
sum / f64::from(count)
}
};
if average(self.late) >= average(self.early) {
self.depth_limit *= self.depth_factor;
}
}
fn track(&mut self, quality: f64, depth: f64) {
let part = if depth > self.depth_limit / self.depth_factor {
&mut self.late
} else {
&mut self.early
};
part.0 += quality;
part.1 = part.1.saturating_add(1);
}
}
impl<M: Mdp, G, L, U, B, O> Run<'_, M, G, L, U, B, O> {
fn focus(&mut self) -> &mut Focus {
match &mut self.explorer {
Explorer::Frtdp(focus) => focus,
_ => unreachable!("only FRTDP runs ask for their focus"),
}
}
fn excess(&self, state: Id) -> f64 {
self.gap(state) - self.epsilon / 2.0
}
pub(crate) fn update_priority(&mut self, state: Id, action: Option<u32>) {
let mut priority = self.excess(state);
if let Some(action) = action {
let (_, best) = self.best_successor(action);
priority = priority.min(best);
}
self.focus().priority[state as usize] = priority;
}
fn best_successor(&self, index: u32) -> (Id, f64) {
let Explorer::Frtdp(focus) = &self.explorer else {
unreachable!("only FRTDP runs have priorities");
};
let mut best = (0, f64::NEG_INFINITY);
for outcome in self.space.outcomes(index) {
let score = outcome.probability * focus.priority[outcome.target as usize];
if score > best.1 {
best = (outcome.target, score);
}
}
best
}
pub(crate) fn frtdp_next(&mut self, state: Id, index: u32, depth: usize) -> Option<Id> {
let depth = f64::from(u32::try_from(depth).unwrap_or(u32::MAX));
let change = self.last_change;
let focus = self.focus();
focus.track(change * focus.path_probability, depth);
if self.excess(state) <= 0.0 || depth >= self.focus().depth_limit {
return None;
}
let (next, _) = self.best_successor(index);
let probability: f64 = self
.space
.outcomes(index)
.iter()
.filter(|outcome| outcome.target == next)
.map(|outcome| outcome.probability)
.sum();
self.focus().path_probability *= probability;
Some(next)
}
}