Algorithm Search⌘K

Algorithmcore

Shared nearest neighbor graph clustering

Also called SNN clustering, PhenoGraph.

Build a k-nearest-neighbor graph of cells in PCA space, weight edges by shared neighbors, and cut it into clusters by modularity.

Time
O(n^2 d + n k^2 + P E log k) worst
Space
O(n k) extra
Where
E = the number of edges; P = the number of moving passes; d = the number of principal components; k = the number of neighbors; n = the number of cells
Properties
deterministicnot exactofflineiterative
Origin
Jacob H. Levine, Dana Pe'er, Garry P. Nolan, 2015

Shared nearest neighbor (SNN) graph clustering is the standard way to find groups of cells, such as cell types, in single-cell RNA-seq data. It takes the cells as points in a space of a few tens of principal components, joins each cell to its kk nearest neighbors, gives each edge a weight equal to the share of neighbors that its two ends have in common, and splits the graph into communities of high modularity with the Louvain method. PhenoGraph (Levine et al. 2015) put these steps together, and Seurat and Scanpy use the same plan. The weights make edges inside a dense group strong and edges between groups weak, so the cut follows the gaps between cell types.

In plain words

Each cell lists the cells most like it. Two cells are strongly linked when their lists share many names, and weakly linked when they are close but have different lists, which happens at the border between two groups. Then the cells are put into groups so that strong links stay inside groups: start with every cell alone, move each cell to the group of its neighbors that gains the most, then treat each group as one cell and repeat. The method stops when no move helps. The number of groups is not given in advance. It comes from the graph, and it changes with the number of neighbors and with a resolution setting.

The problem

Input. A matrix of nn cells by gg features, usually log-normalized counts of the highly variable genes, a number of neighbors kk, a number of principal components dd and a resolution γ≥0\gamma \ge 0.

Output. A label for each cell.

Goal. Labels that match the cell types. This is not a well-defined objective. The method maximizes the modularity of the SNN graph as a stand-in, and finds a local maximum.

The algorithm

  1. SNN-CLUSTER(X, k, d, γ)
  2. 1P ← the first d principal component scores of the rows of X
  3. 2N(i) ← the k nearest cells of i in P, for each cell i; N⁺(i) ← N(i) ∪ {i}
  4. 3E ← all pairs {i, j} with j ∈ N(i) or i ∈ N(j)
  5. 4w_ij ← |N⁺(i) ∩ N⁺(j)| / |N⁺(i) ∪ N⁺(j)| for each {i, j} ∈ E
  6. 5put each vertex of the graph G in its own community
  7. 6for each vertex i, in order: take i out of its community
  8. 7put i in the neighboring community C with the largest gain k_{i,C} - γ k_i Σ_C / 2m, or back if none is larger
  9. 8repeat L6 and L7 until a full pass moves no vertex
  10. 9G ← the graph with one vertex per community; the weight of (C, D) is the sum of the weights from C to D
  11. 10if L5 to L8 moved some vertex then go to L5 with the new G
  12. 11return the community of each cell

Lines L1 to L4 build the graph. The neighbor search of line L2 is brute force here; real tools use an approximate index. Line L2 gives the directed nearest neighbor graph, and line L3 makes it undirected, which gives the k-nearest-neighbor graph. The SNN graph has the same edges as that graph and differs only in the weights of line L4. Line L4 is the Jaccard similarity of the two neighbor sets, each with the cell itself. Lines L5 to L10 are the Louvain method. In line L7, ki,Ck_{i,C} is the weight of the edges from ii to CC, kik_i the weighted degree of ii, ΣC\Sigma_C the sum of the degrees in CC, and 2m2m the sum of all degrees. The gain is mm times the change of modularity, so each move raises the modularity. Line L9 shrinks each community to one vertex with a self-loop for the weight inside it, and the moving starts again on the smaller graph.

Example

Nine cells in two dimensions, with k=3k = 3: a square of four cells at (0,0),(1,0),(0,1),(1,1)(0, 0), (1, 0), (0, 1), (1, 1), a second square at (4,0),(5,0),(4,1),(5,1)(4, 0), (5, 0), (4, 1), (5, 1), and cell 4 at (2.6,0.5)(2.6, 0.5) between them. The cells are numbered 0 to 8 in this order.

The neighbors of cell 4 are cells 5 and 7, at distance 1.49, and cell 1, at 1.68 (it ties with cell 3 and wins by index). Cell 1 has its own square as neighbors, so the edge from cell 4 to cell 1 has N+(4)={1,4,5,7}N^+(4) = \{1, 4, 5, 7\} and N+(1)={0,1,2,3}N^+(1) = \{0, 1, 2, 3\}, which share only cell 1: the weight is 1/71/7. The edges from cell 4 to cells 5 and 7 share cells 5 and 7 out of six, so they weigh 1/31/3. Every edge inside a square weighs 1.

edge shared union weight
inside a square 4 4 1
4 to 5, 4 to 7 2 6 1/3
4 to 1 1 7 1/7

