Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Matrix functions and matrix equations

ProblemCompute the matrix exponential ; solve the linear matrix equations of Sylvester () and Lyapunov (, ); find the stabilising solutions of the continuous and discrete algebraic Riccati equations, which give optimal (LQR) controllers and steady-state Kalman filters
Devised byJames Joseph Sylvester (1884); Aleksandr Lyapunov (1892), stability; Jacopo Riccati (1724); Richard Bartels and G. W. Stewart (1972), the Schur method; Cleve Moler and Charles Van Loan (1978), “nineteen dubious ways”; Nicholas Higham (2005), scaling and squaring; John Roberts (1971), the matrix sign function; David Kleinman (1968) and Gary Hewer (1971), Newton’s method; Eric Chu, Hung-Yuan Fan, Wen-Wei Lin and Chern-Shuh Wang (2004), the doubling algorithm
AccuracyAgrees with SciPy to for expm, Sylvester and Lyapunov, and to for the Riccati equations, with residuals as small as SciPy’s
Costexpm: 6 to 10 matrix products and one LU, plus one product per halving of the norm. Sylvester and Lyapunov: two Schur forms and triangular solves. Riccati: about 10 iterations of each, then 1 to 3 Lyapunov solves
Read firstSymmetric and general eigensolvers, Control: state-space models, PID controllers and the Kalman filter
APIexpm, schur_complex, solve_sylvester, solve_continuous_lyapunov, solve_discrete_lyapunov, solve_continuous_are, solve_discrete_are

Overview

Linear systems of differential equations are solved by the matrix exponential: . It turns a continuous-time model into the discrete-time one that a computer simulates or controls, and it is the most used function of a matrix. Questions about such systems lead to equations whose unknown is itself a matrix:

  • the Sylvester equation , linear in ;
  • the Lyapunov equations (continuous) and (discrete), which give the energy and the covariance of a stable system, and prove its stability;
  • the algebraic Riccati equations, quadratic in , whose solutions give the optimal linear-quadratic regulator and the steady-state Kalman filter:

The library follows SciPy’s names and conventions for all of them.

Where it is used

Matrix functions and equations are central to linear systems theory.

  • Linear dynamics. The matrix exponential is the state-transition matrix that solves ; it discretises a continuous-time system.
  • Control. Lyapunov equations test stability and measure energy; Riccati equations give optimal controllers (LQR) and Kalman filters.
  • Model reduction and vibrations. Sylvester equations arise in decoupling and in balanced truncation.

History

The exponential series is as old as matrices, but computing it well is not: in “Nineteen dubious ways to compute the exponential of a matrix” (1978), Cleve Moler and Charles Van Loan showed how each obvious method fails on some matrix. Their recommendation, scaling and squaring with a Padé approximant, became the standard, and Nicholas Higham (2005) made it precise, choosing the degree and the scaling to reach full accuracy at the least cost; SciPy and MATLAB use his algorithm and its refinements.

Sylvester studied in 1884. Aleksandr Lyapunov’s 1892 thesis on the stability of motion introduced the energy functions that lead to his equation. Richard Bartels and G. W. Stewart (1972) solved both by reducing the coefficients to Schur form, the method LAPACK and SciPy still use. The quadratic equation is named after Jacopo Riccati’s study of a scalar differential equation (1724); Rudolf Kálmán (1960) showed that its matrix form gives the optimal regulator and filter. David Kleinman (1968) and Gary Hewer (1971) solved it by Newton’s method, John Roberts (1971) by the matrix sign function, and Alan Laub (1979) by the Schur vectors of the Hamiltonian matrix. The structure-preserving doubling algorithm of Eric Chu, Hung-Yuan Fan, Wen-Wei Lin and Chern-Shuh Wang (2004) converges quadratically without needing an invertible .

The idea

The matrix exponential

The Taylor series converges for every matrix, but summing it in floating point fails when is large. The terms first grow, then shrink, and when their largest value is much larger than the answer, its rounding errors swamp it. Moler and Van Loan’s example has eigenvalues and , so is small, but its Taylor terms are huge:

