

```{r}
analyzedDatasetNames <- getAnalyzedDatasetNames(rflomics.MAE)
analysisTypes <- names(analyzedDatasetNames)
data.coExp <- unique(c(unlist(analyzedDatasetNames[["DiffExpEnrichAnal"]]),
                       unlist(analyzedDatasetNames[["CoExpEnrichAnal"]])))
```


```{r}
# create export data
explorDir <- list()
diffDir   <- list()
coexpDir  <- list()
annotDir  <- list()

for (analysisType in names(analyzedDatasetNames)){
  
  if (!analysisType %in% c("DiffExpEnrichAnal", "CoExpEnrichAnal")) {
    
    for(data in analyzedDatasetNames[[analysisType]]){
      
      if (analysisType == "DataProcessing"){
        explorDir[[data]] <- 
          paste0(outDir,"/", data, "/03_data_processing/")
        
        dir.create(path = explorDir[[data]],
                   recursive = TRUE, showWarnings = FALSE)
      }
      
      if (analysisType == "DiffExpAnal"){
        diffDir[[data]] <-
          paste0(outDir, "/", data,"/04_differential_analysis/")
        
        dir.create(path = diffDir[[data]],
                   recursive = TRUE, showWarnings = FALSE)
      }
      
      if (analysisType == "CoExpAnal"){
        coexpDir[[data]] <-
          paste0(outDir, "/", data, "/05_coExpression_analysis/")
        
        dir.create(path = coexpDir[[data]],
                   recursive = TRUE, showWarnings = FALSE)
      }
    }
  }else{
    
    for (database in names(analyzedDatasetNames[[analysisType]])) {
      
      for (data in analyzedDatasetNames[[analysisType]][[database]]) {
        
        annotDir[[data]][[analysisType]][[database]] <-
          paste0(outDir, "/", data, "/06_enrichment_analysis/",
                 analysisType, "/", database, "/")
        
        dir.create(path = annotDir[[data]][[analysisType]][[database]],
                   recursive = TRUE, showWarnings = FALSE)
      }
    }
  }
}


```


<br>
<br>

---

<!-- Data pre-processing -->
# 3 - Data pre-processing

Pre-processing step aims at filtering out features or outlier samples. It allows to normalize and/or transform raw data if necessary. The available methods are adapted to the type of omics.

Quality control plots are generated before and after data pre-processing to inspect the effect of the applied methods and 
parameters on the data distribution, technical and biological variability.

The implemented pre-processing strategies are adapted from @Lambert2020ta for RNA-seq data and @efstathiou2017a for metabolomics and proteomics data.

`r if(!"DataProcessing" %in% analysisTypes) {"<p style=\"color:orange\">Data pre-processing has not been performed on this data.</p>"}`

```{r, eval=("DataProcessing" %in% analysisTypes)}
out <- NULL
num <- 0
for (data in analyzedDatasetNames[["DataProcessing"]]){
  num <- num + 1
  out <- c(out, knit_child(
    paste0(path.package("RFLOMICS"),"/RFLOMICSapp/",
           "report_03_data_explor.Rmd") , quiet=TRUE))
}

asis_output(out)
```

<br>
<br>

---

<!-- differential expression analysis -->
# 4 - Differential expression analysis

The goal of Differential Expression Analysis is to identify omics features (transcripts, proteins or metabolites) that exhibit significant differences in expression levels across various experimental conditions or groups, allowing researchers to understand the biological mechanisms underlying those differences.

The strategy for differential expression analysis was adapted from @Lambert2020ta for RNA-seq data and from @efstathiou2017a for transcriptomics and proteomics data.

`r if(!"DiffExpAnal" %in% analysisTypes) {"<p style=\"color:orange\">Differential analysis has not been performed on this data or the contrast has not been validated.</p>"}`

```{r, eval=("DiffExpAnal" %in% analysisTypes)}
opts_chunk$set( 
  fig.path=paste0(outDir, "/Analysis_summary/") 
)
```


```{r diffAnalysesSummary, results='asis', eval=("DiffExpAnal" %in% analysisTypes), fig.cap=paste0("")}

cat("## 4.1 Summary\n")
getDiffAnalysesSummary(rflomics.MAE, plot = TRUE, 
                       nbMaxLabel = 0,
                       interface = TRUE) #+
# theme(
#   plot.caption =
#     element_textbox(
#       width = unit(1, "npc"),
#       hjust = 0, vjust = 1,
#       halign = 0, face = "italic", size = 10, colour = "grey50", margin = margin(t = 10)
#     )
# ) +
# labs(
#   title = "",
#   caption = ""
# )
cat("\n<br>\n")
```


```{r, results='asis', eval=("DiffExpAnal" %in% analysisTypes)}
out <- NULL
num <- 1
for (data in analyzedDatasetNames[["DiffExpAnal"]]){
  num <- num + 1
  out <- c(out, knit_child(
    paste0(path.package("RFLOMICS"),"/RFLOMICSapp/",
           "report_04_diff_analysis.Rmd"), quiet = TRUE))  
}

asis_output(out)
```

