Overview
Persistent homology reports each feature of a shape, a cluster, a loop or a void, together with the scale at which it appears (birth) and the scale at which it is filled in or merges (death). A persistence diagram plots each feature as a point with birth on the horizontal axis and death on the vertical one. Every point lies above the diagonal, and its height above the diagonal is its persistence, its lifetime. Points far from the diagonal are robust structure. Points hugging it are short-lived and usually noise. A barcode shows the same pairs as horizontal bars. The template builds a diagram from a one-dimensional signal, summarises diagrams, and measures how different two of them are.
A short history
Herbert Edelsbrunner, David Letscher and Afra Zomorodian introduced the persistence diagram with their persistence algorithm, published in 2002. Gunnar Carlsson, Zomorodian, Anne Collins and Leonidas Guibas presented the equivalent barcode form in 2004, and Robert Ghrist's 2008 survey made barcodes widely known. In 2007 David Cohen-Steiner, Edelsbrunner and John Harer proved that small changes in the data move a diagram only slightly in bottleneck distance.
How it works
- Get a diagram: an array of (birth, death) rows, from persistent homology or from
from_signal. - For a signal, raise a water level from the bottom. Each local minimum starts a pool at its height. When two pools meet at a peak, the one with the higher minimum ends there.
- Drop pairs whose persistence is at or below
min_persistence. - Summarise the diagram: lifetimes, the Betti curve (how many bars are alive at each scale) and persistent entropy.
- Compare two diagrams by matching their points one to one, where any point may also be matched to the diagonal.
- Report the worst move of the best matching (bottleneck) or the combined cost of all moves (Wasserstein), and draw the diagram or barcode.
Watch out for
- Points near the diagonal are not always noise. In some data many short-lived features together carry the signal, so do not discard them without thought.
- The bottleneck distance sees only the single worst mismatch and ignores all other differences, while the Wasserstein distance sums over all of them.
- Diagrams with different numbers of infinite bars are at infinite distance, so compare diagrams of the same dimension from the same kind of filtration.
- The matching solver here is cubic in the number of points and suits diagrams of up to a few hundred points.
from_signalgives dimension 0 features of sublevel sets only, that is valleys. To study peaks, negate the signal first.
Use cases
When to use it
Reading and comparing the output of persistent homology: separating signal from noise by lifetime, and turning the shape of a data set or time series into numbers that can be compared across samples.
In industry
- Materials science
- Researchers compare persistence diagrams of atomic configurations to describe the structure of glasses and other amorphous materials.
- Machine learning
- Diagrams are turned into fixed length vectors, such as persistence images or landscapes, and used as shape features for classifiers.
- Biomedical signals
- Diagrams computed from delay embeddings of heart or brain signals summarise recurring patterns and are compared across patients with Wasserstein distance.
Choosing it: what must hold
- Persistent homology already computed for the data, giving a birth and a death value for each feature.
- Understanding that points far from the diagonal are long lived features and points near it are usually noise.
- A distance or vector summary chosen for the task: bottleneck for worst case difference, Wasserstein for overall difference.
- Diagrams small enough for matching distances to be affordable, or an approximate method.
When to choose something else
| If | Use instead |
|---|---|
| You need features for a standard model, not diagram to diagram distances | A vectorisation such as persistence images or landscapes |
| You only need counts of features at one scale | Betti numbers |
| You want an explorable graph of the data's shape | The Mapper algorithm |
Math foundations
The diagram
A collection of birth and death pairs, one per feature, where repeats are allowed. A death of infinity marks a feature that never disappears, such as the single connected piece that remains at the end.
Persistence
The lifetime of a feature: the length of its bar, or its vertical distance above the diagonal in the diagram. It is the basic measure of how prominent a feature is.
Betti curve
The number of features alive at scale . It turns a diagram into an ordinary function of scale.
Persistent entropy
Treat the finite lifetimes as shares of a whole and take their Shannon entropy. It is 0 when one bar dominates completely and when all bars have equal length.
Bottleneck distance
ranges over matchings between the two diagrams, where any point may be matched to the diagonal instead of a partner. The cost of a pair is the larger of the birth gap and the death gap, and sending a point to the diagonal costs half its persistence.
Wasserstein distance
The same matchings and costs, but all the moves are added after raising each to the power , the template's
wasserstein_order. Every difference between the diagrams counts, not only the worst.Stability
The stability theorem for sublevel set diagrams: if two functions differ by at most some amount everywhere, their diagrams are at most that far apart. Small noise in the input can only make small changes in the diagram, which is why diagrams are trustworthy summaries.
Symbols
- persistence diagrams
- birth and death of feature i
- number of pairs in the diagram
- a scale value
- number of features alive at scale t
- share of the total lifetime held by bar i
- a matching between two diagrams, with the diagonal allowed as a partner
- the larger of the birth gap and the death gap
- order of the Wasserstein distance
- two functions whose sublevel sets give the diagrams D(f) and D(g)
Worked by hand
Compare with . The best matching pairs with and sends to the diagonal.
The bottleneck distance is 1, set by the long bar alone. The Wasserstein distance of order 2 is 1.031 because it also counts the small bar. Pairing with instead would cost 2.5, so that matching is worse.
Visual example
Loading the example.
Try this
- Sweep the water level from bottom to top and watch pools start at dips and end where they merge.
- Raise the noise: new points crowd the diagonal and the bottleneck distance stays below the largest change in the signal.
- Raise min_persistence until only the long bars are left.
Code sample
import numpy as np
from impl import PersistenceDiagram
from config import PersistenceDiagramsConfig
pd = PersistenceDiagram(PersistenceDiagramsConfig(wasserstein_order=2.0))
x = np.linspace(0, 4 * np.pi, 200)
clean = pd.from_signal(np.sin(x))
noisy = pd.from_signal(np.sin(x) + 0.1 * np.random.default_rng(0).uniform(-1, 1, 200))
print(pd.barcode(clean))
print(pd.bottleneck_distance(clean, noisy), pd.wasserstein_distance(clean, noisy))
svg = pd.diagram_svg(noisy) # a string; write it to a .svg file to view itRead the implementation (265 lines)
"""Persistence diagrams and barcodes: build one from a signal, summarise it, compare two, draw it.
NumPy and the standard library only. A diagram is an array of shape (m, 2) with one (birth, death) row per
topological feature; death may be inf for a feature that never dies. Distances use an assignment solver
(Hungarian algorithm) and a bipartite matching, both written here; they suit diagrams of up to a few hundred
points.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import PersistenceDiagramsConfig
except ImportError: # run from the template's own folder
from config import PersistenceDiagramsConfig
def min_cost_assignment(cost: np.ndarray) -> np.ndarray:
"""Hungarian algorithm. cost: (n, n). Returns `col` (n,) with row i assigned to column col[i],
minimising the total cost."""
n = cost.shape[0]
u, v = np.zeros(n + 1), np.zeros(n + 1) # row and column potentials (index 0 is a dummy)
owner = np.zeros(n + 1, dtype=int) # owner[j]: the row matched to column j, 0 when free
way = np.zeros(n + 1, dtype=int)
for i in range(1, n + 1):
owner[0] = i
j0 = 0
slack = np.full(n + 1, np.inf)
used = np.zeros(n + 1, dtype=bool)
while True: # grow an alternating tree until it reaches a free column
used[j0] = True
i0 = owner[j0]
free = ~used[1:]
reduced = cost[i0 - 1] - u[i0] - v[1:]
better = free & (reduced < slack[1:])
slack[1:][better] = reduced[better]
way[1:][better] = j0
candidates = np.where(free, slack[1:], np.inf)
j1 = int(np.argmin(candidates)) + 1
delta = candidates[j1 - 1]
u[owner[used]] += delta
v[used] -= delta
slack[1:][free] -= delta
j0 = j1
if owner[j0] == 0:
break
while j0: # flip the matching along the path back to the root
j1 = way[j0]
owner[j0] = owner[j1]
j0 = j1
col = np.zeros(n, dtype=int)
col[owner[1:] - 1] = np.arange(n)
return col
def _has_perfect_matching(allowed: np.ndarray) -> bool:
"""True when the bipartite graph with adjacency `allowed` (n, n) has a perfect matching.
Augmenting paths, searched with an explicit stack."""
n = allowed.shape[0]
neighbours = [np.flatnonzero(row).tolist() for row in allowed]
match_of_col = [-1] * n
for start in range(n):
parent_col = {} # column -> the row that reached it
row_via = {start: -1} # row -> the column it was reached through
stack, end = [start], -1
while stack and end < 0:
row = stack.pop()
for col in neighbours[row]:
if col in parent_col:
continue
parent_col[col] = row
if match_of_col[col] < 0:
end = col
break
row_via[match_of_col[col]] = col
stack.append(match_of_col[col])
if end < 0:
return False
while end >= 0: # augment
row = parent_col[end]
match_of_col[end] = row
end = row_via[row]
return True
class PersistenceDiagram:
"""Operations on persistence diagrams, arrays of shape (m, 2) holding (birth, death) rows."""
def __init__(self, config: PersistenceDiagramsConfig | None = None) -> None:
self.config = config or PersistenceDiagramsConfig()
# ---- making and cleaning a diagram ---------------------------------------------------------------
def clean(self, diagram) -> np.ndarray:
"""Validate a diagram and drop pairs with persistence <= min_persistence. Returns (m, 2), sorted
by birth then death."""
d = np.asarray(diagram, dtype=float).reshape(-1, 2)
if np.any(np.isnan(d)) or np.any(d[:, 1] < d[:, 0]) or np.any(np.isinf(d[:, 0])):
raise ValueError("every row needs a finite birth and death >= birth")
d = d[d[:, 1] - d[:, 0] > self.config.min_persistence]
return d[np.lexsort((d[:, 1], d[:, 0]))]
def from_signal(self, values) -> np.ndarray:
"""Dimension 0 persistence diagram of the sublevel sets of a sampled function.
values: (n,) samples of a function on a line. Raise a water level from the bottom: every local
minimum starts a pool (birth), and when two pools meet at a local maximum the younger one ends
(death). The pool of the global minimum never dies. Returns the cleaned diagram.
"""
f = np.asarray(values, dtype=float).ravel()
if f.size == 0:
raise ValueError("the signal is empty")
parent = np.full(f.size, -1) # -1: not flooded yet
lowest = np.arange(f.size) # at a root: index of the minimum of its pool
def find(i: int) -> int:
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
pairs = []
for i in np.argsort(f, kind="stable"):
parent[i] = i
for j in (i - 1, i + 1):
if 0 <= j < f.size and parent[j] >= 0:
a, b = find(i), find(j)
if a == b:
continue
if f[lowest[a]] > f[lowest[b]]:
a, b = b, a # a is the older pool; b ends here
pairs.append((f[lowest[b]], f[i]))
parent[b] = a
pairs.append((f.min(), math.inf))
return self.clean(pairs)
# ---- summaries ----------------------------------------------------------------------------------
def lifetimes(self, diagram) -> np.ndarray:
"""death - birth of every pair, shape (m,)."""
d = self.clean(diagram)
return d[:, 1] - d[:, 0]
def barcode(self, diagram) -> np.ndarray:
"""The same pairs as bars, longest first, shape (m, 2)."""
d = self.clean(diagram)
return d[np.argsort(-(d[:, 1] - d[:, 0]), kind="stable")]
def betti_curve(self, diagram, grid) -> np.ndarray:
"""Number of bars alive at each value t of `grid` (birth <= t < death), shape (len(grid),)."""
d = self.clean(diagram)
t = np.asarray(grid, dtype=float).reshape(-1, 1)
return np.sum((d[:, 0] <= t) & (t < d[:, 1]), axis=1)
def persistent_entropy(self, diagram) -> float:
"""Shannon entropy of the finite lifetimes taken as a probability distribution.
0 for a single bar, log(k) for k bars of equal length."""
life = self.lifetimes(diagram)
life = life[np.isfinite(life)]
if life.size == 0:
return 0.0
p = life / life.sum()
return float(-np.sum(p * np.log(p)))
# ---- distances ----------------------------------------------------------------------------------
def _matching_costs(self, a, b) -> tuple[np.ndarray, np.ndarray]:
"""Cost matrix of the diagram matching problem, and the costs of the infinite bars.
Finite points: a point may be matched to a point of the other diagram (cost: the larger of the
birth gap and the death gap) or to the diagonal (cost: half its persistence). The square matrix
has the n points of `a` then m diagonal slots as rows, the m points of `b` then n diagonal slots
as columns. Infinite bars are matched to each other in order of birth; when their numbers differ
the distance is infinite.
"""
a, b = self.clean(a), self.clean(b)
inf_a, inf_b = np.sort(a[np.isinf(a[:, 1]), 0]), np.sort(b[np.isinf(b[:, 1]), 0])
essential = np.abs(inf_a - inf_b) if inf_a.size == inf_b.size else np.array([np.inf])
a, b = a[np.isfinite(a[:, 1])], b[np.isfinite(b[:, 1])]
n, m = a.shape[0], b.shape[0]
cost = np.zeros((n + m, n + m))
cost[:n, :m] = np.max(np.abs(a[:, None, :] - b[None, :, :]), axis=2)
cost[:n, m:] = ((a[:, 1] - a[:, 0]) / 2.0)[:, None]
cost[n:, :m] = ((b[:, 1] - b[:, 0]) / 2.0)[None, :]
return cost, essential
def bottleneck_distance(self, a, b) -> float:
"""The smallest t such that the two diagrams can be matched with every pair moved by at most t."""
cost, essential = self._matching_costs(a, b)
worst = float(essential.max()) if essential.size else 0.0
if cost.size == 0 or not math.isfinite(worst):
return worst
levels = np.unique(cost)
lo, hi = 0, levels.size - 1 # the full matrix always has a perfect matching
while lo < hi:
mid = (lo + hi) // 2
if _has_perfect_matching(cost <= levels[mid]):
hi = mid
else:
lo = mid + 1
return max(worst, float(levels[lo]))
def wasserstein_distance(self, a, b) -> float:
"""(minimum over matchings of the sum of cost^p)^(1/p), with p = wasserstein_order."""
p = self.config.wasserstein_order
cost, essential = self._matching_costs(a, b)
if essential.size and not np.all(np.isfinite(essential)):
return math.inf
total = float(np.sum(essential**p))
if cost.size:
powered = cost**p
col = min_cost_assignment(powered)
total += float(powered[np.arange(col.size), col].sum())
return total ** (1.0 / p)
# ---- drawings -----------------------------------------------------------------------------------
def _frame(self, diagram) -> tuple[np.ndarray, float, float, float]:
"""The cleaned diagram, the axis range (lo, hi), and the value at which infinite deaths are drawn."""
d = self.clean(diagram)
finite = d[np.isfinite(d)]
lo = float(finite.min()) if finite.size else 0.0
hi = float(finite.max()) if finite.size else 1.0
if hi <= lo:
hi = lo + 1.0
top = hi + 0.1 * (hi - lo) if np.any(np.isinf(d)) else hi
return d, lo, top, top
def diagram_svg(self, diagram) -> str:
"""Scatter plot of the diagram as an SVG string: birth on x, death on y, the diagonal as a line.
Infinite deaths are drawn as squares on the top edge."""
d, lo, hi, cap = self._frame(diagram)
size, pad = self.config.svg_size, 20
scale = (size - 2 * pad) / (hi - lo)
def px(x: float) -> float:
return pad + (x - lo) * scale
def py(y: float) -> float:
return size - pad - (y - lo) * scale
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" viewBox="0 0 {size} {size}">',
f'<rect x="{pad}" y="{pad}" width="{size - 2 * pad}" height="{size - 2 * pad}" fill="none" stroke="#888"/>',
f'<line x1="{px(lo):.1f}" y1="{py(lo):.1f}" x2="{px(hi):.1f}" y2="{py(hi):.1f}" stroke="#888"/>']
for birth, death in d:
if math.isinf(death):
parts.append(f'<rect x="{px(birth) - 3:.1f}" y="{py(cap) - 3:.1f}" width="6" height="6" fill="#c0392b"/>')
else:
parts.append(f'<circle cx="{px(birth):.1f}" cy="{py(death):.1f}" r="3" fill="#2c6fbb"/>')
return "\n".join(parts + ["</svg>"])
def barcode_svg(self, diagram) -> str:
"""The barcode as an SVG string: one horizontal bar per pair, longest on top. Infinite bars run
to the right edge."""
_, lo, hi, cap = self._frame(diagram)
bars = self.barcode(diagram)
size, pad = self.config.svg_size, 20
scale = (size - 2 * pad) / (hi - lo)
step = (size - 2 * pad) / max(len(bars), 1)
parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{size}" height="{size}" viewBox="0 0 {size} {size}">']
for k, (birth, death) in enumerate(bars):
y = pad + (k + 0.5) * step
end = cap if math.isinf(death) else death
colour = "#c0392b" if math.isinf(death) else "#2c6fbb"
parts.append(f'<line x1="{pad + (birth - lo) * scale:.1f}" y1="{y:.1f}" x2="{pad + (end - lo) * scale:.1f}" '
f'y2="{y:.1f}" stroke="{colour}" stroke-width="{max(1.0, min(6.0, step * 0.6)):.1f}"/>')
return "\n".join(parts + ["</svg>"])- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
With PersistenceDiagram() call from_signal([2, 0, 3, 1, 4]) and explain each row of the result from the water-level picture. Then check the worked example with bottleneck_distance and wasserstein_distance, compute persistent_entropy of , and save diagram_svg and barcode_svg to files to view them.
Check on learning
- For the signal the diagram is and . Why does the pool that starts at height 1 end at height 3 and not at 4, and why does the pool at 0 never end?
A way to think about it
Raise the water level step by step. The two pools meet at the peak between them, and when they merge the one with the higher minimum is the one that ends.
- Add small noise to a smooth signal. What kind of new points appear in the diagram, where do they sit, and what does the stability theorem say about the points that were already there?
A way to think about it
Noise creates many shallow dips. Estimate their lifetime from the size of the noise, and recall that the bound limits how far any point can move.
- Two diagrams differ only in that one has 50 extra points very close to the diagonal. Which distance, bottleneck or Wasserstein, reacts more, and when would each behaviour be the one you want?
A way to think about it
One distance takes a maximum over the moves and the other a sum. Fifty tiny costs change a sum but not a maximum.
- Why is matching a point to the diagonal priced at half its persistence and not at its full persistence?
A way to think about it
Find the closest point of the diagonal to and measure the distance with the larger-coordinate-gap rule.