---
title: "Build functional gene modules with GNET2"
author: "Chen Chen"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Build functional gene modules with GNET2}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup,echo = FALSE, include = TRUE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

## 1. Introduction
GNET2 is a R package used for build regulator network and cluster genes to functional groups with E-M process.
It iterative perform TF assigning and Gene assigning, until the assignment of genes did not change, or max number of iterations is reached.

## 2. Installation
To install, open R and type:
```
install.packages("devtools")
library("devtools")
install_github("chrischen1/GNET2")
```

## 3. Build module networks
```{r load_packages, message=FALSE, warning=FALSE, include=FALSE}
library(GNET2)
```

We first generate random expression data and a list of regulator gene names. 

The input is typically a p by n matrix of expression data of p genes and n samples, for example log2 RPKM from RNA-Seq.

```{r,echo = TRUE}
set.seed(2)
init_group_num = 8
init_method = 'boosting'
exp_data <- matrix(rnorm(300*12),300,12)
reg_names <- paste0('TF',1:20)
rownames(exp_data) <- c(reg_names,paste0('gene',1:(nrow(exp_data)-length(reg_names))))
colnames(exp_data) <- paste0('condition_',1:ncol(exp_data))
```


For the list of potential regulator genes, they are usually available from databases. For example, the PlantTFDB (http://planttfdb.gao-lab.org/download.php) curated lists of transcription factors in 156 species, and this information can be imported by the follow steps:

```
url <- "http://planttfdb.gao-lab.org/download/TF_list/Ath_TF_list.txt.gz"
dest_file <- './Ath_TF_list.txt.gz'
download.file(url, destfile)
reg_names <- read.table(gzfile(destfile),sep="\t",header = T,as.is = T)$Gene_ID
```

The module construction process make take a few time, depending on the size of data and maximum iterations allowed. 

```{r, echo=TRUE}
gnet_result <- gnet(exp_data,reg_names,init_method,init_group_num,heuristic = TRUE)
```

## 4. Plot the modules and trees
Plot the regulators module and heatmap of the expression inferred downstream genes for each sample. It can be interpreted as two parts:
the bars at the top shows how samples are split by the regression tree and the heatmap at the bottom shows how downstream genes are regulated by each subgroup determined by the regulators.

```{r, echo=TRUE,fig.width=10, fig.height=12}
plot_gene_group(gnet_result,group_idx = 1,plot_leaf_labels = T)
```

It is also possible to compare the clustering of GNET2 with experiment conditions by providing the labels of conditions

```{r, echo=TRUE,fig.width=10, fig.height=12}
exp_labels = rep(paste0('Exp_',1:4),each = 3)
plot_gene_group(gnet_result,group_idx = 1,group_labels = exp_labels)
```

The similarity between the clusters from each module of GNET2 and experiment conditions can be quantified by Adjuster Rand Index (for categorical labels) or the inverse of K-L Divergence (for ordinal labels, e.g. dosage,time points). For both cases, significant P values suggests high similarity between the grouping of the modules and the label information provided by the user. 

```{r, echo=TRUE,fig.width=10, fig.height=12}
exp_labels_factor = as.numeric(factor(exp_labels))

print('Similarity to categorical experimental conditions of each module:')
print(similarity_score(gnet_result,exp_labels_factor))

print('Similarity to ordinal experimental conditions of each module:')
print(similarity_score(gnet_result,exp_labels_factor),ranked=TRUE)
```


Plot the tree of the first group

```{r, echo=TRUE,fig.width=8, fig.height=8}
plot_tree(gnet_result,group_idx = 1)
```


Plot the correlation of each group and auto detected knee point.

```{r, echo=TRUE,fig.width=8, fig.height=8}
group_above_kn <- plot_group_correlation(gnet_result)
print(group_above_kn)
```

The group IDs in group_above_kn can been used as a list of groups with correlation higher than the knee point. You may consider use them only for further analysis.

## 5. extract information from the GNET2 output
Show the total number of modules

```{r, echo=TRUE,fig.width=8, fig.height=8}
print('Total number of modules:')
print(gnet_result$modules_count)
```

Show the regulatory genes and target genes in the first module

```{r, echo=TRUE,fig.width=8, fig.height=8}
group_index = 1
print('Regulators in module 1:')
print(gnet_result$regulators[[group_index]])
print('Targets in module 1:')
print(gnet_result$target_genes[[group_index]])
```

Return the interactions and their scores as adjacency matrix

```{r, echo=TRUE,fig.width=8, fig.height=8}
mat <- extract_edges(gnet_result)
print(dim(mat))
```


```{r, echo=TRUE}
sessionInfo()
```
