use crate::buffer::take;
use crate::filter::{ArimaSpec, FilterError};
use crate::math;
#[cfg(feature = "alloc")]
use crate::polynomial;
use crate::state_space::{self, Innovation, LyapunovScratch, SteadyBuffers, SteadyState, System};
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "alloc")]
pub fn innovations(y: &[f64], spec: &ArimaSpec<'_>) -> Result<Vec<Innovation>, FilterError> {
innovations_exog(y, &[], spec)
}
#[cfg(feature = "alloc")]
pub fn innovations_exog(
y: &[f64],
regressors: &[f64],
spec: &ArimaSpec<'_>,
) -> Result<Vec<Innovation>, FilterError> {
spec.validate()?;
let w = demeaned_difference(®ressed(y, regressors, spec.exog), spec);
let mut buffer = vec![0.0; workspace_len(spec.arma_states())];
let mut result = Vec::with_capacity(w.len());
Workspace::new(spec, &mut buffer)?.run(&w, |innovation| result.push(innovation));
Ok(result)
}
#[cfg(feature = "alloc")]
pub fn loglike(y: &[f64], spec: &ArimaSpec<'_>) -> Result<f64, FilterError> {
loglike_exog(y, &[], spec)
}
#[cfg(feature = "alloc")]
pub fn loglike_exog(
y: &[f64],
regressors: &[f64],
spec: &ArimaSpec<'_>,
) -> Result<f64, FilterError> {
spec.validate()?;
let w = demeaned_difference(®ressed(y, regressors, spec.exog), spec);
let ln_two_pi = math::ln(core::f64::consts::TAU);
let mut sum = 0.0;
let mut buffer = vec![0.0; workspace_len(spec.arma_states())];
Workspace::new(spec, &mut buffer)?.run(&w, |Innovation { value, variance }| {
if !value.is_nan() {
sum += ln_two_pi + math::ln(variance) + value * value / variance;
}
});
Ok(-0.5 * sum)
}
pub(crate) fn concentrated(
w: &[f64],
shape: &ArimaSpec<'_>,
steady: bool,
buffer: &mut [f64],
) -> Option<(f64, f64, usize)> {
let spec = ArimaSpec {
d: 0,
mean: 0.0,
sigma2: 1.0,
..*shape
};
let (mut count, mut log_variances, mut weighted) = (0_usize, 0.0, 0.0);
let sink = |Innovation { value, variance }: Innovation| {
if !value.is_nan() {
count += 1;
log_variances += math::ln(variance);
weighted += value * value / variance;
}
};
let workspace = Workspace::new(&spec, buffer).ok()?;
if steady {
workspace.run_steady(w, sink);
} else {
workspace.run(w, sink);
}
if count == 0 {
return None;
}
let n = count as f64;
let sigma2 = weighted / n;
if !sigma2.is_finite() || sigma2 <= 0.0 {
return None;
}
let llf =
-0.5 * (n * (math::ln(core::f64::consts::TAU) + 1.0 + math::ln(sigma2)) + log_variances);
Some((llf, sigma2, count))
}
#[cfg(feature = "alloc")]
pub(crate) fn regressed(y: &[f64], regressors: &[f64], beta: &[f64]) -> Vec<f64> {
let m = beta.len();
assert_eq!(
regressors.len(),
y.len() * m,
"one regressor row per observation"
);
y.iter()
.enumerate()
.map(|(t, &value)| {
let row = ®ressors[t * m..(t + 1) * m];
value - row.iter().zip(beta).map(|(x, b)| x * b).sum::<f64>()
})
.collect()
}
#[cfg(feature = "alloc")]
fn demeaned_difference(y: &[f64], spec: &ArimaSpec<'_>) -> Vec<f64> {
let mut w = differenced(y, spec);
for value in &mut w {
*value -= spec.mean;
}
w
}
#[cfg(feature = "alloc")]
pub(crate) fn differenced(y: &[f64], spec: &ArimaSpec<'_>) -> Vec<f64> {
let k = spec.differencing_order();
let mut delta = vec![0.0; k + 1];
polynomial::differencing(spec.d, spec.seasonal.d, spec.seasonal.period, &mut delta);
(k..y.len())
.map(|t| polynomial::apply(&delta, y[t], (1..=k).map(|j| y[t - j])))
.collect()
}
pub(crate) const fn workspace_len(r: usize) -> usize {
r.saturating_mul(r)
.saturating_mul(4)
.saturating_add(r.saturating_mul(5))
}
struct Workspace<'b> {
phi: &'b mut [f64],
selection: &'b mut [f64],
sigma2: f64,
a: &'b mut [f64],
p: &'b mut [f64],
scratch: &'b mut [f64],
gain: &'b mut [f64],
previous: &'b mut [f64],
}
impl<'b> Workspace<'b> {
fn new(spec: &ArimaSpec<'_>, buffer: &'b mut [f64]) -> Result<Self, FilterError> {
spec.validate()?;
let r = spec.arma_states();
let mut buffer = &mut buffer[..workspace_len(r)];
buffer.fill(0.0);
let workspace = Self {
phi: take(&mut buffer, r),
selection: take(&mut buffer, r),
sigma2: spec.sigma2,
a: take(&mut buffer, r),
p: take(&mut buffer, r * r),
scratch: take(&mut buffer, r),
gain: take(&mut buffer, r),
previous: take(&mut buffer, r * r),
};
spec.expand_arma_into(workspace.phi, workspace.selection);
let scratch = LyapunovScratch {
power: workspace.previous,
product: take(&mut buffer, r * r),
term: buffer,
};
let system = System {
phi: workspace.phi,
selection: workspace.selection,
sigma2: workspace.sigma2,
};
if !state_space::stationary_covariance(system, workspace.p, r, scratch) {
return Err(FilterError::NonStationary);
}
Ok(workspace)
}
fn run(self, y: &[f64], mut sink: impl FnMut(Innovation)) {
let Self {
phi,
selection,
sigma2,
a,
p,
scratch,
..
} = self;
let r = phi.len();
let system = System {
phi,
selection,
sigma2,
};
for &value in y {
sink(state_space::update(r, a, p, r, value, scratch));
state_space::predict(system, a, p, r, scratch);
}
}
fn run_steady(self, y: &[f64], mut sink: impl FnMut(Innovation)) {
let Self {
phi,
selection,
sigma2,
a,
p,
scratch,
gain,
previous,
} = self;
let r = phi.len();
let system = System {
phi,
selection,
sigma2,
};
let mut steady = SteadyState::NEW;
for &value in y {
let buffers = SteadyBuffers {
gain,
previous,
scratch,
};
sink(steady.step(system, a, p, r, value, buffers));
}
}
}