In the plain kk-nearest-neighbor graph, cell 4 has one edge to the left and two to the right, all of the same weight. With the SNN weights the left edge is much weaker. The first pass of the moving phase ends with communities {0,1,2,3}\{0, 1, 2, 3\} and {4,5,6,7,8}\{4, 5, 6, 7, 8\}, with modularity 0.48750.4875; with cell 4 on the left it would be lower. The second level moves nothing, and an exhaustive search over all partitions of the nine cells finds no better one.

Correctness

Correct here means that each step computes what it claims; whether communities are cell types is measured, not proved. The proof shows that every edge of the kk-nearest-neighbor graph gets a weight between 1/(2k+1)1/(2k+1) and 1, that the gain of line L7 is the change of modularity, and that line L9 keeps the modularity of every partition. So each move raises the modularity, and the method stops. At the end no single move of a vertex of the last graph raises it, and no community spans two connected components. Maximizing modularity is NP-hard (Brandes et al. 2008), so this is a local optimum. Traag, Waltman and van Eck (2019) show that the Louvain method can even return a community that is not connected inside.

Proof: The shared neighbor weights are bounded, and the Louvain phase raises the modularity at every move and stopsfull

The clustering has no ground truth to be correct against: whether the communities of the graph are the cell types is a modelling question, which the tests measure on simulated data. What can be proved is what the steps compute. We show that every edge of the k-nearest-neighbor graph gets a Jaccard weight between 1/(2k+1)1/(2k+1) and 1 (Lemma 1), that the gain of the moving phase is the change of modularity (Lemma 2), that aggregation keeps the modularity (Lemma 3), and that the method stops with a partition whose modularity grew at each level, which no single move of a vertex of the last level can improve, and which never joins two connected components (Theorem 4). Maximizing modularity is NP-hard (Brandes et al. 2008), so the method is a heuristic and the proof gives no bound on the gap to the optimum.

Setting. Points p1,…,pnp_1, \dots, p_n, the rows after line L1. Line L2 sets N(i)N(i), the kk nearest other points of ii, with ties broken by index, and N+(i)=N(i)∪{i}N^+(i) = N(i) \cup \{i\}. Line L3 takes the edges {i,j}\{i, j\} with j∈N(i)j \in N(i) or i∈N(j)i \in N(j), and line L4 gives the weight wij=∣N+(i)∩N+(j)∣/∣N+(i)∪N+(j)∣w_{ij} = |N^+(i) \cap N^+(j)| / |N^+(i) \cup N^+(j)|. For a symmetric weight matrix AA with Aij≥0A_{ij} \ge 0, let ki=∑jAijk_i = \sum_j A_{ij} and 2m=∑i,jAij2m = \sum_{i,j} A_{ij}, with sums over ordered pairs. The modularity of a labeling cc at resolution γ≥0\gamma \ge 0 is

Q(c)=12m∑i,j(Aij−γkikj2m)[ci=cj].Q(c) = \frac{1}{2m}\sum_{i,j}\Big(A_{ij} - \gamma\frac{k_ik_j}{2m}\Big)[c_i = c_j].

For the graph of line L4, which has no self-loops, this is the usual ∑C(LC/m−γ(dC/2m)2)\sum_C \big(L_C/m - \gamma(d_C/2m)^2\big), with LCL_C the weight of the edges inside CC and dCd_C the sum of the degrees in CC.

Lemma 1 (weights). Every edge of line L3 has 1/(2k+1)≤wij≤11/(2k+1) \le w_{ij} \le 1.

Proof. Let j∈N(i)j \in N(i). Then j∈N+(i)j \in N^+(i) and j∈N+(j)j \in N^+(j), so the intersection is not empty. Both sets have k+1k+1 elements, so the union has at most 2(k+1)−1=2k+12(k+1) - 1 = 2k + 1 elements. A ratio of a subset size to a superset size is at most 1. □\square

So the weight of an edge is high when the two cells share most of their neighbors and low for an edge that crosses between two dense groups, where each end has its neighbors on its own side. With N(i)N(i) in place of N+(i)N^+(i), as in PhenoGraph, an edge can get the weight 0.

Lemma 2 (the gain of line L7). Let vertex ii be alone in its community, let CC be a community not holding ii, let ki,C=∑j∈CAijk_{i,C} = \sum_{j \in C}A_{ij}, and let ΣC=∑j∈Ckj\Sigma_C = \sum_{j \in C}k_j. Moving ii into CC changes QQ by

ΔQ=1m(ki,C−γkiΣC2m).\Delta Q = \frac{1}{m}\Big(k_{i,C} - \gamma\frac{k_i\Sigma_C}{2m}\Big).

Proof. The move adds to the sum the ordered pairs (i,j)(i, j) and (j,i)(j, i) for j∈Cj \in C. Each pair adds Aij−γkikj/2mA_{ij} - \gamma k_ik_j/2m, so the sum grows by 2ki,C−2γkiΣC/2m2k_{i,C} - 2\gamma k_i\Sigma_C/2m. Divide by 2m2m. The pair (i,i)(i, i) is in one community before and after, so it does not change. □\square