Table 7.9. The Taylor series against scaling and squaring.

tlargest Taylor termerror, Taylor serieserror, expm
0.16.4e03e-162e-15
0.52.7e35e-134e-15
19.3e63e-91e-14
21.6e142e-12e-14

The error grows like times the largest term. Scaling and squaring avoids it with the identity : divide by until its norm is small, approximate the exponential of the small matrix, and square the result times. The approximation is a Padé approximant , a ratio of two polynomials of degree that matches the series to order . For , , so with the odd and the even part of , . Higham bounded the backward error of by the norm of . The library takes the lowest degree whose bound covers . Above , it uses and scales until .

The Bartels-Stewart method

is a linear system for the entries of , but solving it as one costs . Instead, reduce and to their complex Schur forms and , with and upper triangular. With and , the equation becomes . Because is triangular, column of involves only columns :

a triangular system for each column. Each system is singular exactly when , so the solution is unique when no eigenvalue of is the negative of an eigenvalue of . The continuous Lyapunov equation is the case . The discrete one, , reduces the same way to . Its column involves only the later columns: . That system is unique when no product of eigenvalues equals 1.

Riccati equations

For the continuous equation, let and form the Hamiltonian matrix . A direct calculation gives

exactly when solves the Riccati equation. The columns of therefore span an invariant subspace of , and the stabilising solution, the one that makes the closed loop stable, belongs to the subspace of the eigenvalues in the left half-plane. The eigenvalues of come in pairs , so exactly half are stable when none lie on the imaginary axis. The matrix sign function maps the stable eigenvalues to and the unstable ones to , keeping the eigenvectors. The stable subspace is then the null space of , and follows from a least-squares solve. Newton’s iteration converges quadratically to ; the scaling speeds up the first steps.

For the discrete equation, the doubling algorithm iterates three matrices from , and :

Each step doubles the horizon of a finite-horizon Riccati recursion: is the cost-to-go over steps. It therefore converges quadratically to , and needs neither an invertible nor any eigenvalue computation.

Both iterations end with a few Newton steps. Linearising the Riccati equation around an approximate gives a Lyapunov equation for the correction. For the continuous equation it is (Kleinman), where is the residual; for the discrete one it is a discrete Lyapunov equation in the closed loop (Hewer). Each step roughly squares the error, and the library stops when the residual no longer decreases.

Algorithm

expm(A):

  1. If for some , take the smallest such and . Otherwise take and , and replace by .
  2. Form and from the even powers (for , from , and only, in Horner form).
  3. Solve with one LU factorisation.
  4. Square times.

solve_sylvester(A, B, Q): complex Schur forms of and ; ; for , solve the shifted triangular system for column of ; return . The continuous Lyapunov solver calls it with ; the discrete one runs the analogous column recurrence from the last column.

solve_continuous_are(A, B, Q, R): ; the sign iteration on until the change is below ; from by least squares; Newton steps while the residual decreases.

solve_discrete_are(A, B, Q, R): the doubling iteration until changes by less than ; Newton steps while the residual decreases. Both return the Hermitian part of .

Implementation

