---
title: "NBAMSeq: Negative Binomial Additive Model for RNA-Seq Data"
author: "Xu Ren and Pei Fen Kuan"
date: "`r Sys.Date()`"
output: 
    rmarkdown::html_document:
        highlight: pygments
        toc: true
bibliography: reference.bib
vignette: >
    %\VignetteIndexEntry{Negative Binomial Additive Model for RNA-Seq Data}
    %\VignetteEngine{knitr::rmarkdown}
    %\VignetteEncoding{UTF-8}
---


```{r, echo = FALSE}
knitr::opts_chunk$set(comment = "", message=FALSE, warning = FALSE)
```

## Installation

To install and load NBAMSeq

```{r eval = FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("NBAMSeq")
```

```{r}
library(NBAMSeq)
```

## Introduction

High-throughput sequencing experiments followed by differential expression 
analysis is a widely used approach to detect genomic biomarkers. A fundamental 
step in differential expression analysis is to model the association between 
gene counts and covariates of interest. NBAMSeq is a flexible statistical model 
based on the generalized additive model and allows for information sharing 
across genes in variance estimation. Specifically, we model the logarithm of 
mean gene counts as sums of smooth functions with the smoothing parameters and 
coefficients estimated simultaneously by a nested iteration. The variance is 
estimated by the Bayesian shrinkage approach to fully exploit the information 
across all genes. 

The workflow of NBAMSeq contains three main steps:

* Step 1: Data input using `NBAMSeqDataSet`;

* Step 2: Differential expression (DE) analysis using `NBAMSeq` function;

* Step 3: Pulling out DE results using `results` function. 

Here we illustrate each of these steps respectively.

## Data input

Users are expected to provide three parts of input, i.e. `countData`, 
`colData`, and `design`.

`countData` is a matrix of gene counts generated by RNASeq experiments.

```{r}
## An example of countData
n = 50  ## n stands for number of genes
m = 20   ## m stands for sample size
countData = matrix(rnbinom(n*m, mu=100, size=1/3), ncol = m) + 1
mode(countData) = "integer"
colnames(countData) = paste0("sample", 1:m)
rownames(countData) = paste0("gene", 1:n)
head(countData)
```

`colData` is a data frame which contains the covariates of samples. The sample
order in `colData` should match the sample order in `countData`.

```{r}
## An example of colData
pheno = runif(m, 20, 80)
var1 = rnorm(m)
var2 = rnorm(m)
var3 = rnorm(m)
var4 = as.factor(sample(c(0,1,2), m, replace = TRUE))
colData = data.frame(pheno = pheno, var1 = var1, var2 = var2,
    var3 = var3, var4 = var4)
rownames(colData) = paste0("sample", 1:m)
head(colData)
```

`design` is a formula which specifies how to model the samples. Compared 
with other packages performing DE analysis including 
DESeq2 [@love2014moderated], edgeR [@robinson2010edger], NBPSeq [@di2015nbpseq] 
and BBSeq [@zhou2011powerful], NBAMSeq supports the nonlinear model of 
covariates via mgcv [@wood2015package]. To indicate the nonlinear covariate in 
the model, users are expected to use `s(variable_name)` in the `design` 
formula. In our example, if we would like to model `pheno` as a nonlinear 
covariate, the `design` formula should be: 

```{r}
design = ~ s(pheno) + var1 + var2 + var3 + var4
```

Several notes should be made regarding the `design` formula:

* multiple nonlinear covariates are supported, 
e.g. `design = ~ s(pheno) + s(var1) + var2 + var3 + var4`;

* the nonlinear covariate cannot be a discrete variable, e.g. 
`design = ~ s(pheno) + var1 + var2 + var3 + s(var4)` as `var4` is a factor, 
and it makes no sense to model a factor as nonlinear; 

