##########################################################################################
#                Relationship between WTs and a chosen climate variable                  #
##########################################################################################

library(s2dverification)  # for the function Load()
source('/home/Earth/ncortesi/Downloads/scripts/Rfunctions.R') # for the calendar functions
Load.path <- '/home/Earth/ncortesi/Downloads/scripts/IC3.conf'      # Load() file path for resampled MSLP

workdir="/scratch/Earth/ncortesi/RESILIENCE/WT"    # working dir with the input files with the WT classifications for each MSLP grid point
mapdir="/scratch/Earth/ncortesi/RESILIENCE/WT_maps"  # output dir with seasonal and yearly maps

psl.rean='ERAintDailyHighRes'   # daily reanalysis dataset used for MSLP data
var.name='sfcWind'  # any daily reanalysis variable we want to find if it is driven by WTs
var.rean='ERAint'   # daily reanalysis dataset used for the var data; it can have a different resolution of the MSLP dataset

year.start=1985 #1985     # starting year of the MSLP daily data (from the 1st of january)
year.end=2014 #2014       # ending year of the MSLP daily data (up to the 31 of December)

##########################################################################################

WTs.type <- c("NE","E","SE","S","SW","W","NW","N","C","C.NE","C.E","C.SE","C.S","C.SW","C.W","C.NW","C.N","A","A.NE","A.E","A.SE","A.S","A.SW","A.W","A.NW","A.N")
WTs.type10<-c("NE","E","SE","S","SW","W","NW","N","C","A")
WTs.type10.name<-c("Northeasterly (NE)","Easterly (E)","Southeasterly (SE)","Southerly (S)","Southwesterly (SW)","Westerly (W)","Northwesterly (NW)",
							"Northerly (N)","Cyclonic (C)","Anticyclonic (A)")
year.tot <- year.end - year.start + 1

periods=c(1:17)       # identify monthly (from 1=Jan to 12=Dec) , seasonal (from 13=winter to 16=Autumn) and yearly=17 values
n.periods <- length(periods)

# Load just 1 day of var data to detect the number of latitude and longitude points;
var <- Load(var.name, NULL, var.rean, paste0(year.start,'0101'), storefreq = 'daily', leadtimemax = 1, output = 'lonlat')
var.lat <- round(var$lat,3)
var.lon <- round(var$lon,3)
var.n.lat <- length(var.lat)  # number of latitude values of var
var.n.lon <- length(var.lon)
var.lon.pos <- ifelse(min(var.lon>=0), TRUE, FALSE)  # set lon.pos to TRUE if the longitude values of the reanalysis grid has no negative values, FALSE if not.
    
# Load just 1 day of MSLP data to detect the number of latitude and longitude points of the WT classifications
# we must exlude points > +80 degrees lat and < -80 deg. because the Lamb grid was created excluding these points:
MSLP <- Load('psl', NULL, psl.rean, paste0(year.start,'0101'), storefreq = 'daily', leadtimemax = 1, output = 'lonlat', configfile = Load.path)
psl.n.lat <- length(MSLP$lat)  # number of latitude values or MSLP
psl.n.lon <- length(MSLP$lon)  # number of longitude values of MSLP
psl.lon.pos <- ifelse(min(MSLP$lon>=0), TRUE, FALSE)  # set lon.pos to TRUE if the longitude values of the reanalysis grid has no negative values, FALSE if not.

psl.n.lat.unused.poles <- 20 # number of discarded latitude values near each of the two poles (it depends on the spatial resolutions of the MSLP reanalysis)
#psl.n.lat.unused.equat <- 20 # number of unused latitude values near each side of the equator (must exclude 10 degrees N/S for side, so it depends on the spat.res. of the reanalysis)
#psl.pos.lat.eq.north <- tail(which(MSLP$lat >= 0),1) # note than the eventual point at lat=0 is always included
#psl.pos.lat.eq.south <- head(which(MSLP$lat < 0),1) # note than the eventual point at lat=0 is always excluded
#psl.pos.lat.unused.eq.north <- (psl.pos.lat.eq.north - psl.n.lat.unused.poles + 1):psl.pos.lat.eq.north
#psl.pos.lat.unused.eq.south <- psl.pos.lat.eq.south:(psl.pos.lat.eq.south + psl.n.lat.unused.equat - 1)

