Overview
Topology describes a shape by features that survive stretching and bending. Betti numbers count them. is the number of separate pieces, the number of independent loops, and the number of enclosed hollow spaces. A circle has and . A hollow sphere has one piece, no loops and one void. To compute them, the shape is built from simple blocks called simplices: points, edges, triangles, tetrahedra. Finding holes then becomes linear algebra: a loop is a chain of edges with no boundary that is not itself the boundary of some triangles. For data, the template joins points closer than a scale and counts the holes of the result.
A short history
The numbers are named after the Italian mathematician Enrico Betti, who studied the connectivity of higher dimensional spaces in 1871. Henri Poincaré gave them their name and a rigorous setting in his 1895 paper Analysis Situs, the founding work of algebraic topology. In the 1920s Emmy Noether showed that they are the ranks of homology groups. They entered data analysis from the 2000s as simple, deformation invariant summaries of the shape of a point cloud.
How it works
- List the simplices of the complex and add all their faces, so every triangle brings its edges and vertices.
- For each dimension , write the boundary matrix , which records the -faces of each -simplex, with arithmetic modulo 2.
- Find the rank of each boundary matrix by Gaussian elimination over the two-element field.
- Compute as the number of -simplices minus the rank of minus the rank of .
- For a point cloud, first build the Vietoris-Rips complex at scale : a set of points forms a simplex when all its pairwise distances are at most .
- Repeat over a range of scales to get a Betti curve, which shows how the counts change as grows.
Watch out for
- The answer depends completely on . Too small and every point is its own piece, too large and everything merges into one blob with no holes.
- A single noisy point can open or close a loop, so Betti numbers at one scale are unstable. Persistent homology tracks features across scales for that reason.
- The number of simplices in a Rips complex grows very fast with the number of points and the dimension, so this template suits small clouds only.
- Ranks are taken modulo 2, which is standard for data but cannot see torsion, a kind of twisting that shows up in shapes such as the Klein bottle.
Use cases
When to use it
Summarising the shape of a small point cloud or network at one chosen scale: how many clusters it has, whether it contains loops or cavities, and how those counts change with scale.
In industry
- Materials science
- Researchers count connected components, tunnels and voids in three dimensional scans of porous rock or foams to relate pore structure to flow.
- Neuroscience
- Studies of neural activity and connectivity use Betti numbers of networks built from recordings to describe cycles and cavities.
- Sensor networks
- Homology has been used to check whether the ranges of a set of sensors cover a region without holes, using only which sensors overlap.
Choosing it: what must hold
- Data represented as a simplicial complex, for example built from a point cloud at a chosen distance scale.
- A scale at which the complex reflects the real shape; a poor choice gives counts of noise.
- A small enough complex for the boundary matrix ranks to be computed, since size grows fast with points and dimension.
- A question about the number of pieces, loops or voids, not about sizes or distances.
When to choose something else
| If | Use instead |
|---|---|
| No single scale is clearly right | Persistent homology, which tracks the counts across all scales |
| You only need the number of clusters | A clustering method such as DBSCAN |
| You want a picture of the data's overall shape to explore | The Mapper algorithm |
Math foundations
The boundary map
The boundary of a -simplex is the sum of its faces, each obtained by dropping one vertex (the hat marks the dropped one). The boundary of an edge is its two endpoints. The boundary of a triangle is its three edges.
A boundary has no boundary
Take the edges around a triangle: each vertex appears twice, and twice is zero modulo 2. So every boundary is a cycle, which is what makes the next definition meaningful.
Homology and the Betti number
Cycles are chains with no boundary, the kernel of . Some cycles are just the boundary of something filled in, the image of . Holes are the cycles left after discarding those.
The rank formula
This is what the template computes. By the rank-nullity theorem the kernel of has dimension , and the image of has dimension .
Euler characteristic
The alternating count of simplices equals the alternating sum of Betti numbers. It is a quick check on a computation: vertices minus edges plus triangles must match pieces minus loops plus voids.
Vietoris-Rips complex
The rule that turns a point cloud into a complex at scale . Only pairwise distances are needed, which makes it easy to build in any dimension.
Symbols
- Betti number k: the number of independent k-dimensional holes
- a k-simplex with vertices v_0 to v_k
- boundary map from k-simplices to (k-1)-simplices
- number of k-simplices in the complex
- homology group k
- kernel (what maps to zero) and image (what is reached) of a linear map
- Euler characteristic
- scale of the Vietoris-Rips complex, epsilon in the template
- the point cloud and a simplex of it
Worked by hand
A hollow triangle: vertices 0, 1, 2 and edges , , , with no filled face. So , , . The edge boundary matrix has three columns, each with two ones, and any two of them are independent while all three sum to zero, so .
One connected piece and one loop, the same as a circle. Filling in the triangle adds one 2-simplex with , which gives : the loop is gone.
Visual example
Loading the example.
Try this
- Grow ε from 0 on the ring: 16 pieces merge into 1, then a loop appears, then triangles fill it.
- Choose two rings and find the range of ε where β₀ = 2 and β₁ = 2.
- Remove one point from the ring at ε = 0.5 and see how much larger ε must be to close the loop again.
Code sample
import numpy as np
from impl import BettiNumbers
from config import BettiNumbersConfig
b = BettiNumbers(BettiNumbersConfig(max_dimension=2, epsilon=0.6))
print(b.betti([(0, 1), (1, 2), (0, 2)])) # hollow triangle: [1, 1, 0]
angles = np.linspace(0, 2 * np.pi, 12, endpoint=False)
points = np.column_stack([np.cos(angles), np.sin(angles)])
print(b.from_points(points)) # 12 points on a circle: [1, 1, 0]
print(b.betti_curve(points, [0.4, 0.6, 2.0]))Read the implementation (112 lines)
"""Betti numbers of a simplicial complex over Z/2, from the ranks of its boundary matrices.
NumPy and the standard library only. Matrix rows are stored as Python integers used as bit sets, so Gaussian
elimination mod 2 is a few XOR operations per row.
"""
from __future__ import annotations
import itertools
import numpy as np
try:
from .config import BettiNumbersConfig
except ImportError: # run from the template's own folder
from config import BettiNumbersConfig
def rank_mod_2(rows: list) -> int:
"""Rank over Z/2 of a 0/1 matrix whose rows are given as integers (bit j set = entry in column j)."""
pivots: dict[int, int] = {} # highest set bit -> the reduced row that owns it
for row in rows:
while row:
high = row.bit_length() - 1
if high not in pivots:
pivots[high] = row
break
row ^= pivots[high]
return len(pivots)
class BettiNumbers:
"""beta_k = dim ker(boundary_k) - rank(boundary_{k+1}) = n_k - rank(boundary_k) - rank(boundary_{k+1})."""
def __init__(self, config: BettiNumbersConfig | None = None) -> None:
self.config = config or BettiNumbersConfig()
@staticmethod
def closure(simplices) -> dict:
"""Add every face of every given simplex.
simplices: iterable of vertex tuples, for example [(0, 1, 2), (2, 3)].
Returns {dimension: sorted list of sorted vertex tuples}.
"""
found: set = set()
for simplex in simplices:
vertices = tuple(sorted(set(simplex)))
for size in range(1, len(vertices) + 1):
found.update(itertools.combinations(vertices, size))
by_dim: dict[int, list] = {}
for s in found:
by_dim.setdefault(len(s) - 1, []).append(s)
return {d: sorted(v) for d, v in sorted(by_dim.items())}
@staticmethod
def boundary_rank(complex_: dict, k: int) -> int:
"""Rank over Z/2 of the boundary map from k-simplices to (k-1)-simplices."""
if k <= 0 or k not in complex_:
return 0
column = {face: j for j, face in enumerate(complex_[k - 1])}
rows = []
for simplex in complex_[k]:
bits = 0
for drop in range(len(simplex)):
bits |= 1 << column[simplex[:drop] + simplex[drop + 1:]]
rows.append(bits)
return rank_mod_2(rows)
def betti(self, simplices) -> list:
"""Betti numbers [beta_0, ..., beta_max_dimension] of the complex spanned by `simplices`.
Faces are added automatically. beta_k is exact when the complex holds all its (k+1)-simplices,
which is always the case for a complex you list in full.
"""
complex_ = self.closure(simplices)
top = self.config.max_dimension
ranks = [self.boundary_rank(complex_, k) for k in range(top + 2)]
return [len(complex_.get(k, [])) - ranks[k] - ranks[k + 1] for k in range(top + 1)]
def euler_characteristic(self, simplices) -> int:
"""Alternating count of simplices: vertices - edges + triangles - ..."""
return sum((-1) ** d * len(s) for d, s in self.closure(simplices).items())
def rips_complex(self, points) -> list:
"""Simplices of the Vietoris-Rips complex of `points` (n, d) at scale epsilon.
A set of points forms a simplex when all its pairwise distances are at most epsilon. Simplices
up to dimension max_dimension + 1 are listed, which is what beta_0..beta_max_dimension need.
"""
points = np.asarray(points, dtype=float)
if points.ndim != 2:
raise ValueError(f"points must have shape (n, d), got {points.shape}")
diff = points[:, None, :] - points[None, :, :]
near = np.sqrt(np.sum(diff * diff, axis=-1)) <= self.config.epsilon
n = points.shape[0]
level = [(i,) for i in range(n)]
out = list(level)
for _ in range(self.config.max_dimension + 1):
level = [s + (v,) for s in level for v in range(s[-1] + 1, n) if near[list(s), v].all()]
out.extend(level)
return out
def from_points(self, points) -> list:
"""Betti numbers of the Vietoris-Rips complex of a point cloud (n, d) at scale epsilon."""
return self.betti(self.rips_complex(points))
def betti_curve(self, points, scales) -> np.ndarray:
"""Betti numbers at each scale. Returns an integer array of shape (len(scales), max_dimension + 1)."""
rows = []
for eps in scales:
at_scale = BettiNumbers(BettiNumbersConfig(max_dimension=self.config.max_dimension, epsilon=float(eps)))
rows.append(at_scale.from_points(points))
return np.array(rows, dtype=int)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
With BettiNumbers() call betti([(0, 1), (1, 2), (0, 2)]) and then betti([(0, 1, 2)]) and compare with the worked example, checking euler_characteristic each time. Then sample 20 points on a circle of radius 1 and call betti_curve(points, scales) for scales from 0.1 to 2.5. At which scales is ?
Check on learning
- For points sampled on a circle, describe how and change as grows from 0 to the diameter. Why does the loop eventually disappear?
A way to think about it
Start with isolated points, then picture neighbours joining into a ring. Ask at what scale triangles begin to span across the middle.
- A complex has 10 vertices, 15 edges, 4 triangles, and is connected with no voids. How many independent loops does it have?
A way to think about it
Use the Euler characteristic two ways: once from the simplex counts and once from the Betti numbers, with and known.
- Why must the complex contain all its -simplices for to be correct? What goes wrong if triangles are left out when counting loops?
A way to think about it
Look at the term in the formula. Without the triangles, no loop is ever recognised as filled in.
- Two data sets have the same Betti numbers at . Does that mean they have the same shape?
A way to think about it
Consider one large circle and one small circle with a few far outliers, and ask what happens at other scales. Betti numbers at a single scale are a coarse summary.