<br>
<br>

---

<!-- co-expression analysis -->
# 5 - Co-expression analysis

Co-expression analysis enables the identification of omics features (transcripts, proteins or metabolites) sets with correlated expression levels, suggesting similar regulation or interactions in common biological pathways. For this step, we adopted an approach based on gaussian mixture models. This method is implemented in the **coseq** R package [@coseq2018].

The co-expression analysis strategy was adapted from @Lambert2020ta and tailored under the guidance of the coseq developer for metabolomic and proteomic data.

`r if(!"CoExpAnal" %in% analysisTypes) {"<p style=\"color:orange\">Co-expression analysis has not been performed on this data.</p>"}`

```{r}
opts_chunk$set( 
  fig.path=paste0(outDir, "/Analysis_summary/") 
)
```


```{r coExpAnalysesSummary, results='asis', eval=("CoExpAnal" %in% analysisTypes), fig.cap=paste0("")}
cat("## 5.1 Summary\n")
getCoExpAnalysesSummary(rflomics.MAE)
cat("\n")
```


```{r,  eval=("CoExpAnal" %in% analysisTypes)}
out <- NULL

num <- 1
for (data in  analyzedDatasetNames[["CoExpAnal"]]){
  num <- num + 1
  out <- c(out, knit_child(
    paste0(path.package("RFLOMICS"), "/RFLOMICSapp/",
           "report_05_coexp_analysis.Rmd"), quiet=TRUE))  
}

asis_output(out)
```

<br>
<br>

---

<!-- enrichement analysis on DE G/P/M lists with clusterprofiler -->
# 6 - Enrichment analysis

Enrichment analysis, particularly through methods like 
**Overrepresentation Analysis (ORA)** such as those used in **clusterProfiler R-package** [@wu-a2021a], is crucial 
for identifying biological significance in omics data. ORA focuses on feature sets—groups of features that share common biological functions or pathways—allowing researchers to determine if these functions or pathways are 
statistically enriched among a list of features of interest. This approach facilitates the interpretation of complex genomic data.

`r if(!"DiffExpEnrichAnal" %in% analysisTypes) {"<p style=\"color:orange\">Enrichment analysis has not been performed on this data.</p>"}`

```{r}
opts_chunk$set( 
  fig.path=paste0(outDir, "/Analysis_summary/") 
)
```

```{r annotAnalysesSummary, results='asis', eval=(length(data.coExp) != 0), fig.width = 15, fig.height = 7.5, fig.cap=""}

annot.list <- list()
for (annot in c("DiffExpEnrichAnal", "CoExpEnrichAnal")) {
  for (db in names(analyzedDatasetNames[[annot]])) {
    
    for (data in analyzedDatasetNames[[annot]][[db]]) {
      
      annot.list[[data]][[db]][[annot]] <- TRUE
    }
  }
}

cat("## 6.1 Summary {.tabset .tabset-fade .tabset-pills}\n")

for (annot in c("DiffExp", "CoExp")) {
  
  if (! paste0(annot, "EnrichAnal") %in% analysisTypes)
    next
  
  cat("### From", 
      ifelse(annot == "DiffExp", 
             "differentially expressed lists", "co-expressed clusters"), 
      "{.tabset .tabset-fade .tabset-pills}\n")
  
  cat("\n\n")
  
  annot.p <- getAnnotAnalysesSummary(rflomics.MAE, from = annot)
  
  for (ontology in  names(annot.p)){
    
    ontology.title <- switch(
      ontology,
      "GO" = {"Gene Ontology database"},
      "KEGG" = {"KEGG database"},
      "custom" = {"Custom annotation"}
    )
    
    if("no-domain" %in% names(annot.p[[ontology]])){
      cat('####', ontology.title, '\n')
      print(annot.p[[ontology]][["no-domain"]])
      cat("\n", "<br>", "\n\n") 
      
    }else if(length(names(annot.p[[ontology]])) == 1){
      cat('####', ontology.title, '(', names(annot.p[[ontology]]), ')\n')
      print(annot.p[[ontology]][[names(annot.p[[ontology]])]])
      cat("\n", "<br>", "\n\n") 
      
    }else{
      cat('####', ontology.title, '{.tabset .tabset-fade .tabset-pills}\n')
      
      for (domain in  names(annot.p[[ontology]])){
        cat('#####', domain, '\n') 
        print(annot.p[[ontology]][[domain]])
        cat("\n", "<br>", "\n\n") 
      }
      cat("\n", "<br>", "\n\n")
    }
  }
}
cat("\n", "<br>", "\n\n")

```


```{r , results ='asis', eval=(length(data.coExp) != 0)}

out <- NULL

num <- 1
for (data in  data.coExp){
  num <- num + 1
  out <- c(out, knit_child(
    paste0(path.package("RFLOMICS"),"/RFLOMICSapp/",
           "report_06_enrichmentORA_analysis.Rmd"), quiet=TRUE))
}

asis_output(out)

```
