#' convert a matrix to a color matrix
#' @param mat - a matrix
#' @export
#' @importFrom scales rescale
#'
corToColor <- function(mat) {
  if (max(mat, na.rm = TRUE) > 1 | min(mat, na.rm = TRUE) < -1) {
    stop("input values should be between -1 and 1")
  }
  mat <- rescale(mat, to = c(0, 1), from = c(-1,1))
  tictoc::tic("mean")
  row <- nrow(mat)
  col <- ncol(mat)
  corp<- colorRamp(c("blue", "white", "red"), alpha = TRUE)
  av <- corp(mat)
  res <- array(dim = c(row, col, 4))
  res[,,1] <- matrix(av[,1], row, col)
  res[,,2] <- matrix(av[,2], row, col)
  res[,,3] <- matrix(av[,3], row, col)
  res[,,4] <- matrix(av[,1], row, col)
  tictoc::toc()
  return(res)
}

#' plot correlation between NMR trace (part of) and MS data with segments
#' @param cor - a matrix with correlation values
#' @param sig - a matrix with significance values
#' @param txt - a matrix with text
#' @param labels - the name of the MS values (x rows)
#' @param trace - the NMR trace to plot (values)
#' @param xaxis - the xaxis for the NMR trace
#'
#' @export
#' @importFrom grid grid.xaxis grid.yaxis pushViewport viewport grid.rect
#' @importFrom grid grid.newpage grid.text gEdit upViewport gpar unit popViewport
#' @importFrom grid grid.circle calcStringMetric grid.roundrect grid.convertY
#' @importFrom grDevices rgb colorRamp
plotSHY <- function(cor, sig, txt, labels, trace, xaxis, options = list()) {
  tictoc::tic("init")

  x <- cor
  Ncol <- length(trace)

  if ("alpha" %in% names(options)) {
    alpha <- options$alpha
  } else {
    alpha <- 1
  }

  if ("columns" %in% names(options)) {
    columns <- TRUE
    columnColors <- options$colors
    columnName <- names(options$columns)
    columnCenter <- Ncol - sapply(options$columns, function(x) sum(xaxis < mean(x)))
    columnWidth <- sapply(options$columns, function(x) sum(xaxis >= x[1] & xaxis <= x[2] ))
    columnMin <- min(columnCenter - columnWidth / 2)
    columnMax <- max(columnCenter + columnWidth / 2)
    print(columnMin)
    print(columnMax)
  } else {
    columns <- FALSE
  }

  if ("xlab" %in% names(options)) {
    xlab <- options$xlab
  } else {
    xlab  <- ""
  }

  if ("ylab" %in% names(options)) {
    ylab <- options$ylab
  } else {
    ylab  <- ""
  }

  grid.newpage()
  pushViewport(viewport(width = 0.9,
                        height = 0.9,
                        xscale=c(0, 4),
                        yscale=c(0, 3)))

  # ploting color matrix
  pushViewport(viewport(width = unit(3, "native"),
                        height = unit(2, "native"),
                        x = unit(2.5, "native"),
                        y = unit(1, "native"),
                        xscale=c(0, Ncol),
                        yscale=c(0, nrow(x))))

  maxTextWidth <- grid.convertY(unit(max(calcStringMetric(labels)$width), "inches"), "native", valueOnly = TRUE)

  corp<- colorRamp(c("blue", "white", "red"))

  for (i in c(1:nrow(x))) {
    if (!missing(labels) & !missing(xaxis)) {
      grid.text(x = unit(-maxTextWidth + columnMin - (0.05 * Ncol), "native"),
                y = unit(nrow(x) + 1 - i - 0.5, "native"),
                label = labels[i], gp = gpar(cex = 0.8), just = "right")
    }
    for (j in c(1:length(options$columns))) {
      if (length(dim(x)) > 2) {
        if (is.na(x[i,j,1]) | is.na(x[i,j,2]) | is.na(x[i,j,3])) {
          fill <- "black"
          pushViewport(viewport(x = unit(columnCenter[[j]], "native"),
                                y = unit(nrow(x) + 1 - i - 0.5, "native"),
                                width = unit(columnWidth[[j]], "native"),
                                height = unit(1, "native"),
                                xscale = c(0,1),
                                yscale = c(0,1)))
          grid.rect(gp = gpar(fill = NA, alpha = alpha))
          upViewport()
        } else {
          fill <- rgb(array(data = c(x[i,j,1], x[i,j,2], x[i,j,3]), dim = c(1,4))/256)
          pushViewport(viewport(x = unit(columnCenter[[j]], "native"),
                                y = unit(nrow(x) + 1 - i - 0.5, "native"),
                                width = unit(columnWidth[[j]], "native"),
                                height = unit(1, "native"),
                                xscale = c(0,1),
                                yscale = c(0,1)))
          if (numToSignificance(sig[i, j]) != "NS" & !is.na(sig[i, j])) {
            grid.rect(gp = gpar(fill = NA, alpha = alpha))
            grid.circle(x = 0.5, y = 0.55, r = 0.3, gp = gpar(fill = fill, col = NA))
            grid.text(x = 0.5, y = 0.15, label = round(txt[i,j], digits = 2), gp = gpar(cex = 1, just = "center"))
            grid.text(x = 0.5, y = 0.875, label = numToSignificance(sig[i, j]), gp = gpar(cex = 1, just = "center"))
          } else {
            # grid.rect(gp = gpar(fill = NA, alpha = alpha))
          }
          upViewport()
        }
      } else {
        fill <- rgb(corp(x[i,j])/255)
      }

    }
  }

  # labels
  if (!missing(labels) & !missing(xaxis)) {
    pushViewport(viewport(width = unit(Ncol, "native"),
                          height = 0.1,
                          x = columnMax / Ncol + 0.03,
                          y = 0.5,
                          angle = 90))
    grid.text(label = ylab)
    upViewport()

    pushViewport(viewport(width = unit(Ncol, "native"),
                          height = 0.1,
                          x = 0.96,
                          y = 0.5,
                          angle = 90))
    grid.text(label = "color scale")
    upViewport()

    pushViewport(viewport(width = 1,
                          height = 0.1,
                          x = 0.5,
                          y = -0.035))
    grid.text(label = xlab)
    upViewport()
  }

  upViewport()

  # ploting trace
  pushViewport(viewport(width = unit(3, "native"),
                        height = unit(0.7, "native"),
                        x = unit(2.5, "native"),
                        y= unit(2.6, "native"),
                        xscale=c(0, Ncol),
                        yscale=c(min(trace), max(trace))))

  if (!missing(labels) & !missing(xaxis)) {
    tick <- seq(1, Ncol, length.out = 15)
    grid.xaxis(at=tick - 0.5,
               label = round(xaxis[tick], 2),
               gp = gpar(cex = 0.6),
               edits = gEdit(gPath="labels", rot=90))

    grid.yaxis(at=round(c(min(trace), max(trace)), 2),
               gp = gpar(cex = 0.6))
  }

  # draw points for trace
  for (i in c(1:Ncol)) {
    pushViewport(viewport(x = unit(i - 0.5, "native"),
                          y = unit(trace[i], "native"),
                          height = unit(1, "native"),
                          width = unit(1, "native")))

      grid.circle(gp = gpar(alpha = 0.8))
    upViewport()
  }
  upViewport()

  # draw segment shade
  pushViewport(viewport(width = unit(3, "native"),
                        height = unit(0.7, "native"),
                        x = unit(2.5, "native"),
                        y= unit(2.6, "native"),
                        xscale=c(0, Ncol),
                        yscale=c(0, 1)))

  for (j in c(1:length(options$columns))) {
    pushViewport(viewport(x = unit(columnCenter[[j]], "native"),
                          y = unit(0.5, "native"),
                          height = unit(1, "native"),
                          width = unit(columnWidth[[j]], "native")))
    grid.rect( gp = gpar(alpha = 0.1, col = NA, fill = columnColors[j]))
    grid.lines(c(0, 0), c(0, 1), gp = gpar(alpha = 0.5, col = "black", lwd = 2, lty = 2))
    grid.lines(c(1, 1), c(0, 1), gp = gpar(alpha = 0.5, col = "black", lwd = 2, lty = 2))
    if (columns) {
      grid.text(label = columnName[j], x = 0.5, y = max(trace) * 1.2)
    }
    upViewport()
  }
  upViewport()

  # draw segment titles
  pushViewport(viewport(width = unit(3, "native"),
                        height = unit(1, "native"),
                        x = unit(2.5, "native"),
                        y= unit(2.6, "native"),
                        xscale=c(0, Ncol),
                        yscale=c(0, 1)))

  for (j in c(1:length(options$columns))) {
    pushViewport(viewport(x = unit(columnCenter[[j]], "native"),
                          y = unit(0.525, "native"),
                          height = unit(1, "native"),
                          width = unit(columnWidth[[j]], "native")))
    if (columns) {
      grid.text(label = columnName[j], x = 0.5, y = 0.9)
    }
    upViewport()
  }
  upViewport()

  # ploting color scale
  colorScale <- rev(seq(-1,1, length.out = nrow(x)))
  sc <- corToColor(matrix(colorScale))
  pushViewport(viewport(width = unit(0.05, "native"),
                        height = unit(2, "native"),
                        x = unit(4, "native"),
                        y = unit(1, "native"),
                        xscale=c(0, 1),
                        yscale=c(0, nrow(x))))
  for (i in c(1:nrow(x))) {
    pushViewport(viewport(x = unit(0.5, "native"),
                          y = unit(nrow(x) + 1 - i - 0.5, "native"),
                          width = unit(1, "native"),
                          height = unit(1, "native"),
                          xscale = c(0,1),
                          yscale = c(0,1)))
    grid.rect(gp = gpar(fill =  rgb(array(data = c(sc[i,1,1], sc[i,1,2], sc[i,1,3]), dim = c(1,4))/256)))
    grid.text(label = round(colorScale[i], 1), x = 2.5, y = 0.5, gp = gpar(cex = 0.7))
    upViewport()
  }
  upViewport()

  tictoc::toc()
  upViewport()
}

