use alloc::vec::Vec;
use rand_core::Rng;
use crate::error::Error;
use crate::pomdp::{Pomdp, below, check_reward};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BeliefFilter {
pub particles: usize,
pub max_attempts: usize,
pub reinvigorate: usize,
}
impl BeliefFilter {
#[must_use]
pub fn with_particles(self, particles: usize) -> Self {
Self { particles, ..self }
}
#[must_use]
pub fn with_max_attempts(self, max_attempts: usize) -> Self {
Self {
max_attempts,
..self
}
}
#[must_use]
pub fn with_reinvigorate(self, reinvigorate: usize) -> Self {
Self {
reinvigorate,
..self
}
}
}
impl Default for BeliefFilter {
fn default() -> Self {
Self {
particles: 1_000,
max_attempts: 100_000,
reinvigorate: 0,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct BeliefUpdate<S> {
pub particles: Vec<S>,
pub accepted: usize,
pub attempts: usize,
pub reinvigorated: usize,
}
pub fn update_belief<P, R, F>(
pomdp: &P,
belief: &[P::State],
action: &P::Action,
observation: &P::Observation,
filter: BeliefFilter,
rng: &mut R,
mut transform: F,
) -> Result<BeliefUpdate<P::State>, Error<P::State>>
where
P: Pomdp,
P::State: Clone,
P::Observation: PartialEq,
R: Rng + ?Sized,
F: FnMut(&P::State, &mut R) -> P::State,
{
if filter.particles == 0 || filter.max_attempts == 0 {
return Err(Error::InvalidConfig {
reason: "the belief filter needs at least one particle and one attempt",
});
}
if belief.is_empty() {
return Err(Error::EmptyBelief);
}
let (mut particles, attempts) = reject(pomdp, belief, action, observation, filter, rng)?;
let accepted = particles.len();
if accepted == 0 {
return Err(Error::BeliefDepleted { attempts });
}
let reinvigorated = filter.particles - accepted + filter.reinvigorate;
for _ in 0..reinvigorated {
let source = &particles[below(rng, accepted)];
let particle = transform(source, rng);
particles.push(particle);
}
Ok(BeliefUpdate {
particles,
accepted,
attempts,
reinvigorated,
})
}
type Accepted<S> = (Vec<S>, usize);
fn reject<P, R>(
pomdp: &P,
belief: &[P::State],
action: &P::Action,
observation: &P::Observation,
filter: BeliefFilter,
rng: &mut R,
) -> Result<Accepted<P::State>, Error<P::State>>
where
P: Pomdp,
P::State: Clone,
P::Observation: PartialEq,
R: Rng + ?Sized,
{
let mut particles = Vec::with_capacity(filter.particles + filter.reinvigorate);
let mut attempts = 0;
while particles.len() < filter.particles && attempts < filter.max_attempts {
attempts += 1;
let state = &belief[below(rng, belief.len())];
let step = pomdp.step(state, action, rng);
check_reward(state, step.reward)?;
if !step.terminal && step.observation == *observation {
particles.push(step.state);
}
}
Ok((particles, attempts))
}