Skip to content

Differential Expression

Cells from the same sample are not independent observations. If you sequence 5,000 cells from one patient, you do not have 5,000 independent measurements. You have one biological replicate measured 5,000 times, and that distinction decides how to test for differential expression between conditions.

Single-cell tests such as the Wilcoxon test and MAST treat each cell as an independent observation. This inflates the effective sample size, so the p-values shrink with the number of cells instead of the number of patients. Squair et al. 2021 measured the problem in “Confronting false discoveries in single-cell differential expression”. Cell-level methods called hundreds of differentially expressed genes between groups with no biological difference at all. In an in vivo check of genes that only one method had called, RNAscope confirmed 5 of 6 genes from a pseudobulk test and 3 of 13 from the Wilcoxon test.

This page runs both routes on the same cells. The Kang 2018 data holds PBMCs from 8 lupus patients, each measured in a control and an IFN-beta stimulated condition.

Antonia Schumacher and Lukas Heumos deposited the processed Kang AnnData object under CC BY 4.0. File 34464122 contains the exact object used here. The original experiment is Kang and colleagues, 2018, deposited as GSE96583. This lesson derives cell summaries, normalized expression, pseudobulk counts, and differential-expression results from that object.

import numpy as np
import pandas as pd
import scanpy as sc
import matplotlib.pyplot as plt
sc.settings.verbosity = 3
np.random.seed(42)
adata = sc.read_h5ad("/opt/data/kang_2018.h5ad")
print(adata)
print(adata.obs["label"].value_counts())
print(adata.obs["cell_type"].value_counts())
AnnData object with n_obs × n_vars = 24673 × 15706
obs: 'nCount_RNA', 'nFeature_RNA', 'tsne1', 'tsne2', 'label', 'cluster', 'cell_type', 'replicate', 'nCount_SCT', 'nFeature_SCT', 'integrated_snn_res.0.4', 'seurat_clusters'
var: 'name'
obsm: 'X_pca', 'X_umap'
layers: None (.X)
label
stim 12358
ctrl 12315
Name: count, dtype: int64
cell_type
CD4 T cells 11238
CD14+ Monocytes 5697
B cells 2651
NK cells 1716
CD8 T cells 1621
FCGR3A+ Monocytes 1089
Dendritic cells 529
Megakaryocytes 132
Name: count, dtype: int64

The object holds 24,673 cells and 15,706 genes, split almost evenly between 12,315 control and 12,358 stimulated cells. The cell type labels ship with the dataset, so this page needs no clustering. CD4 T cells are the largest type, with 11,238 cells, and the tests below use them.

# Compare conditions within one cell type, treating every cell as a
# replicate. sc-best-practices shows this view inflates the false
# discovery rate, because cells from one patient are not independent.
cd4 = adata[adata.obs["cell_type"] == "CD4 T cells"].copy()
sc.pp.normalize_total(cd4, target_sum=1e4)
sc.pp.log1p(cd4)
sc.tl.rank_genes_groups(cd4, groupby="label", groups=["stim"],
reference="ctrl", method="wilcoxon")
de_cell_level = sc.get.rank_genes_groups_df(cd4, group="stim")
print(de_cell_level.head(10).to_string(index=False))
names scores logfoldchanges pvals pvals_adj
ISG15 87.675537 6.587747 0.0 0.0
IFI6 80.029068 6.972263 0.0 0.0
ISG20 76.741043 4.003573 0.0 0.0
IFIT3 73.735214 8.247092 0.0 0.0
IFIT1 70.644501 7.860435 0.0 0.0
LY6E 68.401077 5.068758 0.0 0.0
MX1 65.853409 5.566489 0.0 0.0
B2M 60.497433 0.603757 0.0 0.0
IFIT2 52.917747 6.954865 0.0 0.0
OAS1 49.499474 5.650621 0.0 0.0

Every gene in the top ten has a p-value of 0.0, smaller than the smallest number a float can hold, because the test counts each of the 11,238 cells as a replicate. The genes are the expected response to IFN-beta. ISG15, IFI6 and the IFIT genes are all interferon-stimulated genes.

The pseudobulk approach sums the raw counts of all cells from the same sample and cell type. Each cell type then has a bulk-like count matrix with one column per sample, and a bulk RNA-seq tool such as DESeq2 or edgeR tests it. Each condition keeps its true number of biological replicates. With 3 control and 3 treated patients, the test compares 3 against 3, not 15,000 cells against 15,000.

