5sdrm(list=ls())

library(s2dverification)
library(multiApply)
library(abind)
library(future) # for availableCores() function
source('/esarchive/scratch/ncortesi/scripts/Rfunctions.R')

## folder with the weekly clustering (one .RData for each week of the year):
work.dir <- "/esarchive/scratch/ncortesi/Regimes/87_WRs_subseasonal/weekly_1979-2017_starting_from_first_of_January_of_2014_ERA-Interim"
##work.dir <- "/esarchive/scratch/ncortesi/Regimes/87_WRs_subseasonal/weekly_1979-2017_starting_from_first_of_January_of_2018_ERA-Interim"

##work.dir <- "/esarchive/scratch/ncortesi/Regimes/90_WRs_winter_and_summer"

## number of chunks (start dates in this case):
n.sdates <- 52

## number of regimes:
n.clusters <- 4

## Load the .Rdata with the results for each chunk:

## load the first startdate just to get the dimensions of the arrays to load:
## (in the .RData there are the following variables: sdate, WR.seq.perc, WR.seq.for, WR.seq.rean, yr1, yr2, n.yrs.hind, n.members, work.dir)
load(paste0(work.dir, "/Assign_table_startdate_1.Rdata"))

## arrays where we want to store the full results of all chunks:
WR.seq.perc.full <- array(NA, c(n.sdates, dim(WR.seq.coinc.perc)))
WR.seq.rean.full <- array(NA, c(n.sdates, dim(WR.seq.rean)))
WR.seq.for.full <- array(NA, c(n.sdates, dim(WR.seq.for)))
WR.sp.cor.full <- array(NA, c(n.sdates, dim(WR.sp.cor)))
if(exists("WR.sp.cor.week")) WR.sp.cor.week.full <- array(NA, c(n.sdates, dim(WR.sp.cor.week)))

for(sdate in 1:n.sdates){
    load(paste0(work.dir, "/Assign_table_startdate_", sdate,".Rdata"))
    
    WR.seq.perc.full[sdate,] <- WR.seq.coinc.perc
    WR.seq.rean.full[sdate,,] <- WR.seq.rean
    WR.seq.for.full[sdate,,,,] <- WR.seq.for
    WR.sp.cor.full[sdate,,] <- WR.sp.cor
    ##WR.sp.cor.week.full[sdate,,] <- WR.sp.cor.week
}


## measure WR frequencies and correlations:

## for each WR and forecast WEEK, measure the frequencies of occurrence of predicted and observed WR patterns:
days.we <- list(5:11, 12:18, 19:25, 26:32)  ## define lead weeks
n.for.weeks <- length(days.we) ## number of forecast weeks
 
## frequency of each observed WR (in %) for each year:
fr.wr.obs <- array(NA, c(n.clusters, n.sdates, n.yrs.hind, n.for.weeks))

## frequency of each forecasted WR (in %) for each year:
fr.wr.for <- array(NA, c(n.clusters, n.sdates, n.yrs.hind, n.for.weeks))
                     
for(wr in 1:n.clusters) {
    for(sd in 1:n.sdates){
        for(yr in 1:n.yrs.hind){
            for(we in 1:n.for.weeks){
                fr.wr.obs[wr, sd, yr, we] <- length(which(WR.seq.rean.full[sd, yr, days.we[[we]]] == wr)) / length(days.we[[we]]) 
                fr.wr.for[wr, sd, yr, we] <- length(which(WR.seq.for.full[sd, 1,, yr, days.we[[we]]] == wr)) / ( n.members * length(days.we[[we]]) )                
            }
        }
    }
}

## measure frequency temporary correlations:
WR.temp.cor <- array(NA, c(n.clusters, n.sdates, n.for.weeks))

for(wr in 1:n.clusters) {
    for(sd in 1:n.sdates){
        for(we in 1:length(days.we)){
            WR.temp.cor[wr, sd, we] <- cor(fr.wr.obs[wr, sd,, we], fr.wr.for[wr, sd,, we])
        }
    }
}

## measure temporal correlations between obs and for regime frequencies concatenating 5 consecutive start dates together:
fr.wr.obs.5sd <- fr.wr.for.5sd <- array(NA, c(n.clusters, n.sdates, n.yrs.hind * 5, n.for.weeks))
WR.temp.cor.5sd <- array(NA, c(n.clusters, n.sdates, n.for.weeks))

