sc_quality_check.R 13.7 KB
Newer Older
1 2 3 4
#!/usr/bin/env Rscript
#+ include=FALSE

#**************************************************************
Lena Hersemann's avatar
Lena Hersemann committed
5
#' # Quality check of single-cell RNASeq data
6
#+ include=FALSE
7 8 9
#**************************************************************
# https://www.bioconductor.org/help/workflows/simpleSingleCell/

10

11 12 13 14
suppressMessages(require(docopt))

doc = '
Quality control and filtering of scRNAseq data
15 16 17 18
Usage: sc_quality_check.R [options] <star_counts_matrix> <design>

Options:
--file_prefix <sample_name>          add prefix to output files if storing output of multiple analysis in one folder [default: ]
19 20
'

21 22 23


# commandArgs <- function(x) c("../metrices/SC1_star_counts_matrix.txt", "../metrices/SC1_basic_design.txt")
24 25 26 27 28 29
opts = docopt(doc, commandArgs(TRUE))



# LOAD packages -------------------------------------------------------------------------------
#https://www.bioconductor.org/help/workflows/simpleSingleCell/
30 31
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.40/R/core_commons.R")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.45/R/ggplot_commons.R")
32 33
devtools::source_url("https://git.mpi-cbg.de/bioinfo/ngs_tools/raw/v6/common/cp_utils.R")
library(knitr)
34
# require(gridExtra)
35
library(scran)
36
library(NOISeq)
37 38 39 40 41 42 43 44 45 46 47 48 49
# install.packages("kableExtra")
library(kableExtra)
library(plotly)
library(bsplus)
library(htmltools)
library(shiny)
library(htmltools)
library(BiocParallel)
library(data.table)
# # library(scater)
# # detach("package:scater", unload = TRUE)
# load_pack(SingleCellExperiment)
#
50 51 52 53 54 55 56 57 58 59 60 61 62


# FUNCTIONS ------------------------------------------------------------------------------------

get.cellcycl.phase <- function(x, annot.db){
    cur.anno <- select(annot.db, rownames(x), keytype="ENSEMBL", "ENSEMBL")
    cur.ensembl <- anno$ENSEMBL[match(rownames(x), cur.anno$ENSEMBL)]
    cur.assignments <- cyclone(x, mm.pairs, gene.names = cur.ensembl)
    cur.phase <- cur.assignments$phases
    return(cur.phase)
}


63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
# HANDLE input data -------------------------------------------------------------------------------

counts_file <- opts$star_counts_matrix
design_file <- opts$design
prefix <- opts$file_prefix

countData <- fread(counts_file)

countMatrix <- countData %>%
    mutate(sum = select(., -ensembl_gene_id) %>% rowSums()) %>%
    filter(sum > 0) %>%
    select(-sum) %>%
    column2rownames("ensembl_gene_id") %>%
    as.matrix()

design <- read_tsv(design_file)

if (ncol(countMatrix) != nrow(design)) {print("Count matrix and design have different sample numbers")}


# create SingleCellExperiment object:
sce <- SingleCellExperiment(assays = list(counts=countMatrix), colData = design)



88 89 90 91 92 93
# Quality control and filtering --------------------------------------------------------------

#' Due to low quantities of RNA in single cells, scRNAseq data are much noiser than bulk RNAseq data. Here we perform
#' quality control and filtering of scRNAseq data (i.e. removal of problamatic cells) by using quality metrices recommended by
#' [Lun et al. 2017](https://www.bioconductor.org/help/workflows/simpleSingleCell/).

94 95 96 97
#' **Input data are:**
vec_as_df(unlist(opts)) %>%
    filter(! str_detect(name, "^[<-]")) %>%
    kable()
98 99

# check for spike-ins and mitochondrial genes and include those information in the general calculation of quality metrices
100 101 102
is.spike <- grepl("^ERCC", rownames(sce))
is.mito <- grepl("^mt-", rownames(sce))
sce <- scater::calculateQCMetrics(sce, feature_controls=list(ERCC=is.spike, Mt=is.mito))
103

