pub(crate) fn seasonal_product(
a: &[f64],
b: &[f64],
period: usize,
sign: f64,
out: &mut [f64],
) -> usize {
let n = a.len() + b.len() * period;
out[..n].fill(0.0);
out[..a.len()].copy_from_slice(a);
for (j, &bj) in b.iter().enumerate() {
let lag = (j + 1) * period;
out[lag - 1] += bj;
for (i, &ai) in a.iter().enumerate() {
out[lag + i] += sign * ai * bj;
}
}
n
}
pub(crate) fn differencing(d: usize, seasonal_d: usize, period: usize, out: &mut [f64]) -> usize {
let k = d + seasonal_d * period;
out[..=k].fill(0.0);
out[0] = 1.0;
let mut degree = 0;
for lag in core::iter::repeat_n(1, d).chain(core::iter::repeat_n(period, seasonal_d)) {
degree += lag;
for i in (lag..=degree).rev() {
out[i] -= out[i - lag];
}
}
k
}
pub(crate) fn apply(delta: &[f64], current: f64, lags: impl IntoIterator<Item = f64>) -> f64 {
delta[1..]
.iter()
.zip(lags)
.fold(current, |sum, (d, y)| sum + d * y)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ar_product_matches_hand_expansion() {
let mut out = [9.0; 6];
let n = seasonal_product(&[0.5], &[0.3], 4, -1.0, &mut out);
assert_eq!(n, 5);
assert_eq!(&out[..5], &[0.5, 0.0, 0.0, 0.3, -0.15]);
}
#[test]
fn ma_product_matches_hand_expansion() {
let mut out = [0.0; 5];
let n = seasonal_product(&[0.4], &[0.6, 0.2], 2, 1.0, &mut out);
assert_eq!(n, 5);
let expected = [0.4, 0.6, 0.24, 0.2, 0.08];
for (a, e) in out.iter().zip(expected) {
assert!((a - e).abs() < 1e-15, "{out:?}");
}
}
#[test]
fn differencing_polynomials() {
let mut out = [0.0; 8];
assert_eq!(differencing(0, 0, 4, &mut out), 0);
assert_eq!(out[0], 1.0);
assert_eq!(differencing(2, 0, 4, &mut out), 2);
assert_eq!(&out[..3], &[1.0, -2.0, 1.0]);
assert_eq!(differencing(1, 1, 4, &mut out), 5);
assert_eq!(&out[..6], &[1.0, -1.0, 0.0, 0.0, -1.0, 1.0]);
}
#[test]
fn apply_differences_a_window() {
let delta = [1.0, -1.0, 0.0, 0.0, -1.0, 1.0];
assert_eq!(apply(&delta, 10.0, [7.0, 3.0, 2.0, 6.0, 4.0]), 1.0);
}
}