Source code for hatvis.spectral

r"""Random walks and spectral methods.

Random walks on hypergraphs differ in how the walker moves through a
hyperedge. The *Zhou walk* (Zhou, Huang and Schölkopf 2006) picks a hyperedge
and then a vertex uniformly; the *edge-dependent* walk uses vertex weights that
depend on the hyperedge (Chitra and Raphael 2019); the *higher-order* walk of
Carletti et al. (2020) favours large hyperedges. Spectral embeddings and
spectral clustering use the eigenvectors of the hypergraph Laplacian.
"""

from __future__ import annotations

import numpy as np
import pandas as pd
import scipy.sparse as sp

from .core import Hypergraph
from .representations import clique_adjacency, laplacian

__all__ = ["transition_matrix", "stationary_distribution", "spectral_embedding", "spectral_clustering",
           "fiedler_vector", "algebraic_connectivity"]


[docs] def transition_matrix(H: Hypergraph, kind: str = "zhou") -> sp.csr_array: r"""Row-stochastic transition matrix of a random walk on the vertices. ``kind`` * ``"zhou"``: :math:`\mathbf{P}=\mathbf{D}_v^{-1}\mathbf{B}\mathbf{W}\mathbf{D}_e^{-1}\mathbf{B}^\mathsf{T}` on the 0/1 incidence pattern (the walker may stay put); * ``"edge_dependent"``: as ``"zhou"`` but the second step chooses :math:`v\in e` with probability :math:`b_{ve}/\sum_x b_{xe}`; * ``"carletti"``: :math:`p_{ij}\propto\sum_{e\ni i,j}(|e|-1)`, :math:`i\ne j`; * ``"clique"``: simple random walk on the clique expansion. Rows of isolated vertices are zero. """ Bb = H.binary_incidence() w = H.weights if kind in ("zhou", "edge_dependent"): G = Bb if kind == "zhou" else H.incidence de = np.asarray(G.sum(axis=0)).ravel() de_inv = np.divide(1.0, de, out=np.zeros_like(de), where=de > 0) M = Bb @ sp.diags_array(w * de_inv) @ G.T elif kind == "carletti": sizes = np.asarray(Bb.sum(axis=0)).ravel() M = (Bb @ sp.diags_array(w * (sizes - 1)) @ Bb.T).tocsr() M.setdiag(0) M.eliminate_zeros() elif kind == "clique": M = clique_adjacency(H, "count", dense=False) else: raise ValueError("kind must be 'zhou', 'edge_dependent', 'carletti' or 'clique'") M = sp.csr_array(M) rs = np.asarray(M.sum(axis=1)).ravel() inv = np.divide(1.0, rs, out=np.zeros_like(rs), where=rs > 0) return sp.csr_array(sp.diags_array(inv) @ M)
[docs] def stationary_distribution(H: Hypergraph, kind: str = "zhou", tol: float = 1e-13, max_iter: int = 10000 ) -> pd.Series: r"""Stationary distribution :math:`\boldsymbol{\pi}=\boldsymbol{\pi}\mathbf{P}` of a random walk. For the Zhou walk on a connected hypergraph :math:`\pi_i=d_i/\sum_j d_j` (weighted degrees); the function iterates the lazy chain for any ``kind``. """ P = transition_matrix(H, kind) n = H.n_nodes x = np.ones(n) / n PT = P.T.tocsr() for _ in range(max_iter): y = 0.5 * (x + PT @ x) s = y.sum() y = y / s if s else y if np.abs(y - x).sum() < tol: x = y break x = y return pd.Series(x, index=H.nodes, name="stationary distribution")
[docs] def spectral_embedding(H: Hypergraph, dim: int = 2, kind: str = "normalized", drop_first: bool = True ) -> pd.DataFrame: r"""Spectral embedding of the vertices (Zhou et al. 2006). Uses the eigenvectors of the ``dim`` smallest eigenvalues of the hypergraph Laplacian (the first, trivial one is dropped). For the normalized Laplacian the coordinates are rescaled by :math:`\mathbf{D}_v^{-1/2}`. """ L = laplacian(H, kind) vals, vecs = np.linalg.eigh(L) start = 1 if drop_first else 0 Y = vecs[:, start:start + dim] if kind == "normalized": dv = H.degrees(weighted=True).to_numpy(float) Y = Y / np.sqrt(np.maximum(dv, 1e-12))[:, None] cols = [f"dim{k + 1}" for k in range(Y.shape[1])] return pd.DataFrame(Y, index=H.nodes, columns=cols)
[docs] def spectral_clustering(H: Hypergraph, n_clusters: int, kind: str = "normalized", random_state=None, n_init: int = 10) -> pd.Series: r"""Spectral clustering of the vertices with the hypergraph Laplacian (Zhou et al. 2006). The rows of the :math:`k` leading eigenvectors of :math:`\mathbf{D}_v^{-1/2}\mathbf{B}\mathbf{W}\mathbf{D}_e^{-1}\mathbf{B}^\mathsf{T}\mathbf{D}_v^{-1/2}` (smallest of the normalized Laplacian) are normalized to unit length and clustered with *k*-means (Ng, Jordan and Weiss 2001). It approximately minimizes the normalized hypergraph cut. """ from sklearn.cluster import KMeans L = laplacian(H, kind) vals, vecs = np.linalg.eigh(L) Y = vecs[:, :n_clusters] Y = Y / np.maximum(np.linalg.norm(Y, axis=1, keepdims=True), 1e-12) km = KMeans(n_clusters=n_clusters, n_init=n_init, random_state=random_state).fit(Y) return _relabel(pd.Series(km.labels_, index=H.nodes, name="cluster"))
[docs] def fiedler_vector(H: Hypergraph, kind: str = "normalized") -> pd.Series: """Eigenvector of the second smallest Laplacian eigenvalue (sign fixed: first entry non-negative).""" vals, vecs = np.linalg.eigh(laplacian(H, kind)) f = vecs[:, 1] if f[np.argmax(np.abs(f) > 1e-12)] < 0: f = -f return pd.Series(f, index=H.nodes, name="Fiedler vector")
[docs] def algebraic_connectivity(H: Hypergraph, kind: str = "normalized") -> float: """Second smallest Laplacian eigenvalue (zero iff the hypergraph is disconnected).""" return float(np.sort(np.linalg.eigvalsh(laplacian(H, kind)))[1])
def _relabel(labels: pd.Series) -> pd.Series: """Relabel a partition with 0..k-1 in order of first appearance.""" mp = {} for x in labels: mp.setdefault(x, len(mp)) return labels.map(mp).astype(int)