Single-cell RNA-seq

Author
Affiliation

Lieven Clement

Ghent University

library(tidyverse)
library(SingleCellExperiment)
library(scrapper)
library(scuttle)
library(DropletUtils)
library(MouseGastrulationData)
library(scDblFinder)
library(SingleR)
library(omicsGMF)
library(edgeR)
library(stageR)
library(patchwork)

In the bulk RNA-seq lectures we modelled counts:

Single-cell RNA-seq (scRNA-seq) measures the expression of thousands of individual cells.

Most of these concepts carry over, but the data bring new challenges:

  1. Preprocessing: which droplets contain a cell, and which cells are of good quality?
  2. The count model: very low counts with many zeros. Are the data zero-inflated? How do we normalise?
  3. Exploring the cells: feature selection, dimension reduction, clustering, marker genes and cell type annotation.
  4. Multi-sample experiments: which cells are the experimental units? Differential expression between conditions within each cell type, and differential abundance of the cell types.

We follow the workflow of the Bioconductor book Orchestrating single-cell analysis (Amezquita et al. 2020) and the Carpentries lesson on single-cell analysis with Bioconductor, with the scrapper package, which replaces the computational functions of scran, scater and scuttle.

1 From bulk to single cell

1.1 Evolution of gene expression measurements

Image credit: Bo Xia
  • Bulk RNA-seq blends all cells of the tissue: we only see the average expression.
  • scRNA-seq resolves the individual cells, but the cells are dissociated from the tissue and their location is lost.
  • Spatial transcriptomics measures the expression in the tissue, and keeps the location.

1.2 Protocol

Owens, 2012, doi: 10.1038/491027a
  • Bulk RNA-seq measures the average expression of all cells of a sample, typically with millions of reads per sample.
  • scRNA-seq measures thousands to millions of cells, but with only a limited number of reads per cell.
  • Hence, the counts per gene and per cell are very low, and most counts are zero.

Image credit: Davide Risso

1.3 Protocols

Griffiths et al., 2018, doi: 10.15252/msb.20178046

Image credit: Davide Risso
  • Full-length protocols (typically plate-based, e.g. Smart-seq2 and Smart-seq3): a count is the number of reads that map to a gene, as in bulk RNA-seq. Few cells, but a high sequencing depth per cell and information on the full transcript.
  • UMI-based protocols (typically droplet-based, e.g. 10x Genomics): every molecule gets a unique molecular identifier (UMI) before amplification. Reads with the same UMI are collapsed, so that a count is the number of observed molecules: PCR duplicates are removed. Many cells, but only the 3’ or 5’ end of the transcript is sequenced.
  • Both suffer from a low capture efficiency: only a fraction of the molecules in a cell is captured and sequenced.

In this lecture we focus on UMI-based droplet data, the most common type of scRNA-seq data.

1.4 Multiplexing

Kang et al., 2018, doi: 10.1038/nbt.4042
  • Cells of different individuals can be pooled in one run and assigned to their individual afterwards, based on their genotype (demuxlet) or on a barcoded antibody (cell hashing).
  • Multiplexing reduces the cost and avoids that the individual is confounded with the run.
  • This is a matter of experimental design: we come back to this in the multi-sample section.

The PBMCs of 8 lupus patients were left untreated or stimulated with interferon beta (Kang et al. 2018). The UMAP below summarises the expression of all cells in two dimensions (see dimension reduction).

UMAP of the Kang data, coloured by cell type, condition and patient. Made with R/make_scrnaseq_figs.R.
  • Every cell type splits into a control and a stimulated cluster: a huge effect of the treatment on all cell types. If we see such large effects, we always have to be on our guard!
  • The cells of the patients mix within each cluster: the cells of the 8 patients were pooled and demultiplexed on their genotype.
  • But all control cells were sequenced in a first run and all stimulated cells in a second run.
  • So the large effect might be an effect of the batch!

1.5 Workflow

Image credit: OSCA book
  • The reads are processed with e.g. Cell Ranger, STARsolo or alevin-fry: cell barcode identification and correction, UMI collapsing and counting.
  • The result is a count matrix with one row per gene and one column per droplet.
  • In R/Bioconductor, the counts and all metadata are stored in a SingleCellExperiment object.

Image credit: OSCA book
  • It extends the SummarizedExperiment class of the bulk lectures with slots for dimension reduction results (reducedDims) and alternative experiments (altExps, e.g. spike-ins or antibody-derived tags).
  • All slots are linked: filtering cells or genes also filters the corresponding metadata.

2 Data

We use two datasets:

  • Mouse chimeric embryos (Pijuan-Sala et al. 2019): cells of a tdTomato-positive embryonic stem cell line were injected into wild-type mouse embryos, which were collected at E8.5 and sequenced with 10x Genomics. We analyse sample 5 to illustrate the workflow for a single sample.
  • Kang data (Kang et al. 2018): peripheral blood mononuclear cells (PBMCs) of 8 lupus patients, untreated or stimulated with interferon beta. We use them for the multi-sample analyses.

The chimera data are available in the Bioconductor package MouseGastrulationData. The other data are available as a release of the course repository. The script R/make_scrnaseq_data.R in the course repository shows how these files were built from the Bioconductor packages MouseGastrulationData and muscData.

dataUrl <- "https://github.com/statOmics/SGA/releases/download/scrnaseq-v1/"
dir.create("scrnaseqData", showWarnings = FALSE)
for (f in c("embryo_atlas_ref.rds", "kang.rds")) {
  if (!file.exists(file.path("scrnaseqData", f))) {
    download.file(paste0(dataUrl, f), file.path("scrnaseqData", f), mode = "wb")
  }
}

2.1 Exploring a SingleCellExperiment

We start from the raw counts of sample 5 of the chimera data: the counts of all droplets, as delivered by Cell Ranger.

raw <- WTChimeraData(samples = 5, type = "raw")[[1]]
raw
class: SingleCellExperiment 
dim: 29453 522554 
metadata(0):
assays(1): counts
rownames(29453): ENSMUSG00000051951 ENSMUSG00000089699 ...
  ENSMUSG00000095742 tomato-td
rowData names(2): ENSEMBL SYMBOL
colnames(522554): AAACCTGAGAAACCAT AAACCTGAGAAACCGC ...
  TTTGTCATCTTTACGT TTTGTCATCTTTCCTC
colData names(0):
reducedDimNames(0):
mainExpName: NULL
altExpNames(0):

The counts are stored as an assay, with one row per gene and one column per droplet (barcode), as for the SummarizedExperiment of the bulk RNA-seq lectures.

assays(raw)
List of length 1
names(1): counts
counts(raw)[1:6, 1:6]
6 x 6 sparse Matrix of class "dgCMatrix"
                   AAACCTGAGAAACCAT AAACCTGAGAAACCGC AAACCTGAGAAACCTA
ENSMUSG00000051951                .                .                .
ENSMUSG00000089699                .                .                .
ENSMUSG00000102343                .                .                .
ENSMUSG00000025900                .                .                .
ENSMUSG00000025902                .                .                .
ENSMUSG00000104328                .                .                .
                   AAACCTGAGAAACGCC AAACCTGAGAAAGTGG AAACCTGAGAACAACT
ENSMUSG00000051951                .                .                .
ENSMUSG00000089699                .                .                .
ENSMUSG00000102343                .                .                .
ENSMUSG00000025900                .                .                .
ENSMUSG00000025902                .                .                .
ENSMUSG00000104328                .                .                .
class(counts(raw))
[1] "dgCMatrix"
attr(,"package")
[1] "Matrix"
1 - Matrix::nnzero(counts(raw)) / length(counts(raw))
[1] 0.9987329
  • 99.87% of the counts are zero.
  • The counts are therefore stored as a sparse matrix (dgCMatrix), which only stores the non-zero counts and their position.
  • A dense matrix stores every count, with 8 bytes per count:
format(object.size(counts(raw)), units = "GB")
[1] "0.3 Gb"
as.numeric(nrow(raw)) * ncol(raw) * 8 / 1024^3
[1] 114.6703

The feature annotation is stored in rowData, the droplet annotation in colData.

rowData(raw)
DataFrame with 29453 rows and 2 columns
                         ENSEMBL        SYMBOL
                     <character>   <character>
ENSMUSG00000051951 ENSMUSG000...          Xkr4
ENSMUSG00000089699 ENSMUSG000...        Gm1992
ENSMUSG00000102343 ENSMUSG000...       Gm37381
ENSMUSG00000025900 ENSMUSG000...           Rp1
ENSMUSG00000025902 ENSMUSG000...         Sox17
...                          ...           ...
ENSMUSG00000095041 ENSMUSG000...    AC149090.1
ENSMUSG00000063897 ENSMUSG000...         DHRSX
ENSMUSG00000096730 ENSMUSG000...      Vmn2r122
ENSMUSG00000095742 ENSMUSG000... CAAA011473...
tomato-td              tomato-td     tomato-td
colData(raw)
DataFrame with 522554 rows and 0 columns
  • The rownames are Ensembl gene identifiers, the gene symbols are stored in rowData(raw)$SYMBOL.
  • The last feature, tomato-td, is the tdTomato marker of the injected embryonic stem cells.
  • The colnames are the cell barcodes. The colData is still empty: we will add the results of the preprocessing.

The results of the dimension reduction will be stored in reducedDims, which is also still empty.

reducedDimNames(raw)
character(0)

All slots are linked. We add the total count of each droplet to the colData, and subset the droplets with a total count above 100: the corresponding colData is subsetted along.

raw$total <- colSums(counts(raw))
colData(raw)
DataFrame with 522554 rows and 1 column
                     total
                 <numeric>
AAACCTGAGAAACCAT         4
AAACCTGAGAAACCGC         1
AAACCTGAGAAACCTA         1
AAACCTGAGAAACGCC         1
AAACCTGAGAAAGTGG        16
...                    ...
TTTGTCATCTTGTATC        56
TTTGTCATCTTGTCAT         4
TTTGTCATCTTTACAC         2
TTTGTCATCTTTACGT         2
TTTGTCATCTTTCCTC        47
sub <- raw[, raw$total > 100]
dim(sub)
[1] 29453  9315
summary(sub$total)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
    101     123     212    8921   17254   83260 

Only 9315 of the 522554 droplets have a total count above 100.

3 Preprocessing

3.1 Empty droplets

Most droplets do not contain a cell. Still, they contain some RNA: ambient RNA of cells that were lysed or damaged before the droplets were formed.

ranks <- barcodeRanks(counts(raw))
as_tibble(as.data.frame(ranks)) |>
  filter(total > 0, !duplicated(rank)) |>
  ggplot(aes(rank, total)) +
  geom_point(size = 0.5) +
  geom_hline(yintercept = metadata(ranks)$knee, color = "dodgerblue", linetype = 2) +
  geom_hline(yintercept = metadata(ranks)$inflection, color = "darkgreen", linetype = 2) +
  scale_x_log10() +
  scale_y_log10() +
  labs(x = "Rank", y = "Total UMI count",
       caption = "blue: knee, green: inflection point") +
  theme_bw()

  • The barcodes are ranked according to their total UMI count.
  • Barcodes above the knee very likely contain a cell, barcodes with a very low count are empty.
  • The barcodes in between are hard to classify with a threshold on the total count: a small cell with little RNA can have a lower count than an empty droplet with a lot of ambient RNA.

emptyDrops (Lun et al. 2019) uses the composition of the counts instead:

  1. The ambient profile \(\mathbf{p}_A\), i.e. the expected fraction of the ambient RNA that comes from each gene, is estimated from the barcodes with a total count of at most 100, which are assumed to be empty.
  2. Under the null hypothesis that barcode \(i\) is empty, its counts \(\mathbf{y}_i\) are a sample from the ambient profile: given its total count \(N_i\), they follow a Dirichlet-multinomial distribution with mean \(N_i \mathbf{p}_A\).
  3. The likelihood of the observed counts under this null is compared with that of random samples of the ambient profile with the same total count, which gives a Monte Carlo p-value.
  4. The p-values are corrected for multiple testing, and barcodes with an FDR \(\leq 0.001\) are called cells. Barcodes above the knee are always retained.

