mod grid;
use crate::filter::FilterError;
use crate::optimize;
use grid::{LANES, Lanes};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CrostonVariant {
#[default]
Classic,
Sba,
Sbj,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CrostonFilter {
alpha: f64,
variant: CrostonVariant,
size: f64,
interval: f64,
since: f64,
demands: usize,
started: bool,
}
impl CrostonFilter {
pub fn new(alpha: f64, variant: CrostonVariant) -> Result<Self, FilterError> {
if !(alpha > 0.0 && alpha <= 1.0) {
return Err(FilterError::InvalidParameter);
}
Ok(Self {
alpha,
variant,
size: 0.0,
interval: 0.0,
since: 0.0,
demands: 0,
started: false,
})
}
pub fn update(&mut self, y: f64) -> f64 {
let before = self.forecast();
self.started = true;
self.since += 1.0;
if !(y.is_finite() && y >= 0.0) {
return f64::NAN;
}
if y > 0.0 {
if self.demands == 0 {
self.size = y;
self.interval = self.since;
} else {
self.size += self.alpha * (y - self.size);
self.interval += self.alpha * (self.since - self.interval);
}
self.demands += 1;
self.since = 0.0;
}
y - before
}
pub fn warm_up(&mut self, history: &[f64]) {
for &y in history {
self.update(y);
}
}
pub fn optimised(history: &[f64], variant: CrostonVariant) -> Result<Self, FilterError> {
let demands = history
.iter()
.filter(|&&y| y.is_finite() && y > 0.0)
.count();
if demands < 2 {
return Err(FilterError::InvalidParameter);
}
let mse = |alpha: f64| {
Self::new(alpha, variant).map_or(f64::INFINITY, |mut filter| {
mean_squared_error(history, |y| filter.update(y))
})
};
let alpha = minimise(
|alphas| grid::croston(history, variant, alphas),
mse,
ALPHA_RANGE,
);
let mut filter = Self::new(alpha, variant)?;
filter.warm_up(history);
Ok(filter)
}
#[must_use]
pub const fn alpha(&self) -> f64 {
self.alpha
}
#[must_use]
pub fn forecast(&self) -> f64 {
if !self.started {
return f64::NAN;
}
if self.demands == 0 {
return 0.0;
}
let correction = match self.variant {
CrostonVariant::Classic => 1.0,
CrostonVariant::Sba => 1.0 - self.alpha / 2.0,
CrostonVariant::Sbj => 1.0 - self.alpha / (2.0 - self.alpha),
};
self.size / self.interval * correction
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TsbFilter {
alpha_size: f64,
alpha_probability: f64,
size: f64,
probability: f64,
demanded: bool,
started: bool,
}
impl TsbFilter {
pub fn new(alpha_size: f64, alpha_probability: f64) -> Result<Self, FilterError> {
let valid = |a: f64| a > 0.0 && a <= 1.0;
if !(valid(alpha_size) && valid(alpha_probability)) {
return Err(FilterError::InvalidParameter);
}
Ok(Self {
alpha_size,
alpha_probability,
size: 0.0,
probability: 0.0,
demanded: false,
started: false,
})
}
pub fn update(&mut self, y: f64) -> f64 {
let before = self.forecast();
if !(y.is_finite() && y >= 0.0) {
return f64::NAN;
}
let occurred = if y > 0.0 { 1.0 } else { 0.0 };
if self.started {
self.probability += self.alpha_probability * (occurred - self.probability);
} else {
self.probability = occurred;
self.started = true;
}
if y > 0.0 {
if self.demanded {
self.size += self.alpha_size * (y - self.size);
} else {
self.size = y;
self.demanded = true;
}
}
y - before
}
pub fn warm_up(&mut self, history: &[f64]) {
for &y in history {
self.update(y);
}
}
pub fn optimised(history: &[f64]) -> Result<Self, FilterError> {
let demands = history
.iter()
.filter(|&&y| y.is_finite() && y > 0.0)
.count();
if demands < 2 {
return Err(FilterError::InvalidParameter);
}
let mse = |size: f64, probability: f64| {
Self::new(size, probability).map_or(f64::INFINITY, |mut filter| {
mean_squared_error(history, |y| filter.update(y))
})
};
let (mut size, mut probability) = (TSB_GRID[0], TSB_GRID[0]);
let mut best = f64::INFINITY;
for &a in &TSB_GRID {
for &b in &TSB_GRID {
let value = mse(a, b);
if value < best {
(best, size, probability) = (value, a, b);
}
}
}
for _ in 0..COORDINATE_ROUNDS {
size = minimise(
|sizes| grid::tsb(history, sizes, &[probability; LANES]),
|a| mse(a, probability),
ALPHA_RANGE,
);
probability = minimise(
|probabilities| grid::tsb(history, &[size; LANES], probabilities),
|b| mse(size, b),
ALPHA_RANGE,
);
}
let mut filter = Self::new(size, probability)?;
filter.warm_up(history);
Ok(filter)
}
#[must_use]
pub const fn alphas(&self) -> (f64, f64) {
(self.alpha_size, self.alpha_probability)
}
#[must_use]
pub fn forecast(&self) -> f64 {
if !self.started {
return f64::NAN;
}
self.probability * self.size
}
}
const ALPHA_RANGE: (f64, f64) = (0.01, 1.0);
const TSB_GRID: [f64; 6] = [0.05, 0.1, 0.2, 0.4, 0.7, 1.0];
const COORDINATE_ROUNDS: usize = 3;
fn mean_squared_error(history: &[f64], mut update: impl FnMut(f64) -> f64) -> f64 {
let (mut sum, mut count) = (0.0, 0.0);
for &y in history {
let error = update(y);
if !error.is_nan() {
sum += error * error;
count += 1.0;
}
}
if count > 0.0 {
sum / count
} else {
f64::INFINITY
}
}
const GRID_POINTS: usize = 100;
fn minimise(
lanes: impl Fn(&Lanes) -> Lanes,
f: impl Fn(f64) -> f64,
(low, high): (f64, f64),
) -> f64 {
let step = (high - low) / grid_index(GRID_POINTS - 1);
let mut best = (f64::INFINITY, low);
for first in (0..GRID_POINTS).step_by(LANES) {
let points: Lanes = core::array::from_fn(|j| low + step * grid_index(first + j));
for (&value, &x) in lanes(&points).iter().zip(&points) {
if value < best.0 {
best = (value, x);
}
}
}
let (f_best, x_best) = best;
let bracket = ((x_best - step).max(low), (x_best + step).min(high));
let (x, fx) = optimize::brent(&f, bracket, 1e-8);
if fx < f_best { x } else { x_best }
}
#[expect(
clippy::cast_precision_loss,
reason = "grid indices stay below GRID_POINTS = 100, where the conversion is exact"
)]
const fn grid_index(index: usize) -> f64 {
index as f64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn corrections_scale_the_classic_forecast() {
let history = [0.0, 4.0, 0.0, 0.0, 2.0, 0.0, 6.0];
let forecast = |variant| {
let mut filter = CrostonFilter::new(0.2, variant).unwrap();
filter.warm_up(&history);
filter.forecast()
};
let classic = forecast(CrostonVariant::Classic);
assert!((forecast(CrostonVariant::Sba) - classic * 0.9).abs() < 1e-12);
assert!((forecast(CrostonVariant::Sbj) - classic * (1.0 - 0.2 / 1.8)).abs() < 1e-12);
}
#[test]
fn missing_and_invalid_values() {
assert_eq!(
CrostonFilter::new(0.0, CrostonVariant::Classic),
Err(FilterError::InvalidParameter)
);
assert_eq!(TsbFilter::new(0.1, 1.5), Err(FilterError::InvalidParameter));
let mut filter = TsbFilter::new(0.5, 0.5).unwrap();
assert!(filter.forecast().is_nan());
assert!(filter.update(-1.0).is_nan());
assert!(filter.update(0.0).is_nan());
assert_eq!(filter.forecast(), 0.0);
}
#[test]
fn optimised_croston_beats_every_grid_point() {
let history = [
0.0, 3.0, 0.0, 0.0, 5.0, 0.0, 2.0, 0.0, 0.0, 0.0, 6.0, 1.0, 0.0, 4.0, 0.0, 0.0, 3.0,
];
let best = CrostonFilter::optimised(&history, CrostonVariant::Classic).unwrap();
let mse = |alpha: f64| {
let mut filter = CrostonFilter::new(alpha, CrostonVariant::Classic).unwrap();
mean_squared_error(&history, |y| filter.update(y))
};
let alpha = best.alpha();
for i in 1..=100 {
let grid = f64::from(i) / 100.0;
assert!(mse(alpha) <= mse(grid) + 1e-12, "alpha {alpha} vs {grid}");
}
assert_eq!(
CrostonFilter::optimised(&[0.0, 2.0], CrostonVariant::Classic),
Err(FilterError::InvalidParameter)
);
}
#[test]
fn optimised_tsb_beats_its_grid() {
let history = [
0.0, 3.0, 0.0, 0.0, 5.0, 0.0, 2.0, 0.0, 0.0, 0.0, 6.0, 1.0, 0.0, 4.0, 0.0, 0.0, 3.0,
];
let best = TsbFilter::optimised(&history).unwrap();
let mse = |a: f64, b: f64| {
let mut filter = TsbFilter::new(a, b).unwrap();
mean_squared_error(&history, |y| filter.update(y))
};
let (a, b) = best.alphas();
for grid in [0.05, 0.1, 0.2, 0.4, 0.7, 1.0] {
assert!(mse(a, b) <= mse(grid, b) + 1e-12 && mse(a, b) <= mse(a, grid) + 1e-12);
}
}
}