use xingo_sparse::Real;
use crate::random::Rng;
use crate::real::lt;
use crate::small::{norm2, orthogonalize_against, orthogonalize_prefix};
#[allow(clippy::too_many_arguments)]
pub(crate) fn expand_arnoldi<T: Real>(
basis: &[T],
rows: usize,
ncols: usize,
w: &mut [T],
h: &mut [T],
eta: T,
floor: T,
rng: &mut Rng,
reorth: &mut usize,
) -> T {
let (nu, passes) = orthogonalize_prefix(basis, rows, ncols, w, eta, Some(h));
if passes == 2 {
*reorth += 1;
}
replace_or_normalize(basis, rows, ncols, w, nu, floor, rng)
}
fn replace_or_normalize<T: Real>(
basis: &[T],
rows: usize,
ncols: usize,
w: &mut [T],
nu: T,
floor: T,
rng: &mut Rng,
) -> T {
if lt(floor, nu) {
for v in w.iter_mut() {
*v = *v / nu;
}
return nu;
}
if ncols >= rows {
w.fill(T::ZERO);
return T::ZERO;
}
for v in w.iter_mut() {
*v = T::from_f64(rng.gaussian());
}
orthogonalize_against(basis, rows, ncols, w, T::ONE);
orthogonalize_against(basis, rows, ncols, w, T::ONE);
let nr = norm2(w);
for v in w.iter_mut() {
*v = *v / nr;
}
T::ZERO
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn expand<T: Real>(
basis: &[T],
rows: usize,
ncols: usize,
w: &mut [T],
eta: T,
floor: T,
rng: &mut Rng,
reorth: &mut usize,
) -> T {
let (nu, passes) = orthogonalize_against(basis, rows, ncols, w, eta);
if passes == 2 {
*reorth += 1;
}
replace_or_normalize(basis, rows, ncols, w, nu, floor, rng)
}
pub(crate) fn kept_dimension(k: usize, ncv: usize, n_conv: usize, n_lock: usize) -> usize {
let kp = k + ((ncv - k) / 2).min(n_conv);
kp.max(n_lock + 1).min(ncv - 1)
}
#[cfg(test)]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;
#[test]
fn expansion_normalizes_or_replaces() {
let basis = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
let mut rng = Rng::new(0);
let mut c = 0;
let mut w = [0.3, -0.2, 2.0];
let nu = expand(&basis, 3, 2, &mut w, 0.7, 1e-12, &mut rng, &mut c);
assert_eq!((nu, w), (2.0, [0.0, 0.0, 1.0]));
assert_eq!(c, 0, "no second pass: ‖w‖ fell only from 2.03 to 2");
let mut w = [0.3, -0.2, 1e-20];
let nu = expand(&basis, 3, 2, &mut w, 0.7, 1e-12, &mut rng, &mut c);
assert_eq!((nu, c), (0.0, 1));
assert!((w[2].abs() - 1.0).abs() < 1e-15 && w[0].abs() < 1e-15 && w[1].abs() < 1e-15);
let full = [1.0, 0.0, 0.0, 1.0];
let mut w = [1e-30, 0.0];
assert_eq!(
expand(&full, 2, 2, &mut w, 0.7, 1e-12, &mut rng, &mut c),
0.0
);
assert_eq!(w, [0.0, 0.0]);
}
#[test]
fn restart_dimension_follows_the_arpack_rule() {
assert_eq!(kept_dimension(5, 20, 0, 0), 5);
assert_eq!(kept_dimension(5, 20, 3, 0), 8);
assert_eq!(kept_dimension(5, 20, 4, 4), 9);
assert_eq!(kept_dimension(5, 20, 100, 0), 12);
assert_eq!(kept_dimension(5, 6, 0, 5), 5);
assert_eq!(kept_dimension(1, 2, 0, 0), 1);
}
}