104

105
#'<br><br>
106 107 108 109 110 111 112 113 114 115 116
#+ echo=FALSE, eval=TRUE
# calculate quality control features and plot data -------------------

# median library size
lib_median = median(sce$total_counts_endogenous/1e6)
plot_lib_median <- colData(sce) %>%
    as.data.frame() %>%
    ggplot(aes(total_counts/1e6)) +
        geom_histogram(col = "white", fill = "grey") +
        ylab("Number of cells") +
        xlab("Library size (millions)") +
117
        geom_vline(xintercept = lib_median, color = "red")
118
bs_modal(id = "lib_median_plot", title = paste("\n Median library size per cell in million: ", lib_median , sep = ""), body = htmltools::tagList(ggplotly(plot_lib_median, width = 800)), size = "large")
119

120
bs_modal(id = "lib_median", title = "Median library size per cell in million", body = "The library size is defined by the sum of all counts per cell and corresponds to the number of reads mapped to the reference genome")
121 122


123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
# number of expressed genes
gene_median <- median(sce$total_features_endogenous)
plot_expressed_genes <- colData(sce) %>%
    as.data.frame() %>%
    ggplot(aes(total_features)) +
        geom_histogram(col = "white", fill = "grey") +
        ylab("Number of cells") +
        xlab("Number of expressed genes") +
        geom_vline(xintercept = gene_median, color = "red")
bs_modal(id = "expressed_genes_plot", title = paste("\n Median genes per cell: ", gene_median, sep = ""), body = htmltools::tagList(ggplotly(plot_expressed_genes, width = 800)), size = "large")
bs_modal(id = "expressed_genes", title = "Expressed genes per cell", body = "The number of expressed genes corresponds to the number of genes per cell with an actual count (i.e. > 0)")


# proportion of spike-ins
spike_data <- colData(sce) %>% as.data.frame()
# bs_modal(id = "spikes", title = "Spike-ins", body = "Occassionally, spike-in RNAs are added before sequencing to serve as a standard for quality control, filtering and normalization. The proportion of spike-in RNAs will be reported if any spike-in counts are detected within the alignment results.")
if (max(spike_data$pct_counts_ERCC) > 0) {
    spike_plot <- ggplot(spike_data, aes(pct_counts_ERCC)) +
        geom_histogram(col = "white", fill = "grey") +
        ylab("Number of cells") +
        xlab("ERCC proportion (%)") +
    spike_ins <- "present"
    bs_modal(id = "spike_plot", title = "Proportion of spike-ins:", body = htmltools::tagList(ggplotly(spike_plot, width = 800)), size = "large")
    plot_spike_ins <- '<a data-toggle="modal" data-target="#spike_plot">plot</a>'
} else {
    spike_ins <- "not present"
    plot_spike_ins <- "no data plotted"
150 151
}

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

# # proportion of mitochondrial genes
# mito_data <- colData(sce) %>% as.data.frame()
# bs_modal(id = "mito", title = "Mitochondrial genes", body = "Mitochondrial genes can be used as a criterion for count data normalization")
# if (max(spike_data$pct_counts_Mt) > 0) {
#     mito_plot <- ggplot(mito_data, aes(pct_counts_Mt)) +
#         geom_histogram(col = "white", fill = "grey") +
#         ylab("Number of cells") +
#         xlab("Mitochondrial genes proportion (%)") +
#     mito <- "found"
#     bs_modal(id = "mito_plot", title = "Proportion of mitochondrial genes:", body = htmltools::tagList(ggplotly(mito_plot, width = 700)), size = "large")
#     plot_mito <- '<a data-toggle="modal" data-target="#mito_plot">plot</a>'
# } else {
#     mito <- "not found"
#     plot_mito <- "no data plotted"
Lena Hersemann's avatar
Lena Hersemann committed
167
# }
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

