---
title: "Read Summary and Figures"
output: html_document
date: "`r Sys.Date()`"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, fig.align = 'center')
library(tidyverse)
library(ggExtra)
library(bit64)
source('rdeval_interface.R')
```

```{r results = 'asis'}
# Set color palette (jco from ggsci package)
palette <- c("#0073C2", "#EFC000","#868686", "#CD534C", "#7AA6DC", 
             "#003C67", "#8F7700", "#3B3B3B", "#A73030", "#4A6990")

# Inverse Cumulative Distribution Function
icdf <- function(read_lengths) {
  sum <- sum(read_lengths)
  read_lengths <- sort(read_lengths)
  n <- length(read_lengths)
  vals <- unique(read_lengths)
  inv_cs <- sum - cumsum(as.numeric(tabulate(match(read_lengths, vals)) * vals))
  inv_cs_gb <- inv_cs/10^9
  return(tibble(read_length = vals, inv_cs = inv_cs, inv_cs_gb = inv_cs_gb))
}

reads <- tibble(read_length = numeric(), read_quality = numeric(), run = character())
inv_cs <- tibble(read_length = numeric(), inv_cs = numeric(), run = character())

# files <- list.files(pattern = '.rd')
files <- commandArgs(trailingOnly = TRUE)
n_runs <- length(files)
for (file in files) {
  rdFile <- generateRdFile(file)
  df <- tibble(read_length = rdFile$lengths, 
                   read_quality = rdFile$qualities)
  run <- strsplit(basename(file), '[.]')[[1]][1]
  df$run <- run
  df_icdf <- icdf(df$read_length)
  df_icdf$run <- run
  reads <- rbind(reads, df)
  inv_cs <- rbind(inv_cs, df_icdf)
  cat(printRdSummary(rdFile))
}

```

### Violin Plot
```{r}

violin <- ggplot(reads, aes(x = run, y = read_length, fill = run)) +
  geom_violin() +
  scale_x_discrete(name = ("Run")) +
  scale_y_continuous(name = ("Read Length"),
                     labels = scales::label_comma()) +
  scale_fill_manual(guide = "none", values = palette) +
  theme_bw()
violin
```

### Read lengths

```{r}
read_lengths <- ggplot(reads, aes(x = read_length/1000, fill = run)) +
  geom_density(aes(y = after_stat(count)), alpha = 0.5) +
  scale_x_continuous(name = ("Read length (kbp)"),
                     breaks = scales::breaks_width(10),
                     labels = scales::label_comma(),
                     expand = expansion(mult = c(0, 0))) +
  scale_y_continuous(name = "Count", labels = scales::label_comma(),
                     expand = expansion(mult = c(0, 0.05))) +
  scale_fill_manual(guide = "none", values = palette) +
  theme_bw() 
read_lengths
```

### Read lengths (log transformed)
```{r}
read_lengths_log <- ggplot(reads, aes(x = read_length, fill = run)) +
  geom_density(aes(y = after_stat(count)), alpha = 0.5) +
  scale_x_log10(name = ("Read length (bp)"),
                breaks = scales::breaks_log(n = 5),
                labels = scales::label_comma()) +
  scale_y_continuous(name = "Count", 
                     labels = scales::label_comma(),
                     expand = expansion(mult = c(0, 0.05))) +
  scale_fill_manual(guide = "none", values = palette) +
  theme_bw() 
read_lengths_log
```

### Inverse cumulative distribution plot
```{r}
icd <- ggplot(inv_cs, aes(read_length/1000, inv_cs_gb, color = run)) +
  geom_point() +
  scale_x_continuous(name = "Read length (kbp)",
                     breaks = scales::breaks_width(10),
                     labels = scales::label_comma(),
                     expand = expansion(mult = c(0.05, 0.05))) +
  scale_y_continuous(name = "Cumulative yield (Gbp)",
                     expand = expansion(mult = c(0.05, 0.05))) +
  scale_color_manual(name = "Run", values = palette) +
  theme_bw() 
icd
```

### Read lengths vs average quality
```{r}
reads_by_avg_quality <- reads %>%
  group_by(run, read_length) %>%
  summarize_at("read_quality", mean)

g <- reads_by_avg_quality %>%
  ggplot(aes(x = read_length/1000, y = read_quality, fill = run, color = run)) +
  geom_point(position = position_jitter(h = 0.3), 
             size = 0.75, 
             alpha = 0.2) +
  scale_x_continuous(name = ("Read length (kbp)"),
                     breaks = scales::breaks_width(10),
                     labels = scales::label_comma()) +
  scale_y_continuous(name = ("Average Read Quality")) +
  scale_color_manual(name = "Run", values = palette) +
  scale_fill_discrete(guide = "none") +
  theme_bw() 
g1 <- ggMarginal(g + theme(legend.position = "left"), type = "histogram", groupColour = TRUE, groupFill = TRUE)
g1
```
