Sign in

Mapper

Mapper algorithm

An algorithm that turns a point cloud into a small graph by slicing it along a chosen function, clustering each slice, and linking clusters that share points.

Overview

Mapper draws a simplified skeleton of a data set. Choose a function that gives every point one number, called the filter or lens, such as a coordinate or the distance from the centre. Cut the range of that number into overlapping intervals and gather the points whose value falls in each one. Inside each slice, group nearby points into clusters. Every cluster becomes a node of a graph. Because the intervals overlap, a point can sit in two clusters from neighbouring slices, and whenever that happens the two nodes are joined by an edge. The result shows branches, loops and separate pieces of the data at a glance. A circle of points sliced by height becomes a ring of nodes.

A short history

Gurjeet Singh, Facundo Mémoli and Gunnar Carlsson introduced Mapper in 2007 at Stanford as a practical tool of topological data analysis. It is a discrete version of the Reeb graph from Morse theory: the data are covered by overlapping slices of a filter function, each slice is clustered, and overlapping clusters are joined. The result is a small graph whose branches and loops show structure that a scatter plot of two components can hide.

How it works

  1. Compute the filter value of every point: the configured coordinate, norm or eccentricity, or values you pass in yourself.
  2. Cover the range of the filter with n_intervals intervals of equal length, each sharing the fraction overlap with the next.
  3. For each interval, collect the points whose filter value lies inside it.
  4. Cluster those points by single linkage: two points share a cluster when a chain of steps no longer than cluster_distance connects them.
  5. Make one node per cluster, dropping clusters smaller than min_cluster_size.
  6. Join two nodes from different intervals with an edge when their clusters have at least one point in common.
  7. Read the graph: count connected components and independent loops, and colour nodes by their mean filter value.

Watch out for

  • The graph depends strongly on the filter. A loop is seen only if the filter varies around it, so a poor filter can hide the structure you are looking for.
  • Too few intervals or too much overlap merges everything into a line or a blob, and too many intervals with little overlap shatters the graph into fragments.
  • A cluster_distance set too small makes every point its own node, and one set too large can bridge across a gap and erase a loop.
  • The output is a picture for exploration, not a test. Features should persist over a range of settings before you trust them.
  • The template clusters with a full distance matrix per slice and one fixed threshold, which is a small version of Mapper suited to a few thousand points.

Use cases

When to use it

Exploring the overall shape of a data set, looking for branches, loops or distinct subgroups that a scatter plot of two principal components would flatten or hide.

In industry

Cancer research
Nicolau, Levine and Carlsson applied Mapper to breast tumour gene expression in 2011 and reported a subgroup of patients with very good survival that standard clustering had not separated.
Sports analytics
A widely cited analysis used Mapper on basketball player statistics to suggest more playing styles than the five traditional positions.
Customer and risk analytics
Analysts build Mapper graphs of customer or transaction features to find small, distinct segments that branch off from the main population.

Choosing it: what must hold

  • A point cloud with a meaningful distance between points.
  • A filter function that suits the question, such as a density estimate, an eccentricity measure or a principal component.
  • Willingness to try several settings of the cover, overlap and clustering, since the graph depends on them.
  • An exploratory goal; the output is a picture to interpret and follow up, not a test.

When to choose something else

IfUse instead
You need a quantitative, parameter light summary of loops and voidsPersistent homology
You only want a two dimensional view of the datat-SNE or UMAP from multivariate analysis
You only need a partition into groupsA clustering method such as k-means or DBSCAN

Math foundations

  1. The filter function

    f:X→Rf : X \to \mathbb{R}

    A function that gives each data point one number. The template offers a single coordinate, the distance from the centroid (norm), and the mean distance to all other points (eccentricity).

  2. The cover

    ℓ=fmax⁡−fmin⁡k−(k−1) g,Ii=[ fmin⁡+i ℓ (1−g),  fmin⁡+i ℓ (1−g)+ℓ ],i=0,…,k−1\ell = \frac{f_{\max}-f_{\min}}{k-(k-1)\,g}, \qquad I_i = \big[\,f_{\min}+i\,\ell\,(1-g),\ \ f_{\min}+i\,\ell\,(1-g)+\ell\,\big], \quad i = 0,\dots,k-1

    kk intervals of equal length ℓ\ell, each starting a step ℓ(1−g)\ell(1-g) after the previous one, so neighbours share a length g ℓg\,\ell. The length is chosen so that the last interval ends exactly at fmax⁡f_{\max}.

  3. Slices and nodes

    Xi=f−1(Ii)={x∈X:f(x)∈Ii},Xi=Ci,1∪Ci,2∪⋯X_i = f^{-1}(I_i) = \{x \in X : f(x) \in I_i\}, \qquad X_i = C_{i,1}\cup C_{i,2}\cup\cdots

    Each slice XiX_i is the set of points whose filter value lies in interval IiI_i. Clustering splits it into pieces Ci,aC_{i,a}, and each piece is one node of the graph.

  4. Edges

    {Ci,a, Cj,b}∈E  ⟺  Ci,a∩Cj,b≠∅\{C_{i,a},\ C_{j,b}\} \in E \iff C_{i,a}\cap C_{j,b} \ne \varnothing

    Two nodes are linked when they share at least one data point. This construction is called the nerve of the cover: it records which pieces overlap and forgets everything else.

  5. Loops in the graph

    β1=∣E∣−∣V∣+β0\beta_1 = \lvert E\rvert - \lvert V\rvert + \beta_0

    The number of independent cycles of a graph with ∣V∣\lvert V\rvert nodes, ∣E∣\lvert E\rvert edges and β0\beta_0 connected components. The template's n_loops uses exactly this.

