#[cfg(feature = "alloc")]
mod auto;
mod bfgs;
#[cfg(feature = "alloc")]
mod hannan_rissanen;
mod objective;
mod refit;
#[cfg(feature = "alloc")]
mod roots;
mod transform;
#[cfg(feature = "alloc")]
pub use auto::{AutoArima, AutoFit, Criterion, nsdiffs};
#[cfg(feature = "alloc")]
pub use hannan_rissanen::{ArmaCoefficients, hannan_rissanen};
pub use refit::{Refit, RefitOptions, Refitter};
#[cfg(feature = "alloc")]
use crate::filter::{ArimaSpec, Seasonal};
#[cfg(feature = "alloc")]
use crate::likelihood::differenced;
#[cfg(feature = "alloc")]
use crate::math;
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::error::Error;
use core::fmt::{Display, Formatter};
#[cfg(feature = "alloc")]
use objective::Objective;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Arima {
p: usize,
d: usize,
q: usize,
seasonal_p: usize,
seasonal_d: usize,
seasonal_q: usize,
period: usize,
mean: bool,
}
impl Arima {
const fn coefficients(&self) -> usize {
self.p + self.q + self.seasonal_p + self.seasonal_q
}
const fn parameter_count(&self, columns: usize) -> usize {
self.coefficients() + self.mean as usize + columns
}
const fn arma_states(&self) -> usize {
let ar = self.p + self.seasonal_p * self.period;
let ma = self.q + self.seasonal_q * self.period;
if ar > ma { ar } else { ma + 1 }
}
}
#[cfg(feature = "alloc")]
impl Arima {
#[must_use]
pub fn new(p: usize, d: usize, q: usize) -> Self {
Self {
p,
d,
q,
seasonal_p: 0,
seasonal_d: 0,
seasonal_q: 0,
period: 0,
mean: d == 0,
}
}
#[must_use]
pub fn seasonal(self, p: usize, d: usize, q: usize, period: usize) -> Self {
assert!(
period > 0 || p + d + q == 0,
"a seasonal part needs a period of at least 1"
);
Self {
seasonal_p: p,
seasonal_d: d,
seasonal_q: q,
period,
mean: self.mean && d == 0,
..self
}
}
#[must_use]
pub fn mean(self, include: bool) -> Self {
Self {
mean: include,
..self
}
}
pub fn fit(&self, y: &[f64]) -> Result<Fitted, FitError> {
self.fit_exog(y, &[], 0)
}
pub fn fit_exog(
&self,
y: &[f64],
regressors: &[f64],
columns: usize,
) -> Result<Fitted, FitError> {
if regressors.len() != y.len() * columns {
return Err(FitError::RegressorShape {
expected: y.len() * columns,
got: regressors.len(),
});
}
let differencing = self.differencing();
let dy = differenced(&missing_if_infinite(y), &differencing);
let dx: Vec<f64> = (0..columns)
.flat_map(|j| {
let column: Vec<f64> = (0..y.len()).map(|t| regressors[t * columns + j]).collect();
differenced(&missing_if_infinite(&column), &differencing)
})
.collect();
let present = (0..dy.len())
.filter(|&t| !residual_is_missing(&dy, &dx, columns, t))
.count();
let needed = self.coefficients() + columns + usize::from(self.mean) + 2;
if present < needed {
return Err(FitError::TooShort { needed, present });
}
let beta_start = self.least_squares_start(&dy, &dx, columns);
let mut residual = vec![0.0; dy.len()];
objective::residual_into(&dy, &dx, columns, &beta_start, 0.0, &mut residual);
let mut x = self.start(&residual, &beta_start);
let mut scratch = vec![0.0; Objective::scratch_len(self, dy.len(), columns)];
let mut objective = Objective::new(self, &dy, &dx, columns, &mut scratch);
let mut bfgs_scratch = vec![0.0; bfgs::scratch_len(x.len())];
let max_iterations = bfgs::Options::default().max_iterations;
let estimate =
objective::estimate(&mut objective, &mut x, &mut bfgs_scratch, max_iterations)?;
let parameters = objective.parameters();
Ok(Fitted {
ar: parameters.ar.to_vec(),
d: self.d,
ma: parameters.ma.to_vec(),
seasonal_ar: parameters.seasonal_ar.to_vec(),
seasonal_d: self.seasonal_d,
seasonal_ma: parameters.seasonal_ma.to_vec(),
period: self.period,
exog: parameters.exog.to_vec(),
with_mean: self.mean,
mean: parameters.mean,
sigma2: estimate.sigma2,
loglike: estimate.loglike,
nobs: estimate.nobs,
iterations: estimate.iterations,
converged: estimate.converged,
})
}
fn least_squares_start(&self, dy: &[f64], dx: &[f64], columns: usize) -> Vec<f64> {
if columns == 0 {
return Vec::new();
}
let complete: Vec<usize> = (0..dy.len())
.filter(|&t| !residual_is_missing(dy, dx, columns, t))
.collect();
let rows: Vec<Vec<f64>> = complete
.iter()
.map(|&t| {
let mut row: Vec<f64> = (0..columns).map(|j| dx[j * dy.len() + t]).collect();
if self.mean {
row.push(1.0);
}
row
})
.collect();
let targets: Vec<f64> = complete.iter().map(|&t| dy[t]).collect();
hannan_rissanen::least_squares(&rows, &targets)
.map(|mut b| {
b.truncate(columns);
b
})
.unwrap_or_else(|| vec![0.0; columns])
}
fn differencing(&self) -> ArimaSpec<'static> {
ArimaSpec {
d: self.d,
seasonal: Seasonal {
d: self.seasonal_d,
period: self.period,
..Seasonal::NONE
},
..ArimaSpec::default()
}
}
fn start(&self, w: &[f64], beta: &[f64]) -> Vec<f64> {
let present: Vec<f64> = w.iter().copied().filter(|v| !v.is_nan()).collect();
let sample_mean = present.iter().sum::<f64>() / present.len() as f64;
let mean = if self.mean { sample_mean } else { 0.0 };
let centered: Vec<f64> = w.iter().map(|v| v - mean).collect();
let estimate = hannan_rissanen(¢ered, self.p, self.q);
let (ar, ma) = estimate.map_or((Vec::new(), Vec::new()), |s| (s.ar, s.ma));
let mut start = vec![0.0; self.coefficients()];
let mut work = vec![0.0; 3 * self.p.max(self.q)];
if ar.len() == self.p {
objective::unconstrain_part(&ar, true, &mut start[..self.p], &mut work);
}
if ma.len() == self.q {
let ma_start = &mut start[self.p..self.p + self.q];
objective::unconstrain_part(&ma, false, ma_start, &mut work);
}
if self.mean {
start.push(mean);
}
start.extend_from_slice(beta);
start
}
}
#[cfg(feature = "alloc")]
fn missing_if_infinite(values: &[f64]) -> Vec<f64> {
values
.iter()
.map(|&v| if v.is_finite() { v } else { f64::NAN })
.collect()
}
#[cfg(feature = "alloc")]
fn residual_is_missing(dy: &[f64], dx: &[f64], columns: usize, t: usize) -> bool {
dy[t].is_nan() || (0..columns).any(|j| dx[j * dy.len() + t].is_nan())
}
#[cfg(feature = "alloc")]
#[derive(Debug, Clone, PartialEq)]
pub struct Fitted {
pub ar: Vec<f64>,
pub d: usize,
pub ma: Vec<f64>,
pub seasonal_ar: Vec<f64>,
pub seasonal_d: usize,
pub seasonal_ma: Vec<f64>,
pub period: usize,
pub exog: Vec<f64>,
pub with_mean: bool,
pub mean: f64,
pub sigma2: f64,
pub loglike: f64,
pub nobs: usize,
pub iterations: usize,
pub converged: bool,
}
#[cfg(feature = "alloc")]
impl Fitted {
#[must_use]
pub fn parameters(&self) -> usize {
self.ar.len()
+ self.ma.len()
+ self.seasonal_ar.len()
+ self.seasonal_ma.len()
+ self.exog.len()
+ usize::from(self.with_mean)
+ 1
}
#[must_use]
pub fn aic(&self) -> f64 {
-2.0 * self.loglike + 2.0 * self.parameters() as f64
}
#[must_use]
pub fn aicc(&self) -> f64 {
let k = self.parameters() as f64;
let n = self.nobs as f64;
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 + self.parameters() as f64 * math::ln(self.nobs as f64)
}
#[must_use]
pub fn spec(&self) -> ArimaSpec<'_> {
ArimaSpec {
ar: &self.ar,
d: self.d,
ma: &self.ma,
seasonal: Seasonal {
ar: &self.seasonal_ar,
d: self.seasonal_d,
ma: &self.seasonal_ma,
period: self.period,
},
exog: &self.exog,
mean: self.mean,
sigma2: self.sigma2,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FitError {
RegressorShape {
expected: usize,
got: usize,
},
TooShort {
needed: usize,
present: usize,
},
Degenerate,
BufferTooSmall {
needed: usize,
got: usize,
},
}
impl Display for FitError {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
match self {
FitError::RegressorShape { expected, got } => {
write!(f, "expected {expected} regressor values, got {got}")
}
FitError::TooShort { needed, present } => {
write!(
f,
"model needs {needed} values after differencing, got {present}"
)
}
FitError::Degenerate => write!(f, "the series leaves no innovation variance"),
FitError::BufferTooSmall { needed, got } => {
write!(f, "buffer holds {got} values, needs {needed}")
}
}
}
}
impl Error for FitError {}
#[cfg(all(test, feature = "alloc"))]
mod tests {
use super::*;
#[test]
fn near_unit_root_stays_stationary() {
let mut y = alloc::vec![0.0; 80];
let mut state = 1_u32;
for t in 1..y.len() {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let noise = f64::from(state >> 8) / f64::from(1_u32 << 24) - 0.5;
y[t] = y[t - 1] + noise;
}
let fitted = Arima::new(1, 0, 0).fit(&y).unwrap();
assert!(fitted.ar[0] > 0.8 && fitted.ar[0] < 1.0, "{fitted:?}");
assert!(fitted.loglike.is_finite() && fitted.sigma2 > 0.0);
}
#[test]
fn too_short() {
let error = Arima::new(1, 1, 1).fit(&[1.0, 2.0, 3.0]).unwrap_err();
assert_eq!(
error,
FitError::TooShort {
needed: 4,
present: 2
}
);
}
#[test]
fn exact_fits_are_degenerate() {
assert_eq!(
Arima::new(1, 0, 0).fit(&[5.0; 30]),
Err(FitError::Degenerate)
);
let line: Vec<f64> = (0..30).map(f64::from).collect();
assert_eq!(
Arima::new(0, 1, 1).mean(true).fit(&line),
Err(FitError::Degenerate)
);
let huge: Vec<f64> = (0..30).map(|t| 1e200 * f64::from(t % 3)).collect();
assert_eq!(Arima::new(1, 0, 0).fit(&huge), Err(FitError::Degenerate));
}
#[test]
fn infinite_values_count_as_missing() {
let y: Vec<f64> = (0..40).map(|t| f64::from((t * 7) % 11)).collect();
let x: Vec<f64> = (0..40).map(|t| f64::from(t % 5)).collect();
let mut with_infinity = y.clone();
with_infinity[3] = f64::INFINITY;
let mut with_nan = y;
with_nan[3] = f64::NAN;
let model = Arima::new(1, 0, 0);
let fitted = model.fit_exog(&with_infinity, &x, 1).unwrap();
assert_eq!(fitted, model.fit_exog(&with_nan, &x, 1).unwrap());
assert!(fitted.loglike.is_finite() && fitted.sigma2 > 0.0);
}
#[test]
fn criteria_formulas() {
let fitted = Fitted {
ar: alloc::vec![0.5],
d: 0,
ma: alloc::vec![0.2, 0.1],
seasonal_ar: alloc::vec![],
seasonal_d: 0,
seasonal_ma: alloc::vec![],
period: 0,
exog: alloc::vec![],
with_mean: true,
mean: 1.0,
sigma2: 1.0,
loglike: -50.0,
nobs: 40,
iterations: 3,
converged: true,
};
assert_eq!(fitted.parameters(), 5);
assert_eq!(fitted.aic(), 110.0);
assert!((fitted.aicc() - (110.0 + 60.0 / 34.0)).abs() < 1e-12);
assert!((fitted.bic() - (100.0 + 5.0 * 40.0_f64.ln())).abs() < 1e-12);
let tiny = Fitted { nobs: 6, ..fitted };
assert_eq!(tiny.aicc(), f64::INFINITY);
}
#[test]
fn reported_loglike_is_exact() {
let mut y = alloc::vec![0.0; 400];
let mut state = 5_u32;
for t in 1..y.len() {
state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
y[t] = 0.5 * y[t - 1] + f64::from(state >> 8) / f64::from(1_u32 << 24) - 0.5;
}
let fitted = Arima::new(1, 0, 1).fit(&y).unwrap();
let exact = crate::loglike(&y, &fitted.spec()).unwrap();
assert!(
(fitted.loglike - exact).abs() < 1e-10,
"{} vs {exact}",
fitted.loglike
);
}
#[test]
fn regressor_shape_is_checked() {
let error = Arima::new(1, 0, 0)
.fit_exog(&[1.0, 2.0, 3.0], &[1.0, 2.0], 1)
.unwrap_err();
assert_eq!(
error,
FitError::RegressorShape {
expected: 3,
got: 2
}
);
}
#[test]
fn mean_defaults_follow_statsmodels() {
assert!(Arima::new(1, 0, 0).mean);
assert!(!Arima::new(1, 1, 0).mean);
assert!(Arima::new(1, 1, 0).mean(true).mean);
}
}