use backshift::{ArimaSpec, Conformal, Filter};
const LEVEL: f64 = 0.9;
const HORIZON: usize = 3;
const WINDOW: usize = 250;
const STEPS: usize = 4000;
struct Rng(u64);
impl Rng {
fn uniform(&mut self) -> f64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
((self.0 >> 11) as f64 + 0.5) / (1_u64 << 53) as f64
}
fn normal(&mut self) -> f64 {
let (u, v) = (self.uniform(), self.uniform());
(-2.0 * u.ln()).sqrt() * (std::f64::consts::TAU * v).cos()
}
}
#[derive(Debug, Clone, Copy)]
enum Noise {
Gaussian,
Skewed,
HeavyTailed,
}
impl Noise {
fn draw(self, rng: &mut Rng) -> f64 {
match self {
Noise::Gaussian => rng.normal(),
Noise::Skewed => -rng.uniform().ln() - 1.0,
Noise::HeavyTailed => {
let chi2: f64 = (0..3).map(|_| rng.normal().powi(2)).sum();
rng.normal() / (chi2 / 3.0).sqrt() / 3.0_f64.sqrt()
}
}
}
}
struct Bounds {
lower: [f64; HORIZON],
upper: [f64; HORIZON],
g_lower: [f64; HORIZON],
g_upper: [f64; HORIZON],
}
fn coverage(noise: Noise, seed: u64) -> ([f64; HORIZON], [f64; HORIZON]) {
let spec = ArimaSpec {
ar: &[0.6],
ma: &[0.3],
..ArimaSpec::default()
};
let mut filter = Filter::<2>::new(&spec).unwrap();
let mut conformal = Conformal::<HORIZON, WINDOW>::new();
let mut rng = Rng(seed);
let (mut y, mut e) = (0.0, 0.0);
let mut pending: Vec<Bounds> = Vec::new();
let (mut hits, mut gaussian_hits) = ([0_usize; HORIZON], [0_usize; HORIZON]);
let warm_up = WINDOW + HORIZON + 50;
for t in 0..warm_up + STEPS {
let next = noise.draw(&mut rng);
y = 0.6 * y + next + 0.3 * e;
e = next;
if t >= warm_up + HORIZON {
for h in 0..HORIZON {
let made = &pending[pending.len() - 1 - h];
hits[h] += usize::from(made.lower[h] <= y && y <= made.upper[h]);
gaussian_hits[h] += usize::from(made.g_lower[h] <= y && y <= made.g_upper[h]);
}
}
conformal.observe(y);
filter.update(y);
let (mut mean, mut lower, mut upper) = ([0.0; HORIZON], [0.0; HORIZON], [0.0; HORIZON]);
let (mut g_lower, mut g_upper) = ([0.0; HORIZON], [0.0; HORIZON]);
filter.forecast_interval_into(LEVEL, &mut mean, &mut g_lower, &mut g_upper);
conformal.record(&mean);
conformal.interval_into(LEVEL, &mean, &mut lower, &mut upper);
pending.push(Bounds {
lower,
upper,
g_lower,
g_upper,
});
}
let scored = (STEPS - HORIZON) as f64;
(
hits.map(|h| h as f64 / scored),
gaussian_hits.map(|h| h as f64 / scored),
)
}
#[test]
fn conformal_intervals_reach_their_coverage() {
for (seed, noise) in [
(1, Noise::Gaussian),
(2, Noise::Skewed),
(3, Noise::HeavyTailed),
] {
let (conformal, gaussian) = coverage(noise, seed);
println!("{noise:?}: conformal {conformal:.3?}, Gaussian {gaussian:.3?}");
for (h, c) in conformal.iter().enumerate() {
assert!((c - LEVEL).abs() < 0.03, "{noise:?} h = {}: {c}", h + 1);
}
}
}