
```{r MOFA_chunkoptions, include = FALSE, hide = TRUE, eval = TRUE}
explorDir <- paste0(outDir,"/","Integration/MOFA2/")
dir.create(path = explorDir)

opts_chunk$set(fig.path = explorDir)
```

```{r MOFA_extract}
MOFARes <- MOFAset <- NULL
MOFARes <- getMOFA(rflomics.MAE)
MOFAset <- getMOFASettings(rflomics.MAE)
```


```{r}
fig_width <- 15
nDat <- length(views_names(MOFARes))
n_lines <- ceiling(nDat/2)
fig_height <- n_lines*5.5
```

```{r}
library(ggpubr)
library(gridExtra)
```


```{r}
VarExp <- get_variance_explained(MOFARes)$r2_per_factor$group1
FactNum <- apply(VarExp, 1, FUN = function(vect) any(vect > 5)) # Percentage
nMOFAFactors <- MOFARes@dimensions$K
```

### Settings

MOFA2  R package was used to perform data unsupervised integration, on <span style="color:blue">`r paste(MOFA2::views_names(MOFARes), collapse = ", ")`</span> datatables.

<ins>Variable selection: </ins>

```{r MOFA2_selection, results="asis"}
listSel <- NULL
listSel <- MOFAset$selectionMethod

listSel2 <- lapply(names(listSel),  FUN = function(nam) {
    dat <- listSel[[nam]]
    varNam <- RFLOMICS:::.omicsDic(rflomics.MAE, SE.name = nam)$variableName
    switch(dat[1], 
           "diff" = {
               paste0("Only differentially expressed ", 
                      varNam, 
                      " were processed in the multi-omics analysis, taking the ", 
                      ifelse(dat[2], "union", "intersection"), " of all contrasts lists.")
           },
           "CV" = {
               paste0("<span style=\"color:blue\">",
                      get_dimensions(MOFARes)$D[[nam]], "</span> ",
                      varNam, 
                      " were selected based on the coefficient of variation.")
           },
           "none" = paste0("No features selection was applied, all ",
                           varNam,
                           " were taken into account."))
})
names(listSel2) <- names(listSel)

for (nam in names(listSel2)) {
    cat("* ", nam, ": ", listSel2[[nam]], "\n")
}
rm(listSel, listSel2)
```

This leads to the following analysis setting: 
```{r MOFA2_data_overview, fig.width=6.5, fig.height = 1.5*nDat, fig.align="center"}
plot_data_overview(MOFARes)
```

<ins>Run information: </ins>

* Options:
  * Scale views: `r MOFAset$scale_views` 
  * Number of factors: `r MOFAset$num_factors`. Obtained number of factors: `r MOFA2::get_dimensions(MOFARes)$K`
  * Number of iterations: `r MOFAset$maxiter` 
* RNASeq data were transformed using <span style="color:DarkOrchid">voom</span> transformation from limma package 
* Batch effects `r paste(RFLOMICS::getBatchFactors(rflomics.MAE), collapse = ", ")`  were corrected using <span style="color:DarkOrchid">removebatcheffect</span> function from limma package.

###  Results

#### Correlation between factors

```{r}
mat_cor <- stats::cor(get_factors(MOFARes)[[1]])
mat_cor <- mat_cor - diag(mat_cor)
```

* Number of computed factors: `r nMOFAFactors` 
* Is there a correlation >0.5 between two factors? `r ifelse(any(mat_cor>0.5), "YES, be careful, the results are unreliable.", "No. Results are reliable.")`

The correlation between factor is an indicator to judge the quality of your results. Factors are supposed to be orthogonal (correlation is theoretically 0 between two different ones), however, in some cases (wrong pre-processing or two many factors) it can happen that there is a correlation >0.5 between factors. 

```{r MOFA2_factor_cor, fig.width = min(nMOFAFactors+0.5, 5), fig.height = min(nMOFAFactors, 5), fig.align="center"}
plot_factor_cor(MOFARes)
```

