<br>

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

```{r }

opts_chunk$set(
  fig.path=explorDir[[data]]
)
```

```{r}
dataset.SE     <- getRflomicsSE(rflomics.MAE, data)
DataProcessing <- getAnalysis(dataset.SE, name = "DataProcessing")
variableName   <- RFLOMICS:::.omicsDic(dataset.SE)[["variableName"]]

```

* **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]],"Processed_Data_",
                          data, ".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 = "50%", fig.cap=paste0("*fig: Boxplots of distributions of count or abundance per samples before (left) and after (right) data processing*")}

plotDataDistribution(dataset.SE, plot = "boxplot", raw = TRUE)
plotDataDistribution(dataset.SE, plot = "boxplot", raw = FALSE)

```

#### Distribution (density)

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

plotDataDistribution(dataset.SE, plot = "density", raw = TRUE)
plotDataDistribution(dataset.SE, plot = "density", raw = FALSE)
```

<!-- 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 = "50%", eval=(getOmicsTypes(dataset.SE) == "RNAseq"), fig.cap=paste0("*fig: Barplot of the library size for each sample before and after the normalization step*")}

plotLibrarySize(dataset.SE, raw = TRUE)
plotLibrarySize(dataset.SE, raw = FALSE)

```

```{r export,echo = FALSE}

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

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

```

`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 factor.
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("*fig: Factorial maps formed by the axis 1 and 2: before (left) and after (right) data processing*")}

plotOmicsPCA(dataset.SE, raw=TRUE, axes=c(1, 2), groupColor="groups")
plotOmicsPCA(dataset.SE, raw=FALSE, axes=c(1, 2), groupColor="groups")

```

```{r PCA_1_3, echo=FALSE , fig.show="hold", out.width = "50%", fig.cap=paste0("*fig: Factorial maps formed by the axis 1 and 3: before (left) and after (right) data processing*")}

plotOmicsPCA(dataset.SE, raw=TRUE, axes=c(1, 3), groupColor="groups")
plotOmicsPCA(dataset.SE, raw=FALSE, axes=c(1, 3), groupColor="groups")
```

### {-}