use super::LinalgFloat;
pub fn cholesky_update<T: LinalgFloat>(r: &[T], w: &[T], batch: usize, n: usize) -> Vec<T> {
assert_eq!(r.len(), batch * n * n, "cholesky_update: r");
assert_eq!(w.len(), batch * n, "cholesky_update: w");
let mut out = r.to_vec();
let mut z = vec![T::ZERO; n];
for b in 0..batch {
let r = &mut out[b * n * n..(b + 1) * n * n];
z.copy_from_slice(&w[b * n..(b + 1) * n]);
for k in 0..n {
let (c, s) = drotg(r[k * n + k], z[k]);
for j in 0..n {
let (x, y) = (r[k * n + j], z[j]);
r[k * n + j] = c * x - s * y;
z[j] = c * y + s * x;
}
}
}
out
}
fn drotg<T: LinalgFloat>(x: T, y: T) -> (T, T) {
if y == T::ZERO {
return (T::ONE, T::ZERO);
}
let (ax, ay) = (x.abs(), y.abs());
let denominator = if ax > ay { ax } else { ay };
let (x, y) = (x / denominator, y / denominator);
let rh = T::ONE / (x * x + y * y).sqrt();
(x * rh, -y * rh)
}
pub fn symmetric_product<T: LinalgFloat>(
a: &[T],
c: &[T],
batch: usize,
m: usize,
n: usize,
alpha: T,
beta: T,
) -> Vec<T> {
assert_eq!(a.len(), batch * m * n, "symmetric_product: a");
assert_eq!(c.len(), batch * m * m, "symmetric_product: c");
let mut out = vec![T::ZERO; batch * m * m];
for b in 0..batch {
let a = &a[b * m * n..(b + 1) * m * n];
for i in 0..m {
for j in 0..m {
let mut s = T::ZERO;
for k in 0..n {
s = s + a[i * n + k] * a[j * n + k];
}
let at = b * m * m + i * m + j;
out[at] = alpha * s + beta * c[at];
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_updated_factor_reconstructs_the_updated_matrix() {
let n = 3;
let r = [2.0, 1.0, -1.0, 0.0, 1.5, 0.5, 0.0, 0.0, 1.0];
let w = [0.5, -1.0, 2.0];
let out = cholesky_update(&r, &w, 1, n);
let rtr = |r: &[f64]| symmetric_product(&transpose(r, n), &[0.0; 9], 1, n, n, 1.0, 0.0);
let expected = symmetric_product(&w, &rtr(&r), 1, n, 1, 1.0, 1.0);
for (g, e) in rtr(&out).iter().zip(&expected) {
assert!((g - e).abs() < 1e-12, "{g} vs {e}");
}
for i in 0..n {
for j in 0..i {
assert!(out[i * n + j].abs() < 1e-12, "{out:?}");
}
}
}
fn transpose(x: &[f64], n: usize) -> Vec<f64> {
(0..n * n).map(|k| x[(k % n) * n + k / n]).collect()
}
}