---
author: "SysBioLab"
output:
  html_document:
    toc: true
    toc_float: true
    df_print: paged
    fig_width: 12
---

<style type='text/css'>
    body .main-container { 
        max-width: 90%;
    
    }

    .plot_real_size {
      overflow: scroll;
      max-height: 600px;
    }

    .plot_real_size img{
      max-width: none;
      max-height: none;
    }

    embed {
   
  }   
</style>


# **CoRmiT: RNAseq - miRNAseq correlation report**

This report summarizes the results of ExpHunterSuite CoRmiT, comparing RNAseq and miRNAseq data and looking for putative miRNA-gene target interactions based on different strategies.

## **Strategies comparison**

miRNAseq and RNAseq data are compared and expression levels correlated using multiple strategies. 
Correlated miRNA-mRNA pairs are known **significant pairs** representing putative miRNA-mRNA target interactions. 
Results are then compared with multiMiR databases.

* Brief description of strategies used: 
  specific_evaluation <- eval_method == "specific"
```

```{r check_sig_specific, echo =FALSE, warning=FALSE, result = "asis", eval = (eval_method == "specific")}
  sig_strategies <- unique(cont_tables$strategy[!is.na(cont_tables$coverage)])
```

```{r print_info, echo = FALSE, warning = FALSE, results = "asis", eval = FALSE}

  sig_strategies <- names(strategies)[! names(strategies) %in% unsig_strategies]
  cat(parse_strat_text(sig_strategies))

  mock_strategies <-   c() #"Eigengene_0_RNA_vs_miRNA_normalized_counts", 
      # "normalized_counts_RNA_vs_miRNA_Eigengene_0", 
      # "DEGs_RNA_vs_miRNA_DEMs",
     # "DEGs_DEMs_permutated")

```

```{r sig_unsig, echo = FALSE, warning = FALSE, results = "asis", eval = FALSE}


