#[derive(Debug, Clone, Copy)]
pub struct Conformal<const H: usize, const N: usize> {
pending: [[f64; H]; H],
errors: [[f64; N]; H],
count: [usize; H],
next: [usize; H],
}
impl<const H: usize, const N: usize> Conformal<H, N> {
#[must_use]
pub const fn new() -> Self {
Self {
pending: [[f64::NAN; H]; H],
errors: [[0.0; N]; H],
count: [0; H],
next: [0; H],
}
}
pub fn observe(&mut self, y: f64) {
for h in 0..H {
let forecast = self.pending[h][h];
if !y.is_nan() && !forecast.is_nan() {
self.push(h, (y - forecast).abs());
}
}
self.pending.copy_within(..H.saturating_sub(1), 1);
if let Some(newest) = self.pending.first_mut() {
newest.fill(f64::NAN);
}
}
pub fn record(&mut self, forecast: &[f64]) {
if let Some(newest) = self.pending.first_mut() {
for (slot, &value) in newest.iter_mut().zip(forecast) {
*slot = value;
}
}
}
#[must_use]
pub fn half_width(&self, h: usize, level: f64) -> f64 {
if !(0.0..=1.0).contains(&level) {
return f64::NAN;
}
let n = self.count[h];
let rank = rank(level, n);
if rank > n {
return f64::INFINITY;
}
let mut sorted = self.errors[h];
let sorted = &mut sorted[..n];
sorted.sort_unstable_by(f64::total_cmp);
rank.checked_sub(1).map_or(0.0, |index| sorted[index])
}
pub fn interval_into(&self, level: f64, mean: &[f64], lower: &mut [f64], upper: &mut [f64]) {
assert!(
mean.len() == lower.len() && mean.len() == upper.len(),
"mean, lower and upper must have the same length"
);
for (h, ((m, lo), up)) in mean.iter().zip(lower).zip(upper).enumerate() {
let width = if h < H {
self.half_width(h, level)
} else {
f64::INFINITY
};
*lo = m - width;
*up = m + width;
}
}
#[must_use]
pub fn calibration_len(&self, h: usize) -> usize {
self.count[h]
}
fn push(&mut self, h: usize, error: f64) {
if N == 0 {
return;
}
self.errors[h][self.next[h]] = error;
self.next[h] = (self.next[h] + 1) % N;
self.count[h] = (self.count[h] + 1).min(N);
}
}
impl<const H: usize, const N: usize> Default for Conformal<H, N> {
fn default() -> Self {
Self::new()
}
}
fn rank(level: f64, n: usize) -> usize {
let target = level * (n + 1) as f64;
let floor = target as usize;
floor + usize::from((floor as f64) < target)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scores_each_horizon_when_its_value_arrives() {
let mut conformal = Conformal::<2, 8>::new();
conformal.observe(0.0);
conformal.record(&[1.0, 2.0]); conformal.observe(1.5); conformal.record(&[1.0, 1.0]); conformal.observe(4.0); assert_eq!(conformal.calibration_len(0), 2);
assert_eq!(conformal.calibration_len(1), 1);
assert_eq!(conformal.errors[0][..2], [0.5, 3.0]);
assert_eq!(conformal.errors[1][0], 2.0);
}
#[test]
fn uses_the_split_conformal_rank() {
let mut conformal = Conformal::<1, 16>::new();
for e in 1..=9 {
conformal.record(&[0.0]);
conformal.observe(f64::from(e));
}
assert_eq!(conformal.half_width(0, 0.9), 9.0);
assert_eq!(conformal.half_width(0, 0.95), f64::INFINITY);
assert_eq!(conformal.half_width(0, 0.5), 5.0);
assert!(conformal.half_width(0, 1.5).is_nan());
}
#[test]
fn forgets_the_oldest_error() {
let mut conformal = Conformal::<1, 2>::new();
for e in [100.0, 1.0, 2.0] {
conformal.record(&[0.0]);
conformal.observe(e);
}
assert_eq!(conformal.calibration_len(0), 2);
assert_eq!(conformal.half_width(0, 0.6), 2.0);
}
#[test]
fn missing_values_score_nothing() {
let mut conformal = Conformal::<1, 4>::new();
conformal.record(&[0.0]);
conformal.observe(f64::NAN);
assert_eq!(conformal.calibration_len(0), 0);
}
#[test]
fn horizons_past_capacity_are_unbounded() {
let mut conformal = Conformal::<1, 4>::new();
for y in [1.0, 2.0, 1.5, 2.5] {
conformal.record(&[1.0]);
conformal.observe(y);
}
let (mean, mut lower, mut upper) = ([0.0; 2], [0.0; 2], [0.0; 2]);
conformal.interval_into(0.5, &mean, &mut lower, &mut upper);
assert!(lower[0].is_finite() && upper[0].is_finite());
assert_eq!((lower[1], upper[1]), (f64::NEG_INFINITY, f64::INFINITY));
}
}