for(wr in 1:n.clusters) {
    for(sd in 1:n.sdates){
        for(yr in 1:n.yrs.hind){
            for(we in 1:n.for.weeks){
                if(sd >= 3 && sd <= (n.sdates-2)) {sd1 <- sd-2; sd2 <- sd-1; sd3 <- sd; sd4 <- sd+1; sd5 <- sd+2}
                if(sd == 1) {sd1 <- n.sdates-1; sd2 <- n.sdates; sd3 <- 1; sd4 <- 2; sd5 <- 3}
                if(sd == 2) {sd1 <- n.sdates; sd2 <- 1; sd3 <- 2; sd4 <- 3; sd5 <- 4 }
                if(sd == (n.sdates-1)) {sd1 <- n.sdates - 3; sd2 <- n.sdates - 2; sd3 <- n.sdates-1; sd4 <- n.sdates; sd5 <- 1}
                if(sd == n.sdates) {sd1 <- n.sdates-2; sd2 <- n.sdates-1; sd3 <- sd; sd4 <- 1; sd5 <- 2}
                
                ## concatenate the yearly freq. time series of the 5 start dates in a single time series:
                fr.wr.obs.5sd[wr, sd,, we] <- c(fr.wr.obs[wr, sd1,, we], fr.wr.obs[wr, sd2,, we], fr.wr.obs[wr, sd3,, we], fr.wr.obs[wr, sd4,, we], fr.wr.obs[wr, sd5,, we])
                fr.wr.for.5sd[wr, sd,, we] <- c(fr.wr.for[wr, sd1,, we], fr.wr.for[wr, sd2,, we], fr.wr.for[wr, sd3,, we], fr.wr.for[wr, sd4,, we], fr.wr.for[wr, sd5,, we])
                
            }
        }
    }
}

for(wr in 1:n.clusters) {
    for(sd in 1:n.sdates){
        for(we in 1:length(days.we)){
            WR.temp.cor.5sd[wr, sd, we] <- cor(fr.wr.obs.5sd[wr, sd,, we], fr.wr.for.5sd[wr, sd,, we] )
        }
    }
}

## measure frequency bias:
WR.fr.bias <- array(NA, c(n.clusters, n.sdates, n.for.weeks))

for(wr in 1:n.clusters) {
    for(sd in 1:n.sdates){
        for(we in 1:length(days.we)){
            WR.fr.bias[wr, sd, we] <- mean(fr.wr.for[wr, sd,, we]) - mean(fr.wr.obs[wr, sd,, we])
        }
    }
}

## average the daily 'WR.seq.perc.full' in the four forecasts weeks:
WR.seq.perc.full.weekly <- array(NA, c(n.sdates, n.for.weeks))
                                 
for(sd in 1:n.sdates){
    for(we in 1:length(days.we)){
        WR.seq.perc.full.weekly[sd, we] <- mean(WR.seq.perc.full[sd, days.we[[we]]])
    }
}

## measure weekly spatial correlations:
WR.weekly.sp.cor <-  array(NA, c(n.clusters, n.sdates, n.for.weeks))
for(wr in 1:n.clusters) WR.weekly.sp.cor[wr,,1] <- rowMeans(WR.sp.cor.full[,wr, days.we[[1]]])
for(wr in 1:n.clusters) WR.weekly.sp.cor[wr,,2] <- rowMeans(WR.sp.cor.full[,wr, days.we[[2]]])
for(wr in 1:n.clusters) WR.weekly.sp.cor[wr,,3] <- rowMeans(WR.sp.cor.full[,wr, days.we[[3]]])
for(wr in 1:n.clusters) WR.weekly.sp.cor[wr,,4] <- rowMeans(WR.sp.cor.full[,wr, days.we[[4]]])

## measure persistence and its bias:
## note that due to the short length of the period (1 week), persistence is underestimated!
## however, underestimation is present both in reanalysis and model data, so the two underestimations cancel each other when
## the persistence bias in measured as the difference between them.
WR.pers.obs <- WR.pers.for <- WR.pers.bias <- array(NA, c(n.clusters, n.sdates, n.for.weeks))

