Skip to main content

lib_jsl_linalg/sparse/
expm.rs

1//! The action of the matrix exponential on a vector, `e^{tA} b`, without forming `e^{tA}`
2//! (SciPy's `expm_multiply`): Al-Mohy and Higham's truncated Taylor series with scaling, after
3//! shifting `A` by the mean of its eigenvalues.
4
5use super::formats::CsrMatrix;
6use crate::error::{LinalgError, Result};
7
8/// `θ_m`: the largest `‖tA‖₁` for which `m` Taylor terms reach double precision (Al-Mohy and
9/// Higham 2011, table 3.1, as in SciPy).
10const THETA: [(usize, f64); 35] = [
11    (1, 2.29e-16), (2, 2.58e-8), (3, 1.39e-5), (4, 3.40e-4), (5, 2.40e-3), (6, 9.07e-3), (7, 2.38e-2), (8, 5.00e-2), (9, 8.96e-2), (10, 1.44e-1),
12    (11, 2.14e-1), (12, 3.00e-1), (13, 4.00e-1), (14, 5.14e-1), (15, 6.41e-1), (16, 7.81e-1), (17, 9.31e-1), (18, 1.09), (19, 1.26), (20, 1.44),
13    (21, 1.62), (22, 1.82), (23, 2.01), (24, 2.22), (25, 2.43), (26, 2.64), (27, 2.86), (28, 3.08), (29, 3.31), (30, 3.54),
14    (35, 4.7), (40, 6.0), (45, 7.2), (50, 8.5), (55, 9.9),
15];
16const M_MAX: usize = 55;
17
18fn theta(m: usize) -> Option<f64> {
19    THETA.iter().find(|(k, _)| *k == m).map(|(_, t)| *t)
20}
21
22fn one_norm(a: &CsrMatrix) -> f64 {
23    let mut col = vec![0.0; a.ncols];
24    for (j, v) in a.indices.iter().zip(&a.data) {
25        col[*j] += v.abs();
26    }
27    col.into_iter().fold(0.0, f64::max)
28}
29
30fn inf_norm(v: &[f64]) -> f64 {
31    v.iter().fold(0.0f64, |m, x| m.max(x.abs()))
32}
33
34/// The largest `p` with `p(p − 1) ≤ m_max + 1`.
35fn p_max() -> usize {
36    (1..).take_while(|p| p * (p - 1) <= M_MAX + 1).last().expect("p = 1 qualifies")
37}
38
39// ANCHOR: parameters
40/// The number of Taylor terms `m` and scaling steps `s` that minimise the work `m s` (code
41/// fragment 3.1 of Al-Mohy and Higham). For moderate norms (condition 3.13) `s = ⌈‖tA‖₁/θ_m⌉`;
42/// otherwise the bound uses `α_p = max(‖(tA)^p‖^{1/p}, ‖(tA)^{p+1}‖^{1/(p+1)})`, which can be much
43/// smaller than `‖tA‖₁` for non-normal matrices. SciPy estimates those norms; here they are
44/// computed exactly from sparse powers.
45fn parameters(a: &CsrMatrix, t: f64, norm: f64) -> (usize, usize) {
46    let pm = p_max();
47    let ell = 2.0;
48    let condition_3_13 = norm <= 2.0 * ell * pm as f64 * (pm as f64 + 3.0) * theta(M_MAX).unwrap() / M_MAX as f64;
49    let (mut best_m, mut best_s) = (0usize, usize::MAX);
50    if condition_3_13 {
51        for &(m, th) in &THETA {
52            let s = (norm / th).ceil() as usize;
53            if best_s == usize::MAX || m * s < best_m * best_s {
54                best_m = m;
55                best_s = s;
56            }
57        }
58    } else {
59        // d_p = ‖(tA)^p‖₁^{1/p}, from exact sparse powers.
60        let mut d = vec![0.0; pm + 2];
61        let mut power = a.clone();
62        for (p, slot) in d.iter_mut().enumerate().skip(1) {
63            if p > 1 {
64                power = power.matmul(a).expect("square");
65            }
66            *slot = t.abs() * one_norm(&power).powf(1.0 / p as f64);
67        }
68        for p in 2..=pm {
69            let alpha = d[p].max(d[p + 1]);
70            for m in p * (p - 1) - 1..=M_MAX {
71                if let Some(th) = theta(m) {
72                    let s = (alpha / th).ceil() as usize;
73                    if best_s == usize::MAX || m * s < best_m * best_s {
74                        best_m = m;
75                        best_s = s;
76                    }
77                }
78            }
79        }
80        best_s = best_s.max(1);
81    }
82    (best_m, best_s)
83}
84// ANCHOR_END: parameters
85
86// ANCHOR: expm_multiply
87/// `e^{tA} b` (SciPy's `expm_multiply` at one time point). With `μ = trace(A)/n` and `B = A − μI`,
88/// `e^{tA} b = e^{tμ} (e^{tB/s})^s b`, and each factor is applied by the Taylor series
89/// `Σ_{j≤m} (tB/s)^j b / j!`, stopping early once two consecutive terms are negligible.
90pub fn expm_multiply(a: &CsrMatrix, b: &[f64], t: f64) -> Result<Vec<f64>> {
91    let n = a.nrows;
92    if a.ncols != n || b.len() != n {
93        return Err(LinalgError::Shape(format!("{} × {} operator with a vector of length {}", a.nrows, a.ncols, b.len())));
94    }
95    let mu = a.diagonal().iter().sum::<f64>() / n as f64;
96    let shifted = a.add(1.0, &CsrMatrix::identity(n), -mu)?;
97    let norm = t.abs() * one_norm(&shifted);
98    let (m, s) = if norm == 0.0 { (0, 1) } else { parameters(&shifted, t, norm) };
99    let tol = 2f64.powi(-53);
100    let eta = (t * mu / s as f64).exp();
101    let mut f = b.to_vec();
102    let mut v = b.to_vec();
103    for _ in 0..s {
104        let mut c1 = inf_norm(&v);
105        for j in 0..m {
106            let coeff = t / (s * (j + 1)) as f64;
107            v = shifted.matvec(&v).into_iter().map(|x| coeff * x).collect();
108            let c2 = inf_norm(&v);
109            f.iter_mut().zip(&v).for_each(|(fi, vi)| *fi += vi);
110            if c1 + c2 <= tol * inf_norm(&f) {
111                break;
112            }
113            c1 = c2;
114        }
115        f.iter_mut().for_each(|x| *x *= eta);
116        v = f.clone();
117    }
118    Ok(f)
119}
120// ANCHOR_END: expm_multiply
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125    use crate::matfun::expm;
126    use ndarray::Array1;
127
128    #[test]
129    fn matches_the_dense_exponential() {
130        // A nonsymmetric tridiagonal matrix, at small and large norms.
131        let n = 30;
132        let a = CsrMatrix::diags(&[vec![-2.0; n], vec![1.3; n - 1], vec![0.7; n - 1]], &[0, 1, -1], n, n).unwrap();
133        let b: Vec<f64> = (0..n).map(|i| (i as f64 * 0.3).sin()).collect();
134        for t in [0.1, 1.0, 25.0] {
135            let got = expm_multiply(&a, &b, t).unwrap();
136            let dense = expm(&a.to_dense().mapv(|v| v * t)).unwrap();
137            let want = dense.dot(&Array1::from_vec(b.clone()));
138            let scale = want.iter().fold(0.0f64, |m, v| m.max(v.abs()));
139            assert!(got.iter().zip(want.iter()).all(|(g, w)| (g - w).abs() < 1e-12 * scale), "t = {t}");
140        }
141    }
142}