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
- Compute all pairwise distances between the points, or accept a ready distance matrix with
metric: precomputed. - List every simplex up to dimension
max_dimensionplus one, each with the scale at which it appears: the length of its longest edge. - Sort the simplices by scale, then by dimension, so every face comes before the simplices that contain it.
- Build the boundary matrix modulo 2: column holds the faces of simplex .
- Reduce the columns left to right, adding earlier columns until every non-empty column has its lowest one in a row of its own.
- Read the pairs: a reduced column with lowest row means simplex created a feature and simplex destroyed it. An empty column never paired creates a feature that lives forever.
- 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_lengthtoo 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
| If | Use instead |
|---|---|
| The data set is too large for a Rips filtration | Subsampling with landmark points, or an alpha or witness complex |
| You want an overview graph for exploration | The Mapper algorithm |
| A single trusted scale exists | Betti numbers at that scale |
| Only cluster structure matters | Hierarchical clustering, which matches dimension zero persistence |
Math foundations
The Vietoris-Rips filtration
At scale , a set of points forms a simplex when all of them are within of each other. The complexes are nested: growing only ever adds simplices, and that nesting is what lets features be followed from one scale to the next.
Appearance scale of a simplex
A simplex enters the filtration when its longest edge does. Vertices enter at 0.
Homology at one scale
At each fixed scale, -dimensional holes are cycles that are not boundaries, and the Betti number counts them. gives connected components, loops, voids.
Matrix reduction
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.
Reading off the pairs
Simplex created a cycle and the later simplex filled it in. The feature has the dimension of . An empty column whose index never becomes a lowest row gives a feature with infinite death.
Persistence
The range of scales over which the feature exists. Long persistence marks structure that does not depend on a fine choice of scale.
Symbols
- the point cloud
- distance between two points
- scale values, the largest edge length allowed
- a simplex: a set of points
- the scale at which the simplex appears
- boundary map on k-simplices, modulo 2
- homology group k and its dimension, the Betti number
- the boundary matrix being reduced and its column j
- row index of the lowest 1 in column 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 . Follow the scale upward.
Dimension 0 has three bars and one infinite bar. Dimension 1 has one bar 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 loopRead 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
- 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.
- 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.
- 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.
- 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.