## observed persistence:
for(sd in 1:n.sdates){
    for(wr in 1:n.clusters) {
        for(we in 1:n.for.weeks){
            WR.pers.obs.year <- c() ## observed persistance for each year
            for(yr in 1:n.yrs.hind) {
                if(length(which(WR.seq.rean.full[sd, yr, days.we[[we]]] == wr)) > 0){                    
                    pp <- c() ## vector of seven numbers that converts a weekly WR sequence (i.e: 3334331) in the weekly pseudo-persistence serie 1230120
                    if(WR.seq.rean.full[sd, yr, days.we[[we]]][1] == wr) pp[1] <- 1 else pp[1] <- 0
                    for(dd in 2:7){
                        if(WR.seq.rean.full[sd, yr, days.we[[we]]][dd] == wr & WR.seq.rean.full[sd, yr, days.we[[we]]][dd] == WR.seq.rean.full[sd, yr, days.we[[we]]][dd - 1]){
                            pp[dd] <- pp[dd - 1] + 1
                        } else {
                            pp[dd] <- 0
                        }
                    }

                    qq <- pp ## vector that converts pp in the vector qq=3330220:
                    for(dd in 6:1){
                        if(pp[dd] != 0 & pp[dd] < pp[dd+1]) qq[dd] <- qq[dd + 1] 
                    }
                    
                    num.seq <- 0 ## total number of different wr sequences inside the week (2 in the above example)
                    for(l.seq in 1:7) num.seq <- num.seq + length(which(qq == l.seq)) / l.seq
                    
                    ## sum of the durations (in days) of all wr sequences inside the week (5 in the above example)
                    dur.seq <- length(which(qq != 0))
                    
                    WR.pers.obs.year[yr] <- dur.seq / num.seq ## persistence of a single year
                } else {
                    WR.pers.obs.year[yr] <- NA
                }
            }
        
            WR.pers.obs[wr, sd, we] <- mean(WR.pers.obs.year, na.rm=TRUE)
        }
    }
}

## simulated persistence:
for(sd in 1:n.sdates){
    for(wr in 1:n.clusters) {
        for(we in 1:n.for.weeks){
            WR.pers.for.year <- c() ## forecasted persistance for all members of each year
            for(yr in 1:n.yrs.hind) {
                WR.pers.for.year.memb <- c() ## forecasted persistence for each member and year
                for(mem in 1:n.members){
                    if(length(which(WR.seq.for.full[sd, 1, mem, yr, days.we[[we]]][1] == wr)) > 0){
                        pp <- c() ## vector of seven numbers that converts a weekly WR sequence (i.e: 3334331) in the weekly pseudo-persistence serie 1230120
                        if(WR.seq.for.full[sd, 1, mem, yr, days.we[[we]]][1] == wr) pp[1] <- 1 else pp[1] <- 0
                        for(dd in 2:7){
                            if(WR.seq.for.full[sd, 1, mem, yr, days.we[[we]]][dd] == wr & WR.seq.for.full[sd, 1, mem, yr, days.we[[we]]][dd] == WR.seq.for.full[sd, 1, mem, yr, days.we[[we]]][dd - 1]) pp[dd] <- pp[dd-1] + 1 else pp[dd] <- 0
                        }
                    
                        qq <- pp ## vector that converts pp in the vector qq=3330220:
                        for(dd in 6:1){
                            if(pp[dd] != 0 & pp[dd] < pp[dd+1]) qq[dd] <- qq[dd+1] 
                        }
                        num.seq <- 0 ## total number of different wr sequences inside the week (2 in the above example)
                        for(l.seq in 1:7) num.seq <- num.seq + length(which(qq == l.seq)) / l.seq
               
                        ## sum of the durations (in days) of all wr sequences inside the week (5 in the above example)
                        dur.seq <- length(which(qq != 0))
                
                        WR.pers.for.year.memb[mem] <- dur.seq / num.seq ## persistence of a single year and member
                    } else {
                        WR.pers.for.year.memb[mem] <- NA
                    }
                }
                WR.pers.for.year[yr] <- mean(WR.pers.for.year.memb, na.rm = TRUE)
            }
            
            WR.pers.for[wr, sd, we] <- mean(WR.pers.for.year, na.rm = TRUE)
        }
    }
}

WR.pers.bias <- WR.pers.for - WR.pers.obs

## measure transition probabilities and its bias:
WR.trans.obs <- WR.trans.for <- WR.trans.bias <- array(0, c(n.sdates, n.for.weeks, n.clusters, n.clusters))

## observed transition prob:
for(sd in 1:n.sdates){
    for(we in 1:n.for.weeks){
        for(wr1 in 1:n.clusters) {
            for(wr2 in 1:n.clusters) {
                for(yr in 1:n.yrs.hind){
                    for(dd in 1:6){
                        if(WR.seq.rean.full[sd, yr, days.we[[we]][dd]] == wr1 & WR.seq.rean.full[sd, yr, days.we[[we]][dd+1]] == wr2) {
                            WR.trans.obs[sd, we, wr1, wr2] <- WR.trans.obs[sd, we, wr1, wr2] + 1
                        }
                    }
                }
            }

            num.trans.days <- 0 ## total number of transition days for a given start date and forecast week and wr
            for(wr2 in 1:n.clusters) if(wr2 != wr1) num.trans.days <- num.trans.days + WR.trans.obs[sd, we, wr1, wr2]
            
            ## normalize WR.trans.obs for the total number of transition days of wr1 (which doesn't include days with no regime transition):    
            WR.trans.obs[sd, we, wr1,] <- WR.trans.obs[sd, we, wr1,] / num.trans.days

            ## place NA for the tansition to the same regime (as the transition probability is defined only for different pair of regimes):
            WR.trans.obs[sd, we, wr1, wr1] <- NA

        }    
    }
}

