use crate::filter::FilterError;
use crate::math;
use crate::special::ln_gamma;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NormalGamma {
pub mean: f64,
pub precision: f64,
pub shape: f64,
pub rate: f64,
}
impl NormalGamma {
pub const STANDARD: Self = Self {
mean: 0.0,
precision: 1.0,
shape: 1.0,
rate: 1.0,
};
fn is_valid(&self) -> bool {
let finite = [self.mean, self.precision, self.shape, self.rate]
.iter()
.all(|v| v.is_finite());
finite && self.precision > 0.0 && self.shape >= 0.5 && self.rate > 0.0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct Run {
log_weight: f64,
length: usize,
posterior: NormalGamma,
}
impl Run {
const fn fresh(prior: NormalGamma, log_weight: f64) -> Self {
Self {
log_weight,
length: 0,
posterior: prior,
}
}
fn log_predictive(&self, x: f64) -> f64 {
let NormalGamma {
mean,
precision,
shape,
rate,
} = self.posterior;
let scale2 = rate * (precision + 1.0) / (shape * precision);
let degrees = 2.0 * shape;
let d = x - mean;
ln_gamma(shape + 0.5)
- ln_gamma(shape)
- 0.5 * math::ln(degrees * core::f64::consts::PI * scale2)
- (shape + 0.5) * math::ln(1.0 + d * d / (degrees * scale2))
}
fn observe(&mut self, x: f64) {
let p = &mut self.posterior;
let d = x - p.mean;
p.rate += p.precision * d * d / (2.0 * (p.precision + 1.0));
p.mean += d / (p.precision + 1.0);
p.precision += 1.0;
p.shape += 0.5;
self.length = self.length.saturating_add(1);
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Bocpd<const R: usize> {
log_hazard: f64,
log_survival: f64,
prior: NormalGamma,
runs: [Run; R],
count: usize,
}
impl<const R: usize> Bocpd<R> {
pub fn new(hazard: f64, prior: NormalGamma) -> Result<Self, FilterError> {
if !(hazard > 0.0 && hazard < 1.0 && prior.is_valid()) {
return Err(FilterError::InvalidParameter);
}
if R < 2 {
return Err(FilterError::Capacity {
needed: 2,
capacity: R,
});
}
Ok(Self {
log_hazard: math::ln(hazard),
log_survival: math::ln(1.0 - hazard),
prior,
runs: [Run::fresh(prior, 0.0); R],
count: 0,
})
}
pub fn update(&mut self, x: f64) {
if !(x * x).is_finite() {
return;
}
self.start_segment();
for run in &mut self.runs[..self.count] {
run.log_weight += run.log_predictive(x);
run.observe(x);
}
self.normalise();
}
#[must_use]
pub fn run_length(&self) -> usize {
self.runs[..self.count]
.iter()
.fold(None, |best: Option<&Run>, run| match best {
Some(b) if b.log_weight >= run.log_weight => best,
_ => Some(run),
})
.map_or(0, |run| run.length)
}
#[must_use]
pub fn probability_within(&self, w: usize) -> f64 {
self.runs[..self.count]
.iter()
.filter(|run| run.length <= w)
.map(|run| math::exp(run.log_weight))
.sum()
}
pub const fn reset(&mut self) {
self.count = 0;
}
fn start_segment(&mut self) {
if self.count == R {
self.merge_oldest();
}
let log_weight = if self.count == 0 {
0.0
} else {
self.log_hazard
};
self.runs.copy_within(..self.count, 1);
for run in &mut self.runs[1..=self.count] {
run.log_weight += self.log_survival;
}
self.runs[0] = Run::fresh(self.prior, log_weight);
self.count += 1;
}
fn merge_oldest(&mut self) {
let (older, newer) = (self.runs[R - 1], self.runs[R - 2]);
let kept = if newer.log_weight >= older.log_weight {
newer
} else {
older
};
self.runs[R - 2] = Run {
log_weight: log_add(older.log_weight, newer.log_weight),
..kept
};
self.count = R - 1;
}
fn normalise(&mut self) {
let runs = &mut self.runs[..self.count];
let max = runs
.iter()
.map(|run| run.log_weight)
.fold(f64::NEG_INFINITY, f64::max);
let total = max
+ math::ln(
runs.iter()
.map(|run| math::exp(run.log_weight - max))
.sum::<f64>(),
);
for run in runs {
run.log_weight -= total;
}
}
}
fn log_add(a: f64, b: f64) -> f64 {
let (high, low) = if a >= b { (a, b) } else { (b, a) };
if low == f64::NEG_INFINITY {
high
} else {
high + math::ln(1.0 + math::exp(low - high))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_first_value_starts_a_segment_with_certainty() {
let mut detector = Bocpd::<4>::new(0.1, NormalGamma::STANDARD).unwrap();
assert_eq!(detector.run_length(), 0);
detector.update(0.5);
assert_eq!(detector.run_length(), 1);
assert!((detector.probability_within(1) - 1.0).abs() < 1e-15);
detector.update(f64::NAN);
detector.update(1e300);
assert_eq!(detector.count, 1);
}
#[test]
fn keeps_at_most_r_hypotheses_and_unit_mass() {
let mut detector = Bocpd::<3>::new(0.2, NormalGamma::STANDARD).unwrap();
for t in 0..10 {
detector.update(f64::from(t % 3) - 1.0);
assert!(detector.count <= 3);
assert!((detector.probability_within(usize::MAX) - 1.0).abs() < 1e-12);
}
}
#[test]
fn rejects_invalid_parameters() {
let prior = NormalGamma::STANDARD;
for hazard in [0.0, 1.0, f64::NAN] {
assert_eq!(
Bocpd::<4>::new(hazard, prior),
Err(FilterError::InvalidParameter)
);
}
let bad = NormalGamma {
shape: 0.25,
..prior
};
assert_eq!(
Bocpd::<4>::new(0.1, bad),
Err(FilterError::InvalidParameter)
);
assert_eq!(
Bocpd::<1>::new(0.1, prior),
Err(FilterError::Capacity {
needed: 2,
capacity: 1
})
);
}
}