# final latitude values used as central points:
#psl.lat.used <- MSLP$lat[-c(1:psl.n.lat.unused.poles,(psl.n.lat-psl.n.lat.unused.poles):psl.n.lat, psl.pos.lat.unused.eq.north, psl.pos.lat.unused.eq.south)]  
psl.lat.used <- round(MSLP$lat[-c(1:psl.n.lat.unused.poles,(psl.n.lat-psl.n.lat.unused.poles):psl.n.lat)],3)  # latitude values used as central points
psl.lon.used <- round(MSLP$lon,3) # longitude values used as central points

psl.n.lat.used <- length(psl.lat.used)
psl.n.lon.used <- length(psl.lon.used)   
psl.n.grid.points <- psl.n.lat.used * psl.n.lon.used

if(var.lon.pos && !psl.lon.pos) {ss <- which(psl.lon.used<0); psl.lon.used[ss] <- psl.lon.used[ss] + 360}  # convert the negative long of MSLP to the [0, +360] range
if(!var.lon.pos && psl.lon.pos) {ss <- which(psl.lon.used>180); psl.lon.used[ss] <- psl.lon.used[ss] - 360}  # convert the positive long of MSLP > 180 to the [-180, +180] range


# exlude var points > +~80 degrees lat and < -80 deg. because the Lamb grid was created excluding these points:
var.n.lat.unused.poles <- 20 # number of discarded latitude values near each of the two poles (it depends on the spatial resolutions of the var reanalysis)
var.n.lat.unused.equat <- 20 # numb. of unused latitude values near each side of the equator (must exclude 10 degrees N/S for side, so it depends on the spat.res. of the reanalysis)

var.pos.lat.eq.north <- tail(which(var$lat >= 0),1) # note than the eventual point at lat=0 is always included
var.pos.lat.eq.south <- head(which(var$lat < 0),1) # note than the eventual point at lat=0 is always excluded
var.pos.lat.unused.eq.north <- (var.pos.lat.eq.north - var.n.lat.unused.equat+1):var.pos.lat.eq.north
var.pos.lat.unused.eq.south <- var.pos.lat.eq.south:(var.pos.lat.eq.south + var.n.lat.unused.equat - 1)
var.pos.lat.unused.eq <- c(var.pos.lat.unused.eq.north, var.pos.lat.unused.eq.south)

#var.lat.used <- var.lat[-c(1:var.n.lat.unused.poles,(var.n.lat-var.n.lat.unused.poles):var.n.lat, var.pos.lat.unused.eq.north, var.pos.lat.unused.eq.south)]  # latitude values used as central points

var.lat.used <- var.lat[-c(1:var.n.lat.unused.poles,(var.n.lat-var.n.lat.unused.poles):var.n.lat)]
var.lon.used <- var.lon # longitude values used as central points
var.n.lat.used <- length(var.lat.used)
var.n.lon.used <- length(var.lon.used)   
var.n.grid.points <- var.n.lat.used * var.n.lon.used

# for each var grid point used, find the lat/lon position of the nearby point center of the WT classification:
closer.psl.lat <- closer.psl.lon <- array(NA, c(var.n.lat.used, var.n.lon.used))  # 2 matrices with the lat and lon position of the nearest MSLP grid point

i<-0;vlat.pos <- 0
for (vlat in var.lat.used) {
   vlat.pos<-vlat.pos+1
   
   vlon.pos<-0
   for(vlon in var.lon.used) {
       i<-i+1
       cat(paste0("Point #",i,"/", var.n.grid.points), '\r')
       vlon.pos<-vlon.pos+1
       
       closer.psl.pos <- nearest(vlat, vlon, psl.lat.used, psl.lon.used)
       closer.psl.lat[vlat.pos, vlon.pos] <- psl.lat.used[closer.psl.pos[1]]
       closer.psl.lon[vlat.pos, vlon.pos] <- psl.lon.used[closer.psl.pos[2]]
       
       #print(paste0("vlat=",vlat, " vlat.pos=",vlat.pos, " vlon=",vlon, " vlon.pos=",vlon.pos, " closer.psl.lat.pos=", closer.psl.pos[1], " closer.psl.lon.pos=",closer.psl.pos[2], " closer.psl.lat=", psl.lat.used[closer.psl.pos[1]], " closer.psl.lon=", psl.lon.used[closer.psl.pos[2]] )) # for the debug
       
   }
}