## convert the transition probability in a %:
WR.trans.obs <- WR.trans.obs * 100

## simulated transition prob:
for(sd in 1:n.sdates){
    for(we in 1:n.for.weeks){
        for(wr1 in 1:n.clusters) {
            for(wr2 in 1:n.clusters) {
                for(yr in 1:n.yrs.hind){
                    for(mem in 1:n.members){
                        for(dd in 1:6){
                            if(WR.seq.for.full[sd, 1, mem, yr, days.we[[we]][dd]] == wr1 & WR.seq.for.full[sd, 1, mem, yr, days.we[[we]][dd+1]] == wr2) {
                                WR.trans.for[sd, we, wr1, wr2] <- WR.trans.for[sd, we, wr1, wr2] + 1
                            }
                        }
                    }
                }
            }

            num.trans.days <- 0 ## total number of transition days for a given start date and forecast week and wr
            for(wr2 in 1:n.clusters) if(wr2 != wr1) num.trans.days <- num.trans.days + WR.trans.for[sd, we, wr1, wr2]
            
            ## normalize WR.trans.obs for the total number of transition days of wr1 (which doesn't include days with no regime transition):    
            WR.trans.for[sd, we, wr1,] <- WR.trans.for[sd, we, wr1,] / num.trans.days

            ## place NA for the tansition to the same regime (as the transition probability is defined only for different pair of regimes):
            WR.trans.for[sd, we, wr1, wr1] <- NA
        }
    }
}

## convert the transition probability in a %:
WR.trans.for <- WR.trans.for * 100

WR.trans.bias <- WR.trans.for - WR.trans.obs

## measure all indicators over all start dates of the same season:
##
## note that for forecasts of 2014, the start dates begins from the 2 of January, so winter start dates (from Oct to March) are numbered from 1 to 13 and from 40 to 52,
## while summer start dates (from apr to sep) are numbered from 14 to 39.
winter.sdates <- c(1:13, 40:52)
summer.sdates <- c(14:39)
        
## measure temporary correlations between frequency series all winter or summer start dates together:
mean.fr.winter.obs <- mean.fr.summer.obs <- mean.fr.winter.for <- mean.fr.summer.for <- array(0, c(n.clusters, n.yrs.hind, n.for.weeks))
mean.fr.winter.obs.5sd <- mean.fr.summer.obs.5sd <- mean.fr.winter.for.5sd <- mean.fr.summer.for.5sd <- array(0, c(n.clusters, n.yrs.hind*5, n.for.weeks))

for(wr in 1:n.clusters) {
    for(we in 1:length(days.we)){
        for(sd in winter.sdates)  mean.fr.winter.obs[wr,,we] <- mean.fr.winter.obs[wr,,we] + fr.wr.obs[wr, sd,, we]
        for(sd in summer.sdates)  mean.fr.summer.obs[wr,,we] <- mean.fr.summer.obs[wr,,we] + fr.wr.obs[wr, sd,, we]
        
        for(sd in winter.sdates)  mean.fr.winter.for[wr,,we] <- mean.fr.winter.for[wr,,we] + fr.wr.for[wr, sd,, we]
        for(sd in summer.sdates)  mean.fr.summer.for[wr,,we] <- mean.fr.summer.for[wr,,we] + fr.wr.for[wr, sd,, we]

        for(sd in winter.sdates)  mean.fr.winter.obs.5sd[wr,,we] <- mean.fr.winter.obs.5sd[wr,,we] + fr.wr.obs.5sd[wr, sd,, we]
        for(sd in summer.sdates)  mean.fr.summer.obs.5sd[wr,,we] <- mean.fr.summer.obs.5sd[wr,,we] + fr.wr.obs.5sd[wr, sd,, we]
        
        for(sd in winter.sdates)  mean.fr.winter.for.5sd[wr,,we] <- mean.fr.winter.for.5sd[wr,,we] + fr.wr.for.5sd[wr, sd,, we]
        for(sd in summer.sdates)  mean.fr.summer.for.5sd[wr,,we] <- mean.fr.summer.for.5sd[wr,,we] + fr.wr.for.5sd[wr, sd,, we]
    }
}

mean.fr.winter.obs <- mean.fr.winter.obs / length(winter.sdates)
mean.fr.summer.obs <- mean.fr.summer.obs / length(summer.sdates)

mean.fr.winter.obs.5sd <- mean.fr.winter.obs.5sd / length(winter.sdates)
mean.fr.summer.obs.5sd <- mean.fr.summer.obs.5sd / length(summer.sdates)