Line L6 removes ii from its community c0c_0, which makes ii alone, and then line L7 compares the gains g(C)=ki,C−γkiΣC/2mg(C) = k_{i,C} - \gamma k_i\Sigma_C/2m of the neighboring communities and of c0c_0 itself. The factor 1/m1/m is the same for all, so the largest gain is the largest ΔQ\Delta Q. The code moves ii only when another community beats c0c_0 by more than ε=10−12\varepsilon = 10^{-12}, so each move raises QQ by more than ε/m\varepsilon/m.

Lemma 3 (aggregation). Let cc label the vertices with communities 0,…,r−10, \dots, r-1, and let line L9 form BCD=∑ci=C, cj=DAijB_{CD} = \sum_{c_i = C,\, c_j = D}A_{ij}. Then BB has the same total 2m2m, the degree of CC in BB is ∑ci=Cki\sum_{c_i = C}k_i, and for every labeling dd of the communities, QB(d)=QA(d∘c)Q_B(d) = Q_A(d \circ c).

Proof. Each ordered pair (i,j)(i, j) adds AijA_{ij} to exactly one entry BcicjB_{c_ic_j}, which gives the total and the degrees. In QA(d∘c)Q_A(d \circ c), group the pairs (i,j)(i, j) by (ci,cj)=(C,D)(c_i, c_j) = (C, D). The condition dci=dcjd_{c_i} = d_{c_j} depends only on (C,D)(C, D), the sum of AijA_{ij} over the group is BCDB_{CD}, and the sum of kikjk_ik_j is KCKDK_CK_D with KCK_C the degree of CC. This is QB(d)Q_B(d) term by term. □\square

This is why the code stores the self-loop weight of CC as the sum over ordered pairs inside CC: then the formula of QQ needs no special case for self-loops.

Theorem 4 (Louvain). The method of lines L5 to L11 stops. The modularity of the input labeling after each level is strictly larger than after the level before, starting from the labeling with one vertex per community. At the end, no move of one vertex of the last graph from its community to a neighboring community raises QQ by more than ε/m\varepsilon/m. Two vertices in different connected components are never in one community, and with γ=0\gamma = 0 the communities are exactly the connected components, leaving out isolated vertices.

Proof. By Lemma 2 each move raises QQ of the current graph by more than ε/m\varepsilon/m, and by Lemma 3 this is the QQ of the input labeling. QQ is at most 1, so there are finitely many moves, the loop of line L8 stops, and each level with a move raises QQ. The number of vertices does not grow and falls at each level with a move, because a move empties a community or joins two, so the levels stop too. The last level ends in line L10 when a full pass makes no move. In that pass every vertex starts alone (each vertex of the last graph is its own community), and no community beat staying by more than ε\varepsilon, so no single move raises QQ by more than ε/m\varepsilon/m. A vertex only joins communities with ki,C>0k_{i,C} > 0, that is, with an edge to it. By induction every community, and every vertex of every aggregated graph, lies in one connected component, so no community crosses two components. With γ=0\gamma = 0 the gain of a neighboring community is ki,C>0k_{i,C} > 0 and the gain of staying alone is 0. So if, at the last level, two vertices of one component were in different communities, some edge would join two of them, and the pass would move one of its ends. So at the end each component with an edge is one community. □\square

Theorem 4 says nothing about the vertices of the input graph. A merge at a later level can make an input vertex better off in another community, and Traag, Waltman and van Eck (2019) show that the Louvain method can even return a community that is not connected inside. The Leiden algorithm adds a refinement step that rules this out.

What the lines compute. Line L1 is optional principal component analysis. Line L2 is the brute force neighbor search of the shared module, with ties by index. Lines L3 and L4 are Lemma 1. Lines L5 to L8 are the moving phase with the gain of Lemma 2, visiting vertices in index order and taking the community with the smaller label on ties. Line L9 is Lemma 3, line L10 the stop test of Theorem 4, and line L11 returns the labels of the input vertices.

Complexity. The neighbor search takes O(n2d)O(n^2d) time for dd coordinates, and lines L3 and L4 take O(nk2)O(nk^2) expected time with hash sets, for at most nknk edges. One pass of line L6 over all vertices takes O(∣E∣log⁡kmax)O(|E|\log k_{max}) time, with ∣E∣≤nk|E| \le nk, because the communities next to a vertex are sorted. The number of passes and levels is finite by Theorem 4, but the proof gives no useful bound on it; the tests count them on small graphs.

What the tests check. The test file checks the page example, the bounds of Lemma 1 for k=1,3,6k = 1, 3, 6, the modularity formula against the edge form, Lemma 3 on random graphs, that the moving phase ends where no single move raises QQ, and that the levels raise QQ strictly. It compares the method with an exhaustive search over all partitions of graphs with at most 8 vertices: the result is never above the optimum, and it reaches it on at least 80 percent of the random graphs, which is a measurement. It checks that components are never merged and that γ=0\gamma = 0 gives the components. A simulation with three groups of cells measures that k=15k = 15 finds the groups and that k=10k = 10 splits one group but never mixes two.

Complexity

The neighbor search takes O(n2d)O(n^2d) time by brute force, and the weights take O(nk2)O(nk^2) expected time with hash sets, for at most nknk edges. One pass of the moving phase takes O(∣E∣log⁡k)O(|E|\log k) time, because the communities next to a vertex are sorted. The number of passes and levels has no useful proved bound; in the tests it is small. The graph needs O(nk)O(nk) space. For many cells the brute force neighbor search dominates, which is why real tools use approximate indexes.

