Sign in

Persistent homology

A method that tracks the clusters, loops and voids of a point cloud as a distance scale grows, and records when each one appears and disappears.

Overview

To see the shape of a cloud of points you must decide how close two points have to be to count as connected. Any single choice is arbitrary. Persistent homology uses every choice at once. Grow a scale from zero. Points join into edges when they come within the scale of each other, then into triangles, and so on. Along the way clusters merge, loops form and later get filled in. Each feature is recorded with its birth scale and its death scale. Features that last over a long range of scales reflect real structure. Features that vanish almost at once are artefacts of sampling. The template computes this for a Vietoris-Rips filtration with the standard matrix reduction, written for clarity.

A short history

Related ideas appeared in the 1990s in Patrizio Frosini's size functions and Vanessa Robins's work on multiscale topology. Herbert Edelsbrunner, David Letscher and Afra Zomorodian gave the definition and an efficient algorithm in Topological Persistence and Simplification, published in 2002, and Zomorodian and Gunnar Carlsson supplied the algebraic foundation in 2005. Homology at one scale is fragile. Tracking features across all scales separates lasting structure from noise.

How it works

  1. Compute all pairwise distances between the points, or accept a ready distance matrix with metric: precomputed.
  2. List every simplex up to dimension max_dimension plus one, each with the scale at which it appears: the length of its longest edge.
  3. Sort the simplices by scale, then by dimension, so every face comes before the simplices that contain it.
  4. Build the boundary matrix modulo 2: column jj holds the faces of simplex jj.
  5. Reduce the columns left to right, adding earlier columns until every non-empty column has its lowest one in a row of its own.
  6. Read the pairs: a reduced column jj with lowest row ii means simplex ii created a feature and simplex jj destroyed it. An empty column never paired creates a feature that lives forever.
  7. Convert each pair to (birth scale, death scale), drop pairs of zero length and return one diagram per dimension.

Watch out for

  • The number of simplices grows very fast with the number of points, so this textbook version handles tens of points in dimension 2 and about a hundred in dimension 1.
  • A few outliers far from the cloud create long dimension 0 bars that look like separate clusters, because the method uses distances alone and ignores density.
  • Results depend on the metric. Features measured in very different units should be scaled first or one of them will dominate every distance.
  • Setting max_edge_length too low cuts off features before they die, so they are reported as infinite bars that are not truly permanent.
  • Homology is taken modulo 2, the usual choice for data, which cannot detect torsion.

Use cases

When to use it

Describing the shape of a small to medium point cloud without choosing a scale in advance, for example to detect clusters, circular structure in periodic data, or cavities.

In industry

Structural biology and chemistry
Persistent homology of atom positions gives descriptors of protein and molecule shape that are used to predict properties such as binding affinity.
Cosmology
Astronomers apply it to galaxy survey data to quantify the filaments and voids of the cosmic web.
Time series and dynamics
Engineers embed a signal with time delays and use persistent loops to detect periodic behaviour in machine or physiological data.

Choosing it: what must hold

  • A point cloud with a meaningful metric, or a function on a grid such as an image.
  • A data size the computation can handle: Vietoris-Rips complexes grow very fast, so thousands of points in low homology dimension is typical.
  • Outliers handled or a robust filtration chosen, since single stray points can create or destroy features.
  • A question in which shape, such as clusters, loops or voids, is plausibly informative.

When to choose something else

IfUse instead
The data set is too large for a Rips filtrationSubsampling with landmark points, or an alpha or witness complex
You want an overview graph for explorationThe Mapper algorithm
A single trusted scale existsBetti numbers at that scale
Only cluster structure mattersHierarchical clustering, which matches dimension zero persistence