#### Explained Variance

These two graphs represent the cumulative explained variance per dataset and its decomposition by factor and dataset. This is the amount of variance within the dataset that is explained by the model (factors). The second graph is read line by line, each line describing the percentage of variance explained by a factor for each table. For two tables X and Y, it is interpreted as follows: 'Factor k explains xx% of the total variance of dataset X and yy% of the total variance of dataset Y.'

`r ifelse(sum(FactNum)>5, "In the rest of the report, only the first 5 factors will be shown.", paste0("In the rest of the report, <span style=\"color:blue\">", sum(FactNum), "</span> will be shown in the figure: this is the number of factor representing at least 5% of explained variance in any table."))`

```{r explained_variance, fig.width = 10, fig.height = 4, fig.align = "center"}
# compute both per factor and per table by default.
g1 <- plot_variance_explained(MOFARes, plot_total = TRUE)[[2]] + 
    ggtitle("Total explained variance per omic data")
g2 <- plot_variance_explained(MOFARes, x = "view", y = "factor") + 
    ggtitle("Explained variance by factors and omic data")

ggpubr::ggarrange(g1, g2, ncol = 2)
```

#### Weights of the factors explaining the most variance {.tabset}

The following image shows the weights and their sign (positive or negative) of the *15 first features*, for each table and each factors for the first `r sum(FactNum)` factors. 

```{r, results="asis", fig.height = fig_height, fig.width=fig_width, fig.align = "center"}
childTest <- NULL
outMOFA <- NULL

for (i in which(FactNum)) {
    outMOFA <- c(outMOFA,
                 paste0("\n##### Factor", i, " \n"))
    ggplot_sublist <- list()
    
    for (j in views_names(MOFARes)) {
        
        ggplot_sublist[[length(ggplot_sublist) + 1]] <- plot_top_weights(MOFARes,
                                                                                view = j,
                                                                                factors = i,
                                                                                nfeatures = 15,
                                                                                scale = TRUE) +
            ggtitle(paste0(j, " - Factor ", i))
    }
    
    childTest <-  c(
        "```{r, fig.width = fig_width, fig.height = fig_height}\n",
        "ggpubr::ggarrange(plotlist = ggplot_sublist, 
                ncol = 2, nrow = n_lines)",
        "```\n")
    outMOFA <- c(outMOFA, knitr::knit_child(text = childTest,
                                            envir = environment(),
                                            quiet = TRUE))
}
knitr::asis_output(outMOFA)