# plotSHY(cor = corToColor(rescale(matrixList[[1]][,1:3], to = c(-1,1))),
#         sig = matrixList[[1]][,1:3]/100,
#         txt = rescale(matrixList[[1]][,1:3], to = c(-1,1)),
#         labs,
#         trace * 2,
#         xaxis,
#         options = list(alpha = 0.1,
#                        xlab = "xlab",
#                        ylab = "ylab",
#                        colors = c("blue", "red", "green"),
#                        columns = list("seg1" = c(3.13, 3.19),
#                                       "seg2" = c(3.19, 3.21),
#                                       "seg3" = c(3.21, 3.24))))
# #
# # #
# matrixList <- list()
# for (i in 1:9) {
#   x <- (matrix(rnorm(12000, 0, 1), 10, 40))
#   x[2,2] <- NA
#   x[2,3] <- 1
#   x[3,3] <- 1
#   x[3,1] <- -0.1
#   trace <- x[1,]
#   matrixList[[i]] <- x
# }
# #
# labs <- paste("variable", c(1:nrow(x)))
# trace <- x[1,]
# xaxis <- seq(3.3, 3.1, length.out = ncol(x))
# # # plotSHY(meanColor(matrixList), labs, trace, xaxis, options = list(segments = c(3.13, 3.16, 3.2, 3.22)))
# #
#
# # png(filename = paste0("test_", j, ".png"), width = 2000, height = 600)