Math foundations

  1. The Vietoris-Rips filtration

    VR⁡r(X)={σ⊆X:d(x,y)≤r  for all x,y∈σ},VR⁡r⊆VR⁡r′  for r≤r′\operatorname{VR}_{r}(X) = \big\{\sigma \subseteq X : d(x,y) \le r \ \text{ for all } x,y \in \sigma\big\}, \qquad \operatorname{VR}_{r} \subseteq \operatorname{VR}_{r'} \ \text{ for } r \le r'

    At scale rr, a set of points forms a simplex when all of them are within rr of each other. The complexes are nested: growing rr only ever adds simplices, and that nesting is what lets features be followed from one scale to the next.

  2. Appearance scale of a simplex

    r(σ)=max⁡x,y ∈ σd(x,y)r(\sigma) = \max_{x,y\,\in\,\sigma} d(x,y)

    A simplex enters the filtration when its longest edge does. Vertices enter at 0.

  3. Homology at one scale

    Hk(VR⁡r)=ker⁡∂k / im⁡∂k+1,βk(r)=dim⁡Hk(VR⁡r)H_k\big(\operatorname{VR}_r\big) = \ker\partial_k \,/\, \operatorname{im}\partial_{k+1}, \qquad \beta_k(r) = \dim H_k\big(\operatorname{VR}_r\big)

    At each fixed scale, kk-dimensional holes are cycles that are not boundaries, and the Betti number counts them. k=0k=0 gives connected components, k=1k=1 loops, k=2k=2 voids.

  4. Matrix reduction

    low⁡(j)=max⁡{ i:Rij=1 },while low⁡(j)=low⁡(j′) for some j′<j:  Rj←Rj+Rj′(mod2)\operatorname{low}(j) = \max\{\,i : R_{ij} = 1\,\}, \qquad \text{while } \operatorname{low}(j) = \operatorname{low}(j') \text{ for some } j' < j:\ \ R_j \leftarrow R_j + R_{j'} \pmod 2

    RR starts as the boundary matrix in filtration order. Adding an earlier column removes a shared lowest entry. The loop ends when the column is empty or its lowest row is not owned by any earlier column.

  5. Reading off the pairs

    Rj≠0,  i=low⁡(j) ⟹ feature born at r(σi), dies at r(σj)R_j \ne 0,\ \ i = \operatorname{low}(j) \ \Longrightarrow\ \text{feature born at } r(\sigma_i),\ \text{dies at } r(\sigma_j)

    Simplex σi\sigma_i created a cycle and the later simplex σj\sigma_j filled it in. The feature has the dimension of σi\sigma_i. An empty column whose index never becomes a lowest row gives a feature with infinite death.

  6. Persistence

    pers⁡=r(σj)−r(σi)\operatorname{pers} = r(\sigma_j) - r(\sigma_i)

    The range of scales over which the feature exists. Long persistence marks structure that does not depend on a fine choice of scale.

Symbols

XX
the point cloud
d(x,y)d(x,y)
distance between two points
r, r′r,\ r'
scale values, the largest edge length allowed
σ\sigma
a simplex: a set of points
r(σ)r(\sigma)
the scale at which the simplex appears
∂k\partial_k
boundary map on k-simplices, modulo 2
Hk, βkH_k,\ \beta_k
homology group k and its dimension, the Betti number
R, RjR,\ R_j
the boundary matrix being reduced and its column j
low⁡(j)\operatorname{low}(j)
row index of the lowest 1 in column j
σi, σj\sigma_i,\ \sigma_j
the simplices at positions i and j in filtration order

Worked by hand

Four points at the corners of a unit square. The four sides have length 1 and the two diagonals have length 2=1.414\sqrt{2} = 1.414. Follow the scale rr upward.

r=0:  4 vertices appear ⇒ 4 components born at 0r = 0:\ \ 4 \text{ vertices appear} \ \Rightarrow\ 4 \text{ components born at } 0
r=1:  4 sides appear. Three of them merge the components: H0 bars (0,1), (0,1), (0,1), (0,∞)r = 1:\ \ 4 \text{ sides appear. Three of them merge the components: } H_0 \text{ bars } (0,1),\ (0,1),\ (0,1),\ (0,\infty)
r=1:  the fourth side closes a cycle ⇒ a loop is born at 1r = 1:\ \ \text{the fourth side closes a cycle} \ \Rightarrow\ \text{a loop is born at } 1
r=1.414:  diagonals and triangles appear and fill the square ⇒ H1 bar (1, 1.414)r = 1.414:\ \ \text{diagonals and triangles appear and fill the square} \ \Rightarrow\ H_1 \text{ bar } (1,\ 1.414)

Dimension 0 has three bars (0,1)(0, 1) and one infinite bar. Dimension 1 has one bar (1,1.414)(1, 1.414) with persistence 0.414: the square's loop exists only between the side length and the diagonal length.

Visual example

Loading the example.

Try this

  • Press Run and watch pieces merge, the loop appear, and triangles fill it.
  • Choose the unit square with jitter at 0: the loop lives from 1 to 1.414, as in the worked example.
  • Raise the jitter on the ring and see which bars change and which one stays long.

Code sample

import numpy as np
from impl import PersistentHomology
from config import PersistentHomologyConfig

angles = np.linspace(0, 2 * np.pi, 20, endpoint=False)
points = np.column_stack([np.cos(angles), np.sin(angles)])       # 20 points on a circle
h0, h1 = PersistentHomology(PersistentHomologyConfig(max_dimension=1)).fit(points)
print(h1)                                                      # one (birth, death) row: the loop
print(PersistentHomology.betti_numbers([h0, h1], scale=0.5))   # [1, 1]: one component, one loop
Read the implementation (125 lines)
"""Persistent homology of a Vietoris-Rips filtration, by boundary matrix reduction over Z/2.

NumPy and the standard library only. This is the textbook algorithm written for clarity: every simplex up to
dimension max_dimension + 1 is listed, so it suits small point clouds (tens of points for dimension 2, up to
about a hundred for dimension 1). Production libraries add cohomology, clearing and implicit matrices.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import PersistentHomologyConfig
except ImportError:  # run from the template's own folder
    from config import PersistentHomologyConfig


def rips_filtration(dist: np.ndarray, max_simplex_dim: int, max_edge_length: float | None = None) -> list:
    """All simplices of the Vietoris-Rips complex with the scale at which each appears.

    dist: symmetric distance matrix, shape (n, n).
    A simplex appears when all its edges are present, so its scale is its longest edge.
    Returns a list of (scale, vertices) with vertices a sorted tuple, ordered by scale, then dimension,
    then vertices. That order puts every face before the simplices it belongs to.
    """
    n = dist.shape[0]
    limit = math.inf if max_edge_length is None else max_edge_length
    level = [(0.0, (i,)) for i in range(n)]
    out = list(level)
    for _ in range(max_simplex_dim):
        grown = []
        for scale, simplex in level:
            members = list(simplex)
            for v in range(simplex[-1] + 1, n):  # extend by a larger vertex, so each simplex is built once
                reach = float(dist[members, v].max())
                if reach <= limit:
                    grown.append((max(scale, reach), simplex + (v,)))
        out.extend(grown)
        level = grown
    out.sort(key=lambda item: (item[0], len(item[1]), item[1]))
    return out


def reduce_boundary_matrix(simplices: list) -> tuple[list, list]:
    """The standard persistence algorithm.

    simplices: vertex tuples in filtration order (faces first).
    Column j of the boundary matrix holds the faces of simplex j. Columns are reduced left to right by
    adding (mod 2) earlier columns until every lowest non-zero row is unique. A column that ends non-empty
    with lowest row i means simplex j kills the class that simplex i created.
    Returns (pairs, unpaired): pairs is a list of (birth index, death index), unpaired the indices of
    simplices that create a class which never dies.
    """
    index = {s: i for i, s in enumerate(simplices)}
    pivot_owner: dict[int, int] = {}  # lowest row -> the column that owns it
    reduced: dict[int, set] = {}
    creators, pairs, killed = [], [], set()
    for j, simplex in enumerate(simplices):
        column = set()
        if len(simplex) > 1:
            column = {index[simplex[:k] + simplex[k + 1:]] for k in range(len(simplex))}
        while column:
            low = max(column)
            if low not in pivot_owner:
                break
            column ^= reduced[pivot_owner[low]]
        if column:
            low = max(column)
            pivot_owner[low] = j
            reduced[j] = column
            pairs.append((low, j))
            killed.add(low)
        else:
            creators.append(j)
    return pairs, [i for i in creators if i not in killed]


class PersistentHomology:
    """Computes persistence diagrams: one (birth, death) pair per topological feature."""

    def __init__(self, config: PersistentHomologyConfig | None = None) -> None:
        self.config = config or PersistentHomologyConfig()

    def distance_matrix(self, data) -> np.ndarray:
        """The (n, n) distance matrix: computed from points (n, d), or checked when precomputed."""
        data = np.asarray(data, dtype=float)
        if self.config.metric == "precomputed":
            if data.ndim != 2 or data.shape[0] != data.shape[1] or not np.allclose(data, data.T):
                raise ValueError("a precomputed distance matrix must be square and symmetric")
            return data
        if data.ndim != 2:
            raise ValueError(f"points must have shape (n, d), got {data.shape}")
        diff = data[:, None, :] - data[None, :, :]
        return np.sqrt(np.sum(diff * diff, axis=-1))

    def fit(self, data) -> list:
        """Persistence diagrams of the Vietoris-Rips filtration.

        data: points (n, d), or a distance matrix (n, n) when metric is `precomputed`.
        Returns a list with one array per dimension 0..max_dimension, each of shape (m, 2) holding
        (birth, death) rows sorted by birth. A feature that never dies has death = inf. Features that
        die at the scale they are born are dropped.
        """
        dist = self.distance_matrix(data)
        top = self.config.max_dimension
        filtration = rips_filtration(dist, top + 1, self.config.max_edge_length)
        scales = [s for s, _ in filtration]
        simplices = [v for _, v in filtration]
        pairs, unpaired = reduce_boundary_matrix(simplices)
        bars: list[list] = [[] for _ in range(top + 1)]
        for birth, death in pairs:
            dim = len(simplices[birth]) - 1
            if dim <= top and scales[death] > scales[birth]:
                bars[dim].append((scales[birth], scales[death]))
        for birth in unpaired:
            dim = len(simplices[birth]) - 1
            if dim <= top:  # classes created by the top-dimensional simplices are not computed
                bars[dim].append((scales[birth], math.inf))
        return [np.array(sorted(b), dtype=float).reshape(-1, 2) for b in bars]

    @staticmethod
    def betti_numbers(diagrams: list, scale: float) -> list:
        """Number of features of each dimension alive at `scale` (birth <= scale < death)."""
        return [int(np.sum((d[:, 0] <= scale) & (scale < d[:, 1]))) for d in diagrams]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Run PersistentHomology().fit(points) on the four corners of the unit square and compare both diagrams with the worked example. Then sample 30 points on a circle of radius 1, fit again, and find the longest dimension 1 bar. Use PersistentHomology.betti_numbers(diagrams, scale) at a scale inside that bar and at one beyond its death.

Check on learning

  1. For 30 points on a unit circle, roughly at what scales is the main loop born and killed? What does each scale correspond to geometrically?
    A way to think about it

    The loop is born when neighbouring points connect all the way round, so think about the largest gap between neighbours. It dies when triangles can span the middle, which needs edges of a certain length relative to the radius.

  2. Why does every dimension 0 bar start at 0 in a Rips filtration, and what do the death values of those bars tell you about the data?
    A way to think about it

    All vertices are present from the start. Each death is the scale at which two clusters merge, which links these bars to single-linkage clustering.

  3. In the unit square, one of the four sides creates a loop while the other three destroy components. What decides which role a simplex plays?
    A way to think about it

    When an edge arrives, check whether its two endpoints are already connected. In the reduction this is whether its column becomes empty.

  4. A data set has one very long dimension 1 bar and twenty very short ones. A colleague says it has 21 loops. How would you respond?
    A way to think about it

    Compare the persistence values. Then think about how sampling noise creates tiny cycles that are filled in almost at once.