Skip to main content

lib_jsl_electromagnetics/
linalg.rs

1//! Small complex linear-algebra helpers shared by the signal models and beamformers.
2
3use crate::conventions::C64;
4use lib_jsl_core::ErrorsJSL;
5use ndarray::{Array1, Array2};
6use lib_jsl_linalg::{Eigh, UPLO};
7
8/// `‖R v - λ v‖` summed over the eigenpairs.
9fn residual(r: &Array2<C64>, vals: &[f64], vecs: &Array2<C64>) -> f64 {
10    (0..vals.len()).map(|k| {
11        let v = vecs.column(k);
12        let rv = r.dot(&v);
13        rv.iter().zip(v.iter()).map(|(a, b)| (a - b * vals[k]).norm()).sum::<f64>()
14    }).sum()
15}
16
17/// Eigen-decomposition of a Hermitian matrix: eigenvalues in *descending* order and the matching
18/// orthonormal eigenvectors as columns, verified against `R v = λ v`.
19pub(crate) fn hermitian_eigen(r: &Array2<C64>) -> Result<(Vec<f64>, Array2<C64>), ErrorsJSL> {
20    let n = r.nrows();
21    if r.ncols() != n || n == 0 {
22        return Err(ErrorsJSL::InvalidInputRange("Need a non-empty square matrix."));
23    }
24    let (vals, vecs) = r.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("Hermitian eigendecomposition failed."))?;
25    let order: Vec<usize> = (0..n).rev().collect();
26    let sorted: Vec<f64> = order.iter().map(|&i| vals[i]).collect();
27    let vectors = Array2::from_shape_fn((n, n), |(i, c)| vecs[[i, order[c]]]);
28    let scale = sorted.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(1e-300);
29    if residual(r, &sorted, &vectors) > 1e-8 * scale * n as f64 {
30        return Err(ErrorsJSL::RuntimeError("The eigendecomposition did not satisfy R v = λ v."));
31    }
32    Ok((sorted, vectors))
33}
34
35/// The conjugate transpose.
36pub(crate) fn hermitian_transpose(a: &Array2<C64>) -> Array2<C64> {
37    a.t().mapv(|v| v.conj())
38}
39
40/// `wᴴ R w` (real part; exact for Hermitian `R`).
41pub fn quadratic_form(w: &Array1<C64>, r: &Array2<C64>) -> f64 {
42    w.iter().zip(r.dot(w).iter()).map(|(a, b)| (a.conj() * b).re).sum()
43}
44
45/// Checks that `r` is square, of size `n`, and Hermitian to a relative tolerance.
46pub(crate) fn check_hermitian(r: &Array2<C64>, n: usize) -> Result<(), ErrorsJSL> {
47    if r.dim() != (n, n) {
48        return Err(ErrorsJSL::IncompatibleArraySizes((r.nrows(), n)));
49    }
50    let scale = r.iter().fold(0.0f64, |m, v| m.max(v.norm())).max(1e-300);
51    for i in 0..n {
52        for j in 0..n {
53            if (r[[i, j]] - r[[j, i]].conj()).norm() > 1e-9 * scale {
54                return Err(ErrorsJSL::InvalidInputRange("The matrix is not Hermitian."));
55            }
56        }
57    }
58    Ok(())
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn eigen_pairs_are_correct_and_descending() {
67        let r = ndarray::arr2(&[[C64::new(2.0, 0.0), C64::new(0.0, 1.0)], [C64::new(0.0, -1.0), C64::new(2.0, 0.0)]]);
68        let (vals, vecs) = hermitian_eigen(&r).unwrap();
69        assert!((vals[0] - 3.0).abs() < 1e-12 && (vals[1] - 1.0).abs() < 1e-12);
70        assert!(residual(&r, &vals, &vecs) < 1e-12);
71        assert!((quadratic_form(&vecs.column(0).to_owned(), &r) - 3.0).abs() < 1e-12);
72        assert!(check_hermitian(&r, 2).is_ok() && check_hermitian(&hermitian_transpose(&r).mapv(|v| v * C64::new(0.0, 1.0)), 2).is_err());
73    }
74}