dat<-Read.summary.data(extend=F,read.init.function=F)
sp<-1
s<-subset(dat,Species.n==sp)
av.F.age<-SMS.control@avg.F.ages[sp-first.VPA+1,]
s1<-subset(s,s$Age>=av.F.age[1] & s$Age<=av.F.age[2])
FI<-tapply(s1$F,list(s1$Year),sum)/(av.F.age[2]-av.F.age[1]+1)
FI<-c(FI,-1)
a<-read.table(file=file.path(data.path,"summary_table_raw.out"),header=TRUE)
a$old.Mean.F<-a$Mean.F
a$mean.F<-FI

write.table(a, file =file.path(data.path,"summary_table_raw.out"), row.names = F)


#' @export
DeterminePloidy <- function(meanThresh, sdThresh, inds){
  ########### Ind x Locus agreement with informative ######################################
  if(missing(inds)){} else {cutMat <- rankMat[1:inds,]}
  if(missing(meanThresh)){indThresh <- .75} else {indThresh <- meanThresh}
  if(missing(sdThresh)){sThresh <- .8} else {sThresh <- sdThresh}

  meanLocusDif <- (alleleCheckMat[,2]+alleleCheckMat[,1])/2
  individuals <- unique(allMat[,2])
  infTestMat <- matrix(nrow=length(individuals)+1, ncol=length(cutMat[,1])+1)
  infTestMat[,1] <- c(0,individuals)
  infTestMat[1,] <- c(0,cutMat[,1])
  ratioMat <- matrix (nrow=length(individuals), ncol = 3)
  totalsMat <- matrix(nrow=length(individuals),ncol=3)
  for (i in 1:length(individuals)){
    tempMeanSum <- 0

    rowRef <- which(grepl(paste(c("^I",individuals[i],"$"), collapse = ""), info$Individual))

    tSum <- 0
    fSum <- 0
    iCount = i+1
    indMat <- allMat[allMat[,2]==individuals[i],]
    for (j in 1:length(cutMat[,1])){
      jCount = j+1
      locusMean <- meanLocusDif[which(testLoci==cutMat[j,1])]
      tetSd <- sdOutsCheckMat[which(testLoci==cutMat[j,1]),2]
      indLocMean <- mean(indMat[indMat[,1]==cutMat[j,1],4])
      indSdofOuts <- mean(indMat[indMat[,1]==cutMat[j,1],5])
      tempMeanSum <- tempMeanSum + indLocMean
      if (indLocMean != "NaN"){
        if (indLocMean >= locusMean+-(locusMean*indThresh) & indSdofOuts >=tetSd+-(tetSd*sThresh)){
          infTestMat[iCount,jCount] <- 1
          tSum <- tSum +1
        }
        else{
          infTestMat[iCount,jCount] <- 0
          fSum <- fSum +1
        }
      }

      else{}
    }

    ratioMat[i,] <- c(individuals[i],tSum,info$PrePloidy[rowRef])

  }

  plot(ratioMat[,3]+runif(length(ratioMat[,3]),-0.1,0.1),ratioMat[,2], xlab="Ploidy", ylab="Number of Agreeing Informative Loci")

  tetMin <- 1
  dipMax <-1
  tetMean <-1
  dipMean <-1

  tets <- ratioMat[ratioMat[,3]==4,]
  avgAgree <- mean(tets[,2])
  sdAgree <- sd(tets[,2])
  badTet <- tets[tets[,2]<(avgAgree-(1.96*sdAgree)),]

  dips <- ratioMat[ratioMat[,3]==2,]
  badDip <- dips[dips[,2]>(avgAgree-(1.96*sdAgree)),]

  unknowns <- ratioMat[ratioMat[,3]==0,]

  assign("badTet", badTet, globalenv())
  assign("badDip", badDip, globalenv())
  assign("unknowns", unknowns, globalenv())
  assign("infMat", ratioMat, globalenv())
}