Properties

  • The number of clusters is an output. It usually grows with γ\gamma and falls as kk grows. This is an observation, not a theorem.
  • Deterministic in this version. The vertices are visited in index order and ties go to the smaller label. Most tools visit them in a random order, so the labels change with the seed.
  • Local optimum. No single vertex move at the last level improves the modularity.
  • Never joins disconnected parts. A cell only joins a community it has an edge to.
  • Not stable under adding cells. One new cell can change the neighbor sets of others and move a border.

Variants and improvements

  • Leiden instead of Louvain. The Leiden algorithm refines each community before aggregation, which guarantees connected communities. Seurat and Scanpy both offer it.
  • Without the cell itself. PhenoGraph computes the Jaccard index of N(i)N(i) and N(j)N(j) without the cells, so an edge can get weight 0. Seurat includes the cells and removes edges below a small weight.
  • Rank-based weights. SNN-Cliq (Xu and Su 2015) and scran give weights from the ranks of the shared neighbors instead of their count.
  • Other partitions. Any community detection method can cut the graph, for example Walktrap or Infomap.
  • Plain kk-means on the principal components. K-means needs the number of clusters and prefers round groups of similar size; the graph method needs neither.

When to use it

Use it to find cell types and states in thousands to millions of cells after normalization, gene selection and principal component analysis. Tune kk and γ\gamma to the level of detail you want, and check clusters with marker genes. Draw the clusters on a UMAP or t-SNE map, but do not cluster on those maps: they are for display, and their distances between groups have no fixed meaning.

Pitfalls

  • Clusters at any resolution. Modularity finds communities even in data without structure. A cluster is a hypothesis to test, not a cell type.
  • Small kk splits groups. In the tests, three groups of 40 cells came back exactly with k=15k = 15, but with k=10k = 10 one group split in two. The split groups were pure, so the error is too many clusters, not mixed ones.
  • Doublets and low quality cells form their own small clusters. Remove them first, for example with doublet detection.
  • Batch effects give clusters by batch. Correct them before building the graph.
  • Disconnected or badly connected communities from the Louvain method. Use Leiden, or check that each cluster is connected.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

rq3lin.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Group module of the single-cell pages of https://algorithm.tamnd.com/ (group rq3). The authors are listed in prov/.
"""Small dense linear algebra and neighbor search for the single-cell pages.

The reference copy is in biology/transcriptomics/doublet-detection/impl/python/.
The other rq3 pages hold identical copies. The module holds no algorithm of a
page: no doublet score, no clustering, no batch correction and no pseudotime.

Conventions:
- A vector is a list of floats and a matrix is a list of rows.
- Ties between equal distances are broken by the smaller index, so that every
  result is deterministic.
- Random draws use a random.Random object that the caller passes in.
"""

from __future__ import annotations

import math
import random
from typing import List, Optional, Sequence, Tuple

Vector = List[float]
Matrix = List[List[float]]


