---
title: "Getting started with EWAScaller"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with EWAScaller}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

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

EWAScaller queries the [EWAS Atlas](https://ngdc.cncb.ac.cn/ewas/) database
for epigenome-wide association study results, and runs enrichment analyses
on CpG probe sets. Because every example below contacts a remote web
service, the code in this vignette is shown but not executed when the
package documentation is built; run it interactively to see live results.

```{r setup}
library(EWAScaller)
```

## Querying by CpG probe

```{r}
res <- query_cpg(c("cg05575921", "cg11903855", "cg00240195"), workers = 2, delay = 1)
res
summary(res)
head(res$associations)
head(res$probes)
```

`query_cpg()`, `query_gene()`, and `query_region()` all return an
`ewas_result` object with the same shape: an `associations` table (one row
per probe-trait association), a `probes` table (one row per unique probe),
and a `failed` table listing any input terms that could not be resolved.

## Querying by gene or genomic region

```{r}
gene_res <- query_gene(c("AHRR", "F2RL3"))
region_res <- query_region(chr = "5", start = 373000, end = 374000)
```

Multiple regions can be supplied at once via a data frame:

```{r}
regions <- data.frame(chr = c("5", "1"), start = c(373000, 1), end = c(374000, 100000))
query_region(regions)
```

## Enrichment analysis

`ewas_enrichment()` submits a probe set (20-5000 probes) to the EWAS Atlas
toolkit and retrieves enrichment results against a chosen background
(`"450K"`, `"850K"`, or a custom probe list).

```{r}
# enrichment needs 20-5000 distinct probes
probes <- c(
  "cg05575921", "cg00240195", "cg16419584", "cg11903855", "cg21566642",
  "cg23771366", "cg19859270", "cg00382138", "cg25648203", "cg01940273",
  "cg23576855", "cg00401753", "cg00300637", "cg12803068", "cg09935388",
  "cg01899089", "cg04180046", "cg00050873", "cg02228185", "cg18147296"
)

enr <- ewas_enrichment(
  probes,
  background = "850K",
  types = c("trait", "genomic_location", "gene_ontology", "kegg")
)
enr
summary(enr)
top_traits(enr)
```

## EPIC v2 arrays

EWAS Atlas annotates probes by their 450K/EPIC v1 names. EPIC v2 names
such as `cg05575921_BC21` are accepted by every function and converted to
`cg05575921`; replicate EPIC v2 probes are merged into one. For enrichment
and eQTM analyses, set `background = "EPICv2"`. EWAS Atlas has no EPIC v2
background, so the EPIC/850K background is used instead; it also contains
EPIC v1 probes that are not on EPIC v2, so genomic location, GO, and KEGG
p-values are approximate (trait enrichment does not depend on the
background). Probes that are new on EPIC v2 have no EWAS Atlas data, and
the toolkit rejects a job containing any of them, so they are dropped
before submission and listed in the result's `excluded` element.

```{r}
v2_probes <- paste0(probes, "_BC21")
enr_v2 <- ewas_enrichment(v2_probes, background = "EPICv2")
enr_v2$excluded  # EPIC v2-only probes that were dropped
```

## eQTM: CpG methylation vs gene expression

Expression quantitative trait methylation (eQTM) pairs link a CpG to a gene
whose expression correlates with that CpG's methylation. `ewas_eqtm()` runs
the EWAS Atlas toolkit's "Expression Regulation" analysis, which reports
Pearson correlations computed from matched methylation and RNA-seq data in
The Cancer Genome Atlas (TCGA), for several tissues. It takes the same
20-5000 probe set as `ewas_enrichment()`, and reuses the toolkit job if the
same probes were already submitted.

```{r}
eq <- ewas_eqtm(probes, background = "850K")
eq
summary(eq)
head(eq$pairs)
```

Each row of `eq$pairs` is one CpG-gene-tissue correlation, with the gene's
symbol and Ensembl identifier, the CpG's position relative to the gene,
the correlation `cor`, its `p` value, the `tissue`, and the TCGA `source`.
`eqtm_samples()` downloads the per-sample values behind one pair:

```{r}
eqtm_samples("cg05575921", "ENSG00000063438", "brain")
```

## Plots

```{r}
plot_wordcloud(res)
plot_wordcloud(enr, type = "trait")
plot_wordcloud(eq)

autoplot(res, type = "traits")
autoplot(res, type = "chromosome")
autoplot(res, type = "direction")
autoplot(enr, type = "trait")
autoplot(enr, type = "kegg", style = "bar")

autoplot(eq, type = "heatmap")
autoplot(eq, type = "volcano", label_top = 10)
autoplot(eq, type = "tissue")
autoplot(eq, type = "scatter", probe = "cg05575921", gene = "AHRR", tissue = "brain")
```

### Customising plots

All `autoplot()` methods share the arguments `colors`, `title`,
`subtitle`, `base_size`, `theme`, and `wrap`, and `plot_wordcloud()`
accepts `title`, `subtitle`, `base_size`, `theme`, `max_size`, and `seed`.
`title = NULL` keeps the default title and `title = NA` removes it. `theme`
takes any ggplot2 theme function (called with `base_size`) or a complete
theme object. What `colors` means depends on the plot; see
`?autoplot.ewas_eqtm` for the eQTM plots.

```{r}
autoplot(eq, type = "heatmap",
         colors = c("navy", "white", "firebrick"),
         title = "Smoking CpGs: eQTM", theme = ggplot2::theme_bw, base_size = 13)

autoplot(enr, style = "bar", colors = "#6d597a", wrap = 25, title = NA)
```

Every plot is an ordinary `ggplot` object, so anything else can be added
with `+`, e.g. `autoplot(eq, type = "volcano") + ggplot2::xlim(-1, 1)`.

## Rate limiting

Query functions dispatch up to `workers` requests concurrently and pause
`delay` seconds between batches. Increase `workers` for faster throughput on
large probe lists, or increase `delay` to be gentler on the remote service.
