<br>


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


```{r}
dataset.SE     <- getRflomicsSE(rflomics.MAE, data)
DataProcessing <- getAnalysis(dataset.SE, name = "DataProcessing")
variableName   <- RFLOMICS:::.omicsDic(dataset.SE)[["variableName"]]
factorType <- getFactorTypes(rflomics.MAE)
factorNames <-names(factorType)[factorType %in% c("batch","Bio")]
```

* **Completness:**

`r if(length(getSelectedSamples(dataset.SE)) - length(colnames(dataset.SE)) == 0) {"\\begin{comment}"}`

The *outlier samples* are removed: `r setdiff(getSelectedSamples(dataset.SE), colnames(dataset.SE))`.

`r if(length(getSelectedSamples(dataset.SE)) - length(colnames(dataset.SE)) == 0) {"\\end{comment}"}`

```{r check-design, out.width = "60%", fig.align='center', fig.cap=paste0("*fig: Number of samples per combination of factor levels. The experimental design must be complete and ideally balanced*")}

plotExpDesignCompleteness(dataset.SE)
```

<br>

* **Methods:**

```{r M_M_03_rna, results='asis', eval=(getOmicsTypes(dataset.SE) == "RNAseq")}

settings <- getFilterSettings(dataset.SE)

filtering <- paste0(
  "By default unexpressed genes were removed (", 
  length(DataProcessing[["rowSumsZero"]])," transcript).",
  " The low counts genes with a ", settings$method, 
  " lower to ", settings$cpmCutoff, " (CMP cutoff)",
  " in at least \"", settings$filterStrategy, "\" (filter strategy)",
  " were filtered out (",length(getFilteredFeatures(dataset.SE)),
  " transcript)."
)

Normalisation <- paste0(
  "The **TMM (Trimmed Mean of M-values)** method from **edgeR** package (version ",
  RFLOMICS:::.getPackageInfo(rflomics.MAE, "edgeR"), ") was applied to normalise the RNAseq libraries.")

cat("\n", filtering, " ", Normalisation, "\n")
```

```{r M_M_03_prot_meta, results='asis',  eval=(getOmicsTypes(dataset.SE) != "RNAseq")}

Transformation <- ""
if(is.null(getTransSettings(dataset.SE)$method)){
   Transformation <- "The data are not transformed."
   
}else if(getTransSettings(dataset.SE)$method == "none"){
  Transformation <- 
    paste0("The data were already transformed before being input into rflomics using **",
           getTransSettings(dataset.SE)$suppInfo, "**.")
}else{
  Transformation <- 
    paste0("The data were transformed using **",
           getTransSettings(dataset.SE)$method, "**.")
}

Normalisation <- ""
if(is.null(getNormSettings(dataset.SE)$method)){
  Normalisation <- "The data are not normalised."
  
}else if(getNormSettings(dataset.SE)$method == "none"){
  Normalisation <- 
    paste0("The data were already normalized before being input into rflomics using **",
           getNormSettings(dataset.SE)$suppInfo, "**.")
}else{
  Normalisation <- 
    paste0("The data were normalized using The **", 
           getNormSettings(dataset.SE)$method, "**.")
}

cat("\n", Transformation, " ", Normalisation, "\n")
```

```{r write Processed_Data}

processed.df <- 
  SummarizedExperiment::assay(getProcessedData(dataset.SE, norm = TRUE)) |>
  as.data.frame()
processed.cn <- colnames(processed.df)
processed.df[[variableName]] <- rownames(processed.df)
processed.df <- processed.df[c(variableName, processed.cn)]

write.table(x = processed.df,
            file = paste0(explorDir[[data]],
                          data, "_processed.txt"),
            sep ="\t",quote=FALSE,col.names=TRUE,row.names=FALSE)
```


<br>

<!-- Distribution of feature counts before/after pre-processing : boxplot -->

### {.tabset}

* **Quality control:**

#### Distribution (boxplot)

```{r boxplot, fig.show = "hold", out.width = "100%", fig.cap=paste0("*Boxplots of distributions of count or abundance per samples  after data processing*")}

p <- plotDataDistribution(dataset.SE, plot = "boxplot", raw = FALSE)

ggsave(
  filename = paste0(explorDir[[data]],data,"_Boxplot.png"),
  plot = p,
  width = 6,
  height = 4
)

print(p)
```

#### Distribution (density)

```{r density-plot, fig.show = "hold", out.width = "100%", fig.cap=paste0("*Density distributions of count or abundance per sample after data processing*")}

p <- plotDataDistribution(dataset.SE, plot = "density", raw = FALSE)

ggsave(
  filename = paste0(explorDir[[data]],data,"_Density.png"),
  plot = p,
  width = 6,
  height = 4
)

print(p)
```

<!-- Histograms of the library size before/after pre-processing -->

`r if(getOmicsTypes(dataset.SE) != "RNAseq") {"\\begin{comment}"}`

#### Library sizes

```{r Library_size_barplot, fig.show = "hold", out.width = "100%", eval=(getOmicsTypes(dataset.SE) == "RNAseq"), fig.cap=paste0("Barplot of the library size for each sample after the normalization step*")}

p <- plotLibrarySize(dataset.SE, raw = FALSE)

ggsave(
  filename = paste0(explorDir[[data]],data,"_LibSize.png"),
  plot = p,
  width = 6,
  height = 4
)

print(p)

```

```{r export,echo = FALSE}

write.table(DataProcessing[["rowSumsZero"]],
            file = paste0(explorDir[[data]],data,"_No_expressed.txt"),
            sep ="\t",quote=FALSE,col.names=FALSE,row.names=FALSE)

write.table(getFilteredFeatures(dataset.SE),
            file = paste0(explorDir[[data]],data,"_Low_expressed.txt"),
            sep="\t",quote=FALSE,col.names=FALSE,row.names=FALSE)

```

`r if(getOmicsTypes(dataset.SE) != "RNAseq") {"\\end{comment}"}`

#### PCA

This figure represents a Principal Component Analysis (PCA) of the biological samples. It shows the percentage of variability explained by each principal axis, which aids in interpreting the relative importance of each biological or batch factors.
Outlier samples can be identified as they significantly influence the observed variability. Biological replicates should group together, forming overlapping ellipses, indicating consistency within groups. If not, this may indicate a batch effect, suggesting non-biological variations between the samples.

```{r PCA_1_2, echo=FALSE , fig.show="hold", out.width = "50%", fig.cap=paste0("*Factorial maps with samples colored by factors*")}

for (var in factorNames) {

  p12 <- plotOmicsPCA(dataset.SE, axes=c(1,2), groupColor=var) 
 
  p13 <- plotOmicsPCA(dataset.SE, axes=c(1,3), groupColor=var) 
 
 
  # sauvegarde explicite
  ggsave(
    filename = paste0(explorDir[[data]],data,"_PCA_1-2_", var, ".png"),
    plot = p12,
    width = 6,
    height = 4
  )
  
  ggsave(
    filename = paste0(explorDir[[data]],data,"_PCA_1-3_", var, ".png"),
    plot = p13,
    width = 6,
    height = 4
  )

  print(p12)
  print(p13)
}

```

### {-}