---
## Updated 2019-10-11.
params:
  title: "Differential expression using DESeq2"
  
  ## Use DESeqAnalysis object as input.
  ## - Standard: Load from file on disk, either RDS or RDA.
  ## - Advanced: Loop across multiple objects using `rmarkdown::render()`.
  object: "rds/YYYY-MM-DD/object.rds"
  
  ## The `name` param is only required when passing in object directly, during
  ## an `rmarkdown::render()` call. See `object` param.
  name: ""
  
  ## Use log2 fold change values with adaptive shrinkage applied.
  ## Recommended by default. Refer to `DESeq2::lfcShrink()` for details.
  lfc_shrink: TRUE
  
  output_dir: !r file.path("results", Sys.Date(), "differential-expression")

title: "`r params$title`"
author: "`r getOption('author')`"
date: "`r Sys.Date()`"
bibliography: bibliography.bib
---

```{r setup, cache=FALSE, message=FALSE}
library(DESeq2)
library(DESeqAnalysis)
prepareTemplate()
source("_setup.R")
## This is required for tabset R Markdown headers to work in `lapply()` call.
knitr::opts_chunk[["set"]](message = FALSE)
```

```{r header, child="_header.Rmd"}
```

# Load DESeqAnalysis object

```{r load-object}
if (is.character(params$object)) {
    file <- params$object
    object <- import(file)
    name <- params$name
    if (!isTRUE(nzchar(name))) {
      name <- basenameSansExt(file)
    }
    rm(file)
} else {
    object <- params$object
    name <- params$name
}
stopifnot(
    is(object, "DESeqAnalysis"),
    isTRUE(nzchar(name))
)
## Note that DESeq2 will mask the S4 generic.
resultsNames <- DESeqAnalysis::resultsNames(object)
invisible(validObject(object))
print(object)
```

# Sample data

```{r sample-data}
sampleData(object)
```

# MA plot {.tabset}

An MA plot compares transformed counts on `M` (log ratio) and `A` (mean average) scales [@Yang2002-sx].

```{r plot-ma, results="asis"}
invisible(mapply(
    results = resultsNames,
    MoreArgs = list(object = object),
    FUN = function(object, results) {
        markdownHeader(results, level = 2L, asis = TRUE)
        print(plotMA(
            object = object,
            results = results,
            lfcShrink = params$lfc_shrink
        ))
    },
    SIMPLIFY = FALSE,
    USE.NAMES = TRUE
))
```

# Volcano plot {.tabset}

A volcano plot compares significance (BH-adjusted *P* value) against fold change (log2) [@Cui2003-rn; @Li2014-ll]. Genes in the green box with text labels have an adjusted *P* value are likely to be the top candidate genes of interest.

```{r plot-volcano, results="asis"}
invisible(mapply(
    results = resultsNames,
    MoreArgs = list(object = object),
    FUN = function(object, results) {
        markdownHeader(results, level = 2L, asis = TRUE)
        print(plotVolcano(
            object = object,
            results = results,
            lfcShrink = params$lfc_shrink
        ))
    },
    SIMPLIFY = FALSE,
    USE.NAMES = TRUE
))
```

# PCA {.tabset}

```{r plot-deg-pca, results="asis"}
invisible(mapply(
    results = resultsNames,
    MoreArgs = list(
        object = object,
        contrastSamples = TRUE
    ),
    FUN = function(object, results, contrastSamples) {
        markdownHeader(results, level = 2L, asis = TRUE)
        print(plotDEGPCA(
            object = object,
            results = results,
            contrastSamples = contrastSamples
        ))
    },
    SIMPLIFY = FALSE,
    USE.NAMES = TRUE
))
```

# Heatmap {.tabset}

This plot shows only differentially expressed genes on a per-sample basis. We have scaled the data by row (z-score) and used the `ward.D2` method for clustering [@Ward1963-xf].

```{r plot-deg-heatmap, results="asis"}
invisible(mapply(
    results = resultsNames,
    MoreArgs = list(
        object = object,
        contrastSamples = TRUE
    ),
    FUN = function(object, results, contrastSamples) {
        markdownHeader(results, level = 2L, asis = TRUE)
        plotDEGHeatmap(
            object = object,
            results = results,
            contrastSamples = contrastSamples,
            lfcShrink = params$lfc_shrink
        )
    },
    SIMPLIFY = FALSE,
    USE.NAMES = TRUE
))
```

# Top tables {.tabset}

Only the top up- and down-regulated genes (arranged by adjusted *P* value) are shown.

```{r top-tables, results="asis"}
invisible(mapply(
    results = resultsNames,
    MoreArgs = list(
        object = object,
        n = 25L
    ),
    FUN = function(object, results, n) {
        markdownHeader(results, level = 2L, asis = TRUE)
        topTables(
            object = object,
            results = results,
            n = n,
            lfcShrink = params$lfc_shrink
        )
    },
    SIMPLIFY = FALSE,
    USE.NAMES = TRUE
))
```

# Export

Here we are exporting the data stored inside our `DESeqDataSet`, `DESeqTransform`, and `DESeqResults` objects (results = unshrunken LFC; lfcShrink = shrunken LFC), along with the differentially expressed gene (DEG) results tables (resultsTables).

The DEG results tables are sorted by BH-adjusted P value (except for the "all" file, which is unmodified), and contain the following columns:

- `baseMean`: Mean of the normalized counts per gene for all samples.
- `log2FoldChange`: log2 fold change.
- `lfcSE`: log2 standard error.
- `stat`: Wald statistic.
- `pvalue`: Walt test *P* value.
- `padj`: BH adjusted Wald test *P* value (corrected for multiple comparisons; aka FDR).

These files also contain genome annotation information and the size-factor adjusted normalized counts stored inside the `DESeqDataSet` used to perform the differential expression analysis.

Note that `colData` files contain annotations corresponding to the columns (i.e. samples) and the `rowData` files contain annotations corresponding to the rows (i.e. genes). You can obtain gene-to-symbol mappings using this `rowData` file, for example.

```{r export}
export(
    object = object,
    name = name,
    dir = params$output_dir,
    compress = FALSE,
    lfcShrink = params$lfc_shrink
)
```

```{r footer, child="_footer.Rmd"}
```

```{r links, child="_links.Rmd"}
```
