
# Coverage in regions

```{r total-coverage-load}
get_quantile_cov = function(path){
    cov_tab = data.frame()
    cov_regions = data.frame()
    for (fn in list.files(path, pattern = "_coverage_summary.bed", full.names = TRUE)){
            d = read.table(fn, header=T, sep="\t", comment.char = "%")
            
            d$region_pct = 100-d$region_pct
            cov_tab = rbind(cov_tab, d)
            
    }
    ma = matrix()
    for (fn in list.files(path, pattern = "_coverage.bed", full.names = TRUE)){
            d = read.table(fn, header=T)
            if (nrow(ma)>1){
              ma = ma + (d[,c("percentage10", "percentage20", "percentage50")] > 60 * 1)
            }else{
              ma = as.matrix(d[,c("percentage10", "percentage20", "percentage50")] > 60) * 1 
            }
            
    }
    cov_regions = cbind(d[,1:5], ma)
    list("sample" = cov_tab, "region" = as.data.frame(cov_regions))
}

get_total_cov = function(path){
    cov_tab = data.frame()
    for (fn in list.files(path, pattern = "_total_summary.bed", full.names = TRUE)){
            d = read.table(fn, header=T, sep="\t")
            d[,1] = as.numeric(as.character(gsub("percentage", "", d$cutoff_reads)))
            d = d[order(d[,1]),]
            pct = d[,2]
            t = data.frame(depth=d[,1], bases=pct, sample=d$sample[1])
            cov_tab = rbind(cov_tab, t)
    }
    cov_tab
}

make_total_cov_plots = function(cov_tab){
    p =ggplot(cov_tab, aes(y=bases, x=depth, group=sample)) +
        geom_line(size=2, alpha=.5)+
        theme_bw()+
        labs(list(y="% of bed file > depth", x="# of reads"))
    print(p)
}

make_quantile_plots = function(cov_tab){
    p1 = ggplot(cov_tab %>% filter(cutoff_reads=='percentage10'), aes(x=region_pct, y=bases_pct,  group=sample)) +
    geom_line(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="% of target regions with\nmore than X bases covered", y="% of nt covered\ninside the target", title="considered covered when nt has >10 reads"))

    p2 = ggplot(cov_tab %>% filter(cutoff_reads=='percentage20'), aes(x=region_pct, y=bases_pct,   group=sample)) +
    geom_line(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="% of target regions with\nmore than X bases covered", y="% of nt covered\ninside the target", title="considered covered when nt has >20 reads"))

    p3 = ggplot(cov_tab %>% filter(cutoff_reads=='percentage50'), aes(x=region_pct, y=bases_pct,  group=sample)) +
    geom_line(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="% of target regions with\nmore than X bases covered", y="% of nt covered\ninside the target", title="considered covered when nt has >50 reads"))

    grid.arrange(p1, p2, p3, ncol=1)
}

make_quantile_region_plots = function(dd, n_samples){
    # cov_tab = melt(cov_tab, id.vars="region")
    
    p1 = ggplot(dd %>% group_by(percentage10) %>% summarise(n_regions = n())  %>% filter(percentage10<n_samples*0.8), aes(x=n_regions, y=percentage10)) +
    geom_point(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="number of regions", y="num of samples with region covered", title="considered covered when nt has >10 reads. Only looking at regions with < 80% of samples"))

    p2 = ggplot(dd %>% group_by(percentage20) %>% summarise(n_regions = n())  %>% filter(percentage20<n_samples*0.8), aes(x=n_regions, y=percentage20)) +
    geom_point(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="number of regions", y="num of samples with region covered", title="considered covered when nt has >10 reads. Only looking at regions with < 80% of samples"))

    p3 = ggplot(dd %>% group_by(percentage50) %>% summarise(n_regions = n())  %>% filter(percentage50<n_samples*0.8), aes(x=n_regions, y=percentage50)) +
    geom_point(size=2, alpha=.5)+
    theme_bw()+
    labs(list(x="number of regions", y="num of samples with region covered", title="considered covered when nt has >10 reads. Only looking at regions with < 80% of samples"))

    grid.arrange(p1, p2, p3, ncol=1)
}


```

### coverage distribution (total) by sample


```{r cov-total-fig, fig.height=6, fig.width=11, cache=TRUE}
n_samples = nrow(qc)
cov_tab_total = get_total_cov(file.path(path_results, "coverage"))
make_total_cov_plots(cov_tab_total)
```

## coverage distribution (completeness) by sample

```{r completeness-fig, fig.height=12, fig.width=12, cache=TRUE}
cov_tab = get_quantile_cov(file.path(path_results, "coverage"))
make_quantile_plots(cov_tab$sample)
```

Samples where more than 90% of targets have less than 60% covered at completeness cut-off of 10.

```{r table-completeness, results='asis'}
kable(cov_tab$sample %>% filter(region_pct >= 90) %>%
          spread(cutoff_reads, bases_pct) %>%
          dplyr::select(region_pct, sample, percentage10, percentage20, percentage40) %>%
          dplyr::filter(percentage10<=60),
      align="c", digits=2)

```

## coverage distribution (completeness) by region

```{r completeness-region-fig, fig.height=12, fig.width=12, cache=TRUE}
make_quantile_region_plots(cov_tab$region, n_samples)
```

Regions where less than 60% of samples covered at completeness cut-off of 10.

```{r table-completeness-regions, results='asis'}
n_samples = nrow(qc)
kable(head(cov_tab$region %>% filter(percentage10 < n_samples*0.6),50), 
      align="c", digits=2)
write.table(cov_tab$region, file.path(path_results, "completeness_by_region_and_sample.tsv"))
```


## coverage uniformity


```{r cov-uniformity-load, echo=FALSE, eval=FALSE}
cov_tab = data.frame()

get_bias_cov = function(path){
    for (fn in list.files(path, pattern = "_cov.tsv", full.names = TRUE)){
            d = read.table(fn, header=T, sep="\t")

            cv = d[,"std"]/d[,"mean"]
            bias = (d[,"ntdow"] + d[,"ntup"])/d[,"size"] * 100
            s = as.character(gsub("-ready","",d[1,"sample"]))
            t = data.frame(bias=bias, cv=cv, mean=d[,"mean"], sample=s)
            cov_tab = rbind(cov_tab, t)


    }
    cov_tab
}

make_bias_plot = function(cov_tab){
    p1 = ggplot(cov_tab, aes(x=log2(mean), y=cv)) +
    geom_point(alpha=0.5) +
    scale_color_brewer(palette = "Set1") +
    labs(list(y="coefficient of variation",x="log2(mean coverage)")) +
    theme_bw() +
        ggtitle("coverage variation for each target region")

    p2 = ggplot(cov_tab, aes( x=sample,y=bias)) +
    geom_jitter(alpha=0.5) +
    scale_color_brewer(palette = "Set1") +
    theme_bw() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
    labs(list(y="% of nt with mean-2SD > coverage > mean+2SD ")) +
        ggtitle("% of nucleotides with extreme\ncoverage inside target regions")
    # grid.arrange(p1, p2, ncol=1)
    print(p2)
}
```

```{r cov-uniformity-fig, fig.height=12, fig.width=12, cache=TRUE, eval=FALSE, echo=FALSE}
bias_tab = get_bias_cov(file.path(path_results,"bias"))
make_bias_plot(bias_tab)
```