#' ## General characteristics of this dataset

#+ echo=FALSE, eval=TRUE
bs_modal(id = "total_features", title = "Total number of features", body = "Number of unique features (i.e. genes, spike-ins, etc.) in the whole data set.")

#+ include=TRUE
tribble(~feature, ~value, ~visualization,
# "test", "test", "test", '<a data-toggle="modal" data-target="#modal">Title</a>'
'<a data-toggle="modal" data-target="#lib_median">Median library size</a>', lib_median, '<a data-toggle="modal" data-target="#lib_median_plot">plot</a>',
'<a data-toggle="modal" data-target="#total_features">Total number of features</a>', nrow(counts(sce)), "no data plotted",
'<a data-toggle="modal" data-target="#expressed_genes">Expressed genes per cell</a>', gene_median, '<a data-toggle="modal" data-target="#expressed_genes_plot">plot</a>',
'<a data-toggle="modal" data-target="#spikes">Spike-ins</a>', spike_ins, plot_spike_ins
# '<a data-toggle="modal" data-target="#mito">Mitochondrial genes</a>', mito, plot_mito,
) %>% kable(escape = TRUE)


#----------------------------------------------------------

#'<br><br>
#' ## Sequencing saturation
#' The following saturation plot of the invidivudal cells is based on the sequencing depth of each cell as well as 6 higher
#' and lower simulated sequencing depths. For this plot all features with a counts > 0 were taken into account. Due to memory usage
#' only a subset of 500 cells will be used to indicate sequencing saturation of the data set.
dat <- readData(data = counts(sce)[,1:500], factors = colData(sce)[1:500,])
mysaturation = dat(dat, k = 0, ndepth = 6, type = "saturation")
sat_data <- dat2save(mysaturation)


do.call(rbind,lapply(names(sat_data), function(x){
    data <- sat_data[[x]] %>% as.data.frame()
    data.frame(cell = x, depth = data$depth, global = data$global)
})) %>% ggplot(aes(depth/10^6, global, group = cell, alpha = 0.8)) +
    geom_point() +
    geom_line() +
    xlab("sequencing depth (million reads)") +
    ylab("Number of detected features") +
    ggtitle(paste("Sequencing saturation of 500 out of", nrow(colData(sce)), "cells", sep = " ")) +
    theme(legend.position="none") +
    coord_fixed(ratio = 10/10^6)



#' <br><br>
#' ## Average counts per feature
#' The following plot visualizes the log10 of the average counts per feature which are observed across all samples. Values with a log10(average count) >= 0 represent average counts of >= 1.
scater::calcAverage(sce) %>%
    as.data.frame() %>% `colnames<-`(c("average")) %>% mutate(ensembl_gene_id = rownames(.)) %>%
        ggplot(aes(log10(average))) + geom_histogram(col = "white", binwidth = 0.1, fill = "grey") + ylab("frequency") + xlab(expression(paste(log[10], " average count"))) +
            # labs(title = x) +
            theme(plot.title = element_text(size = 10, face = "bold")) +
            geom_vline(xintercept = 0, color = "red", linetype=2)

221 222

#' <br><br>
223 224 225 226
#' ## 50 most highly abundant features
#' Percentage of total counts assigned to the top 50 most highly-abundant features. Each bar represents the percentage count of the individual feature (i.e. gene, spike-in)
#' in a single cell, coloured by the total number of features in that cell.
scater::plotQC(sce, type = "highest-expression", exprs_values = "counts")
227

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
# # <br><br>
# # ## Frequency of expression
# # Frequency of number of cells with expression for a gene above the defined threshold vs mean expression level.
#  scater::plotQC(sce, type = "exprs-freq-vs-mean")


