require(RCurl)
require("bitops")
require("methods")
require("rjson")

# Replaces 'source' to work with https connections
eval(expr = parse(text = getURL("https://molgenis56.target.rug.nl/molgenis.R")))

#Function for getting scientific numbers
getScientificNUmberExpressionPrefix <- function(x, prefix, digits = 2){
  if(is.infinite(x)){
    stop("Error inf")
  }
  b <- x
  e <- 0
  if(b >= 10){
    while(b >= 10){
      b <- b /10
      e <- e + 1
    }
  } else if(b < 1 & b != 0) {
    while(b < 1){
      b <- b * 10
      e <- e - 1
    }
  }
  b <- round(b, digits)
  return(bquote(paste(.(prefix), .(b) %*% 10 ^{.(e)},)))
}

# Set the RSID e.g. rs12460890
rsId <- "${entityId}"

# Get the SampleAse and ASE table from the molgenis api
samplesAses <- molgenis.get("SampleAse", q = paste("SNP_ID==", rsId, sep=""), num = 10000)
ases <- molgenis.get("ASE", q = paste("SNP_ID==", rsId, sep=""), num = 10000)

# Get the number of ref and alt allele counts for this observed ase
aseRefCounts <- samplesAses$Ref_Counts
aseAltCounts <- samplesAses$Alt_Counts

# Get the maximum number of observed counts
aseMaxCounts <- max(aseRefCounts, aseAltCounts)

# Get parameters from the ASE table
ref <- as.character(ases$Reference_allele)
alt <- as.character(ases$Alternative_allele)
effect <- as.numeric(ases$Fraction_alternative_allele)
genes <- as.vector(ases$Genes)
pValue <- ases$P_Value

# Set the plot title
if(is.na(genes)){
  title <- rsId
} else {
  title <- paste(rsId,"-",genes)
}

# Check if the T allel is changed to a TRUE
if(ref == TRUE){
  ref <- "T"
}

if(alt == TRUE){
  alt <- "T"
}

# Set size of text
bigTextCex <- 1.1
smallTextCex <- 0.9

# Get the number of reads and determine the percentage of alternative allele counts
reads <- aseRefCounts+aseAltCounts
percentageAlt <- (aseAltCounts*100)/reads

# Set the limits for the axis
ylim = c(0, 100)
xlim = c(0, max(reads))

# Take log of your maximum count to set variable for your plot scale
ymgp <- (floor(log10(aseMaxCounts)) * 0.6) + 1.5

# Set plot color
pt.col = "dodgerblue2"

# Set main
main = NULL

# Start plotting
png("${outputFile}", width = 800, height = 400)
layout(matrix(c(1,2), nrow = 1, byrow = TRUE), respect = TRUE,heights = c(1), widths = c(1,1))

### Plot #1 ###
par(mar = c(4, 7, 3, 0), xpd = NA)

plot(aseRefCounts, aseAltCounts, xlim = c(0, aseMaxCounts), ylim = c(0, aseMaxCounts), xlab = "", ylab = paste("Alternative allele count (", alt, ")", sep = ""), asp =1, col = pt.col, mgp = c(ymgp,0.5,0), xpd = NA, xaxt='n', yaxt='n', frame.plot = FALSE, col.lab = "black", cex.lab = bigTextCex, main = main, cex.main = bigTextCex)
title(xlab = paste("Reference allele count (", ref, ")", sep = ""), cex.lab = bigTextCex, mgp = c(2.3,0.5,0))
axis(1, at = axTicks(1), labels = format(axTicks(1), big.mark = ",", scientific= FALSE, trim = T), col = "grey50", col.axis = "grey50", cex.axis = smallTextCex, lwd = 1, mgp = c(2,0.8,0))
axis(2, at = axTicks(2), labels = format(axTicks(2), big.mark = ",", scientific= FALSE, trim = T), col = "grey50", col.axis = "grey50", cex.axis = smallTextCex, lwd = 1, mgp = c(2,0.8,0), las = 2)
lines(c(0,aseMaxCounts), c(0, aseMaxCounts), lwd = 2, lty = "13")

# Calculate the regression line
effectEstimatedRatio <- ((effect)/(1-effect))
if(effectEstimatedRatio < 1){
  lines(c(0,aseMaxCounts), c(0, aseMaxCounts * effectEstimatedRatio), lwd = 2, col = "dodgerblue")
} else {
  lines(c(0,aseMaxCounts / effectEstimatedRatio), c(0, aseMaxCounts), lwd = 2, col = "dodgerblue")
}

text(x = grconvertX(0.5, "ndc"), y = grconvertY(0.97, "ndc"), title, font = 2, cex = 1.3)

if(pValue == 0){
  pValue <- getScientificNUmberExpressionPrefix(2e-311, "p-value <= ")
} else {
  pValue <- getScientificNUmberExpressionPrefix(pValue, "p-value: ")
}

text(x = grconvertX(0.5, "ndc"), y = grconvertY(0.93, "ndc"), pValue, font = 2, cex = 0.9, col = "grey50")
if(nrow(samplesAses) >= 10000){
  text(x = grconvertX(0.5, "ndc"), y = grconvertY(0.89, "ndc"), "warning: number of points is limited to 10000", font = 2, cex = 0.9, col = "red")
}
### Plot #2 ###
par(mar = c(4, 4, 3, 1))

ylab = paste("Percentage alternative (", alt, ")", sep = "")
plot(reads, percentageAlt, col = pt.col, xlim = xlim, ylim = ylim, ylab = ylab, xlab = "Total number of reads", cex = 1, main = main, mgp = c(2.3,0.5,0), xpd = NA, xaxt='n', yaxt='n', frame.plot = FALSE, col.lab = "black", cex.lab = bigTextCex, cex.axis = 1, cex.main = bigTextCex)
axis(1, at = axTicks(1), labels = format(axTicks(1), big.mark = ",", scientific= FALSE, trim = T), col = "grey50", col.axis = "grey50", cex.axis = smallTextCex, lwd = 1, mgp = c(2,0.8,0))
axis(2, col = "grey50", col.axis = "grey50", cex.axis = smallTextCex, lwd = 1, mgp = c(2,0.8,0), las = 2)

# Draw additional lines
fittedPercentageAlt <- (effect)*100
lines(x = c(0,xlim[2]), y = c(50,50), lwd = 2, lty = "13")
lines(x = c(0,xlim[2]), y = c(fittedPercentageAlt,fittedPercentageAlt), lwd = 2, col = "dodgerblue")  