cor.fr.season <- cor.fr.season.5sd <- array(NA, c(n.clusters, 2, n.for.weeks))

for(wr in 1:n.clusters) {
    for(we in 1:length(days.we)){
        cor.fr.season[wr,1,we] <- cor(mean.fr.winter.obs[wr,,we], mean.fr.winter.for[wr,,we])
        cor.fr.season[wr,2,we] <- cor(mean.fr.summer.obs[wr,,we], mean.fr.summer.for[wr,,we])
        cor.fr.season.5sd[wr,1,we] <- cor(mean.fr.winter.obs.5sd[wr,,we], mean.fr.winter.for.5sd[wr,,we])
        cor.fr.season.5sd[wr,2,we] <- cor(mean.fr.summer.obs.5sd[wr,,we], mean.fr.summer.for.5sd[wr,,we])
    }
}

## measure seasonal frequency bias:
WR.fr.bias.season <- array(NA, c(n.clusters, 2, n.for.weeks))
WR.fr.bias.season[,1,] <- apply(WR.fr.bias[, winter.sdates,], c(1,3), mean, na.rm=TRUE)
WR.fr.bias.season[,2,] <- apply(WR.fr.bias[, summer.sdates,], c(1,3), mean, na.rm=TRUE)

## measure daily coincidents regimes for each season:
WR.seq.perc.full.season <- array(NA, c(2, 32))
WR.seq.perc.full.season[1,] <- apply(WR.seq.perc.full[winter.sdates,], 2, mean, na.rm=T)
WR.seq.perc.full.season[2,] <- apply(WR.seq.perc.full[summer.sdates,], 2, mean, na.rm=T)



##
## Plot Figure 1 with % of coincident regimes
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
my.brks <- c(0,30,40,50,60,70,80,90,100)

## ColorTable <- function(matrix, cols, brks, fileout = NULL, wifth = 8, height = 5, size_units = "in", res = 100){
##     if (!is.null(fileout)) {
##         saveToFile(fileout)
##     } else {
##         dev.new(units = size_units, res = res, width = width, height = height)
##     }
## }

my.file <- paste0(work.dir, "/Figure1_coincident_regimes_for_forecast_day.png")
png(file=my.file, width=530, height=700)  
plot.new()

##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
par(fig = c(0, 0.88, 0, 1))
plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 30.2), ann = F, bty="n") ## to remove black border

## Add axes labels:
mtext(side = 1, text = "                   Forecast day", line = 3, cex = 1.2, font = 3)
mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

## Add figure title:
my.title = "Coincident regimes (in %) between ECMWF-MPS and ERA-Interim\nwith the assign method (1979-2017)"
mtext(side = 3, text = my.title, cex = 1.3)

## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
axis(1, at=seq(0,31), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

## Plot x-axis labels rotated of 45 degrees at default tick marks:
##labels <- paste0(" ",1:31)
text(0:31, par("usr")[3] - 1.55, srt = 0, adj = 1, labels = 1:32, xpd = TRUE, cex=.8) 

## Draw subtitle:
##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

## Plot y-axis:
axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

## create an array similar to array.pers but with colors instead of frequencies:                
n.cols <- length(my.cols)
array.colors <- array(my.cols[n.cols], c(52,32))
for(int in (n.cols-1):1) array.colors[WR.seq.perc.full < my.brks[int+1]] <- my.cols[int]

##set to gray the last column:
##array.colors[,32] <- "#ece7f2"

## fill with colors the cells in the figure:
for(p in 1:52){ for(l in 0:(32-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

## add color legend:
par(fig = c(0.83, 1, 0.30, 0.75), new=TRUE)
ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
dev.off()    


##
## Plot Figure 2 with daily Spatial correlations:
##

## my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
## my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
## my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#fcfbfd','#efedf5','#dadaeb','#bcbddc','#9e9ac8','#807dba','#6a51a3','#4a1486')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#034e7b')
my.cols <- c('#fff5f0','#fee0d2','#fcbba1','#fc9272','#fb6a4a','#ef3b2c','#cb181d','#99000d')

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure2_regime_", wr,".png")
    png(file=my.file, width=530, height=700)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0, 0.88, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 30.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "               Forecast day", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = paste0("Spatial correlation between ECMWF-MPS regime ",wr,"\nand ERA-Interim's (1979-2017)")
    mtext(side = 3, text = my.title, cex = 1.3)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0,31), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    text(0:31, par("usr")[3] - 1.55, srt = 0, adj = 1, labels = 1:32, xpd = TRUE, cex=.8) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52,32))
    for(int in (n.cols-1):1) array.colors[WR.sp.cor.full[, wr,] < my.brks[int+1]] <- my.cols[int]

    ##set to black the NAs:
    ss <- which(is.na(WR.sp.cor.full[,wr,]))
    if(length(ss) > 0)  array.colors[ss] <- "black"

    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(32-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.83, 1, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    

}



##
## Plot Figure 3 with Temporal freq.correlations:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure3_regime_", wr,".png")
    png(file=my.file, width=530, height=700)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = paste0("Temporal correlation between ECMWF-MPS regime ", wr,"\nand ERA-Interim's (1979-2017)")
    mtext(side = 3, text = my.title, cex = 1.3)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52, 4))
    for(int in (n.cols-1):1) array.colors[WR.temp.cor[wr,,] < my.brks[int+1]] <- my.cols[int]

    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1)
    
    dev.off()    

}