#' <br><br>
#' ## Check for outliers based on quality control metrices
#' Quality control metrices include the number of total features, total counts, log10_total_features, pct_counts_top_50_features, pct_counts_top_100_features, pct_counts_top_200_features as well as pct_counts_top_500_features.
# PCA <- colData(sce) %>% as.data.frame() %>% select(total_features, log10_total_features, log10_total_counts, pct_counts_top_50_features, pct_counts_top_100_features, pct_counts_top_200_features, pct_counts_top_500_features) %>% as.matrix() %>% prcomp()
PCA <- colData(sce) %>% as.data.frame() %>% select(total_features, log10_total_counts, pct_counts_top_50_features, pct_counts_top_100_features, pct_counts_top_200_features, pct_counts_top_500_features) %>% as.matrix() %>% prcomp()
percent <- round((((PCA$sdev)^2 / sum(PCA$sdev^2))*100))
PCA$x %>%
    as.data.frame() %>%
    ggplot(aes(PC1, PC2)) +
    geom_point() +
    xlab(paste("PC1 (", percent[1], "%)", sep = "")) +
    ylab(paste("PC2 (", percent[2], "%)", sep = ""))
246 247 248 249



#' <br><br>
250
#' ## Cell cycle phase
251 252 253
#' Cells are classified as being (i) in G1 phase if the G1 score is above 0.5 and greater than the G2/M score, (ii) in G2/M phase if the G2/M score is above 0.5 and greater than the G1 score and (iii) in S phase if neither score is above 0.5.
#' A file with the suffix '_cell_cycle_phases.txt' will be saved and can be subsequently used to either filter the cells or correct for differences in cell cycle phases as a batch effect.

254 255
# So far only mouse and human cycle markers are available as standard data set for checking the cell cycle phase.
# However, scran::sandbag() can be used to train a classifier for cell cylce phases in other organisms.
256
#https://www.bioconductor.org/packages/devel/bioc/vignettes/AnnotationDbi/inst/doc/IntroToAnnotationPackages.pdf
257
db <- guess_anno_db(rownames(counts(sce))[1])
258 259 260 261 262 263 264 265 266

if (db == "org.Mm.eg.db"){
    cc.pairs <- readRDS(system.file("exdata", "mouse_cycle_markers.rds", package="scran"))
} else if (db == "org.Hs.eg.db") {
    cc.pairs <- readRDS(system.file("exdata", "human_cycle_markers.rds", package="scran"))
} else {
    print("For this organism no cell cycle markers are provided by the Bioconductor package scran")
}

267
# phase <- data.frame(sample = character())
268
if (exists("cc.pairs")) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    # system.time( assignments <- cyclone(sce, pairs = cc.pairs, BPPARAM=MulticoreParam(10)) )
    # system.time( assignments <- cyclone(sce, pairs = cc.pairs) )
    assignments <- cyclone(sce, pairs = cc.pairs, BPPARAM=MulticoreParam(10))
    data <- cbind(assignments$scores, data.frame(cell = rownames(colData(sce)), phase = assignments$phases))

    sce$phase <- data$phase

    # export cell cycle data with its actual data...
    data %>% write_tsv(paste(prefix, "cell_cycle_phases.txt", sep = ""))
    # ...and only the phase as additional batch effect in the design file
    design %>%
        left_join(data, by = "cell") %>%
        select(-G1, -S, -G2M) %>%
        write_tsv(paste(prefix, "basic_design_incl_ccp.txt", sep = ""))

    # plot data
    cc_plot <- ggplot(data, aes(G1, G2M, color = phase)) +
        geom_point(alpha = 0.3) +
        xlab("G1 score") +
        ylab("G2/M score") +
        coord_fixed(ratio = 1)

    print(cc_plot)
    datatable(data.frame(G1 = length(sce$phase[sce$phase == "G1"]), S = length(sce$phase[sce$phase == "S"]), G2M = length(sce$phase[sce$phase == "G2M"])))
293 294
}

295 296 297


#-----------------------------------------------------------
298
session::save.session(paste(".", prefix, "quality_check_filtered_genes.dat", sep = ""))
299
#session::restore.session(".quality_check_filtered_genes.dat")