
# Creation: 6/2016
# Author: Nicola Cortesi
#
# Aim: to visualize the regime anomalies of the weather regimes, their interannual frequencies and their impact on a chosen cliamte variable (i.e: wind speed or temperature)
#
# I/O: the only input file needed is the output of the weather_regimes.R script, which ends with the suffix "_mapdata.RData".
#      Output files are the maps, with the user can generate as .png or as .pdf
#
# Assumptions: If your regimes derive from a reanalysis, this script must be run twice: once, with the option 'ordering = F' to create a .pdf or .png file that the user
#              must open to find visually the order by which the four regimes are stored inside the four clusters. For example, he can find that the sequence of the images
#              in the file (from top to down) corresponds to: Blocking / NAO- / Atl.Ridge / NAO+ regime. Subsequently, he has to change 'ordering' from F to T
#              and set the four variables 'clusterX.name' (X=1..4) to follow the same order found inside that file.
#              The second time, you have to run this script only to get the maps in the right order, which by default is, from top to down:
#              "NAO+","NAO-","Blocking" and "Atl.Ridge" (you can change it with the variable 'orden').
#              During these first two runs, the variable 'save.names' must be set to TRUE, so an .RData file is written to store the order of the four regimes, in case
#              in future a user needs to visualize these maps again. In this case, the user must set 'save.names= FALSE' and 'ordering=TRUE' to be able to visualize the maps
#              in the correct order.
#
#              If your regimes derive from a forecast system, you have to compute before the regimes derived from a reanalysis. Then, you can associate the reanalysis
#              to the forecast system, to employ it to automatically associate to each simulated cluster one of the
#              observed regimes, the one with the highest spatial correlation. Beware that the two maps of regime anomalies must have the same spatial resolution!
#
# Branch: weather_regimes

library(s2dverification)  # for the function Load()
library(Kendall) # for the MannKendall test

source('/home/Earth/ncortesi/Downloads/scripts/Rfunctions.R') # for the calendar functions
workdir <- "/scratch/Earth/ncortesi/RESILIENCE/Regimes"    # working dir with the input files with the WT classifications for each MSLP grid point

rean.name <- "ERA-Interim"       # reanalysis name (if input data comes from a reanalysis)
forecast.name <- "ECMWF-S4"      # forecast system name (if input data comes from a forecast system)

fields.name <- forecast.name         # Choose between loading reanalysis ('rean.name') or forecasts ('forecast.name')
var.num <- 2                         # if fields.name ='rean.name', Choose a variable for the impact maps 1: sfcWind  2: tas 

period <- 12      # 1:12          # Choose one or more periods to plot from 1 to 17 (1-12: Jan - Dec, 13-16: Winter, Spring, Summer, Autumn, 17: Year).
                                 # You need to have created before the '_mapdata.RData' file with the output of 'weather_regimes'.R for that period. 
lead.month <- 0                  # in case you selected 'fields.name = forecast.name', specify a leadtime (0 = same month of the start month) to plot
                                 # (and variable 'period' becomes the start month)

# run it twice: once, with ordering <- FALSE to look only at the cartography and find visually the right regime names of the four clusters;
# and the second time, to save the ordered cartography:
ordering <- T    # If TRUE, order the clusters following the regimes listed in the 'orden' vector (after you manually insert the names below).
as.pdf <- T # FALSE: save results as one .png file for each season, TRUE: save only 1 .pdf file with all seasons
save.names <- F  # if TRUE, also save the cluster names (i.e: the association between clusters and weather regimes); if FALSE, the cluster names are loaded from a file

rean.dir <- "20) as 18) but for monthly WRs"  # if fields.name='forecast.name', subdir of 'workdir' where the weather regimes computed with a reanalysis are stored.

# Associates the regimes to the four cluster:
cluster3.name <- "NAO+"  
cluster2.name <- "NAO-"
cluster1.name <- "Blocking"
cluster4.name <- "Atl.Ridge"

# choose an order to give to the cartograpy, from top to bottom:
orden <- c("NAO+","NAO-","Blocking","Atl.Ridge")
    
regime1.name <- orden[1]
regime2.name <- orden[2]
regime3.name <- orden[3]
regime4.name <- orden[4]

