---
title: "Advanced examples"
abstract: >
  This vignette assumes you are familiar with set operations from the basic vignette.
date: "`r format(Sys.time(), '%Y %b %d')`"
output:
  html_document:
    fig_caption: true
    code_folding: show
    self_contained: yes
    toc_float:
      collapsed: true
      toc_depth: 3
author:
- name: Lluís Revilla
  email: lluis.revilla@gmail.com
vignette: >
  %\VignetteIndexEntry{Advanced examples}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteDepends{GO.db}
  %\VignetteDepends{reactome.db}
  %\VignetteDepends{GSEABase}
  %\VignetteDepends{org.Hs.eg.db}
  %\DeclareUnicodeCharacter{2229}{$\cap$}
  %\DeclareUnicodeCharacter{222A}{$\cup$}
editor_options: 
  chunk_output_type: console
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, 
                      warning = TRUE,
                      comment = "#>")
run_vignette <- requireNamespace("GSEABase", quietly = TRUE) &&
    requireNamespace("GO.db", quietly = TRUE) &&  
    requireNamespace("reactome.db", quietly = TRUE) && 
    requireNamespace("org.Hs.eg.db", quietly = TRUE) &&  
    requireNamespace("ggplot2", quietly = TRUE) &&
    requireNamespace("forcats", quietly = TRUE)
```


# Initial setup

To show compatibility with tidy workflows we will use magrittr pipe operator and the
dplyr verbs.

```{r setupr, message=FALSE}
library("BaseSet", quietly = TRUE)
library("dplyr", quietly = TRUE)
```

# Human gene ontology

We will explore the genes with assigned gene ontology terms. 
These terms describe what is the process and role of the genes.
The links are annotated with different [evidence codes](https://geneontology.org/docs/guide-go-evidence-codes/) to indicate how such annotation is supported. 

```{r prepare_GO, message=FALSE, eval=run_vignette}
# We load some libraries
library("org.Hs.eg.db", quietly = TRUE)
library("GO.db", quietly = TRUE)
library("ggplot2", quietly = TRUE)
# Prepare the data 
h2GO_TS <- tidySet(org.Hs.egGO)
h2GO <- as.data.frame(org.Hs.egGO)
```

We can now explore if there are differences in evidence usage for each ontology in gene ontology:

```{r evidence_ontology, eval=run_vignette}
library("forcats", include.only = "fct_reorder2", quietly = TRUE)
h2GO %>% 
    group_by(Evidence, Ontology) %>% 
    count(name = "Freq") %>% 
    ungroup() %>% 
    mutate(Evidence = fct_reorder2(Evidence, Ontology, -Freq),
           Ontology = case_match(Ontology,
                                 "CC" ~ "Cellular Component",
                                 "MF" ~ "Molecular Function",
                                 "BP" ~ "Biological Process",
                                 .default = NA)) %>% 
    ggplot() +
    geom_col(aes(Evidence, Freq)) +
    facet_grid(~Ontology) + 
    theme_minimal() +
    coord_flip() +
    labs(x = element_blank(), y = element_blank(),
         title = "Evidence codes for each ontology")
```

We can see that biological process are more likely to be defined by IMP evidence code that means inferred from mutant phenotype. 
While inferred from physical interaction (IPI) is almost exclusively used to assign molecular functions. 

This graph doesn't consider that some relationships are better annotated than other:

```{r nEvidence_plot, eval=run_vignette}
h2GO_TS %>% 
    relations() %>% 
    group_by(elements, sets) %>% 
    count(sort = TRUE, name = "Annotations") %>% 
    ungroup() %>% 
    count(Annotations, sort = TRUE) %>% 
    ggplot() +
    geom_col(aes(Annotations, n)) +
    theme_minimal() +
    labs(x = "Evidence codes", y = "Annotations", 
         title = "Evidence codes for each annotation",
         subtitle = "in human") +
    scale_x_continuous(breaks = 1:7)
```

We can see that mostly all the annotations are done with a single evidence code.
So far we have explored the code that it is related to a gene but how many genes don't have any annotation?

```{r numbers, eval=run_vignette}
# Add all the genes and GO terms
h2GO_TS <- add_elements(h2GO_TS, keys(org.Hs.eg.db)) %>% 
    add_sets(grep("^GO:", keys(GO.db), value = TRUE))

sizes_element <- element_size(h2GO_TS) %>% 
    arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)

sizes_set <- set_size(h2GO_TS) %>% 
    arrange(desc(size))
sum(sizes_set$size == 0)
sum(sizes_set$size != 0)
```

So we can see that both there are more genes without annotation and more gene ontology terms without a (direct) gene annotated.

```{r plots_GO, eval=run_vignette}
sizes_element %>% 
    filter(size != 0) %>% 
    ggplot() +
    geom_histogram(aes(size), binwidth = 1) +
    theme_minimal() +
    labs(x = "# sets per element", y = "Count")

sizes_set %>% 
    filter(size != 0) %>% 
    ggplot() +
    geom_histogram(aes(size), binwidth = 1) +
    theme_minimal() +
    labs(x = "# elements per set", y = "Count")