require( raster )
require( dplyr )
require( tidyr )
require( rgdal )
require( tictoc )
require( maptools )
require( rgeos )

#### Initialization / Model setup #####

tic()

# Location of input data
setwd( 'P:/is-wel/indus/message_indus' )

# Use ixmp? Takes time to upload - can choose option to debug w/o ixmp
use_ixmp = FALSE

# Local location of indus ix model - MAKE SURE TO ADD TO SYSTEM ENVIRONMENT VARIABLES
indus_ix_path = Sys.getenv("INDUS_IX_PATH")

# Location of GAMS - need to add to system environemtn variables but can't change from remote desktop :(
gams_path = 'C:/GAMS/win64/25.1'

# Basin analyzed
basin = 'Indus'

# Historical and planned electricity generation

# Historical capacity of technologies
hist_new_cap.df = read.csv( "input/historical_new_cap.csv", stringsAsFactors=FALSE ) %>%
					dplyr::select( -units )

ppls = 	unique( hist_new_cap.df$tec )[1:24]
cap = hist_new_cap.df	%>%
	filter( tec %in% ppls ) %>%
	mutate( country = unlist( strsplit( node, '_' ) )[seq(1,2*length(node),by=2)] ) %>%
	mutate( type = sapply( tec, function( ttt ){ rs = unlist( strsplit( ttt, '_' ) )[1] } ) ) %>%
	group_by( country, type, year_all ) %>% summarise( value = sum(value) ) %>% ungroup() %>% data.frame()