#save(closer.psl.lat, closer.psl.lon, file=paste0(workdir,"/closer_psl.RData"))  # save it if it is the first time
load(file=paste0(workdir,"/closer_psl.RData"))  # load it if already saved

#PlotEquiMap(closer.psl.lon, var.lon.used, var.lat.used, filled.continents = FALSE, brks=seq(0,360,1) ) # for the debug
#PlotEquiMap(closer.psl.lat, var.lon.used, var.lat.used, filled.continents = FALSE, brks=seq(-90,90,1) ) # for the debug

# for each var grid point used, load 1 year of daily var and wt data at time, and assign it to the closer mslp central point:
# (you can't open all data at once because it weights too much, but you can open 1 year at time)

#n.days.tot <- n.days.in.a.yearly.period(year.start,year.end)
n.days.tot <- 365 # for the debug

sub <- split.array.big(dimensions=c(n.days.in.a.yearly.period(year.start,year.end),var.n.lat.used, var.n.lon.used), along=3)
#save(sub, file=paste0(workdir,"/sub.RData")) # save sub to retrieve it later of you run the next loop only for 1 year only (because 'year.end' changes, so 'sub' changes too)
load(paste0(workdir,"/sub.RData"))

i=0
for(y in year.start:year.end){
   #y<-1981 # for the debug
   i<-i+1
   print(paste0("Year #",i,"/", year.tot))
   
   n.days <- n.days.in.a.year(y) 
   var <- Load(var.name, NULL, var.rean, paste0(y,'0101'), storefreq = 'daily', leadtimemax = n.days, output = 'lonlat') # load var data for the year y only
   #PlotEquiMap(var$obs[1, 1, 1, 1, , ], var.lon, var.lat, filled.continents = FALSE)

   var.serie <- wt.serie <- array(NA,c(var.n.lat.used, var.n.lon.used, n.days))  # arrays where to store the var and wt daily data of year y for all points

   j<-0
   vlat.pos <- 0
   for (vlat in var.lat.used) {
       #vlat<-var.lat.used[1]; vlon<-var.lon.used[1]  # for the debug
       j<-j+1
       vlat.pos <- vlat.pos+1       
       cat('Latitude ',j,'/',var.n.lat.used,'\r')
       
       vlon.pos <- 0
       for(vlon in var.lon.used) {
           vlon.pos <- vlon.pos+1
          
           var.serie[vlat.pos, vlon.pos,] <- var$obs[1,1,1,,which(var.lat==vlat),which(var.lon==vlon)]

           #WT <- read.table(file=paste0(workdir,"/","10WTs_",psl.rean,"_",year.start,"-",year.end,"_lat_",closer.psl.lat[vlat.pos,vlon.pos],"_lon_",closer.psl.lon[vlat.pos,vlon.pos],".txt"), header=TRUE, sep=" ", stringsAsFactors=FALSE, row.names=NULL)
           
           # load WTs classifications (variable WTs) for that year created with WT_vX.R:
           load(paste0(workdir,"/",y,"_Rdata/","10WTs_",psl.rean,"_year_",y,"_lat_",closer.psl.lat[vlat.pos,vlon.pos],"_lon_",closer.psl.lon[vlat.pos,vlon.pos],".RData"))
           
           # interval of days belonging to the year y, but starting to count from the year year.begin:
           #seq.days.year <- n.days.in.a.yearly.period(year.start,y) - n.days.in.a.yearly.period(year.start,year.start) + 1:n.days.in.a.year(y)
           
           wt.serie[vlat.pos, vlon.pos,] <- WTs  #[seq.days.year]  #,4]  # extract only the days of the year y
          
       }
   }

   #PlotEquiMap(var.serie[,,1], var.lon, var.lat.used, filled.continents = FALSE) # for the debug

   #save(var.serie, file=paste0(workdir,"/local_",var.name,"_",psl.rean,"_year_",y,".RData"), compress=FALSE)
   #save(wt.serie,  file=paste0(workdir,"/local_","10WTs_",psl.rean,"_year_",y,".RData"), compress=FALSE)

   # instead of saving only 1 file for all the spatial domain, save 1 file for each subarray s: (to be able to load them faster in the following step)
   for(s in 1:sub$n.sub){
     var.serie.year.sub<-var.serie[,sub$int[[s]],]  # format: [lat, lon, day]
     save(var.serie.year.sub, file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_",psl.rean,"_year_",y,"_sub_",s,".RData"), compress=FALSE)
     
     wt.serie.year.sub <- wt.serie[,sub$int[[s]],]
     save(wt.serie.year.sub, file=paste0(workdir,"/wt_sub/local_","10WTs_",psl.rean,"_year_",y,"_sub_",s,".RData"), compress=FALSE)
     # n.wt10<-apply(wt.serie.year.sub,c(1,2),function(x)length(which(x==18)))  # for the debug
     # edit(n.wt10) # for the debug
   }
    
} # close for on y

#rm(closer.psl.lat, closer.psl.lon, var)


# compute the climatology of var and its daily anomalies for each subarray:
var.clim <- array(NA, c(var.n.lat.used, var.n.lon.used))

for(s in 1:sub$n.sub){
      #s=1;y=year.start # for the debug
      cat(paste0("Computing subarray n. ", s,"/", sub$n.sub),'\r')

      if(s == sub$n.sub)  {
           var.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size.last, n.days.tot))
      } else {
          var.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size, n.days.tot))
      }
             
      for(y in year.start:year.end){
           load(file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_",psl.rean,"_year_",y,"_sub_",s,".RData"))  # load var.serie.year.sub
           int.days.year <- seq.days.in.a.future.year(year.start,y)
               
           var.serie.sub[,,int.days.year] <- var.serie.year.sub
    
           #int.days.period <- pos.period(y, p)
           #int.days.future.period <- n.days.in.a.future.year(year.start, y) + int.days.period
           #int.days.na <- which(1:n.days.in.a.year(y)==int.days.future.period)
           #var.serie.sub[,,int.days.future.period] <- 
                         
           rm(var.serie.year.sub)
      }

      var.clim.sub <- apply(var.serie.sub,c(1,2),mean, na.rm=T)
    
      var.anom.sub <- var.serie.sub - InsertDim(var.clim.sub,3,n.days.tot)
      var.clim[,sub$int[[s]]] <- var.clim.sub

      # save the var anomaly, one file for each subarray:
      save(var.anom.sub, file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_anomaly_",psl.rean,"_",year.start,"-",year.end,"_sub_",s,".RData"), compress=FALSE)

      rm(var.serie.sub, var.anom.sub)
}

save(var.clim, file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_climatology_",psl.rean,"_",year.start,"-",year.end,".RData"), compress=FALSE)
load(paste0(workdir,"/",var.name,"_sub/local_",var.name,"_climatology_",psl.rean,"_",year.start,"-",year.end,".RData"))

# do the same as above, but for the wt:

wts <- c(1:10) # weather type numbers inside wt.serie
n.wts<-length(wts)
n.wt <- var.wt.sum <- var.wt.mean.anom <- var.wt.sd.anom <- array(NA, c(n.wts, var.n.lat.used, var.n.lon.used))
#vlat.mat <- vlon.mat <- array(NA, c(var.n.lat.used, var.n.lon.used))  # for the debug

for(s in 1:sub$n.sub){
      #s=1;y=year.start # for the debug
      cat(paste0("Computing subarray n. ", s,"/", sub$n.sub),'\r')

      if(s == sub$n.sub)  {
           wt.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size.last, n.days.tot))
           n.wt.sub <- var.wt.sum.sub <- var.wt.mean.anom.sub <- var.wt.sd.anom.sub <- array(NA,c(n.wts, var.n.lat.used, sub$sub.size.last))
           var.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size.last, n.days.tot)) 
      } else {
           wt.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size, n.days.tot))
           n.wt.sub <- var.wt.sum.sub <- var.wt.mean.anom.sub <- var.wt.sd.anom.sub <- array(NA,c(n.wts, var.n.lat.used, sub$sub.size))
           var.serie.sub <- array(NA, c(var.n.lat.used, sub$sub.size, n.days.tot))
      }
    
             
      for(y in year.start:year.end){
           load(file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_",psl.rean,"_year_",y,"_sub_",s,".RData"))  # load var.serie.year.sub
           int.days.year <- seq.days.in.a.future.year(year.start,y)
               
           var.serie.sub[,,int.days.year] <- var.serie.year.sub    
           rm(var.serie.year.sub)
      }

    
      for(y in year.start:year.end){
           load(file=paste0(workdir,"/wt_sub/local_","10WTs_",psl.rean,"_year_",y,"_sub_",s,".RData"))  # load wt.serie.year.sub

           wt.serie.year.sub[which(wt.serie.year.sub==18)]<-10  # rename the A type from number 18 to number 10, to have only the numbers from 1 to 10
           int.days <- seq.days.in.a.future.year(year.start,y)
               
           wt.serie.sub[,,int.days] <- wt.serie.year.sub  #[,sub$int[[s]],]
           rm(wt.serie.year.sub)
      }

      load(file=paste0(workdir,"/",var.name,"_sub/local_",var.name,"_anomaly_",psl.rean,"_",year.start,"-",year.end,"_sub_",s,".RData"))  # load var.anom.sub
    
      vlat.pos  <- 0
      for (vlat in var.lat.used) {
         #vlat<-var.lat.used[1]; vlon<-var.lon.used[1]; wt=1  # for the debug
         vlat.pos <- vlat.pos + 1
         #cat('Latitude ',vlat.pos,'/',var.n.lat.used,'\r')
       
         vlon.pos <- 0 #sub$int[[s]]-1
         for(vlon in var.lon.used[sub$int[[s]]]) {
             vlon.pos <- vlon.pos + 1
              for(wt in wts){
                  pos.wt <- which(wt.serie.sub[vlat.pos,vlon.pos,]==wt)
                  
                  n.wt.sub[wt,vlat.pos,vlon.pos] <- length(pos.wt)
                  var.wt.sum.sub[wt,vlat.pos,vlon.pos] <- sum(var.serie.sub[vlat.pos,vlon.pos,][pos.wt])  # only for wind and prec
                  var.wt.mean.anom.sub[wt,vlat.pos,vlon.pos] <- mean(var.anom.sub[vlat.pos,vlon.pos,][pos.wt])
                  var.wt.sd.anom.sub[wt,vlat.pos,vlon.pos] <- sd(var.anom.sub[vlat.pos,vlon.pos,][pos.wt]) 

              }
         }
      }
    
      n.wt[,,sub$int[[s]]] <- n.wt.sub
      var.wt.sum[,,sub$int[[s]]] <- var.wt.sum.sub
      var.wt.mean.anom[,,sub$int[[s]]] <- var.wt.mean.anom.sub
      var.wt.sd.anom[,,sub$int[[s]]] <- var.wt.sd.anom.sub
}

