<br>


## `r paste0("4.",num, " ", data)` 

```{r}

dataset.SE     <- getRflomicsSE(rflomics.MAE, data)
validContrasts <- getValidContrasts(dataset.SE)
omicsType      <- getOmicsTypes(dataset.SE)
variableName   <- RFLOMICS:::.omicsDic(dataset.SE)[["variableName"]]
DiffExpAnal    <- getAnalysis(dataset.SE, name = "DiffExpAnal", subName = "results")
```

<!-- ## Summary table of differential expression analysis -->

* **Methods:**

`r if(omicsType != "RNAseq") {"\\begin{comment}"}`

The **edgeR R-package** (version `r RFLOMICS:::.getPackageInfo(rflomics.MAE, "edgeR")`) [@robinson2010a] was used to perform the analysis. First, the parameters of the generalized linear model were estimate thanks to the <span style="color:DarkOrchid">estimateGLMCommonDisp</span>, <span style="color:DarkOrchid">estimateGLMTrendedDisp</span>, <span style="color:DarkOrchid">estimateGLMTagwiseDisp</span> and <span style="color:DarkOrchid">glmFit</span> functions. Then, likelihood ratio tests (LRT) were performed for each contrast thanks to the <span style="color:DarkOrchid">glmLRT</span> function to obtain statistics.

`r if(omicsType != "RNAseq") {"\\end{comment}"}`

`r if(omicsType == "RNAseq") {"\\begin{comment}"}`

The **limma R-package** (version `r RFLOMICS:::.getPackageInfo(rflomics.MAE, "limma")`) [@limma2015a] was used to performed the analysis.
First, the parameters of the linear model were estimated thanks to <span style="color:DarkOrchid">lmFit</span> function.
In a second time, <span style="color:DarkOrchid">contrasts.fit</span> function was used to compute coefficients for each contrast  and 
statistics were obtained thanks to the <span style="color:DarkOrchid">eBayes</span> function.

`r if(omicsType == "RNAseq") {"\\end{comment}"}`

P-values of differential expressed `r variableName` were adjusted according 
to the **`r getDiffSettings(dataset.SE)$p.adj.method`** procedure with a **cutoff** set to **`r getDiffSettings(dataset.SE)$p.adj.cutoff`**.
**LogFC cut-off** was set to **`r getDiffSettings(dataset.SE)$abs.logFC.cutoff`**.

<br>

###  {.tabset}

* **Summary of the results for all the contrasts:**

#### Intersection

```{r Upset_plot, fig.show = "hold", out.width = "100%", fig.cap=paste0("*fig: This **UpSetR** plot gives the number of common and specific differential expressed ",variableName," per contrasts.*")}

DEF_mat <- as.data.frame(DiffExpAnal[["mergeDEF"]])
DEF_mat <- DEF_mat[c("DEF", validContrasts$contrastName)]

write.table(DEF_mat, file=paste0(diffDir[[data]],"/",data,"_DExContr.txt"), sep="\t",quote=FALSE,col.names=TRUE,row.names=FALSE)

names(DEF_mat) <- 
  c(names(DEF_mat)[1], validContrasts$tag)

if(dim(DEF_mat)[2] > 2){
  upset(DEF_mat, sets = (names(DEF_mat[,-1])), order.by = "freq") 
}

```

#### Stat summary
```{r , echo=FALSE, results="asis", fig.cap=paste0("*tab: Table summarising the number of DE features by contrast.*")}

DE <- vector()
DEup <- vector()
DEdown <- vector()

for (i  in  1:nrow(DiffExpAnal[["Validcontrasts"]])){
  contrastName <- DiffExpAnal[["Validcontrasts"]][i,]$contrastName
  stats <- DiffExpAnal[["stats"]][contrastName,]
  DE[i] <- stats[["All"]]
  DEup[i] <- 
    paste(stats[["Up"]]," (",round(stats[["Up"]]/stats[["All"]],2)*100," %)",sep="")
  DEdown[i] <- 
    paste(stats[["Down"]]," (",round(stats[["Down"]]/stats[["All"]],2)*100," %)",sep="")
}

stat_summary <- cbind(DiffExpAnal[["Validcontrasts"]][,c("tag","contrastName")],
                      data.frame("DE.Tot"=DE,"DE.Up"=DEup,"DE.Down"=DEdown))

write.table(stat_summary, file=paste0(diffDir[[data]],data,"_Summary.txt"),
            sep="\t", quote=FALSE, col.names=T, row.names=F)

noValidContrasts <- 
  setdiff(stat_summary$contrastName, validContrasts$contrastName)

if(length(noValidContrasts) !=0){
  
  datatable(stat_summary, rownames = FALSE , class = 'cell-border stripe',
              options = list( pageLength = 6, scrollX = F, dom = 'tip')) |>
  formatStyle(
      "contrastName", target = 'row', 
      color = styleEqual(noValidContrasts, 'red')
    )
}else{
  datatable(stat_summary, rownames = FALSE , class = 'cell-border stripe',
              options = list( pageLength = 6, scrollX = F, dom = 'tip'))
}


```

`r if(length(noValidContrasts) !=0) {"<p style=\"color:red;\">*Red: No differentially expressed features or contrasts not validated by the user.*</p>"}`

### {-}

<br>

* **Display results by contrast(s):** 

*Please click on the arrows to scroll down the results and click on the figure to zoom*


```{r, results='asis'}

out <- NULL

DiffExpAnal <- getAnalysis(dataset.SE, name = "DiffExpAnal", subName = "results")
logFC.cutoff <- getDiffSettings(dataset.SE)[["abs.logFC.cutoff"]]
p.adj.cutoff <- getDiffSettings(dataset.SE)[["p.adj.cutoff"]]

for (contrast  in  getValidContrasts(dataset.SE)$contrastName) {
#for (contrast  in  getSelectedContrasts(dataset.SE)$contrastName) {
  
  tag <- stat_summary[which(stat_summary$contrastName == contrast),]$tag
  out <- c(out, knit_child(
    paste0(path.package("RFLOMICS"),"/RFLOMICSapp/",
           "report_04_diff_analysis_per_contrast.Rmd"), quiet=TRUE)) 
}

asis_output(out)
```

