mod layout;
mod start;
use super::{Criterion, FitError, bfgs};
use crate::ets::{EtsSpec, Form, Smoothing, Trend};
use crate::math;
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use layout::{Layout, Run, count_as_f64, objective};
pub(crate) const MAX_PERIOD: usize = 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Ets {
error: Form,
trend: bool,
damped: bool,
period: usize,
season: Form,
}
impl Ets {
#[must_use]
pub const fn new() -> Self {
Self {
error: Form::Additive,
trend: false,
damped: false,
period: 0,
season: Form::Additive,
}
}
#[must_use]
pub const fn error(self, error: Form) -> Self {
Self { error, ..self }
}
#[must_use]
pub const fn trend(self) -> Self {
Self {
trend: true,
..self
}
}
#[must_use]
pub const fn damped(self) -> Self {
Self {
trend: true,
damped: true,
..self
}
}
#[must_use]
pub const fn seasonal(self, period: usize) -> Self {
Self {
period: if period > 1 { period } else { 0 },
..self
}
}
#[must_use]
pub const fn season(self, season: Form) -> Self {
Self { season, ..self }
}
pub fn fit(&self, y: &[f64]) -> Result<EtsFit, FitError> {
self.check(y)?;
let layout = Layout::of(self);
let start = if layout.concentrated() {
Vec::new()
} else {
start::start_states(y, self.trend, self.period.max(1), self.season)
};
let (u, minimum) = if layout.concentrated() && layout.smoothing_len() == 1 {
let u = layout.alpha_search(y).ok_or(FitError::Degenerate)?;
let minimum = bfgs::Minimum {
iterations: 0,
converged: true,
};
(u, minimum)
} else {
layout
.best_starts(y, &start)
.into_iter()
.map(|mut u| {
let mut scratch = vec![0.0; bfgs::scratch_len(u.len())];
let minimum = bfgs::minimize(
|u| objective(&layout, y, u),
&mut u,
&mut scratch,
bfgs::Options::default(),
);
(objective(&layout, y, &u), u, minimum)
})
.filter(|(value, ..)| value.is_finite())
.min_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, u, minimum)| (u, minimum))
.ok_or(FitError::Degenerate)?
};
let run = layout.run(y, &u).ok_or(FitError::Degenerate)?;
if run.sse <= 0.0 || !run.sse.is_finite() {
return Err(FitError::Degenerate);
}
Ok(EtsFit::new(&layout, y.len(), run, minimum))
}
fn check(&self, y: &[f64]) -> Result<(), FitError> {
let multiplicative = self.error == Form::Multiplicative || self.multiplicative_season();
let forbidden = self.error == Form::Additive && self.multiplicative_season();
let positive = y.iter().all(|&v| v > 0.0);
if !math::all_finite(y)
|| self.period > MAX_PERIOD
|| forbidden
|| (multiplicative && !positive)
{
return Err(FitError::Unsupported);
}
let needed = self.npars() + 5;
if y.len() < needed || (self.period > 0 && y.len() <= self.period) {
return Err(FitError::TooShort {
needed: needed.max(self.period + 1),
present: y.len(),
});
}
Ok(())
}
fn multiplicative_season(&self) -> bool {
self.period > 0 && self.season == Form::Multiplicative
}
const fn npars(&self) -> usize {
2 + 2 * (self.trend as usize) + self.period + (self.damped as usize)
}
fn label(&self) -> String {
let letter = |form: Form| match form {
Form::Additive => "A",
Form::Multiplicative => "M",
};
let trend = match (self.trend, self.damped) {
(false, _) => "N",
(true, false) => "A",
(true, true) => "Ad",
};
let season = if self.period > 0 {
letter(self.season)
} else {
"N"
};
format!("ETS({},{trend},{season})", letter(self.error))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct EtsFit {
label: String,
pub error: Form,
pub alpha: f64,
pub trend: Trend,
pub season: Form,
pub gamma: f64,
pub initial_states: Vec<f64>,
pub level: f64,
pub slope: f64,
pub seasonal: Vec<f64>,
pub sigma2: f64,
pub loglike: f64,
pub nobs: usize,
pub parameters: usize,
pub iterations: usize,
pub converged: bool,
}
impl EtsFit {
fn new(layout: &Layout, n: usize, run: Run, minimum: bfgs::Minimum) -> Self {
let model = &layout.model;
let Smoothing {
alpha,
beta,
gamma,
phi,
..
} = run.smoothing;
let trend = match (model.trend, model.damped) {
(false, _) => Trend::None,
(true, false) => Trend::Additive { beta },
(true, true) => Trend::Damped { beta, phi },
};
let mut initial_seasonal = vec![0.0; model.period];
let (level, slope) = layout.expand(&run.initial, &mut initial_seasonal);
let mut initial_states = vec![level];
if model.trend {
initial_states.push(slope);
}
initial_states.extend(initial_seasonal);
let parameters = layout.smoothing_len() + layout.states_len();
let nf = count_as_f64(n);
Self {
label: model.label(),
error: model.error,
alpha,
trend,
season: model.season,
gamma,
initial_states,
level: run.level,
slope: run.slope,
seasonal: run.seasonal,
sigma2: run.sse / count_as_f64(n - parameters),
loglike: -0.5 * nf * (math::ln(core::f64::consts::TAU * run.sse / nf) + 1.0)
- run.log_forecasts,
nobs: n,
parameters,
iterations: minimum.iterations,
converged: minimum.converged,
}
}
#[must_use]
pub fn label(&self) -> &str {
&self.label
}
const fn counted(&self) -> usize {
self.parameters + 1
}
#[must_use]
pub fn aic(&self) -> f64 {
-2.0 * self.loglike + 2.0 * count_as_f64(self.counted())
}
#[must_use]
pub fn aicc(&self) -> f64 {
let k = count_as_f64(self.counted());
let n = count_as_f64(self.nobs);
if n <= k + 1.0 {
return f64::INFINITY;
}
self.aic() + 2.0 * k * (k + 1.0) / (n - k - 1.0)
}
#[must_use]
pub fn bic(&self) -> f64 {
-2.0 * self.loglike + count_as_f64(self.counted()) * math::ln(count_as_f64(self.nobs))
}
#[must_use]
pub fn spec(&self) -> EtsSpec<'_> {
EtsSpec {
error: self.error,
alpha: self.alpha,
trend: self.trend,
season: self.season,
gamma: self.gamma,
level: self.level,
slope: self.slope,
seasonal: &self.seasonal,
sigma2: self.sigma2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoEts {
period: usize,
criterion: Criterion,
additive_only: bool,
}
impl Default for AutoEts {
fn default() -> Self {
Self::new()
}
}
impl AutoEts {
#[must_use]
pub const fn new() -> Self {
Self {
period: 0,
criterion: Criterion::Aicc,
additive_only: false,
}
}
#[must_use]
pub const fn seasonal(self, period: usize) -> Self {
Self { period, ..self }
}
#[must_use]
pub const fn criterion(self, criterion: Criterion) -> Self {
Self { criterion, ..self }
}
#[must_use]
pub const fn additive_only(self, additive_only: bool) -> Self {
Self {
additive_only,
..self
}
}
pub fn fit(&self, y: &[f64]) -> Result<EtsFit, FitError> {
let mut best: Option<(f64, EtsFit)> = None;
let mut first_error = None;
for model in self.candidates(y) {
match model.fit(y) {
Ok(fit) => {
let score = self.score(&fit);
if score.is_finite() && best.as_ref().is_none_or(|(b, _)| score < *b) {
best = Some((score, fit));
}
}
Err(error) => {
first_error.get_or_insert(error);
}
}
}
best.map(|(_, fit)| fit)
.ok_or(first_error.unwrap_or(FitError::Degenerate))
}
fn candidates(&self, y: &[f64]) -> Vec<Ets> {
let multiplicative = !self.additive_only && y.iter().all(|&v| v > 0.0);
let seasonal = self.period > 1 && self.period <= MAX_PERIOD && y.len() > self.period;
let errors: &[Form] = if multiplicative {
&[Form::Additive, Form::Multiplicative]
} else {
&[Form::Additive]
};
let trends = [Ets::new(), Ets::new().damped(), Ets::new().trend()];
let mut seasons = vec![None];
if seasonal {
seasons.push(Some(Form::Additive));
if multiplicative {
seasons.push(Some(Form::Multiplicative));
}
}
let mut models = Vec::new();
for &error in errors {
for trend in trends {
for &season in &seasons {
let model = trend.error(error);
let model = match season {
None => model,
Some(form) => model.seasonal(self.period).season(form),
};
let forbidden = error == Form::Additive && model.multiplicative_season();
if !forbidden {
models.push(model);
}
}
}
}
models
}
fn score(&self, fit: &EtsFit) -> f64 {
match self.criterion {
Criterion::Aicc => fit.aicc(),
Criterion::Aic => fit.aic(),
Criterion::Bic => fit.bic(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_series_are_rejected_like_r() {
let error = Ets::new().trend().fit(&[1.0; 8]).unwrap_err();
assert_eq!(
error,
FitError::TooShort {
needed: 9,
present: 8
}
);
assert_eq!(
Ets::new().fit(&[1.0, f64::NAN, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]),
Err(FitError::Unsupported)
);
}
#[test]
fn multiplicative_models_need_positive_data_and_errors() {
let y = [1.0, 2.0, -1.0, 3.0, 2.0, 1.0, 2.0, 3.0, 1.0, 2.0];
let multiplicative = Ets::new().error(Form::Multiplicative);
assert_eq!(multiplicative.fit(&y), Err(FitError::Unsupported));
let forbidden = Ets::new().seasonal(2).season(Form::Multiplicative);
assert_eq!(forbidden.fit(&[1.0; 12]), Err(FitError::Unsupported));
}
#[test]
fn labels_follow_r() {
let model = Ets::new()
.error(Form::Multiplicative)
.damped()
.seasonal(12)
.season(Form::Multiplicative);
assert_eq!(model.label(), "ETS(M,Ad,M)");
assert_eq!(Ets::new().seasonal(4).label(), "ETS(A,N,A)");
}
}