# Unfiltered human PBMCs (10X Genomics)

```{r unref-setup, cache=FALSE, echo=FALSE, results="asis"}
library(rebook)
chapterPreamble(cache=TRUE)
```

## Introduction

Here, we describe a brief analysis of the peripheral blood mononuclear cell (PBMC) dataset from 10X Genomics [@zheng2017massively].
The data are publicly available from the [10X Genomics website](https://support.10xgenomics.com/single-cell-gene-expression/datasets/2.1.0/pbmc4k),
from which we download the raw gene/barcode count matrices, i.e., before cell calling from the _CellRanger_ pipeline.

## Data loading

```{r loading}
library(DropletTestFiles)
raw.path <- getTestFile("tenx-2.1.0-pbmc4k/1.0.0/raw.tar.gz")
out.path <- file.path(tempdir(), "pbmc4k")
untar(raw.path, exdir=out.path)

library(DropletUtils)
fname <- file.path(out.path, "raw_gene_bc_matrices/GRCh38")
sce.pbmc <- read10xCounts(fname, col.names=TRUE)
```

```{r gene-annotation}
library(scater)
rownames(sce.pbmc) <- uniquifyFeatureNames(
    rowData(sce.pbmc)$ID, rowData(sce.pbmc)$Symbol)

library(EnsDb.Hsapiens.v86)
location <- mapIds(EnsDb.Hsapiens.v86, keys=rowData(sce.pbmc)$ID, 
    column="SEQNAME", keytype="GENEID")
```

## Quality control

We perform cell detection using the `emptyDrops()` algorithm, as discussed in `r link("qc-droplets", "OSCA.advanced")`.

```{r cell-detection}
set.seed(100)
e.out <- emptyDrops(counts(sce.pbmc))
sce.pbmc <- sce.pbmc[,which(e.out$FDR <= 0.001)]
```

```{r}
unfiltered <- sce.pbmc
```

We use a relaxed QC strategy and only remove cells with large mitochondrial proportions, using it as a proxy for cell damage.
This reduces the risk of removing cell types with low RNA content, especially in a heterogeneous PBMC population with many different cell types.

```{r quality-control}
stats <- perCellQCMetrics(sce.pbmc, subsets=list(Mito=which(location=="MT")))
high.mito <- isOutlier(stats$subsets_Mito_percent, type="higher")
sce.pbmc <- sce.pbmc[,!high.mito]
```

```{r}
summary(high.mito)
```

```{r unref-unfiltered-pbmc-qc, fig.wide=TRUE, fig.asp=1, fig.cap="Distribution of various QC metrics in the PBMC dataset after cell calling. Each point is a cell and is colored according to whether it was discarded by the mitochondrial filter."}
colData(unfiltered) <- cbind(colData(unfiltered), stats)
unfiltered$discard <- high.mito

gridExtra::grid.arrange(
    plotColData(unfiltered, y="sum", colour_by="discard") +
        scale_y_log10() + ggtitle("Total count"),
    plotColData(unfiltered, y="detected", colour_by="discard") +
        scale_y_log10() + ggtitle("Detected features"),
    plotColData(unfiltered, y="subsets_Mito_percent",
        colour_by="discard") + ggtitle("Mito percent"),
    ncol=2
)
```

```{r unref-unfiltered-pbmc-mito, fig.cap="Proportion of mitochondrial reads in each cell of the PBMC dataset compared to its total count."}
plotColData(unfiltered, x="sum", y="subsets_Mito_percent",
    colour_by="discard") + scale_x_log10()
```

## Normalization

```{r normalization}
library(scran)
set.seed(1000)
clusters <- quickCluster(sce.pbmc)
sce.pbmc <- computeSumFactors(sce.pbmc, cluster=clusters)
sce.pbmc <- logNormCounts(sce.pbmc)
```

```{r}
summary(sizeFactors(sce.pbmc))
```

```{r unref-unfiltered-pbmc-norm, fig.cap="Relationship between the library size factors and the deconvolution size factors in the PBMC dataset."}
plot(librarySizeFactors(sce.pbmc), sizeFactors(sce.pbmc), pch=16,
    xlab="Library size factors", ylab="Deconvolution factors", log="xy")
```

## Variance modelling

```{r variance-modelling}
set.seed(1001)
dec.pbmc <- modelGeneVarByPoisson(sce.pbmc)
top.pbmc <- getTopHVGs(dec.pbmc, prop=0.1)
```

```{r unref-unfiltered-pbmc-var, fig.cap="Per-gene variance as a function of the mean for the log-expression values in the PBMC dataset. Each point represents a gene (black) with the mean-variance trend (blue) fitted to simulated Poisson counts."}
plot(dec.pbmc$mean, dec.pbmc$total, pch=16, cex=0.5,
    xlab="Mean of log-expression", ylab="Variance of log-expression")
curfit <- metadata(dec.pbmc)
curve(curfit$trend(x), col='dodgerblue', add=TRUE, lwd=2)
```

## Dimensionality reduction

```{r dimensionality-reduction}
set.seed(10000)
sce.pbmc <- denoisePCA(sce.pbmc, subset.row=top.pbmc, technical=dec.pbmc)

set.seed(100000)
sce.pbmc <- runTSNE(sce.pbmc, dimred="PCA")

set.seed(1000000)
sce.pbmc <- runUMAP(sce.pbmc, dimred="PCA")
```

We verify that a reasonable number of PCs is retained.

```{r}
ncol(reducedDim(sce.pbmc, "PCA"))
```

## Clustering

```{r clustering}
g <- buildSNNGraph(sce.pbmc, k=10, use.dimred = 'PCA')
clust <- igraph::cluster_walktrap(g)$membership
colLabels(sce.pbmc) <- factor(clust)
```

```{r}
table(colLabels(sce.pbmc))
```

```{r unref-unfiltered-pbmc-tsne, fig.cap="Obligatory $t$-SNE plot of the PBMC dataset, where each point represents a cell and is colored according to the assigned cluster."}
plotTSNE(sce.pbmc, colour_by="label")
```

## Interpretation

```{r, echo=FALSE}
chosen.mono <- "7"
chosen.macro <- "16"
```

```{r}
markers <- findMarkers(sce.pbmc, pval.type="some", direction="up")
```

We examine the markers for cluster `r chosen.mono` in more detail.
High expression of _CD14_, _CD68_ and _MNDA_ combined with low expression of _FCGR3A_ (_CD16_) suggests that this cluster contains monocytes,
compared to macrophages in cluster `r chosen.macro` (Figure \@ref(fig:unref-mono-pbmc-markers)).

```{r}
marker.set <- markers[["7"]]
as.data.frame(marker.set[1:30,1:3])
```

```{r, echo=FALSE, results="hide"}
# Checking 'marker.set' and 'chosen.mono' are consistent.
stopifnot(identical(marker.set, markers[[chosen.mono]]))

# Checking the cluster is what we wanted.
topset <- rownames(marker.set)[1:30]
stopifnot(all(c("CD14", "CD68", "MNDA") %in% topset))
stopifnot(marker.set["FCGR3A",paste0("logFC.", chosen.macro)] < -1)

# Checking that the chosen.macro is actually a macrophage.
alt.marker.set <- markers[[chosen.macro]]
alt.topset <- rownames(alt.marker.set)[1:60]
stopifnot(all(c("FCGR3A", "CD68", "MNDA") %in% alt.topset))
stopifnot(alt.marker.set["CD14",paste0("logFC.", chosen.mono)] < -1)
```

```{r unref-mono-pbmc-markers, fig.cap="Distribution of expression values for monocyte and macrophage markers across clusters in the PBMC dataset.", fig.wide=TRUE, fig.asp=0.8}
plotExpression(sce.pbmc, features=c("CD14", "CD68",
    "MNDA", "FCGR3A"), x="label", colour_by="label")
```

## Session Info {-}

```{r sessionInfo, echo=FALSE, results='asis'}
prettySessionInfo()
```