cap_2017 = hist_new_cap.df	%>%
	filter( tec %in% ppls, year_all < 2020 ) %>%
	mutate( country = unlist( strsplit( node, '_' ) )[seq(1,2*length(node),by=2)] ) %>%
	mutate( type = sapply( tec, function( ttt ){ rs = unlist( strsplit( ttt, '_' ) )[1] } ) ) %>%
	group_by( country, type ) %>% summarise( value = sum(value) ) %>% ungroup() %>% data.frame()
cap_2020 = hist_new_cap.df	%>%
	filter( tec %in% ppls, year_all >= 2020 ) %>%
	mutate( country = unlist( strsplit( node, '_' ) )[seq(1,2*length(node),by=2)] ) %>%
	mutate( type = sapply( tec, function( ttt ){ rs = unlist( strsplit( ttt, '_' ) )[1] } ) ) %>%
	group_by( country, type ) %>% summarise( value = sum(value) ) %>% ungroup() %>% data.frame()

pdf( 'input/indus_electricity_capacity.pdf', width=5, height=6 )
p1 = layout( matrix( c(2,1),2,1, byrow=TRUE ), widths=c(1), heights=c(0.12,0.9) )
cap2plot = reshape(cap_2017, direction='wide', idvar = 'type', timevar = 'country' )
row.names(cap2plot) = cap2plot$type
cap2plot = cap2plot[,c(2:ncol(cap2plot))]
names(cap2plot) = unlist(strsplit(names(cap2plot),'[.]'))[seq(2,2*length(names(cap2plot)),by=2)]
cap2plot_tot = colSums( cap2plot, na.rm=TRUE )
cap2plot_fr = do.call( cbind, lapply( 1:ncol( cap2plot ), function( iii ){ ( 100 * cap2plot[,iii] /  colSums( cap2plot, na.rm=TRUE )[iii] ) } ) )
cap2plot_fr[is.na(cap2plot_fr)]=0
par(mar=c(2,4,0.5,3),oma=c(2,2,2,2))
cols = c( 'deepskyblue', 'brown', 'mistyrose', 'springgreen', 'black', 'yellow', 'orange', 'purple' )
cntrs = barplot( as.matrix( cap2plot_fr ), names.arg = names( cap2plot ), col = cols, ylab = 'Percent of Total Capacity [ % ]' )
abline(h=0)
abline(h=100)
abline(v=par()$usr[1])
abline(v=par()$usr[2],col='red')
xlim0=par()$usr[1:2]
par(new=TRUE)
plot.new()
plot.window(xlim=xlim0,ylim=c(700,round(max(cap2plot_tot)*1.05, digits=-3)),xaxs="i")
points( as.vector(cap2plot_tot) ~ cntrs, col = 'black', bg = 'red', pch = 21, cex = 1.2, lwd = 1.5 )
axis(side = 4, col = 'red' )
mtext('Total Installed Capacity [ MW ]', side = 4, line = 2.75 )
par(mar=c(0.5,4,0,3))
plot.new()
legend( 'center', legend = row.names(cap2plot), fill = cols, bty = 'n', ncol = 3, cex = 0.9 )
dev.off()


library(ggplot2)
library(reshape2)
library(extrafont)
args=commandArgs(trailingOnly = T)

args[1]="dataCSV20181010.famknown2018Oct10"
args[2]="dataCSV20181010.famunid2018Oct10"
args[3]="dataCSV20181010.famhtr2018Oct10"
known=read.table(args[1],sep="\t")
unidentified=read.table(args[2],sep="\t")
htr=read.table(args[3],sep="\t")

outbase="RBPfamDist"
tstring=gsub(" .*$","",Sys.time(),perl=TRUE)
outname=paste(outbase,tstring,".pdf",sep="")

