---
title: "Untitled"
output: html_document
---

```{r}
knitr::opts_chunk$set(cache=FALSE)
source('functions.R')
library(org.Hs.eg.db)
library(DESeq2)
library(pheatmap)
library(dplyr)
library(yaml)
```

```{r , echo=TRUE,warning=FALSE,message=FALSE,error=FALSE, include=FALSE}
params <- read_yaml("../pipeline.yml")
df_mRNA <- read.table(gzfile("../merged_idxstats.txt.gz"), sep = "\t", header = TRUE, row.names = 1)

colnames(df_mRNA) <- gsub("_trna", "", x = colnames(df_mRNA), fixed = T)
meta_data <- read.table("../meta_data.csv", sep=",", header = TRUE)

rownames(meta_data) <- meta_data$Sample
df_mRNA = df_mRNA[,rownames(meta_data)]

all(rownames(meta_data) %in% colnames(df_mRNA))
```

```{r , include=FALSE}

dds <- run_deseq2_full(df_mRNA, meta_data)

```

# Heatmap of counts matrix

To explore a count matrix, it is often instructive to look at it as a heatmap. Below we show how to produce such a heatmap for various transformations of the data. I have plotted a heatmap of the top 200 highly expressed genes to determine if the samples cluster together by condition.

```{r , echo=FALSE}
library(pheatmap)

vsd <- varianceStabilizingTransformation(dds, blind=FALSE)
select <- order(rowMeans(counts(dds, normalized=TRUE)), decreasing=TRUE)[1:200]
df <- as.data.frame(colData(dds)[,"Condition"])
annotation <- data.frame(Var1 = meta_data$Condition)
rownames(annotation) <- colnames(assay(vsd))

pheatmap(assay(vsd)[select,], cluster_rows = FALSE, show_rownames = FALSE, cluster_cols = TRUE, annotation =annotation, show_colnames=FALSE)
```

# Heatmap of sample-to-sample distances

Another use of the transformed data is sample clustering. Here, we apply the dist function to the transpose of the transformed count matrix to get sample-to-sample distances.

A heatmap of this distance matrix gives us an overview over similarities and dissimilarities between samples. We have to provide a hierarchical clustering hc to the heatmap function based on the sample distances, or else the heatmap function would calculate a clustering based on the distances between the rows/columns of the distance matrix.

```{r , echo=FALSE}
library(RColorBrewer)
sampleDists <- dist(t(assay(vsd)))
samplDistMatrix <- as.matrix(sampleDists)
rownames(samplDistMatrix) <- meta_data$Condition
colnames(samplDistMatrix) <- meta_data$Lab_sample
colors <- colorRampPalette(rev(brewer.pal(9, "Blues")) )(255)

pheatmap(samplDistMatrix, 
         clustering_distance_cols = sampleDists, 
         clustering_distance_rows = sampleDists,
         color = colors)

```

# PCA analysis of the samples {.tabset .tabset-fade}

Related to the distance matrix is the PCA plot, which shows the samples in the 2D plane spanned by their first two principal components. This type of plot is useful for visualizing the overall effect of experimental covariates and batch effects.

## PCA - group

```{r , echo=FALSE}
plotPCA(vsd, intgroup=params$Wald$value)
```