save(n.wt, var.wt.sum, var.wt.mean.anom, file=paste0(workdir,"/",var.name,"_sub/output_",psl.rean,"_",year.start,"-",year.end,".RData"), compress=FALSE)
load(file=paste0(workdir,"/",var.name,"_sub/output_",psl.rean,"_",year.start,"-",year.end,".RData"))

#s <- which(is.na(var.wt.mean))
#ar.wt.mean[ss] <- -999
var.lon.used.bis <- c(var.lon.used[c(257:512)]-360,var.lon.used[c(1:256)]) # to put Europe in the middle of the map

#pos.var.lat.unused <- which(is.na( match(var.lat,var.lat.used)))  # position inside var.lat of the latitude values not used (those not in var.lat.used)
pos.var.lat.used <- match(var.lat.used, var.lat) # =which(!is.na( match(var.lat,var.lat.used)))  # position inside var.lat of the latitude values used (those in var.lat.used)
#var.lat[pos.var.lat.unused]

var.wt.mean <- var.wt.sum/n.wt # average value of var associated to a WT
n.wt <- 100*n.wt/n.days.tot # convert to yearly frequency in %
var.wt.mean.contrib <- 100*var.wt.sum/(InsertDim(var.clim,1,n.wts)*n.days.tot)  # convert the sum to a % contribution

