"""Geometry of covariance matrices and Gaussian segment models.
A homogeneous segment of a multivariate series is summarized by its mean
and covariance. PCA similarity factors compare only the orientation of the
principal subspaces; the distances below compare the whole covariance
matrix on the manifold of symmetric positive definite (SPD) matrices, and
the Gaussian distances also take the means into account. They are the local
dissimilarities of the Riemannian extension of correlation-based dynamic
time warping (:class:`mvtsa.warping.CBDTW` with ``local="log_euclidean"``,
``"affine_invariant"``, ``"bures_wasserstein"`` or ``"gaussian_w2"``).
References: Arsigny et al. (2007) log-Euclidean metric; Pennec, Fillard and
Ayache (2006) affine-invariant metric; Bhatia, Jain and Lim (2019)
Bures--Wasserstein distance.
"""
from __future__ import annotations
import numpy as np
__all__ = [
"regularize_spd",
"spd_log",
"spd_sqrt",
"log_euclidean_distance",
"affine_invariant_distance",
"bures_wasserstein_distance",
"gaussian_w2_distance",
"gaussian_jeffreys_divergence",
"spd_mean",
]
def regularize_spd(S, eps: float = 1e-6) -> np.ndarray:
"""Symmetrize and add ``eps`` times the mean eigenvalue to the diagonal."""
S = np.atleast_2d(np.asarray(S, float))
S = (S + S.T) / 2.0
tr = np.trace(S) / S.shape[0]
return S + eps * max(tr, 1e-12) * np.eye(S.shape[0])
def _eig_fun(S, f):
lam, U = np.linalg.eigh(S)
lam = np.clip(lam, 1e-300, None)
return (U * f(lam)) @ U.T
def spd_log(S) -> np.ndarray:
"""Matrix logarithm of an SPD matrix."""
return _eig_fun(regularize_spd(S, 0.0), np.log)
def spd_sqrt(S) -> np.ndarray:
"""Matrix square root of an SPD matrix."""
return _eig_fun(regularize_spd(S, 0.0), np.sqrt)
[docs]
def log_euclidean_distance(A, B, eps: float = 1e-6) -> float:
""":math:`\\lVert\\log A-\\log B\\rVert_F` (Arsigny et al., 2007)."""
return float(np.linalg.norm(spd_log(regularize_spd(A, eps)) - spd_log(regularize_spd(B, eps))))
[docs]
def affine_invariant_distance(A, B, eps: float = 1e-6) -> float:
""":math:`\\sqrt{\\sum_i\\log^2\\lambda_i(A^{-1}B)}` (Pennec et al., 2006)."""
from scipy.linalg import eigh
A, B = regularize_spd(A, eps), regularize_spd(B, eps)
lam = eigh(B, A, eigvals_only=True)
lam = np.clip(lam, 1e-300, None)
return float(np.sqrt(np.sum(np.log(lam) ** 2)))
[docs]
def bures_wasserstein_distance(A, B, eps: float = 1e-9) -> float:
""":math:`\\bigl(\\operatorname{tr}A+\\operatorname{tr}B-2\\operatorname{tr}
(A^{1/2}BA^{1/2})^{1/2}\\bigr)^{1/2}`, the 2-Wasserstein distance of two
centered Gaussians (Bhatia et al., 2019)."""
A, B = regularize_spd(A, eps), regularize_spd(B, eps)
rA = spd_sqrt(A)
cross = spd_sqrt(rA @ B @ rA)
val = np.trace(A) + np.trace(B) - 2.0 * np.trace(cross)
return float(np.sqrt(max(val, 0.0)))
[docs]
def gaussian_w2_distance(mu1, A, mu2, B) -> float:
"""2-Wasserstein distance between :math:`N(\\mu_1,A)` and :math:`N(\\mu_2,B)`."""
d = np.asarray(mu1, float) - np.asarray(mu2, float)
return float(np.sqrt(d @ d + bures_wasserstein_distance(A, B) ** 2))
[docs]
def gaussian_jeffreys_divergence(mu1, A, mu2, B, eps: float = 1e-6) -> float:
"""Symmetric Kullback--Leibler (Jeffreys) divergence of two Gaussians."""
A, B = regularize_spd(A, eps), regularize_spd(B, eps)
n = A.shape[0]
d = np.asarray(mu1, float) - np.asarray(mu2, float)
iA, iB = np.linalg.inv(A), np.linalg.inv(B)
kl1 = 0.5 * (np.trace(iB @ A) + d @ iB @ d - n + np.linalg.slogdet(B)[1] - np.linalg.slogdet(A)[1])
kl2 = 0.5 * (np.trace(iA @ B) + d @ iA @ d - n + np.linalg.slogdet(A)[1] - np.linalg.slogdet(B)[1])
return float(max(kl1 + kl2, 0.0))
[docs]
def spd_mean(mats, metric: str = "log_euclidean", weights=None) -> np.ndarray:
"""Mean of SPD matrices: ``"log_euclidean"`` (closed form) or
``"euclidean"``."""
M = [regularize_spd(S) for S in mats]
w = np.ones(len(M)) / len(M) if weights is None else np.asarray(weights, float) / np.sum(weights)
if metric == "euclidean":
return sum(wi * S for wi, S in zip(w, M, strict=True))
if metric == "log_euclidean":
L = sum(wi * spd_log(S) for wi, S in zip(w, M, strict=True))
return _eig_fun((L + L.T) / 2, np.exp)
raise ValueError(f"unknown metric {metric!r}")