var.name <- c("sfcWind","tas")
var.num.orig <- var.num  # loading _mapadata files this value can change!
fields.name.orig <- fields.name

if(as.pdf && fields.name==rean.name)(pdf(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],".pdf"),width=40, height=60))
if(as.pdf && fields.name==forecast.name)(pdf(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_leadmonth_",lead.month,".pdf"),width=40,height=60))

for(p in period){
    # load regime data (for forecasts, it load only the data correpsonding to the chosen start month p and lead month 'lead.month'::
    if(fields.name == rean.name) load(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_mapdata.RData"))
    if(fields.name == forecast.name) load(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_leadmonth_",lead.month,"_mapdata.RData"))
    if(var.num != var.num.orig) var.num <- var.num.orig  # ripristinate original values of this script (necessary after loading regime data)
    if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
    
    if(fields.name == forecast.name){
        # compute correlations between simulated clusters and observed regime's anomalies:
        cluster1.sim <- pslwr1mean; cluster2.sim <- pslwr2mean; cluster3.sim <- pslwr3mean; cluster4.sim <- pslwr4mean
        lat.forecast <- lat; lon.forecast <- lon
        
        load(file=paste0(workdir,"/",rean.dir,"/",rean.name,"_",var.name[var.num],"_",my.period[p],"_mapdata.RData")) # load also reanalysis data, which overwrities the pslwrXmean variables
        if((p + lead.month) > 12) { load.month <- p + lead.month - 12 } else { load.month <- p + lead.month }  # reanalysis forecast month to load
        load(paste0(workdir,"/",rean.dir,"/",rean.name,"_", my.period[load.month],"_ClusterNames.RData")) # load also reanalysis regime names

        regimes.obs <- c(cluster1.name.period[p], cluster2.name.period[p], cluster3.name.period[p], cluster4.name.period[p]) # to be replaced soon by c(cluster1.name, cluster2.name, ...)

        if(identical(rev(lat),lat.forecast)) {lat.forecast <- rev(lat.forecast); print("Warning: forecast latitudes are in the opposite order than renalysis's")}
        if(!identical(lat, lat.forecast)) stop("forecast latitudes are different from reanalysis latitudes!")
        if(!identical(lon, lon.forecast)) stop("forecast longitude are different from reanalysis longitudes!")
        
        cluster.corr <- array(NA, c(4,4), dimnames=list(c("cluster1.sim","cluster2.sim","cluster3.sim","cluster4.sim"), regimes.obs))
        cluster.corr[1,1] <- cor(as.vector(cluster1.sim), as.vector(pslwr1mean))
        cluster.corr[1,2] <- cor(as.vector(cluster1.sim), as.vector(pslwr2mean))
        cluster.corr[1,3] <- cor(as.vector(cluster1.sim), as.vector(pslwr3mean))
        cluster.corr[1,4] <- cor(as.vector(cluster1.sim), as.vector(pslwr4mean))
        cluster.corr[2,1] <- cor(as.vector(cluster2.sim), as.vector(pslwr1mean))
        cluster.corr[2,2] <- cor(as.vector(cluster2.sim), as.vector(pslwr2mean))
        cluster.corr[2,3] <- cor(as.vector(cluster2.sim), as.vector(pslwr3mean))
        cluster.corr[2,4] <- cor(as.vector(cluster2.sim), as.vector(pslwr4mean))
        cluster.corr[3,1] <- cor(as.vector(cluster3.sim), as.vector(pslwr1mean))
        cluster.corr[3,2] <- cor(as.vector(cluster3.sim), as.vector(pslwr2mean))
        cluster.corr[3,3] <- cor(as.vector(cluster3.sim), as.vector(pslwr3mean))
        cluster.corr[3,4] <- cor(as.vector(cluster3.sim), as.vector(pslwr4mean))
        cluster.corr[4,1] <- cor(as.vector(cluster4.sim), as.vector(pslwr1mean))
        cluster.corr[4,2] <- cor(as.vector(cluster4.sim), as.vector(pslwr2mean))
        cluster.corr[4,3] <- cor(as.vector(cluster4.sim), as.vector(pslwr3mean))
        cluster.corr[4,4] <- cor(as.vector(cluster4.sim), as.vector(pslwr4mean))

        cluster1.regime <- unname(which(cluster.corr[1,] == max(cluster.corr[1,])))
        cluster2.regime <- unname(which(cluster.corr[2,] == max(cluster.corr[2,])))
        cluster3.regime <- unname(which(cluster.corr[3,] == max(cluster.corr[3,])))
        cluster4.regime <- unname(which(cluster.corr[4,] == max(cluster.corr[4])))

        # associate each simulated cluster to one observed regime:
        cluster1.name <- regimes.obs[cluster1.regime]
        cluster2.name <- regimes.obs[cluster2.regime]
        cluster3.name <- regimes.obs[cluster3.regime]
        cluster4.name <- regimes.obs[cluster4.regime]

        if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script
        load(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_leadmonth_",lead.month,"_mapdata.RData")) # reload forecast regime data
        if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script 
        if(identical(rev(lat),lat.forecast)) lat <- rev(lat) # ripristinate right lat order

    } # close for on 'forecast.name'

    # position of long values of Europe only (without the Atlantic Sea and America):
    #if(fields.name == "ERA-Interim") EU <- c(1:which(lon >= lon.max)[1], (length(lon)-30):length(lon))  # restrict area to continental europe only
    EU <- c(1:which(lon >= lon.max)[1], (which(lon >= 337)[1]:length(lon)))  # restrict area to continental europe only

        # breaks and colors of the geopotential fields:
    if(psl == "g500"){
        #my.brks <- c(-300,-199:200,300) # % Mean anomaly of a WR
        my.brks <- c(-300,seq(-200,200,10),300) # % Mean anomaly of a WR
        my.brks2 <- c(-300,seq(-200,200,10),300) # % Mean anomaly of a WR for the contour lines
        #my.cols <- colorRampPalette((brewer.pal(9,"PuBu")))(length(my.brks)-1)
        values.to.plot <- c(-200, -100, 0, 100, 200)  # values we want to show in the labels
    }

    if(psl == "psl"){
        my.brks <- c(seq(-19,-1,2),0,seq(1,19,2)) # % Mean anomaly of a WR
        #  my.brks <- c(seq(-19,-1,2),0,seq(1,19,2)) # % Mean anomaly of a WR

        my.brks2 <- my.brks #c(seq(-20,20,2)) # % Mean anomaly of a WR for the contour lines
        values.to.plot <- my.brks #c(-17,-15,-13,-11,-9,-7,-5,-3,-1,0,1,3,5,7,9,11,13,15,17)
    }

    my.cols <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks)-1)    # blue--white--red colors
    my.cols[floor(length(my.cols)/2)] <- my.cols[floor(length(my.cols)/2)+1] <- "white"
    
    # breaks and colors of the impact maps (valid both for Wind speed anomalies and Temperature anomalies):
    #my.brks.var <- c(-20,seq(-10,-3,1),seq(-2.9,2.9,0.1),seq(3,10,1),20) # % Mean anomaly of a WR
    #my.brks.var <- c(-20,-2,-1.5,-1,-0.5,-0.2,0.2,0.5,1,1.5,2,20) # % Mean anomaly of a WR
    #my.brks.var <- c(-20,seq(-3,3,0.5),20) # % Mean anomaly of a WR
    if(var.name[var.num] == "sfcWind") {
        my.brks.var <- seq(-3,3,0.5)
        values.to.plot2 <- c(-3,-2,-1,0,1,2,3)
    }
    if(var.name[var.num] == "tas") {
        my.brks.var <- seq(-5,5,1) 
        values.to.plot2 <- my.brks.var #c(-5,-3,-1,0,1,3,5)
    }
    
    #my.cols <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks)-1)  # blue--yellow-red colors
    my.cols.var <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks.var)-1)    # blue--white--red colors
    #my.cols.var[floor(length(my.cols.var)/2)] <- my.cols.var[floor(length(my.cols.var)/2)+1] <- "white"

    if(save.names){
        #cluster1.name.period <- cluster2.name.period <- cluster3.name.period <- cluster4.name.period <- c()
        
        #cluster1.name.period[p] <- cluster1.name
        #cluster2.name.period[p] <- cluster2.name
        #cluster3.name.period[p] <- cluster3.name
        #cluster4.name.period[p] <- cluster4.name
        
        #if(fields.name==rean.name) save(cluster1.name.period, cluster2.name.period, cluster3.name.period, cluster4.name.period, file=paste0(workdir,"/",fields.name,"_", var.name[var.num],"_",my.period[p],"_ClusterNames.RData"))
        #if(fields.name==forecast.name) save(cluster1.name.period, cluster2.name.period, cluster3.name.period, cluster4.name.period, file=paste0(workdir,"/",fields.name,"_", var.name[var.num],"_",my.period[p],"_leadmonth_",lead.month,"_ClusterNames.RData"))
        
        if(fields.name == rean.name) save(cluster1.name, cluster2.name, cluster3.name, cluster4.name,
                                          file=paste0(workdir,"/",fields.name,"_", my.period[p],"_ClusterNames.RData"))
        #if(fields.name == forecast.name) save(cluster1.name, cluster2.name, cluster3.name, cluster4.name, cluster.corr,
        #                                      file=paste0(workdir,"/",fields.name,"_", my.period[p],"_leadmonth_",lead.month,"_ClusterNames.RData"))
        
    } else { # in this case, we load the cluster names from the file already saved, if regimes come from a reanalysis:
        if(fields.name == rean.name) load(paste0(workdir,"/",fields.name,"_", my.period[p],"_ClusterNames.RData"))
        #if(fields.name == forecast.name && auto==F) load(paste0(workdir,"/",fields.name,"_", my.period[p],"_leadmonth_",lead.month,"_ClusterNames.RData"))

        if(var.num != var.num.orig) var.num <- var.num.orig # ripristinate original values of this script
        if(fields.name != fields.name.orig) fields.name <- fields.name.orig # ripristinate original values of this script

        #cluster1.name <- cluster1.name.period[p]
        #cluster2.name <- cluster2.name.period[p]
        #cluster3.name <- cluster3.name.period[p]
        #cluster4.name <- cluster4.name.period[p]
    }
    
    # assign to each cluster its regime:
    if(ordering == FALSE){
       cluster1 <- 1; cluster2 <- 2; cluster3 <- 3; cluster4 <- 4
    } else {
       cluster1 <- which(orden == cluster1.name)
       cluster2 <- which(orden == cluster2.name)
       cluster3 <- which(orden == cluster3.name)
       cluster4 <- which(orden == cluster4.name)
    }
    
    assign(paste0("map",cluster1), pslwr1mean)
    assign(paste0("map",cluster2), pslwr2mean)
    assign(paste0("map",cluster3), pslwr3mean)
    assign(paste0("map",cluster4), pslwr4mean)

    assign(paste0("fre",cluster1), wr1y)
    assign(paste0("fre",cluster2), wr2y)
    assign(paste0("fre",cluster3), wr3y)
    assign(paste0("fre",cluster4), wr4y)

    if(fields.name == rean.name){  
      assign(paste0("imp",cluster1), varPeriodAnom1mean)
      assign(paste0("imp",cluster2), varPeriodAnom2mean)
      assign(paste0("imp",cluster3), varPeriodAnom3mean)
      assign(paste0("imp",cluster4), varPeriodAnom4mean)

      assign(paste0("sig",cluster1), pvalue1)
      assign(paste0("sig",cluster2), pvalue2)
      assign(paste0("sig",cluster3), pvalue3)
      assign(paste0("sig",cluster4), pvalue4)
    }
    
    # Visualize the composition with the 3 graphs for all the 4 regimes: its pressure fields, its impact on var and its frequency series:
    if(!as.pdf && fields.name==rean.name) png(filename=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],".png"),width=3000,height=3700)
    if(!as.pdf && fields.name==forecast.name) png(filename=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_leadmonth_",lead.month,".png"),width=3000,height=3700)
   
    plot.new()

    # Sheet title:
    par(fig=c(0, 1, 0.94, 0.98), new=TRUE)
    
    if(fields.name == forecast.name) {forecast.title <- paste0(" startdate and ",lead.month," forecast month ")} else {forecast.title <- ""}
    mtext(paste0(fields.name, " Weather Regimes for ", my.period[p], forecast.title," (",year.start,"-",year.end,")"), cex=5.5, font=2)
            
    # Centroid maps:
    map.xpos <- 0
    map.width <- 0.46
    par(fig=c(map.xpos + 0.003, map.xpos + map.width - 0.003, 0.745, 0.925), new=TRUE)
    PlotEquiMap2(rescale(map1,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map1), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, xlabel.dist=1.5, contours.lty="F1FF1F")
    par(fig=c(map.xpos, map.xpos + map.width, 0.51, 0.69), new=TRUE)
    PlotEquiMap2(rescale(map2,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map2), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
    par(fig=c(map.xpos, map.xpos + map.width, 0.275, 0.455), new=TRUE)
    PlotEquiMap2(rescale(map3,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map3), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")
    par(fig=c(map.xpos, map.xpos + map.width, 0.04, 0.22), new=TRUE)
    PlotEquiMap2(rescale(map4,my.brks[1],tail(my.brks,1)), lon, lat, filled.continents=FALSE, brks=my.brks, cols=my.cols, sizetit=1.2, contours=t(map4), brks2=my.brks2, intxlon=10, intylat=10, drawleg=F, cex.lab=1.5, contours.lty="F1FF1F")

    # Title Centroid Maps:
    map.title.xpos <- 0.76
    map.title.width <- 0.2
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.728, 0.729), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.494, 0.495), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.260, 0.261), new=TRUE)
    mtext("year", cex=3)
    par(fig=c(map.title.xpos, map.title.xpos + map.title.width, 0.026, 0.027), new=TRUE)
    mtext("year", cex=3)

     # Title 1:
    title1.xpos <- 0.02
    title1.width <- 0.4
    par(fig=c(title1.xpos, title1.xpos + title1.width, 0.930, 0.935), new=TRUE)
    mtext(paste0(regime1.name,": ", psl.name, " Anomaly"), font=2, cex=4)
    par(fig=c(title1.xpos, title1.xpos + title1.width, 0.695, 0.700), new=TRUE)
    mtext(paste0(regime2.name,": ", psl.name, " Anomaly"), font=2, cex=4)
    par(fig=c(title1.xpos, title1.xpos + title1.width, 0.460, 0.465), new=TRUE)
    mtext(paste0(regime3.name,": ", psl.name, " Anomaly"), font=2, cex=4)
    par(fig=c(title1.xpos, title1.xpos + title1.width, 0.225, 0.230), new=TRUE)
    mtext(paste0(regime4.name,": ", psl.name, " Anomaly"), font=2, cex=4)
    
    # Impact maps:
    if(fields.name == rean.name){  
        impact.xpos <- 0.47
        impact.width <- 0.26    
        par(fig=c(impact.xpos, impact.xpos + impact.width, 0.745, 0.925), new=TRUE)
        PlotEquiMap2(rescale(imp1[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig1[,EU] < 0.05), cex.lab=1.5)
        par(fig=c(impact.xpos, impact.xpos + impact.width, 0.51, 0.69), new=TRUE)
        PlotEquiMap2(rescale(imp2[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig2[,EU] < 0.05), cex.lab=1.5)
        par(fig=c(impact.xpos, impact.xpos + impact.width, 0.275, 0.455), new=TRUE)
        PlotEquiMap2(rescale(imp3[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig3[,EU] < 0.05), cex.lab=1.5)
        par(fig=c(impact.xpos, impact.xpos + impact.width, 0.04, 0.22), new=TRUE)
        PlotEquiMap2(rescale(imp4[,EU],my.brks.var[1],tail(my.brks.var,1)), lon[EU], lat, filled.continents = FALSE, brks=my.brks.var, cols=my.cols.var, intxlon=10, intylat=10, drawleg=F, dots=t(sig4[,EU] < 0.05), cex.lab=1.5)   
    }
    
    # Frequency plots:
    barplot.xpos <- 0.75
    barplot.width <- 0.25
    freq.max=80

    if(fields.name == forecast.name){
        pos.years.present <- match(year.start:year.end, years)
        years.missing <- which(is.na(pos.years.present))
        fre1.NA <- fre2.NA <- fre3.NA <- fre4.NA <- c()

        k <- 0
        for(y in year.start:year.end) {
            if(y %in% (years.missing + year.start - 1)) {
                fre1.NA <- c(fre1.NA,NA)
                fre2.NA <- c(fre2.NA,NA)
                fre3.NA <- c(fre3.NA,NA)
                fre4.NA <- c(fre4.NA,NA)
                k=k+1
            } else {
                fre1.NA <- c(fre1.NA,fre1[y - year.start + 1 - k])
                fre2.NA <- c(fre2.NA,fre2[y - year.start + 1 - k])
                fre3.NA <- c(fre3.NA,fre3[y - year.start + 1 - k])
                fre4.NA <- c(fre4.NA,fre4[y - year.start + 1 - k])
            }    
        }
    } else { fre1.NA <- fre1; fre2.NA <- fre2; fre3.NA <- fre3; fre4.NA <- fre4 }
    
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width, 0.745, 0.915), new=TRUE)
    if(fields.name == rean.name) barplot.freq(100*fre1.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    if(fields.name == forecast.name) fre1.NA
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.510,0.680), new=TRUE)
    if(fields.name == rean.name) barplot.freq(100*fre2.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.275,0.445), new=TRUE)
    if(fields.name == rean.name) barplot.freq(100*fre3.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0)) 
    par(fig=c(barplot.xpos, barplot.xpos + barplot.width,0.040,0.210), new=TRUE)
    if(fields.name == rean.name) barplot.freq(100*fre4.NA, year.start, year.end, cex.y=2, cex.x=2, freq.max=freq.max, ylab="", mgp=c(3,1.5,0))

    # % on Frequency plots:
    symbol.xpos <- 0.735
    symbol.width <- 0.01
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.83, 0.84), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.60, 0.61), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.36, 0.37), new=TRUE)
    mtext("%", cex=3.3)
    par(fig=c(symbol.xpos, symbol.xpos + symbol.width, 0.13, 0.14), new=TRUE)
    mtext("%", cex=3.3)

    
    # Title 2:
    if(fields.name == rean.name){  
        title2.xpos <- 0.42
        title2.width <- 0.35
        par(fig=c(title2.xpos, title2.xpos + title2.width, 0.930, 0.935), new=TRUE)
        mtext(paste0(regime1.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
        par(fig=c(title2.xpos, title2.xpos + title2.width, 0.695, 0.700), new=TRUE)
        mtext(paste0(regime2.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
        par(fig=c(title2.xpos, title2.xpos + title2.width, 0.460, 0.465), new=TRUE)
        mtext(paste0(regime3.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
        par(fig=c(title2.xpos, title2.xpos + title2.width, 0.225, 0.230), new=TRUE)
        mtext(paste0(regime4.name, ": Impact on ", var.name.full[var.num]), font=2, cex=4)
    }
    
    # Title 3:
    title3.xpos <- 0.75
    title3.width <-0.25
    par(fig=c(title3.xpos, title3.xpos + title3.width, 0.930, 0.935), new=TRUE)
    mtext(paste0(regime1.name, ": Frequency (", round(100*mean(fre1),1), "%)"), font=2, cex=4)
    par(fig=c(title3.xpos, title3.xpos + title3.width, 0.695, 0.700), new=TRUE)
    mtext(paste0(regime2.name, ": Frequency (", round(100*mean(fre2),1), "%)"), font=2, cex=4)
    par(fig=c(title3.xpos, title3.xpos + title3.width, 0.460, 0.465), new=TRUE)
    mtext(paste0(regime3.name, ": Frequency (", round(100*mean(fre3),1), "%)"), font=2, cex=4)
    par(fig=c(title3.xpos, title3.xpos + title3.width, 0.225, 0.230), new=TRUE)
    mtext(paste0(regime4.name, ": Frequency (", round(100*mean(fre4),1), "%)"), font=2, cex=4)
    
    # Legend 1:
    legend1.xpos <- 0.01
    legend1.width <- 0.44
    legend1.cex <- 1.8
    my.subset <- match(values.to.plot, my.brks)    
    par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.719, 0.744), new=TRUE)  # syntax fig=c(xmin, xmax, ymin, ymax)
    ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
    if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
    par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.485, 0.508), new=TRUE)
    ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
    if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
    par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.250, 0.273), new=TRUE)
    ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
    if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}
    par(fig=c(legend1.xpos, legend1.xpos + legend1.width, 0.015, 0.038), new=TRUE)
    ColorBar3(my.brks, cols=my.cols, vert=FALSE, cex=legend1.cex, subset=my.subset)
    if(psl=="g500") {mtext(side=4," m", cex=2.5)} else {mtext(side=4," hPa", cex=legend1.cex)}

    # Legend 2:
    if(fields.name == rean.name){  
      legend2.xpos <- 0.48
      legend2.width <- 0.25
      legend2.cex <- 1.8
      my.subset2 <- match(values.to.plot2, my.brks.var)
      par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.719 + 0.001, 0.744), new=TRUE)
      ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
      mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)
      par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.485, 0.508), new=TRUE)
      ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
      mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
      par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.250, 0.273), new=TRUE)
      ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
      mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
      par(fig=c(legend2.xpos, legend2.xpos + legend2.width, 0.015, 0.038), new=TRUE)
      ColorBar3(my.brks.var, cols=my.cols.var, vert=FALSE, cex=legend2.cex, subset=my.subset2)
      mtext(side=4,paste0(" ",var.unit[var.num]), cex=legend2.cex)  
    }

    if(!as.pdf) dev.off() # for saving 4 png
    
} # close 'p' on 'period'

