---
editor_options: 
  markdown: 
    wrap: 72
---

<br>

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

```{r }

opts_chunk$set(
  fig.path=paste0(coexpDir[[data]],data,"_")
)

dataset.SE   <- getRflomicsSE(rflomics.MAE, data)
variableName <- RFLOMICS:::.omicsDic(dataset.SE)[["variableName"]]
CoExpAnal    <- getAnalysis(dataset.SE, name = "CoExpAnal", subName = "results")
isResults    <- CoExpAnal[["results"]]
```

* **Methods:**

The co-expression analysis was carried out using 
**coseq R package** (version `r RFLOMICS:::.getPackageInfo(rflomics.MAE, "coseq")`) [@coseq2018] on 
**`r length(getDEList(dataset.SE, getCoexpSettings(dataset.SE)$gene.list.names, getCoexpSettings(dataset.SE)$merge))`
`r variableName`** from
the
**`r getCoexpSettings(dataset.SE)$merge`** of the following 
contrast lists:

```{r, class.output='scroll-200'}

gene.list.name <- getCoexpSettings(dataset.SE)$contrastNames

coExptag <- 
  stat_summary[which(stat_summary$contrastName %in% gene.list.name),
               c("tag","contrastName")]

cat(paste(paste0("[",coExptag$tag,"] ", coExptag$contrastName), collapse = "\n"))

```

```{r contruct_MM, results="asis"}

MM <- 
  paste0("The gaussian mixture model (model = **normal**; form = **",
         getCoexpSettings(dataset.SE)$GaussianModel,
         "**) was applied to the pre-processed data which was: ")

MM.vec <-c(
  ifelse(getCoexpSettings(dataset.SE)$scale == TRUE, "scaled", "not scaled"))
  
if(!is.null(getCoexpSettings(dataset.SE)$meanFilterCutoff))
  MM.vec <-c(MM.vec,
    paste0("filtered (meanFilterCutoff = **",
           getCoexpSettings(dataset.SE)$meanFilterCutoff,"**)"))

if(getCoexpSettings(dataset.SE)$normFactors != "none")
  MM.vec <- c(
    MM.vec, 
    paste0("normalized by **", 
           getCoexpSettings(dataset.SE)$normFactors, "** method"))

if(getCoexpSettings(dataset.SE)$transformation != "none")
  MM.vec <- c(
    MM.vec, 
    paste0("transformed by **", 
           getCoexpSettings(dataset.SE)$transformation, "** method"))

MM <- paste0(MM, paste(MM.vec, collapse = ", "), ".")

MM <- sub(",([^,]*)$", " and\\1", MM)

cat("\n", MM, "\n")

```

`r getCoexpSettings(dataset.SE)$replicates.nb` 
technical replicates were performed for each K (number of clusters) in 
`r getCoexpSettings(dataset.SE)$K`.

<br>

### {.tabset}

* **Results:** 

The best number of cluster (K) selected via the Integrated Completed
Likelihood (ICL) criterion was
`r CoExpAnal[["cluster.nb"]]`.

#### Cluster profiles

<p style="color:grey">
*Overview of cluster's expression profiles. Boxplots are colored according to  biological conditions*.
</p>

```{r coseq_Boxplots,  eval=isResults}
plot.coseq.res <- plotCoExpression(dataset.SE)

par(mar = c(4, 4, .5, .1))
plot.coseq.res$boxplots + theme(axis.text.x = element_text(angle = 90, hjust = 1))
```

`r if(length(getCoexpSettings(dataset.SE)$gene.list.names) == 1 || getCoexpSettings(dataset.SE)$merge != "union") {"\\begin{comment}"}`

#### Cluster composition

<p style="color:grey">
*Cluster's composition by contrasts*.
</p>

```{r coseq-ClustComp,  eval=isResults}
par(mar = c(4, 4, .5, .1))
plotCoseqContrasts(dataset.SE)
```

`r if(length(getCoexpSettings(dataset.SE)$gene.list.names) == 1 || getCoexpSettings(dataset.SE)$merge != "union") {"\\end{comment}"}`

#### ICL (QC)

<p style="color:grey">
*Integrated Completed Likelihood (ICL) plotted versus number of clusters. The ICL is the criterion used to select the number of clusters. The number of clusters (K) that minimizes the ICL is the best number of clusters.*
</p>

```{r coseq_ICL,  eval=isResults}

par(mar = c(4, 4, .5, .1))

plot.coseq.res$ICL 
```

#### probapost (QC)

<p style="color:grey">
*Barplots giving a quality control of each cluster. In green: number of* `r variableName` *that are member of a cluster with a high confidance (Max Conditional Probability  > 0.8). In purple:  number of* `r variableName` *that are member of a cluster with a low confidance (Max Conditional Probability < 0.8). A high proportion of green observations may indicate that the clustering is not reliable and can't be exploited.*
</p>

```{r coseq_MaxProb,  eval=isResults}

par(mar = c(4, 4, .5, .1))

plot.coseq.res$probapost_barplots 
```


```{r, eval=isResults}

cosRes <- CoExpAnal$coseqResults@allResults
tab.clusters <- 
  as.data.frame(cosRes[[paste0("K=", CoExpAnal$cluster.nb)]])
colNames <- names(tab.clusters)
tab.clusters[["DEF"]] <- rownames(tab.clusters)
tab.clusters[c("DEF",colNames)]
      
write.table(tab.clusters,
             file=paste0(coexpDir[[data]],data,"_",variableName,"_Table_DExCluster",".txt"),
             sep="\t",quote=FALSE,col.names=TRUE,row.names=FALSE)

```

### {-}
