Sign in

Betti numbers

Counts of the holes of each dimension in a shape: connected pieces, loops and enclosed voids, computed from matrix ranks.

Overview

Topology describes a shape by features that survive stretching and bending. Betti numbers count them. β0\beta_0 is the number of separate pieces, β1\beta_1 the number of independent loops, and β2\beta_2 the number of enclosed hollow spaces. A circle has β0=1\beta_0 = 1 and β1=1\beta_1 = 1. 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 ε\varepsilon 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

  1. List the simplices of the complex and add all their faces, so every triangle brings its edges and vertices.
  2. For each dimension kk, write the boundary matrix ∂k\partial_k, which records the (k−1)(k-1)-faces of each kk-simplex, with arithmetic modulo 2.
  3. Find the rank of each boundary matrix by Gaussian elimination over the two-element field.
  4. Compute βk\beta_k as the number of kk-simplices minus the rank of ∂k\partial_k minus the rank of ∂k+1\partial_{k+1}.
  5. For a point cloud, first build the Vietoris-Rips complex at scale ε\varepsilon: a set of points forms a simplex when all its pairwise distances are at most ε\varepsilon.
  6. Repeat over a range of scales to get a Betti curve, which shows how the counts change as ε\varepsilon grows.

Watch out for

  • The answer depends completely on ε\varepsilon. 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

IfUse instead
No single scale is clearly rightPersistent homology, which tracks the counts across all scales
You only need the number of clustersA clustering method such as DBSCAN
You want a picture of the data's overall shape to exploreThe Mapper algorithm

Math foundations

  1. The boundary map

    ∂k [v0,…,vk]=∑i=0k [v0,…,vi^,…,vk](mod2)\partial_k\,[v_0,\dots,v_k] = \sum_{i=0}^{k}\,[v_0,\dots,\widehat{v_i},\dots,v_k] \pmod 2

    The boundary of a kk-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.

  2. A boundary has no boundary

    ∂k∘∂k+1=0\partial_{k}\circ\partial_{k+1} = 0

    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.

  3. Homology and the Betti number

    Hk=ker⁡∂k / im⁡∂k+1,βk=dim⁡HkH_k = \ker\partial_k \,/\, \operatorname{im}\partial_{k+1}, \qquad \beta_k = \dim H_k

    Cycles are chains with no boundary, the kernel of ∂k\partial_k. Some cycles are just the boundary of something filled in, the image of ∂k+1\partial_{k+1}. Holes are the cycles left after discarding those.

  4. The rank formula

    βk=nk−rank⁡∂k−rank⁡∂k+1\beta_k = n_k - \operatorname{rank}\partial_k - \operatorname{rank}\partial_{k+1}

    This is what the template computes. By the rank-nullity theorem the kernel of ∂k\partial_k has dimension nk−rank⁡∂kn_k - \operatorname{rank}\partial_k, and the image of ∂k+1\partial_{k+1} has dimension rank⁡∂k+1\operatorname{rank}\partial_{k+1}.

  5. Euler characteristic

    χ=∑k(−1)knk=∑k(−1)kβk\chi = \sum_{k}(-1)^k n_k = \sum_{k}(-1)^k \beta_k

    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.

  6. Vietoris-Rips complex

    σ={x0,…,xk}∈VR⁡ε(X)  ⟺  ∥xi−xj∥≤ε  for all i,j\sigma = \{x_{0},\dots,x_{k}\} \in \operatorname{VR}_{\varepsilon}(X) \iff \lVert x_{i}-x_{j}\rVert \le \varepsilon \ \text{ for all } i,j

    The rule that turns a point cloud into a complex at scale ε\varepsilon. Only pairwise distances are needed, which makes it easy to build in any dimension.

Symbols

βk\beta_k
Betti number k: the number of independent k-dimensional holes
[v0,…,vk][v_0,\dots,v_k]
a k-simplex with vertices v_0 to v_k
∂k\partial_k
boundary map from k-simplices to (k-1)-simplices
nkn_k
number of k-simplices in the complex
HkH_k
homology group k
ker⁡, im⁡\ker,\ \operatorname{im}
kernel (what maps to zero) and image (what is reached) of a linear map
χ\chi
Euler characteristic
ε\varepsilon
scale of the Vietoris-Rips complex, epsilon in the template
X, σX,\ \sigma
the point cloud and a simplex of it

Worked by hand

A hollow triangle: vertices 0, 1, 2 and edges (0,1)(0,1), (1,2)(1,2), (0,2)(0,2), with no filled face. So n0=3n_0 = 3, n1=3n_1 = 3, n2=0n_2 = 0. 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 rank⁡∂1=2\operatorname{rank}\partial_1 = 2.

β0=n0−rank⁡∂0−rank⁡∂1=3−0−2=1\beta_0 = n_0 - \operatorname{rank}\partial_0 - \operatorname{rank}\partial_1 = 3 - 0 - 2 = 1
β1=n1−rank⁡∂1−rank⁡∂2=3−2−0=1\beta_1 = n_1 - \operatorname{rank}\partial_1 - \operatorname{rank}\partial_2 = 3 - 2 - 0 = 1
χ=3−3=0=β0−β1=1−1\chi = 3 - 3 = 0 = \beta_0 - \beta_1 = 1 - 1

One connected piece and one loop, the same as a circle. Filling in the triangle adds one 2-simplex with rank⁡∂2=1\operatorname{rank}\partial_2 = 1, which gives β1=3−2−1=0\beta_1 = 3-2-1 = 0: 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 β1=1\beta_1 = 1?

Check on learning

  1. For points sampled on a circle, describe how β0\beta_0 and β1\beta_1 change as ε\varepsilon 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.

  2. 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 β0\beta_0 and β2\beta_2 known.

  3. Why must the complex contain all its (k+1)(k+1)-simplices for βk\beta_k to be correct? What goes wrong if triangles are left out when counting loops?
    A way to think about it

    Look at the term rank⁡∂k+1\operatorname{rank}\partial_{k+1} in the formula. Without the triangles, no loop is ever recognised as filled in.

  4. Two data sets have the same Betti numbers at ε=1\varepsilon = 1. 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.