A cell differs from the ambient profile in its composition, regardless of its total count. The p-values are based on random samples, so we set a seed.

set.seed(20261116)
ed <- emptyDrops(counts(raw))
ed
DataFrame with 522554 rows and 5 columns
                     Total   LogProb    PValue   Limited       FDR
                 <integer> <numeric> <numeric> <logical> <numeric>
AAACCTGAGAAACCAT         4        NA        NA        NA        NA
AAACCTGAGAAACCGC         1        NA        NA        NA        NA
AAACCTGAGAAACCTA         1        NA        NA        NA        NA
AAACCTGAGAAACGCC         1        NA        NA        NA        NA
AAACCTGAGAAAGTGG        16        NA        NA        NA        NA
...                    ...       ...       ...       ...       ...
TTTGTCATCTTGTATC        56        NA        NA        NA        NA
TTTGTCATCTTGTCAT         4        NA        NA        NA        NA
TTTGTCATCTTTACAC         2        NA        NA        NA        NA
TTTGTCATCTTTACGT         2        NA        NA        NA        NA
TTTGTCATCTTTCCTC        47        NA        NA        NA        NA
  • The barcodes with a total count of at most 100 are not tested: their FDR is NA.
  • We use a very low FDR threshold, so that very few empty droplets are called cells.
isCell <- !is.na(ed$FDR) & ed$FDR <= 0.001
table(tested = !is.na(ed$FDR), cell = isCell)
       cell
tested   FALSE   TRUE
  FALSE 513239      0
  TRUE    5927   3388
table(limited = ed$Limited, cell = isCell)
       cell
limited FALSE TRUE
  FALSE  5927   63
  TRUE      0 3325
  • Limited = TRUE means that none of the random samples of the ambient profile had a lower likelihood than the barcode: its p-value is the smallest possible Monte Carlo p-value, \(1/(\text{niters} + 1)\) with niters = 10000 random samples by default.
  • For barcodes that are not called a cell but have Limited = TRUE, more random samples (argument niters) could lower the p-value. Here, all limited barcodes are called cells.
as_tibble(as.data.frame(ed)) |>
  mutate(cell = isCell) |>
  filter(!is.na(FDR)) |>
  ggplot(aes(Total, -LogProb, color = cell)) +
  geom_point(size = 0.5) +
  geom_vline(xintercept = metadata(ranks)$knee, color = "dodgerblue", linetype = 2) +
  geom_vline(xintercept = metadata(ranks)$inflection, color = "darkgreen", linetype = 2) +
  scale_x_log10() +
  scale_y_log10() +
  labs(x = "Total UMI count", y = "-log likelihood under the ambient profile",
       color = "Cell", caption = "tested barcodes; blue: knee, green: inflection point") +
  theme_bw()

  • The log-likelihood decreases with the total count: a barcode with more counts has a smaller probability of every specific outcome.
  • For the same total count, the barcodes called cells have a much lower likelihood under the ambient profile: their composition differs from that of the ambient RNA.
  • Hence, barcodes with the same total count can be called a cell or not: emptyDrops does not use a threshold on the total count, and also calls cells below the knee and the inflection point.

We keep the cells and store the results of emptyDrops in the colData.

sce <- raw[, isCell]
colData(sce) <- ed[isCell, c("Total", "LogProb", "PValue", "FDR")]
sce
class: SingleCellExperiment 
dim: 29453 3388 
metadata(0):
assays(1): counts
rownames(29453): ENSMUSG00000051951 ENSMUSG00000089699 ...
  ENSMUSG00000095742 tomato-td
rowData names(2): ENSEMBL SYMBOL
colnames(3388): AAACCTGAGACTGTAA AAACCTGAGATGCCTT ... TTTGTCACATTCTCAT
  TTTGTCATCTGAGTGT
colData names(4): Total LogProb PValue FDR
reducedDimNames(0):
mainExpName: NULL
altExpNames(0):

3388 of the 522554 barcodes contain a cell.

3.2 Quality control

Some cells are damaged or stressed. Typically, the cell membrane is damaged so that the cytoplasmic RNA leaks out, while the mitochondria, which have their own membrane, stay in the cell. Such cells have

  • a low total count (library size),
  • a low number of detected genes,
  • a high proportion of counts from mitochondrial genes.

Fixed thresholds, e.g. “at least 1000 genes and less than 5% mitochondrial counts”, require experience with the tissue and the protocol: e.g. tumour cells and cardiomyocytes naturally have a high mitochondrial content. We therefore use adaptive thresholds: we assume that most cells are of good quality, and flag cells that are outliers. For the library size \(N_i\), e.g., a cell is removed if

\[ \log N_i < \text{median}(\log \mathbf{N}) - 3 \times \text{MAD}(\log \mathbf{N}), \]

with MAD the median absolute deviation, a robust estimate of the standard deviation. For normally distributed data, the threshold of 3 MADs only removes 0.13% of the cells in each direction. The library size and the number of detected genes are assessed on the log scale with a lower threshold, the mitochondrial proportion with an upper threshold.

The mitochondrial genes of the mouse have a gene symbol that starts with “mt-”. We flag them in the rowData.

rowData(sce)$chr_mito <- grepl("^mt-", rowData(sce)$SYMBOL)
rowData(sce)$SYMBOL[rowData(sce)$chr_mito]
 [1] "mt-Nd1"  "mt-Nd2"  "mt-Co1"  "mt-Co2"  "mt-Atp8" "mt-Atp6" "mt-Co3" 
 [8] "mt-Nd3"  "mt-Nd4l" "mt-Nd4"  "mt-Nd5"  "mt-Nd6"  "mt-Cytb"
sce <- quickRnaQc.se(sce, subsets = list(mito = rowData(sce)$chr_mito))
metadata(sce)$qc$thresholds
$sum
[1] 5421.33

$detected
[1] 2732.415

$subset.proportion
      mito 
0.04317669 
table(sce$keep)

FALSE  TRUE 
  914  2474 
qcData <- as_tibble(as.data.frame(colData(sce)))
p1 <- ggplot(qcData, aes(sum, detected, color = keep)) +
  geom_point(size = 0.5) +
  scale_x_log10() +
  scale_y_log10() +
  labs(x = "Library size", y = "Detected genes") +
  theme_bw()
p2 <- ggplot(qcData, aes(detected, subset.proportion.mito, color = keep)) +
  geom_point(size = 0.5) +
  scale_x_log10() +
  labs(x = "Detected genes", y = "Mitochondrial proportion") +
  theme_bw()
p1 + p2 + plot_layout(guides = "collect")

  • Most removed cells have a small library, few detected genes and a high mitochondrial proportion: they are damaged cells.
  • A concern is that we may remove a biologically distinct cell type, e.g. cells with a naturally low RNA content or a high metabolic activity.
  • QC metrics are therefore often explored per cluster, or the removed cells are compared with the retained cells.

The authors of the study performed their own QC and annotated the remaining cells. Their cell type labels are available in the processed data of MouseGastrulationData. We add them to the colData to compare them with our results later on. The processed data identify the cells with their barcode. Cells that the authors removed get no label (NA).

processed <- WTChimeraData(samples = 5)
sce$celltype.published <- processed$celltype.mapped[match(colnames(sce), processed$barcode)]
rm(processed)
table(keep = sce$keep, published = !is.na(sce$celltype.published))
       published
keep    FALSE TRUE
  FALSE   894   20
  TRUE     90 2384
sce <- sce[, sce$keep]

3.3 Doublets

Some droplets contain two (or more) cells: doublets. Doublets can be mistaken for intermediate or transitional cell states.

Germain et al., 2021, doi: 10.12688/f1000research.73600.2

scDblFinder (Germain et al. 2021) simulates doublets:

  1. Two random cells are selected and their counts are summed. This is repeated many times.
  2. The real and simulated cells are projected into the same principal component space.
  3. For each cell, the proportion of simulated doublets among its nearest neighbours is computed. Cells in a neighbourhood with many simulated doublets are likely doublets.
  4. This proportion and other features are used to train a classifier that distinguishes the simulated doublets from the real cells.

Doublets of two cells of the same type cannot be detected in this way, but they are also less harmful.

set.seed(1234)
sce <- scDblFinder(sce)
table(sce$scDblFinder.class)

singlet doublet 
   2397      77 
table(class = sce$scDblFinder.class, published = !is.na(sce$celltype.published))
         published
class     FALSE TRUE
  singlet    88 2309
  doublet     2   75
sce <- sce[, sce$scDblFinder.class == "singlet"]

As for QC, we should be careful: rare transitional cell populations can be hard to distinguish from doublets.

3.4 Filtering genes

Many genes are not detected in any of the remaining cells.

detectedCells <- rowSums(counts(sce) > 0)
table(cut(detectedCells, c(-Inf, 0, 9, Inf), labels = c("0", "1-9", ">= 10")))

    0   1-9 >= 10 
 9946  4251 15256 
  • Genes that are not detected or only in a few cells carry no information about the differences between the cells.
  • We remove the genes that are detected in fewer than 10 cells. This reduces the memory and the computation time of all subsequent steps.
  • We filter after QC and doublet removal, so that the detection is counted in good cells only. Before emptyDrops, a detection in a droplet would mostly reflect ambient RNA.
  • The threshold is deliberately low: a strict threshold could remove the marker genes of rare cell types.
  • This filter only removes uninformative genes. Selecting informative genes for the exploration of the cells is the goal of feature selection, and for differential expression we filter the genes again on the pseudobulk counts.
sce <- sce[detectedCells >= 10, ]
sce
class: SingleCellExperiment 
dim: 15256 2397 
metadata(2): qc scDblFinder.threshold
assays(1): counts
rownames(15256): ENSMUSG00000025902 ENSMUSG00000033845 ...
  ENSMUSG00000063897 tomato-td
rowData names(4): ENSEMBL SYMBOL chr_mito scDblFinder.selected
colnames(2397): AAACCTGAGACTGTAA AAACCTGAGATGCCTT ... TTTGGTTTCAGTCAGT
  TTTGGTTTCGCCATAA
colData names(13): Total LogProb ... scDblFinder.weighted
  scDblFinder.cxds_score
reducedDimNames(0):
mainExpName: NULL
altExpNames(0):

4 The count model and normalisation

4.1 A count model for UMI data

Let \(y_{gi}\) be the UMI count of gene \(g\) in cell \(i\). As in bulk RNA-seq, we model

\[ y_{gi} \sim NB(\mu_{gi}, \phi_g), \qquad \mu_{gi} = s_i N_i\, \pi_{gi}, \]

with \(\pi_{gi}\) the relative abundance of gene \(g\) in cell \(i\), \(N_i\) the library size and \(s_i\) a normalisation factor. In a GLM, \(\log(s_i N_i)\) is used as an offset, so that the model parameters describe the relative abundances \(\pi_{gi}\).

  • The UMIs remove the PCR duplicates. For a homogeneous population of cells, the counts are therefore close to Poisson, i.e. the technical sampling of the molecules.
  • The NB dispersion captures the biological variability between cells of the same population.

4.2 Zero inflation?

scRNA-seq data contain many zeros. Many authors have proposed zero-inflated models, e.g. the zero-inflated negative binomial (ZINB) distribution

\[ f(y_{gi}) = \pi^0_{gi}\, \delta_0(y_{gi}) + (1 - \pi^0_{gi})\, f_{NB}(y_{gi}; \mu_{gi}, \phi_g), \]

a mixture of a point mass at zero, which represents “technical” zeros or dropouts, and an NB count component.

