library(s2dverification)
DATAPATH <- "~/Desktop/BSC/Journal/Clim_Dyn_Data/Old/"




# load data
# ----------


# Ano_CV_DJF <- readRDS(paste(DATAPATH,"tas/AnomDJF.rds", sep = ''))
# Ano_CV_JJA <- readRDS(paste(DATAPATH,"tas/AnomJJA.rds", sep = ''))
# Lat <- readRDS(paste(DATAPATH,"tas/Lat.rds", sep = ''))
# Lon <- readRDS(paste(DATAPATH,"tas/Lon.rds", sep = ''))

Ano_CV_DJF <- readRDS(paste(DATAPATH,"prlr/AnomPrDJF.rds", sep = ''))
Ano_CV_JJA <- readRDS(paste(DATAPATH,"prlr/AnomPrJJA.rds", sep = ''))
Lat <- readRDS(paste(DATAPATH,"prlr/PrLat.rds", sep = ''))
Lon <- readRDS(paste(DATAPATH,"prlr/PrLon.rds", sep = ''))

nlat <- length(Lat)
nlon <- length(Lon)

# seasonal ensemble mean
# -----------------------

ExpDJF <- MeanListDim(Ano_CV_DJF$ano_exp, narm = T, c(2,4))
ObsDJF <- MeanListDim(Ano_CV_DJF$ano_obs, narm = T, c(2,4))
DataDJF <- aperm(abind::abind(ExpDJF, ObsDJF, along = 1), c(2,1,3,4))


ExpJJA <- MeanListDim(Ano_CV_JJA$ano_exp, narm = T, c(2,4))
ObsJJA <- MeanListDim(Ano_CV_JJA$ano_obs, narm = T, c(2,4))
DataJJA <- aperm(abind::abind(ExpJJA, ObsJJA, along = 1), c(2,1,3,4))


######### The data is now in the form of seasonal ensemble mean for each model ############


# Compute VIF for multicollinearity
# =================================

vif_DJF_DAAG <- array(NA, dim = c(4,nlat, nlon))
for (lat in 1:nlat) {
  for (lon in 1:nlon) {
    ifelse(all(is.na(DataDJF[,,lat,lon])),
           vif_DJF_DAAG[,lat,lon] <- NA,
           vif_DJF_DAAG[,lat,lon] <- DAAG::vif(lm(DataDJF[,5,lat,lon] ~ DataDJF[,1:4,lat,lon], data = as.data.frame(DataDJF[,,lat,lon]))))
  }
}

vif_JJA_DAAG <- array(NA, dim = c(4,nlat, nlon))
vif_JJA_DAAG <- array(NA, dim = c(4,nlat, nlon))
for (lat in 1:nlat) {
  for (lon in 1:nlon) {
    ifelse(all(is.na(DataJJA[,,lat,lon])),
           vif_JJA_DAAG[,lat,lon] <- NA,
           vif_JJA_DAAG[,lat,lon] <- DAAG::vif(lm(DataJJA[,5,lat,lon] ~ DataJJA[,1:4,lat,lon], data = as.data.frame(DataJJA[,,lat,lon]))))
  }
}


# vif_DJF_car <- apply(DataDJF, c(3,4),
#                      function(x) car::vif(lm(x[,5] ~ x[,1]+x[,2]+x[,3]+x[,4], data = as.data.frame(x))))
# vif_JJA_car <- apply(DataJJA, c(3,4), 
#                      function(x) car::vif(lm(x[,5] ~ x[,1]+x[,2]+x[,3]+x[,4], data = as.data.frame(x))))




# Plot results
# =============



# map interval/color
# ------------------


vif_DJF_DAAG[vif_DJF_DAAG > 10] <- 11 
vif_JJA_DAAG[vif_JJA_DAAG > 10] <- 11 

int <- seq(1, 11, 1)
ncols <- length(int) -1
int.col <- c("#deebf7", "#c6dbef", "#9ecae1", 
             "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#a50f15", "#67000d")
interval <- c("VIF: 1", int[-c(1,11)], "10+")


setwd("~/Desktop/BSC/Journal/plot") 
source("~/Desktop/BSC/Journal/R/3.0.ColorBar.R")

postscript("multicoll_prlr.ps")
#postscript("multicoll_tas.ps")

par(mar=c(0,1,0,0))
layout(matrix(c(1,1,1,1,1,
                2,3,4,5,6,
                7,8,9,10,11,
                12,13,14,15,16,
                17,18,18,18,18), 5, 5, byrow = TRUE), 
       respect = TRUE, widths=c(.5,3,3,3,3), heights=c(.75,.5, 3,3,1)) 