##
## Plot Figure 4 with Frequency bias for each day:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(-0.25, -0.15, -0.10, -0.05, 0, 0.05, 0.10, 0.15, 0.25)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure4_regime_", wr,".png")
    png(file=my.file, width=530, height=700)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = "Frequency bias between ECMWF-MPS regimes\nand ERA-Interim's (1979-2017)"
    mtext(side = 3, text = my.title, cex = 1.3)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

    ## create an array similar to array.pers but with colors instead of frequencies:
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52, 4))
    for(int in (n.cols-1):1) array.colors[WR.fr.bias[wr,,] < my.brks[int+1]] <- my.cols[int]

    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    

}



##
## Plot Figure 5 with Weekly spatial correlations:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(0, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure5_regime_", wr,".png")
    png(file=my.file, width=530, height=700)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = paste0("Temporal correlation between ECMWF-MPS regime ",wr,"\nand ERA-Interim's (1979-2017)")
    mtext(side = 3, text = my.title, cex = 1.3)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52, 4))
    for(int in (n.cols-1):1) array.colors[WR.weekly.sp.cor[wr,,] < my.brks[int+1]] <- my.cols[int]

    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    

}

##
## Plot Figure 6 with Frequency bias for each season and forecast week:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(-0.25, -0.15, -0.10, -0.05, 0, 0.05, 0.10, 0.15, 0.25)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure6_regime_weekly_bias", wr,".png")
    png(file=my.file, width=530, height=300)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0.2, 0.8))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 2.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 4, cex = 1.2, font = 3)
    ## mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = "Frequency bias between ECMWF-MPS regimes\nand ERA-Interim's (1979-2017)"
    mtext(side = 3, text = my.title, cex = 1.3, line = 4)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 0.5, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=1) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=2:1, las=2, labels=c("Winter","Summer"), cex.axis=1.5)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(2, 4))
    for(int in (n.cols-1):1) array.colors[WR.fr.bias.season[wr,,] < my.brks[int+1]] <- my.cols[int]

    ## fill with colors the cells in the figure:
    for(p in 1:2){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+3-p, 0.5+3-p, 0.5+3-p, -0.5+3-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.67, 0.84, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    

}



##
## Plot Figure 7 with % of coincident regimes for season
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
my.brks <- c(0,30,40,50,60,70,80,90,100)

## ColorTable <- function(matrix, cols, brks, fileout = NULL, wifth = 8, height = 5, size_units = "in", res = 100){
##     if (!is.null(fileout)) {
##         saveToFile(fileout)
##     } else {
##         dev.new(units = size_units, res = res, width = width, height = height)
##     }
## }

my.file <- paste0(work.dir, "/Figure7_coincident_regimes_for_season.png")
png(file=my.file, width=530, height=300)  
plot.new()

##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
par(fig = c(0, 0.88, 0.2, 0.8))
plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 2.04), xlim = c(-0.23, 30.2), ann = F, bty="n") ## to remove black border

## Add axes labels:
mtext(side = 1, text = "                   Forecast day", line = 3, cex = 1.2, font = 3)
mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

## Add figure title:
my.title = "Coincident regimes (in %) between ECMWF-MPS and ERA-Interim\nwith the assign method (1979-2017)"
mtext(side = 3, text = my.title, cex = 1.3, line = 3)

## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
axis(1, at=seq(0,31), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

## Plot x-axis labels rotated of 45 degrees at default tick marks:
##labels <- paste0(" ",1:31)
text(0:31, par("usr")[3] - 0.55, srt = 0, adj = 1, labels = 1:32, xpd = TRUE, cex=.8) 

## Draw subtitle:
##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

## Plot y-axis:
axis(2, at=2:1, las=2, labels=1:2, cex.axis=.8)

## create an array similar to array.pers but with colors instead of frequencies:                
n.cols <- length(my.cols)
array.colors <- array(my.cols[n.cols], c(2,32))
for(int in (n.cols-1):1) array.colors[WR.seq.perc.full.season < my.brks[int+1]] <- my.cols[int]

##set to gray the last column:
##array.colors[,32] <- "#ece7f2"

## fill with colors the cells in the figure:
for(p in 1:2){ for(l in 0:(32-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+3-p, 0.5+3-p, 0.5+3-p, -0.5+3-p), col=array.colors[p,1+l], border="black") }}

