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
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 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 cells by features, usually log-normalized counts of the highly variable genes, a number of neighbors , a number of principal components and a resolution .
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
SNN-CLUSTER(X, k, d, γ)- 1
P ← the first d principal component scores of the rows of X - 2
N(i) ← the k nearest cells of i in P, for each cell i; N⁺(i) ← N(i) ∪ {i} - 3
E ← all pairs {i, j} with j ∈ N(i) or i ∈ N(j) - 4
w_ij ← |N⁺(i) ∩ N⁺(j)| / |N⁺(i) ∪ N⁺(j)| for each {i, j} ∈ E - 5
put each vertex of the graph G in its own community - 6
for each vertex i, in order: take i out of its community - 7
put i in the neighboring community C with the largest gain k_{i,C} - γ k_i Σ_C / 2m, or back if none is larger - 8
repeat L6 and L7 until a full pass moves no vertex - 9
G ← the graph with one vertex per community; the weight of (C, D) is the sum of the weights from C to D - 10
if L5 to L8 moved some vertex then go to L5 with the new G - 11
return 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, is the weight of the edges from to , the weighted degree of , the sum of the degrees in , and the sum of all degrees. The gain is 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 : a square of four cells at , a second square at , and cell 4 at 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 and , which share only cell 1: the weight is . The edges from cell 4 to cells 5 and 7 share cells 5 and 7 out of six, so they weigh . 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 -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 and , with modularity ; 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 -nearest-neighbor graph gets a weight between 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 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 , the rows after line L1. Line L2 sets , the nearest other points of , with ties broken by index, and . Line L3 takes the edges with or , and line L4 gives the weight . For a symmetric weight matrix with , let and , with sums over ordered pairs. The modularity of a labeling at resolution is
For the graph of line L4, which has no self-loops, this is the usual , with the weight of the edges inside and the sum of the degrees in .
Lemma 1 (weights). Every edge of line L3 has .
Proof. Let . Then and , so the intersection is not empty. Both sets have elements, so the union has at most elements. A ratio of a subset size to a superset size is at most 1.
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 in place of , as in PhenoGraph, an edge can get the weight 0.
Lemma 2 (the gain of line L7). Let vertex be alone in its community, let be a community not holding , let , and let . Moving into changes by
Proof. The move adds to the sum the ordered pairs and for . Each pair adds , so the sum grows by . Divide by . The pair is in one community before and after, so it does not change.
Line L6 removes from its community , which makes alone, and then line L7 compares the gains of the neighboring communities and of itself. The factor is the same for all, so the largest gain is the largest . The code moves only when another community beats by more than , so each move raises by more than .
Lemma 3 (aggregation). Let label the vertices with communities , and let line L9 form . Then has the same total , the degree of in is , and for every labeling of the communities, .
Proof. Each ordered pair adds to exactly one entry , which gives the total and the degrees. In , group the pairs by . The condition depends only on , the sum of over the group is , and the sum of is with the degree of . This is term by term.
This is why the code stores the self-loop weight of as the sum over ordered pairs inside : then the formula of 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 by more than . Two vertices in different connected components are never in one community, and with the communities are exactly the connected components, leaving out isolated vertices.
Proof. By Lemma 2 each move raises of the current graph by more than , and by Lemma 3 this is the of the input labeling. is at most 1, so there are finitely many moves, the loop of line L8 stops, and each level with a move raises . 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 , so no single move raises by more than . A vertex only joins communities with , 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 the gain of a neighboring community is 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.
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 time for coordinates, and lines L3 and L4 take expected time with hash sets, for at most edges. One pass of line L6 over all vertices takes time, with , 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 , the modularity formula against the edge form, Lemma 3 on random graphs, that the moving phase ends where no single move raises , and that the levels raise 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 gives the components. A simulation with three groups of cells measures that finds the groups and that splits one group but never mixes two.
Complexity
The neighbor search takes time by brute force, and the weights take expected time with hash sets, for at most edges. One pass of the moving phase takes 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 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 and falls as 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 and 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 -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 and 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 splits groups. In the tests, three groups of 40 cells came back exactly with , but with 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.
# 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 -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
- 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 6JJNPV Edit this page History Report an error Markdown