kn_htr=merge(known,htr,by="V1")
kn_htr_unid=merge(kn_htr,unidentified,by="V1")
colnames(kn_htr_unid)=c("V1","V2","V3","V4")
kn_htr_unid$V5=kn_htr_unid$V2 - kn_htr_unid$V3
colnames(kn_htr_unid)=c("name","known","HTR","unknown","previous")
ntab=data.frame(kn_htr_unid[,1],kn_htr_unid[,4],kn_htr_unid[,5],kn_htr_unid[,3])
colnames(ntab)=c("name","unknown","previous","HTR")
ntab=ntab[order(ntab$HTR+ntab$unknown+ntab$previous,decreasing=T),]
nntab=melt(ntab)

p=ggplot(nntab,aes(name,value,fill=variable))+geom_col(width = 0.618)+
  scale_x_discrete("RBP Family",limits=ntab$name)+ scale_fill_brewer(limits=c("HTR","previous","unknown"),labels=c("HTR","Previous","Unknown"),palette="Pastel1")+
  scale_y_continuous("RBP Counts")+ggtitle("RBPs protein class")+
  theme(panel.background=element_blank(),axis.line.x=element_line(size=1,color="grey",linetype="solid"),axis.line.y=element_line(size=1,color="grey",linetype="solid"),plot.title=element_text(size=rel(1.5),hjust = 0.5),axis.text.y=element_text(size=rel(1.2)),axis.text.x=element_text(angle=60,size=rel(1.2),vjust=0.5),axis.title=element_text(size=rel(1.5)),legend.text=element_text(size=rel(1.2)),legend.position=c(0.85,0.9),legend.title=element_blank(),legend.background=element_blank(),text = element_text(family = "Arial Narrow"))

ggsave(p,filename = outname,height = 10,width = 10,units = "cm")


# wahpenayo at gmail dot com
# 2017-12-10
#-----------------------------------------------------------------
if (file.exists('e:/porta/projects/taigabench')) {
  setwd('e:/porta/projects/taigabench')
} else {
  setwd('c:/porta/projects/taigabench')
}
source('src/scripts/r/functions.r')
readr.show_progress <- FALSE
#-----------------------------------------------------------------
dataset <- 'ontime'
problem <- 'l2'
response <- 'arrdelay'
dataf <- ontime.data
dtest <- dataf(test.file(dataset=dataset))
suffixes <- c('32768','131072','524288','2097152','8388608','33554432')
#-----------------------------------------------------------------
bench(
  dataset=dataset,problem=problem,dataf=dataf,dtest=dtest,
  response=response,
  suffixes=suffixes,
  trainf=l2.randomForestSRC,
  prefix='randomForestSRC')

bench(
  dataset=dataset,problem=problem,dataf=dataf,dtest=dtest,
  response=response,
  suffixes=suffixes,
  trainf=l2.h2o.randomForest,
  prefix='h2o')

bench(
  dataset=dataset,problem=problem,dataf=dataf,dtest=dtest,
  response=response,
  suffixes=suffixes,
  trainf=l2.xgboost.randomForest,
  prefix='xgboost')

bench(
  dataset=dataset,problem=problem,dataf=dataf,dtest=dtest,
  response=response,
  suffixes=suffixes,
  trainf=l2.xgboost.exact.randomForest,
  prefix='xgboost.exact')

bench(
  dataset=dataset,problem=problem,dataf=dataf,dtest=dtest,
  response=response,
  # crashes in 64gb at 1m
  suffixes=suffixes[1:min(3,length(suffixes))],
  trainf=l2.randomForest,
  prefix='randomForest')
#-----------------------------------------------------------------


require( rgeos )
require( raster )
require( dplyr )
require( rgdal )
require( ggmap )
require( cartography )

# Increase memory size
memory.limit( size = 1e9 )

# set working drive
setwd( 'P:/is-wel/indus/message_indus' )

basin = 'Indus'

# Get the basin country units with provicial detail for india and pakistan
test.spdf = readOGR( 'input', paste( basin, 'prov_bcu', sep = '_' ), verbose = FALSE )
admin_basin.sp = gUnaryUnion( test.spdf, test.spdf@data$ADMIN )
proj4string( admin_basin.sp ) = proj4string( test.spdf )
admin_basin.sp = spTransform( admin_basin.sp, crs( test.spdf ) )

