#Figure 1 Table
setwd('//vfs01/users01/butlerr/Linux/Clinotator/')
library(dplyr)
library(ggplot2)

# import & slice tbls
big_tbl <- read.csv('20180601_2str.clinvar_ge_2str.tsv', header=TRUE, sep='\t', na.strings='.')
US_tbl <- filter(big_tbl, grepl('Uncertain significance', CTPS) & CVNA >= 2 & CVSZ == 2)
LP_tbl <- filter(big_tbl, grepl('^Likely pathogenic', CTPS) & CVNA >= 2 & CVSZ == 2)
PLP_tbl <- filter(big_tbl, grepl('^Pathogenic/', CTPS) & CVNA >= 2 & CVSZ == 2)
BLB_tbl <- filter(big_tbl, grepl('^Benign/', CTPS) & CVNA >= 2 & CVSZ == 2)
LB_tbl <- filter(big_tbl, grepl('^Likely benign', CTPS) & CVNA >= 2 & CVSZ == 2)
P_tbl <- filter(big_tbl, grepl('Pathogenic($|,)', CTPS) & CVNA >= 2 & CVSZ == 2)
B_tbl <- filter(big_tbl, grepl('Benign($|,)', CTPS) & CVNA >= 2 & CVSZ == 2)

# distributions by ctps sorting
B_dist <- sort(B_tbl$CTRS)
BLB_dist <- sort(BLB_tbl$CTRS)
LB_dist <- sort(LB_tbl$CTRS)
US_dist <- sort(US_tbl$CTRS)
LP_dist <- sort(LP_tbl$CTRS)
PLP_dist <- sort(PLP_tbl$CTRS)
P_dist <- sort(P_tbl$CTRS)

# plotting ctps data prep
B_frame <- data.frame('dist'=B_dist)
BLB_frame <- data.frame('dist'=BLB_dist)
LB_frame <- data.frame('dist'=LB_dist)
US_frame <- data.frame('dist'=US_dist)
LP_frame <- data.frame('dist'=LP_dist)
PLP_frame <- data.frame('dist'=PLP_dist)
P_frame <- data.frame('dist'=P_dist)
B_frame$type <- "B"
BLB_frame$type <- "B/LB"
LB_frame$type <- "LB"
US_frame$type <- "US"
LP_frame$type <- "LP"
PLP_frame$type <- "P/LP"
P_frame$type <- "P"
distFrame <- rbind(B_frame, BLB_frame, LB_frame, US_frame, LP_frame, PLP_frame, P_frame)

#ctps histogram plot combo
ctps_breaks = c(1, 100, 400, 900, 1600, 2500, 3600, 13000)
histo_breaks = c(seq(-60.9, -27.3, 2.1), -26.7, seq(-25.2, 0, 2.1), seq(2.09999, 14.69999, 2.1), seq(16.79999, 60.89999, 2.1))

ctps_plot <- ggplot(distFrame, aes(x=dist, fill=type)) +
  geom_histogram(breaks = histo_breaks, alpha=0.3, position="identity") +
  scale_x_continuous(breaks = seq(-60, 60, 20), minor_breaks=NULL, limits = c(-60, 60)) +
  theme_bw() + scale_y_sqrt(minor_breaks=NULL, breaks=ctps_breaks)
ctps_plot

# get plot data
ctps_dat <- ggplot_build(ctps_plot)
cs_dat <- ctps_dat$data[[1]]

#density plot combo
# plot <- ggplot(distFrame, aes(x=dist, color=type)) + geom_density() +
#   scale_x_continuous(breaks = seq(-60, 60, 20), minor_breaks=NULL, limits = c(-60, 60)) +
#   theme_bw() + scale_y_sqrt(minor_breaks=NULL, breaks=ctps_breaks)
# plot
