use ndarray::{Array1, Array2};
use solow_core::error::{Error, Result};
#[derive(Clone, Debug, PartialEq)]
pub enum CovType {
Hc0,
Hc1,
Hc2,
Hc3,
Hac {
maxlags: usize,
use_correction: bool,
},
Cluster {
groups: Vec<i64>,
use_correction: bool,
},
}
fn leverages(x: &Array2<f64>, normalized_cov_params: &Array2<f64>) -> Array1<f64> {
let xc = x.dot(normalized_cov_params); let n = x.nrows();
let k = x.ncols();
let mut h = Array1::<f64>::zeros(n);
for i in 0..n {
let mut acc = 0.0;
for j in 0..k {
acc += xc[[i, j]] * x[[i, j]];
}
h[i] = acc;
}
h
}
fn hccm_diag(
x: &Array2<f64>,
scale: &Array1<f64>,
normalized_cov_params: &Array2<f64>,
) -> Array2<f64> {
let k = x.ncols();
let n = x.nrows();
let mut meat = Array2::<f64>::zeros((k, k));
for i in 0..n {
let s = scale[i];
if s == 0.0 {
continue;
}
let row = x.row(i);
for a in 0..k {
let xa = row[a] * s;
for b in 0..k {
meat[[a, b]] += xa * row[b];
}
}
}
sandwich(normalized_cov_params, &meat)
}
fn sandwich(bread: &Array2<f64>, meat: &Array2<f64>) -> Array2<f64> {
bread.dot(meat).dot(&bread.t())
}
fn bartlett_weights(maxlags: usize) -> Vec<f64> {
(0..=maxlags)
.map(|l| 1.0 - (l as f64) / ((maxlags + 1) as f64))
.collect()
}
fn scores(x: &Array2<f64>, resid: &Array1<f64>) -> Array2<f64> {
let n = x.nrows();
let k = x.ncols();
let mut xu = Array2::<f64>::zeros((n, k));
for i in 0..n {
let u = resid[i];
for j in 0..k {
xu[[i, j]] = x[[i, j]] * u;
}
}
xu
}
fn s_hac(xu: &Array2<f64>, maxlags: usize) -> Array2<f64> {
let n = xu.nrows();
let k = xu.ncols();
let weights = bartlett_weights(maxlags);
let mut s = xu.t().dot(xu);
for (lag, &w) in weights.iter().enumerate().take(maxlags + 1).skip(1) {
if lag >= n {
break;
}
let mut gamma = Array2::<f64>::zeros((k, k));
for i in lag..n {
let hi = xu.row(i);
let lo = xu.row(i - lag);
for a in 0..k {
let v = hi[a];
for b in 0..k {
gamma[[a, b]] += v * lo[b];
}
}
}
for a in 0..k {
for b in 0..k {
s[[a, b]] += w * (gamma[[a, b]] + gamma[[b, a]]);
}
}
}
s
}
fn s_cluster(xu: &Array2<f64>, groups: &[i64]) -> (Array2<f64>, usize) {
let k = xu.ncols();
let mut uniq: Vec<i64> = groups.to_vec();
uniq.sort_unstable();
uniq.dedup();
let n_groups = uniq.len();
let index = |g: i64| uniq.binary_search(&g).unwrap();
let mut gsum = Array2::<f64>::zeros((n_groups, k));
for (i, &g) in groups.iter().enumerate() {
let gi = index(g);
for j in 0..k {
gsum[[gi, j]] += xu[[i, j]];
}
}
let s = gsum.t().dot(&gsum);
(s, n_groups)
}
pub fn robust_cov(
x: &Array2<f64>,
resid: &Array1<f64>,
normalized_cov_params: &Array2<f64>,
df_resid: f64,
cov_type: &CovType,
) -> Result<Array2<f64>> {
let n = x.nrows();
let k = x.ncols();
if resid.len() != n {
return Err(Error::Shape(format!(
"resid length {} != design rows {}",
resid.len(),
n
)));
}
if normalized_cov_params.dim() != (k, k) {
return Err(Error::Shape(format!(
"normalized_cov_params must be {k}×{k}"
)));
}
let nobs = n as f64;
match cov_type {
CovType::Hc0 | CovType::Hc1 => {
let mut scale: Array1<f64> = resid.iter().map(|&u| u * u).collect();
if matches!(cov_type, CovType::Hc1) {
let f = nobs / df_resid;
scale.mapv_inplace(|v| v * f);
}
Ok(hccm_diag(x, &scale, normalized_cov_params))
}
CovType::Hc2 => {
let h = leverages(x, normalized_cov_params);
let scale: Array1<f64> = resid
.iter()
.zip(h.iter())
.map(|(&u, &hi)| u * u / (1.0 - hi))
.collect();
Ok(hccm_diag(x, &scale, normalized_cov_params))
}
CovType::Hc3 => {
let h = leverages(x, normalized_cov_params);
let scale: Array1<f64> = resid
.iter()
.zip(h.iter())
.map(|(&u, &hi)| {
let t = u / (1.0 - hi);
t * t
})
.collect();
Ok(hccm_diag(x, &scale, normalized_cov_params))
}
CovType::Hac {
maxlags,
use_correction,
} => {
let xu = scores(x, resid);
let s = s_hac(&xu, *maxlags);
let mut cov = sandwich(normalized_cov_params, &s);
if *use_correction {
let f = nobs / df_resid;
cov.mapv_inplace(|v| v * f);
}
Ok(cov)
}
CovType::Cluster {
groups,
use_correction,
} => {
if groups.len() != n {
return Err(Error::Shape(format!(
"groups length {} != design rows {}",
groups.len(),
n
)));
}
let xu = scores(x, resid);
let (s, n_groups) = s_cluster(&xu, groups);
let mut cov = sandwich(normalized_cov_params, &s);
if *use_correction {
let g = n_groups as f64;
let f = (g / (g - 1.0)) * ((nobs - 1.0) / (nobs - k as f64));
cov.mapv_inplace(|v| v * f);
}
Ok(cov)
}
}
}
pub fn bse_from_cov(cov: &Array2<f64>) -> Array1<f64> {
let k = cov.nrows();
let mut bse = Array1::<f64>::zeros(k);
for i in 0..k {
bse[i] = cov[[i, i]].sqrt();
}
bse
}