library(Seurat)
library(dplyr)
library(ggplot2)
library(here)1 The reference, the query and the question
If you took my scRNA-seq course, you annotated cells in chapter 4 with two Seurat functions, FindTransferAnchors() and TransferData(). They worked. But what do they do with your data? In this course we open those two functions and rebuild every step from scratch, on two public datasets. This first lesson gets the two datasets ready.
In this lesson
- Meet the query, 2,700 blood cells, and process it the routine way.
- Meet the reference, 9,432 blood cells with 13 labels, stored in an old Seurat object.
- Look at what is already inside the reference: its normalization, its scaled data and its PCA.
- Keep the genes the two datasets share, and see what that leaves of the reference.
- Save both objects for the rest of the course.
1.1 The question
You have a reference: cells that someone has already annotated, one label per cell. You have a query: new cells without labels. Label transfer gives every query cell a label from the reference.
First, both datasets have to live in the same space, so that “close” means “similar”. Seurat has two ways to get there. It can compute a PCA of the reference and project the query onto those PCs (reduction = "pcaproject", the default), or it can run a CCA on the two datasets together (reduction = "cca"). Once the cells share a space, a query cell takes the labels of the reference cells closest to it.
Load the libraries.
1.2 The query: PBMC 3k
Our query is the 3k PBMC data from 10x Genomics, 3k PBMCs from a Healthy Donor, the dataset of Seurat’s PBMC 3k tutorial.
Both files of this course are public. You need R with Seurat 5, dplyr, ggplot2 and here, and an RStudio project so that here() finds your folder. Then run this once from the project to put the two files in data/ (182 MB together):
dir.create("data", showWarnings = FALSE)
options(timeout = 3600)
for (f in c("pbmc3k_raw.rds", "pbmc_10k_v3.rds")) {
download.file(paste0("https://learn.chatomics.com/data/pcacca/", f),
file.path("data", f), mode = "wb")
}Now the query:
pbmc3k <- readRDS(here("data/pbmc3k_raw.rds"))
pbmc3k
#> An object of class Seurat
#> 13714 features across 2700 samples within 1 assay
#> Active assay: RNA (13714 features, 0 variable features)
#> 2 layers present: counts, data13,714 genes and 2,700 cells. The object has two layers, counts and data, but nothing has been done to it yet:
identical(LayerData(pbmc3k, layer = "counts"), LayerData(pbmc3k, layer = "data"))
#> [1] TRUEdata is a copy of the raw counts, so we will normalize it ourselves. Now the metadata:
head(pbmc3k@meta.data)
#> orig.ident nCount_RNA nFeature_RNA seurat_annotations
#> AAACATACAACCAC pbmc3k 2419 779 Memory CD4 T
#> AAACATTGAGCTAC pbmc3k 4903 1352 B
#> AAACATTGATCAGC pbmc3k 3147 1129 Memory CD4 T
#> AAACCGTGCTTCCG pbmc3k 2639 960 CD14+ Mono
#> AAACCGTGTATGCG pbmc3k 980 521 NK
#> AAACGCACTGGTAC pbmc3k 2163 781 Memory CD4 T
table(pbmc3k$seurat_annotations, useNA = "ifany")
#>
#> Naive CD4 T Memory CD4 T CD14+ Mono B CD8 T FCGR3A+ Mono
#> 697 483 480 344 271 162
#> NK DC Platelet <NA>
#> 155 32 14 62The pbmc3k dataset comes with annotations, the seurat_annotations column: 9 cell types, plus 62 cells without a label (NA). In this course we will pretend we do not have it and use the 10k data to transfer the labels. It comes back in lesson 3, to check our labels.
Routine processing, the usual Seurat steps:
pbmc3k <- pbmc3k %>%
NormalizeData(normalization.method = "LogNormalize", scale.factor = 10000) %>%
FindVariableFeatures(selection.method = "vst", nfeatures = 3000) %>%
ScaleData() %>%
RunPCA(verbose = FALSE) %>%
FindNeighbors(dims = 1:10, verbose = FALSE) %>%
FindClusters(resolution = 0.5, verbose = FALSE) %>%
RunUMAP(dims = 1:10, verbose = FALSE)Let’s get an idea of what the 3k data look like.
p1 <- DimPlot(pbmc3k, reduction = "umap", label = TRUE, group.by = "RNA_snn_res.0.5")
p2 <- DimPlot(pbmc3k, reduction = "umap", label = TRUE, group.by = "seurat_annotations", label.size = 3)
p1 + p2
table(pbmc3k$RNA_snn_res.0.5)
#>
#> 0 1 2 3 4 5 6 7 8
#> 684 492 427 384 350 161 154 35 13Resolution 0.5 gives 9 clusters, from 684 cells in cluster 0 down to 13 in cluster 8. They line up with the annotation pretty well: cluster 4 is the B cells and cluster 8 the platelets, for example.
1.3 The reference: PBMC 10k
The reference is the 10k PBMC data from 10x Genomics, 10k PBMCs from a Healthy Donor (v3 chemistry), as an annotated Seurat object: the file the Seurat vignettes used, and the one my blog post downloaded. The two datasets are separate 10x experiments; the 10k one was made with the newer v3 chemistry and a newer Cell Ranger.
pbmc10k <- readRDS(here("data/pbmc_10k_v3.rds"))
pbmc10k@version
#> [1] '3.0.0.9000'
pbmc10k <- UpdateSeuratObject(pbmc10k)
pbmc10k
#> An object of class Seurat
#> 19089 features across 9432 samples within 1 assay
#> Active assay: RNA (19089 features, 3000 variable features)
#> 3 layers present: counts, data, scale.data
#> 3 dimensional reductions calculated: pca, tsne, umapThe object was saved with Seurat 3.0 (version 3.0.0.9000). It lacks slots that Seurat 5 expects, and without UpdateSeuratObject() even rownames(pbmc10k) fails.
After the update we have 19,089 genes, 9,432 cells and 3,000 variable features, with three layers (counts, data, scale.data) and three dimensional reductions (pca, tsne, umap).
head(pbmc10k@meta.data)
#> orig.ident nCount_RNA nFeature_RNA observed simulated
#> rna_AAACCCAAGCGCCCAT-1 10x_RNA 2204 1087 0.035812672 0.4382022
#> rna_AAACCCACAGAGTTGG-1 10x_RNA 5884 1836 0.019227034 0.1017964
#> rna_AAACCCACAGGTATGG-1 10x_RNA 5530 2216 0.005447865 0.1392801
#> rna_AAACCCACATAGTCAC-1 10x_RNA 5106 1615 0.014276003 0.4949495
#> rna_AAACCCACATCCAATG-1 10x_RNA 4572 1800 0.053857351 0.1392801
#> rna_AAACCCAGTGGCTACC-1 10x_RNA 6702 1965 0.056603774 0.3554328
#> percent.mito RNA_snn_res.0.4 celltype
#> rna_AAACCCAAGCGCCCAT-1 0.02359347 1 CD4 Memory
#> rna_AAACCCACAGAGTTGG-1 0.10757988 0 CD14+ Monocytes
#> rna_AAACCCACAGGTATGG-1 0.07848101 5 NK cell
#> rna_AAACCCACATAGTCAC-1 0.10830396 3 pre-B cell
#> rna_AAACCCACATCCAATG-1 0.08989501 5 NK cell
#> rna_AAACCCAGTGGCTACC-1 0.06326470 1 CD4 Memory
table(pbmc10k$celltype)
#>
#> Platelets CD14+ Monocytes CD4 Memory
#> 52 2992 1596
#> CD4 Naive pre-B cell Double negative T cell
#> 1047 959 592
#> NK cell B cell progenitor CD8 effector
#> 544 460 383
#> CD8 Naive CD16+ Monocytes Dendritic cell
#> 337 328 74
#> pDC
#> 68The labels are in the celltype column: 13 cell types, from 2,992 CD14+ Monocytes down to 52 Platelets. Cell names start with rna_. The 10k labels are a little more granular than the 3k ones. Where the 3k data has one CD8 T, one B and one DC group, the 10k data has two of each: CD8 effector and CD8 Naive, pre-B cell and B cell progenitor, Dendritic cell and pDC. It also has a Double negative T cell group.
DimPlot(pbmc10k, label = TRUE, repel = TRUE) + NoLegend()
1.3.1 What is already inside the reference
This object is not raw. Someone already ran the whole pipeline on it, and Seurat keeps a log of every command:
Command(pbmc10k)
#> [1] "NormalizeData.RNA" "FindVariableFeatures.RNA"
#> [3] "ScaleData.RNA" "RunPCA.RNA"
#> [5] "RunTSNE.pca" "FindNeighbors.RNA.pca"
#> [7] "FindClusters" "RunUMAP.RNA.pca"
Command(pbmc10k, "NormalizeData.RNA", "normalization.method")
#> [1] "LogNormalize"
Command(pbmc10k, "NormalizeData.RNA", "scale.factor")
#> [1] 10000
Command(pbmc10k, "FindVariableFeatures.RNA", "nfeatures")
#> [1] 3000
Command(pbmc10k, "ScaleData.RNA", "scale.max")
#> [1] 10
Command(pbmc10k, "RunPCA.RNA", "npcs")
#> [1] 100The data layer is log-normalized with a scale factor of 10000, the same as our 3k data. The 3,000 variable genes were scaled, with the scaled values clipped at 10, and 100 PCs were computed from them. A small test of the first line: undo the log for the first three cells and add up their values.
colSums(expm1(LayerData(pbmc10k, layer = "data")[, 1:3]))
#> rna_AAACCCAAGCGCCCAT-1 rna_AAACCCACAGAGTTGG-1 rna_AAACCCACAGGTATGG-1
#> 10000 10000 10000Exactly 10000 for each cell, the scale factor. Now the results of the other steps:
Reductions(pbmc10k)
#> [1] "pca" "tsne" "umap"
dim(Embeddings(pbmc10k, reduction = "pca"))
#> [1] 9432 100
length(VariableFeatures(pbmc10k))
#> [1] 3000
dim(LayerData(pbmc10k, layer = "scale.data"))
#> [1] 3000 9432
range(LayerData(pbmc10k, layer = "scale.data"))
#> [1] -7.901501 10.000000The stored PCA has 100 PCs for the 9,432 cells. The scaled matrix has the 3,000 variable genes in rows and the cells in columns, with values from -7.9 up to exactly 10: that 10 is the clip. Lesson 2 starts from this scaled matrix.
1.4 Keep the genes both datasets have
To put the query into the reference’s PCA space (lesson 3), we multiply the query’s expression by the reference’s gene loadings, gene by gene. That only works when the two objects have the same genes in the same order. Do they?
pbmc3k_genes <- rownames(pbmc3k)
pbmc10k_genes <- rownames(pbmc10k)
length(pbmc3k_genes)
#> [1] 13714
length(pbmc10k_genes)
#> [1] 19089
common_genes <- intersect(pbmc3k_genes, pbmc10k_genes)
length(common_genes)
#> [1] 11774
length(setdiff(pbmc3k_genes, pbmc10k_genes))
#> [1] 1940
length(setdiff(pbmc10k_genes, pbmc3k_genes))
#> [1] 731511,774 genes are in both. 1,940 are only in the 3k data and 7,315 only in the 10k data. Some of those are the same gene under two names:
c("GNB2L1", "RACK1") %in% pbmc3k_genes
#> [1] TRUE FALSE
c("GNB2L1", "RACK1") %in% pbmc10k_genes
#> [1] FALSE TRUEThe 3k data calls this gene GNB2L1; the 10k data uses its newer name, RACK1. Matching by gene symbol with intersect() drops both. For this course I keep the simple intersection, as in my blog post. Exercise 1 below shows what it costs.
Let’s subset both objects to the common genes.
pbmc3k <- subset(pbmc3k, features = common_genes)
pbmc10k <- subset(pbmc10k, features = common_genes)
all.equal(rownames(pbmc3k), rownames(pbmc10k))
#> [1] TRUESame genes, same order. Note the order of the steps: I normalized the 3k data with all its genes and cut it afterwards. NormalizeData() divides every count by the cell’s total count, so cutting first would change the totals and every number after them. The reference was normalized with all its genes too, and subset() does not normalize again:
colSums(expm1(LayerData(pbmc10k, layer = "data")[, 1:3]))
#> rna_AAACCCAAGCGCCCAT-1 rna_AAACCCACAGAGTTGG-1 rna_AAACCCACAGGTATGG-1
#> 9632.486 9714.480 9584.087The same three cells now add up to 9632, 9714 and 9584, because the genes we dropped took their share with them. The values we kept are the ones computed from all the genes, which is what we want.
1.4.1 What the subset leaves in the reference
length(VariableFeatures(pbmc10k))
#> [1] 2068
dim(LayerData(pbmc10k, layer = "scale.data"))
#> [1] 2068 9432
dim(Loadings(pbmc10k, reduction = "pca"))
#> [1] 2068 100
Reductions(pbmc10k)
#> [1] "pca" "tsne" "umap"
length(VariableFeatures(pbmc3k))
#> [1] 26852,068 of the 3,000 variable genes survive; the others are not in the 3k data. The scaled matrix is cut to the same 2,068 genes, and so are the gene loadings of the stored PCA. The three reductions are still there, but the cell embeddings of that PCA were computed from all 3,000 genes, so they no longer match the genes we have. That is why lesson 2 computes the PCA again. The 3k object keeps 2,685 of its own 3,000 variable genes.
Ideally, we should re-run FindVariableFeatures(), but I am skipping it. We work with the 2,068 genes that already have scaled values, and exercise 2 checks what a re-run would give.
Save the two objects for the next lessons.
saveRDS(pbmc3k, here("data/pbmc3k_processed.rds"))
saveRDS(pbmc10k, here("data/pbmc10k_common.rds"))pbmc3k_processed.rds is the query (normalized, scaled, clustered, then cut to the common genes) and pbmc10k_common.rds is the reference cut to the same genes. Every later lesson starts from these two files.
1.5 The plan of the course
The PCA route:
- Lesson 2: the PCA of the reference by SVD, checked against
RunPCA. - Lesson 3: project the query onto the reference’s PCs and give each query cell the majority label of its k-nearest neighbors; compare with
FindTransferAnchors()andTransferData(). - Lesson 4: mutual nearest neighbors, and the anchors Seurat builds from them.
The CCA route:
- Lesson 5: the CCA of the two datasets from scratch, checked against
RunCCA. - Lesson 6: label transfer and integration in the CCA space, and PCA versus CCA.
Both routes come from the Satija lab, who wrote Seurat. Butler et al. 2018 (Nature Biotechnology) aligned datasets with CCA, and Stuart, Butler et al. 2019 (Cell, open copy) added the anchors. Figure 1 of the 2019 paper draws the anchor steps (CCA, L2-normalization, mutual nearest neighbors) that lessons 4 to 6 rebuild.
1.6 Your turn
1. What share of all the counts in the 3k data sits in the 1,940 genes that only the 3k data has? Start again from pbmc3k_raw.rds.
pbmc3k_raw <- readRDS(here("data/pbmc3k_raw.rds"))
counts_3k <- LayerData(pbmc3k_raw, layer = "counts")
only_3k <- setdiff(rownames(counts_3k), common_genes)
length(only_3k)
#> [1] 1940
round(100 * sum(counts_3k[only_3k, ]) / sum(counts_3k), 2)
#> [1] 3.19
summary(100 * colSums(counts_3k[only_3k, ]) / colSums(counts_3k))
#> Min. 1st Qu. Median Mean 3rd Qu. Max.
#> 1.561 2.799 3.104 3.205 3.478 8.532
head(sort(rowSums(counts_3k[only_3k, ]), decreasing = TRUE), 5)
#> GNB2L1 GLTSCR2 ATP5G2 TMEM66 ATP5E
#> 20555 6560 6337 4822 46473.19 percent of all counts, between 1.6 and 8.5 percent per cell. The gene with the most counts among them is GNB2L1, the RACK1 from above. This is also why I normalize before the subset: the library sizes stay the real ones.
2. Re-run FindVariableFeatures() with nfeatures = 3000 on the cut-down reference. How many of the 2,068 surviving variable genes are in the new list?
pbmc10k_rerun <- FindVariableFeatures(pbmc10k, selection.method = "vst", nfeatures = 3000, verbose = FALSE)
sum(VariableFeatures(pbmc10k) %in% VariableFeatures(pbmc10k_rerun))
#> [1] 2068
length(setdiff(VariableFeatures(pbmc10k_rerun), VariableFeatures(pbmc10k)))
#> [1] 932All 2,068. A re-run would bring in 932 new genes, but every gene we keep would still be on the list.
1.7 Take-home messages
- Label transfer needs a reference with labels and a query without, in one shared space. Seurat builds that space by PCA projection or by CCA.
- Look inside an old object before you use it:
UpdateSeuratObject(), thenCommand(),Reductions()and the layers tell you what was already done to it. - The query and the reference must have the same genes in the same order. Normalize first, then subset.
- Matching genes by symbol drops genes that were renamed, such as GNB2L1 and RACK1.
- After the subset, the reference keeps 2,068 variable genes and its stored PCA no longer matches them, so lesson 2 computes it again.