use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::Vec;
use crate::accuracy::accuracy;
use crate::ets::EtsFilter;
use crate::filter::Filter;
use crate::fit::ets::MAX_PERIOD;
use crate::fit::{AutoArima, AutoEts, FitError, Theta};
use crate::math;
use crate::theta::ThetaFilter;
const ARIMA_CAPACITY: usize = 80;
const THETA_CAPACITY: usize = 366;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Family {
Arima,
Ets,
Theta,
Naive,
SeasonalNaive,
}
impl Family {
pub const ALL: [Family; 5] = [
Family::Arima,
Family::Ets,
Family::Theta,
Family::Naive,
Family::SeasonalNaive,
];
}
#[derive(Debug, Clone, PartialEq)]
pub struct FamilySelection {
pub family: Family,
pub scores: [(Family, f64); 5],
pub forecast: Vec<f64>,
}
pub fn cross_validation_errors<F>(
y: &[f64],
horizon: usize,
initial: usize,
mut forecaster: F,
) -> Vec<f64>
where
F: FnMut(&[f64], usize) -> Option<Vec<f64>>,
{
let n = y.len();
let cells = n
.checked_mul(horizon)
.expect("y.len() * horizon must not overflow");
let mut errors = vec![f64::NAN; cells];
for t in initial..n.saturating_sub(1) {
let Some(forecast) = forecaster(&y[..=t], horizon) else {
continue;
};
assert!(
forecast.len() >= horizon,
"the forecaster must return horizon values"
);
let row = &mut errors[t * horizon..(t + 1) * horizon];
for ((error, actual), predicted) in row.iter_mut().zip(&y[t + 1..]).zip(&forecast) {
*error = actual - predicted;
}
}
errors
}
pub fn select_family(
y: &[f64],
period: usize,
horizon: usize,
origins: usize,
) -> Result<FamilySelection, FitError> {
if horizon == 0 || origins == 0 {
return Err(FitError::Unsupported);
}
let needed = origins.saturating_mul(horizon).saturating_add(2);
if y.len() < needed {
return Err(FitError::TooShort {
needed,
present: y.len(),
});
}
let scores = Family::ALL.map(|family| (family, score(family, y, period, horizon, origins)));
let (family, _) = scores
.iter()
.filter(|(_, score)| score.is_finite())
.fold(
None,
|best: Option<(Family, f64)>, &(family, score)| match best {
Some((_, lowest)) if lowest <= score => best,
_ => Some((family, score)),
},
)
.ok_or(FitError::Degenerate)?;
let forecast = forecast(family, y, period, horizon).ok_or(FitError::Degenerate)?;
Ok(FamilySelection {
family,
scores,
forecast,
})
}
fn score(family: Family, y: &[f64], period: usize, horizon: usize, origins: usize) -> f64 {
let mut total = 0.0;
for k in (1..=origins).rev() {
let end = y.len() - k * horizon;
let (training, rest) = y.split_at(end);
let Some(predicted) = forecast(family, training, period, horizon) else {
return f64::NAN;
};
let mase = accuracy(&predicted, &rest[..horizon], training, period).mase;
if !mase.is_finite() {
return f64::NAN;
}
total += mase;
}
total / count_as_f64(origins)
}
fn forecast(family: Family, y: &[f64], period: usize, horizon: usize) -> Option<Vec<f64>> {
let seasonal = period > 1;
let mut mean = vec![0.0; horizon];
let mut variance = vec![0.0; horizon];
match family {
Family::Arima => {
let search = if seasonal {
AutoArima::new().seasonal(period)
} else {
AutoArima::new()
};
let fit = search.fit(y).ok()?;
let mut filter = Box::new(Filter::<ARIMA_CAPACITY>::new(&fit.fitted.spec()).ok()?);
filter.warm_up(y);
filter.forecast_into(&mut mean, &mut variance);
}
Family::Ets => {
let fit = AutoEts::new().seasonal(period).fit(y).ok()?;
let filter = EtsFilter::<MAX_PERIOD>::new(&fit.spec()).ok()?;
let mut scratch = vec![0.0; filter.forecast_scratch_len()];
filter.forecast_with(&mut scratch, &mut mean, &mut variance);
}
Family::Theta => {
let fit = Theta::new().seasonal(period).fit(y).ok()?;
let filter = Box::new(ThetaFilter::<THETA_CAPACITY>::new(&fit.spec()).ok()?);
filter.forecast_into(&mut mean, &mut variance);
}
Family::Naive => mean.fill(*y.last()?),
Family::SeasonalNaive => {
let cycle = y.get(y.len().checked_sub(period)?..).filter(|_| seasonal)?;
for (value, last) in mean.iter_mut().zip(cycle.iter().cycle()) {
*value = *last;
}
}
}
math::all_finite(&mean).then_some(mean)
}
#[expect(
clippy::cast_precision_loss,
reason = "origin counts stay far below 2^53, where the conversion is exact"
)]
fn count_as_f64(count: usize) -> f64 {
count as f64
}