require( RColorBrewer )
windows()
par(mar=c(2,2,2,2), oma = c(2,2,2,2))
plot( basin.sp, border = alpha( c('black'), alpha=0.8 ))
plot( admin_basin.sp, border = 'white', col = alpha( rev( brewer.pal(12, 'Set3' ) ), alpha=0.8 ) )
legend( 'bottomright', legend = c(names(admin_basin.sp)), fill = alpha( rev( brewer.pal(12, 'Set3' ) ), alpha=0.8 ), border = alpha( rev( brewer.pal(12, 'Set3' ) ), alpha=0.8 ), ncol = 1, cex=0.55, bty='n' )

## Cities for plotting
cities = c('Lahore', 'Islamabad', 'Hyderabad Pakistan', 'Gilgit', 'Kabul')
cities2 = c('Lahore', 'Islamabad', 'Hyderabad', 'Gilgit', 'Kabul')
cities.spdf = data.frame( geocode( cities ) )
cities.spdf$city = cities2
row.names(cities.spdf) = cities2
coordinates( cities.spdf ) = ~lon+lat
proj4string(cities.spdf) = proj4string(admin_basin.sp)
cities.spdf = spTransform( cities.spdf, crs(admin_basin.sp) )
cities.spdf@data$num = 1
cities.df = data.frame( cities.spdf )
cities_lab.df = cities.df %>%
					mutate( lat = lat - 0.5 ) %>%
					mutate( lon = lon - 0 )
cities_lab.spdf = cities_lab.df
coordinates( cities_lab.spdf ) = ~lon+lat
proj4string(cities_lab.spdf) = proj4string(admin_basin.sp)
cities_lab.spdf = spTransform( cities_lab.spdf, crs(admin_basin.sp) )

## Major reservoirs for plotting

reservoirs = c('Tarbela','Mangla')
reservoirs.spdf = spTransform(readOGR("P:/ene.general/Water/global_basin_modeling/grand_v1_1",'GRanD_dams_v1_1',verbose=FALSE), crs(admin_basin.sp))[ which( grepl( paste( reservoirs, collapse='|'), global_reservoirs.spdf@data$RES_NAME ) ) , 'RES_NAME' ]
reservoirs.spdf@data$num=1
reservoirs.df = data.frame( reservoirs.spdf )
reservoirs_lab.df = reservoirs.df %>%
					mutate( coords.x2 = coords.x2 + 1 ) %>%
					mutate( coords.x1 = coords.x1 + 1.3 )
reservoirs_lab.spdf = reservoirs_lab.df
coordinates( reservoirs_lab.spdf ) = ~coords.x1+coords.x2
proj4string(reservoirs_lab.spdf) = proj4string(admin_basin.sp)
reservoirs_lab.spdf = spTransform( reservoirs_lab.spdf, crs(admin_basin.sp) )

## Label for arabian sea
sea_label.spdf = data.frame( coords.x1 = 65.5, coords.x2 = 23.5, sea = 'Arabian Sea' )
coordinates( sea_label.spdf ) = ~coords.x1+coords.x2
proj4string(sea_label.spdf) = proj4string(admin_basin.sp)
sea_label.spdf = spTransform( sea_label.spdf, crs(admin_basin.sp) )

## Map 1 - Existing and Planned Hydropower

# Get hydropower data and aggregate to provinces
global_hydropower.spdf = readOGR("P:/ene.general/Water/global_basin_modeling/global_hydropower_plants",'global_hydropower_plants')
global_hydropower.df = data.frame(global_hydropower.spdf)
planned_projects.df = data.frame( read.csv( "P:/is-wel/indus/datagis/raw/indus_future_hydro_projects.csv", stringsAsFactors = FALSE ) )
planned_projects.df = planned_projects.df[, c('x','y','opening','capacity_MW') ]
names(planned_projects.df) = c( 'coords.x1', 'coords.x2', 'YEAR', 'MW' )
planned_projects.df$STATUS = 'PLN'
planned_projects.df = planned_projects.df[,c( 'MW','STATUS','YEAR','coords.x1','coords.x2')]
global_hydropower.df = global_hydropower.df[,c( 'MW','STATUS','YEAR','coords.x1','coords.x2')]
global_hydropower.df = rbind( global_hydropower.df, planned_projects.df)
coordinates(global_hydropower.df) = ~ coords.x1 + coords.x2
proj4string(global_hydropower.df) = proj4string(admin_basin.sp)
global_hydropower.df = spTransform( global_hydropower.df, crs(admin_basin.sp) )
basin_hydro.df = do.call( rbind, lapply( 1:length(admin_basin.sp), function( iii ){

	data.frame( Installed = sum( c( 0, global_hydropower.df@data[ which(	!is.na( over(global_hydropower.df,admin_basin.sp[iii]) ) &
																			as.character( global_hydropower.df$STATUS ) == 'OPR'), 'MW' ] ), na.rm=TRUE ),
				Planned =  sum( c( 0, global_hydropower.df@data[ which(		!is.na( over(global_hydropower.df,admin_basin.sp[iii]) ) &
																			as.character( global_hydropower.df$STATUS ) == 'PLN'), 'MW' ] ), na.rm=TRUE ) )

	} ) )
