use std::ops::{Add, Div, Mul, Neg, Sub};
use crate::complex::Complex;
use crate::dtype::Element;
mod bidiagonal;
mod eig;
mod products;
mod tridiagonal;
pub use eig::{Cx, eig, hessenberg, schur};
pub use products::{cholesky_update, symmetric_product};
pub use tridiagonal::{tridiagonal, tridiagonal_solve};
mod sealed {
pub trait Sealed {}
impl Sealed for f32 {}
impl Sealed for f64 {}
impl Sealed for super::Complex<f32> {}
impl Sealed for super::Complex<f64> {}
}
pub trait LinalgFloat: LinalgScalar<LinalgReal = Self> + PartialOrd + sealed::Sealed {
const EPSILON: Self;
const MIN_POSITIVE: Self;
fn sqrt(self) -> Self;
fn hypot(self, other: Self) -> Self;
fn copysign(self, sign: Self) -> Self;
fn is_nan(self) -> bool;
type Complex: LinalgScalar<LinalgReal = Self>;
}
pub trait LinalgScalar:
Element<Real = <Self as LinalgScalar>::LinalgReal>
+ Add<Output = Self>
+ Sub<Output = Self>
+ Mul<Output = Self>
+ Div<Output = Self>
+ Neg<Output = Self>
+ PartialEq
+ sealed::Sealed
{
type LinalgReal: LinalgFloat;
const IS_COMPLEX: bool;
const ZERO: Self;
const ONE: Self;
const NAN: Self;
fn conj(self) -> Self;
fn abs(self) -> Self::LinalgReal;
fn abs1(self) -> Self::LinalgReal;
fn abs2(self) -> Self::LinalgReal;
fn scale(self, r: Self::LinalgReal) -> Self;
fn is_finite(self) -> bool;
fn csqrt(self) -> Self;
fn from_real(r: Self::LinalgReal) -> Self {
Self::from_parts(r, Self::LinalgReal::ZERO)
}
}
macro_rules! impl_linalg_float {
($($t:ty)*) => {$(
impl LinalgScalar for $t {
type LinalgReal = $t;
const IS_COMPLEX: bool = false;
const ZERO: Self = 0.0;
const ONE: Self = 1.0;
const NAN: Self = <$t>::NAN;
#[inline]
fn conj(self) -> Self {
self
}
#[inline]
fn abs(self) -> Self {
<$t>::abs(self)
}
#[inline]
fn abs1(self) -> Self {
<$t>::abs(self)
}
#[inline]
fn abs2(self) -> Self {
self * self
}
#[inline]
fn scale(self, r: Self) -> Self {
self * r
}
#[inline]
fn is_finite(self) -> bool {
<$t>::is_finite(self)
}
#[inline]
fn csqrt(self) -> Self {
<$t>::sqrt(self)
}
#[inline]
fn from_real(r: Self) -> Self {
r
}
}
impl LinalgFloat for $t {
type Complex = Complex<$t>;
const EPSILON: Self = <$t>::EPSILON;
const MIN_POSITIVE: Self = <$t>::MIN_POSITIVE;
#[inline]
fn sqrt(self) -> Self {
<$t>::sqrt(self)
}
#[inline]
fn hypot(self, other: Self) -> Self {
<$t>::hypot(self, other)
}
#[inline]
fn copysign(self, sign: Self) -> Self {
<$t>::copysign(self, sign)
}
#[inline]
fn is_nan(self) -> bool {
<$t>::is_nan(self)
}
}
impl LinalgScalar for Complex<$t> {
type LinalgReal = $t;
const IS_COMPLEX: bool = true;
const ZERO: Self = Complex::new(0.0, 0.0);
const ONE: Self = Complex::new(1.0, 0.0);
const NAN: Self = Complex::new(<$t>::NAN, <$t>::NAN);
#[inline]
fn conj(self) -> Self {
Complex::new(self.re, -self.im)
}
#[inline]
fn abs(self) -> $t {
self.re.hypot(self.im)
}
#[inline]
fn abs1(self) -> $t {
self.re.abs() + self.im.abs()
}
#[inline]
fn abs2(self) -> $t {
self.re * self.re + self.im * self.im
}
#[inline]
fn scale(self, r: $t) -> Self {
Complex::new(self.re * r, self.im * r)
}
#[inline]
fn is_finite(self) -> bool {
self.re.is_finite() && self.im.is_finite()
}
#[inline]
fn csqrt(self) -> Self {
self.sqrt()
}
}
)*};
}
impl_linalg_float!(f32 f64);
pub fn cholesky<T: LinalgScalar>(a: &[T], batch: usize, n: usize) -> Vec<T> {
assert_eq!(a.len(), batch * n * n, "cholesky: wrong number of elements");
let mut out = a.to_vec();
for m in out.chunks_exact_mut((n * n).max(1)).filter(|_| n > 0) {
if !cholesky_one(m, n) {
m.fill(T::NAN);
}
}
out
}
fn cholesky_one<T: LinalgScalar>(a: &mut [T], n: usize) -> bool {
for j in 0..n {
let mut ajj = a[j * n + j].re();
for k in 0..j {
ajj = ajj - a[j * n + k].abs2();
}
if ajj.is_nan() || ajj <= T::LinalgReal::ZERO {
return false;
}
let ajj = ajj.sqrt();
a[j * n + j] = T::from_real(ajj);
let r = T::LinalgReal::ONE / ajj;
for i in j + 1..n {
let mut v = a[i * n + j];
for k in 0..j {
v = v - a[i * n + k] * a[j * n + k].conj();
}
a[i * n + j] = v.scale(r);
}
}
true
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct TriangularSolveOptions {
pub left_side: bool,
pub lower: bool,
pub transpose_a: bool,
pub conjugate_a: bool,
pub unit_diagonal: bool,
}
pub fn triangular_solve<T: LinalgScalar>(
a: &[T],
b: &[T],
batch: usize,
m: usize,
n: usize,
options: TriangularSolveOptions,
) -> Vec<T> {
let k = if options.left_side { m } else { n };
assert_eq!(a.len(), batch * k * k, "triangular_solve: wrong size of a");
assert_eq!(b.len(), batch * m * n, "triangular_solve: wrong size of b");
let mut out = b.to_vec();
if k == 0 || m * n == 0 {
return out;
}
let conjugate = options.conjugate_a && T::IS_COMPLEX;
for (a, x) in a.chunks_exact(k * k).zip(out.chunks_exact_mut(m * n)) {
let conj_a: Vec<T>;
let a = if conjugate {
conj_a = a.iter().map(|v| v.conj()).collect();
&conj_a[..]
} else {
a
};
if options.left_side {
solve_vectors(
a,
k,
options.lower,
options.transpose_a,
options.unit_diagonal,
n,
|i, c| i * n + c,
x,
);
} else {
solve_vectors(
a,
k,
options.lower,
!options.transpose_a,
options.unit_diagonal,
m,
|i, r| r * n + i,
x,
);
}
}
out
}
#[allow(clippy::too_many_arguments)] fn solve_vectors<T: LinalgScalar>(
a: &[T],
k: usize,
lower: bool,
transpose: bool,
unit_diagonal: bool,
count: usize,
index: impl Fn(usize, usize) -> usize,
x: &mut [T],
) {
let at = |i: usize, j: usize| {
if transpose {
a[j * k + i]
} else {
a[i * k + j]
}
};
let forward = lower != transpose;
for v in 0..count {
let mut solve_row = |i: usize, js: &mut dyn Iterator<Item = usize>| {
let mut s = x[index(i, v)];
for j in js {
s = s - at(i, j) * x[index(j, v)];
}
if !unit_diagonal {
s = s / at(i, i);
}
x[index(i, v)] = s;
};
if forward {
for i in 0..k {
solve_row(i, &mut (0..i));
}
} else {
for i in (0..k).rev() {
solve_row(i, &mut (i + 1..k));
}
}
}
}
pub fn lu<T: LinalgScalar>(
a: &[T],
batch: usize,
m: usize,
n: usize,
) -> (Vec<T>, Vec<i32>, Vec<i32>) {
assert_eq!(a.len(), batch * m * n, "lu: wrong number of elements");
assert!(i32::try_from(m).is_ok(), "lu: too many rows for i32 pivots");
let k = m.min(n);
let mut out = a.to_vec();
let mut pivots = vec![0i32; batch * k];
for b in 0..batch {
let mat = &mut out[b * m * n..(b + 1) * m * n];
let piv = &mut pivots[b * k..(b + 1) * k];
lu_one(mat, m, n, piv);
}
let permutation = lu_pivots_to_permutation(&pivots, batch, k, m);
(out, pivots, permutation)
}
fn lu_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize, pivots: &mut [i32]) {
for j in 0..m.min(n) {
let mut p = j;
let mut max = a[j * n + j].abs1();
for i in j + 1..m {
let v = a[i * n + j].abs1();
if v > max {
max = v;
p = i;
}
}
pivots[j] = p as i32;
if a[p * n + j] != T::ZERO {
if p != j {
for c in 0..n {
a.swap(j * n + c, p * n + c);
}
}
let pivot = a[j * n + j];
if pivot.abs() >= T::LinalgReal::MIN_POSITIVE {
let r = T::ONE / pivot;
for i in j + 1..m {
a[i * n + j] = a[i * n + j] * r;
}
} else {
for i in j + 1..m {
a[i * n + j] = a[i * n + j] / pivot;
}
}
}
for i in j + 1..m {
let l = a[i * n + j];
for c in j + 1..n {
a[i * n + c] = a[i * n + c] - l * a[j * n + c];
}
}
}
}
pub fn lu_pivots_to_permutation(pivots: &[i32], batch: usize, k: usize, size: usize) -> Vec<i32> {
assert_eq!(
pivots.len(),
batch * k,
"lu_pivots_to_permutation: wrong size"
);
let mut out = Vec::with_capacity(batch * size);
for b in 0..batch {
let start = out.len();
out.extend((0..size).map(|i| i as i32));
let perm = &mut out[start..];
for (i, &p) in pivots[b * k..(b + 1) * k].iter().enumerate() {
if i < size && p >= 0 && (p as usize) < size {
perm.swap(i, p as usize);
}
}
}
out
}
fn norm2<T: LinalgScalar>(x: impl Iterator<Item = T> + Clone) -> T::LinalgReal {
let parts = x.flat_map(|v| {
let im = T::IS_COMPLEX.then(|| v.im());
std::iter::once(v.re()).chain(im)
});
let zero = T::LinalgReal::ZERO;
let mut scale = zero;
for v in parts.clone() {
let a = v.abs();
if a > scale || a.is_nan() {
scale = a;
}
}
if scale == zero || !scale.is_finite() {
return scale;
}
let mut sum = zero;
for v in parts {
let s = v / scale;
sum = sum + s * s;
}
scale * sum.sqrt()
}
fn larfg<T: LinalgScalar>(alpha: T, x: &mut [T]) -> (T, T) {
let xnorm = norm2(x.iter().copied());
let zero = T::LinalgReal::ZERO;
let one = T::LinalgReal::ONE;
if xnorm == zero && alpha.im() == zero {
return (alpha, T::ZERO);
}
let lapy = |alpha: T, xnorm: T::LinalgReal| {
if T::IS_COMPLEX {
alpha.re().hypot(alpha.im()).hypot(xnorm)
} else {
alpha.re().hypot(xnorm)
}
};
let mut alpha = alpha;
let mut xnorm = xnorm;
let mut beta = -lapy(alpha, xnorm).copysign(alpha.re());
let safmin =
T::LinalgReal::MIN_POSITIVE / (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5));
let rsafmn = one / safmin;
let mut knt = 0;
if beta.abs() < safmin {
while beta.abs() < safmin && knt < 20 {
knt += 1;
for v in x.iter_mut() {
*v = v.scale(rsafmn);
}
beta = beta * rsafmn;
alpha = alpha.scale(rsafmn);
}
xnorm = norm2(x.iter().copied());
beta = -lapy(alpha, xnorm).copysign(alpha.re());
}
let tau = T::from_parts((beta - alpha.re()) / beta, -alpha.im() / beta);
let r = T::ONE / (alpha - T::from_real(beta));
for v in x.iter_mut() {
*v = *v * r;
}
for _ in 0..knt {
beta = beta * safmin;
}
(T::from_real(beta), tau)
}
fn from_f64<T: LinalgFloat>(v: f64) -> T {
crate::dtype::cast::<f64, T>(v)
}
#[allow(clippy::too_many_arguments)] fn apply_reflector<T: LinalgScalar>(
a: &mut [T],
n: usize,
m: usize,
r0: usize,
vc: usize,
tau: T,
c0: usize,
c1: usize,
) {
if tau == T::ZERO || c0 >= c1 {
return;
}
let v: Vec<T> = (r0..m)
.map(|i| if i == r0 { T::ONE } else { a[i * n + vc] })
.collect();
let mut w = vec![T::ZERO; c1 - c0];
for (i, vi) in (r0..m).zip(&v) {
let vi = vi.conj();
for (wc, x) in w.iter_mut().zip(&a[i * n + c0..i * n + c1]) {
*wc = *wc + vi * *x;
}
}
for wc in &mut w {
*wc = tau * *wc;
}
for (i, &vi) in (r0..m).zip(&v) {
for (x, &tw) in a[i * n + c0..i * n + c1].iter_mut().zip(&w) {
*x = *x - vi * tw;
}
}
}
pub fn qr<T: LinalgScalar>(
a: &[T],
batch: usize,
m: usize,
n: usize,
full_matrices: bool,
) -> (Vec<T>, Vec<T>) {
let (q, r, _) = qr_impl(a, batch, m, n, full_matrices, false);
(q, r)
}
pub fn qr_pivoting<T: LinalgScalar>(
a: &[T],
batch: usize,
m: usize,
n: usize,
full_matrices: bool,
) -> (Vec<T>, Vec<T>, Vec<i32>) {
assert!(
i32::try_from(n).is_ok(),
"qr: too many columns for i32 pivots"
);
qr_impl(a, batch, m, n, full_matrices, true)
}
fn qr_impl<T: LinalgScalar>(
a: &[T],
batch: usize,
m: usize,
n: usize,
full_matrices: bool,
pivoting: bool,
) -> (Vec<T>, Vec<T>, Vec<i32>) {
assert_eq!(a.len(), batch * m * n, "qr: wrong number of elements");
let k = m.min(n);
let kq = if full_matrices { m } else { k };
let mut q_out = Vec::with_capacity(batch * m * kq);
let mut r_out = Vec::with_capacity(batch * kq * n);
let mut p_out = Vec::with_capacity(if pivoting { batch * n } else { 0 });
for mat in a.chunks_exact((m * n).max(1)).take(batch) {
let mut r = mat.to_vec();
let taus = if pivoting {
let (taus, jpvt) = geqp3_one(&mut r, m, n);
p_out.extend(jpvt);
taus
} else {
geqrf_one(&mut r, m, n)
};
let mut q = vec![T::ZERO; m * kq];
for i in 0..m {
for j in 0..kq.min(n) {
q[i * kq + j] = r[i * n + j];
}
}
orgqr_one(&mut q, m, kq, &taus);
q_out.extend_from_slice(&q);
for i in 0..kq {
for j in 0..n {
r_out.push(if j >= i && i < m {
r[i * n + j]
} else {
T::ZERO
});
}
}
}
if m * n == 0 {
q_out.clear();
r_out.clear();
p_out.clear();
for _ in 0..batch {
let mut q = vec![T::ZERO; m * kq];
orgqr_one(&mut q, m, kq, &[]);
q_out.extend_from_slice(&q);
r_out.extend(std::iter::repeat_n(T::ZERO, kq * n));
if pivoting {
p_out.extend(std::iter::repeat_n(0, n));
}
}
}
(q_out, r_out, p_out)
}
fn geqp3_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> (Vec<T>, Vec<i32>) {
let k = m.min(n);
let mut jpvt: Vec<i32> = (0..n as i32).collect();
let mut vn1: Vec<T::LinalgReal> = (0..n)
.map(|j| norm2((0..m).map(|r| a[r * n + j])))
.collect();
let mut vn2 = vn1.clone();
let zero = T::LinalgReal::ZERO;
let one = T::LinalgReal::ONE;
let tol3z = (T::LinalgReal::EPSILON * from_f64::<T::LinalgReal>(0.5)).sqrt();
let mut taus = Vec::with_capacity(k);
for i in 0..k {
let mut pvt = i;
let mut max = vn1[i];
for (j, &v) in vn1.iter().enumerate().skip(i + 1) {
if v > max {
max = v;
pvt = j;
}
}
if pvt != i {
for r in 0..m {
a.swap(r * n + pvt, r * n + i);
}
jpvt.swap(pvt, i);
vn1[pvt] = vn1[i];
vn2[pvt] = vn2[i];
}
let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
let (beta, tau) = larfg(a[i * n + i], &mut x);
for (r, v) in (i + 1..m).zip(x) {
a[r * n + i] = v;
}
a[i * n + i] = beta;
apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
taus.push(tau);
for j in i + 1..n {
if vn1[j] == zero {
continue;
}
let ratio = a[i * n + j].abs() / vn1[j];
let temp = one - ratio * ratio;
let temp = if temp > zero { temp } else { zero };
let scale = vn1[j] / vn2[j];
let temp2 = temp * scale * scale;
if temp2 <= tol3z {
if i + 1 < m {
vn1[j] = norm2((i + 1..m).map(|r| a[r * n + j]));
vn2[j] = vn1[j];
} else {
vn1[j] = zero;
vn2[j] = zero;
}
} else {
vn1[j] = vn1[j] * temp.sqrt();
}
}
}
(taus, jpvt)
}
pub fn householder_product<T: LinalgScalar>(
a: &[T],
taus: &[T],
batch: usize,
m: usize,
n: usize,
k: usize,
) -> Vec<T> {
assert!(m >= n && n >= k, "householder_product: needs m >= n >= k");
assert_eq!(
a.len(),
batch * m * n,
"householder_product: wrong size of a"
);
assert_eq!(
taus.len(),
batch * k,
"householder_product: wrong size of taus"
);
let mut out = a.to_vec();
for b in 0..batch {
orgqr_one(
&mut out[b * m * n..(b + 1) * m * n],
m,
n,
&taus[b * k..(b + 1) * k],
);
}
out
}
#[allow(clippy::too_many_arguments)] pub fn ormqr<T: LinalgScalar>(
a: &[T],
taus: &[T],
c: &[T],
batch: usize,
(m, n, k): (usize, usize, usize),
(rows, cols): (usize, usize),
left: bool,
transpose: bool,
) -> Vec<T> {
assert_eq!(a.len(), batch * m * n, "ormqr: wrong size of a");
assert_eq!(taus.len(), batch * k, "ormqr: wrong size of taus");
assert_eq!(c.len(), batch * rows * cols, "ormqr: wrong size of c");
assert_eq!(
if left { rows } else { cols },
m,
"ormqr: incompatible shapes"
);
let mut out = c.to_vec();
for b in 0..batch {
let a = &a[b * m * n..(b + 1) * m * n];
let taus = &taus[b * k..(b + 1) * k];
let c = &mut out[b * rows * cols..(b + 1) * rows * cols];
let reverse = left != transpose;
for step in 0..k {
let i = if reverse { k - 1 - step } else { step };
let tau = if transpose { taus[i].conj() } else { taus[i] };
if tau == T::ZERO {
continue;
}
let v = |r: usize| if r == i { T::ONE } else { a[r * n + i] };
if left {
for col in 0..cols {
let mut w = T::ZERO;
for r in i..m {
w = w + v(r).conj() * c[r * cols + col];
}
let tw = tau * w;
for r in i..m {
c[r * cols + col] = c[r * cols + col] - v(r) * tw;
}
}
} else {
for row in 0..rows {
let mut w = T::ZERO;
for r in i..m {
w = w + c[row * cols + r] * v(r);
}
let tw = w * tau;
for r in i..m {
c[row * cols + r] = c[row * cols + r] - tw * v(r).conj();
}
}
}
}
}
out
}
fn geqrf_one<T: LinalgScalar>(a: &mut [T], m: usize, n: usize) -> Vec<T> {
let k = m.min(n);
let mut taus = Vec::with_capacity(k);
for i in 0..k {
let mut x: Vec<T> = (i + 1..m).map(|r| a[r * n + i]).collect();
let (beta, tau) = larfg(a[i * n + i], &mut x);
for (r, v) in (i + 1..m).zip(x) {
a[r * n + i] = v;
}
a[i * n + i] = beta;
apply_reflector(a, n, m, i, i, tau.conj(), i + 1, n);
taus.push(tau);
}
taus
}
fn orgqr_one<T: LinalgScalar>(a: &mut [T], m: usize, nq: usize, taus: &[T]) {
let k = taus.len();
for j in k..nq {
for i in 0..m {
a[i * nq + j] = T::ZERO;
}
if j < m {
a[j * nq + j] = T::ONE;
}
}
for i in (0..k).rev() {
if i + 1 < nq {
a[i * nq + i] = T::ONE;
apply_reflector(a, nq, m, i, i, taus[i], i + 1, nq);
}
for r in i + 1..m {
a[r * nq + i] = -taus[i] * a[r * nq + i];
}
a[i * nq + i] = T::ONE - taus[i];
for r in 0..i {
a[r * nq + i] = T::ZERO;
}
}
}
fn normalize_phase<T: LinalgScalar>(v: &mut [T], rows: usize, cols: usize, c: usize) -> Option<T> {
let mut best = 0;
let mut max = T::LinalgReal::ZERO;
for r in 0..rows {
let a = v[r * cols + c].abs();
if a > max {
max = a;
best = r;
}
}
if rows == 0 {
return None;
}
let z = v[best * cols + c];
if !T::IS_COMPLEX {
if z.re() < T::LinalgReal::ZERO {
for r in 0..rows {
v[r * cols + c] = -v[r * cols + c];
}
return Some(-T::ONE);
}
return None;
}
if z.im() == T::LinalgReal::ZERO && z.re() >= T::LinalgReal::ZERO {
return None;
}
let f = T::from_parts(z.re() / max, -z.im() / max);
for r in 0..rows {
v[r * cols + c] = v[r * cols + c] * f;
}
v[best * cols + c] = T::from_real(max);
Some(f)
}
fn rotation_phase<T: LinalgScalar>(x: T) -> (T::LinalgReal, Option<T>) {
if T::IS_COMPLEX {
let mag = x.abs();
(mag, Some(T::from_parts(x.re() / mag, -x.im() / mag)))
} else {
(x.re(), None)
}
}
const MAX_SWEEPS: usize = 60;
pub fn eigh<T: LinalgScalar>(
a: &[T],
batch: usize,
n: usize,
lower: bool,
jacobi: bool,
) -> (Vec<T>, Vec<T::LinalgReal>) {
assert_eq!(a.len(), batch * n * n, "eigh: wrong number of elements");
let mut vs = Vec::with_capacity(batch * n * n);
let mut ws = Vec::with_capacity(batch * n);
for b in 0..batch {
let mat = &a[b * n * n..(b + 1) * n * n];
let (v, w) = eigh_one(mat, n, lower, jacobi);
vs.extend(v);
ws.extend(w);
}
(vs, ws)
}
fn eigh_one<T: LinalgScalar>(
a: &[T],
n: usize,
lower: bool,
jacobi: bool,
) -> (Vec<T>, Vec<T::LinalgReal>) {
let mut s = vec![T::ZERO; n * n];
let mut finite = true;
for i in 0..n {
for j in 0..=i {
let v = if lower {
a[i * n + j]
} else {
a[j * n + i].conj()
};
finite &= v.is_finite();
if i == j {
s[i * n + i] = T::from_real(v.re());
} else {
s[i * n + j] = v;
s[j * n + i] = v.conj();
}
}
}
if !finite {
return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
}
let solved = if jacobi {
Some(eigh_jacobi(s, n))
} else {
tridiagonal::eigh_tridiagonal(&s, n)
};
let Some((mut sorted, w)) = solved else {
return (vec![T::NAN; n * n], vec![T::LinalgReal::NAN; n]);
};
for c in 0..n {
normalize_phase(&mut sorted, n, n, c);
}
(sorted, w)
}
fn eigh_jacobi<T: LinalgScalar>(mut s: Vec<T>, n: usize) -> (Vec<T>, Vec<T::LinalgReal>) {
let mut v = vec![T::ZERO; n * n];
for i in 0..n {
v[i * n + i] = T::ONE;
}
let fro = norm2(s.iter().copied());
let floor = fmax(
T::LinalgReal::MIN_POSITIVE,
fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
);
let one = T::LinalgReal::ONE;
for _ in 0..MAX_SWEEPS {
let mut rotated = false;
for p in 0..n {
for q in p + 1..n {
let apq = s[p * n + q];
let (app, aqq) = (s[p * n + p].re(), s[q * n + q].re());
let mag = apq.abs();
if mag <= floor || mag <= T::LinalgReal::EPSILON * (app.abs() * aqq.abs()).sqrt() {
continue;
}
rotated = true;
let (apq, u) = rotation_phase(apq);
let phase = |x: T| u.map_or(x, |u| x * u);
let theta = (aqq - app) / (apq + apq);
let t = one.copysign(theta) / (theta.abs() + one.hypot(theta));
let c = one / one.hypot(t);
let sn = t * c;
s[p * n + p] = T::from_real(app - t * apq);
s[q * n + q] = T::from_real(aqq + t * apq);
s[p * n + q] = T::ZERO;
s[q * n + p] = T::ZERO;
for r in 0..n {
if r != p && r != q {
let (arp, arq) = (s[r * n + p], phase(s[r * n + q]));
let np = arp.scale(c) - arq.scale(sn);
let nq = arp.scale(sn) + arq.scale(c);
s[r * n + p] = np;
s[p * n + r] = np.conj();
s[r * n + q] = nq;
s[q * n + r] = nq.conj();
}
let (vrp, vrq) = (v[r * n + p], phase(v[r * n + q]));
v[r * n + p] = vrp.scale(c) - vrq.scale(sn);
v[r * n + q] = vrp.scale(sn) + vrq.scale(c);
}
}
}
if !rotated {
break;
}
}
let mut order: Vec<usize> = (0..n).collect();
order.sort_by(|&i, &j| {
s[i * n + i]
.re()
.partial_cmp(&s[j * n + j].re())
.unwrap_or(std::cmp::Ordering::Equal)
});
let w: Vec<T::LinalgReal> = order.iter().map(|&i| s[i * n + i].re()).collect();
let mut sorted = vec![T::ZERO; n * n];
for (c, &i) in order.iter().enumerate() {
for r in 0..n {
sorted[r * n + c] = v[r * n + i];
}
}
(sorted, w)
}
fn fmax<T: LinalgFloat>(a: T, b: T) -> T {
if b > a { b } else { a }
}
pub fn svd<T: LinalgScalar>(
a: &[T],
batch: usize,
m: usize,
n: usize,
full_matrices: bool,
compute_uv: bool,
jacobi: bool,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
assert_eq!(a.len(), batch * m * n, "svd: wrong number of elements");
let k = m.min(n);
let (ucols, vrows) = if full_matrices { (m, n) } else { (k, k) };
let mut s_out = Vec::with_capacity(batch * k);
let mut u_out = Vec::new();
let mut vt_out = Vec::new();
for b in 0..batch {
let mat = &a[b * m * n..(b + 1) * m * n];
let (s, u, vt) = svd_one(mat, m, n, ucols, vrows, jacobi);
s_out.extend(s);
if compute_uv {
u_out.extend(u);
vt_out.extend(vt);
}
}
(s_out, u_out, vt_out)
}
fn svd_one<T: LinalgScalar>(
a: &[T],
m: usize,
n: usize,
ucols: usize,
vrows: usize,
jacobi: bool,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
let k = m.min(n);
if a.iter().any(|v| !v.is_finite()) {
return (
vec![T::LinalgReal::NAN; k],
vec![T::NAN; m * ucols],
vec![T::NAN; vrows * n],
);
}
let tall = m >= n;
let (rows, cols) = if tall { (m, n) } else { (n, m) };
let mut g = vec![T::ZERO; rows * cols];
for i in 0..m {
for j in 0..n {
if tall {
g[j * rows + i] = a[i * n + j];
} else {
g[i * rows + j] = a[i * n + j].conj();
}
}
}
let solved = if jacobi {
Some(svd_jacobi(g, rows, cols))
} else {
let mut row_major = vec![T::ZERO; rows * cols];
for c in 0..cols {
for r in 0..rows {
row_major[r * cols + c] = g[c * rows + r];
}
}
bidiagonal::svd_bidiagonal(&row_major, rows, cols)
};
let Some((s, mut left, mut right)) = solved else {
return (
vec![T::LinalgReal::NAN; k],
vec![T::NAN; m * ucols],
vec![T::NAN; vrows * n],
);
};
let (u_full, v_full) = if tall {
(&mut left, &mut right)
} else {
(&mut right, &mut left)
};
let (urows, vdim) = (m, n);
for c in 0..urows {
let factor = normalize_phase(u_full, urows, urows, c);
if let Some(f) = factor
&& c < k
&& s[c] > T::LinalgReal::ZERO
{
for r in 0..vdim {
v_full[r * vdim + c] = if T::IS_COMPLEX {
v_full[r * vdim + c] * f
} else {
-v_full[r * vdim + c]
};
}
}
}
for c in 0..vdim {
let paired = s.get(c).is_some_and(|&sc| sc > T::LinalgReal::ZERO);
if !paired {
normalize_phase(v_full, vdim, vdim, c);
}
}
let mut u = Vec::with_capacity(m * ucols);
for r in 0..m {
u.extend_from_slice(&u_full[r * m..r * m + ucols]);
}
let mut vt = Vec::with_capacity(vrows * n);
for c in 0..vrows {
for r in 0..n {
vt.push(v_full[r * n + c].conj());
}
}
(s, u, vt)
}
#[allow(clippy::type_complexity)] fn svd_jacobi<T: LinalgScalar>(
mut g: Vec<T>,
rows: usize,
cols: usize,
) -> (Vec<T::LinalgReal>, Vec<T>, Vec<T>) {
let mut w = vec![T::ZERO; cols * cols];
for i in 0..cols {
w[i * cols + i] = T::ONE;
}
let col_dot = |g: &[T], i: usize, j: usize| {
let (gi, gj) = (&g[i * rows..(i + 1) * rows], &g[j * rows..(j + 1) * rows]);
gi.iter()
.zip(gj)
.fold(T::ZERO, |s, (&x, &y)| s + x.conj() * y)
};
let rotate = |x: &mut [T], len: usize, i: usize, j: usize, c, s, phase: &dyn Fn(T) -> T| {
let (head, tail) = x.split_at_mut(j * len);
let (xi, xj) = (&mut head[i * len..(i + 1) * len], &mut tail[..len]);
for (a, b) in xi.iter_mut().zip(xj.iter_mut()) {
let (gi, gj) = (*a, phase(*b));
*a = gi.scale(c) - gj.scale(s);
*b = gi.scale(s) + gj.scale(c);
}
};
let one = T::LinalgReal::ONE;
let fro = norm2(g.iter().copied());
let floor = fmax(
T::LinalgReal::MIN_POSITIVE,
fro * fro * T::LinalgReal::EPSILON * T::LinalgReal::EPSILON,
);
for _ in 0..MAX_SWEEPS {
let mut rotated = false;
for i in 0..cols {
for j in i + 1..cols {
let alpha = col_dot(&g, i, i).re();
let beta = col_dot(&g, j, j).re();
let gamma = col_dot(&g, i, j);
let mag = gamma.abs();
if mag <= floor || mag <= T::LinalgReal::EPSILON * (alpha * beta).sqrt() {
continue;
}
rotated = true;
let (gamma, u) = rotation_phase(gamma);
let phase = |x: T| u.map_or(x, |u| x * u);
let zeta = (beta - alpha) / (gamma + gamma);
let t = one.copysign(zeta) / (zeta.abs() + one.hypot(zeta));
let c = one / one.hypot(t);
let s = c * t;
rotate(&mut g, rows, i, j, c, s, &phase);
rotate(&mut w, cols, i, j, c, s, &phase);
}
}
if !rotated {
break;
}
}
let norms: Vec<T::LinalgReal> = (0..cols)
.map(|c| norm2(g[c * rows..(c + 1) * rows].iter().copied()))
.collect();
let mut order: Vec<usize> = (0..cols).collect();
order.sort_by(|&i, &j| {
norms[j]
.partial_cmp(&norms[i])
.unwrap_or(std::cmp::Ordering::Equal)
});
let s: Vec<T::LinalgReal> = order.iter().map(|&i| norms[i]).collect();
let mut left = vec![T::ZERO; rows * rows];
let mut have = vec![false; rows];
let mut right = vec![T::ZERO; cols * cols];
for (c, &i) in order.iter().enumerate() {
let norm = norms[i];
if norm > T::LinalgReal::ZERO {
let r = one / norm;
for row in 0..rows {
left[row * rows + c] = g[i * rows + row].scale(r);
}
have[c] = true;
}
for row in 0..cols {
right[row * cols + c] = w[i * cols + row];
}
}
complete_basis(&mut left, rows, &mut have);
(s, left, right)
}
fn complete_basis<T: LinalgScalar>(q: &mut [T], d: usize, have: &mut [bool]) {
for c in 0..d {
if have[c] {
continue;
}
let mut best: Option<(T::LinalgReal, Vec<T>)> = None;
for e in 0..d {
let mut v = vec![T::ZERO; d];
v[e] = T::ONE;
for _ in 0..2 {
for j in (0..d).filter(|&j| have[j]) {
let mut dot = T::ZERO;
for r in 0..d {
dot = dot + q[r * d + j].conj() * v[r];
}
for r in 0..d {
v[r] = v[r] - dot * q[r * d + j];
}
}
}
let norm = norm2(v.iter().copied());
if best.as_ref().is_none_or(|(b, _)| norm > *b) {
best = Some((norm, v));
}
}
let (norm, v) = best.expect("d > 0");
let r = T::LinalgReal::ONE / norm;
for row in 0..d {
q[row * d + c] = v[row].scale(r);
}
have[c] = true;
}
}
#[cfg(test)]
mod tests {
use super::*;
fn matmul(a: &[f64], b: &[f64], m: usize, k: usize, n: usize) -> Vec<f64> {
let mut c = vec![0.0; m * n];
for i in 0..m {
for j in 0..n {
c[i * n + j] = (0..k).map(|l| a[i * k + l] * b[l * n + j]).sum();
}
}
c
}
fn transpose(a: &[f64], m: usize, n: usize) -> Vec<f64> {
let mut t = vec![0.0; m * n];
for i in 0..m {
for j in 0..n {
t[j * m + i] = a[i * n + j];
}
}
t
}
fn assert_close(a: &[f64], b: &[f64], tol: f64) {
assert_eq!(a.len(), b.len());
for (i, (x, y)) in a.iter().zip(b).enumerate() {
assert!(
(x - y).abs() <= tol,
"element {i}: {x} vs {y}\n{a:?}\n{b:?}"
);
}
}
fn matrix(m: usize, n: usize, seed: u64) -> Vec<f64> {
let mut s = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
(0..m * n)
.map(|_| {
s = s
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((s >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
})
.collect()
}
fn eye(n: usize) -> Vec<f64> {
let mut e = vec![0.0; n * n];
for i in 0..n {
e[i * n + i] = 1.0;
}
e
}
#[test]
fn cholesky_of_a_textbook_matrix() {
let a = [4.0, 12.0, -16.0, 12.0, 37.0, -43.0, -16.0, -43.0, 98.0];
let l = cholesky(&a, 1, 3);
assert_eq!(l, [2.0, 12.0, -16.0, 6.0, 1.0, -43.0, -8.0, 5.0, 3.0]);
let bad = cholesky(&[1.0, 2.0, 2.0, 1.0], 1, 2);
assert!(bad.iter().all(|v| v.is_nan()));
assert!(cholesky::<f32>(&[], 0, 3).is_empty());
}
#[test]
fn triangular_solves_invert_products() {
let n = 4;
let a = matrix(n, n, 1);
let b = matrix(n, 3, 2);
let bt = matrix(3, n, 3);
for lower in [false, true] {
for transpose_a in [false, true] {
for unit_diagonal in [false, true] {
let mut t = vec![0.0; n * n];
for i in 0..n {
for j in 0..n {
let keep = if lower { j <= i } else { j >= i };
if keep {
t[i * n + j] = if i == j {
if unit_diagonal {
1.0
} else {
a[i * n + j] + 3.0
}
} else {
a[i * n + j]
};
}
}
}
let mut stored = a.clone();
for i in 0..n {
stored[i * n + i] = if unit_diagonal {
f64::NAN
} else {
a[i * n + i] + 3.0
};
}
let op = if transpose_a {
transpose(&t, n, n)
} else {
t.clone()
};
let options = TriangularSolveOptions {
left_side: true,
lower,
transpose_a,
conjugate_a: false,
unit_diagonal,
};
let x = triangular_solve(&stored, &b, 1, n, 3, options);
assert_close(&matmul(&op, &x, n, n, 3), &b, 1e-12);
let options = TriangularSolveOptions {
left_side: false,
..options
};
let x = triangular_solve(&stored, &bt, 1, 3, n, options);
assert_close(&matmul(&x, &op, 3, n, n), &bt, 1e-12);
}
}
}
}
#[test]
fn lu_pivots_by_the_largest_magnitude() {
let a = [1.0, 2.0, -4.0, 3.0, 4.0, 1.0];
let (lu_, piv, perm) = lu(&a, 1, 3, 2);
assert_eq!(piv, [1, 2]);
assert_eq!(perm, [1, 2, 0]);
let l = [1.0, 0.0, lu_[2], 1.0, lu_[4], lu_[5]];
let u = [lu_[0], lu_[1], 0.0, lu_[3]];
let pa: Vec<f64> = perm
.iter()
.flat_map(|&r| a[r as usize * 2..r as usize * 2 + 2].to_vec())
.collect();
assert_close(&matmul(&l, &u, 3, 2, 2), &pa, 1e-12);
let (_, piv, _) = lu(&[0.0, 1.0, 0.0, 2.0], 1, 2, 2);
assert_eq!(piv, [0, 1]);
let (_, piv, _) = lu(&[-2.0, 1.0, 2.0, 1.0], 1, 2, 2);
assert_eq!(piv, [0, 1]);
assert_eq!(lu_pivots_to_permutation(&[2, 2, 2], 1, 3, 4), [2, 0, 1, 3]);
}
#[test]
fn qr_follows_lapack_signs() {
for (m, n) in [(4, 3), (3, 4), (3, 3), (1, 1), (5, 2)] {
let a = matrix(m, n, (m * 10 + n) as u64);
for full in [false, true] {
let (q, r) = qr(&a, 1, m, n, full);
let kq = if full { m } else { m.min(n) };
assert_close(&matmul(&q, &r, m, kq, n), &a, 1e-12);
let qtq = matmul(&transpose(&q, m, kq), &q, kq, m, kq);
assert_close(&qtq, &eye(kq), 1e-12);
for i in 0..kq {
for j in 0..i.min(n) {
assert_eq!(r[i * n + j], 0.0);
}
}
}
}
let (q, r) = qr(&[3.0, 4.0], 1, 2, 1, false);
assert_close(&r, &[-5.0], 1e-15);
assert_close(&q, &[-0.6, -0.8], 1e-15);
let (q, r) = qr::<f64>(&[], 2, 2, 0, true);
assert_eq!(q, [1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0]);
assert!(r.is_empty());
}
#[test]
fn eigh_diagonalizes() {
let n = 5;
let b = matrix(n, n, 7);
let a = matmul(&b, &transpose(&b, n, n), n, n, n);
for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
let mut stored = a.clone();
for i in 0..n {
for j in 0..n {
if (lower && j > i) || (!lower && j < i) {
stored[i * n + j] = 1e3;
}
}
}
let (v, w) = eigh(&stored, 1, n, lower, jacobi);
assert!(w.windows(2).all(|p| p[0] <= p[1]));
let mut vw = v.clone();
for r in 0..n {
for c in 0..n {
vw[r * n + c] *= w[c];
}
}
assert_close(&matmul(&vw, &transpose(&v, n, n), n, n, n), &a, 1e-12);
assert_close(&matmul(&transpose(&v, n, n), &v, n, n, n), &eye(n), 1e-12);
}
let (v, w) = eigh(&[f64::NAN, 0.0, 0.0, 1.0], 1, 2, true, false);
assert!(v.iter().chain(&w).all(|x| x.is_nan()));
}
#[test]
fn svd_reconstructs() {
for (m, n) in [(4, 3), (3, 4), (3, 3), (5, 1), (1, 4), (2, 0), (0, 3)] {
let mut a = matrix(m, n, (m * 7 + n) as u64);
if m == 4 && n == 3 {
for i in 0..m {
a[i * n + 2] = a[i * n];
}
}
let k = m.min(n);
for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
assert!(s.windows(2).all(|p| p[0] >= p[1]));
let (uc, vr) = if full { (m, n) } else { (k, k) };
let mut us = vec![0.0; m * vr];
for i in 0..m {
for j in 0..k {
us[i * vr + j] = u[i * uc + j] * s[j];
}
}
assert_close(&matmul(&us, &vt, m, vr, n), &a, 1e-12);
assert_close(
&matmul(&transpose(&u, m, uc), &u, uc, m, uc),
&eye(uc),
1e-12,
);
assert_close(
&matmul(&vt, &transpose(&vt, vr, n), vr, n, vr),
&eye(vr),
1e-12,
);
let (s2, u2, vt2) = svd(&a, 1, m, n, full, false, jacobi);
assert_eq!(s2, s);
assert!(u2.is_empty() && vt2.is_empty());
}
}
}
type Z = Complex<f64>;
fn z(re: f64, im: f64) -> Z {
Complex::new(re, im)
}
fn cmatrix(m: usize, n: usize, seed: u64) -> Vec<Z> {
let re = matrix(m, n, seed);
let im = matrix(m, n, seed + 1000);
re.into_iter().zip(im).map(|(a, b)| z(a, b)).collect()
}
fn cmatmul(a: &[Z], b: &[Z], m: usize, k: usize, n: usize) -> Vec<Z> {
let mut c = vec![Z::ZERO; m * n];
for i in 0..m {
for j in 0..n {
let mut s = Z::ZERO;
for l in 0..k {
s = s + a[i * k + l] * b[l * n + j];
}
c[i * n + j] = s;
}
}
c
}
fn adjoint(a: &[Z], m: usize, n: usize) -> Vec<Z> {
let mut t = vec![Z::ZERO; m * n];
for i in 0..m {
for j in 0..n {
t[j * m + i] = a[i * n + j].conj();
}
}
t
}
fn ceye(n: usize) -> Vec<Z> {
let mut e = vec![Z::ZERO; n * n];
for i in 0..n {
e[i * n + i] = Z::ONE;
}
e
}
fn assert_cclose(a: &[Z], b: &[Z], tol: f64) {
assert_eq!(a.len(), b.len());
for (i, (x, y)) in a.iter().zip(b).enumerate() {
assert!((*x - *y).abs() <= tol, "element {i}: {x:?} vs {y:?}");
}
}
fn hpd(n: usize, seed: u64) -> Vec<Z> {
let b = cmatrix(n, n, seed);
let mut a = cmatmul(&b, &adjoint(&b, n, n), n, n, n);
for i in 0..n {
a[i * n + i] = a[i * n + i] + z(n as f64, 0.0);
}
a
}
#[test]
fn complex_cholesky_reconstructs() {
let n = 4;
let a = hpd(n, 1);
let l = cholesky(&a, 1, n);
let mut lower = vec![Z::ZERO; n * n];
for i in 0..n {
assert_eq!(l[i * n + i].im, 0.0);
for j in 0..=i {
lower[i * n + j] = l[i * n + j];
}
for j in i + 1..n {
assert_eq!(l[i * n + j], a[i * n + j], "the upper triangle is kept");
}
}
assert_cclose(&cmatmul(&lower, &adjoint(&lower, n, n), n, n, n), &a, 1e-12);
}
#[test]
fn complex_triangular_solves_conjugate() {
let n = 3;
let mut a = cmatrix(n, n, 5);
for i in 0..n {
a[i * n + i] = a[i * n + i] + z(3.0, 0.0);
}
let b = cmatrix(n, 2, 6);
for transpose_a in [false, true] {
for conjugate_a in [false, true] {
let mut t = vec![Z::ZERO; n * n];
for i in 0..n {
for j in 0..=i {
t[i * n + j] = a[i * n + j];
}
}
let mut op = if transpose_a {
adjoint(&adjoint(&adjoint(&t, n, n), n, n), n, n)
.iter()
.map(|v| v.conj())
.collect()
} else {
t.clone()
};
if conjugate_a {
op = op.iter().map(|v| v.conj()).collect();
}
let options = TriangularSolveOptions {
left_side: true,
lower: true,
transpose_a,
conjugate_a,
unit_diagonal: false,
};
let x = triangular_solve(&a, &b, 1, n, 2, options);
assert_cclose(&cmatmul(&op, &x, n, n, 2), &b, 1e-12);
}
}
}
#[test]
fn complex_lu_pivots_by_abs1() {
let a = [z(4.5, 0.0), z(1.0, 0.0), z(2.9, 2.9), z(1.0, 1.0)];
let (_, piv, _) = lu(&a, 1, 2, 2);
assert_eq!(piv, [1, 1]);
let (m, n) = (4, 3);
let a = cmatrix(m, n, 9);
let (f, _, perm) = lu(&a, 1, m, n);
let mut l = vec![Z::ZERO; m * n];
let mut u = vec![Z::ZERO; n * n];
for i in 0..m {
for j in 0..n {
if j < i {
l[i * n + j] = f[i * n + j];
} else {
if i == j {
l[i * n + j] = Z::ONE;
}
if i < n {
u[i * n + j] = f[i * n + j];
}
}
}
}
let pa: Vec<Z> = perm
.iter()
.flat_map(|&r| a[r as usize * n..(r as usize + 1) * n].to_vec())
.collect();
assert_cclose(&cmatmul(&l, &u, m, n, n), &pa, 1e-12);
}
#[test]
fn complex_qr_is_unitary() {
for (m, n) in [(4, 3), (3, 4), (3, 3)] {
let a = cmatrix(m, n, (m * 10 + n) as u64);
for full in [false, true] {
let (q, r) = qr(&a, 1, m, n, full);
let kq = if full { m } else { m.min(n) };
assert_cclose(&cmatmul(&q, &r, m, kq, n), &a, 1e-12);
assert_cclose(
&cmatmul(&adjoint(&q, m, kq), &q, kq, m, kq),
&ceye(kq),
1e-12,
);
for i in 0..kq.min(n) {
assert_eq!(r[i * n + i].im, 0.0);
}
}
}
}
#[test]
fn complex_eigh_diagonalizes() {
let n = 4;
let a = hpd(n, 3);
for (lower, jacobi) in [(true, false), (false, false), (true, true), (false, true)] {
let (v, w) = eigh(&a, 1, n, lower, jacobi);
assert!(w.windows(2).all(|p| p[0] <= p[1]));
let mut vw = v.clone();
for r in 0..n {
for c in 0..n {
vw[r * n + c] = vw[r * n + c].scale(w[c]);
}
}
assert_cclose(&cmatmul(&vw, &adjoint(&v, n, n), n, n, n), &a, 1e-10);
assert_cclose(&cmatmul(&adjoint(&v, n, n), &v, n, n, n), &ceye(n), 1e-12);
for c in 0..n {
let best = (0..n)
.max_by(|&i, &j| v[i * n + c].abs().total_cmp(&v[j * n + c].abs()))
.unwrap();
assert_eq!(v[best * n + c].im, 0.0);
assert!(v[best * n + c].re > 0.0);
}
}
}
#[test]
fn complex_svd_reconstructs() {
for (m, n) in [(4, 3), (3, 4), (3, 3)] {
let a = cmatrix(m, n, (m * 7 + n) as u64);
let k = m.min(n);
for (full, jacobi) in [(false, false), (true, false), (false, true), (true, true)] {
let (s, u, vt) = svd(&a, 1, m, n, full, true, jacobi);
assert!(s.windows(2).all(|p| p[0] >= p[1]));
let (uc, vr) = if full { (m, n) } else { (k, k) };
let mut us = vec![Z::ZERO; m * vr];
for i in 0..m {
for j in 0..k {
us[i * vr + j] = u[i * uc + j].scale(s[j]);
}
}
assert_cclose(&cmatmul(&us, &vt, m, vr, n), &a, 1e-12);
assert_cclose(
&cmatmul(&adjoint(&u, m, uc), &u, uc, m, uc),
&ceye(uc),
1e-12,
);
assert_cclose(
&cmatmul(&vt, &adjoint(&vt, vr, n), vr, n, vr),
&ceye(vr),
1e-12,
);
}
}
}
#[test]
fn qr_pivoting_moves_large_columns_forward() {
let a = [1.0, 0.0, 5.0, 2.0, 0.1, 0.0, 0.0, 0.0, 1.0];
let (q, r, p) = qr_pivoting(&a, 1, 3, 3, false);
assert_eq!(p, [2, 0, 1]);
let mut ap = vec![0.0; 9];
for i in 0..3 {
for j in 0..3 {
ap[i * 3 + j] = a[i * 3 + p[j] as usize];
}
}
assert_close(&matmul(&q, &r, 3, 3, 3), &ap, 1e-12);
assert!(r[0].abs() >= r[4].abs() && r[4].abs() >= r[8].abs());
for (m, n) in [(4, 3), (3, 5), (5, 5)] {
let mut a = matrix(m, n, (m * 13 + n) as u64);
for i in 0..m {
a[i * n + n - 1] = a[i * n];
}
for full in [false, true] {
let (q, r, p) = qr_pivoting(&a, 1, m, n, full);
let kq = if full { m } else { m.min(n) };
let mut ap = vec![0.0; m * n];
for i in 0..m {
for j in 0..n {
ap[i * n + j] = a[i * n + p[j] as usize];
}
}
assert_close(&matmul(&q, &r, m, kq, n), &ap, 1e-12);
let mut sorted = p.clone();
sorted.sort_unstable();
assert_eq!(sorted, (0..n as i32).collect::<Vec<_>>());
}
}
let (_, _, p) = qr_pivoting::<f64>(&[], 2, 0, 3, true);
assert_eq!(p, [0; 6]);
}
#[test]
fn complex_qr_pivoting_reconstructs() {
let (m, n) = (4, 3);
let a = cmatrix(m, n, 21);
let (q, r, p) = qr_pivoting(&a, 1, m, n, false);
let mut ap = vec![Z::ZERO; m * n];
for i in 0..m {
for j in 0..n {
ap[i * n + j] = a[i * n + p[j] as usize];
}
}
assert_cclose(&cmatmul(&q, &r, m, n, n), &ap, 1e-12);
assert_cclose(&cmatmul(&adjoint(&q, m, n), &q, n, m, n), &ceye(n), 1e-12);
}
#[test]
fn householder_product_and_ormqr_agree_with_qr() {
let (m, n) = (5, 3);
let a = matrix(m, n, 44);
let mut r = a.clone();
let taus = geqrf_one(&mut r, m, n);
let q = householder_product(&r, &taus, 1, m, n, n);
let (q_ref, _) = qr(&a, 1, m, n, false);
assert_close(&q, &q_ref, 1e-14);
let c = matrix(m, 2, 45);
let qc = ormqr(&r, &taus, &c, 1, (m, n, n), (m, 2), true, false);
let back = ormqr(&r, &taus, &qc, 1, (m, n, n), (m, 2), true, true);
assert_close(&back, &c, 1e-12);
let ct = transpose(&c, m, 2);
let cq = ormqr(&r, &taus, &ct, 1, (m, n, n), (2, m), false, true);
assert_close(&transpose(&cq, 2, m), &qc, 1e-12);
}
}