cat("

  * Three **control strategies** are also used:
    + **Similar lFC:** All possible permutations between differentially expressed genes (DEGs) and differentially expressed miRNAs (DEMs) with similar log2FC (Possitive control). Correlation is not performed.
    + **Opposite lFC:** All possible permutations between DEGs and DEMs with opposite log2FC (Negative control). Correlation is not performed.
    + **E0_vs_counts:** Correlation between the Eigengene profile for gene module 0 (which contains genes that could not be assigned to any other coexpression module) and miRNA normalized counts (Negative control).

Graphics are only displayed for the strategies that were run and for which significant results were found. 
The **control strategies** are artifical correlation strategies used for comparison with the real strategies in terms of performance.
Their results should not be considered for miRNA-gene target selection.

")
    # + **normalized_counts_RNA_vs_miRNA_Eigengene_0:** Correlation between gene normalized counts and the Eigengene profile for miRNA module 0, which contains miRNAs that could not be assigned to any other module.
  sig_strats <-  paste0("**", paste(sig_strategies, collapse = "**, **"), "**")

  unsig_strats <- paste0("**", paste(unsig_strategies, collapse = "**, **"), "**")

 cat(paste0("In this report, only the strategies ", sig_strats[!sig_strats %in% mock_strategies], " produced signficant results.\n\n"))
 if (length(unsig_strategies) > 0){
  cat(paste0(unsig_strats, " were run, however no signficant correlated pairs were obtained."))
 } 

```

### **Correlation distributions**

Distributions of correlation values between miRNAs and target genes obtained using the different strategies.
Dashed line shows the correlation cut-off below which miRNA-target pairs are considered significant. 
Horizontal white lines within the distributions represent the 90 and 95 percentiles. 
The **DEGs_DEMs_permutated** strategy is not included.


```{r methods_comparison_violin_cor, echo=FALSE, results = 'asis', warning = FALSE, message = FALSE}
all_cor_dist_fil <- all_cor_dist[!all_cor_dist$strategy %in% c("DEGs_RNA_vs_miRNA_DEMs_opp", "DEGs_RNA_vs_miRNA_DEMs_sim"),]
pp <- ggplot2::ggplot(all_cor_dist_fil, ggplot2::aes(x = strategy, y = correlation, fill = strategy)) +
  ggplot2::geom_violin(col = "white",trim = FALSE, scale = "width",draw_quantiles = c(0.1, 0.05)) + #ggplot2::ylim(-1.000001, min + 0.00001) +
  ggplot2::geom_hline(yintercept= corr_cutoff, linetype = "dashed", colour = "black") +
  ggplot2::geom_boxplot(width=0.05)+ ggplot2::ylim(-1, 1)+
  ggplot2::coord_flip()+
  ggplot2::theme(axis.text.y = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank()) +
  ggplot2::labs(fill = "Strategy")

pp 
```

### **Correlation p-values distribution**

Distributions of correlation p-values between miRNAs and target genes obtained using the different strategies.
The dashed line represents a p-value of 0.05
The **DEGs_RNA_vs_miRNA_DEMs_opp** and **DEGs_RNA_vs_miRNA_DEMs_sim** strategy are not included.

```{r methods_comparison_violin_p, echo=FALSE, results = 'asis', warning = FALSE, message = FALSE}

pp <- ggplot2::ggplot(all_cor_dist_fil, ggplot2::aes(x = strategy, y = pval, fill = strategy)) +
  ggplot2::geom_violin(trim = FALSE, scale = "width") + 
  ggplot2::geom_hline(yintercept= p_val_cutoff, linetype = "dashed", colour = "black") +
  ggplot2::geom_boxplot(width=0.05)+ ggplot2::ylim(-0.01, 1) +
  ggplot2::coord_flip()+
  ggplot2::theme(axis.text.y = ggplot2::element_blank(), axis.title.y = ggplot2::element_blank()) +
  ggplot2::labs(fill = "Strategy")
pp

```

### **Overlapping strategies**

This table shows the number of **significant pairs** overlapping between strategies.

```{r methods_comparison_intersection, echo=FALSE, results = 'asis', warning = FALSE, message = FALSE}
 subchunk_count <- 3
  common_pairs <- sig_pairs[["all"]]
  sig_pairs[["all"]] <- NULL
  common_pairs <- as.data.frame(as.table(as.matrix(common_pairs)))
  names(common_pairs) <- c("x_axis", "y_axis",  "intersection")
  common_pairs$text <- as.character(common_pairs$intersection)
  common_pairs$x_axis <- as.character(common_pairs$x_axis)
  common_pairs$y_axis <- as.character(common_pairs$y_axis)
  # common_pairs[common_pairs$x_axis == common_pairs$y_axis, "text"] <- "-"
  pp <- gg_heatmap(data =  common_pairs, 
              x_axis = "x_axis",
              y_axis= "y_axis",
              fill = "intersection",
              text_plot= "text", 
              labs = FALSE)
  subchunk_count <- rechunk(pp, counter = subchunk_count, 
          chunk_options = "echo=FALSE, results = 'asis', warning = FALSE, message = FALSE")

```

### **Overlapping strategies for different database groups**

The following tables shows the number of significant pairs that were found in multiMiR database groups for each strategy, and their overlap.

MultiMiR pairs can be classified based on which kind of database they appear in. The two main groups are **predicted** pairs and experimentally **validated** pairs.
We therefore repeated the steps indicated above for the union of **predicted** databases, **validated** databases, and their intersection **(pred_and_val)**.


```{r methods_comparison_intersection_groups, echo=FALSE, results = 'asis', warning = FALSE, message = FALSE}

for (db_group in names(sig_pairs)){
   common_pairs <- sig_pairs[[db_group]]
   check_ovlp <- common_pairs
   diag(check_ovlp) <- 0
   cat(paste0("#### **Overlap of significant pairs found on ", stringr::str_to_title(db_group), " databases**\n\n"))
   if (any(check_ovlp > 0)){
       common_pairs <- as.data.frame(as.table(as.matrix(common_pairs)))
       names(common_pairs) <- c("x_axis", "y_axis",  "intersection")
       common_pairs$text <- as.character(common_pairs$intersection)
       common_pairs$x_axis <- as.character(common_pairs$x_axis)
       common_pairs$y_axis <- as.character(common_pairs$y_axis)
       # common_pairs[common_pairs$x_axis == common_pairs$y_axis, "text"] <- "-"
       pp <- gg_heatmap(data =  common_pairs, 
                   x_axis = "x_axis",
                   y_axis= "y_axis",
                   fill = "intersection",
                   text_plot= "text", 
                   labs = FALSE)
       subchunk_count <- rechunk(pp, counter = subchunk_count, 
               chunk_options = "echo=FALSE, results = 'asis', warning = FALSE, message = FALSE")
   } else {
       cat(paste0("There were not overlap between significant pairs of strategies for ", db_group, " databases.\n\n"))
   }
}
   
```

### **Odds ratios for the different strategies**

The plot shows the significant strategies ordered by Odds ratio (OR). 
OR can be thought of as a measure of the association between a given strategy and pairs in the databases. 
OR > 1 represents association while OR = 1 means independence.
The color represents the p-value from the Fisher exact test.
The X-axis represents the OR and the dot size the number of pairs associated with the group of databases.

```{r dotplot, echo=FALSE, results = 'asis', warning = FALSE, message = FALSE}

significant_ct <- cont_tables[!cont_tables$strategy %in% unsig_strategies,]
splitted_c_tables <- split(significant_ct, significant_ct$db_group)

for (db_group in c("predicted", "validated")){
  filtered_cont <- splitted_c_tables[[db_group]]  
  
  cat(paste0("\n\n#### Comparison with ", stringr::str_to_title(db_group), " pairs\n\n"))
  
  overal_OR <- plot_odds_ratio(filtered_cont)
  plot(overal_OR)
  cat("\n\n")
  if (specific_evaluation) {
     cat("\n\nmedian_OR: miRNAs were evaluated independently. OR and Fisher exact test P value was computed for every miRNA and here is represented the median of the OR for miRNA with a P value lower than 0.05.
In that case Strategies without significant miRNAs were rejected.
\n\n")

     filtered_cont <- filtered_cont[!is.na(splitted_c_tables[[db_group]]$median_OR),]
     if (nrow(filtered_cont) == 0 ) {
       cat(paste0("\n\nAny miRNA overlapped with ", db_group," pairs databases. Plotting general stats.\n\n"))
       next 
     }
  filtered_cont[,"Validated_pairs"] <- filtered_cont$TP
  specific_OR <- ggplot2::ggplot(filtered_cont, ggplot2::aes(x = coverage, y = median_OR)) +
  ggplot2::geom_point(ggplot2::aes(color = strategy, size = Validated_pairs), alpha = 0.3) + 
  ggrepel::geom_text_repel(ggplot2::aes(label = coverage_text)) # +
  # ggplot2::theme(legend.position="bottom") +
  # ggplot2::guides(colour = guide_legend(nrow = 4))

  plot(specific_OR)
    cat("\n\n")

    }
}
```


## **Strategies specific results**

```{r render_partial_reports, echo = FALSE, warning = FALSE}
  curr_out <- ""

  curr_out <- unlist(lapply(sig_strategies[sig_strategies != "DEGs_DEMs_permutated"] ,function(method_name){
      sec_text <- paste(c("### **", method_name ," correlation method**\n"),collapse="") # Header
      sec_text <- c(sec_text, knitr::knit_expand("partial/miRNA_cor_methods.Rmd")) # Body
      return(sec_text)
  }))    

``` 
`r paste(knitr::knit(text = curr_out), collapse = '\n')`





### **Values of options used to run CorMiT**
First column contains the option names; second column contains the given values for each option in this run.
```{r opt_vals, echo = FALSE, warning = FALSE}
knitr::kable(cbind(opt))
```