```

As you can see on the second plot we have very large values but that are on associated on many genes:

```{r distr_sizes, eval=run_vignette}
head(sizes_set, 10)
```


## Using fuzzy values

This could radically change if we used fuzzy values. 
We could assign a fuzzy value to each evidence code given the lowest fuzzy value for the [IEA (Inferred from Electronic Annotation)](https://wiki.geneontology.org/index.php/Inferred_from_Electronic_Annotation_(IEA)) evidence.
The highest values would be for evidence codes coming from experiments or alike. 

```{r fuzzy_setup, eval=run_vignette}
nr <- h2GO_TS %>% 
    relations() %>% 
    dplyr::select(sets, Evidence) %>% 
    distinct() %>% 
    mutate(fuzzy = case_match(Evidence,
                              "EXP" ~ 0.9,
                              "IDA" ~ 0.8,
                              "IPI" ~ 0.8,
                              "IMP" ~ 0.75,
                              "IGI" ~ 0.7,
                              "IEP" ~ 0.65,
                              "HEP" ~ 0.6,
                              "HDA" ~ 0.6,
                              "HMP" ~ 0.5,
                              "IBA" ~ 0.45,
                              "ISS" ~ 0.4,
                              "ISO" ~ 0.32,
                              "ISA" ~ 0.32,
                              "ISM" ~ 0.3,
                              "RCA" ~ 0.2,
                              "TAS" ~ 0.15,
                              "NAS" ~ 0.1,
                              "IC" ~ 0.02,
                              "ND" ~ 0.02,
                              "IEA" ~ 0.01,
                              .default = 0.01)) %>% 
    dplyr::select(sets = "sets", elements = "Evidence", fuzzy = fuzzy)
```

We have several evidence codes for the same ontology, this would result on different fuzzy values for each relation. 
Instead, we extract this and add them as new sets and elements and add an extra column to classify what are those elements:

```{r fuzzy_setup2, eval=run_vignette}
ts <- h2GO_TS %>% 
    relations() %>% 
    dplyr::select(-Evidence) %>% 
    rbind(nr) %>% 
    tidySet() %>% 
    mutate_element(Type = ifelse(grepl("^[0-9]+$", elements), "gene", "evidence"))
```

Now we can see which gene ontologies are more supported by the evidence:

```{r cardinality, eval=run_vignette}
ts %>% 
    dplyr::filter(Type != "Gene") %>% 
    cardinality() %>% 
    arrange(desc(cardinality)) %>% 
    head()
```

Surprisingly the most supported terms are protein binding, nucleus and cytosol. 
I would expect them to be the top three terms for cellular component, biological function and molecular function. 

Calculating set sizes would be interesting but it requires computing a big number of combinations that make it last long and require many memory available.

```{r size_go, eval=run_vignette}
ts %>% 
    filter(sets %in% c("GO:0008152", "GO:0003674", "GO:0005575"),
           Type != "gene") %>% 
    set_size()
```

Unexpectedly there is few evidence for the main terms:

```{r evidence_go, eval=run_vignette}
go_terms <- c("GO:0008152", "GO:0003674", "GO:0005575")
ts %>% 
    filter(sets %in% go_terms & Type != "gene") 
```

In fact those terms are arbitrarily decided or inferred from electronic analysis. 

# Human pathways

Now we will repeat the same analysis with pathways:

```{r prepare_reactome, eval=run_vignette}
# We load some libraries
library("reactome.db")

# Prepare the data (is easier, there isn't any ontoogy or evidence column)
h2p <- as.data.frame(reactomeEXTID2PATHID)
colnames(h2p) <- c("sets", "elements")
# Filter only for human pathways
h2p <- h2p[grepl("^R-HSA-", h2p$sets), ]

# There are duplicate relations with different evidence codes!!: 
summary(duplicated(h2p[, c("elements", "sets")]))
h2p <- unique(h2p)
# Create a TidySet and 
h2p_TS <- tidySet(h2p) %>% 
    # Add all the genes 
    add_elements(keys(org.Hs.eg.db))
```

Now that we have everything ready we can start measuring some things...

```{r numbers_pathways, eval=run_vignette}
sizes_element <- element_size(h2p_TS) %>% 
    arrange(desc(size))
sum(sizes_element$size == 0)
sum(sizes_element$size != 0)

sizes_set <- set_size(h2p_TS) %>% 
    arrange(desc(size))
```

We can see there are more genes without pathways than genes with pathways.

```{r pathways_plots, eval=run_vignette}
sizes_element %>% 
    filter(size != 0) %>% 
    ggplot() +
    geom_histogram(aes(size), binwidth = 1) +
    scale_y_log10() +
    theme_minimal() +
    labs(x = "# sets per element", y = "Count")

sizes_set %>% 
    ggplot() +
    geom_histogram(aes(size), binwidth = 1) +
    scale_y_log10() +
    theme_minimal() +
    labs(x = "# elements per set", y = "Count")
```

As you can see on the second plot we have very large values but that are on associated on many genes:

```{r distr_sizes_pathways, eval=run_vignette}
head(sizes_set, 10)
```

# Session info {.unnumbered}

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