row.names( basin_hydro.df ) = row.names( admin_basin.sp )
basin_hydro.spdf = SpatialPolygonsDataFrame( admin_basin.sp, basin_hydro.df )

# plot using cartography packages
plt.spdf = basin_hydro.spdf
plt.df=data.frame(plt.spdf)
# Set a custom color palette
bb = 4
cols2 = carto.pal(pal1="green.pal", n1 = bb-1, pal2 = "orange.pal", n2 = bb, middle = FALSE,transparency = FALSE)
#cols2 = carto.pal(pal1 = "red.pal" ,n1 = 7)

# Country borders
cnt.spdf = do.call( rbind, lapply( c('IND','PAK','AFG','CHN','NPL','TJK','UZB','TKM','IRN'), function(cnt){ getData( 'GADM', country = cnt, level = 0 ) } ) )
cnt.spdf = gSimplify( cnt.spdf, tol = 0.1 )

windows()
plot( 	buffer( plt.spdf, width = 1.4 ),
		border = NA,
		col = NA,
		cex.axis = 0.8,
		cex.main = 0.9,
		cex.lab = 0.8,
		main="Installed Hydropower Capacity",
		bg = "#A6CAE0",
		xlab = expression("Longitude ["~degree*"E ]"),
		ylab = expression("Latitude ["~degree*"N ]"),
		mgp = c(2.5,0.5,0) )
#plot(spTransform( world.spdf, crs(plt.spdf ) ), col  = "grey95", border=NA, add=TRUE)
plot(spTransform( cnt.spdf, crs(plt.spdf ) ), border  = "grey40", col="grey95", add=TRUE)
choroLayer(	spdf = plt.spdf,
			df = plt.df,
			var = "Installed",
			#breaks = round( unlist( c( quantile(plt.df$Installed,c(0,0.3,0.4,0.6,0.8,0.9,0.95,1)) ) ), digits=-1 ),
			breaks = c(0,50,100,1000,2000,2500,4000,5700),
			col = cols2,
			border = 'white',
			lwd = 0.1,
			legend.pos = "topright",
			legend.title.txt = "Megawatts",
			legend.title.cex = 0.6,
			legend.values.rnd = 0,
			add = TRUE )
propSymbolsLayer( 	spdf = cities.spdf,
					var = "num",
					inches = 0.035,
					col = 'black',
					legend.pos = 'n',
					border = 'white' )
labelLayer(spdf = cities_lab.spdf, # SpatialPolygonsDataFrame used to plot he labels
           txt = "city", # label field in df
           col = "black", # color of the labels
           cex = 0.6, # size of the labels
           font = 2) # label font
labelLayer(spdf = sea_label.spdf, # SpatialPolygonsDataFrame used to plot he labels
           txt = "sea", # label field in df
           col = "royalblue4", # color of the labels
           cex = 0.6, # size of the labels
           font = 3) # label font
# propSymbolsLayer( 	spdf = reservoirs.spdf,
					# var = "num",
					# inches = 0.035,
					# col = 'mediumorchid1',
					# legend.pos = 'n',
					# border = 'white' )
# labelLayer(spdf = reservoirs_lab.spdf, # SpatialPolygonsDataFrame used to plot he labels
           # txt = "RES_NAME", # label field in df
           # col = "mediumorchid1", # color of the labels
           # cex = 0.7, # size of the labels
           # font = 2) # label font
box()
axis(side=1, cex.axis = 0.8)
axis(side=2, cex.axis = 0.8)