```

#### Heatmaps {.tabset}

For all views, these heatmaps show the *15 first features* in terms of weights for the first `r sum(FactNum)` factors. These are the transformed and processed data passed to MOFA2, not the raw data or denoised data.

```{r, fig.width = 15, fig.height = 5.5*nDat, fig.show = "hold", include = FALSE, fig.keep = "none"}
list_heat_views <- list()
list_arrange <- list()
for (fac in seq_len(MOFARes@dimensions$K)) {
    list_heat_views[[fac]] <- list()
    for (nam in views_names(MOFARes)) {
        list_heat_views[[fac]][[nam]] <- NULL
        png(file = "temp.png")
        list_heat_views[[fac]][[nam]] <- plot_data_heatmap(MOFARes, 
                                                                  view = nam, 
                                                                  factor = fac, 
                                                                  features = 15, 
                                                                  main = paste0(nam, " - Factor ", fac))
        dev.off()
        invisible(file.remove("temp.png"))
    }
    list_arrange[[fac]] <- gridExtra::grid.arrange(grobs = lapply(list_heat_views[[fac]], FUN = function(object) object$gtable),
                                                   ncol = 1)
}
dev.off()
```

##### Factor 1

```{r MOFA2_heatmap1, fig.width = fig_width, fig.height = fig_height*1.5}
ggpubr::as_ggplot(list_arrange[[1]])
```

##### Factor 2

```{r MOFA2_heatmap2, fig.width = fig_width, fig.height = fig_height*1.5}
ggpubr::as_ggplot(list_arrange[[2]])
```

`r if(sum(FactNum)<3) {"\\begin{comment}"}`

##### Factor 3

```{r MOFA2_heatmap3, fig.width = fig_width, fig.height = fig_height*1.5}
ggpubr::as_ggplot(list_arrange[[3]])
```

`r if(sum(FactNum)<3) {"\\end{comment}"}`


`r if(sum(FactNum)<4) {"\\begin{comment}"}`

##### Factor 4

```{r MOFA2_heatmap3, fig.width = fig_width, fig.height = fig_height*1.5}
ggpubr::as_ggplot(list_arrange[[4]])
```

`r if(sum(FactNum)<4) {"\\end{comment}"}`

`r if(sum(FactNum)<5) {"\\begin{comment}"}`

##### Factor 5

```{r MOFA2_heatmap3, fig.width = fig_width, fig.height = fig_height*1.5}
ggpubr::as_ggplot(list_arrange[[5]])
```

`r if(sum(FactNum)<5) {"\\end{comment}"}`

#### Correlation between factors and metadata 

This table presents the adjusted pvalues from a kruskall-wallis test between 
each factor and each biological or metadata factor entered in the design.
Pvalues are corrected using Benjamini-Hochberg method row-wise.
This allows to make the connection between MOFA2 results and prior information 
on the datasets. 

```{r}
relationsDF <- RFLOMICS:::.relationsMOFA(mofaRes = MOFARes, method = "BH")
namcol <- colnames(relationsDF)
brks <- c(0.05, 0.1)
```

```{r, results="asis"}
DT::datatable(relationsDF, 
              class = 'cell-border stripe', 
              options = list(dom = 't')) |>
    DT::formatStyle(
        columns = namcol,
        backgroundColor = DT::styleInterval(brks, 
                                            c('forestgreen',
                                              "yellow2",
                                              "white"))) |> 
    DT::formatSignif(columns = seq_len(length(namcol)), 
                     digits = 3)
```

<br>

```{r, results="asis", fig.width = fig_width, fig.height = fig_height}
cat('\n#### {.unlisted .unnumbered .tabset} \n')
cat("\n")

childTest <- NULL
outMOFA <- NULL

for (i in seq_len(length(rownames(relationsDF)))) {
    outMOFA <- c(outMOFA,
             paste0("\n##### ", rownames(relationsDF)[i], " \n"))
    
    childTest <-  c("```{r, fig.width = 15, fig.height = 5.5}\n",
                    "MOFA2::plot_factor(
                    MOFARes,
                    factors = seq_len(min(5, sum(FactNum))),
                    color_by = rownames(relationsDF)[i],
                    group_by = rownames(relationsDF)[i],
                    shape_by = rownames(relationsDF)[i],
                    legend = TRUE,
                    add_violin = TRUE,
                    violin_alpha = 0.25,
                    add_boxplot = FALSE,
                    boxplot_alpha = 0.25,
                    dodge = TRUE,
                    scale = FALSE,
                    dot_size = 3
                ) + 
                theme(text = element_text(size = 15))\n", 
                "```\n")
    outMOFA <- c(outMOFA, knitr::knit_child(text = childTest, 
                                    envir = environment(), 
                                    quiet = TRUE))
}
knitr::asis_output(outMOFA)
```

---

```{r MOFA2_export}
write.table(get_factors(MOFARes, as.data.frame = TRUE),
            file = paste0(explorDir, "Factors_values.txt"),
            sep = "\t", quote = FALSE, col.names = TRUE, row.names = TRUE)
write.table(get_weights(MOFARes, as.data.frame = TRUE),
            file = paste0(explorDir, "Factors_weights.txt"),
            sep = "\t", quote = FALSE, col.names = TRUE, row.names = TRUE)
```

