use super::FitError;
use super::decompose::classical_figure;
use super::ets::Ets;
use crate::ets::Form;
use crate::normal::normal_quantile;
use crate::theta::ThetaSpec;
use crate::{Estimator, TimeSeries, acorr, math};
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Theta {
period: usize,
}
impl Theta {
#[must_use]
pub const fn new() -> Self {
Self { period: 0 }
}
#[must_use]
pub const fn seasonal(self, period: usize) -> Self {
Self { period }
}
pub fn fit(&self, y: &[f64]) -> Result<ThetaFit, FitError> {
if !math::all_finite(y) {
return Err(FitError::Unsupported);
}
let m = self.period;
let figure = (m > 1 && seasonal(y, m))
.then(|| classical_figure(y, m, Form::Multiplicative))
.filter(|figure| figure.iter().all(|s| s.abs() >= MIN_INDEX));
let adjusted: Vec<f64> = match &figure {
Some(figure) => y
.iter()
.enumerate()
.map(|(t, v)| v / figure[t % m])
.collect(),
None => y.to_vec(),
};
let smoothing = Ets::new().fit(&adjusted)?;
let n = y.len();
let factors = figure.map_or_else(Vec::new, |figure| {
(0..m).map(|j| figure[(n + j) % m]).collect()
});
Ok(ThetaFit {
alpha: smoothing.alpha,
drift: slope(&adjusted) / 2.0,
level: smoothing.level,
count: n,
sigma2: smoothing.sigma2,
factors,
})
}
}
const MIN_INDEX: f64 = 1e-4;
fn seasonal(y: &[f64], m: usize) -> bool {
let n = y.len();
if n <= 2 * m || math::is_constant(y) {
return false;
}
let Ok(series) = TimeSeries::try_new(y, Estimator::Biased) else {
return false;
};
let r: Vec<f64> = (1..=m).filter_map(|lag| acorr(&series, lag)).collect();
if r.len() < m {
return false;
}
let spread: f64 = r[..m - 1].iter().map(|v| v * v).sum();
let stat = math::sqrt((1.0 + 2.0 * spread) / count_as_f64(n));
r[m - 1].abs() / stat > normal_quantile(0.95)
}
fn slope(values: &[f64]) -> f64 {
let n = count_as_f64(values.len());
let t_mean = (n - 1.0) / 2.0;
let y_mean = values.iter().sum::<f64>() / n;
let (sxy, sxx) = values
.iter()
.enumerate()
.fold((0.0, 0.0), |(sxy, sxx), (t, v)| {
let dt = count_as_f64(t) - t_mean;
(sxy + dt * (v - y_mean), sxx + dt * dt)
});
sxy / sxx
}
#[expect(
clippy::cast_precision_loss,
reason = "series lengths stay far below 2^53, where the conversion is exact"
)]
fn count_as_f64(count: usize) -> f64 {
count as f64
}
#[derive(Debug, Clone, PartialEq)]
pub struct ThetaFit {
pub alpha: f64,
pub drift: f64,
pub level: f64,
pub count: usize,
pub sigma2: f64,
pub factors: Vec<f64>,
}
impl ThetaFit {
#[must_use]
pub fn spec(&self) -> ThetaSpec<'_> {
ThetaSpec {
alpha: self.alpha,
drift: self.drift,
level: self.level,
count: self.count,
sigma2: self.sigma2,
seasonal: &self.factors,
}
}
}