Symbols

XX
the point cloud
ff
the filter function
fmin⁡, fmax⁡f_{\min},\ f_{\max}
smallest and largest filter value
kk
number of intervals, n_intervals in the template
gg
overlap fraction between neighbouring intervals
ℓ\ell
length of each interval
IiI_i
interval i of the cover
XiX_i
the points whose filter value lies in interval i
Ci,aC_{i,a}
cluster a found in slice i, one node of the graph
V, EV,\ E
the sets of nodes and edges
β0, β1\beta_0,\ \beta_1
number of connected components and of independent loops of the graph

Worked by hand

Filter values run from 0 to 10. Cover them with k=3k = 3 intervals and overlap g=0.5g = 0.5. Then suppose the resulting graph has 6 nodes, 6 edges and 1 component.

ℓ=10−03−(3−1)×0.5=102=5\ell = \frac{10-0}{3-(3-1)\times 0.5} = \frac{10}{2} = 5
step=ℓ (1−g)=5×0.5=2.5\text{step} = \ell\,(1-g) = 5 \times 0.5 = 2.5
I0=[0, 5],I1=[2.5, 7.5],I2=[5, 10]I_0 = [0,\ 5], \qquad I_1 = [2.5,\ 7.5], \qquad I_2 = [5,\ 10]
β1=6−6+1=1\beta_1 = 6 - 6 + 1 = 1

Three intervals of length 5 that each share half their length with the next. A graph with 6 nodes, 6 edges and one component has exactly one loop.

Visual example

Loading the example.

Try this

  • Click the four steps in order, then click nodes of the graph to see which points each one holds.
  • Change the filter to distance from the centre and watch the ring's loop disappear from the graph.
  • Lower the overlap to 0.05: neighbouring slices stop sharing points and the graph falls apart.

Code sample

import numpy as np
from impl import Mapper
from config import MapperConfig

angles = np.linspace(0, 2 * np.pi, 200, endpoint=False)
points = np.column_stack([np.cos(angles), np.sin(angles)])          # a circle
graph = Mapper(MapperConfig(n_intervals=6, overlap=0.3, cluster_distance=0.3)).fit(points)
print(len(graph["nodes"]), graph["edges"])
print(Mapper.n_components(graph), Mapper.n_loops(graph))            # 1 component, 1 loop
Read the implementation (133 lines)
"""Mapper: a graph summary of the shape of a point cloud.

NumPy and the standard library only. Clustering is single linkage cut at a fixed distance, computed from the
full distance matrix of each slice, so the template suits clouds of up to a few thousand points.
"""
from __future__ import annotations

import numpy as np

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


def _pairwise(points: np.ndarray) -> np.ndarray:
    """Euclidean distance matrix (m, m) of points (m, d)."""
    sq = np.sum(points * points, axis=1)
    return np.sqrt(np.maximum(sq[:, None] + sq[None, :] - 2.0 * points @ points.T, 0.0))