/// The matrix exponential `eᴬ = I + A + A²/2! + …` (SciPy's `linalg.expm`).
///
/// Scaling and squaring (Higham 2005): choose the lowest Padé degree `m ∈ {3, 5, 7, 9, 13}`
/// accurate to rounding for `‖A‖₁`, or, for larger norms, scale `A` by `2⁻ˢ` until
/// `‖A‖₁ ≤ θ₁₃`; evaluate `r_m(A) = (V − U)⁻¹ (V + U)` from the even part `V` and odd part `U` of
/// the Padé numerator; and square the result `s` times.
pub fn expm<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<Array2<T>> {
    let a = Mat::from_array(a)?;
    require_square(a.rows, a.cols)?;
    let n = a.rows;
    let eye = Mat::<T>::identity(n);
    let norm = norm1(&a);
    let a2 = matmul(&a, &a);
    // Low degrees: U = A Σ b_{2k+1} A^{2k}, V = Σ b_{2k} A^{2k}.
    for (m, theta) in THETA {
        if norm <= theta {
            let b: &[f64] = match m {
                3 => &B3,
                5 => &B5,
                7 => &B7,
                _ => &B9,
            };
            let (mut u, mut v) = (Mat::zeros(n, n), Mat::zeros(n, n));
            let mut power = eye.clone();
            for k in 0..=m / 2 {
                u = lincomb(T::one(), &u, T::from_real(b[2 * k + 1]), &power);
                v = lincomb(T::one(), &v, T::from_real(b[2 * k]), &power);
                if k < m / 2 {
                    power = matmul(&power, &a2);
                }
            }
            return Ok(pade_quotient(&matmul(&a, &u), &v)?.into_array());
        }
    }
    // Degree 13 with scaling: A ← A / 2ˢ.
    let s = (norm / THETA13).log2().ceil().max(0.0) as i32;
    let scale = T::from_real(0.5f64.powi(s));
    let a1 = Mat { rows: n, cols: n, data: a.data.iter().map(|&v| v * scale).collect() };
    let a2 = matmul(&a1, &a1);
    let a4 = matmul(&a2, &a2);
    let a6 = matmul(&a4, &a2);
    let b = |k: usize| T::from_real(B13[k]);
    let sum3 = |c6: T, c4: T, c2: T, c0: T| {
        let t = lincomb(c6, &a6, c4, &a4);
        let t = lincomb(T::one(), &t, c2, &a2);
        lincomb(T::one(), &t, c0, &eye)
    };
    let inner_u = sum3(b(13), b(11), b(9), T::zero());
    let u = lincomb(T::one(), &matmul(&a6, &inner_u), T::one(), &sum3(b(7), b(5), b(3), b(1)));
    let u = matmul(&a1, &u);
    let inner_v = sum3(b(12), b(10), b(8), T::zero());
    let v = lincomb(T::one(), &matmul(&a6, &inner_v), T::one(), &sum3(b(6), b(4), b(2), b(0)));
    let mut r = pade_quotient(&u, &v)?;
    for _ in 0..s {
        r = matmul(&r, &r);
    }
    Ok(r.into_array())
}
/// Bartels-Stewart for `A X + X B = Q` on complex matrices.
fn sylvester(a: &Mat<C>, b: &Mat<C>, q: &Mat<C>) -> Result<Mat<C>> {
    let (r, u) = schur_unbalanced(a)?;
    let (s, v) = schur_unbalanced(b)?;
    // With A = U R Uᴴ and B = V S Vᴴ, Y = Uᴴ X V solves R Y + Y S = F = Uᴴ Q V.
    let f = matmul(&matmul(&u.adjoint(), q), &v);
    let (n, m) = (a.rows, b.rows);
    let tiny = f64::EPSILON * (max_abs(&r) + max_abs(&s)).max(f64::MIN_POSITIVE);
    let mut y = Mat::<C>::zeros(n, m);
    // S is upper triangular, so column k of Y involves only columns j ≤ k:
    // (R + s_kk I) y_k = f_k − Σ_{j<k} s_jk y_j.
    for k in 0..m {
        let mut rhs = column(&f, k);
        for j in 0..k {
            let sjk = s.at(j, k);
            for i in 0..n {
                rhs[i] -= sjk * y.at(i, j);
            }
        }
        shifted_back_substitution(&r, s.at(k, k), &mut rhs, tiny)?;
        set_column(&mut y, k, &rhs);
    }
    Ok(matmul(&matmul(&u, &y), &v.adjoint()))
}
/// Solves the discrete algebraic Riccati equation
/// `Aᴴ X A − X − Aᴴ X B (R + Bᴴ X B)⁻¹ Bᴴ X A + Q = 0` for the stabilising solution (SciPy's
/// `linalg.solve_discrete_are`, without its `e` and `s` options), for which `A − B K` with
/// `K = (R + Bᴴ X B)⁻¹ Bᴴ X A` has all its eigenvalues inside the unit circle.
///
/// The structure-preserving doubling algorithm (Chu, Fan, Lin and Wang 2004) starts from
/// `A₀ = A`, `G₀ = B R⁻¹ Bᴴ`, `H₀ = Q` and iterates
/// `A ← A (I + G H)⁻¹ A`, `G ← G + A (I + G H)⁻¹ G Aᴴ`, `H ← H + Aᴴ H (I + G H)⁻¹ A`;
/// `H` converges quadratically to `X`, which is then polished by Newton (Hewer) steps, each a
/// discrete Lyapunov equation. Requires `(A, B)` stabilisable and no eigenvalues of the
/// symplectic pencil on the unit circle; `A` need not be invertible.
pub fn solve_discrete_are<T: Scalar, S1: Data<Elem = T>, S2: Data<Elem = T>, S3: Data<Elem = T>, S4: Data<Elem = T>>(
    a: &ArrayBase<S1, Ix2>,
    b: &ArrayBase<S2, Ix2>,
    q: &ArrayBase<S3, Ix2>,
    r: &ArrayBase<S4, Ix2>,
) -> Result<Array2<T>> {
    let (a, b, q, r) = riccati_inputs(a, b, q, r)?;
    let n = a.rows;
    let eye = Mat::<C>::identity(n);
    let (mut ak, mut gk, mut hk) = (a.clone(), matmul(&b, &solve_left(&r, &b.adjoint())?), q.clone());
    let mut converged = false;
    for _ in 0..100 {
        let w = add(&eye, &matmul(&gk, &hk));
        let t1 = solve_left(&w, &ak).map_err(|_| LinalgError::NoConvergence("the doubling algorithm (I + G H singular)"))?;
        let t2 = solve_left(&w, &gk)?;
        let h_next = add(&hk, &matmul(&matmul(&ak.adjoint(), &hk), &t1));
        let g_next = add(&gk, &matmul(&matmul(&ak, &t2), &ak.adjoint()));
        ak = matmul(&ak, &t1);
        let change = norm1(&sub(&h_next, &hk));
        (gk, hk) = (g_next, h_next);
        if change <= 1e-14 * norm1(&hk) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(LinalgError::NoConvergence("the doubling algorithm"));
    }
    let bh = b.adjoint();
    let gain = |x: &Mat<C>| -> Result<Mat<C>> {
        let bhx = matmul(&bh, x);
        solve_left(&add(&r, &matmul(&bhx, &b)), &matmul(&bhx, &a))
    };
    let residual = |x: &Mat<C>| {
        let ah_x = matmul(&a.adjoint(), x);
        let k = gain(x).unwrap_or_else(|_| Mat::zeros(b.cols, n));
        hermitian_part(&add(&sub(&sub(&matmul(&ah_x, &a), x), &matmul(&matmul(&ah_x, &b), &k)), &q))
    };
    let correction = |x: &Mat<C>, res: &Mat<C>| {
        // (A − B K)ᴴ Δ (A − B K) − Δ + Res = 0.
        let ac = sub(&a, &matmul(&b, &gain(x)?));
        stein(&ac.adjoint(), res)
    };
    Ok(back(refine(hermitian_part(&hk), 10, residual, correction)))
}
  • The equations are solved in complex arithmetic. The complex Schur form avoids the 2 × 2 blocks of the real form, and for real data the real part is returned. expm works in the input’s own arithmetic, so real matrices stay real.
  • The Schur forms are computed without balancing, so that and are unitary; schur_complex makes this factorisation public.
  • The Riccati solvers omit SciPy’s options e (a descriptor matrix) and s (a cross term). A cross term can be absorbed by replacing with and with .

