# Last modified 2018-03-17
bcbioRNASeq::prepareRNASeqTemplate()
source("_setup.R")

# Directory paths ==============================================================
invisible(mapply(
    FUN = dir.create,
    path = c(params$data_dir, params$results_dir),
    MoreArgs = list(showWarnings = FALSE, recursive = TRUE)
))

# Load object ==================================================================
bcb_name <- load(params$bcb_file)
bcb <- get(bcb_name, inherits = FALSE)
stopifnot(is(bcb, "bcbioRNASeq"))
invisible(validObject(bcb))

sampleData(bcb, return = "data.frame")

[bcbio][] run data was imported from r metadata(bcb)$uploadDir.

Count matrices

raw_counts <- counts(bcb, normalized = FALSE)
# DESeq2 normalized counts
normalized_counts <- counts(bcb, normalized = TRUE)
# Transcripts per million
tpm <- counts(bcb, normalized = "tpm")
saveData(raw_counts, normalized_counts, tpm, dir = params$data_dir)
writeCounts(raw_counts, normalized_counts, tpm, dir = params$results_dir)

The results are saved as gzip-compressed comma separated values (CSV). Gzip compression is natively supported on [macOS][] and Linux-based operating systems. If you're running Windows, we recommend installing [7-Zip][]. CSV files can be opened in [Excel][] or [RStudio][].

Read metrics {.tabset}

Total reads

plotTotalReads(bcb)

Mapped reads

The number of mapped reads should correspond to the number of total reads.

plotMappedReads(bcb)

Mapping rate

The genomic mapping rate represents the percentage of reads mapping to the reference genome. Low mapping rates are indicative of sample contamination, poor sequencing quality or other artifacts.

plotMappingRate(bcb)

Number of genes detected

plotGenesDetected(bcb)

Gene detection saturation

We should observe a linear trend in the number of genes detected with the number of mapped reads, which indicates that the sample input was not overloaded.

plotGeneSaturation(bcb, interestingGroups = "sampleName")

Exonic mapping rate

Ideally, at least 60% of total reads should map to exons.

plotExonicMappingRate(bcb)

Intronic mapping rate

The majority of reads should map to exons and not introns.

plotIntronicMappingRate(bcb)

rRNA mapping rate

Samples should have a ribosomal RNA (rRNA) contamination rate below 10%.

plotRRNAMappingRate(bcb)

5'->3' bias

plot5Prime3PrimeBias(bcb)

Counts per gene

Generally, we expect similar count spreads for all genes between samples unless the library sizes or total RNA expression are different. The log10 TMM-normalized counts per gene normalization method [@Robinson:2010dd] equates the overall expression levels of genes between samples under the assumption that the majority of them are not differentially expressed. Therefore, by normalizing for total RNA expression by sample, we expect the spread of the log10 TMM-normalized counts per gene to be similar for every sample.

plotCountsPerGene(bcb, normalized = "tmm")
basejump::mdHeader("TPM per biotype", level=2)
knitr::asis_output("Different RNA-seq processing methods can preferentially capture a subset of
  the RNA species from the total RNA. For example, polyA selection should select for mostly
  coding genes and skip a large percentage of non-polyA non-coding RNA. Here we make boxplots
  of the TPM for the top 12 biotypes with the most genes assigned to them for each sample.")

keep_biotypes = rowData(bcb) %>%
  as.data.frame() %>%
  group_by(geneBiotype) %>%
  summarise(nBiotype=n()) %>%
  arrange(-nBiotype) %>%
  top_n(12) %>%
  pull(geneBiotype) %>%
  droplevels()
biotypetpm = tpm(bcb) %>%
  as.data.frame() %>%
  tibble::rownames_to_column("gene") %>%
  tidyr::gather(sample, tpm, -gene) %>%
  dplyr::left_join(rowData(bcb) %>%
                   as.data.frame(), by=c("gene"="geneID")) %>%
  filter(geneBiotype %in% keep_biotypes)

ggplot(biotypetpm, aes(sample, tpm))+
  geom_violin() +
  scale_y_log10() +
  facet_wrap(~geneBiotype) +
  xlab("") +
  ylab("Transcripts Per Million (TPM)") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1),
        axis.text=element_text(size=8),
        axis.title=element_text(size=10))