## add color legend:
par(fig = c(0.83, 1, 0.30, 0.75), new=TRUE)
ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)

dev.off()    


##
## Plot Figure 8 with Temporal freq.correlations for season:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure8_regime_temp_corr_for_season_regime_", wr,".png")
    png(file=my.file, width=530, height=300)  
    plot.new()

    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0.2, 0.8))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 2.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

    ## Add figure title:
    my.title = "Temporal correlation between ECMWF-MPS regimes\nand ERA-Interim's (1979-2017)"
    mtext(side = 3, text = my.title, cex = 1.3)

    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 

    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

    ## Plot y-axis:
    axis(2, at=2:1, las=2, labels=1:2, cex.axis=.8)

    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(2, 4))
    for(int in (n.cols-1):1) array.colors[cor.fr.season[wr,,] < my.brks[int+1]] <- my.cols[int]

    ## fill with colors the cells in the figure:
    for(p in 1:2){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+3-p, 0.5+3-p, 0.5+3-p, -0.5+3-p), col=array.colors[p,1+l], border="black") }}

    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    

}

##
## Plot Figure 9 persistence bias for each regime, start date and forecast week:
##

my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

my.brks <- c(-2, -1.5, -1, -0.5, 0, 0.5, 1, 1.5, 2)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure9_persistence_bias_of_regime_", wr,"_for_start_date.png")
    png(file=my.file, width=530, height=700)  
    plot.new()
    
    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border
    
    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)
    
    ## Add figure title:
    my.title = paste0("Persistence bias between ECMWF-MPS regime ", wr,"\nand ERA-Interim's (1979-2017)")
    mtext(side = 3, text = my.title, cex = 1.3)
    
    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 
    
    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 
    
    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)
    
    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)
    
    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52, 4))
    for(int in (n.cols-1):1) array.colors[WR.pers.bias[wr,,] < my.brks[int+1]] <- my.cols[int]
    
    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}
    
    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
    dev.off()    
    
}

##
## Plot Figure 10 transition probabilities for each regime, start date and forecast week:
##

my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

my.brks <- c(-100, -20, -10, -5, 0, 5, 10, 20, 100)

for(wr1 in 1:n.clusters){
    for(wr2 in 1:n.clusters){
        if(wr2 != wr1){
            my.file <- paste0(work.dir, "/Figure10_transition_prob_bias_between_regime_", wr1,"_and_", wr2, "_for_start_date.png")
            png(file=my.file, width=530, height=700)  
            plot.new()
    
            ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
            par(fig = c(0.3, 0.63, 0, 1))
            plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border
    
            ## Add axes labels:
            mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
            mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)
    
            ## Add figure title:
            my.title = paste0("Transition prob. bias between ECMWF-MPS regimes ", wr1," and ", wr2, "\nand ERA-Interim's (1979-2017)")
            mtext(side = 3, text = my.title, cex = 1.3)
    
            ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
            axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 
    
            ## Plot x-axis labels rotated of 45 degrees at default tick marks:
            ##labels <- paste0(" ",1:31)
            xlabel <- c("5-11", "12-18","19-25","26-32")
            text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 
    
            ## Draw subtitle:
            ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)
    
            ## Plot y-axis:
            axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)
    
            ## create an array similar to array.pers but with colors instead of frequencies:                
            n.cols <- length(my.cols)
            array.colors <- array(my.cols[n.cols], c(52, 4))
            for(int in (n.cols-1):1) array.colors[WR.trans.bias[,,wr1,wr2] < my.brks[int+1]] <- my.cols[int]
            
            ## fill with colors the cells in the figure:
            for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}
    
            ## add color legend:
            par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
            ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1, triangle_ends=c(FALSE,FALSE)) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
    
            dev.off()   
        }
    }
}


##
## Plot Figure 11 temporal freq.correlations of regime frequencies for 5 consecutive start dates:
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- rev(c('#b2182b','#d6604d','#f4a582','#fddbc7','#d1e5f0','#92c5de','#4393c3','#2166ac'))

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1)