In practice

Every function is compared with SciPy 1.17.1 on random 20 × 20 problems, with references written by book/generator/data/make_matrix_equations_refs.py. The difference is relative to the largest entry of SciPy’s solution. The residuals are those of the equation, also relative to the largest entry of the solution, for the library’s and for SciPy’s:

Table 7.10. Matrix functions and equations against SciPy.

computation (SciPy reference)differenceresidual, libraryresidual, SciPy
expm, 20 × 20, ‖A‖₁ ≈ 4.6 (linalg.expm)1e-16
expm, 20 × 20, ‖A‖₁ ≈ 54, entries up to 4 × 10⁵8e-16
expm, complex 20 × 204e-16
solve_sylvester, 20 × 20 and 15 × 156e-153e-153e-15
solve_continuous_lyapunov, 20 × 203e-154e-154e-15
solve_continuous_lyapunov, complex4e-154e-156e-15
solve_discrete_lyapunov, 20 × 20, spectral radius 0.88e-153e-152e-15
solve_continuous_are, 20 states, 4 inputs2e-132e-132e-13
solve_continuous_are, complex2e-131e-133e-13
solve_discrete_are, 20 states, 4 inputs3e-152e-163e-15

An optimal controller. A cart on a frictionless track, with position and velocity as its state and a force as its input, has and . Sampled every s with the force held constant in between, it becomes . Both matrices come from one exponential: . The linear-quadratic regulator minimises , and its optimal input is , with and the solution of the discrete Riccati equation. With penalising position only, the weight trades speed against effort:

