use super::{Arima, FitError, bfgs, transform};
use crate::buffer::take;
use crate::filter::{ArimaSpec, Seasonal};
use crate::likelihood::{concentrated, workspace_len};
use crate::math;
pub(crate) struct Parameters<'a> {
pub(crate) ar: &'a [f64],
pub(crate) ma: &'a [f64],
pub(crate) seasonal_ar: &'a [f64],
pub(crate) seasonal_ma: &'a [f64],
pub(crate) mean: f64,
pub(crate) exog: &'a [f64],
}
pub(crate) struct Objective<'a> {
model: &'a Arima,
dy: &'a [f64],
dx: &'a [f64],
columns: usize,
pinned: &'a [f64],
params: &'a mut [f64],
work: &'a mut [f64],
centered: &'a mut [f64],
filter: &'a mut [f64],
}
impl<'a> Objective<'a> {
pub(crate) const fn scratch_len(model: &Arima, n: usize, columns: usize) -> usize {
let parameters = model.parameter_count(columns);
2 * parameters + n + workspace_len(model.arma_states())
}
pub(crate) fn new(
model: &'a Arima,
dy: &'a [f64],
dx: &'a [f64],
columns: usize,
pinned: &'a [f64],
mut scratch: &'a mut [f64],
) -> Self {
let parameters = model.parameter_count(columns);
Self {
model,
dy,
dx,
columns,
pinned,
params: take(&mut scratch, parameters),
work: take(&mut scratch, parameters),
centered: take(&mut scratch, dy.len()),
filter: scratch,
}
}
pub(crate) fn evaluate(&mut self, u: &[f64], steady: bool) -> Option<(f64, f64, usize)> {
self.constrain(u);
let parameters = split(self.model, self.params);
residual_into(
self.dy,
self.dx,
self.columns,
parameters.exog,
parameters.mean,
self.centered,
);
concentrated(
self.centered,
&shape(self.model, ¶meters),
steady,
self.filter,
)
}
#[cfg(feature = "alloc")]
pub(crate) const fn css_scratch_len(model: &Arima, n: usize, columns: usize) -> usize {
2 * model.arma_states() + n + model.parameter_count(columns)
}
#[cfg(feature = "alloc")]
pub(crate) fn css(&mut self, u: &[f64], mut scratch: &mut [f64]) -> Option<f64> {
self.constrain(u);
let parameters = split(self.model, self.params);
residual_into(
self.dy,
self.dx,
self.columns,
parameters.exog,
parameters.mean,
self.centered,
);
let shape = shape(self.model, ¶meters);
let r = shape.arma_states();
let phi = take(&mut scratch, r);
let selection = take(&mut scratch, r);
shape.expand_arma_into(phi, selection);
let w = &*self.centered;
let conditioned = self.model.p + self.model.seasonal_p * self.model.period;
let residuals = &mut scratch[..w.len()];
let mut sum = 0.0;
for t in 0..w.len() {
if t < conditioned {
residuals[t] = 0.0;
continue;
}
let mut e = w[t];
for i in 1..=conditioned {
e -= phi[i - 1] * w[t - i];
}
for j in 1..r.min(t + 1) {
e -= selection[j] * residuals[t - j];
}
residuals[t] = e;
sum += e * e;
}
let m = w.len().saturating_sub(conditioned);
if m == 0 || !sum.is_finite() || sum <= 0.0 {
return None;
}
Some(0.5 * math::ln(sum / m as f64))
}
fn range(&self) -> f64 {
let (low, high) = self
.dy
.iter()
.filter(|v| !v.is_nan())
.fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), &v| {
(low.min(v), high.max(v))
});
if high >= low { high - low } else { 0.0 }
}
pub(crate) fn parameters(&self) -> Parameters<'_> {
split(self.model, self.params)
}
fn constrain(&mut self, u: &[f64]) {
let model = self.model;
let parts = [
(model.p, true),
(model.q, false),
(model.seasonal_p, true),
(model.seasonal_q, false),
];
let mut start = 0;
for (len, negate) in parts {
let range = start..start + len;
transform::constrain(
&u[range.clone()],
&mut self.params[range.clone()],
self.work,
);
if negate {
for value in &mut self.params[range] {
*value = -*value;
}
}
start += len;
}
self.params[start..].copy_from_slice(&u[start..]);
for (value, &pin) in self.params.iter_mut().zip(self.pinned) {
if !pin.is_nan() {
*value = pin;
}
}
}
}
const NOISE_FLOOR: f64 = 1e-9;
pub(crate) struct Estimate {
pub(crate) loglike: f64,
pub(crate) sigma2: f64,
pub(crate) nobs: usize,
pub(crate) iterations: usize,
pub(crate) converged: bool,
}
pub(crate) fn estimate(
objective: &mut Objective<'_>,
x: &mut [f64],
bfgs_scratch: &mut [f64],
max_iterations: usize,
css: Css,
css_scratch: &mut [f64],
) -> Result<Estimate, FitError> {
let options = bfgs::Options {
max_iterations,
..bfgs::Options::default()
};
#[cfg(feature = "alloc")]
debug_assert!(
css == Css::Off
|| css_scratch.len()
>= Objective::css_scratch_len(
objective.model,
objective.dy.len(),
objective.columns
),
"CSS scratch too small"
);
#[cfg(not(feature = "alloc"))]
let _ = css_scratch;
let (iterations, converged) = match css {
Css::Off => exact_phase(objective, x, bfgs_scratch, options, 0, false),
#[cfg(feature = "alloc")]
Css::WarmStart => {
let (css_iterations, warm) =
css_phase(objective, x, bfgs_scratch, options, css_scratch);
exact_phase(objective, x, bfgs_scratch, options, css_iterations, warm)
}
#[cfg(feature = "alloc")]
Css::Only => {
let minimum = bfgs::minimize(
|u| objective.css(u, css_scratch).unwrap_or(f64::INFINITY),
x,
bfgs_scratch,
options,
);
(minimum.iterations, minimum.converged)
}
};
let (loglike, sigma2, nobs) = objective.evaluate(x, false).ok_or(FitError::Degenerate)?;
if math::sqrt(sigma2) <= NOISE_FLOOR * objective.range() {
return Err(FitError::Degenerate);
}
Ok(Estimate {
loglike,
sigma2,
nobs,
iterations,
converged,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Css {
Off,
#[cfg(feature = "alloc")]
WarmStart,
#[cfg(feature = "alloc")]
Only,
}
fn exact_phase(
objective: &mut Objective<'_>,
x: &mut [f64],
bfgs_scratch: &mut [f64],
options: bfgs::Options,
earlier: usize,
warm: bool,
) -> (usize, bool) {
let minimum = bfgs::minimize(
|u| exact(objective, u),
x,
bfgs_scratch,
bfgs::Options {
warm_hessian: warm,
..options
},
);
(earlier + minimum.iterations, minimum.converged)
}
fn exact(objective: &mut Objective<'_>, u: &[f64]) -> f64 {
match objective.evaluate(u, true) {
Some((llf, _, n)) => -llf / n as f64,
None => f64::INFINITY,
}
}
#[cfg(feature = "alloc")]
fn css_phase(
objective: &mut Objective<'_>,
x: &mut [f64],
bfgs_scratch: &mut [f64],
options: bfgs::Options,
mut scratch: &mut [f64],
) -> (usize, bool) {
let start = take(&mut scratch, x.len());
start.copy_from_slice(x);
let minimum = bfgs::minimize(
|u| objective.css(u, scratch).unwrap_or(f64::INFINITY),
x,
bfgs_scratch,
options,
);
if minimum.iterations > 0 && exact(objective, x) <= exact(objective, start) {
return (minimum.iterations, true);
}
x.copy_from_slice(start);
(minimum.iterations, false)
}
pub(crate) fn unconstrain_part(
coefficients: &[f64],
negate: bool,
out: &mut [f64],
work: &mut [f64],
) {
let n = coefficients.len();
let (input, work) = work.split_at_mut(n);
for (value, &c) in input.iter_mut().zip(coefficients) {
*value = if negate { -c } else { c };
}
if !transform::unconstrain(input, out, work) {
out[..n].fill(0.0);
}
}
fn shape<'p>(model: &Arima, parameters: &Parameters<'p>) -> ArimaSpec<'p> {
ArimaSpec {
ar: parameters.ar,
d: model.d,
ma: parameters.ma,
seasonal: Seasonal {
ar: parameters.seasonal_ar,
d: model.seasonal_d,
ma: parameters.seasonal_ma,
period: model.period,
},
..ArimaSpec::default()
}
}
fn split<'p>(model: &Arima, params: &'p [f64]) -> Parameters<'p> {
let (ar, rest) = params.split_at(model.p);
let (ma, rest) = rest.split_at(model.q);
let (seasonal_ar, rest) = rest.split_at(model.seasonal_p);
let (seasonal_ma, rest) = rest.split_at(model.seasonal_q);
let mean = if model.mean { rest[0] } else { 0.0 };
Parameters {
ar,
ma,
seasonal_ar,
seasonal_ma,
mean,
exog: &rest[usize::from(model.mean)..],
}
}
pub(crate) fn residual_into(
dy: &[f64],
dx: &[f64],
columns: usize,
beta: &[f64],
mean: f64,
out: &mut [f64],
) {
let n = dy.len();
for (t, value) in out.iter_mut().enumerate().take(n) {
let regression = (0..columns).map(|j| dx[j * n + t] * beta[j]).sum::<f64>();
*value = dy[t] - regression - mean;
}
}