use ndarray::{Array1, Array2};
use solow_core::error::{Error, Result};
use solow_distributions::norm_sf;
use solow_linalg::{inv, solve};
use crate::tsatools::Trend;
#[derive(Debug, Clone)]
pub struct AutoReg {
endog: Array1<f64>,
lags: usize,
trend: Trend,
}
#[derive(Debug, Clone)]
pub struct AutoRegResults {
pub params: Array1<f64>,
pub bse: Array1<f64>,
pub tvalues: Array1<f64>,
pub pvalues: Array1<f64>,
pub sigma2: f64,
pub llf: f64,
pub aic: f64,
pub bic: f64,
pub hqic: f64,
pub nobs: usize,
pub df_model: usize,
pub fittedvalues: Array1<f64>,
pub resid: Array1<f64>,
}
impl AutoReg {
pub fn new(endog: Array1<f64>, lags: usize, trend: Trend) -> Result<Self> {
if lags >= endog.len() {
return Err(Error::Value("lags must be smaller than nobs".into()));
}
solow_core::tools::ensure_all_finite(&endog.view(), "endog")?;
Ok(Self { endog, lags, trend })
}
fn ntrend(&self) -> usize {
match self.trend {
Trend::N => 0,
Trend::C | Trend::T => 1,
Trend::Ct => 2,
Trend::Ctt => 3,
}
}
fn trend_powers(&self) -> Vec<i32> {
match self.trend {
Trend::N => vec![],
Trend::C => vec![0],
Trend::T => vec![1],
Trend::Ct => vec![0, 1],
Trend::Ctt => vec![0, 1, 2],
}
}
fn build(&self) -> (Array1<f64>, Array2<f64>) {
let n = self.endog.len();
let p = self.lags;
let nobs = n - p;
let ntrend = self.ntrend();
let powers = self.trend_powers();
let k = ntrend + p;
let mut x = Array2::<f64>::zeros((nobs, k));
let mut y = Array1::<f64>::zeros(nobs);
for i in 0..nobs {
let t = p + i; y[i] = self.endog[t];
let time = (t + 1) as f64;
for (c, &power) in powers.iter().enumerate() {
x[[i, c]] = time.powi(power);
}
for j in 0..p {
x[[i, ntrend + j]] = self.endog[t - 1 - j];
}
}
(y, x)
}
pub fn fit(&self) -> Result<AutoRegResults> {
let (y, x) = self.build();
let (nobs, k) = x.dim();
let xtx = x.t().dot(&x);
let xty = x.t().dot(&y);
let params = solve(&xtx, &xty)?;
let fitted = x.dot(¶ms);
let resid = &y - &fitted;
let ssr = resid.dot(&resid);
let nobs_f = nobs as f64;
let sigma2 = ssr / nobs_f;
let xtx_inv = inv(&xtx)?;
let mut bse = Array1::<f64>::zeros(k);
for j in 0..k {
bse[j] = (sigma2 * xtx_inv[[j, j]]).sqrt();
}
let tvalues = ¶ms / &bse;
let pvalues = tvalues.mapv(|t| 2.0 * norm_sf(t.abs()));
let llf = -(nobs_f / 2.0) * ((2.0 * std::f64::consts::PI).ln() + (ssr / nobs_f).ln() + 1.0);
let kp = (k + 1) as f64;
let aic = -2.0 * llf + 2.0 * kp;
let bic = -2.0 * llf + nobs_f.ln() * kp;
let hqic = -2.0 * llf + 2.0 * nobs_f.ln().ln() * kp;
Ok(AutoRegResults {
params,
bse,
tvalues,
pvalues,
sigma2,
llf,
aic,
bic,
hqic,
nobs,
df_model: k,
fittedvalues: fitted,
resid,
})
}
}