basejump::mdHeader("TPM per broad biotype class", level=2)
knitr::asis_output("The Ensembl biotype clasifications are too specific to plot them all--
  here we have grouped the biotypes into broad classes and plot boxplots of the TPM for each
  sample.")
biotypetpm = tpm(bcb) %>%
  as.data.frame() %>%
  tibble::rownames_to_column("gene") %>%
  tidyr::gather(sample, tpm, -gene) %>%
  dplyr::left_join(rowData(bcb) %>%
                   as.data.frame(), by=c("gene"="geneID")) %>%
  filter(!is.na(broadClass))

ggplot(biotypetpm, aes(sample, tpm)) +
  geom_violin() +
  facet_wrap(~broadClass) +
  scale_y_log10() +
  xlab("") +
  ylab("Transcripts Per Million (TPM)") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1),
        axis.text=element_text(size=8),
        axis.title=element_text(size=10))

Count density

Generally, we expect similar count spreads for all genes between samples unless the total expressed RNA per sample is different.

plotCountDensity(bcb, normalized = "tmm", style = "line")

Fit modeling

Several quality metrics are first assessed to explore the fit of the model, before differential expression analysis is performed.

Variance stabilization

The plots below show the standard deviation of normalized counts (normalized_counts) using log2(), rlog(), and variance stabilizing (vst()) transformations by rank(mean). The transformations greatly reduce the standard deviation, with rlog() stabilizing the variance best across the mean.

plotMeanSD(bcb, orientation = "vertical")

Dispersion

The following plot shows the dispersion by mean of normalized counts. We expect the dispersion to decrease as the mean of normalized counts increases.

plotDispEsts(bcb)

Sample similarity analysis

Before performing similarity analysis, we transform counts to log2, which acts to minimize large differences in sequencing depth and helps normalize all samples to a similar dynamic range. For RNA-seq count data, variance increases with the mean. Logarithmic transformation of normalized count values with a small pseudocount will account for large variations seen between the highest expressing genes so that these genes won't dominate the PCA plots. However, due to the strong noise among low count values due to Poisson, the general log2 transformation will amplify this noise, and instead, low count genes will now dominate the PCA plots. So instead, we use a regularized log ("rlog"; base 2) transformation that gives similar results for high counts as a log2 transformation but also shrinks the values of low counts towards the genes’ average across samples. We do this with the rlog() function in the [DESeq2][] package [@DESeq2], which we will later use for differential gene expression analysis.

Principal component analysis (PCA) {.tabset}

PCA [@Jolliffe:2002wx] is a multivariate technique that allows us to summarize the systematic patterns of variations in the data. PCA takes the expression levels for genes and transforms it in principal component space, reducing each sample into one point. Thereby, we can separate samples by expression variation, and identify potential sample outliers. The PCA plot is a way to look at how samples are clustering.

markdownHeader("unlabeled", level = 3)
plotPCA(bcb, label = FALSE)

markdownHeader("labeled", level = 3)
plotPCA(bcb, label = TRUE)

Covariates correlation with PCs

When multiple factors may influence the results of a given experiment, it is useful to assess which of them is responsible for the most variance as determined by PCA. We adapted the method described by Daily et al. where they integrated a method to correlate covariates with principal components values to determine the importance of each factor.

Here we are showing the correlational analysis of the rlog transformed count data's principal components with the metadata covariates of interest. Significant correlations (FDR < 0.1) are shaded from blue (anti-correlated) to orange (correlated), with non-significant correlations shaded in gray.

plotPCACovariates(bcb)

Hierarchical clustering

Inter-correlation analysis (ICA) is another way to look at how well samples cluster by plotting the correlation between the expression profiles of the samples.

plotCorrelationHeatmap(bcb, method = "pearson")



roryk/bcbioRnaseq documentation built on May 27, 2019, 10:44 p.m.