import decoupler as dc
# Aggregate the counts per patient and cell type. One pseudobulk sample
# per patient, condition and cell type: 8 patients x 2 conditions x 8
# cell types, 128 in principle and 124 in practice.
pdata = dc.pp.pseudobulk(adata, sample_col="replicate",
groups_col=["label", "cell_type"], mode="sum",
verbose=False)
# decoupler fills the combinations a patient does not contribute to
# with zero counts, and those empty rows also carry broken metadata,
# so drop them.
pdata = pdata[pdata.obs["psbulk_cells"] > 0].copy()
print(pdata)
print(pdata.obs["label"].value_counts())
AnnData object with n_obs × n_vars = 124 × 15706
obs: 'replicate', 'label_cell_type', 'label', 'cell_type', 'psbulk_cells', 'psbulk_counts'
var: 'name'
layers: 'psbulk_props', None (.X)
label
ctrl 63
stim 61
Name: count, dtype: int64

The 24,673 cells collapse into 124 pseudobulk samples, 63 control and 61 stimulated. Four combinations of patient, condition and cell type hold no cells, so 124 of the 128 possible samples remain.

cd4_pb = pdata[pdata.obs["cell_type"] == "CD4 T cells"].copy()
print(cd4_pb.n_obs, "CD4 T cell pseudobulks")
# Explore the pseudobulks before modeling. PCA on the samples shows
# whether the condition dominates the variation.
sc.pp.normalize_total(cd4_pb, target_sum=1e4)
sc.pp.log1p(cd4_pb)
sc.pp.scale(cd4_pb, max_value=10)
sc.tl.pca(cd4_pb, n_comps=10, random_state=42)
# 16 points: shrink the dots from scanpy's cell-scale default.
sc.pl.pca(cd4_pb, color="label", size=40, show=False)
plt.savefig("outputs/differential-expression_pca.png", dpi=150,
bbox_inches="tight")
plt.close()
16 CD4 T cell pseudobulks

PCA of the 16 CD4 T cell pseudobulks colored by condition. The stimulated and control samples split along the first component, so the IFN-beta response is the largest axis of variation in the pseudobulk data.

The 16 CD4 T cell samples, 8 patients in two conditions, split by condition along PC1. The stimulation effect is larger than the differences between patients.

# Remove lowly expressed genes, separately for this cell type, before
# the model.
cd4_pb = pdata[pdata.obs["cell_type"] == "CD4 T cells"].copy()
dc.pp.filter_by_expr(cd4_pb, group="label", min_count=10,
min_total_count=15)
print(cd4_pb.shape)
from pydeseq2.dds import DeseqDataSet
from pydeseq2.ds import DeseqStats
counts = cd4_pb.to_df().astype(int)
metadata = cd4_pb.obs[["label", "replicate"]]
# The design blocks on the patient, so the condition effect is
# estimated within patients.
dds = DeseqDataSet(counts=counts, metadata=metadata,
design="~ label + replicate", ref_level=["label", "ctrl"],
quiet=True)
dds.deseq2()
stats = DeseqStats(dds, contrast=["label", "stim", "ctrl"], quiet=True)
stats.summary()
de_pseudobulk = stats.results_df.sort_values("padj")
print(de_pseudobulk.head(10).to_string())
print("significant at padj < 0.05:",
int((de_pseudobulk["padj"] < 0.05).sum()))
(16, 5159)
baseMean log2FoldChange lfcSE stat pvalue padj
index
ISG20 1509.146999 3.063848 0.073911 41.453114 0.000000e+00 0.000000e+00
TNFSF10 292.675552 4.388434 0.140119 31.319225 2.554415e-215 6.589113e-212
BST2 224.632691 2.429823 0.086237 28.176230 1.143746e-174 1.966862e-171
PSMB9 524.773807 1.694189 0.061767 27.428682 1.248003e-165 1.609612e-162
IRF7 269.087570 3.414138 0.125294 27.249006 1.707549e-163 1.761849e-160
LY6E 578.418419 4.122293 0.151493 27.211081 4.802571e-163 3.932896e-160
GBP1 197.969970 3.742823 0.137567 27.207213 5.336358e-163 3.932896e-160
DRAP1 298.407798 1.930828 0.072805 26.520522 5.621050e-155 3.624875e-152
MT2A 346.704642 4.244987 0.160454 26.456043 3.108980e-154 1.782136e-151
UBE2L6 321.916230 2.597496 0.101012 25.714812 7.982627e-146 4.118237e-143
significant at padj < 0.05: 1173