class Mapper:
    """Builds the Mapper graph: nodes are clusters of slices of the data, edges join clusters that share points."""

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

    def filter_values(self, points: np.ndarray) -> np.ndarray:
        """The configured filter function evaluated at every point. points: (n, d), returns (n,)."""
        kind = self.config.filter
        if kind == "coordinate":
            if self.config.coordinate >= points.shape[1]:
                raise ValueError(f"coordinate {self.config.coordinate} is out of range for {points.shape[1]} columns")
            return points[:, self.config.coordinate].copy()
        if kind == "norm":
            return np.linalg.norm(points - points.mean(axis=0), axis=1)
        return _pairwise(points).sum(axis=1) / max(points.shape[0] - 1, 1)

    def cover(self, low: float, high: float) -> np.ndarray:
        """The overlapping intervals covering [low, high], shape (n_intervals, 2).

        All intervals have the same length, and each shares the fraction `overlap` of it with the next.
        """
        k, g = self.config.n_intervals, self.config.overlap
        span = high - low
        length = span / (k - (k - 1) * g) if span > 0 else 1.0
        starts = low + np.arange(k) * length * (1.0 - g)
        intervals = np.column_stack([starts, starts + length])
        intervals[-1, 1] = max(intervals[-1, 1], high)  # guard the top end against rounding
        return intervals

    def cluster(self, points: np.ndarray) -> np.ndarray:
        """Single-linkage clusters at the configured distance. points: (m, d). Returns labels (m,), 0-based.

        Two points share a cluster when a chain of points links them with every step at most
        `cluster_distance`: the connected components of the neighbourhood graph.
        """
        m = points.shape[0]
        near = _pairwise(points) <= self.config.cluster_distance
        labels = np.full(m, -1)
        current = 0
        for seed in range(m):
            if labels[seed] >= 0:
                continue
            labels[seed] = current
            frontier = [seed]
            while frontier:
                reached = np.flatnonzero(near[frontier].any(axis=0) & (labels < 0))
                labels[reached] = current
                frontier = reached.tolist()
            current += 1
        return labels

    def fit(self, points, filter_values=None) -> dict:
        """Build the Mapper graph.

        points:        the data, shape (n, d).
        filter_values: your own filter function evaluated at the points, shape (n,). When None, the
                       configured filter is used.
        Returns a dict with
          `nodes`:     list of dicts {`interval`: index of the slice, `members`: sorted point indices,
                       `filter_mean`: mean filter value of the members},
          `edges`:     sorted list of (i, j), i < j, for nodes that share at least one point,
          `intervals`: the cover, shape (n_intervals, 2),
          `filter`:    the filter values, shape (n,).
        """
        points = np.asarray(points, dtype=float)
        if points.ndim != 2 or points.shape[0] == 0:
            raise ValueError(f"points must have shape (n, d) with n > 0, got {points.shape}")
        if filter_values is None:
            f = self.filter_values(points)
        else:
            f = np.asarray(filter_values, dtype=float).ravel()
            if f.size != points.shape[0]:
                raise ValueError("filter_values must have one value per point")
        intervals = self.cover(float(f.min()), float(f.max()))
        nodes = []
        for k, (low, high) in enumerate(intervals):
            inside = np.flatnonzero((f >= low) & (f <= high))
            if inside.size == 0:
                continue
            labels = self.cluster(points[inside])
            for label in range(labels.max() + 1):
                members = inside[labels == label]
                if members.size >= self.config.min_cluster_size:
                    nodes.append({"interval": k, "members": members, "filter_mean": float(f[members].mean())})
        edges = []
        for i in range(len(nodes)):
            for j in range(i + 1, len(nodes)):
                if nodes[i]["interval"] != nodes[j]["interval"] and np.intersect1d(
                        nodes[i]["members"], nodes[j]["members"], assume_unique=True).size:
                    edges.append((i, j))
        return {"nodes": nodes, "edges": edges, "intervals": intervals, "filter": f}

    @staticmethod
    def n_components(graph: dict) -> int:
        """Number of connected components of the Mapper graph."""
        parent = list(range(len(graph["nodes"])))

        def find(i: int) -> int:
            while parent[i] != i:
                parent[i] = parent[parent[i]]
                i = parent[i]
            return i

        for i, j in graph["edges"]:
            parent[find(i)] = find(j)
        return len({find(i) for i in range(len(parent))})

    @staticmethod
    def n_loops(graph: dict) -> int:
        """Number of independent cycles of the graph: edges - nodes + components."""
        return len(graph["edges"]) - len(graph["nodes"]) + Mapper.n_components(graph)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Sample 400 points on a unit circle with a little noise. Build Mapper(MapperConfig(n_intervals=6, overlap=0.5, cluster_distance=0.4)), call fit(points) and check that Mapper.n_components(graph) is 1 and Mapper.n_loops(graph) is 1. Then change overlap to 0 and, separately, cluster_distance to 3, and explain what each does to the graph.

Check on learning

  1. For points on a circle with the coordinate filter, the middle slices each give two nodes but the top and bottom slices give one. Why, and how does that produce a loop in the graph?
    A way to think about it

    Picture a horizontal band cutting the circle. Near the middle it catches two separate arcs, near the top a single cap.

  2. With overlap set to 0 the graph has no edges. Why does the algorithm need overlap at all?
    A way to think about it

    An edge needs a point that belongs to two nodes from different slices. Ask where such a point could live.

  3. For the same circle, what graph would the norm filter, distance from the centroid, produce? What does that teach about choosing a filter?
    A way to think about it

    Every point on a circle is about the same distance from the centre, so think about how many slices actually contain points.

  4. You see a loop in the Mapper graph of real data. Name two checks that would raise your confidence that it is a feature of the data and not of the settings.
    A way to think about it

    Vary n_intervals, overlap and cluster_distance and see whether the loop survives. Also try a different filter or a random subsample of the points.