for(wr in 1:n.clusters){
    my.file <- paste0(work.dir, "/Figure11_temporal_correlations_frequency_regime_", wr,"_for_5_start_dates.png")
    png(file=my.file, width=530, height=700)  
    plot.new()
    
    ##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
    par(fig = c(0.3, 0.63, 0, 1))
    plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border
    
    ## Add axes labels:
    mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
    mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)
    
    ## Add figure title:
    my.title = paste0("Temporal correlation between ECMWF-MPS regime ", wr, "\nand ERA-Interim's concatenating 5 start dates (1979-2017)")
    mtext(side = 3, text = my.title, cex = 1.3)
    
    ## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
    axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0))
   
    ## Plot x-axis labels rotated of 45 degrees at default tick marks:
    ##labels <- paste0(" ",1:31)
    xlabel <- c("5-11", "12-18","19-25","26-32")
    text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 
    
    ## Draw subtitle:
    ##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)
    
    ## Plot y-axis:
    axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)
    
    ## create an array similar to array.pers but with colors instead of frequencies:                
    n.cols <- length(my.cols)
    array.colors <- array(my.cols[n.cols], c(52, 4))
    for(int in (n.cols-1):1) array.colors[WR.temp.cor.5sd[wr,,] < my.brks[int+1]] <- my.cols[int]
    
    ## fill with colors the cells in the figure:
    for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}
    
    ## add color legend:
    par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
    ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1) #my.ticks=-0.5 + 1:length(my.brks.var2), my.labels=my.brks.var2) subset=my.subset2)
   
    dev.off()
    
}


##
## Plot Figure 12 with % of Coincident regimes for start date and forecast week (like Figre 1 but for forecast weeks instead of days):
##

##my.cols <- c('white','#fef0d9','#fdd49e','#fdbb84','#fc8d59','#e34a33','#b30000', '#7f0000')
##my.cols <- c('#fff7fb','#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
##my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')
my.cols <- c('#ece7f2','#d0d1e6','#a6bddb','#74a9cf','#3690c0','#0570b0','#045a8d','#023858')

##my.brks <- c(-0.05, 0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.30, 1)
##my.brks <- c(0,20,30,40,50,60,70,80,90,100)
##my.brks <- c(0,30,40,50,60,70,80,90,100)
my.brks <- c(0, 30, 40, 50, 60, 70, 80, 90, 100)

my.file <- paste0(work.dir, "/Figure12_coincident_regimes_for_forecast_week.png")
png(file=my.file, width=530, height=700)  
plot.new()

##par(mar = c(0, 0, 2, 0), fig = c(0.32, 0.57, 0.8, 0.94), new=TRUE)
par(fig = c(0.3, 0.63, 0, 1))
plot(1, 1, type = "n", xaxt = "n", yaxt = "n", ylim = c(1, 52.04), xlim = c(-0.23, 4.2), ann = F, bty="n") ## to remove black border

## Add axes labels:
mtext(side = 1, text = "Forecast week", line = 3, cex = 1.2, font = 3)
mtext(side = 2, text = "Start date", line = 3, cex = 1.2, font = 3)

## Add figure title:
my.title = "% of coincident regimes between ECMWF-MPS \nand ERA-Interim's"
mtext(side = 3, text = my.title, cex = 1.3)

## old x-axis that cannot be rotated of 45 degrees; only used to draw ticks:
axis(1, at=seq(0, 3), las=3, cex.axis=1, labels=FALSE, mgp=c(3,0.7,0)) 

## Plot x-axis labels rotated of 45 degrees at default tick marks:
##labels <- paste0(" ",1:31)
xlabel <- c("5-11", "12-18","19-25","26-32")
text(0:3, par("usr")[3] - 1.55, srt = 45, adj = 1, labels = xlabel, xpd = TRUE, cex=.8) 

## Draw subtitle:
##mtext(1, text = "                                     Reference dataset: Era-Interim", line = 7)

## Plot y-axis:
axis(2, at=52:1, las=2, labels=1:52, cex.axis=.8)

## create an array similar to array.pers but with colors instead of frequencies:                
n.cols <- length(my.cols)
array.colors <- array(my.cols[n.cols], c(52, 4))
for(int in (n.cols-1):1) array.colors[WR.seq.perc.full.weekly < my.brks[int+1]] <- my.cols[int]

## fill with colors the cells in the figure:
for(p in 1:52){ for(l in 0:(4-1)){ polygon(c(0.5+l-1, 0.5+l-1, 1.5+l-1, 1.5+l-1), c(-0.5+53-p, 0.5+53-p, 0.5+53-p, -0.5+53-p), col=array.colors[p,1+l], border="black") }}

## add color legend:
par(fig = c(0.57, 0.74, 0.30, 0.75), new=TRUE)
ColorBar(brks=my.brks, cols=my.cols, vert=TRUE, label_scale=1.3, subsample=1)

dev.off()    