def dot(a: Sequence[float], b: Sequence[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


def sqdist(a: Sequence[float], b: Sequence[float]) -> float:
    return sum((x - y) * (x - y) for x, y in zip(a, b))


def transpose(A: Sequence[Sequence[float]]) -> Matrix:
    return [list(col) for col in zip(*A)]


def matmul(A: Sequence[Sequence[float]], B: Sequence[Sequence[float]]) -> Matrix:
    Bt = transpose(B)
    return [[dot(row, col) for col in Bt] for row in A]


def matvec(A: Sequence[Sequence[float]], x: Sequence[float]) -> Vector:
    return [dot(row, x) for row in A]


def identity(n: int) -> Matrix:
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def column_means(X: Sequence[Sequence[float]]) -> Vector:
    n = len(X)
    return [sum(col) / n for col in zip(*X)]


def knn(points: Sequence[Sequence[float]], k: int,
        queries: Optional[Sequence[Sequence[float]]] = None) -> List[List[int]]:
    """The k nearest points (Euclidean) of each query, by brute force.

    With queries=None the queries are the points themselves and each point is
    left out of its own list. Each list is sorted by (distance, index).
    """
    self_query = queries is None
    qs = points if self_query else queries
    limit = len(points) - (1 if self_query else 0)
    if not 0 <= k <= limit:
        raise ValueError("k must be between 0 and the number of candidate points")
    out = []
    for i, q in enumerate(qs):
        cand = [(sqdist(q, p), j) for j, p in enumerate(points) if not (self_query and j == i)]
        cand.sort()
        out.append([j for _, j in cand[:k]])
    return out


def solve(A: Sequence[Sequence[float]], b: Sequence[float]) -> Vector:
    """Solve A x = b by Gaussian elimination with partial pivoting.

    Raises ValueError when a pivot is zero, that is when A is singular in
    floating point.
    """
    n = len(A)
    M = [list(map(float, A[i])) + [float(b[i])] for i in range(n)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[p][c] == 0.0:
            raise ValueError("singular matrix")
        M[c], M[p] = M[p], M[c]
        piv = M[c][c]
        for r in range(c + 1, n):
            f = M[r][c] / piv
            if f != 0.0:
                row, top = M[r], M[c]
                for j in range(c, n + 1):
                    row[j] -= f * top[j]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        s = M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))
        x[i] = s / M[i][i]
    return x


def inverse(A: Sequence[Sequence[float]]) -> Matrix:
    """The inverse of A, one column at a time with solve."""
    n = len(A)
    cols = [solve(A, [1.0 if i == j else 0.0 for i in range(n)]) for j in range(n)]
    return transpose(cols)


def jacobi_eigh(S: Sequence[Sequence[float]], tol: float = 1e-12,
                max_sweeps: int = 100) -> Tuple[Vector, Matrix]:
    """All eigenvalues and eigenvectors of a symmetric matrix by the cyclic Jacobi method.

    Returns (values, vectors): values in decreasing order, and vectors[i] the
    unit eigenvector of values[i]. Each eigenvector is given the sign that
    makes its entry of largest absolute value positive.
    """
    n = len(S)
    A = [list(map(float, row)) for row in S]
    V = identity(n)
    for _ in range(max_sweeps):
        off = sum(A[i][j] * A[i][j] for i in range(n) for j in range(n) if i != j)
        scale = sum(A[i][i] * A[i][i] for i in range(n)) + off
        if off <= tol * tol * max(scale, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                apq = A[p][q]
                if apq == 0.0:
                    continue
                theta = (A[q][q] - A[p][p]) / (2.0 * apq)
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    akp, akq = A[k][p], A[k][q]
                    A[k][p] = c * akp - s * akq
                    A[k][q] = s * akp + c * akq
                for k in range(n):
                    apk, aqk = A[p][k], A[q][k]
                    A[p][k] = c * apk - s * aqk
                    A[q][k] = s * apk + c * aqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p] = c * vkp - s * vkq
                    V[k][q] = s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: -A[i][i])
    values = [A[i][i] for i in order]
    vectors = []
    for i in order:
        v = [V[k][i] for k in range(n)]
        big = max(range(n), key=lambda k: abs(v[k]))
        if v[big] < 0:
            v = [-x for x in v]
        vectors.append(v)
    return values, vectors


def pca_fit(X: Sequence[Sequence[float]], r: int) -> Tuple[Vector, Matrix, Vector]:
    """Principal axes of the rows of X: (means, axes, variances), r axes of unit length.

    The covariance uses the divisor n - 1. The axes come from jacobi_eigh, so they
    are deterministic up to the sign rule of that function.
    """
    n, d = len(X), len(X[0])
    if not 1 <= r <= d:
        raise ValueError("r must be between 1 and the number of columns")
    mu = column_means(X)
    C = [[0.0] * d for _ in range(d)]
    for row in X:
        z = [x - m for x, m in zip(row, mu)]
        for a in range(d):
            za = z[a]
            if za != 0.0:
                Ca = C[a]
                for b in range(a, d):
                    Ca[b] += za * z[b]
    for a in range(d):
        for b in range(a, d):
            C[a][b] /= max(n - 1, 1)
            C[b][a] = C[a][b]
    values, vectors = jacobi_eigh(C)
    return mu, vectors[:r], values[:r]


def pca_project(X: Sequence[Sequence[float]], mu: Sequence[float], axes: Sequence[Sequence[float]]) -> Matrix:
    """The coordinates of the rows of X on the axes, after subtracting mu."""
    return [[dot([x - m for x, m in zip(row, mu)], a) for a in axes] for row in X]


def poisson_knuth(rng: random.Random, lam: float) -> int:
    """A Poisson draw by multiplying uniforms (Knuth); for test data with lam up to about 50.

    Draw order: rng.random() until the product falls below exp(-lam).
    """
    if lam < 0:
        raise ValueError("lam must be non-negative")
    limit, k, p = math.exp(-lam), 0, 1.0
    while True:
        p *= rng.random()
        if p <= limit:
            return k
        k += 1
shared_nearest_neighbor_clustering.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shared-nearest-neighbor-clustering/. The authors are listed in prov/6JJNPV.jsonl.
"""Clustering of cells on a shared nearest neighbor graph with the Louvain method.

The steps are those of PhenoGraph (Levine et al. 2015) and of the Seurat
pipeline: the k nearest neighbors of each cell in PCA space, edge weights from
the overlap of the neighbor sets (the Jaccard index), and communities of
high modularity found by the Louvain method of Blondel et al. (2008).

Choices of this version:
- The neighbor set of cell i is i with its k nearest neighbors, as in Seurat.
  PhenoGraph leaves i out. With i in the set, every edge of the k-nearest-
  neighbor graph gets a positive weight.
- Neighbor search is brute force and the Louvain method visits the vertices in
  index order and breaks ties by the smaller community label, so the output
  is deterministic. Real tools use approximate neighbor search and a random
  vertex order.
- There is no pruning of small weights and no Leiden refinement.

A graph is a list of dicts: adj[i][j] is the weight of the pair (i, j), and
adj[i][j] == adj[j][i]. Sums run over ordered pairs, so a self-loop weight
adj[c][c] after aggregation is the total weight of the ordered pairs inside c.
"""

