use core::hash::Hash;
use alloc::vec::Vec;
use crate::bounds::{Explorer, Run, gap, 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 VpiRtdpConfig<B = Limits, O = ()> {
pub base: Config<B, O>,
pub alpha: f64,
pub beta: f64,
pub tau: f64,
}
impl Default for VpiRtdpConfig {
fn default() -> Self {
Self::new(Config::default())
}
}
impl<B, O> VpiRtdpConfig<B, O> {
#[must_use]
pub fn new(base: Config<B, O>) -> Self {
Self {
base,
alpha: 0.001,
beta: 0.95,
tau: crate::BrtdpConfig::DEFAULT_TAU,
}
}
#[must_use]
pub fn with_tau(self, tau: f64) -> Self {
Self { tau, ..self }
}
#[must_use]
pub fn with_alpha(self, alpha: f64) -> Self {
Self { alpha, ..self }
}
#[must_use]
pub fn with_beta(self, beta: f64) -> Self {
Self { beta, ..self }
}
fn validate<S>(&self) -> Result<(), Error<S>> {
if !(0.0..=1.0).contains(&self.alpha) {
return Err(Error::InvalidConfig {
reason: "alpha must lie in [0, 1]",
});
}
if !(self.beta > 0.0 && self.beta <= 1.0) {
return Err(Error::InvalidConfig {
reason: "beta must lie in (0, 1]",
});
}
if !(self.tau.is_finite() && self.tau > 1.0) {
return Err(Error::InvalidConfig {
reason: "tau must be finite and greater than 1",
});
}
Ok(())
}
}
impl<B, O> From<Config<B, O>> for VpiRtdpConfig<B, O> {
fn from(base: Config<B, O>) -> Self {
Self::new(base)
}
}
pub fn vpi_rtdp<M, G, L, U, B, O>(
mdp: &M,
initial: M::State,
goal: &G,
lower: L,
upper: U,
config: VpiRtdpConfig<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::Vpi(Vpi {
alpha: config.alpha,
beta: config.beta,
tau: config.tau,
threshold: 0.0,
means: Vec::new(),
});
solve((mdp, initial, goal), lower, upper, config.base, explorer)
}
pub(crate) struct Vpi {
alpha: f64,
beta: f64,
tau: f64,
threshold: f64,
means: Vec<f64>,
}
impl Vpi {
pub(crate) fn set_threshold(&mut self, initial_gap: f64) {
self.threshold = self.beta * initial_gap;
}
pub(crate) fn tau(&self) -> f64 {
self.tau
}
}
impl<M: Mdp, G, L, U, B, O> Run<'_, M, G, L, U, B, O> {
pub(crate) fn vpi_next(&mut self, state: Id, index: u32) -> Option<Id> {
let Explorer::Vpi(vpi) = &self.explorer else {
unreachable!("only VPI-RTDP runs choose by value of information");
};
let (alpha, tau, threshold) = (vpi.alpha, vpi.tau, vpi.threshold);
let u = self.rng.next_unit();
let (total, largest) = self.gap_weights(index);
if largest > threshold {
return self.pick_weighted(index, total, u);
}
let information = self.information_weights(state, index);
if information > 0.0 {
return self.pick_weighted(index, information, u);
}
self.gap_weights(index);
if total > 0.0 && total >= self.gap(self.start) / tau {
return self.pick_weighted(index, total, u);
}
let r = self.rng.next_unit();
if r < alpha && total > 0.0 {
return self.pick_weighted(index, total, u);
}
None
}
fn information_weights(&mut self, state: Id, index: u32) -> f64 {
let Explorer::Vpi(vpi) = &mut self.explorer else {
unreachable!("only VPI-RTDP runs choose by value of information");
};
let mut means = core::mem::take(&mut vpi.means);
means.clear();
means.extend(
self.space
.actions_of(state)
.map(|(action, entry)| entry.cost + self.expected_midpoint(action)),
);
let mut weights = core::mem::take(&mut self.weights);
weights.clear();
let (first, _) = self.space.node(state).actions;
for outcome in self.space.outcomes(index) {
weights.push(self.information(state, index - first, outcome.target, &means));
}
let total = weights.iter().sum();
self.weights = weights;
if let Explorer::Vpi(vpi) = &mut self.explorer {
vpi.means = means;
}
total
}
fn expected_midpoint(&self, index: u32) -> f64 {
self.space
.outcomes(index)
.iter()
.map(|outcome| outcome.probability * self.midpoint(outcome.target))
.sum()
}
fn midpoint(&self, id: Id) -> f64 {
f64::midpoint(self.space.node(id).value, self.upper[id as usize])
}
fn information(&self, state: Id, greedy: u32, t: Id, means: &[f64]) -> f64 {
let (lower, upper) = (self.space.node(t).value, self.upper[t as usize]);
if gap(lower, upper) <= 0.0 {
return 0.0;
}
let midpoint = self.midpoint(t);
let (first, _) = self.space.node(state).actions;
let greedy_mean = means[greedy as usize];
let greedy_probability = self.probability_of(first + greedy, t);
let mut best = 0.0_f64;
for (position, &mean) in means.iter().enumerate() {
let position = u32::try_from(position).expect("action positions fit u32");
if position == greedy || !mean.is_finite() {
continue;
}
let slope = greedy_probability - self.probability_of(first + position, t);
let gain = |v: f64| (greedy_mean - mean) + slope * (v - midpoint);
best = best.max(average_positive_part(gain(lower), gain(upper)));
}
best
}
fn probability_of(&self, index: u32, t: Id) -> f64 {
self.space
.outcomes(index)
.iter()
.filter(|outcome| outcome.target == t)
.map(|outcome| outcome.probability)
.sum()
}
}
fn average_positive_part(at_start: f64, at_end: f64) -> f64 {
if at_start >= 0.0 && at_end >= 0.0 {
f64::midpoint(at_start, at_end)
} else if at_start <= 0.0 && at_end <= 0.0 {
0.0
} else {
let (positive, negative) = (at_start.max(at_end), at_start.min(at_end));
positive * positive / (2.0 * (positive - negative))
}
}
#[cfg(test)]
mod tests {
use super::average_positive_part;
#[test]
fn average_positive_part_is_the_mean_gain() {
assert_eq!(average_positive_part(2.0, 4.0), 3.0);
assert_eq!(average_positive_part(-2.0, -4.0), 0.0);
assert_eq!(average_positive_part(2.0, -2.0), 0.5);
assert_eq!(average_positive_part(-2.0, 2.0), 0.5);
}
}