if(as.pdf) dev.off() # for saving a single pdf with all months/seasons






# impact map of the stronger WR:
if(fields.name == rean.name){
    
   var.num <- 2  # choose a variable (1:sfcWind, 2:tas)
   
   png(filename=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_most_influent.png"), width=500, height=600)
    
   plot.new()    
   #par(mfrow=c(4,3))
   col.regimes <- c("indianred1","cyan","khaki","lightpink")
    
   for(p in 1:12){
        load(file=paste0(workdir,"/",fields.name,"_",var.name[var.num],"_",my.period[p],"_mapdata.RData"))
        load(paste0(workdir,"/",fields.name,"_", my.period[p],"_ClusterNames.RData")) # they should not depend on var.name!!!

        cluster1 <- which(orden == cluster1.name.period[p]) # in future it will be == cluster1.name
        cluster2 <- which(orden == cluster2.name.period[p])
        cluster3 <- which(orden == cluster3.name.period[p])
        cluster4 <- which(orden == cluster4.name.period[p])

        assign(paste0("imp",cluster1), varPeriodAnom1mean)
        assign(paste0("imp",cluster2), varPeriodAnom2mean)
        assign(paste0("imp",cluster3), varPeriodAnom3mean)
        assign(paste0("imp",cluster4), varPeriodAnom4mean)
        
        imp.all <- imp1
        for(i in 1:dim(imp1)[1]){
            for(j in 1:dim(imp1)[2]){
                if(abs(imp1[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 1.5
                if(abs(imp2[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 2.5
                if(abs(imp3[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 3.5
                if(abs(imp4[i,j]) >= max(abs(imp1[i,j]), abs(imp2[i,j]), abs(imp3[i,j]), abs(imp4[i,j]))) imp.all[i,j] <- 4.5
            }
        }

        if(p<=3) yMod <- 0.7
        if(p>=4 && p<=6) yMod <- 0.5
        if(p>=7 && p<=9) yMod <- 0.3
        if(p>=10) yMod <- 0.1
        if(p==1 || p==4 || p==7 || p==10) xMod <- 0.05
        if(p==2 || p==5 || p==8 || p==11) xMod <- 0.35
        if(p==3 || p==6 || p==9 || p==12) xMod <- 0.65
        
        # impact map:
        par(fig=c(xMod, xMod + 0.3, yMod, yMod + 0.17), new=TRUE)
        PlotEquiMap(imp.all[,EU], lon[EU], lat, filled.continents = FALSE, brks=1:5, cols=col.regimes, axelab=F, drawleg=F)
        
        # title map:
        par(fig=c(xMod, xMod + 0.3, yMod + 0.162, yMod + 0.172), new=TRUE)
        mtext(my.period[p], font=2, cex=.9)
        
    } # close 'p' on 'period'
    
    par(fig=c(0.1,0.9, 0, 0.11), new=TRUE)  
    ColorBar2(1:5, cols=col.regimes, vert=FALSE, my.ticks=c(1,2,3,4), my.labels=orden)
    
    par(fig=c(0.1,0.9, 0.9, 0.95), new=TRUE)
    mtext(paste0("Most influent WR on ",var.name[var.num]), font=2, cex=1.5)
    
    dev.off()    
}  
    