* at least one nonlinear covariate should be provided in `design`. If all 
covariates are assumed to have linear effect on gene count, use DESeq2 
[@love2014moderated], edgeR [@robinson2010edger], NBPSeq [@di2015nbpseq] or
BBSeq [@zhou2011powerful] instead. e.g. 
`design = ~ pheno + var1 + var2 + var3 + var4` is not supported in NBAMSeq;

* design matrix is not supported. 

We then construct the `NBAMSeqDataSet` using `countData`, `colData`, 
and `design`: 

```{r}
gsd = NBAMSeqDataSet(countData = countData, colData = colData, design = design)
gsd
```

## Differential expression analysis

Differential expression analysis can be performed by `NBAMSeq` function:

```{r}
gsd = NBAMSeq(gsd)
```

Several other arguments in `NBAMSeq` function are available for users to 
customize the analysis.

* `gamma` argument can be used to control the smoothness of the nonlinear 
function. Higher `gamma` means the nonlinear function will be more smooth. 
See the `gamma` argument of 
[gam](https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/gam.html) 
function in mgcv [@wood2015package] for details. Default `gamma` is 2.5;

* `fitlin` is either `TRUE` or `FALSE` indicating whether linear model should 
be fitted after fitting the nonlinear model;

* `parallel` is either `TRUE` or `FALSE` indicating whether parallel should be
used. e.g. Run `NBAMSeq` with `parallel = TRUE`:

```{r eval=TRUE}
library(BiocParallel)
gsd = NBAMSeq(gsd, parallel = TRUE)
```


## Pulling out DE results

Results of DE analysis can be pulled out by `results` function. For continuous
covariates, the `name` argument should be specified indicating the covariate of
interest. For nonlinear continuous covariates, base mean, effective degrees of 
freedom (edf), test statistics, p-value, and adjusted p-value will be returned.

```{r}
res1 = results(gsd, name = "pheno")
head(res1)
```

For linear continuous covariates, base mean, estimated coefficient, standard 
error, test statistics, p-value, and adjusted p-value will be returned.

```{r}
res2 = results(gsd, name = "var1")
head(res2)
```

For discrete covariates, the `contrast` argument should be specified. e.g. 
`contrast = c("var4", "2", "0")` means comparing level 2 vs. level 0 in `var4`.

```{r}
res3 = results(gsd, contrast = c("var4", "2", "0"))
head(res3)
```

## Visualization

We suggest two approaches to visualize the nonlinear associations. The first 
approach is to plot the smooth components of a fitted negative binomial 
additive model by `plot.gam` function in mgcv [@wood2015package]. This can be
done by calling `makeplot` function and passing in `NBAMSeqDataSet` object. 
Users are expected to provide the phenotype of interest in `phenoname` 
argument and gene of interest in `genename` argument.

```{r}
## assuming we are interested in the nonlinear relationship between gene10's 
## expression and "pheno"
makeplot(gsd, phenoname = "pheno", genename = "gene10", main = "gene10")
```

In addition, to explore the nonlinear association of covariates, it is also 
instructive to look at log normalized counts vs. variable scatter plot. 
Below we show how to produce such plot.

```{r}
## here we explore the most significant nonlinear association
res1 = res1[order(res1$pvalue),]
topgene = rownames(res1)[1]  
sf = getsf(gsd)  ## get the estimated size factors
## divide raw count by size factors to obtain normalized counts
countnorm = t(t(countData)/sf) 
head(res1)
```

```{r}
library(ggplot2)
setTitle = topgene
df = data.frame(pheno = pheno, logcount = log2(countnorm[topgene,]+1))
ggplot(df, aes(x=pheno, y=logcount))+geom_point(shape=19,size=1)+
    geom_smooth(method='loess')+xlab("pheno")+ylab("log(normcount + 1)")+
    annotate("text", x = max(df$pheno)-5, y = max(df$logcount)-1, 
    label = paste0("edf: ", signif(res1[topgene,"edf"],digits = 4)))+
    ggtitle(setTitle)+
    theme(text = element_text(size=10), plot.title = element_text(hjust = 0.5))
```

## Session info

```{r sessionInfo}
sessionInfo()
```


## References
