<!--
%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{Analyze with GREAT}
-->

Analyze with GREAT
==================

**Author**: Zuguang Gu ( z.gu@dkfz.de )

**Date**: `r Sys.Date()`

--------------------------------------------------------

```{r, echo = FALSE, message = FALSE}
library(knitr)
knitr::opts_chunk$set(
    error = FALSE,
    tidy  = FALSE,
    message = FALSE,
    fig.align = "center")
options(width = 100)
options(markdown.HTML.stylesheet = "custom.css")
```

**GREAT** ([Genomic Regions Enrichment of Annotations Tool](http://great.stanford.edu)) is a popular 
web-based tool to associate biological functions to genomic regions. 
The **rGREAT** package makes GREAT anlaysis automatic by first constructing a HTTP POST request 
according to user's input and retrieving results from **GREAT** web server afterwards.

Load the package:

```{r, echo = 2}
suppressWarnings(suppressPackageStartupMessages(library(rGREAT)))
library(rGREAT)
```

The input data is either a `GRanges` object or a _BED_-format data frame, no matter it is sorted or not.
In following example, we use a data frame which is randomly generated.

```{r}
set.seed(123)
bed = circlize::generateRandomBed(nr = 1000, nc = 0)
bed[1:2, ]
```

Submit genomic regions by `submitGreatJob()`. Before submitting, genomic regions will be sorted and overlapping regions will be merged.

The returned variable `job` is a `GreatJob` class instance which can be used to retrieve results from
**GREAT** server and stored results which are already downloaded.

```{r}
job = submitGreatJob(bed)
```

You can get the summary of your job by directly calling `job` variable.

```{r}
job
```

More parameters can be set for the job:

```{r, eval = FALSE}
job = submitGreatJob(bed, species = "mm9")
job = submitGreatJob(bed, bg, species = "mm9")
job = submitGreatJob(bed, adv_upstream = 10, adv_downstream = 2, adv_span = 2000)
job = submitGreatJob(bed, rule = "twoClosest", adv_twoDistance = 2000)
job = submitGreatJob(bed, rule = "oneClosest", adv_oneDistance = 2000)
```

Also you can choose different versions of GREAT for the analysis.

```{r, eval = FALSE}
job = submitGreatJob(bed, version = "3.0")
job = submitGreatJob(bed, version = "2.0")
```

Available parameters are (following content is copied from **GREAT** website):

- `species`:  `hg19` and `hg18` for human, `mm9` for mouse and `danRer7` for zebrafish
- `bgChoise`: Background regions. `wholeGenome` and `data`. If this value is set to `data`, `bg` argument should be specified 
- `includeCuratedRegDoms`: Whether to include curated regulatory domains.
- `rule`: How to associate genomic regions to genes.
    * `basalPlusExt`: mode 'Basal plus extension'. Gene regulatory domain definition: Each gene is assigned a basal regulatory domain of a minimum distance upstream and downstream of the TSS (regardless of other nearby genes). The gene regulatory domain is extended in both directions to the nearest gene's basal domain but no more than the maximum extension in one direction.
        + `adv_upstream`: proximal extension to upstream (unit: kb)
        + `adv_downstream`: proximal extension to downstream (unit: kb)
        + `adv_span`: maximum extension (unit: kb)
    * `twoClosest`: mode 'Two nearest genes'. Gene regulatory domain definition: Each gene is assigned a regulatory domain that extends in both directions to the nearest gene's TSS but no more than the maximum extension in one direction.
        + `adv_twoDistance`: maximum extension (unit: kb)
    * `oneClosest`: mode 'Single nearest gene'. Gene regulatory domain definition: Each gene is assigned a regulatory domain that extends in both directions to the midpoint between the gene's TSS and the nearest gene's TSS but no more than the maximum extension in one direction.
        + `adv_oneDistance`: maximum extension (unit: kb)


With `job`, we can now retrieve results from **GREAT**. The first and the primary results are
the tables which contain enrichment statistics for the analysis. By default it will retrieve 
results from three GO Ontologies and all pathway ontologies. All tables contains statistics 
for all terms no matter they are significant or not. Users can then make filtering yb self-defined cutoff.

One thing that users should note is that there is no column for adjusted p-values. But it is can be
easily done by using `p.adjust()`.

The returned value of `getEnrichmentTables()` is a list of data frames in which each one corresponds
to tables for single ontology. The structure of data frames are same as the tables on **GREAT** website.

```{r}
tb = getEnrichmentTables(job)
names(tb)
tb[[1]][1:2, ]
```

Information stored in `job` will be updated after retrieving enrichment tables.

```{r}
job
```

You can get results by either specifying the ontologies or by the pre-defined categories 
(categories already contains pre-defined sets of ontologies):

```{r, eval = FALSE}
tb = getEnrichmentTables(job, ontology = c("GO Molecular Function", "BioCyc Pathway"))
tb = getEnrichmentTables(job, category = c("GO"))
```

All available ontology names for given species can be get by `availableOntologies()` 
and all available ontology categories can be get by `availableCategories()`. Here you do not
need to provide species information because `job` already contains it.

```{r}
availableOntologies(job)
availableCategories(job)
availableOntologies(job, category = "Pathway Data")
```

Association between genomic regions and genes can be get by `plotRegionGeneAssociationGraphs()`.
The function will make the three plots which are same as on **GREAT** website and returns a `GRanges` 
object which contains the gene-region associations. 

```{r, fig.width = 12, fig.height = 4, fig.align = 'center'}
par(mfrow = c(1, 3))
res = plotRegionGeneAssociationGraphs(job)
res[1:2, ]
```

For those regions that are not associated with any genes under current settings, 
the corresponding `gene` and `distTSS` columns will be `NA`.

You can also choose only plotting one of the three figures.

```{r, eval = FALSE}
plotRegionGeneAssociationGraphs(job, type = 1)
```

By specifying ontology and term ID, you can get the association in a certain term.
Here the term ID is from the first column of the data frame which is returned by 
`getEnrichmentTables()`.

```{r, fig.width = 12, fig.height = 4}
par(mfrow = c(1, 3))
res = plotRegionGeneAssociationGraphs(job, ontology = "GO Molecular Function",
    termID = "GO:0004984")
res[1:2, ]
```

## Session info

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