from __future__ import annotations

from typing import Dict, List, Optional, Sequence, Tuple

from rq3lin import knn, pca_fit, pca_project

Graph = List[Dict[int, float]]
EPS = 1e-12


def snn_graph(points: Sequence[Sequence[float]], k: int) -> Graph:
    """Shared nearest neighbor graph: Jaccard weights on the edges of the k-NN graph."""
    n = len(points)
    nbrs = knn(points, k)  # @line L2
    sets = [set(nbrs[i]) | {i} for i in range(n)]
    adj: Graph = [dict() for _ in range(n)]
    for i in range(n):
        for j in nbrs[i]:  # @line L3
            if j in adj[i]:
                continue
            w = len(sets[i] & sets[j]) / len(sets[i] | sets[j])  # @line L4
            adj[i][j] = w
            adj[j][i] = w
    return adj


def degrees(adj: Graph) -> List[float]:
    return [sum(row.values()) for row in adj]


def modularity(adj: Graph, labels: Sequence[int], resolution: float = 1.0) -> float:
    """Q = (1 / 2m) sum over ordered pairs (i, j) in one community of (A_ij - gamma k_i k_j / 2m)."""
    k = degrees(adj)
    two_m = sum(k)
    if two_m == 0:
        return 0.0
    inside = sum(w for i, row in enumerate(adj) for j, w in row.items() if labels[i] == labels[j])
    tot: Dict[int, float] = {}
    for i, c in enumerate(labels):
        tot[c] = tot.get(c, 0.0) + k[i]
    return inside / two_m - resolution * sum(t * t for t in tot.values()) / (two_m * two_m)


def local_moving(adj: Graph, resolution: float = 1.0) -> Tuple[List[int], int]:
    """Phase 1 of Louvain: move single vertices while the modularity grows.

    Returns (community of each vertex, number of moves).
    """
    n = len(adj)
    k = degrees(adj)
    two_m = sum(k)
    comm = list(range(n))  # @line L5
    tot = k[:]
    moves = 0
    changed = True
    while changed:  # @line L8
        changed = False
        for i in range(n):  # @line L6
            c0 = comm[i]
            links: Dict[int, float] = {}
            for j, w in adj[i].items():
                if j != i:
                    links[comm[j]] = links.get(comm[j], 0.0) + w
            tot[c0] -= k[i]
            best = c0
            best_gain = links.get(c0, 0.0) - resolution * k[i] * tot[c0] / two_m
            for c in sorted(links):
                gain = links[c] - resolution * k[i] * tot[c] / two_m  # @line L7
                if gain > best_gain + EPS:
                    best, best_gain = c, gain
            tot[best] += k[i]
            comm[i] = best
            if best != c0:
                moves += 1
                changed = True
    return comm, moves


def relabel(comm: Sequence[int]) -> List[int]:
    """Labels 0, 1, 2, ... in the order of first appearance."""
    seen: Dict[int, int] = {}
    return [seen.setdefault(c, len(seen)) for c in comm]


def aggregate(adj: Graph, comm: Sequence[int]) -> Graph:
    """One vertex per community; the weight of (C, D) is the sum of the weights of the ordered pairs from C to D."""
    r = max(comm) + 1
    out: Graph = [dict() for _ in range(r)]
    for i, row in enumerate(adj):
        for j, w in row.items():
            a, b = comm[i], comm[j]
            out[a][b] = out[a].get(b, 0.0) + w  # @line L9
    return out


def louvain(adj: Graph, resolution: float = 1.0) -> Tuple[List[int], List[List[int]]]:
    """Louvain method: local moving and aggregation until no vertex moves.

    Returns (labels of the input vertices, labels after each level).
    """
    labels = list(range(len(adj)))
    levels = []
    g = adj
    if sum(degrees(adj)) == 0:
        return labels, levels
    while True:
        comm, moves = local_moving(g, resolution)
        if moves == 0:  # @line L10
            break
        comm = relabel(comm)
        labels = [comm[c] for c in labels]
        levels.append(labels[:])
        g = aggregate(g, comm)
    return labels, levels  # @line L11


def snn_cluster(X: Sequence[Sequence[float]], k: int = 10, n_pcs: Optional[int] = None,
                resolution: float = 1.0) -> List[int]:
    """Cluster the rows of X (cells by features): optional PCA, SNN graph, Louvain."""
    pts = X
    if n_pcs is not None:
        mu, axes, _ = pca_fit(X, n_pcs)
        pts = pca_project(X, mu, axes)  # @line L1
    return louvain(snn_graph(pts, k), resolution)[0]
test_shared_nearest_neighbor_clustering.py 231 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shared-nearest-neighbor-clustering/. The authors are listed in prov/6JJNPV.jsonl.

import math
import random

import pytest

from rq3lin import knn
from shared_nearest_neighbor_clustering import (
    aggregate,
    local_moving,
    louvain,
    modularity,
    relabel,
    snn_cluster,
    snn_graph,
)

PAGE = [(0, 0), (1, 0), (0, 1), (1, 1), (2.6, 0.5), (4, 0), (5, 0), (4, 1), (5, 1)]


