use super::roots::max_inverse_root;
use super::{Arima, FitError, Fitted, Method};
use crate::fourier::{FourierError, fourier, fourier_columns};
use crate::stl::SEASONAL_STRENGTH_THRESHOLD;
use crate::{ndiffs, polynomial, stl};
use alloc::collections::BTreeMap;
use alloc::vec;
use alloc::vec::Vec;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Criterion {
#[default]
Aicc,
Aic,
Bic,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AutoArima {
period: usize,
max: Orders,
max_order: usize,
max_d: usize,
max_seasonal_d: usize,
d: Option<usize>,
seasonal_d: Option<usize>,
criterion: Criterion,
stepwise: bool,
approximation: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Orders {
p: usize,
q: usize,
seasonal_p: usize,
seasonal_q: usize,
}
impl Orders {
fn total(self) -> usize {
self.p + self.q + self.seasonal_p + self.seasonal_q
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct FourierFit {
pub fit: AutoFit,
pub terms: Vec<(f64, usize)>,
pub candidates: usize,
}
fn largest_k(period: f64, max_k: usize) -> usize {
max_k.min((period / 2.0) as usize)
}
#[derive(Debug, Clone, PartialEq)]
pub struct AutoFit {
pub fitted: Fitted,
pub criterion: f64,
pub candidates: usize,
}
impl Default for AutoArima {
fn default() -> Self {
Self::new()
}
}
const MAX_STEPWISE_MODELS: usize = 94;
const MAX_INVERSE_ROOT: f64 = 0.99;
impl AutoArima {
#[must_use]
pub fn new() -> Self {
Self {
period: 0,
max: Orders {
p: 5,
q: 5,
seasonal_p: 2,
seasonal_q: 2,
},
max_order: 5,
max_d: 2,
max_seasonal_d: 1,
d: None,
seasonal_d: None,
criterion: Criterion::Aicc,
stepwise: true,
approximation: false,
}
}
#[must_use]
pub fn seasonal(self, period: usize) -> Self {
Self { period, ..self }
}
#[must_use]
pub fn max_orders(self, p: usize, q: usize, seasonal_p: usize, seasonal_q: usize) -> Self {
Self {
max: Orders {
p,
q,
seasonal_p,
seasonal_q,
},
..self
}
}
#[must_use]
pub fn max_order(self, max_order: usize) -> Self {
Self { max_order, ..self }
}
#[must_use]
pub fn d(self, d: usize) -> Self {
Self { d: Some(d), ..self }
}
#[must_use]
pub fn seasonal_d(self, seasonal_d: usize) -> Self {
Self {
seasonal_d: Some(seasonal_d),
..self
}
}
#[must_use]
pub fn criterion(self, criterion: Criterion) -> Self {
Self { criterion, ..self }
}
#[must_use]
pub fn exhaustive(self) -> Self {
Self {
stepwise: false,
..self
}
}
#[must_use]
pub fn approximation(self, approximation: bool) -> Self {
Self {
approximation,
..self
}
}
pub fn fit(&self, y: &[f64]) -> Result<AutoFit, FitError> {
self.fit_exog(y, &[], 0)
}
pub fn fit_exog(
&self,
y: &[f64],
regressors: &[f64],
columns: usize,
) -> Result<AutoFit, FitError> {
if regressors.len() != y.len() * columns {
return Err(FitError::RegressorShape {
expected: y.len() * columns,
got: regressors.len(),
});
}
let (d, seasonal_d) = self.differencing(®ression_residuals(y, regressors, columns));
let search = Search {
auto: self,
y,
regressors,
columns,
d,
seasonal_d,
constant_allowed: d + seasonal_d <= 1,
seasonal: self.period > 1,
cache: BTreeMap::new(),
best: None,
};
search.run()
}
pub fn fit_fourier(&self, y: &[f64], periods: &[(f64, usize)]) -> Result<FourierFit, FitError> {
let auto = self.non_seasonal();
let mut terms = Vec::with_capacity(periods.len());
for &(period, max_k) in periods {
if !period.is_finite() || period < 2.0 || max_k == 0 {
return Err(FourierError::InvalidTerms.into());
}
terms.push((period, 1));
}
let mut best = auto.fit_terms(y, &terms)?;
let mut candidates = 1;
for (j, &(period, max_k)) in periods.iter().enumerate() {
let largest = largest_k(period, max_k);
let start = terms[j].1;
let mut chosen = start;
for k in (1..=largest).filter(|&k| k != start) {
terms[j].1 = k;
candidates += 1;
if let Ok(fit) = auto.fit_terms(y, &terms) {
if fit.criterion < best.criterion {
best = fit;
chosen = k;
}
}
}
terms[j].1 = chosen;
}
Ok(FourierFit {
fit: best,
terms,
candidates,
})
}
pub(super) fn non_seasonal(&self) -> Self {
Self {
period: 0,
seasonal_d: Some(0),
..*self
}
}
fn fit_terms(&self, y: &[f64], terms: &[(f64, usize)]) -> Result<AutoFit, FitError> {
let regressors = fourier(terms, 0, y.len())?;
let columns = terms.iter().map(|&(p, k)| fourier_columns(p, k)).sum();
self.fit_exog(y, ®ressors, columns)
}
fn differencing(&self, x: &[f64]) -> (usize, usize) {
let seasonal_d = match (self.seasonal_d, self.period > 1) {
(Some(seasonal_d), true) => seasonal_d,
(None, true) => nsdiffs(x, self.period, self.max_seasonal_d),
(_, false) => 0,
};
let mut seasonally = x.to_vec();
for _ in 0..seasonal_d {
seasonally = seasonal_difference(&seasonally, self.period);
}
let d = self
.d
.unwrap_or_else(|| ndiffs(&seasonally, 0.05, self.max_d));
(d, seasonal_d)
}
}
type Key = (Orders, bool);
struct Search<'a> {
auto: &'a AutoArima,
y: &'a [f64],
regressors: &'a [f64],
columns: usize,
d: usize,
seasonal_d: usize,
constant_allowed: bool,
seasonal: bool,
cache: BTreeMap<Key, (f64, Result<Fitted, FitError>)>,
best: Option<(Key, f64)>,
}
impl Search<'_> {
fn run(mut self) -> Result<AutoFit, FitError> {
if self.auto.stepwise {
self.stepwise();
} else {
self.exhaustive();
}
let candidates = self.cache.len();
if self.auto.approximation {
return self.refit_exactly(candidates);
}
let Some((key, criterion)) = self.best else {
return Err(self.first_error());
};
let fitted = self
.cache
.remove(&key)
.and_then(|(_, fitted)| fitted.ok())
.expect("the best key was cached with its fit");
Ok(AutoFit {
fitted,
criterion,
candidates,
})
}
fn refit_exactly(&self, candidates: usize) -> Result<AutoFit, FitError> {
let mut ranked: Vec<(f64, Key)> = self
.cache
.iter()
.filter(|(_, (score, _))| score.is_finite())
.map(|(key, (score, _))| (*score, *key))
.collect();
ranked.sort_by(|a, b| a.0.total_cmp(&b.0));
for (_, (orders, constant)) in ranked {
if let (criterion, Ok(fitted)) = self.score_with(orders, constant, Method::Exact) {
if criterion.is_finite() {
return Ok(AutoFit {
fitted,
criterion,
candidates,
});
}
}
}
Err(self.first_error())
}
fn first_error(&self) -> FitError {
self.cache
.values()
.find_map(|(_, fitted)| fitted.as_ref().err().copied())
.unwrap_or(FitError::Degenerate)
}
fn stepwise(&mut self) {
let max = self.limits();
let mut constant = self.constant_allowed;
let mut at = Orders {
p: max.p.min(2),
q: max.q.min(2),
seasonal_p: max.seasonal_p.min(1),
seasonal_q: max.seasonal_q.min(1),
};
self.try_model(at, constant);
let null = Orders {
p: 0,
q: 0,
seasonal_p: 0,
seasonal_q: 0,
};
if self.try_model(null, constant) {
at = null;
}
if max.p > 0 || max.seasonal_p > 0 {
let ar = Orders {
p: usize::from(max.p > 0),
seasonal_p: usize::from(max.seasonal_p > 0),
..null
};
if self.try_model(ar, constant) {
at = ar;
}
}
if max.q > 0 || max.seasonal_q > 0 {
let ma = Orders {
q: usize::from(max.q > 0),
seasonal_q: usize::from(max.seasonal_q > 0),
..null
};
if self.try_model(ma, constant) {
at = ma;
}
}
if constant && self.try_model(null, false) {
at = null;
constant = false;
}
while self.cache.len() < MAX_STEPWISE_MODELS {
match self.improving_neighbour(at, constant, max) {
Some((next, next_constant)) => {
at = next;
constant = next_constant;
}
None => break,
}
}
}
fn improving_neighbour(
&mut self,
at: Orders,
constant: bool,
max: Orders,
) -> Option<(Orders, bool)> {
const MOVES: [(isize, isize, isize, isize); 16] = [
(0, 0, -1, 0),
(0, 0, 0, -1),
(0, 0, 1, 0),
(0, 0, 0, 1),
(0, 0, -1, -1),
(0, 0, -1, 1),
(0, 0, 1, -1),
(0, 0, 1, 1),
(-1, 0, 0, 0),
(0, -1, 0, 0),
(1, 0, 0, 0),
(0, 1, 0, 0),
(-1, -1, 0, 0),
(-1, 1, 0, 0),
(1, -1, 0, 0),
(1, 1, 0, 0),
];
let mut candidates: Vec<Key> = MOVES
.iter()
.filter_map(|&delta| moved(at, delta, max))
.map(|orders| (orders, constant))
.collect();
if self.constant_allowed {
candidates.push((at, !constant));
}
candidates.retain(|key| !self.cache.contains_key(key));
let mut speculative = self.speculate(&candidates).into_iter();
for key in candidates {
if self.cache.len() >= MAX_STEPWISE_MODELS {
return None;
}
let score = speculative
.next()
.unwrap_or_else(|| self.score(key.0, key.1));
if self.record(key, score) {
return Some(key);
}
}
None
}
fn exhaustive(&mut self) {
let max = self.limits();
let constants: &[bool] = if self.constant_allowed {
&[true, false]
} else {
&[false]
};
let mut keys = Vec::new();
for p in 0..=max.p {
for q in 0..=max.q {
for seasonal_p in 0..=max.seasonal_p {
for seasonal_q in 0..=max.seasonal_q {
let orders = Orders {
p,
q,
seasonal_p,
seasonal_q,
};
if orders.total() <= self.auto.max_order {
keys.extend(constants.iter().map(|&c| (orders, c)));
}
}
}
}
}
for (key, scored) in keys.iter().zip(self.score_all(&keys)) {
self.record(*key, scored);
}
}
fn score_all(&self, keys: &[Key]) -> Vec<(f64, Result<Fitted, FitError>)> {
#[cfg(feature = "rayon")]
{
use rayon::prelude::*;
keys.par_iter()
.map(|&(orders, constant)| self.score(orders, constant))
.collect()
}
#[cfg(not(feature = "rayon"))]
{
keys.iter()
.map(|&(orders, constant)| self.score(orders, constant))
.collect()
}
}
fn speculate(&self, keys: &[Key]) -> Vec<(f64, Result<Fitted, FitError>)> {
if cfg!(feature = "rayon") && self.seasonal {
let room = MAX_STEPWISE_MODELS.saturating_sub(self.cache.len());
self.score_all(&keys[..keys.len().min(room)])
} else {
Vec::new()
}
}
fn limits(&self) -> Orders {
let max = self.auto.max;
if self.seasonal {
max
} else {
Orders {
seasonal_p: 0,
seasonal_q: 0,
..max
}
}
}
fn try_model(&mut self, orders: Orders, constant: bool) -> bool {
let key = (orders, constant);
if self.cache.contains_key(&key) {
return false;
}
let scored = self.score(orders, constant);
self.record(key, scored)
}
fn record(&mut self, key: Key, scored: (f64, Result<Fitted, FitError>)) -> bool {
let score = scored.0;
self.cache.insert(key, scored);
let improves = score.is_finite() && self.best.is_none_or(|(_, best)| score < best);
if improves {
self.best = Some((key, score));
}
improves
}
fn score(&self, orders: Orders, constant: bool) -> (f64, Result<Fitted, FitError>) {
let method = if self.auto.approximation {
Method::Css
} else {
Method::Exact
};
self.score_with(orders, constant, method)
}
fn score_with(
&self,
orders: Orders,
constant: bool,
method: Method,
) -> (f64, Result<Fitted, FitError>) {
let model = Arima::new(orders.p, self.d, orders.q);
let model = if self.seasonal {
model.seasonal(
orders.seasonal_p,
self.seasonal_d,
orders.seasonal_q,
self.auto.period,
)
} else {
model
};
let model = model.mean(constant).method(method);
let fitted = match model.fit_exog(self.y, self.regressors, self.columns) {
Ok(fitted) => fitted,
Err(error) => return (f64::INFINITY, Err(error)),
};
let value = match self.auto.criterion {
Criterion::Aicc => fitted.aicc(),
Criterion::Aic => fitted.aic(),
Criterion::Bic => fitted.bic(),
};
if !value.is_finite() || near_unit_root(&fitted) {
return (f64::INFINITY, Ok(fitted));
}
(value, Ok(fitted))
}
}
fn moved(at: Orders, delta: (isize, isize, isize, isize), max: Orders) -> Option<Orders> {
let step = |value: usize, by: isize, limit: usize| {
let next = value.checked_add_signed(by)?;
(next <= limit).then_some(next)
};
Some(Orders {
p: step(at.p, delta.0, max.p)?,
q: step(at.q, delta.1, max.q)?,
seasonal_p: step(at.seasonal_p, delta.2, max.seasonal_p)?,
seasonal_q: step(at.seasonal_q, delta.3, max.seasonal_q)?,
})
}
fn near_unit_root(fitted: &Fitted) -> bool {
let expand = |a: &[f64], b: &[f64], sign: f64| {
let mut out = vec![0.0; a.len() + b.len() * fitted.period];
polynomial::seasonal_product(a, b, fitted.period, sign, &mut out);
out
};
let ar: Vec<f64> = expand(&fitted.ar, &fitted.seasonal_ar, -1.0)
.iter()
.map(|c| -c)
.collect();
let ma = expand(&fitted.ma, &fitted.seasonal_ma, 1.0);
max_inverse_root(&ar) > MAX_INVERSE_ROOT || max_inverse_root(&ma) > MAX_INVERSE_ROOT
}
fn seasonal_difference(x: &[f64], period: usize) -> Vec<f64> {
(period..x.len()).map(|t| x[t] - x[t - period]).collect()
}
fn regression_residuals(y: &[f64], regressors: &[f64], columns: usize) -> Vec<f64> {
if columns == 0 {
return y.to_vec();
}
let row = |t: usize| {
let mut r = vec![1.0];
r.extend_from_slice(®ressors[t * columns..(t + 1) * columns]);
r
};
let complete: Vec<usize> = (0..y.len())
.filter(|&t| y[t].is_finite() && row(t).iter().all(|v| v.is_finite()))
.collect();
let rows: Vec<Vec<f64>> = complete.iter().map(|&t| row(t)).collect();
let targets: Vec<f64> = complete.iter().map(|&t| y[t]).collect();
match super::hannan_rissanen::least_squares(&rows, &targets) {
Some(beta) => (0..y.len())
.map(|t| y[t] - row(t).iter().zip(&beta).map(|(x, b)| x * b).sum::<f64>())
.collect(),
None => y.to_vec(),
}
}
#[must_use]
pub fn nsdiffs(x: &[f64], period: usize, max_seasonal_d: usize) -> usize {
let mut series = x.to_vec();
for seasonal_d in 0..max_seasonal_d {
let strength = stl(&series, period).map_or(0.0, |parts| parts.seasonal_strength());
if strength <= SEASONAL_STRENGTH_THRESHOLD {
return seasonal_d;
}
series = seasonal_difference(&series, period);
}
max_seasonal_d
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn moves_respect_bounds() {
let max = Orders {
p: 2,
q: 2,
seasonal_p: 1,
seasonal_q: 1,
};
let at = Orders {
p: 0,
q: 2,
seasonal_p: 1,
seasonal_q: 0,
};
assert_eq!(moved(at, (-1, 0, 0, 0), max), None);
assert_eq!(moved(at, (0, 1, 0, 0), max), None);
assert_eq!(moved(at, (0, 0, 1, 0), max), None);
assert_eq!(
moved(at, (1, -1, -1, 1), max),
Some(Orders {
p: 1,
q: 1,
seasonal_p: 0,
seasonal_q: 1
})
);
}
#[test]
fn nsdiffs_separates_seasonal_and_noise() {
let seasonal: Vec<f64> = (0..48)
.map(|t| [3.0, -1.0, 0.5, -2.5][t % 4] + 0.05 * t as f64)
.collect();
assert_eq!(nsdiffs(&seasonal, 4, 1), 1);
let mut state = 9_u32;
let noise: Vec<f64> = (0..48)
.map(|_| {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
f64::from(state >> 8) / f64::from(1_u32 << 24)
})
.collect();
assert_eq!(nsdiffs(&noise, 4, 1), 0);
assert_eq!(nsdiffs(&noise[..7], 4, 1), 0);
}
#[test]
fn failed_search_reports_the_simplest_candidate_error() {
assert_eq!(
AutoArima::new().d(0).fit(&[1.0]),
Err(FitError::TooShort {
needed: 2,
present: 1
})
);
}
#[test]
fn infinite_regressor_counts_as_missing() {
let y: Vec<f64> = (0..40).map(|t| f64::from((t * 7) % 11)).collect();
let mut x: Vec<f64> = (0..40).map(|t| f64::from(t % 5)).collect();
x[10] = f64::INFINITY;
let best = AutoArima::new().fit_exog(&y, &x, 1).unwrap();
assert!(best.criterion.is_finite());
}
}