Are the zeros in UMI data more frequent than expected under an NB model? We assess this for the Mesenchyme cells, the largest cell type of the published annotation (Svensson 2020). Under the model above with a common relative abundance \(\pi_g\) for all cells of a homogeneous population,

  • the relative abundance is estimated as \(\hat\pi_g = \sum_i y_{gi} / \sum_i N_i\). This is the maximum likelihood estimator under the Poisson model; under the NB model it is a moment estimator, which is unbiased because \(\text{E}[y_{gi}] = N_i \pi_g\),
  • the expected fraction of zeros under a Poisson model is \(\frac{1}{n}\sum_i e^{-\hat\mu_{gi}}\),
  • and under an NB model \(\frac{1}{n}\sum_i (1 + \phi_g \hat\mu_{gi})^{-1/\phi_g}\), with \(\phi_g\) estimated with the method of moments.

Here, \(\hat\mu_{gi} = N_i \hat\pi_g\): we set the normalisation factors \(s_i\) to one and only correct for the library size. Normalisation factors correct for differences in the composition of the cells, which are negligible within a homogeneous population of cells.

y <- counts(sce)[, which(sce$celltype.published == ct)]
N <- colSums(y)
y <- y[rowSums(y) > 0, ]
pi <- rowSums(y) / sum(N)
mu <- outer(pi, N)
yDense <- as.matrix(y)
# moment estimator of the dispersion; a dispersion of (almost) zero gives the Poisson model
phi <- pmax(1e-8, rowSums((yDense - mu)^2 - mu) / rowSums(mu^2))
zeros <- tibble(
  mean = rowMeans(mu),
  observed = rowMeans(yDense == 0),
  Poisson = rowMeans(exp(-mu)),
  NB = rowMeans((1 + phi * mu)^(-1 / phi))
)
rm(yDense, mu)
p1 <- ggplot(zeros, aes(mean, observed)) +
  geom_point(size = 0.3, alpha = 0.3) +
  geom_line(aes(y = Poisson), color = "red", data = ~ arrange(.x, mean)) +
  scale_x_log10() +
  labs(x = "Mean count", y = "Fraction of zeros",
       title = paste(ct, "- red: expected under Poisson")) +
  theme_bw()
p2 <- zeros |>
  pivot_longer(c(Poisson, NB), names_to = "model", values_to = "expected") |>
  ggplot(aes(expected, observed)) +
  geom_point(size = 0.3, alpha = 0.3) +
  geom_abline(intercept = 0, slope = 1, color = "red") +
  facet_wrap(~ model) +
  labs(x = "Expected fraction of zeros", y = "Observed fraction of zeros") +
  theme_bw()
p1 + p2 + plot_layout(widths = c(1, 1.6))

  • The observed fraction of zeros closely follows the fraction expected under the Poisson model: no zero inflation is needed for UMI data of a homogeneous population.
  • The zeros are mainly due to the low counts: a gene with an expected count of 0.1 in a cell is not observed in 90% of the cells.
  • The few genes with more zeros than expected under the Poisson model are typically genes that differ in expression between the cells, e.g. because of cell subtypes or the cell cycle. The NB model captures this extra variability.
  • Data of full-length protocols, with their high counts and the PCR amplification, may show zero inflation.

In a heterogeneous population, many zeros are biological: the gene is not expressed in a cell type. They are captured by the cell type effects in the mean model, not by a zero-inflation component.

A gene that is expressed in every cell. The cells of sample 5 were sorted on the fluorescence of tdTomato, a red fluorescent protein that is expressed by all cells derived from the injected embryonic stem cells. The tdTomato sequence was added to the reference genome, so the counts contain a feature tomato-td.

yTomato <- counts(sce)["tomato-td", ]
table(yTomato)
yTomato
   0    1    2    3    4    5    7 
1319  726  264   71   15    1    1 
NTomato <- colSums(counts(sce))
muTomato <- NTomato * sum(yTomato) / sum(NTomato)
c(observed = mean(yTomato > 0), Poisson = mean(1 - exp(-muTomato)))
 observed   Poisson 
0.4497288 0.4633694 
  • Although every cell expresses tdTomato, the transcript is detected in only 45% of the cells, with on average 0.64 UMI per cell.
  • A Poisson model with the library size as offset and the same relative abundance in all cells predicts that the transcript is detected in 46% of the cells.
  • The zeros are thus fully explained by the low capture efficiency, i.e. the sampling of a few molecules per cell. No separate dropout mechanism is needed.
  • A zero in a single cell is therefore weak evidence that a gene is not expressed.

4.3 Normalisation

Lun et al., 2016, doi: 10.1186/s13059-016-0947-7
  • Library size normalisation: \(s_i = 1\), i.e. we only correct for the total count. This assumes that there is no composition bias between the cells.
  • TMM and DESeq2 correct for composition bias, but they are driven by the few genes without zeros, which makes them unstable for scRNA-seq data.
  • Deconvolution (Lun et al. 2016): the counts of pools of cells are summed, so that there are fewer zeros, and a size factor is estimated for each pool against a reference pseudo-cell. The pools are overlapping, so that the size factors of the individual cells can be obtained from those of the pools by solving a linear system.

Lun et al., 2016, doi: 10.1186/s13059-016-0947-7
libFactors <- sce$sum / mean(sce$sum)
pooledFactors <- pooledSizeFactors(sce)
tibble(library = libFactors, deconvolution = pooledFactors,
       erythroid = grepl("Erythroid", sce$celltype.published)) |>
  ggplot(aes(library, deconvolution, color = erythroid)) +
  geom_point(size = 0.5) +
  geom_abline(intercept = 0, slope = 1, color = "red") +
  scale_x_log10() +
  scale_y_log10() +
  labs(x = "Library size factor", y = "Deconvolution size factor",
       color = "Erythroid cell") +
  theme_bw()

  • Both size factors largely agree, but the deviations are cell type specific.
  • The erythroid cells systematically get a smaller deconvolution size factor than their library size factor: a large part of their library consists of haemoglobin transcripts. This is a composition bias: with library size factors, all other genes appear to be expressed at a lower level in erythroid cells.
  • In practice, library size factors are mostly used for exploration and clustering: composition bias shifts the expression of all genes of a cell type by roughly the same factor, which rarely creates or removes clusters.
  • In the exploration below, we therefore use library size factors, i.e. \(s_i = 1\) and an offset \(\log N_i\), for the log-normalised counts, the highly variable genes and the deviance. The deconvolution size factors estimate \(s_i N_i\) up to a constant. To use them, we would pass them to normalizeRnaCounts.se(sce, size.factors = pooledFactors) for the log-normalised counts, and use their log as offset in the count models.
  • GMF, in contrast, estimates an intercept for each cell, which captures the library size and the normalisation factor (see generalised matrix factorisation).
  • For differential expression between conditions, we will aggregate the counts into pseudobulk samples, which can again be normalised with TMM (see multi-sample experiments).

4.4 Log-normalised counts

For exploration, most workflows use log-normalised counts

\[ z_{gi} = \log_2\left(\frac{y_{gi}}{s_i} + 1\right), \]

with \(s_i\) the size factor, centred at one.

sce <- normalizeRnaCounts.se(sce)
assayNames(sce)
[1] "counts"    "logcounts"

The log transformation, however, does not stabilise the variance of low counts, and the pseudocount of 1 distorts the data: a zero in a cell with a large library is more informative than a zero in a cell with a small library, but both get \(z_{gi} = 0\).

Townes et al., 2019, doi: 10.1186/s13059-019-1861-6
  • Townes et al. (2019) simulated data without any biological signal. After log normalisation, the first principal component is strongly related to the fraction of zeros in a cell.
  • This motivates count models that account for the library size on the count scale, also for dimension reduction: see generalised matrix factorisation.

5 Feature selection

  • With thousands of genes, the distances between cells are dominated by noise: in high dimensions, all cells appear to be far apart.
  • Most genes are uninformative: they are not expressed, or they are expressed at the same level in all cells.
  • We therefore select the genes that are informative for the structure in the data, a first and simple step of dimension reduction.

5.1 Highly variable genes

The most common approach selects genes with a high variance of the log-normalised counts relative to their mean. The log transformation does not remove the mean-variance relation, so a trend is fitted, and genes with the largest residuals with respect to the trend are selected.

sce <- chooseRnaHvgs.se(sce)
table(rowData(sce)$hvg)

FALSE  TRUE 
11256  4000 
as_tibble(as.data.frame(rowData(sce))) |>
  ggplot(aes(means, variances, color = hvg)) +
  geom_point(size = 0.5) +
  geom_line(aes(y = fitted), color = "black") +
  labs(x = "Mean log-expression", y = "Variance of log-expression") +
  theme_bw()

5.2 Genes with a high deviance

Townes et al. (2019) select genes that fit poorly to a null model in which the relative abundance of a gene is the same in all cells,

\[ y_{gi} \sim Poisson(\mu_{gi}), \qquad \mu_{gi} = N_i\, \pi_g. \]

The deviance compares the log-likelihood of this null model with that of the saturated model, in which every observation has its own mean:

\[ D_g = 2 \sum_i \left[ y_{gi} \log\frac{y_{gi}}{\hat\mu_{gi}} - (y_{gi} - \hat\mu_{gi}) \right], \qquad \hat\mu_{gi} = N_i \hat\pi_g. \]

  • This is the likelihood ratio test statistic for lack of fit of the null model of the technical lecture.
  • With \(\hat\pi_g = \sum_i y_{gi}/\sum_i N_i\), the second term sums to zero, and only the non-zero counts contribute to the first term: the deviance is cheap to compute on a sparse matrix.
  • Genes with a large deviance vary more between cells than expected from the technical sampling: they are informative.
  • Townes et al. (2019) use the binomial deviance, which is close to the Poisson deviance for low counts.
y <- counts(sce)
N <- colSums(y)
piHat <- rowSums(y) / sum(N)
nonzero <- summary(y)
devNonzero <- rowsum(nonzero$x * log(nonzero$x / (piHat[nonzero$i] * N[nonzero$j])), nonzero$i)
# genes without counts have a deviance of zero
deviance <- numeric(nrow(y))
deviance[as.integer(rownames(devNonzero))] <- 2 * devNonzero[, 1]
rowData(sce)$deviance <- deviance
rowData(sce)$highDeviance <- rank(-deviance) <= sum(rowData(sce)$hvg)
table(hvg = rowData(sce)$hvg, highDeviance = rowData(sce)$highDeviance)
       highDeviance
hvg     FALSE  TRUE
  FALSE 10219  1037
  TRUE   1037  2963

Both approaches select largely the same genes.

Pearson residuals (Lause et al. 2021) are a closely related approach. Under an NB model with a fixed dispersion \(\phi\) (e.g. 0.01),

\[ r_{gi} = \frac{y_{gi} - \hat\mu_{gi}}{\sqrt{\hat\mu_{gi} + \phi\hat\mu_{gi}^2}} \]

has a variance of approximately one for all genes that follow the null model, whatever their mean. Genes with a large variance of the Pearson residuals, \(\sum_i r_{gi}^2/(n-1)\), are informative. Note that \(\sum_i r_{gi}^2\) and \(D_g\) are the Pearson and deviance goodness-of-fit statistics, i.e. the numerators of the two estimators of the quasi-likelihood dispersion of the technical lecture.

The selected genes are only used for exploration: dimension reduction, visualisation and clustering. For differential expression, we use all genes, and only remove lowly expressed genes with a filter that does not use the group labels (filterByExpr, see multi-sample experiments). A filter on the variance would distort the inference (Bourgon et al. 2010):

  • The variance across all cells also contains the differences between the conditions, so that the selection depends on the outcome of the test: the filter is not independent of the test statistic under the null hypothesis.
  • Retaining only genes with a high variance distorts the empirical Bayes prior of limma and edgeR, which is estimated across the genes.

6 Dimension reduction