var.clim.NA <-  array(NA, c(var.n.lat, var.n.lon.used))
n.wt.NA <- var.wt.mean.contrib.NA <- var.wt.sum.NA <- var.wt.mean.anom.NA <- var.wt.mean.NA <- var.wt.sd.anom.NA <- array(NA, c(n.wts, var.n.lat, var.n.lon.used))

var.clim.NA[pos.var.lat.used,] <- var.clim
n.wt.NA[,pos.var.lat.used,] <- n.wt
var.wt.mean.NA[,pos.var.lat.used,] <- var.wt.mean
var.wt.sum.NA[,pos.var.lat.used,] <- var.wt.sum
var.wt.mean.anom.NA[,pos.var.lat.used,] <- var.wt.mean.anom
var.wt.mean.contrib.NA[,pos.var.lat.used,] <- var.wt.mean.contrib
var.wt.sd.anom.NA[,pos.var.lat.used,] <- var.wt.sd.anom.NA

# remove the equatorial area from visualization:
n.wt.NA[,var.pos.lat.unused.eq,] <- var.wt.mean.NA[,var.pos.lat.unused.eq,] <- var.wt.sum.NA[,var.pos.lat.unused.eq,] <- var.wt.mean.contrib.NA[,var.pos.lat.unused.eq,] <- NA
var.wt.sd.anom.NA[,var.pos.lat.unused.eq,] <- NA

