setwd('//vfs01/users01/butlerr/Linux/Clinotator/')
library(dplyr)
library(ggplot2)
library(RColorBrewer)
library(reshape)

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

# rename CVCS
US_tbl$CVCS <- "US"
LP_tbl$CVCS <- "LP"
PLP_tbl$CVCS <- "PLP"
BLB_tbl$CVCS <- "BLB"
LB_tbl$CVCS <- "LB"
P_tbl$CVCS <- "P"
B_tbl$CVCS <- "B"

# rbind and rename CTPS
heatmap_tbl <- rbind(B_tbl, BLB_tbl, LB_tbl, US_tbl, LP_tbl, PLP_tbl, P_tbl)

heatmap_tbl$CTPS[grepl('Uncertain significance', heatmap_tbl$CTPS)] <- "US"
heatmap_tbl$CTPS[grepl('^Likely pathogenic', heatmap_tbl$CTPS)] <- "LP"
heatmap_tbl$CTPS[grepl('^Pathogenic/', heatmap_tbl$CTPS)] <- "PLP"
heatmap_tbl$CTPS[grepl('^Benign/', heatmap_tbl$CTPS)] <- "BLB"
heatmap_tbl$CTPS[grepl('^Likely benign', heatmap_tbl$CTPS)] <- "LB"
heatmap_tbl$CTPS[grepl('Pathogenic($|,)', heatmap_tbl$CTPS)] <- "P"
heatmap_tbl$CTPS[grepl('Benign($|,)', heatmap_tbl$CTPS)] <- "B"

# building a matrix
heatmatrix <- with(heatmap_tbl, table(CVCS, CTPS))
pattern <- c('B', 'BLB', 'LB', 'US', 'LP', 'PLP', 'P')
heatframe <- melt(heatmatrix)
heatmatrix <- heatmatrix[match(pattern, heatframe$CVCS),pattern]
reclass_map <- heatmap(heatmatrix, Rowv=NA, Colv=NA, col = brewer.pal(9,"Greys"), scale='column', margins=c(5,5))

# ggplot
ggplot(heatframe, aes(CTPS, CVCS)) +
  geom_tile(aes(fill = value)) + geom_text(aes(label = value)) + coord_equal() +
  scale_fill_gradientn(colors=c('grey98', 'grey50'), values=c(0, 0.574, 1)) +
  scale_x_discrete(limits=pattern) + scale_y_discrete(limits=rev(pattern))