We project the cells into a low-dimensional space that retains as much of the structure as possible, for visualisation, clustering and the detection of batch effects.

6.1 PCA

  • Principal component analysis (PCA) finds the linear combinations of the genes with the largest variance, see the HDDA course for a refresher.
  • It is typically performed on the log-normalised counts of the highly variable genes, and the top 10 to 50 principal components (PCs) are retained.
sce <- runPca.se(sce, features = rowData(sce)$hvg, number = 30)
pcaInfo <- metadata(sce)$PCA
tibble(pc = seq_along(pcaInfo$variance.explained),
       explained = pcaInfo$variance.explained / pcaInfo$total.variance) |>
  ggplot(aes(pc, explained)) +
  geom_point() +
  geom_line() +
  labs(x = "PC", y = "Proportion of variance explained") +
  theme_bw()

We retain the first 10 PCs, the same number of components as for GMF below, so that both embeddings can be compared on an equal footing.

reducedDim(sce, "PCA") <- reducedDim(sce, "PCA")[, 1:10]

6.2 Generalised matrix factorisation

PCA minimises the squared error between the (log-normalised) data and their low-rank approximation, which corresponds to a Gaussian likelihood with a constant variance. This is inappropriate for counts, which have a mean-variance relation.

Generalised matrix factorisation (GMF) brings the low-rank approximation into a GLM:

\[ \left\{ \begin{array}{lcl} y_{gi} &\sim& \text{Poisson}(\mu_{gi}) \text{ or } NB(\mu_{gi}, \phi)\\ \log \mu_{gi} &=& \mathbf{x}_i^T\boldsymbol{\beta}_g + \boldsymbol{\alpha}_i^T\mathbf{z}_g + \mathbf{u}_i^T\mathbf{v}_g \end{array} \right. \]

  • \(\mathbf{x}_i\) are known covariates of cell \(i\), e.g. the sample or the batch, with gene-specific effects \(\boldsymbol{\beta}_g\) (argument X). By default, \(\mathbf{x}_i = 1\): an intercept \(\beta_{g0}\) for each gene, which models its average expression. GMF can correct for known covariates, which can be used for batch correction.
  • \(\mathbf{z}_g\) are known covariates of gene \(g\), e.g. its GC content or length, with cell-specific effects \(\boldsymbol{\alpha}_i\) (argument Z). By default, \(\mathbf{z}_g = 1\): an intercept \(\alpha_i\) for each cell.
  • The cell intercept \(\alpha_i\) plays the role of the offset \(\log(s_i N_i)\) of the bulk RNA-seq models, but it is estimated: it captures the library size and the normalisation factor of the cell. No log transformation or pseudocount is needed.
  • \(\mathbf{u}_i\) are the scores of cell \(i\) on \(K\) latent factors and \(\mathbf{v}_g\) the loadings of gene \(g\). They play the role of the PC scores and loadings, but they are estimated on the scale of the linear predictor, by maximising the (penalised) likelihood.
  • A fixed offset can be added to the linear predictor (argument offset), e.g. the log library size. With a cell intercept in the model, this is not needed.

Hence, GMF generalises PCA to the exponential family.

  • The idea goes back to exponential family PCA (Collins et al. 2001).
  • With a Gaussian distribution, identity link and only the gene intercepts, GMF reduces to PCA on the centred data.

scRNA-seq implementations:

  • Implementations for scRNA-seq include ZINB-WaVE (Risso et al. 2018), which adds a zero-inflation component, GLM-PCA (Townes et al. 2019) and NewWave (Agostinis et al. 2022). They fit the same type of model, with known covariates of the cells and the genes.

  • They differ in the normalisation: GLM-PCA, e.g., uses the log library size as a fixed offset by default, while omicsGMF estimates an intercept for each cell.

  • omicsGMF (Segers et al. 2025):

hvgSce <- sce[rowData(sce)$hvg, ]
set.seed(1234)
hvgSce <- runGMF(hvgSce, family = poisson(), ncomponents = 10)
reducedDim(sce, "GMF") <- reducedDim(hvgSce, "GMF")

We use the default covariates, i.e. an intercept for each gene and an intercept for each cell, as in the vignettes of omicsGMF. Adding the log library size as offset gives exactly the same latent factors: an offset that is the same for all genes of a cell is absorbed by the cell intercept \(\alpha_i\).

plotDims <- function(dims, color, colorName, title) {
  tibble(dim1 = dims[, 1], dim2 = dims[, 2], color = color) |>
    ggplot(aes(dim1, dim2, color = color)) +
    geom_point(size = 0.3) +
    labs(color = colorName, title = title) +
    theme_bw() +
    theme(legend.text = element_text(size = 6), legend.key.size = unit(0.3, "cm"))
}
plotDims(reducedDim(sce, "PCA"), sce$celltype.published, "Cell type", "PCA") +
  plotDims(reducedDim(sce, "GMF"), sce$celltype.published, "Cell type", "GMF") +
  plot_layout(guides = "collect")

  • Both methods separate the erythroid cells from the other cell types along the first dimension.
  • On these data, with a large sequencing depth per cell, both embeddings look similar in the first two dimensions. The clustering on all components, however, agrees better with the published cell types for GMF than for PCA for most numbers of components (see clustering). The advantages of GMF are largest for sparse data with low counts, where the log transformation and the pseudocount distort the data most (Townes et al. 2019), and when known covariates such as batch have to be corrected for.

How many components should we retain?

  • For PCA, the variance explained by each component gives a scree plot.
  • For GMF, runRankGMF computes the eigenvalues of the residual matrix after fitting the covariates, which also gives a scree plot, and runCVGMF selects the rank by cross-validation: the likelihood of held-out entries of the count matrix is computed for models with an increasing number of components. Cross-validation is the more principled approach, but it requires a model fit for every rank and fold.
set.seed(1234)
rankFit <- runRankGMF(hvgSce, family = poisson(), maxcomp = 30)
tibble(component = 1:30, eigenvalue = metadata(rankFit)$rank_GMF$lambdas[1:30]) |>
  ggplot(aes(component, eigenvalue)) +
  geom_point() +
  geom_line() +
  scale_y_log10() +
  theme_bw()

rm(rankFit)

The eigenvalues drop sharply over the first 4 to 5 components and then decrease slowly. We used 10 components: retaining a few components too many is less harmful for clustering than missing structure.

6.3 t-SNE and UMAP

  • With linear methods, the main structure is captured by a few components, but the cells of many cell types overlap in the first two dimensions.
  • Non-linear methods such as t-SNE and UMAP are therefore used for visualisation. They start from the top PCs (or GMF components) and try to preserve the neighbourhood of each cell in two dimensions.
  • t-SNE and UMAP preserve local structure: cells that are close together have a similar profile. Distances between clusters and the size of clusters, however, cannot be interpreted.
  • The results depend on random initialisation and tuning parameters (e.g. the perplexity of t-SNE and the number of neighbours of UMAP).
  • They are visualisation tools: downstream analyses such as clustering are performed on the PCs or GMF components, not on the t-SNE or UMAP coordinates.

runAllNeighborSteps.se computes the nearest neighbours of each cell once, and uses them for t-SNE and UMAP. It can also cluster the cells, but we do this separately in the next section.

set.seed(1234)
sce <- runAllNeighborSteps.se(sce, cluster.output.name = NULL)
sce <- runAllNeighborSteps.se(sce, reddim.type = "GMF", umap.output.name = "UMAP_GMF",
                              tsne.output.name = NULL, cluster.output.name = NULL)
reducedDimNames(sce)
[1] "PCA"      "GMF"      "TSNE"     "UMAP"     "UMAP_GMF"
plotDims(reducedDim(sce, "UMAP"), sce$celltype.published, "Cell type", "UMAP on PCA") +
  plotDims(reducedDim(sce, "UMAP_GMF"), sce$celltype.published, "Cell type", "UMAP on GMF") +
  plot_layout(guides = "collect")

7 Clustering

We identify groups of cells with a similar expression profile, which we will interpret as cell types or states.

  • Cells of the same type have a similar expression profile, so they are each other’s nearest neighbours in the PC (or GMF) space.
  • Graph-based clustering links every cell to its \(k\) nearest neighbours (here \(k = 10\)), and then looks for groups of cells that are more strongly linked among themselves than with the rest of the cells (Louvain or Leiden algorithm).
  • The number of neighbours sets the granularity: a larger \(k\) gives fewer, larger clusters.
  • There is no “correct” number of clusters. As with a microscope, you choose a magnification: cell types can often be split further into subtypes or states.

See OSCA, chapter 5 for details.

We cluster the cells on the 10 GMF components, and for comparison on the 10 PCs. buildSnnGraph builds the graph of the nearest neighbours and clusterGraph detects the groups with the Louvain algorithm.

sce$clusters <- clusterGraph(buildSnnGraph(t(reducedDim(sce, "GMF")), num.neighbors = 10))$membership
sce$clustersPCA <- clusterGraph(buildSnnGraph(t(reducedDim(sce, "PCA")), num.neighbors = 10))$membership

The number of clusters for different numbers of neighbours:

sapply(c(5, 10, 20, 50), function(k)
  nlevels(clusterGraph(buildSnnGraph(t(reducedDim(sce, "GMF")), num.neighbors = k))$membership)) |>
  setNames(paste0("k = ", c(5, 10, 20, 50)))
 k = 5 k = 10 k = 20 k = 50 
    21     16     12      9 

We compare the clusters of PCA and GMF with the published cell types. Each cell type is labelled in its largest cluster.

labelPlot <- function(dims, group, title, anchor = group, minSize = 1, palette = NULL) {
  df <- tibble(dim1 = dims[, 1], dim2 = dims[, 2], group = group, anchor = anchor)
  # label each group at the median of its cells in its largest anchor group
  centres <- df |>
    filter(!is.na(group)) |>
    group_by(group) |>
    filter(n() >= minSize) |>
    group_by(group, anchor) |>
    mutate(nAnchor = n()) |>
    group_by(group) |>
    filter(nAnchor == max(nAnchor)) |>
    summarise(dim1 = median(dim1), dim2 = median(dim2))
  p <- ggplot(df, aes(dim1, dim2, color = group)) +
    geom_point(size = 0.3, show.legend = FALSE) +
    ggrepel::geom_label_repel(data = centres, aes(label = group), color = "black", size = 2.5,
                              label.padding = unit(0.1, "lines"), alpha = 0.8,
                              max.overlaps = Inf, min.segment.length = 0) +
    labs(title = title) +
    theme_bw()
  if (!is.null(palette)) p <- p + scale_color_manual(values = palette, na.value = "grey80")
  p
}
types <- sort(unique(na.omit(sce$celltype.published)))
typeColors <- colorspace::qualitative_hcl(length(types), palette = "Dark 3")
typeColors <- setNames(typeColors[order(seq_along(types) %% 3)], types)
(labelPlot(reducedDim(sce, "UMAP"), factor(sce$clustersPCA), "PCA: clusters") +
    labelPlot(reducedDim(sce, "UMAP"), sce$celltype.published, "PCA: published cell types",
              anchor = sce$clustersPCA, minSize = 20, palette = typeColors)) /
  (labelPlot(reducedDim(sce, "UMAP_GMF"), factor(sce$clusters), "GMF: clusters") +
     labelPlot(reducedDim(sce, "UMAP_GMF"), sce$celltype.published, "GMF: published cell types",
               anchor = sce$clusters, minSize = 20, palette = typeColors))

We quantify the agreement with the published cell types (without the doublets and stripped nuclei) with

  • the adjusted Rand index (ARI): the agreement between two partitions of the cells, corrected for chance, with 1 for a perfect agreement and 0 for a random clustering, and
  • the purity: the fraction of the cells that belong to the most frequent cell type of their cluster.
ari <- function(a, b) {
  tab <- table(a, b)
  sumPairs <- sum(choose(tab, 2))
  sumA <- sum(choose(rowSums(tab), 2))
  sumB <- sum(choose(colSums(tab), 2))
  expected <- sumA * sumB / choose(sum(tab), 2)
  (sumPairs - expected) / ((sumA + sumB) / 2 - expected)
}
purity <- function(cl, lab) {
  tab <- table(cl, lab)
  sum(apply(tab, 1, max)) / sum(tab)
}
labelled <- !is.na(sce$celltype.published) & !sce$celltype.published %in% c("Doublet", "Stripped")
agreement <- sapply(list(PCA = sce$clustersPCA, GMF = sce$clusters), function(cl)
  c(clusters = nlevels(factor(cl)),
    ARI = ari(cl[labelled], sce$celltype.published[labelled]),
    purity = purity(cl[labelled], sce$celltype.published[labelled])))
round(agreement, 2)
           PCA   GMF
clusters 14.00 16.00
ARI       0.59  0.66
purity    0.68  0.75
  • With 10 components, the clusters of GMF agree better with the published cell types than those of PCA: ARI 0.66 versus 0.59.
  • The number of components is a tuning parameter. In a sensitivity analysis with 5 to 30 components and 10 or 20 neighbours, the clusters of GMF agreed better with the published cell types in most settings, but the difference depends on these choices: it was largest for few components, and small or even reversed for 30 components.
  • In two dimensions, both UMAPs show a similar structure, but the clustering uses all components, where the count model of GMF captures the differences between the cell types better.
  • Note that the published labels are the annotation of the authors, not the ground truth.

In the remainder, we use the clusters of GMF.

table(sce$clusters)

  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16 
198  91  74 274 130 259 227 189  71 121 130 170 196  45  38 184 
tab <- table(cluster = sce$clusters, celltype = sce$celltype.published)
clusterPurity <- apply(tab, 1, max) / rowSums(tab)
as_tibble(tab) |>
  group_by(cluster) |>
  mutate(proportion = n / sum(n)) |>
  ggplot(aes(factor(cluster, levels = sort(unique(sce$clusters))), celltype, fill = proportion)) +
  geom_tile() +
  scale_fill_viridis_c() +
  labs(x = "Cluster", y = "Published cell type") +
  theme_bw()

  • Most clusters are dominated by one published cell type: in 9 of the 16 clusters, more than 80% of the cells have the same label.
  • Some cell types are split into several clusters, e.g. the cells of the forebrain, midbrain and hindbrain.
  • Other clusters combine related cell types, e.g. the erythroid cells at different stages of differentiation and the blood progenitors.
  • This is the granularity of the clustering: it depends on \(k\), and the published annotation is only one possible granularity.

8 Marker genes

To interpret the clusters, we look for marker genes: genes that are highly expressed in one cluster compared to the others.

scoreMarkers.se compares every cluster with every other cluster, and summarises the pairwise effect sizes per gene:

  • Cohen’s d: the difference in mean log-expression divided by the pooled standard deviation.
  • AUC: the probability that a random cell of the cluster has a higher expression than a random cell of the other cluster, i.e. the Wilcoxon-Mann-Whitney statistic divided by the product of the group sizes.
  • Detected: the difference in the proportion of cells with a non-zero count.

The pairwise effects of a gene are summarised by their minimum, mean, median and maximum over all other clusters. A high minimum AUC, e.g., means that the gene is up in the cluster compared to every other cluster. Pairwise comparisons are preferred over a comparison with “all other cells”, whose result depends on the composition of the other cells.

markers <- scoreMarkers.se(sce, sce$clusters)
cl <- names(markers)[1]
markers[[cl]] |>
  as.data.frame() |>
  rownames_to_column("ENSEMBL") |>
  mutate(SYMBOL = rowData(sce)[ENSEMBL, "SYMBOL"]) |>
  arrange(desc(auc.mean)) |>
  dplyr::select(SYMBOL, mean, detected, cohens.d.mean, auc.min, auc.mean) |>
  head(10) |>
  knitr::kable(digits = 2, caption = paste("Top markers of cluster", cl))
Top markers of cluster 1
SYMBOL mean detected cohens.d.mean auc.min auc.mean
Krt18 6.14 1.00 7.92 0.86 0.99
Hand1 4.60 1.00 6.69 0.93 0.98
Krt8 6.06 1.00 7.41 0.85 0.98
Dlk1 5.57 1.00 5.94 0.88 0.98
Steap1 2.67 0.97 3.66 0.97 0.98
Pmp22 5.39 1.00 5.48 0.83 0.98
Serpinh1 6.34 0.99 3.10 0.90 0.98
Ahnak 4.12 0.98 3.90 0.91 0.98
Smoc2 3.25 0.95 3.68 0.92 0.97
Cmtm7 3.66 0.99 3.04 0.92 0.97
top <- rownames(markers[[cl]])[which.max(markers[[cl]]$auc.mean)]
tibble(cluster = factor(sce$clusters), expression = logcounts(sce)[top, ]) |>
  ggplot(aes(cluster, expression)) +
  geom_violin(scale = "width") +
  labs(y = "log-expression", title = rowData(sce)[top, "SYMBOL"]) +
  theme_bw()

8.1 Double dipping

Can we use p-values to select the marker genes?

  • The clusters are defined with the same data, so that the cells are split exactly where the expression differs.
  • A test between clusters is therefore biased: it finds differences, even if there is no structure in the data.

We simulate 500 cells with Poisson counts for 200 genes, all with the same mean: there is no structure at all.

set.seed(1234)
nullCounts <- matrix(rpois(200 * 500, lambda = 5), nrow = 200)
nullLog <- log2(nullCounts + 1)
nullClusters <- kmeans(prcomp(t(nullLog))$x[, 1:5], centers = 2)$cluster
pNull <- apply(nullLog, 1, function(x) t.test(x[nullClusters == 1], x[nullClusters == 2])$p.value)
tibble(p = pNull) |>
  ggplot(aes(p)) +
  geom_histogram(breaks = seq(0, 1, 0.05), color = "black", fill = "grey") +
  labs(x = "p-value", title = "Tests between clusters of null data") +
  theme_bw()

mean(p.adjust(pNull, "BH") < 0.05)
[1] 0.26
  • The p-values are far from uniform: many genes appear to be “markers” between clusters that do not exist.
  • p-values of marker genes are therefore only useful to rank the genes, not for formal inference.
  • Valid inference requires e.g. count splitting (Neufeld et al. 2024): the counts are split into two independent Poisson parts, one to cluster and one to test.
  • Note that this problem does not arise when we compare predefined groups, e.g. treated and untreated samples within a cell type: see the next section.

9 Cell type annotation

Clusters can be annotated manually with known marker genes. Alternatively, cells can be annotated with a labelled reference dataset. SingleR (Aran et al. 2019)

  1. identifies marker genes that discriminate between each pair of cell types in the reference,
  2. calculates, on these marker genes, the Spearman correlation between the expression profile of each query cell and each cell of the reference; the score of a cell type is a high quantile (by default the 80% quantile) of the correlations with the reference cells of that type,
  3. assigns each cell to the cell type with the highest score, after a fine-tuning step: the cell types with a score close to the highest score are retained, new marker genes are selected between these cell types only, and the scores are recomputed.

The reference must be representative: the same tissue and developmental stage, and ideally the same technology. Cell types that are absent in the reference cannot be found. We use a sample of the mouse gastrulation atlas of the same study as reference.

ref <- readRDS("scrnaseqData/embryo_atlas_ref.rds")
ref <- normalizeRnaCounts.se(ref)
pred <- SingleR(sce, ref, labels = ref$celltype,
                assay.type.test = "logcounts", assay.type.ref = "logcounts")
table(pred$pruned.labels, useNA = "ifany") |> sort(decreasing = TRUE) |> head(10)

                  Erythroid3 Forebrain/Midbrain/Hindbrain 
                         314                          250 
                  Mesenchyme                 ExE mesoderm 
                         231                          183 
           Paraxial mesoderm          Pharyngeal mesoderm 
                         168                          149 
                 Spinal cord                          NMP 
                         142                          139 
            Somitic mesoderm                    Allantois 
                         122                           93 
mean(pred$labels == sce$celltype.published, na.rm = TRUE)
[1] 0.7877869
as_tibble(table(cluster = sce$clusters, label = pred$labels)) |>
  group_by(cluster) |>
  mutate(proportion = n / sum(n)) |>
  ggplot(aes(factor(cluster, levels = sort(unique(sce$clusters))), label, fill = proportion)) +
  geom_tile() +
  scale_fill_viridis_c() +
  labs(x = "Cluster", y = "SingleR label") +
  theme_bw()

  • Most clusters get one dominant SingleR label, and clusters that combine related cell types (e.g. the erythroid cells at different stages) also get a mix of the corresponding labels.
  • 79% of the cells with a published label get the same SingleR label. This is not an independent validation: the published labels were themselves obtained by mapping the chimera cells onto the same atlas (celltype.mapped), so both annotations rely on the cell type assignments of the atlas.
  • Reference-based annotation can only be as good as the labels of the reference, and cell types that are absent from the reference cannot be found, e.g. the cells that the authors labelled as doublets or stripped nuclei, and the rare cell types that we removed from the reference.
  • SingleR sets the label of a cell to NA in pruned.labels when the difference between its score for the assigned label and its median score over all labels is unusually small compared with the other cells of that label (more than 3 MADs below their median): 32 cells are ambiguous in this sense.

10 Multi-sample experiments

Most scRNA-seq experiments compare conditions, with cells of several individuals or samples per condition. Two questions are of interest:

  • Differential expression (DE, differential state): does the expression of a gene change between conditions, within a cell type?
  • Differential abundance (DA): does the proportion of a cell type change between conditions?

10.1 Kang data

kang <- readRDS("scrnaseqData/kang.rds")
kang
class: SingleCellExperiment 
dim: 18464 24673 
metadata(2): source reference
assays(1): counts
rownames(18464): RP11-34P13.8 AL627309.1 ... S100B PRMT2
rowData names(2): ENSEMBL SYMBOL
colnames(24673): AAACATACATTTCC-1 AAACATACCAGAAA-1 ... TTTGCATGGGACGA-1
  TTTGCATGTCTTAC-1
colData names(3): patient stim celltype
reducedDimNames(0):
mainExpName: NULL
altExpNames(0):
table(kang$patient, kang$stim)
      
       ctrl stim
  101   858 1166
  107   517  525
  1015 2738 2352
  1016 1723 1635
  1039  461  641
  1244 1879 1464
  1256 2108 2026
  1488 2031 2549
table(kang$celltype)

          B cells   CD14+ Monocytes       CD4 T cells       CD8 T cells 
             2573              5385             10389              2042 
  Dendritic cells FCGR3A+ Monocytes    Megakaryocytes          NK cells 
              432              1599               260              1993 
  • The PBMCs of 8 lupus patients were stimulated with interferon beta (IFN-\(\beta\)) for 6 hours or left untreated (Kang et al. 2018).
  • The cells of the 8 patients were pooled per condition: one pool with all control cells and one pool with all stimulated cells, each processed and sequenced in a separate run.
  • The cells were assigned to their patient with demuxlet, based on their genotype (multiplexing, see above).
  • Each patient contributes cells to both conditions: the patients are blocks, as the cell lines in the airway data.

10.2 Exploration: the cells cluster per condition

We explore the data with the same workflow as before. To keep it fast, we use the library size as size factor.

kangExpl <- normalizeRnaCounts.se(kang, size.factors = colSums(counts(kang)))
kangExpl <- chooseRnaHvgs.se(kangExpl)
kangExpl <- runPca.se(kangExpl, features = rowData(kangExpl)$hvg)
set.seed(1234)
kangExpl <- runAllNeighborSteps.se(kangExpl, tsne.output.name = NULL, cluster.output.name = NULL)
plotDims(reducedDim(kangExpl, "UMAP"), kangExpl$stim, "Condition", "UMAP") +
  plotDims(reducedDim(kangExpl, "UMAP"), kangExpl$celltype, "Cell type", "UMAP")

pcKang <- reducedDim(kangExpl, "PCA")
r2Stim <- sapply(1:5, function(k) summary(lm(pcKang[, k] ~ kangExpl$stim))$r.squared)
round(r2Stim, 2)
[1] 0.04 0.71 0.00 0.00 0.00
  • Every cell type splits into a control and a stimulated cluster: the UMAP is almost a mirror image of itself.
  • The condition explains 71% of the variance of PC2.
  • At first sight, this suggests a huge effect of the stimulation on all cell types.

10.3 Experimental design: condition and run are confounded

  • With genotype-based multiplexing, the control and stimulated cells of the same patient cannot be sequenced in the same run: they have the same genotype, so demuxlet cannot tell them apart.
  • In this experiment, all control cells were therefore sequenced in a first run and all stimulated cells in a second run.
  • The condition is completely confounded with the run (batch): every difference between the conditions is the sum of the effect of IFN-\(\beta\) and the effect of the run (sample preparation, capture, library preparation, sequencing).
  • Multiplexing removes the batch effect between patients: all patients are in the same run, and blocking for the patient is possible. It does not help for the comparison of the conditions.
  • With a single run per condition, the run effect cannot be estimated, and no statistical method can separate it from the effect of the stimulation.

Better designs

  • Balanced genotype multiplexing: run 1 contains the control cells of patients 1–4 and the stimulated cells of patients 5–8, run 2 the stimulated cells of patients 1–4 and the control cells of patients 5–8. Every run contains both conditions, and every patient both runs. The run effect is then estimable and is removed by including it in the model, e.g. ~ patient + run + stim.
  • Cell hashing: the cells of each sample are labelled with an antibody carrying a sample-specific DNA barcode (hashtag) before pooling, so that the control and stimulated cells of the same patient can be sequenced in the same run.
  • More runs, with the conditions randomised over the runs, so that the run becomes a block.

This is the same principle as in the blocking lecture: randomise and block for known sources of variability, and never let a nuisance factor coincide with the factor of interest.

In the remainder, we keep this flaw in mind: the effects of the “stimulation” are the combined effects of IFN-\(\beta\) and the run.

10.4 Batch correction

When samples are processed in different batches, the cells of the same cell type of different batches can form separate clusters, as the control and stimulated cells above. How we deal with the batch depends on the goal of the analysis.

Exploration (visualisation, clustering, annotation) needs coordinates for each cell in which the batch effect is removed:

  • Model-based: GMF can include the batch as a known covariate, \(\log \mu_{gi} = \mathbf{x}_i^T \boldsymbol\beta_g + \alpha_i + \mathbf{u}_i^T \mathbf{v}_g\), with \(\mathbf{x}_i\) the intercept and the batch of cell \(i\) (argument X of runGMF, e.g. model.matrix(~ batch)). Note that X replaces the default intercept, so it has to contain the intercept itself. The latent factors \(\mathbf{u}_i\) then capture the structure that remains after accounting for the batch.
  • Integration: methods such as mutual nearest neighbours (MNN, Haghverdi et al. 2018) or Harmony align the cells of the batches in the PC space. MNN pairs each cell with the cells of the other batch that are among its nearest neighbours, and vice versa. These pairs are assumed to be of the same cell type, and their differences estimate the batch effect, locally in each region of the PC space.

Inference (DE, DA) models the batch: it is included in the design of the pseudobulk model, as we do for the patient. The model estimates the batch effect together with its uncertainty, and the counts remain counts. The clusters or labels of the exploration define which cells form a pseudobulk sample, but the test is performed on the raw counts, not on corrected values.

Batch effects can differ between cell types. A covariate \(\mathbf{x}_i\) for the batch gives each gene one batch effect, which is the same for all cells. We illustrate what this implies on a random subset of 1000 cells of the Kang data, where the condition plays the role of the batch. We remove the effect of the condition

  • with a linear model on the log-normalised expression values, either with one effect per gene for all cells, or with a separate effect per gene in each cell type (using the known cell types, which is not possible in practice), and
  • with GMF, with the condition as covariate (argument X), i.e. with one effect per gene on the log scale of the counts.
set.seed(1234)
cellSub <- sample(ncol(kangExpl), 1000)
hvgKang <- rowData(kangExpl)$hvg
logExpr <- as.matrix(logcounts(kangExpl)[hvgKang, cellSub])
cellInfo <- as.data.frame(colData(kangExpl)[cellSub, c("stim", "celltype")])

# remove the effect of the condition on each gene with a linear model
removeStim <- function(y, info) {
  X <- model.matrix(~ stim, data = info)
  beta <- coef(lm.fit(X, t(y)))
  y - outer(beta["stimstim", ], X[, "stimstim"])
}

# one effect per gene for all cells
logMain <- removeStim(logExpr, cellInfo)

# a separate effect per gene in each cell type
logPerType <- logExpr
for (ct in as.character(unique(cellInfo$celltype))) {
  sel <- cellInfo$celltype == ct
  if (length(unique(cellInfo$stim[sel])) == 2) {
    logPerType[, sel] <- removeStim(logExpr[, sel], cellInfo[sel, ])
  }
}

# GMF on the counts, without and with the condition as covariate
kangSub <- kangExpl[hvgKang, cellSub]
kangSub <- kangSub[rowSums(counts(kangSub)) > 0, ]
set.seed(1234)
gmfNone <- runGMF(kangSub, family = poisson(), ncomponents = 10, exprs_values = "counts")
set.seed(1234)
gmfStim <- runGMF(kangSub, family = poisson(), ncomponents = 10, exprs_values = "counts",
                  X = model.matrix(~ stim, data = cellInfo))

# embeddings with 10 dimensions (dimensions x cells)
embeddings <- list(
  "Linear model: no correction" = runPca(logExpr, number = 10)$components,
  "Linear model: one effect per gene" = runPca(logMain, number = 10)$components,
  "Linear model: one effect per gene and cell type" = runPca(logPerType, number = 10)$components,
  "GMF: no covariate" = t(reducedDim(gmfNone, "GMF")),
  "GMF: one effect per gene" = t(reducedDim(gmfStim, "GMF"))
)

# fraction of the 10 nearest neighbours of a cell with the same condition (0.5: fully mixed)
mixing <- function(emb) {
  nn <- BiocNeighbors::queryKNN(t(emb), t(emb), k = 11)$index[, -1]
  mean(cellInfo$stim[nn] == rep(cellInfo$stim, 10))
}
mixingScores <- sapply(embeddings, mixing)
round(mixingScores, 2)
                    Linear model: no correction 
                                           0.97 
              Linear model: one effect per gene 
                                           0.90 
Linear model: one effect per gene and cell type 
                                           0.54 
                              GMF: no covariate 
                                           0.88 
                       GMF: one effect per gene 
                                           0.68 
umaps <- lapply(embeddings, function(emb) {
  set.seed(1234)
  runUmap(emb)
})
wrap_plots(c(
  lapply(seq_along(umaps), function(i)
    plotDims(umaps[[i]], cellInfo$stim, "Condition", names(umaps)[i]) +
      labs(subtitle = paste("mixing:", round(mixingScores[i], 2))) +
      theme(plot.title = element_text(size = 9))),
  lapply(seq_along(umaps), function(i)
    plotDims(umaps[[i]], cellInfo$celltype, "Cell type", ""))
), nrow = 2, guides = "collect")

The mixing is the fraction of the 10 nearest neighbours of a cell (in the 10-dimensional embedding) that have the same condition, averaged over the cells: 1 when the conditions are completely separated, 0.5 when they are fully mixed.

  • With one effect per gene in the linear model, the separation between the conditions decreases, but most cell types are still split into a control and a stimulated cluster (mixing 0.9).
  • Only when the effect is removed separately in each cell type, the control and stimulated cells of each cell type overlap (mixing 0.54). This requires the cell types, which are unknown at this stage, as the cell types are what we want to find.
  • With one effect per gene in GMF, the conditions are much better mixed (mixing 0.68), while the cell types remain separated.
  • A plausible explanation: the linear model works on \(\log(y/s + 1)\). A fold change that is the same in all cells becomes, on this scale, a shift that depends on the expression level of the cell, because the pseudocount compresses the low counts. One effect per gene on the log-normalised scale can therefore not remove a constant fold change, and part of the “cell-type-specific” effect is an artifact of the transformation. GMF models the counts with a log link, so that a constant fold change is one effect per gene.
  • Still, a batch covariate in GMF or in a linear model only removes the part of the batch effect that is shared by all cells: the mixing remains above 0.5.
  • Removing a genuinely cell-type-specific part requires an interaction with the cell type.
  • However, this is not possible in practice as the cell-types are typically unknown at this stage.
  • Integration methods such as MNN correct locally, and can therefore also remove batch effects that differ between cell types.

Pitfalls

  • Integration methods assume that the batches contain (largely) the same cell types in the same states. They can therefore also remove genuine biological differences between batches (overcorrection).
  • Batch correction cannot rescue a design in which the batch is confounded with the condition.
  • In the Kang data, the corrected embeddings look like a successful correction, but they remove the effect of the run and the effect of IFN-\(\beta\), as both cannot be distinguished.
  • Including the run in the pseudobulk model is impossible for the same reason: the run and condition columns of the design matrix are identical.
  • For the annotation of the cell types, aligning the conditions can still be useful: the same cell types are then found in both conditions, and the effect of the condition is assessed afterwards with the pseudobulk analysis.

10.5 Pseudoreplication

Image credit: Milan Malfait
  • The cells are nested in patients: cells of the same patient are correlated.
  • The experimental unit for the comparison of conditions is the patient sample, not the cell. Treating cells as independent replicates is pseudoreplication, as the technical repeats of the mixed models lecture.
  • With thousands of cells per sample, the standard errors are severely underestimated, and many false positives arise.

We illustrate this with the CD14+ monocytes of the untreated cells, which were all sequenced in the same run. We randomly split the 8 patients in two groups of 4: there is no true difference between the groups.

mono <- kang[, kang$celltype == "CD14+ Monocytes" & kang$stim == "ctrl"]
set.seed(1234)
groupA <- sample(levels(mono$patient), 4)
mono$group <- factor(ifelse(mono$patient %in% groupA, "A", "B"))
table(mono$patient, mono$group)
      
         A   B
  101    0 202
  107  209   0
  1015   0 779
  1016 369   0
  1039 126   0
  1244 415   0
  1256   0 390
  1488   0 295

Cells as replicates: the edgeR QL pipeline on the counts of all cells, with the library size of each cell as offset. We only keep genes that are detected in more than 10% of the cells.

keepGenes <- rowMeans(counts(mono) > 0) > 0.1
yCells <- DGEList(counts(mono)[keepGenes, ], lib.size = colSums(counts(mono)))
fitCells <- glmQLFit(yCells, model.matrix(~ group, data = colData(mono)))
resCells <- glmQLFTest(fitCells, coef = "groupB")
summary(decideTests(resCells))
       groupB
Down      218
NotSig   1331
Up        110

Pseudobulk: the counts of all cells of a patient are summed, and the pseudobulk samples are analysed with the same edgeR QL pipeline.

pbMono <- aggregateAcrossCells.se(mono, factors = list(patient = mono$patient))
yMono <- DGEList(assay(pbMono, "sums"),
                 samples = data.frame(group = mono$group[match(pbMono$patient, mono$patient)]))
yMono <- yMono[filterByExpr(yMono, group = yMono$samples$group), , keep.lib.sizes = FALSE]
yMono <- normLibSizes(yMono)
fitMono <- glmQLFit(yMono, model.matrix(~ group, data = yMono$samples))
resMono <- glmQLFTest(fitMono, coef = "groupB")
summary(decideTests(resMono))
       groupB
Down        0
NotSig   3758
Up          0
  • When cells are treated as replicates, 328 genes are “differentially expressed” between two random groups of patients: the differences between patients are mistaken for differences between the groups.
  • The pseudobulk analysis correctly finds no or hardly any DE genes.
  • Both analyses use the same model: only the experimental unit differs. With cells as replicates, the dispersion only captures the variability between the cells of the same patient, not the variability between patients.
  • This does not depend on the random split: over all 35 splits of the 8 patients in two groups of 4, the analysis of the cells finds between 186 and 501 DE genes, the pseudobulk analysis none in 33 splits.
  • The same happens with tests on the log-normalised counts of the cells, e.g. t-tests or Wilcoxon tests, which are common in single-cell workflows.

Crowell et al., 2020, doi: 10.1038/s41467-020-19894-4

Squair et al., 2021, doi: 10.1038/s41467-021-25960-2
  • Benchmarks confirm that pseudobulk methods control the false discovery rate and are among the most powerful methods (Crowell et al. 2020; Squair et al. 2021; Junttila et al. 2022).
  • Mixed models with a random effect for the patient are an alternative, but they are computationally much more demanding and not more powerful.

10.6 Differential expression between conditions

For each cell type, we sum the counts of the cells per patient and condition, and analyse the pseudobulk samples with the edgeR QL pipeline.

pb <- aggregateAcrossCells.se(kang, factors = list(celltype = kang$celltype,
                                                   patient = kang$patient,
                                                   stim = kang$stim),
                              counts.name = "ncells")
pb
class: SummarizedExperiment 
dim: 18464 128 
metadata(1): aggregated
assays(2): sums detected
rownames(18464): RP11-34P13.8 AL627309.1 ... S100B PRMT2
rowData names(2): ENSEMBL SYMBOL
colnames: NULL
colData names(7): factor.celltype factor.patient ... stim celltype
summary(pb$ncells)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   4.00   31.75  106.00  192.76  228.75 1484.00 

Every pseudobulk sample consists of 4 to 1484 cells. As in the airway data, we block for the patient:

\[ \log \mu_{gpc} = \beta_{g0} + \beta_{g,p} + \beta_{g,\text{stim}}\, x_{c} + \log(s_{pc} N_{pc}), \]

with \(p\) the patient, \(c\) the condition and \(x_c\) an indicator for the stimulated cells. Because of the confounding, \(\beta_{g,\text{stim}}\) estimates the sum of the effect of IFN-\(\beta\) and the effect of the run.

pseudobulkDE <- function(celltype) {
  sel <- pb$celltype == celltype
  y <- DGEList(assay(pb, "sums")[, sel],
               samples = as.data.frame(colData(pb)[sel, c("patient", "stim", "ncells")]))
  y <- y[filterByExpr(y, group = y$samples$stim), , keep.lib.sizes = FALSE]
  y <- normLibSizes(y)
  design <- model.matrix(~ patient + stim, data = y$samples)
  fit <- glmQLFit(y, design)
  glmQLFTest(fit, coef = "stimstim")
}
deResults <- lapply(setNames(levels(kang$celltype), levels(kang$celltype)), pseudobulkDE)
sapply(deResults, function(res) summary(decideTests(res))[, 1]) |>
  t() |>
  knitr::kable(caption = "Number of DE genes (FDR 5%) per cell type")
Number of DE genes (FDR 5%) per cell type
Down NotSig Up
B cells 242 1250 323
CD14+ Monocytes 1348 1141 1162
CD4 T cells 664 3403 728
CD8 T cells 94 593 134
Dendritic cells 160 605 218
FCGR3A+ Monocytes 482 891 575
Megakaryocytes 3 189 15
NK cells 205 921 256
topTags(deResults[["CD14+ Monocytes"]], n = 10)$table |>
  dplyr::select(logFC, logCPM, F, FDR) |>
  knitr::kable(digits = 3, caption = "CD14+ Monocytes")
CD14+ Monocytes
logFC logCPM F FDR
NCOA7 6.602 5.641 549.575 0
NEXN 6.597 6.168 524.133 0
CD38 7.123 7.423 719.385 0
HESX1 8.518 6.734 522.651 0
IFITM1 6.059 6.289 581.385 0
NT5C3A 5.716 8.286 1298.794 0
NUPR1 8.103 6.308 487.168 0
C19orf59 -4.877 6.366 897.918 0
SAMD4A 5.799 5.678 391.842 0
SOCS1 4.296 6.892 942.598 0
  • Many genes differ between the conditions in most cell types. The number of DE genes is much smaller for cell types with few cells, e.g. the megakaryocytes: their pseudobulk samples have low counts, so that fewer genes pass the filter and the power is lower.
  • The top genes of the CD14+ monocytes include interferon-stimulated genes such as IFITM1, CD38 and SOCS1. This is prior knowledge that supports a genuine response to IFN-\(\beta\).
  • The design, however, does not allow to attribute the individual DE genes, or the number of DE genes, to the stimulation: each of them can equally well be a run effect.
  • With many DE genes, TREAT (glmTreat) can be used to focus on large fold changes.
  • The analysis per cell type allows to find cell-type-specific responses.

A formal test of whether the response differs between cell types would require a model with a cell type \(\times\) condition interaction on the pseudobulk samples of all cell types.

  • Such a model assumes that the variability between patients is the same in all cell types, which is often not the case, e.g. because the pseudobulk samples of different cell types consist of very different numbers of cells.
  • Pseudobulk workflows such as muscat (Crowell et al. 2020) therefore analyse each cell type separately.

10.7 Differential detection

  • Pseudobulk DE analyses test for changes in the mean expression.
  • However, the distribution of the gene expression can also change in other aspects.
  • With the low counts of scRNA-seq data, whether a gene is detected in a cell at all is also informative.
  • Note, that methods exists for assessing differential distributions, i.e. differences in location and shape.
  • Here, we will focus on one specific modality, i.e. differential detection.

Gilis et al. (2025) show that changes in the average fraction of cells in which a gene is detected (differential detection, DD) provide information that is complementary to DE.

Data: we binarise the counts (\(z_{gi} = 1\) if \(y_{gi} > 0\)) and sum them per sample: \(Z_{gs} = \sum_{i \in s} z_{gi}\) is the number of cells of sample \(s\) in which gene \(g\) is detected, out of \(n_s\) cells. We do not have to compute this ourselves: aggregateAcrossCells.se stores \(Z_{gs}\) in the assay detected of the pseudobulk object pb, next to the summed counts (assay sums) that we used for DE. DE and DD thus start from the same pseudobulk samples, but summarise the cells differently: the total number of UMIs versus the number of cells with at least one UMI.

Model: the same NB GLM with the edgeR QL pipeline,

\[ \log \text{E}[Z_{gs}] = \mathbf{x}_s^\top \boldsymbol\beta_g + \log(n_s \, \text{CDR}_s), \]

  • The offset contains the number of cells \(n_s\): we model the fraction of cells in which the gene is detected, as the library size in the DE analysis.
  • \(\text{CDR}_s\) is the cellular detection rate of the sample: the average fraction of cells in which a gene is detected. It corrects for global differences in detection, e.g. due to the sequencing depth, as the normalisation factors in the DE analysis.
  • Genes detected in (almost) all cells carry no information on detection: genes with a median detection fraction of 0.9 or more over the samples are removed.
  • The binarised counts are bounded by \(n_s\), so they can be underdispersed with respect to the Poisson distribution: the QL test is performed with poisson.bound = FALSE.

This is the workflow edgeR_NB_optim of Gilis et al. (2025), which performed best in their benchmarks. We use it for the CD14+ monocytes, on the genes of the DE analysis.

selDD <- pb$celltype == "CD14+ Monocytes"
# number of cells of each sample in which each gene is detected
Z <- assay(pb, "detected")[, selDD]
nCells <- pb$ncells[selDD]

deMono <- deResults[["CD14+ Monocytes"]]
detection <- sweep(Z, 2, nCells, "/")
medDetection <- matrixStats::rowMedians(as.matrix(detection[rownames(deMono), ]))
keepDD <- rownames(deMono)[medDetection < 0.9]
cdr <- colMeans(detection[keepDD, ])

yDD <- DGEList(Z[keepDD, ],
               samples = as.data.frame(colData(pb)[selDD, c("patient", "stim", "ncells")]))
yDD$offset <- log(nCells * cdr)
designDD <- model.matrix(~ patient + stim, data = yDD$samples)
yDD <- estimateDisp(yDD, designDD)
fitDD <- glmQLFit(yDD, designDD, robust = TRUE)
ddMono <- glmQLFTest(fitDD, coef = "stimstim", poisson.bound = FALSE)
summary(decideTests(ddMono))
       stimstim
Down       1828
NotSig      853
Up          910

Stage-wise testing of DE and DD

With two hypotheses per gene, we control the FDR at the gene level with stage-wise testing:

  1. Screening: the null hypothesis that neither the mean expression nor the detection changes. We combine the DE and DD p-values with the harmonic mean, \(p_g = 2 / (1/p_g^{DE} + 1/p_g^{DD})\), which is also valid for dependent tests (Wilson 2019). Genes that were removed from the DD analysis get their DE p-value.
  2. Confirmation: the DE and DD hypotheses of the genes that pass the screening. Once the screening null hypothesis is rejected, at most one of the two hypotheses can be true, so Shaffer’s method requires no further correction (shafferS1(diag(2)) returns 1 1, method = "none").
pDE <- setNames(deMono$table$PValue, rownames(deMono))
pDD <- setNames(rep(NA, length(pDE)), names(pDE))
pDD[rownames(ddMono)] <- ddMono$table$PValue
pScreen <- ifelse(is.na(pDD), pDE, 2 / (1 / pDE + 1 / pDD))

stageRObj <- stageR(pScreen = pScreen, pConfirmation = cbind(DD = pDD, DE = pDE),
                    pScreenAdjusted = FALSE)
stageRObj <- stageWiseAdjustment(stageRObj, method = "none", alpha = 0.05, allowNA = TRUE)
ddDe <- getResults(stageRObj)
table(DD = ddDe[, "DD"], DE = ddDe[, "DE"])
   DE
DD     0    1
  0  733  245
  1  420 2253
tibble(gene = rownames(ddMono),
       logFC_DE = deMono$table[rownames(ddMono), "logFC"],
       logFC_DD = ddMono$table$logFC,
       DE = ddDe[rownames(ddMono), "DE"] == 1,
       DD = ddDe[rownames(ddMono), "DD"] == 1) |>
  mutate(significant = case_when(DE & DD ~ "DE and DD", DE ~ "DE only",
                                 DD ~ "DD only", TRUE ~ "none")) |>
  ggplot(aes(logFC_DE, logFC_DD, color = significant)) +
  geom_point(size = 0.5) +
  geom_abline(linetype = 2) +
  labs(x = "log fold change DE", y = "log fold change DD", color = "") +
  theme_bw()

  • The log fold changes of DE and DD are strongly correlated: for most genes, a change in mean expression goes together with a change in detection.
  • Still, 420 genes are only found in the DD analysis, and 245 only in the DE analysis: both analyses provide complementary information, and Gilis et al. (2025) recommend to perform both.
  • The DD log fold changes are relative to the CDR of the sample, and are interpreted as the change in the detection fraction compared to an average gene.
  • The confounding with the run also applies here: e.g. differences in capture efficiency between the runs affect the detection of genes. The CDR offset is one factor per sample: it corrects for differences in detection that affect all genes equally, but not for technical differences that affect genes differently, e.g. because the detection of lowly and highly expressed genes responds differently to the capture efficiency.

All cell types with muscat

We analysed DD for one cell type, to show the model. The muscat package (Crowell et al. 2020) implements the same pseudobulk workflows, and performs the DE and DD analyses for all cell types in one call:

  • aggregateData() sums the counts (fun = "sum") or the binarised counts (fun = "num.detected") per cell type and sample, as the sums and detected assays of pb. The result contains one assay per cell type.
  • pbDS() performs the pseudobulk DE analysis with the edgeR QL pipeline, and pbDD() the DD analysis with the workflow above: the filter on the median detection fraction, the CDR offset, and poisson.bound = FALSE. Before that, pbDD() filters the genes with filterByExpr on the number of detected cells, so it can test a slightly different set of genes than we did. Both fit a separate model for each cell type, and return one table of results per cell type. The p-values are adjusted for multiple testing within each cell type (p_adj.loc) and over all cell types together (p_adj.glb).
  • stagewise_DS_DD() combines the DE and DD results of each cell type with the stage-wise test of this section.
  • Cell types with too few cells per sample are skipped (argument min_cells).

The DD vignette of muscat illustrates this on the same Kang data, with the default design ~ group_id. To block for the patient, as we did, pass a design matrix:

sce <- kang
sce$id <- paste0(sce$stim, sce$patient)
sce <- muscat::prepSCE(sce, kid = "celltype", sid = "id", gid = "stim")
pbSum <- muscat::aggregateData(sce, assay = "counts", fun = "sum")
pbDet <- muscat::aggregateData(sce, assay = "counts", fun = "num.detected")
design <- model.matrix(~ patient + group_id, data = as.data.frame(colData(pbDet)))
resDS <- muscat::pbDS(pbSum, design = design, coef = ncol(design))
resDD <- muscat::pbDD(pbDet, design = design, coef = ncol(design))
resStagewise <- muscat::stagewise_DS_DD(resDS, resDD)
# results for one cell type
resStagewise[[1]][["CD14+ Monocytes"]]

10.8 Differential abundance

Does the composition of the PBMCs change upon stimulation? We count the cells per cell type and sample, and model these counts with the same NB GLM.

abundances <- table(kang$celltype, interaction(kang$patient, kang$stim, sep = "_"))
abundanceSamples <- tibble(sample = colnames(abundances)) |>
  separate(sample, c("patient", "stim"), sep = "_", remove = FALSE) |>
  mutate(patient = factor(patient), stim = factor(stim, levels = c("ctrl", "stim")))
yDA <- DGEList(unclass(abundances), samples = as.data.frame(abundanceSamples))
designDA <- model.matrix(~ patient + stim, data = yDA$samples)
fitDA <- glmQLFit(yDA, designDA)
topTags(glmQLFTest(fitDA, coef = "stimstim"))$table |>
  knitr::kable(digits = 3)
logFC logCPM F PValue FDR
NK cells 0.246 16.290 11.130 0.002 0.012
FCGR3A+ Monocytes 0.187 16.041 5.444 0.023 0.093
CD8 T cells -0.147 16.353 4.152 0.046 0.103
CD14+ Monocytes -0.079 17.836 3.956 0.052 0.103
Dendritic cells 0.126 14.253 1.151 0.288 0.461
B cells -0.051 16.596 0.638 0.428 0.570
Megakaryocytes 0.046 13.691 0.108 0.743 0.849
CD4 T cells 0.000 18.640 0.000 0.992 0.992
  • Only the proportion of NK cells changes significantly, and the fold change is small. The composition of the PBMCs hardly changes between the conditions, as expected after only 6 hours.
  • Again, the change in NK cells cannot be attributed to the stimulation: the cell type proportions can also differ between runs, e.g. because cell types differ in how well they survive the sample preparation or are captured in the droplets.
  • The library size is the total number of cells of a sample: the model describes the proportion of each cell type.
  • The proportions are compositional: if one cell type increases, the proportions of all other cell types decrease. A change in one cell type therefore shows up as a change in the opposite direction in all other cell types.
  • TMM normalisation assumes that most cell types do not change. With only a few cell types this is a strong assumption. Alternatively, TREAT can be used to focus on large changes, which are unlikely to be due to a compositional effect of another cell type.
  • Here, the cell types were annotated after the stimulation: the stimulation can change the expression of the marker genes, and thus the labels.
  • A large literature exists on addressing compositionality, which is beyond the scope of the course.

11 Summary

  • Droplet-based scRNA-seq data are low counts with many zeros. After removal of empty droplets, low-quality cells and doublets, they are well described by Poisson and NB models: no zero inflation is needed.
  • The concepts of the bulk RNA-seq lectures carry over: offsets for the library size, deviances for feature selection, and GLMs with a low-rank term for dimension reduction (GMF).
  • Clustering and marker gene detection are exploratory: the p-values of tests between clusters are not valid, because the data are used twice.
  • In multi-sample experiments, the experimental unit is the sample, not the cell. Pseudobulk analyses with the edgeR QL pipeline control the FDR for differential expression between conditions, and allow to block for the individual.
  • Differential detection, a pseudobulk analysis of the binarised counts, provides information that is complementary to DE; both can be combined with stage-wise testing.
  • The cell counts per cell type and sample can be analysed with the same NB GLMs for differential abundance, keeping their compositional nature in mind.
  • Batch effects are removed for exploration (GMF with a batch covariate, or integration methods such as MNN for batch effects that differ between cell types), but modelled for inference (the batch in the pseudobulk design).
  • Experimental design remains crucial: multiplexing removes batch effects between individuals, but conditions that are processed in separate runs are confounded with the run. Neither batch correction nor modelling can repair this afterwards.

References

Agostinis, Federico, Chiara Romualdi, Gabriele Sales, and Davide Risso. 2022. “NewWave: A Scalable R/Bioconductor Package for the Dimensionality Reduction and Batch Effect Removal of Single-Cell RNA-seq Data.” Bioinformatics 38 (9): 2648–50. https://doi.org/10.1093/bioinformatics/btac149.
Amezquita, Robert A., Aaron T. L. Lun, Etienne Becht, et al. 2020. “Orchestrating Single-Cell Analysis with Bioconductor.” Nature Methods 17: 137–45. https://doi.org/10.1038/s41592-019-0654-x.
Aran, Dvir, Agnieszka P. Looney, Leqian Liu, et al. 2019. “Reference-Based Analysis of Lung Single-Cell Sequencing Reveals a Transitional Profibrotic Macrophage.” Nature Immunology 20: 163–72. https://doi.org/10.1038/s41590-018-0276-y.
Bourgon, Richard, Robert Gentleman, and Wolfgang Huber. 2010. “Independent Filtering Increases Detection Power for High-Throughput Experiments.” Proceedings of the National Academy of Sciences 107 (21): 9546–51.
Castiglione, Cristian, Alexandre Segers, Lieven Clement, and Davide Risso. 2026. “Stochastic Gradient Descent Estimation of Generalized Matrix Factorization Models with Application to Single-Cell RNA Sequencing Data.” Biostatistics 27 (1): kxag010. https://doi.org/10.1093/biostatistics/kxag010.
Collins, Michael, Sanjoy Dasgupta, and Robert E. Schapire. 2001. “A Generalization of Principal Components Analysis to the Exponential Family.” Advances in Neural Information Processing Systems 14, 617–24.
Crowell, Helena L., Charlotte Soneson, Pierre-Luc Germain, et al. 2020. “Muscat Detects Subpopulation-Specific State Transitions from Multi-Sample Multi-Condition Single-Cell Transcriptomics Data.” Nature Communications 11: 6077. https://doi.org/10.1038/s41467-020-19894-4.
Germain, Pierre-Luc, Aaron Lun, Carlos Garcia Meixide, Will Macnair, and Mark D. Robinson. 2021. “Doublet Identification in Single-Cell Sequencing Data Using scDblFinder.” F1000Research 10: 979. https://doi.org/10.12688/f1000research.73600.2.
Gilis, Jeroen, Laura Perin, Milan Malfait, et al. 2025. “Differential Detection Workflows for Multi-Sample Single-Cell RNA-seq Data.” BMC Genomics 26: 886. https://doi.org/10.1186/s12864-025-12102-x.
Haghverdi, Laleh, Aaron T. L. Lun, Michael D. Morgan, and John C. Marioni. 2018. “Batch Effects in Single-Cell RNA-Sequencing Data Are Corrected by Matching Mutual Nearest Neighbors.” Nature Biotechnology 36: 421–27. https://doi.org/10.1038/nbt.4091.
Junttila, Sini, Johannes Smolander, and Laura L. Elo. 2022. “Benchmarking Methods for Detecting Differential States Between Conditions from Multi-Subject Single-Cell RNA-seq Data.” Briefings in Bioinformatics 23 (5): bbac286. https://doi.org/10.1093/bib/bbac286.
Kang, Hyun Min, Meena Subramaniam, Sasha Targ, et al. 2018. “Multiplexed Droplet Single-Cell RNA-Sequencing Using Natural Genetic Variation.” Nature Biotechnology 36: 89–94. https://doi.org/10.1038/nbt.4042.
Lause, Jan, Philipp Berens, and Dmitry Kobak. 2021. “Analytic Pearson Residuals for Normalization of Single-Cell RNA-seq UMI Data.” Genome Biology 22: 258. https://doi.org/10.1186/s13059-021-02451-7.
Lun, Aaron T. L., Karsten Bach, and John C. Marioni. 2016. “Pooling Across Cells to Normalize Single-Cell RNA Sequencing Data with Many Zero Counts.” Genome Biology 17: 75. https://doi.org/10.1186/s13059-016-0947-7.
Lun, Aaron T. L., Samantha Riesenfeld, Tallulah Andrews, et al. 2019. “EmptyDrops: Distinguishing Cells from Empty Droplets in Droplet-Based Single-Cell RNA Sequencing Data.” Genome Biology 20: 63. https://doi.org/10.1186/s13059-019-1662-y.
Neufeld, Anna, Lucy L. Gao, Joshua Popp, Alexis Battle, and Daniela Witten. 2024. “Inference After Latent Variable Estimation for Single-Cell RNA Sequencing Data.” Biostatistics 25 (1): 270–87. https://doi.org/10.1093/biostatistics/kxac047.
Pijuan-Sala, Blanca, Jonathan A. Griffiths, Carolina Guibentif, et al. 2019. “A Single-Cell Molecular Map of Mouse Gastrulation and Early Organogenesis.” Nature 566: 490–95. https://doi.org/10.1038/s41586-019-0933-9.
Risso, Davide, Fanny Perraudeau, Svetlana Gribkova, Sandrine Dudoit, and Jean-Philippe Vert. 2018. “A General and Flexible Method for Signal Extraction from Single-Cell RNA-seq Data.” Nature Communications 9: 284. https://doi.org/10.1038/s41467-017-02554-5.
Segers, Alexandre, Cristian Castiglione, Christophe Vanderaa, et al. 2025. “omicsGMF: A Multi-Tool for Dimensionality Reduction, Batch Correction and Imputation Applied to Bulk- and Single Cell Proteomics Data.” bioRxiv, March, 2025.03.24.644996.
Squair, Jordan W., Matthieu Gautier, Claudia Kathe, et al. 2021. “Confronting False Discoveries in Single-Cell Differential Expression.” Nature Communications 12: 5692. https://doi.org/10.1038/s41467-021-25960-2.
Svensson, Valentine. 2020. “Droplet scRNA-seq Is Not Zero-Inflated.” Nature Biotechnology 38: 147–50. https://doi.org/10.1038/s41587-019-0379-5.
Townes, F. William, Stephanie C. Hicks, Martin J. Aryee, and Rafael A. Irizarry. 2019. “Feature Selection and Dimension Reduction for Single-Cell RNA-Seq Based on a Multinomial Model.” Genome Biology 20: 295. https://doi.org/10.1186/s13059-019-1861-6.
Wilson, Daniel J. 2019. “The Harmonic Mean p-Value for Combining Dependent Tests.” Proceedings of the National Academy of Sciences 116 (4): 1195–200. https://doi.org/10.1073/pnas.1814092116.