The filter keeps 5,159 of the 15,706 genes for CD4 T cells. With the patient in the design, PyDESeq2 calls 1,173 genes at an adjusted p-value below 0.05. ISG20 leads with a log2 fold change of 3.06, and IRF7, BST2 and GBP1 in the top ten are interferon response genes too.

top_cell = set(de_cell_level.head(20)["names"])
top_bulk = set(de_pseudobulk.head(20).index)
print(len(top_cell & top_bulk), "genes shared by both top-20 lists")
# Count the calls of each route at the same cutoff.
n_cell = int((de_cell_level["pvals_adj"] < 0.05).sum())
n_bulk = int((de_pseudobulk["padj"] < 0.05).sum())
print(f"cell level: {n_cell} of {len(de_cell_level)} genes, "
f"{cd4.n_obs} cells as replicates")
print(f"pseudobulk: {n_bulk} of {len(de_pseudobulk)} genes, "
f"{cd4_pb.n_obs} samples as replicates")
# The same Wilcoxon test with the tie correction that Scanpy leaves off
# by default.
sc.tl.rank_genes_groups(cd4, groupby="label", groups=["stim"],
reference="ctrl", method="wilcoxon",
tie_correct=True, key_added="wilcoxon_ties")
de_ties = sc.get.rank_genes_groups_df(cd4, group="stim",
key="wilcoxon_ties")
n_ties = int((de_ties["pvals_adj"] < 0.05).sum())
print(f"cell level, tie corrected: {n_ties} of {len(de_ties)} genes")
11 genes shared by both top-20 lists
cell level: 584 of 15706 genes, 11238 cells as replicates
pseudobulk: 1173 of 5159 genes, 16 samples as replicates
cell level, tie corrected: 2273 of 15706 genes

The two routes agree on 11 of their top 20 genes. The call counts go the other way from what the warning at the top of this page might suggest. The Wilcoxon test calls 584 of 15,706 genes, and pseudobulk calls 1,173 of 5,159.

The default setting is the reason. Scanpy runs the Wilcoxon test without a tie correction unless asked. Most values of a sparse gene are tied at zero, and without the correction the test overestimates the variance of its statistic, so it is conservative on those genes. With tie_correct=True the same test on the same cells calls 2,273 of 15,706 genes, more than pseudobulk. A call count still cannot show the problem that Squair et al. 2021 describe. Their false discoveries are genes that differ between patients, which a test with cells as replicates reports as an effect of the condition. Pseudobulk keeps the patient as the unit of replication, and this design also blocks on the patient, so that variation stays out of the condition effect.

When cell-level tests are still appropriate

Section titled “When cell-level tests are still appropriate”

Cell-level tests are fine for finding the marker genes that set clusters apart within one dataset. rank_genes_groups in Scanpy and FindAllMarkers in Seurat compare clusters, not experimental conditions, so they describe how groups of cells in one dataset differ. The Annotation page uses the Wilcoxon test that way.

Tool Language Notes
muscat R Purpose-built for pseudobulk scRNA-seq DE analysis
DESeq2 R Standard bulk DE tool, works on aggregated counts
PyDESeq2 Python Python port of DESeq2, used on this page
edgeR R Standard bulk DE tool, works on aggregated counts
decoupleR R, Python Builds the pseudobulk matrix, and runs functional analysis on the results
  • Squair et al. 2021, “Confronting false discoveries in single-cell differential expression”, Nature Communications 12, 5692, doi 10.1038/s41467-021-25960-2
  • Crowell et al. 2020, the muscat paper, which formalized the pseudobulk approach
  • Murphy and Skene 2022, a further benchmark in favor of pseudobulk methods

Wolf, Angerer, and Theis, 2018 describe Scanpy, the Python toolkit for large-scale single-cell expression analysis.

Badia-i-Mompel and colleagues, 2022 describe decoupleR and its ensemble of methods that infer biological activities from omics data.

Muzellec and colleagues, 2023 describe PyDESeq2, the Python implementation of the DESeq2 method.

The Single-cell best practices differential-expression chapter explains biological replication and pseudobulk comparisons. It separates donor-level inference from a test that treats cells as independent replicates.

The decoupler pseudobulk reference defines sample grouping, count layers, and aggregation. Those choices determine the units passed to the paired model.