def partitions(n):
    """All set partitions of range(n) as restricted growth strings."""
    def rec(prefix, top):
        if len(prefix) == n:
            yield list(prefix)
            return
        for c in range(top + 2):
            prefix.append(c)
            yield from rec(prefix, max(top, c))
            prefix.pop()
    yield from rec([0], 0) if n else iter([[]])


def best_modularity(adj, resolution=1.0):
    return max(modularity(adj, p, resolution) for p in partitions(len(adj)))


def modularity_by_edges(adj, labels, resolution=1.0):
    """sum over communities of L_c / m - gamma (d_c / 2m)^2, from the unordered edge list."""
    m = sum(w for i, row in enumerate(adj) for j, w in row.items() if i < j)
    d, L = {}, {}
    for i, row in enumerate(adj):
        c = labels[i]
        d[c] = d.get(c, 0.0) + sum(row.values())
        for j, w in row.items():
            if i < j and labels[j] == c:
                L[c] = L.get(c, 0.0) + w
    return sum(L.get(c, 0.0) / m - resolution * (d[c] / (2 * m)) ** 2 for c in d)


def random_graph(rng, n, p):
    adj = [dict() for _ in range(n)]
    for i in range(n):
        for j in range(i + 1, n):
            if rng.random() < p:
                w = rng.choice([0.25, 0.5, 1.0])
                adj[i][j] = adj[j][i] = w
    return adj


def ari(a, b):
    n = len(a)
    pairs = {}
    for x, y in zip(a, b):
        pairs[(x, y)] = pairs.get((x, y), 0) + 1
    ca, cb = {}, {}
    for x in a:
        ca[x] = ca.get(x, 0) + 1
    for y in b:
        cb[y] = cb.get(y, 0) + 1

    def c2(v):
        return v * (v - 1) / 2

    s = sum(c2(v) for v in pairs.values())
    sa = sum(c2(v) for v in ca.values())
    sb = sum(c2(v) for v in cb.values())
    exp = sa * sb / c2(n)
    return (s - exp) / ((sa + sb) / 2 - exp)


def test_page_example():
    assert knn(PAGE, 3)[4] == [5, 7, 1]
    g = snn_graph(PAGE, 3)
    assert math.isclose(g[4][1], 1 / 7) and math.isclose(g[4][5], 1 / 3) and math.isclose(g[4][7], 1 / 3)
    assert g[0][1] == 1.0 and g[5][6] == 1.0
    labels, levels = louvain(g)
    assert labels == [0, 0, 0, 0, 1, 1, 1, 1, 1]
    assert len(levels) == 1
    q = modularity(g, labels)
    assert math.isclose(q, 0.4874932629455092, rel_tol=1e-12)
    # The other place for the bridge cell 4 is worse, and here Louvain finds the best partition.
    assert modularity(g, [0, 0, 0, 0, 0, 1, 1, 1, 1]) < q
    assert math.isclose(q, best_modularity(g), rel_tol=1e-12)


