use super::super::hannan_rissanen::cholesky_solve;
use super::super::roots::roots_inside;
use super::Ets;
use crate::ets::{Form, Smoothing, unroll};
use crate::math;
use crate::optimize::brent;
use alloc::vec;
use alloc::vec::Vec;
const LOWER: f64 = 1e-4;
const UPPER: f64 = 0.9999;
pub(super) const PHI_BOUNDS: (f64, f64) = (0.8, 0.98);
const ALPHA_GRID: [f64; 6] = [0.01, 0.05, 0.15, 0.3, 0.5, 0.8];
const BETA_GRID: [f64; 3] = [0.01, 0.3, 0.99];
const GAMMA_GRID: [f64; 2] = [0.01, 0.3];
const PHI_GRID: [f64; 2] = [0.5, 0.99];
const REFINED: usize = 2;
const EDGE: f64 = 20.0;
const REFINED_JOINT: usize = 4;
#[derive(Debug, Clone, Copy)]
pub(super) struct Layout {
pub(super) model: Ets,
}
impl Layout {
pub(super) const fn of(model: &Ets) -> Self {
Self { model: *model }
}
pub(super) fn concentrated(&self) -> bool {
self.model.error == Form::Additive && !self.multiplicative_season()
}
fn multiplicative_season(&self) -> bool {
self.model.period > 0 && self.model.season == Form::Multiplicative
}
pub(super) const fn smoothing_len(&self) -> usize {
let model = &self.model;
1 + (model.trend as usize) + ((model.period > 0) as usize) + (model.damped as usize)
}
pub(super) const fn states_len(&self) -> usize {
1 + (self.model.trend as usize) + self.model.period.saturating_sub(1)
}
pub(super) fn best_starts(&self, y: &[f64], start: &[f64]) -> Vec<Vec<f64>> {
let mut scored: Vec<(f64, Vec<f64>)> = self
.grid()
.into_iter()
.map(|mut u| {
if !self.concentrated() {
u.extend_from_slice(start);
}
(objective(self, y, &u), u)
})
.collect();
scored.sort_by(|a, b| a.0.total_cmp(&b.0));
let refined = if self.concentrated() {
REFINED
} else {
REFINED_JOINT
};
scored.into_iter().take(refined).map(|(_, u)| u).collect()
}
pub(super) fn alpha_search(&self, y: &[f64]) -> Option<Vec<f64>> {
debug_assert!(self.concentrated() && self.smoothing_len() == 1);
let points = ALPHA_GRID.map(logit);
let scores = points.map(|u| objective(self, y, &[u]));
let (best, &score) = scores
.iter()
.enumerate()
.filter(|(_, value)| value.is_finite())
.min_by(|a, b| a.1.total_cmp(b.1))?;
let low = points
.get(best.wrapping_sub(1))
.copied()
.unwrap_or(points[0] - EDGE);
let high = points.get(best + 1).copied().unwrap_or(points[best] + EDGE);
let (u, value) = brent(|u| objective(self, y, &[u]), (low, high), 0.0);
Some(vec![if value < score { u } else { points[best] }])
}
fn grid(&self) -> Vec<Vec<f64>> {
let model = &self.model;
let axes: [&[f64]; 4] = [
&ALPHA_GRID,
if model.trend { &BETA_GRID } else { &[] },
if model.period > 0 { &GAMMA_GRID } else { &[] },
if model.damped { &PHI_GRID } else { &[] },
];
let mut points = vec![Vec::new()];
for axis in axes.iter().filter(|axis| !axis.is_empty()) {
points = points
.iter()
.flat_map(|point| {
axis.iter().map(move |&fraction| {
let mut next: Vec<f64> = point.clone();
next.push(logit(fraction));
next
})
})
.collect();
}
points
}
pub(super) fn smoothing(&self, u: &[f64]) -> Smoothing {
let model = &self.model;
let mut next = u.iter().copied();
let mut take = || next.next().unwrap_or(0.0);
let alpha = LOWER + (UPPER - LOWER) * logistic(take());
let beta = if model.trend {
LOWER + (alpha.min(UPPER) - LOWER) * logistic(take())
} else {
0.0
};
let gamma = if model.period > 0 {
LOWER + ((1.0 - alpha).min(UPPER) - LOWER) * logistic(take())
} else {
0.0
};
let phi = if model.damped {
PHI_BOUNDS.0 + (PHI_BOUNDS.1 - PHI_BOUNDS.0) * logistic(take())
} else {
1.0
};
Smoothing {
alpha,
beta,
gamma,
phi,
trend: model.trend,
multiplicative_season: self.multiplicative_season(),
}
}
pub(super) fn expand(&self, free: &[f64], seasonal: &mut [f64]) -> (f64, f64) {
let level = free[0];
let slope = if self.model.trend { free[1] } else { 0.0 };
let rest = &free[1 + usize::from(self.model.trend)..];
if let Some(last) = seasonal.len().checked_sub(1) {
let total = if self.multiplicative_season() {
count_as_f64(seasonal.len())
} else {
0.0
};
seasonal[..last].copy_from_slice(rest);
seasonal[last] = total - rest.iter().sum::<f64>();
}
(level, slope)
}
fn errors(
&self,
smoothing: &Smoothing,
free: &[f64],
y: &[f64],
seasonal: &mut [f64],
errors: &mut [f64],
) -> (f64, f64, usize) {
let (level, slope) = self.expand(free, seasonal);
recurse(smoothing, level, slope, seasonal, y, errors)
}
fn best_states(&self, smoothing: &Smoothing, y: &[f64]) -> Option<Vec<f64>> {
let (n, k) = (y.len(), self.states_len());
let mut seasonal = vec![0.0; self.model.period];
let mut base = vec![0.0; n];
self.errors(smoothing, &vec![0.0; k], y, &mut seasonal, &mut base);
let columns = self.state_columns(smoothing, n);
let mut gram = vec![vec![0.0; k]; k];
let mut moment = vec![0.0; k];
for (i, column_i) in columns.chunks_exact(n).enumerate() {
moment[i] = -column_i.iter().zip(&base).map(|(c, e)| c * e).sum::<f64>();
for (j, column_j) in columns.chunks_exact(n).take(i + 1).enumerate() {
gram[i][j] = column_i.iter().zip(column_j).map(|(a, b)| a * b).sum();
}
}
cholesky_solve(gram, moment)
}
fn state_columns(&self, smoothing: &Smoothing, n: usize) -> Vec<f64> {
let k = self.states_len();
let leading = 1 + usize::from(self.model.trend);
let zeros = vec![0.0; n];
let mut seasonal = vec![0.0; self.model.period];
let mut columns = vec![0.0; k * n];
let mut unit = vec![0.0; k];
for (j, column) in columns.chunks_exact_mut(n).take(leading).enumerate() {
unit.fill(0.0);
unit[j] = 1.0;
self.errors(smoothing, &unit, &zeros, &mut seasonal, column);
}
let m = self.model.period;
if m == 0 {
return columns;
}
seasonal.fill(0.0);
seasonal[m - 1] = 1.0;
let mut oldest = vec![0.0; n];
recurse(smoothing, 0.0, 0.0, &mut seasonal, &zeros, &mut oldest);
for (j, column) in columns.chunks_exact_mut(n).skip(leading).enumerate() {
let delay = m - 1 - j;
for (t, value) in column.iter_mut().enumerate() {
let aged = t.checked_sub(delay).map_or(0.0, |s| oldest[s]);
*value = aged - oldest[t];
}
}
columns
}
pub(super) fn run(&self, y: &[f64], u: &[f64]) -> Option<Run> {
let smoothing = self.smoothing(u);
if !admissible(&smoothing, self.model.period) {
return None;
}
let initial = if self.concentrated() {
self.best_states(&smoothing, y)?
} else {
u[self.smoothing_len()..].to_vec()
};
let mut ring = vec![0.0; self.model.period];
let mut errors = vec![0.0; y.len()];
let (level, slope, head) = self.errors(&smoothing, &initial, y, &mut ring, &mut errors);
let (sse, log_forecasts) = self.score(y, &errors)?;
let mut seasonal = vec![0.0; self.model.period];
unroll(&ring, head, &mut seasonal);
if self.multiplicative_season() && !self.positive_seasons(&initial) {
return None;
}
Some(Run {
smoothing,
sse,
log_forecasts,
initial,
level,
slope,
seasonal,
})
}
fn score(&self, y: &[f64], errors: &[f64]) -> Option<(f64, f64)> {
if self.model.error == Form::Additive {
return Some((errors.iter().map(|e| e * e).sum(), 0.0));
}
let (mut sse, mut log_forecasts) = (0.0, 0.0);
for (&value, &error) in y.iter().zip(errors) {
let forecast = value - error;
if forecast == 0.0 || !forecast.is_finite() {
return None;
}
let relative = error / forecast;
sse += relative * relative;
log_forecasts += math::ln(forecast.abs());
}
Some((sse, log_forecasts))
}
fn positive_seasons(&self, initial: &[f64]) -> bool {
let mut seasonal = vec![0.0; self.model.period];
self.expand(initial, &mut seasonal);
seasonal.iter().all(|&s| s > 0.0)
}
}
fn recurse(
smoothing: &Smoothing,
mut level: f64,
mut slope: f64,
seasonal: &mut [f64],
y: &[f64],
errors: &mut [f64],
) -> (f64, f64, usize) {
let mut head = 0;
for (&value, error) in y.iter().zip(errors.iter_mut()) {
*error = value - smoothing.forecast(level, slope, seasonal, head);
smoothing.update(&mut level, &mut slope, seasonal, &mut head, value);
}
(level, slope, head)
}
#[derive(Debug, Clone)]
pub(super) struct Run {
pub(super) smoothing: Smoothing,
pub(super) sse: f64,
pub(super) log_forecasts: f64,
pub(super) initial: Vec<f64>,
pub(super) level: f64,
pub(super) slope: f64,
pub(super) seasonal: Vec<f64>,
}
pub(super) fn objective(layout: &Layout, y: &[f64], u: &[f64]) -> f64 {
match layout.run(y, u) {
Some(run) if run.sse > 0.0 && run.sse.is_finite() => {
let n = count_as_f64(y.len());
0.5 * math::ln(run.sse / n) + run.log_forecasts / n
}
_ => f64::INFINITY,
}
}
fn admissible(smoothing: &Smoothing, m: usize) -> bool {
let Smoothing {
alpha,
beta,
gamma,
phi,
trend,
..
} = *smoothing;
if !(0.0..=1.0 + 1e-8).contains(&phi) {
return false;
}
if m == 0 {
let level_ok = alpha >= 1.0 - 1.0 / phi && alpha <= 1.0 + 1.0 / phi;
let slope_ok =
!trend || (beta >= alpha * (phi - 1.0) && beta <= (1.0 + phi) * (2.0 - alpha));
return level_ok && slope_ok;
}
seasonal_admissible(alpha, beta, gamma, phi, m)
}
fn seasonal_admissible(alpha: f64, beta: f64, gamma: f64, phi: f64, m: usize) -> bool {
let mf = count_as_f64(m);
let gamma_ok = gamma >= (1.0 - 1.0 / phi - alpha).max(0.0) && gamma <= 1.0 + 1.0 / phi - alpha;
let alpha_ok =
alpha >= 1.0 - 1.0 / phi - gamma * (1.0 - mf + phi + phi * mf) / (2.0 * phi * mf);
let beta_ok = beta >= -(1.0 - phi) * (gamma / mf + alpha);
if !(gamma_ok && alpha_ok && beta_ok) {
return false;
}
let middle = alpha + beta - alpha * phi;
let mut a = vec![alpha + beta - phi];
a.extend(core::iter::repeat_n(middle, m - 2));
a.push(middle + gamma - 1.0);
a.push(phi * (1.0 - alpha - gamma));
roots_inside(&a, 1.0 + 1e-10)
}
fn logistic(u: f64) -> f64 {
1.0 / (1.0 + math::exp(-u))
}
fn logit(p: f64) -> f64 {
math::ln(p / (1.0 - p))
}
#[expect(
clippy::cast_precision_loss,
reason = "series lengths and parameter counts stay far below 2^53, where the conversion is exact"
)]
pub(super) fn count_as_f64(count: usize) -> f64 {
count as f64
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn concentrated_states_minimise_the_squared_errors() {
let layout = Layout::of(&Ets::new().damped().seasonal(4));
let smoothing = layout.smoothing(&[-1.0, -2.0, -1.5, 0.5]);
let y: Vec<f64> = (0..40)
.map(|t| {
let t = f64::from(t);
20.0 + 0.3 * t + [2.0, -1.0, 0.5, -1.5][(t as usize) % 4] + (t * 1.7).sin()
})
.collect();
let best = layout.best_states(&smoothing, &y).unwrap();
let sse = |free: &[f64]| {
let (mut ring, mut errors) = (vec![0.0; 4], vec![0.0; y.len()]);
layout.errors(&smoothing, free, &y, &mut ring, &mut errors);
errors.iter().map(|e| e * e).sum::<f64>()
};
let minimum = sse(&best);
for j in 0..best.len() {
for step in [-1e-3, 1e-3] {
let mut moved = best.clone();
moved[j] += step;
assert!(sse(&moved) > minimum, "state {j}, step {step}");
}
}
}
#[test]
fn transforms_respect_rs_bounds() {
let layout = Layout::of(&Ets::new().damped().seasonal(4));
for u in [-40.0, 0.0, 40.0] {
let s = layout.smoothing(&[u, u, u, u]);
assert!((LOWER..=UPPER).contains(&s.alpha));
assert!(s.beta >= LOWER && s.beta <= s.alpha + 1e-12);
assert!(s.gamma >= LOWER - 1e-12 && s.gamma <= 1.0 - s.alpha + 1e-12);
assert!((PHI_BOUNDS.0..=PHI_BOUNDS.1).contains(&s.phi));
}
}
#[test]
fn seasonal_states_sum_to_their_constraint() {
let additive = Layout::of(&Ets::new().seasonal(3));
let mut seasonal = [0.0; 3];
assert_eq!(
additive.expand(&[10.0, 1.5, -0.5], &mut seasonal),
(10.0, 0.0)
);
assert_eq!(seasonal, [1.5, -0.5, -1.0]);
let model = Ets::new()
.error(Form::Multiplicative)
.seasonal(3)
.season(Form::Multiplicative);
Layout::of(&model).expand(&[10.0, 1.2, 0.9], &mut seasonal);
assert!((seasonal[2] - 0.9).abs() < 1e-12);
}
}