Compare Two Clusterings¶
A SetCollection makes sets of cells, such as
clusters, the observations, and keeps exactly which cells are in each set. That
makes it easy to compare two clusterings of the same cells: which clusters
match, which one merged, and which one split. This brief example uses
simulated cells of six cell types and two clusterings that disagree in known
ways.
import anndata as ad
import numpy as np
import pandas as pd
import celldega as dega
Simulate cells and two clusterings¶
rng = np.random.default_rng(0)
cell_types = ["B cells", "CD4 T", "CD8 T", "Myeloid", "Epithelial", "Stromal"]
markers = {
"B cells": ["MS4A1", "CD79A"],
"CD4 T": ["CD3E", "CD4"],
"CD8 T": ["CD3E", "CD8A"],
"Myeloid": ["CD68", "LYZ"],
"Epithelial": ["EPCAM", "KRT8"],
"Stromal": ["COL1A1", "DCN"],
}
genes = sorted({gene for genes_ in markers.values() for gene in genes_})
n_cells = 3000
cell_type = rng.choice(cell_types, n_cells, p=[0.12, 0.15, 0.13, 0.15, 0.30, 0.15])
counts = rng.poisson(0.3, (n_cells, len(genes))).astype(float)
for i, kind in enumerate(cell_type):
for gene in markers[kind]:
counts[i, genes.index(gene)] = rng.poisson(6)
adata = ad.AnnData(
counts,
obs=pd.DataFrame(
{"cell_type": pd.Categorical(cell_type, categories=cell_types)},
index=[f"cell_{i}" for i in range(n_cells)],
),
var=pd.DataFrame(index=genes),
)
adata
AnnData object with n_obs × n_vars = 3000 × 11
obs: 'cell_type'
Algorithm A finds all six cell types, with 5% of cells assigned at random. Algorithm B merges the two T cell types into one cluster and splits the epithelial cells into two.
truth = pd.Series(cell_type, index=adata.obs_names)
algorithm_a = truth.copy()
noisy = rng.random(n_cells) < 0.05
algorithm_a[noisy] = rng.choice(cell_types, noisy.sum())
algorithm_b = truth.replace({"CD4 T": "T cells", "CD8 T": "T cells"})
epithelial = algorithm_b == "Epithelial"
algorithm_b[epithelial] = np.where(rng.random(epithelial.sum()) < 0.5, "Epithelial 1", "Epithelial 2")
adata.obs["algorithm_a"] = pd.Categorical(algorithm_a)
adata.obs["algorithm_b"] = pd.Categorical(algorithm_b)
One SetCollection per clustering¶
Each collection has one row per cluster and a membership modality: a sparse
clusters × cells matrix.
clusters_a = dega.SetCollection(adata, set_col="algorithm_a", name="A")
clusters_b = dega.SetCollection(adata, set_col="algorithm_b", name="B")
clusters_a.mod["membership"]
AnnData object with n_obs × n_vars = 6 × 3000
obs: 'algorithm_a', 'n_cells', 'set_source'
var: 'cell', 'entity_type'
Overlap between the clusterings¶
calc_overlap compares the two collections' memberships: entry (a, b) is the
intersection over union (IoU) of the cells in cluster a and cluster b. It adds
an A clusters × B clusters modality that clusters in a Clustergram. Matching
clusters overlap near 1. A merge shows as two A clusters sharing one B
cluster, and a split as one A cluster spread across two B clusters.
clusters_a.calc_overlap(clusters_b, modality_name="overlap_with_b")
clusters_a.mod["overlap_with_b"].to_df().round(2)
| algorithm_b | Epithelial 1 | T cells | B cells | Epithelial 2 | Stromal | Myeloid |
|---|---|---|---|---|---|---|
| algorithm_a | ||||||
| Epithelial | 0.49 | 0.00 | 0.00 | 0.48 | 0.00 | 0.00 |
| CD4 T | 0.00 | 0.48 | 0.00 | 0.00 | 0.00 | 0.01 |
| B cells | 0.00 | 0.00 | 0.92 | 0.01 | 0.00 | 0.00 |
| Stromal | 0.01 | 0.01 | 0.00 | 0.00 | 0.93 | 0.00 |
| Myeloid | 0.00 | 0.01 | 0.00 | 0.00 | 0.00 | 0.92 |
| CD8 T | 0.00 | 0.47 | 0.00 | 0.00 | 0.00 | 0.01 |
mat = dega.clust.Matrix(clusters_a.mod["overlap_with_b"])
mat.cluster()
cgm = dega.viz.Clustergram(matrix=mat, width=350, height=350, row_label_scale=0.35, col_label_scale=0.45)
cgm
Consensus across clusterings¶
To find groups the clusterings agree on, stack the collections with
concat_sets, calculate the overlap of every cluster with every other, and cut
the clustered overlap into groups. Most groups pair matching clusters from A
and B. B's merged T cell cluster pairs with A's CD4 T cells, leaving A's CD8
T cells on their own: the merge B made.
combined = dega.concat_sets([clusters_a, clusters_b], names=["A", "B"])
combined.calc_overlap() # a square relation between all clusters
combined.add_relation_modality("overlap") # as a modality that can be clustered
consensus_mat = dega.clust.Matrix(combined.mod["overlap_relation"])
consensus_mat.cluster()
consensus = consensus_mat.cut_tree(axis="col", n_clusters=6)
consensus.groupby(consensus).apply(lambda group: ", ".join(group.index)).rename("clusters")
cluster 1 A::B cells, B::B cells 2 A::Epithelial, B::Epithelial 1, B::Epithelial 2 3 A::Stromal, B::Stromal 4 A::Myeloid, B::Myeloid 5 A::CD4 T, B::T cells 6 A::CD8 T Name: clusters, dtype: object