Skip to main content

lib_jsl_linalg/
logsqrt.rs

1//! The principal matrix square root and logarithm, and fractional powers, through the complex
2//! Schur form (SciPy's `sqrtm`, `logm` and `fractional_matrix_power`).
3//!
4//! See the book entry [Matrix functions, subspaces and norms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/subspaces-norms.html).
5
6use crate::dense::{Mat, lincomb, matmul, norm1};
7use crate::eig::schur_unbalanced;
8use crate::error::{LinalgError, Result};
9use crate::lu::LuFactorization;
10use crate::scalar::Scalar;
11use ndarray::{Array2, ArrayBase, Data, Ix2};
12use num_complex::Complex;
13
14type C = Complex<f64>;
15
16// ANCHOR: sqrtm_triangular
17/// The principal square root of an upper triangular matrix, column by column (Björck and
18/// Hammarling): `rᵢᵢ = √tᵢᵢ` and `rᵢⱼ = (tᵢⱼ − Σ_{i<k<j} rᵢₖ rₖⱼ) / (rᵢᵢ + rⱼⱼ)`.
19fn sqrt_triangular(t: &Mat<C>) -> Result<Mat<C>> {
20    let n = t.rows;
21    let mut r = Mat::<C>::zeros(n, n);
22    for j in 0..n {
23        *r.at_mut(j, j) = t.at(j, j).sqrt();
24        for i in (0..j).rev() {
25            let s = (i + 1..j).fold(C::new(0.0, 0.0), |acc, k| acc + r.at(i, k) * r.at(k, j));
26            let d = r.at(i, i) + r.at(j, j);
27            if d.norm() == 0.0 {
28                return Err(LinalgError::Singular(i));
29            }
30            *r.at_mut(i, j) = (t.at(i, j) - s) / d;
31        }
32    }
33    Ok(r)
34}
35// ANCHOR_END: sqrtm_triangular
36
37fn schur<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<(Mat<C>, Mat<C>)> {
38    schur_unbalanced(&Mat::from_array(a)?)
39}
40
41fn back(z: &Mat<C>, f: &Mat<C>) -> Array2<C> {
42    matmul(&matmul(z, f), &z.adjoint()).into_array()
43}
44
45/// The principal square root `X` with `X² = A` and eigenvalues in the right half-plane (SciPy's
46/// `sqrtm`), by the Schur method: `A = Z T Zᴴ`, `X = Z R Zᴴ` with `R² = T` triangular. Matrices
47/// with eigenvalues on the closed negative real axis have no principal square root; zero
48/// eigenvalues of multiplicity above one make it fail.
49pub fn sqrtm<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<Array2<C>> {
50    let (t, z) = schur(a)?;
51    Ok(back(&z, &sqrt_triangular(&t)?))
52}
53
54/// Nodes and weights of `m`-point Gauss-Legendre quadrature on [0, 1].
55fn gauss_legendre_01(m: usize) -> Vec<(f64, f64)> {
56    (0..m)
57        .map(|i| {
58            let mut z = (std::f64::consts::PI * (i as f64 + 0.75) / (m as f64 + 0.5)).cos();
59            let mut dp = 0.0;
60            for _ in 0..100 {
61                let (mut p0, mut p1) = (1.0, z);
62                for k in 2..=m {
63                    let p2 = ((2 * k - 1) as f64 * z * p1 - (k - 1) as f64 * p0) / k as f64;
64                    p0 = p1;
65                    p1 = p2;
66                }
67                dp = m as f64 * (z * p1 - p0) / (z * z - 1.0);
68                let dz = p1 / dp;
69                z -= dz;
70                if dz.abs() < 1e-16 {
71                    break;
72                }
73            }
74            (0.5 * (z + 1.0), 1.0 / ((1.0 - z * z) * dp * dp))
75        })
76        .collect()
77}
78
79// ANCHOR: logm
80/// The principal logarithm `L` with `e^L = A` and eigenvalues with imaginary parts in `(−π, π)`
81/// (SciPy's `logm`), by the inverse scaling and squaring method on the Schur form: take square
82/// roots of `T` until `‖T − I‖₁ ≤ 0.25` (`k` times), evaluate `log(I + X)` by the `[8/8]` Padé
83/// approximant written as Gauss-Legendre quadrature, `Σ wⱼ X (I + xⱼ X)⁻¹`, and multiply by `2ᵏ`.
84pub fn logm<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<Array2<C>> {
85    let (mut t, z) = schur(a)?;
86    let n = t.rows;
87    if (0..n).any(|i| t.at(i, i).norm() == 0.0) {
88        return Err(LinalgError::Singular(0));
89    }
90    let eye = Mat::<C>::identity(n);
91    let one = C::new(1.0, 0.0);
92    let mut k = 0;
93    while norm1(&lincomb(one, &t, -one, &eye)) > 0.25 {
94        t = sqrt_triangular(&t)?;
95        k += 1;
96        if k > 100 {
97            return Err(LinalgError::NoConvergence("logm square roots"));
98        }
99    }
100    let x = lincomb(one, &t, -one, &eye);
101    let mut log = Mat::<C>::zeros(n, n);
102    for (node, weight) in gauss_legendre_01(8) {
103        // X (I + x_j X)⁻¹ = (I + x_j X)⁻¹ X, since the two commute.
104        let m = lincomb(one, &eye, C::new(node, 0.0), &x);
105        let lu = LuFactorization::new(m)?;
106        for col in 0..n {
107            let rhs: Vec<C> = (0..n).map(|r| x.at(r, col)).collect();
108            for (r, v) in lu.solve_vec(&rhs).into_iter().enumerate() {
109                *log.at_mut(r, col) += v * weight;
110            }
111        }
112    }
113    let scale = C::new(2f64.powi(k), 0.0);
114    log.data.iter_mut().for_each(|v| *v *= scale);
115    Ok(back(&z, &log))
116}
117// ANCHOR_END: logm
118
119/// `A^p = exp(p log A)` for real `p` (SciPy's `fractional_matrix_power`, by this route rather
120/// than its Schur-Padé algorithm).
121pub fn fractional_matrix_power<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, p: f64) -> Result<Array2<C>> {
122    let l = logm(a)?;
123    crate::expm(&l.mapv(|v| v * p))
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use ndarray::array;
130
131    fn max_diff(a: &Array2<C>, b: &Array2<C>) -> f64 {
132        a.iter().zip(b.iter()).fold(0.0, |m, (x, y)| m.max((x - y).norm()))
133    }
134
135    #[test]
136    fn sqrtm_squares_back_and_logm_inverts_expm() {
137        let a = array![[4.0, 1.0, 0.5], [0.2, 3.0, -0.4], [0.1, 0.3, 2.0]];
138        let s = sqrtm(&a).unwrap();
139        let ac = a.mapv(|v| C::new(v, 0.0));
140        assert!(max_diff(&s.dot(&s), &ac) < 1e-13);
141        let l = logm(&a).unwrap();
142        assert!(max_diff(&crate::expm(&l).unwrap(), &ac) < 1e-12);
143        // A rotation by θ: log is the generator.
144        let th = 0.7f64;
145        let r = array![[th.cos(), -th.sin()], [th.sin(), th.cos()]];
146        let l = logm(&r).unwrap();
147        assert!((l[(1, 0)].re - th).abs() < 1e-14 && (l[(0, 1)].re + th).abs() < 1e-14 && l[(0, 0)].norm() < 1e-14);
148        let half = fractional_matrix_power(&a, 0.5).unwrap();
149        assert!(max_diff(&half, &s) < 1e-12);
150    }
151}