#heading
plot.new()
title="Multicollinearity between Seasonal Precipitation Forecast Anomalies \n of Individual EUROSIP Models"
#title="Multicollinearity between Seasonal Temperature Forecast Anomalies \n of Individual EUROSIP Models"
text(0.5,0.5, title, cex=1.5,font=2)


# subheading
plot.new()
text(0.5,0.5,"", cex=1.25,font=2)
plot.new()
text(0.5,0.5,"Glosea5", cex=1.25,font=2)
plot.new()
text(0.5,0.5,"ECMWF", cex=1.25,font=2)
plot.new()
text(0.5,0.5,"NCEP", cex=1.25,font=2)
plot.new()
text(0.5,0.5,"MF", cex=1.25,font=2)


# winter
plot.new()
text(0.5,0.5,"W\nI\nN\nT\nE\nR", cex=1.25,font=2)

# WINTER
PlotEquiMap(vif_DJF_DAAG[1,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',           drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_DJF_DAAG[2,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_DJF_DAAG[3,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_DJF_DAAG[4,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)


# summer
plot.new()
text(0.5,0.5,"S\nU\nM\nM\nE\nR", cex=1.25,font=2)

# SUMMER
PlotEquiMap(vif_JJA_DAAG[1,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_JJA_DAAG[2,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_JJA_DAAG[3,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)
PlotEquiMap(vif_JJA_DAAG[4,,], Lon, Lat,
            brks = int, cols = int.col, colNA = 'white',
            drawleg = FALSE, numbfig = 8, axelab = FALSE,
            filled.continents = FALSE)

# int.col
plot.new()
text(0.5,0.5," ", cex=1.25,font=2)
ColorBar(interval, cols=int.col, vert=FALSE, cex = .65, tick=FALSE, 
         upperspace=0.5, lowerspace = .5) 
dev.off()



# # Compute Condtional Number
# # ==========================
# 
# # rule of thumb - values of CN > 30 indicate severe collinearity
# cn_DJF <- apply(DataDJF, c(3,4), function(x) kappa(x)) # max 20.92335
# cn_JJA <- apply(DataJJA, c(3,4), function(x) kappa(x)) # max 21.39942
# 
# 
# det_DJF <- apply(DataDJF, c(3,4), function(x) det(cov(x[,-5]))) 
# det_JJA <- apply(DataJJA, c(3,4), function(x) det(cov(x[,-5]))) 
# 
# 
# 
# 
# eigen_DJF <- apply(DataDJF, c(3,4), function(x) min(eigen(cov(x[,-5]))$values)) 
# eigen_JJA <- apply(DataJJA, c(3,4), function(x) min(eigen(cov(x[,-5]))$values)) 
# 
# setwd("~/2_SForecastAssessment/plots")
# source("~/2_SForecastAssessment/R/3.0.ColorBar.R")
# 
# int <- seq(max(min(eigen_DJF),min(eigen_JJA)) , max(max(eigen_DJF),max(eigen_JJA)), .1)
# ncols <- length(int) -1
# int.col <- c(hcl(10, l=seq(99,20,length=ncols), c=seq(30,70,length=ncols)))
# 
# par(mar=c(.2, .2, .2, .2))
# layout(matrix(c(1,1,2,3,4,4), 3, 2, byrow = TRUE), respect = TRUE, widths=c(2,2), heights=c(.65,2,.35)) 
# 
# #heading
# plot.new()
# text(0.5,0.5,"Multicollinearity Assessment using min Eigen values",
#      cex=2,font=2)
# 
# PlotEquiMap(eigen_DJF, Lon, Lat,
#             toptitle = "DJF", title_scale = 0.75,
#             brks = int, cols = int.col, 
#             drawleg = FALSE, numbfig = 2, axelab = FALSE,
#             filled.continents = FALSE)
# 
# PlotEquiMap(eigen_JJA, Lon, Lat,        toptitle = "JJA", title_scale = 0.75,
#             brks = int, cols = int.col, 
#             drawleg = FALSE, numbfig = 2, axelab = FALSE,
#             filled.continents = FALSE)
# 
# ColorBar(round(int, 3), cols=int.col, vert=FALSE, cex = .5, tick=FALSE, 
#          upperspace=0.4, lowerspace = .6)
# 
# # ====================================================================================
# 
