use crate::error::VeridictError;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BernoulliHypotheses {
pub p0: f64,
pub p1: f64,
}
impl BernoulliHypotheses {
pub fn validate(&self) -> Result<(), VeridictError> {
for (name, v) in [("p0", self.p0), ("p1", self.p1)] {
if !v.is_finite() || v <= 0.0 || v >= 1.0 {
return Err(VeridictError::InvalidThreshold(format!(
"{name} must be finite and in (0, 1), got {v}"
)));
}
}
if self.p0 >= self.p1 {
return Err(VeridictError::InvalidThreshold(format!(
"p0 ({}) must be strictly less than p1 ({}): this module only implements the \
one-sided p0 < p1 simple-vs-simple case",
self.p0, self.p1
)));
}
Ok(())
}
}
pub(crate) const ACTION_EPSILON: f64 = 1e-9;
pub fn phi(a: f64, p0: f64, success: bool) -> f64 {
if success {
a / p0
} else {
(1.0 - a) / (1.0 - p0)
}
}
pub fn log_phi(a: f64, p0: f64, success: bool) -> f64 {
phi(a, p0, success).ln()
}
pub(crate) fn gro_action(hypotheses: &BernoulliHypotheses) -> f64 {
hypotheses.p1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn phi_is_a_valid_e_variable_across_a_fine_action_grid() {
let p0 = 0.5;
let n = 2000;
for i in 0..=n {
let a = ACTION_EPSILON + (1.0 - 2.0 * ACTION_EPSILON) * (i as f64 / n as f64);
let expectation = p0 * phi(a, p0, true) + (1.0 - p0) * phi(a, p0, false);
assert!(
(expectation - 1.0).abs() < 1e-9,
"a={a}, p0*phi(success)+((1-p0))*phi(failure)={expectation}, expected 1.0"
);
}
}
#[test]
fn phi_is_a_valid_e_variable_for_varied_p0() {
for &p0 in &[0.05, 0.3, 0.5, 0.7, 0.95] {
for &a in &[0.01, 0.1, 0.3, 0.5, 0.7, 0.9, 0.99] {
let expectation = p0 * phi(a, p0, true) + (1.0 - p0) * phi(a, p0, false);
assert!(
(expectation - 1.0).abs() < 1e-9,
"p0={p0}, a={a}, expectation={expectation}"
);
}
}
}
#[test]
fn gro_action_is_the_alternative_parameter() {
let h = BernoulliHypotheses { p0: 0.5, p1: 0.55 };
assert_eq!(gro_action(&h), 0.55);
}
#[test]
fn hypotheses_reject_p0_at_or_above_p1() {
assert!(BernoulliHypotheses { p0: 0.5, p1: 0.5 }.validate().is_err());
assert!(BernoulliHypotheses { p0: 0.6, p1: 0.5 }.validate().is_err());
}
#[test]
fn hypotheses_reject_out_of_range() {
assert!(BernoulliHypotheses { p0: 0.0, p1: 0.5 }.validate().is_err());
assert!(BernoulliHypotheses { p0: 0.5, p1: 1.0 }.validate().is_err());
}
#[test]
fn hypotheses_accept_a_valid_pair() {
BernoulliHypotheses { p0: 0.5, p1: 0.55 }
.validate()
.unwrap();
}
}