Figure 7.10. LQR responses.

Table 7.11. LQR gains for three control weights.

Rgain Kspectral radius of A − BKlargest force
0.01[8.00, 4.00]0.8008.00
0.1[2.79, 2.36]0.8822.79
1[0.93, 1.37]0.9320.93

A steady-state Kalman filter. Estimation is the dual of control. The Kalman filter’s predicted covariance converges to the solution of the discrete Riccati equation for , so a filter that runs long enough can use the constant gain from the start. For the constant-velocity tracker (, ), the steady-state gain from solve_discrete_are is , and the covariance of the running KalmanFilter, started from , agrees with it to after 82 measurements.

Strengths

  • expm is accurate to rounding for any norm, and cheap for small norms.
  • The Schur method handles any coefficients with a unique solution, real or complex, including unstable in the Sylvester equation.
  • The Riccati solvers need no initial stabilising gain and no invertible , and the Newton refinement brings their residuals to the level of SciPy’s.

Weaknesses

  • The sign function fails when the Hamiltonian has eigenvalues on or near the imaginary axis. These are marginally stabilisable or detectable problems, where every method loses accuracy.
  • No descriptor () or cross () terms, and no other matrix functions (logm, sqrtm, funm).
  • The solvers are with dense matrices, suitable for up to a few hundred states. Large sparse problems need low-rank methods.

Exercises

  1. Show that when , and find matrices for which it fails.
  2. Show that for a stable (all eigenvalues in the left half-plane), solves , and that is positive definite when is.
  3. Verify for the Hamiltonian matrix, and show that the eigenvalues of come in pairs , .
  4. Use expm on to discretise with , and check and .
  5. For the scalar discrete Riccati equation with , , and , solve the quadratic and check the doubling iteration against it.
Hints and answers
  1. When and commute, the binomial theorem applies to and the series multiply term by term. A counterexample is , : has on its diagonal, but .
  2. , since the integrand decays. For , .
  3. The first block row reads . The second reads , which is the Riccati equation. For the pairs, is Hermitian for , so and is similar to .
  4. The top blocks of the exponential are and .
  5. With the equation is , so . With , , the golden ratio. The doubling iterates reach it to rounding in about five steps.

Further reading

  • C. Moler and C. Van Loan, “Nineteen dubious ways to compute the exponential of a matrix, twenty-five years later”, SIAM Review 45 (2003) 3–49.
  • N. J. Higham, “The scaling and squaring method for the matrix exponential revisited”, SIAM Journal on Matrix Analysis and Applications 26 (2005) 1179–1193.
  • R. H. Bartels and G. W. Stewart, “Solution of the matrix equation AX + XB = C”, Communications of the ACM 15 (1972) 820–826.
  • E. K.-W. Chu, H.-Y. Fan, W.-W. Lin and C.-S. Wang, “Structure-preserving algorithms for periodic discrete-time algebraic Riccati equations”, International Journal of Control 77 (2004) 767–788.
  • P. Lancaster and L. Rodman, Algebraic Riccati Equations, Oxford University Press, 1995.