```{r "corr_stats_config", include = FALSE}
# ###########################################
# ################# READ ME #################
# ###########################################
#
# This template assumes that the following variables exists
# => clgenes :: a named list of vectors with cluster name as IDs and genes of each clusters as vectors
# => cl :: cluster ID to be used
# => norm_counts :: a data frame with columns Gene (character), Sample (character) and Count (numeric) 
# => norm_counts_gnorm :: a data frame with columns Gene (character), Sample (character) and Count (numeric) 
# => cl_eigvalues_gnorm ::
# => wgcna_pval_cl_trait ::
# => wgcna_corr_cl_trait ::
# => wgcna_count_sample_trait ::
#
# This templates include the following chunk names:
# => <cl>_corr_stats_config
# => <cl>_explote_genes
 
# Load necessary packages
# require(ggplot2)
n_category <- 30
pval_thr_forFeatures <- 0.05

```
## **Profiles data**


```{r "explore_genes", echo = FALSE, message = FALSE, warning = FALSE, results = 'asis'}
# Load genes expressions
#cl_i_genes <- unique(rownames(DEGH_results)[which(DEGH_results$Cluster_ID == {{cl}})])
cl_i_genes <- unique(rownames(DEGH_results))
# cl_i_genes <- clgenes[[as.character({{cl}})]]
tgt_indx <- which(scaled_counts_table$Gene %in% cl_i_genes)
# Prepare regular cluster info
cl_profile <- cl_eigvalues_gnorm[cl_eigvalues_gnorm$Cluster_ID == paste0("ME", cl),]
# message(cl_profile)
# cl_profile <- cl_eigvalues_gnorm[grepl(paste(c("ME",{{cl}},"$"),collapse=""), cl_eigvalues_gnorm$Cluster_ID),]
# message(cl_profile)
# q()
# Plot
pp <- ggplot2::ggplot(mapping = ggplot2::aes(x = Sample)) + 
	  ggplot2::geom_line(data = scaled_counts_table[tgt_indx,], alpha = 0.05, mapping = ggplot2::aes(y = Count, group = Gene)) +
	  ggplot2::labs(y = "Scaled gene expression value") +
	  ggplot2::geom_line(data = cl_profile, mapping = ggplot2::aes(y = Count, group = Cluster_ID), color = "blue", linetype = "dashed", size = 0.5) +
	  ggplot2::scale_y_continuous(sec.axis = ggplot2::sec_axis(~.*2-1, name = "Eigengene Value (broken blue line)")) +
      ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 30, hjust = 1))
plot(pp)

# Tidy to expanded
tidy_cl_exp <- scaled_counts_table[tgt_indx, ]
max_cl_exp <- matrix(, length(unique(tidy_cl_exp$Gene)), length(unique(tidy_cl_exp$Sample)))
colnames(max_cl_exp) <- unique(tidy_cl_exp$Sample)
row.names(max_cl_exp) <- unique(tidy_cl_exp$Gene)
max_cl_exp[as.matrix(tidy_cl_exp[, 1:2])] <- tidy_cl_exp[, "Count"]

invisible(plot_in_div(gplots::heatmap.2(max_cl_exp, Colv=FALSE, col="bluered", 
	  key.title="Expression", keysize=1.2, density.info="none", dendrogram ="row", trace="none")))
```

```{r "wgcna_corr", echo = FALSE, results = 'asis'}
# Take pval of Cluster-Treats
clpvals <- wgcna_pval_cl_trait[paste0("Cluster_", cl),]
clcorrs <- wgcna_corr_cl_trait[paste0("Cluster_", cl),]
# Filter
clpvals <- clpvals[clpvals <= pval_thr_forFeatures]
```
```{r "wgcna_corr_pl1", echo = FALSE, results = 'asis', eval = length(clpvals) > 0}
cat(paste0("After apply a threshold of ",pval_thr_forFeatures," over cluster correlation with Traits following relationships have been signifcant observed:"))
clcorrs <- clcorrs[names(clpvals)]
# Transform
clpvals <- as.data.frame(as.table(clpvals))
colnames(clpvals) <- c("Trait","Cl_Trait_Pval")
clcorrs <- as.data.frame(as.table(clcorrs))
colnames(clcorrs) <- c("Trait","Cl_Trait_Corr")
# Merge
cltraits <- merge(x = clcorrs, y = clpvals, by = "Trait", all = TRUE)
# Plot Cluster correlations
pp <- ggplot2::ggplot(cltraits,ggplot2::aes(x = Trait, y = Cl_Trait_Corr, color = Cl_Trait_Pval)) + 
	  ggplot2::geom_point() +
	  ggplot2::geom_hline(yintercept = 0) + 
 	  ggplot2::labs(y = "Correlation between eigengene and external variable", color="Correlation\np-value") +
	  ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 30, hjust = 1)) + 
	  ggplot2::ylim(c(-1,1))
plot(pp)
```
```{r "wgcna_corr_pl2", echo = FALSE, results = 'asis', eval = length(clpvals) > 0}
# cat("\nTEXTHERE:\n")
# Prepare Sample-Trait correlations
smtraits <- as.matrix(wgcna_count_sample_trait[,as.character(cltraits$Trait)])
rownames(smtraits) <- rownames(wgcna_count_sample_trait)
colnames(smtraits) <- cltraits$Trait
smtraits <- as.data.frame(as.table(smtraits))
colnames(smtraits) <- c("Sample","Trait","Correlation")
colnames(cl_profile) <- colnames(smtraits)
cl_profile$Trait <- rep(paste0("Cluster_",cl),nrow(cl_profile))
# smtraits <- rbind(smtraits,cl_profile)

pp2 <- ggplot2::ggplot(smtraits, ggplot2::aes(x = Sample, y = Correlation, group = Trait, color = Trait)) +
	  ggplot2::geom_point(na.rm = TRUE) +
	  ggplot2::geom_line(na.rm = TRUE) +
	  ggplot2::geom_line(data = cl_profile, linetype = "dashed", size = 0.5, color = "blue") +
	  ggplot2::labs(y="Scaled external variable value", color="External Variable") +
	  ggplot2::scale_y_continuous(sec.axis = ggplot2::sec_axis(~.*2-1, name = "Eigengene value (broken blue line)")) +
      ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 30, hjust = 1))
plot(pp2)
```
```{r "wgcna_corr_plERR", echo = FALSE, results = 'asis', eval = length(clpvals) <= 0}
cat(paste0("After apply a threshold of ",pval_thr_forFeatures," over cluster correlation with Traits **any correlation have been tagged as significant**"))
```