def test_jaccard_weight_bounds():
    rng = random.Random(1)
    pts = [(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(40)]
    for k in (1, 3, 6):
        g = snn_graph(pts, k)
        nb = knn(pts, k)
        for i, row in enumerate(g):
            for j, w in row.items():
                assert j in nb[i] or i in nb[j]
                assert 1 / (2 * k + 1) - 1e-15 <= w <= 1.0
            assert all(j in row for j in nb[i])


def test_modularity_matches_the_edge_formula():
    rng = random.Random(2)
    for _ in range(30):
        g = random_graph(rng, 8, 0.4)
        if not any(g):
            continue
        lab = [rng.randrange(3) for _ in range(8)]
        for gamma in (0.5, 1.0, 2.0):
            assert math.isclose(modularity(g, lab, gamma), modularity_by_edges(g, lab, gamma), abs_tol=1e-12)


def test_aggregation_keeps_modularity():
    rng = random.Random(3)
    for _ in range(30):
        g = random_graph(rng, 9, 0.35)
        if not any(g):
            continue
        comm = relabel([rng.randrange(4) for _ in range(9)])
        h = aggregate(g, comm)
        assert math.isclose(modularity(g, comm), modularity(h, list(range(len(h)))), abs_tol=1e-12)
        assert math.isclose(sum(map(lambda r: sum(r.values()), g)), sum(map(lambda r: sum(r.values()), h)))


def test_local_moving_ends_in_a_local_optimum():
    rng = random.Random(4)
    for _ in range(25):
        g = random_graph(rng, 8, 0.4)
        if not any(g):
            continue
        comm, _ = local_moving(g)
        q = modularity(g, comm)
        assert q >= modularity(g, list(range(8))) - 1e-12
        for i in range(8):
            for c in set(comm[j] for j in g[i]):
                trial = comm[:]
                trial[i] = c
                assert modularity(g, trial) <= q + 1e-9


def test_louvain_against_exhaustive_search():
    """Louvain is a heuristic: never above the optimum, and measured to reach it on most small graphs."""
    rng = random.Random(5)
    hits = total = 0
    for _ in range(30):
        n = rng.randint(4, 8)
        g = random_graph(rng, n, 0.45)
        if not any(g):
            continue
        labels, levels = louvain(g)
        q, best = modularity(g, labels), best_modularity(g)
        assert q <= best + 1e-12
        qs = [modularity(g, lv) for lv in levels]
        assert all(b > a for a, b in zip([modularity(g, list(range(n)))] + qs, qs))
        total += 1
        hits += math.isclose(q, best, abs_tol=1e-9)
    assert total >= 25 and hits >= 0.8 * total


def test_components_are_never_merged():
    a = snn_graph([(0, 0), (1, 0), (0, 1)], 2)
    g = [dict(r) for r in a] + [{4: 1.0}, {3: 1.0}]
    labels, _ = louvain(g)
    assert labels[0] == labels[1] == labels[2] != labels[3] == labels[4]


def test_resolution_zero_gives_the_connected_components():
    rng = random.Random(6)
    for _ in range(20):
        g = random_graph(rng, 9, 0.2)
        if not any(g):
            continue
        labels, _ = louvain(g, resolution=0.0)
        comp = list(range(9))

        def find(x):
            while comp[x] != x:
                x = comp[x]
            return x

        for i, row in enumerate(g):
            for j in row:
                comp[find(i)] = find(j)
        roots = [find(i) for i in range(9)]
        for i in range(9):
            for j in range(9):
                if g[i] and g[j]:
                    assert (labels[i] == labels[j]) == (roots[i] == roots[j])


def test_empty_graph_and_errors():
    assert louvain([dict(), dict()])[0] == [0, 1]
    with pytest.raises(ValueError):
        snn_graph([(0, 0), (1, 1)], 2)


def test_gaussian_clusters_measured():
    """A measurement: 3 groups of 40 cells in 20 dimensions, PCA to 5.

    With k = 15 the groups come back exactly. With k = 10 one group is split in
    two, but no cluster mixes two groups: a smaller k gives more clusters.
    """
    rng = random.Random(2015)
    centers = [[rng.gauss(0, 1.2) for _ in range(20)] for _ in range(3)]
    X, truth = [], []
    for c in range(3):
        for _ in range(40):
            X.append([m + rng.gauss(0, 1) for m in centers[c]])
            truth.append(c)
    assert ari(snn_cluster(X, k=15, n_pcs=5), truth) > 0.95
    labels = snn_cluster(X, k=10, n_pcs=5)
    assert len(set(labels)) > 3
    assert all(len({t for t, l in zip(truth, labels) if l == c}) == 1 for c in set(labels))
    # Edges between groups get smaller Jaccard weights than edges inside groups.
    from rq3lin import pca_fit, pca_project
    mu, axes, _ = pca_fit(X, 5)
    g = snn_graph(pca_project(X, mu, axes), 10)
    inside = [w for i, r in enumerate(g) for j, w in r.items() if truth[i] == truth[j]]
    across = [w for i, r in enumerate(g) for j, w in r.items() if truth[i] != truth[j]]
    if across:
        assert sum(across) / len(across) < 0.6 * sum(inside) / len(inside)

History

Jarvis and Patrick (1973) defined clusters by shared near neighbors: two points belong together when they share many of their nearest neighbors. Blondel and co-authors (2008) published the Louvain method for large networks. In 2015, SNN-Cliq (Xu and Su) used a shared neighbor graph to find cell types in single-cell RNA-seq, and PhenoGraph (Levine et al.) put Jaccard weights on a kk-nearest-neighbor graph of mass cytometry data and cut it with Louvain. Seurat adopted the plan for single-cell RNA-seq, and Traag, Waltman and van Eck (2019) replaced Louvain with Leiden to fix its badly connected communities.

References

  1. Jacob H. Levine et al., Data-driven phenotypic dissection of AML reveals progenitor-like cells that correlate with prognosis, Cell 162(1), 184 to 197 (2015), the description of PhenoGraph, with the k-nearest-neighbor graph, the Jaccard weights and the Louvain partition
  2. Vincent D. Blondel, Jean-Loup Guillaume, Renaud Lambiotte and Etienne Lefebvre, Fast unfolding of communities in large networks, Journal of Statistical Mechanics, Theory and Experiment 2008, P10008 (2008), Section 2, the local moving phase with the modularity gain and the aggregation phase
  3. R. A. Jarvis and E. A. Patrick, Clustering using a similarity measure based on shared near neighbors, IEEE Transactions on Computers C-22(11), 1025 to 1034 (1973), the shared near neighbor similarity
  4. Chen Xu and Zhengchang Su, Identification of cell types from single-cell transcriptomes using a novel clustering method, Bioinformatics 31(12), 1974 to 1980 (2015), the SNN graph of cells and the search for quasi-cliques in it
  5. V. A. Traag, L. Waltman and N. J. van Eck, From Louvain to Leiden, guaranteeing well-connected communities, Scientific Reports 9, 5233 (2019), the section on the Louvain algorithm, which shows that it can return badly connected communities
  6. Ulrik Brandes, Daniel Delling, Marco Gaertler, Robert Görke, Martin Hoefer, Zoran Nikoloski and Dorothea Wagner, On modularity clustering, IEEE Transactions on Knowledge and Data Engineering 20(2), 172 to 188 (2008), the NP-completeness of maximizing modularity

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example