# Map intervals and colors:
my.brks <- list()

#my.brks[[1]] <- c(0,seq(1.5,9,0.5),15)  # Wind speed Climatology
my.brks[[1]] <- c(0,seq(1.05,10,0.05),15)  # Wind speed Climatology
#my.brks[[2]] <- c(-10,seq(-4.95,5,0.05),10) # Wind Speed Anomaly associated to a WT
my.brks[[2]] <- c(seq(0,10,0.1),100) # Mean wind speed in m/s associated to a WT
my.brks[[3]] <- c(seq(0,30,0.1),100) # Frequency associated to a WT
my.brks[[4]] <- c(seq(0,30,0.1),100) # % Contribution of a WT to total var
my.brks[[5]] <- c(seq(-10,-3,1),seq(-2.3,2.3,0.1),seq(3,10,1)) # % Mean anomaly of a WT
my.brks[[6]] <- c(seq(0,3,0.1),10) # Standard deviation of the anomalies pf a WT

my.cols <- list()
#my.cols[[index]] <- colorRampPalette(my.palette[[index]])(length(my.brks[[index]])-1)
#my.cols[[1]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1)  # blue-green-white-yellow-red colors
#my.cols[[1]] <-  colorRampPalette(c("white","yellow","orange","red","darkred"))(length(my.brks[[1]])-1)  # blue-yellow-red colors
#my.cols[[1]] <-  colorRampPalette(c("white","white","green","yellow","orange","red","darkred"))(length(my.brks[[1]])-1)  # blue-yellow-red colors
#my.cols[[1]] <-  colorRampPalette(c("blue","white","darkred"))(length(my.brks[[1]])-1)  # blue-yellow-red colors
#my.cols[[1]] <-  colorRampPalette(c("blue","green","yellow","red","brown","violetred4"))(length(my.brks[[1]])-1)  # blue-yellow-red colors
my.cols[[1]] <-  colorRampPalette(c("white","cyan2","gold","orange","red","brown","brown4","deeppink4"))(length(my.brks[[1]])-1)  # blue-yellow-red colors
#my.cols[[2]] <-  colorRampPalette(c("deeppink4","darkblue","blue","white","red","darkred","brown4"))(length(my.brks[[2]])-1)  # blue-white-red colors
my.cols[[2]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[2]])-1)  # blue--yellow-red colors
my.cols[[3]] <-  rev(colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[3]])-1))  # blue-yellow-red colors
#my.cols[[4]] <-  colorRampPalette(c("white","cyan2","blue","deeppink4"))(length(my.brks[[4]])-1)  # blue-yellow-red colors
my.cols[[4]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[4]])-1)  # blue--yellow-red colors
my.cols[[5]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[5]])-1)  # blue--yellow-red colors
my.cols[[6]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[6]])-1)  # blue--yellow-red colors


# Create and save maps:

index=1

png(filename=paste0(mapdir,"/10-m_Wind_Speed_Climatology.png"),width=1000,height=700)

layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
#layout.show(2)
#PlotEquiMap2(var.clim.NA, var.lon.used, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F)
# change longitude in format -180,180 to displey europe in the middle of the map:

var.clim.NA.bis <- var.clim.NA[,c(257:512,1:256)]
PlotEquiMap(var.clim.NA.bis, var.lon.used.bis, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=20, cex=1)

dev.off()


index=2
wt=6

png(filename=paste0(mapdir,"/Average_10-m_Wind_Speed_WT_", WTs.type10[wt],".png"),width=1000,height=700)

layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
#PlotEquiMap(var.wt.mean.NA[wt,,], var.lon.used, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
#PlotEquiMap(var.wt.mean.NA[wt,,100:200], var.lon.used[100:200], var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
var.wt.mean.NA.bis <- var.wt.mean.NA[,,c(257:512,1:256)]
PlotEquiMap(var.wt.mean.NA.bis[wt,,], var.lon.used.bis, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
#PlotEquiMap(var.wt.mean.NA.bis[wt,,1:50], head(var.lon.used.bis,50), var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=10, cex=1)

dev.off()


index=3
wt=10

png(filename=paste0(mapdir,"/Frequency_WT_", WTs.type10[wt],".png"),width=1000,height=700)

layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
#PlotEquiMap(n.wt.NA[wt,,], var.lon.used, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F)
#PlotEquiMap(n.wt.NA[wt,,1:18], tail(var.lon.used,18), var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F)
#n.wt.NA[wt,50:55,490:512]
#ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=5, cex=1)
#n.wt10<-apply(wt.serie.,c(1,2),function(x)length(which(x==18)))  # for the debug
#edit(n.wt.NA[10,,]) # for the debug
#layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
n.wt.NA.bis <- n.wt.NA[,,c(257:512,1:256)]
PlotEquiMap(n.wt.NA.bis[wt,,], var.lon.used.bis, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray")
ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=5, cex=1)

dev.off()

index=4
wt=6 # for the debug

for(wt in 1:n.wts){
    png(filename=paste0(mapdir,"/Daily_contribution_of_WT_", WTs.type10[wt],".png"),width=1000,height=700)
    
    layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
    var.wt.mean.contrib.NA.bis <- var.wt.mean.contrib.NA[,,c(257:512,1:256)]
    PlotEquiMap(var.wt.mean.contrib.NA.bis[wt,,], var.lon.used.bis, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]],
                drawleg=F, colNA="gray", toptitle=WTs.type10.name[wt] , sizetit=1)
    ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=10, cex=1)
    
    dev.off()
}

index=5
wt=6 # for the debug
slide=TRUE  # put TRUE if you wan to print maps for a slide, with bigger titles and legends, false otherwise

if(!slide) {n.box <- 10; col.cex=1.5; my.title <- WTs.type10.name[wt]} else {n.box <- 5; col.cex=3}

for(wt in 1:n.wts){
    png(filename=paste0(mapdir,"/Mean_Anomalies_of_WT_", WTs.type10[wt],".png"),width=1000,height=700)
    
    layout(matrix(c(rep(1,n.box),2), n.box+1, 1, byrow = TRUE))
    var.wt.mean.anom.NA.bis <- var.wt.mean.anom.NA[,,c(257:512,1:256)]
    PlotEquiMap(var.wt.mean.anom.NA.bis[wt,,], var.lon.used.bis, var.lat, filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]],
                drawleg=F, colNA="gray", toptitle=my.title, sizetit=1.5)
    ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, subsampleg=2, cex=col.cex)
    if(slide) title(WTs.type10.name[wt],cex.main=3.5,outer=T)
    
    dev.off()
}

# Poster version over Europe:
index=5
for(wt in 1:n.wts){ #  wt==9
    png(filename=paste0(mapdir,"/Mean_European_Anomalies_of_WT_", WTs.type10[wt],".png"),width=1000,height=700)

    layout(matrix(c(rep(1,5),2), 6, 1, byrow = TRUE)) #, widths=c(1,2,3,4,5,6,7,8,9))
    #layout(matrix(c(1,1,1,2), 4, 1, byrow = TRUE), widths=c(11,1.2))
    par(oma=c(0,0,2,0))#, mar = rep(5, 4))
    var.wt.mean.anom.NA.bis <- var.wt.mean.anom.NA[,,c(257:512,1:256)]
    PlotEquiMap2(var.wt.mean.anom.NA.bis[wt,25:90,220:310], var.lon.used.bis[220:310], var.lat[25:90], filled.continents = FALSE, brks=my.brks[[index]], cols=my.cols[[index]], drawleg=F, colNA="gray", square=T) #, contours=var.wt.mean.anom.NA.bis[wt,25:90,220:310])
    ColorBar(my.brks[[index]], cols=my.cols[[index]], vert=FALSE, cex=3)    
    title(WTs.type10.name[wt],cex.main=3.5,outer=T)
    
    dev.off()
}
    

#WTs.type<-c("NE","E","SE","S","SW","W","NW","N","C","C.NE","C.E","C.SE","C.S","C.SW","C.W","C.NW","C.N","A","A.NE","A.E","A.SE","A.S","A.SW","A.W","A.NW","A.N")
