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

rm(list=ls())
library(s2dverification)  # for the function Load()
library(abind) # for funcion abind()
source('/home/Earth/ncortesi/scripts/Rfunctions.R') # for the calendar functions

# directory where to find the WT classification
workdir <- "/scratch/Earth/ncortesi/RESILIENCE/WT"

# reanalysis used for daily var data (must be the same as the mslp data):
var.rean <- list(path = '/esnas/recon/ecmwf/erainterim/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc')
#var.rean <- list(path = '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc')
rean.name <- 'erai' #'ncep'  #'erai'
    
# any daily variable:
var.name='psl' ##'tas' #'sfcWind' #'prlr'        
#var.name.file='Temperature' #'10-m Wind Speed'  #'Precipitation' #'Surface_Temperature' # '10-m_Wind_Speed'   # variable name used in the ouput map's title

year.start <- 1985
year.end <- 2014

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

LOESS <- TRUE  # LOESS climatology filter on/off (if off, a 5-days mobile windows is usedto measure daily anomalies)

rm.lat <- c(-12,12)  # in case of WTs, remove these lat values from the maps

##########################################################################################
n.periods <- length(periods)
n.years <- year.end - year.start + 1

my.brks <- my.cols <- my.labels <- my.unit <- list()
my.brks.freq <- c(0,0.05,seq(0.1,0.7,0.1),1) # Frequency of a WT or WD
my.cols.freq <-  colorRampPalette(c('#f7fbff','#deebf7','#c6dbef','#9ecae1','#6baed6','#4292c6','#2171b5','#08519c','#08306b'))(length(my.brks.freq)-1)
my.unit.freq <- "%"

if(var.name == 'tas') var.num <- 1
if(var.name == 'sfcWind') var.num <- 2
if(var.name == 'prlr') var.num <- 3

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)")
wd.dir <- c("N","NE","E","SE","S","SW","W","NW")
n.wd <- length(wd.dir)

# load one day of var data only to detect lat and lon values:
var <- Load(var.name, NULL, list(var.rean), paste0(year.start,'0101'), storefreq = 'daily', leadtimemax=1, output = 'lonlat', nprocs=1)
var.lat <- var$lat # var lat and lon MUST be the same of WT classification, even if the latter can have NA for certain lat values.
var.lon <- var$lon
n.lat.var <- length(var.lat)
n.lon.var <- length(var.lon)
n.lonr <- n.lon.var - ceiling(length(var.lon[var.lon>0 & var.lon < 180])) # count the num of lon values between 180 and 360 degrees
lon.swapped <- c((n.lonr+1):n.lon.var,1:n.lonr) # lon is always positive but rearranged
var.lon2 <-  c(var.lon[c((n.lonr+1):n.lon.var)]-360,var.lon[1:n.lonr]) # to have lon values from -180 to 180

l1 <- which(var.lat > rm.lat[1]) # lat values greater than -12
l2 <- which(var.lat < rm.lat[2]) # lat values lower than 12
pos.lat.unused <- which(!is.na(match(l1,l2)))
var.lat.unused <- var.lat[pos.lat.unused]  # latitude values not visualized in the WT classification because too close to equator

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

# save var anomalies:

# load WT metadata to get the info on year.start and year.end
#WTs_files <- list.files(paste0(workdir,"/txt/ERAint/all_years"))
#WTs_file1 <- read.table(file=paste0(workdir,"/txt/ERAint/all_years/",WTs_files[1]), header=TRUE)
#load(paste0(workdir,"/txt/ERAint/metadata.RData")) 

# load daily var data for all years:
var <- Load(var.name, NULL, list(var.rean), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax=366, output = 'lonlat', nprocs=8)

# remove bisestile days from var to have all arrays with the same dimensions:
cat("Removing bisestile days. Please wait...\n")
var365 <- var$obs[,,,1:365,,,drop=FALSE]

for(y in year.start:year.end){
    y2 <- y - year.start + 1        
    if(n.days.in.a.year(y) == 366) var365[,,y2,60:365,,] <- var$obs[,,y2,61:366,,] # take the march to december period removing the 29th of February
}

rm(var)
gc()

# convert var to daily anomalies:
cat("Calculating anomalies. Please wait...\n")

if(LOESS == TRUE){
        var365ClimDaily <- apply(var365, c(1,2,4,5,6), mean, na.rm=T)
        var365ClimLoess <- var365ClimDaily
        
        for(i in 1:n.lat.var){
            for(j in 1:n.lon.var){
                my.data <- data.frame(ens.mean=var365ClimDaily[1,1,,i,j], day=1:365)
                my.loess <- loess(ens.mean ~ day, my.data, span=0.35)
                var365ClimLoess[1,1,,i,j] <- predict(my.loess)
            }
        }

        rm(var365ClimDaily, my.data, my.loess)
        gc()

        var365Clim <- InsertDim(var365ClimLoess, 3, year.end-year.start+1)

        rm(var365ClimLoess)
        gc()
        
} else { # apply a 5-days mobile window:

        #var365Clim  <- InsertDim(var365ClimDaily, 3, n.years)
        var365Clim <- array(NA,c(365,dim(var365)[5:6]))
    
        var365x3 <- abind(var365[,,,364:365,,,drop=FALSE],var365[,,,,,,drop=FALSE],var365[,,,1:2,,,drop=FALSE],along=4) # add the two days before 1st january and after 31 dec

        for(d in 1:365){
           window <- var365x3[1,1,,2+d+seq(-2,2),,,drop=FALSE]
           var365Clim[d,,] <- apply(window,c(5,6),mean,na.rm=TRUE)
        }
           
        rm(var365x3, window)
        gc()

        var365Clim <- InsertDim(var365Clim, 1, n.years)
        
}
    
        
var365Anom <- var365[1,1,,,,] - var365Clim

rm(var365Clim)
gc()

rm(var365)
gc()

# save var anomalies for retreiving them when necessary:
save(var365Anom, file=paste0(workdir,"/",rean.name,"_",var.name,"365Anom.RData"))





    
# Compute wind directions:
uas <- Load(var = 'uas', exp = NULL, obs = list(var.rean), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax=366, output = 'lonlat', nprocs=8)$obs
vas <- Load(var = 'vas', exp = NULL, obs = list(var.rean), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax=366, output = 'lonlat', nprocs=8)$obs

windir <- (180/pi)*atan2(uas,vas) + 180 # wind direction in degrees; 90 is necessary to shift from trigonometric system to cardinal system and +180 to shift
                                            # from the direction wind is blowing to the direction wind is coming from
rm(uas, vas)
gc()

# remove bisestile days from windir, to compare it with var, which has no bisestiles:
cat("Removing bisestile days. Please wait...\n")
windir365 <- windir[,,,1:365,,,drop=FALSE]

for(y in year.start:year.end){
    y2 <- y - year.start + 1        
    if(n.days.in.a.year(y) == 366) windir365[,,y2,60:365,,] <- windir[,,y2,61:366,,] # take the march to december period removing the 29th of February
}


rm(windir)
gc()

dir2 <- which(windir365 > 22.5)
dir3 <- which(windir365 > 22.5 + 45)
dir4 <- which(windir365 > 22.5 + 90)
dir5 <- which(windir365 > 22.5 + 135)
dir6 <- which(windir365 > 22.5 + 180)
dir7 <- which(windir365 > 22.5 + 225)
dir8 <- which(windir365 > 22.5 + 270)
dir1 <- which(windir365 > 22.5 + 315)

windirClass <- array(1, dim(windir365)) # N
windirClass[dir2] <- 2 # NE
windirClass[dir3] <- 3 # E
windirClass[dir4] <- 4 # SE
windirClass[dir5] <- 5 # S
windirClass[dir6] <- 6 # SW
windirClass[dir7] <- 7 # W
windirClass[dir8] <- 8 # NW
windirClass[dir1] <- 1 # N

rm(windir365)
rm(dir1,dir2,dir3,dir4,dir5,dir6,dir7,dir8)
gc()

# save it once to retreive it later:
save(windirClass, file=paste0(workdir,"/",rean.name,"_windirClass.RData"))





# Plot frequency maps:
    
load(paste0(workdir,"/",rean.name,"_windirClass.RData"))

windirFreqInter <- array(NA, c(n.wd, length(periods), n.years, n.lat.var, n.lon.var)) # array where to store the interannual frequencies

dir.create(paste0(workdir,"/windir"))
           
# save wind direction mean frequency maps:
for(p in periods){
    # select wind direction data only inside period p:
    windirPeriod <- windirClass[1,1,,pos.period(1,p),,]

    for(wd in 1:8){
  
      # remove from windPeriod the days not belonging to that wd (setting its value to NA):
      windirPeriod.wt <- windirPeriod
        
      ss <- which(windirPeriod == wd)
      pp <- which(windirPeriod != wd)
        
      windirPeriod.wt[ss] <- 1   # set to 1 the days belonging to that wt
      windirPeriod.wt[pp] <- NA  # set to NA the days not belonging to that wt
      rm(ss,pp)
      gc()
          
      # mean frequency maps:
      windirDays <- apply(windirPeriod.wt, c(3,4), sum, na.rm=TRUE)
      windirFreq <- windirDays / (n.years * n.days.in.a.period(p,1))

      my.fileout <- paste0(workdir,"/windir/",rean.name,"_frequency_",period.name[p],"_direction_",wd.dir[wd],".png")
        
      png(filename=my.fileout,width=900,height=600)
 
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
      PlotEquiMap(windirFreq[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks.freq, cols=my.cols.freq, colNA="gray", drawleg=F)
      ColorBar2(my.brks.freq, cols=my.cols.freq, vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks.freq), my.labels=100*my.brks.freq, label.dist=.5)
      dev.off()

      # mean frequency maps for North Pole:
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_frequency_polar_",period.name[p],"_direction_",wd.dir[wd],".png")
      PlotStereoMap(windirFreq, var.lon, var.lat, latlims = c(60,90), brks=my.brks.freq, cols=my.cols.freq, subsampleg=1, units=my.unit.freq, colNA="gray", fileout=my.fileout)

      # measure the interannual frequency series of that wind direction (for each grid point):
      windirFreqInter[wd,p,,,] <- apply(windirPeriod.wt,c(1,3,4), sum, na.rm=TRUE) / n.days.in.a.period(p,1)
      #windirPeriod.wt[year,days,,]
        
      # plot the frequency maps for each year:
      for(y in year.start:year.end){
          y2 <- y - year.start + 1
          my.fileout <- paste0(workdir,"/windir/",rean.name,"_frequency_",period.name[p],"_year_",y,"_direction_",wd.dir[wd],".png")
          png(filename=my.fileout,width=900,height=600)
          layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
          PlotEquiMap(windirFreqInter[wd,p,y2,,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks.freq, cols=my.cols.freq, colNA="gray", drawleg=F)
          ColorBar2(my.brks.freq, cols=my.cols.freq, vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks.freq), my.labels=100*my.brks.freq, label.dist=.5)
          dev.off()
      
      } # close for on y
        
    } # close for on wd
    
} # close for on p

save(windirFreqInter, file=paste0(workdir,"/",rean.name,"_windirFreqInter.RData"))







# save impact map of wind direction on var (average of var only during the days belonging to a particular wind direction):

# load var anomalies and wind direction array:
load(file=paste0(workdir,"/",rean.name,"_",var.name,"365Anom.RData"))
load(paste0(workdir,"/",rean.name,"_windirClass.RData"))

my.brks[[1]] <- seq(-10,10,1) # % Mean anomaly of a WT for temperature
my.cols[[1]] <-  colorRampPalette(as.character(read.csv("~/scripts/palettes/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1)  # blue--yellow-red colors for temperature
my.unit[[1]] <- "degrees"

my.brks[[2]] <- seq(-3,3,0.5) # Mean wind speed anomaly in m/s
my.cols[[2]] <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks[[2]])-1)    # blue--white--red colors for wind speed impact
my.unit[[2]] <- "m/s"

impact.var <- array(NA, c(n.wd, length(periods), n.lat.var, n.lon.var)) # array where to save the impact of each wd on var

for(p in periods){
    # select var data only inside period p:
    varPeriod <- var365Anom[,pos.period(1,p),,]

    # select wind direction data only inside period p:
    windirPeriod <- windirClass[1,1,,pos.period(1,p),,]

    for(wd in 1:8){ # 1:N, 2=NE, 3=E, ...
  
      # remove from varPeriod the days not belonging to that wd (setting its value to NA):
      windirPeriod.wt <- array(NA, dim(windirPeriod))
        
      ss <- which(windirPeriod == wd)
      #pp <- which(windirPeriod != wd)
        
      windirPeriod.wt[ss] <- 1   # set to 1 the days belonging to that wt
      #windirPeriod.wt[pp] <- NA  # set to NA the days not belonging to that wt
      rm(ss)
      gc()
        
      varPeriod.wt <- varPeriod * windirPeriod.wt
    
      var.mean.wt <- apply(varPeriod.wt, c(3,4), mean, na.rm=TRUE)

      impact.var[wd,p,,] <- var.mean.wt
        
      # visualize impact map of the wd on var:
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_impact_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png")
        
      png(filename=my.fileout,width=900,height=600)
        
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
      #PlotEquiMap(var.mean.wt, var.lon, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], drawleg=F, colNA="gray")
      PlotEquiMap(rescale(var.mean.wt[,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
      dev.off()

        
      # North Pole map:
      #png(filename=paste0(workdir,"/windir/impact_polar_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png"))
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_impact_polar_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png")
      PlotStereoMap(rescale(var.mean.wt,min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon, var.lat, latlims = c(60,90), brks=my.brks[[var.num]], cols=my.cols[[var.num]], subsampleg=1, units=my.unit[[var.num]], colNA="gray", fileout=my.fileout)

      # 
      # same maps as above but removing points with frequency < 3%:
      #
        
      windirFreq.wt <- apply(windirPeriod.wt, c(3,4), sum, na.rm=TRUE) / (n.years * n.days.in.a.period(p,1))

      ss <- which(windirFreq.wt < 0.03)
      pp <- which(windirFreq.wt >= 0.03)
        
      windirFreq.wt[ss] <- NA
      windirFreq.wt[pp] <- 1
  
      var.mean.wt2 <- var.mean.wt * windirFreq.wt  
      rm(ss,windirFreq.wt)
      gc()
        
      # visualize impact map of the wd on var:
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_impact_min3percent_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png")
        
      png(filename=my.fileout,width=900,height=600)
        
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
      #PlotEquiMap(var.mean.wt, var.lon, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], drawleg=F, colNA="gray")
      PlotEquiMap(rescale(var.mean.wt2[,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
      dev.off()

      # North Pole map:
      #png(filename=paste0(workdir,"/windir/impact_polar_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png"))
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_impact_min3percent_polar_",var.name,"_",period.name[p],"_direction_",wd.dir[wd],".png")
      PlotStereoMap(rescale(var.mean.wt2,min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon, var.lat, latlims = c(60,90), brks=my.brks[[var.num]], cols=my.cols[[var.num]], subsampleg=1, units=my.unit[[var.num]], colNA="gray", fileout=my.fileout)

      rm(var.mean.wt, var.mean.wt2)
    
    } # close for on wd
    
} # close for on p

save(impact.var, file=paste0(workdir,"/",rean.name,"_",var.name,"_impact.RData"))




# visualize and save the reconstructed monthly/seasonal anomalies with the WDs:

load(paste0(workdir,"/",rean.name,"_windirFreqInter.RData"))
load(paste0(workdir,"/",rean.name,"_",var.name,"_impact.RData"))

impact.total <- array(NA, c(length(periods), n.years, n.lat.var, n.lon.var)) # array where to store the interannual frequencies

my.brks[[1]] <- seq(-10,10,1) # % Mean anomaly of a WT for temperature
my.cols[[1]] <-  colorRampPalette(as.character(read.csv("~/scripts/palettes/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1) 
my.unit[[1]] <- "degrees"

my.brks[[2]] <- seq(-3,3,0.5) # Mean wind speed anomaly in m/s
my.cols[[2]] <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks[[2]])-1)    # blue--white--red colors for wind speed impact
my.unit[[2]] <- "m/s"

for(p in periods){
   for(y in year.start:year.end){
      #p <- 10;  y <- 2016 # for debugging
       
      #test <- impact.var[1,10,,]*windirFreqInter[1,10,32,,]+impact.var[2,10,,]*windirFreqInter[2,10,32,,]+impact.var[3,10,,]*windirFreqInter[3,10,32,,]+impact.var[4,10,,]*windirFreqInter[4,10,32,,]+impact.var[5,10,,]*windirFreqInter[5,10,32,,]+impact.var[6,10,,]*windirFreqInter[6,10,32,,]+impact.var[7,10,,]*windirFreqInter[7,10,32,,]+impact.var[8,10,,]*windirFreqInter[8,10,32,,]
      
      #PlotEquiMap(test[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      # windirFreqInter[,10,32,66,507]
      #test2 <- impact.var[3,10,,]*0.4516 # + impact.var[2,10,,]*0.225 + impact.var[8,10,,]*0.0967 + impact.var[4,10,,]*0.06451 + impact.var[6,10,,]*0.0645 + impact.var[1,10,,]*0.03225 + impact.var[5,10,,]*0.0645
      
      #PlotEquiMap(test2[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      #test3 <- impact.var[3,10,,] #*windirFreqInter[3,10,32,,]
      #PlotEquiMap(test3[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      #test4 <- impact.var[3,10,,] * windirFreqInter[3,10,32,,]
      #PlotEquiMap(test4[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      y2 <- y - year.start + 1
      impact.weighted <- impact.var[,p,,] * windirFreqInter[,p,y2,,]
      impact.total[p,y2,,] <- apply(impact.weighted, c(2,3), sum, na.rm=T)
  
      my.fileout <- paste0(workdir,"/windir/",rean.name,"_reconstructed_",var.name,"_anomalies_",period.name[p],"_year_",y,".png")
      png(filename=my.fileout,width=900,height=600)
        
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
      PlotEquiMap(rescale(impact.total[p,y2,,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
      dev.off()

      for(wd in 1:n.wd){
          my.fileout <- paste0(workdir,"/windir/",rean.name,"_weighted_impact_",var.name,"_",period.name[p],"_year_",y,"_direction_",wd.dir[wd],".png")
          png(filename=my.fileout,width=900,height=600)
        
          layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
          PlotEquiMap(rescale(impact.weighted[wd,,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
          ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
         dev.off()
 
      }
       
   } # close for on y
} # close for on p

save(impact.total, file=paste0(workdir,"/",rean.name,"_",var.name,"_reconstructed_anomalies.RData"))






















# Plot WTs frequency maps:
    
#load(paste0(workdir,"/",rean.name,"_windirClass.RData"))
#windirClass <- [wd,1,1,year,1:365,lat,lon]
    
# load lat and lon from SLP grid:
load(paste0(workdir,"/txt/",rean.name,"/metadata.RData"))  # load lat.used and lon.used

# load daily WT classification for all years and grid points and with the same format of var365Anom:
load(paste0(workdir,"/txt/",rean.name,"/WTs.RData"))

WTs.code <- sort(unique(as.vector(WTs[1,1,,])))
n.wt <- length(WTs.code)
WTs.name <- WTs.type[WTs.code]
wt.num <- c(1:9,NA,NA,NA,NA,NA,NA,NA,NA,10)
    
windirFreqInter <- array(NA, c(n.wt, length(periods), n.years, n.lat.var, n.lon.var)) # array where to store the interannual frequencies

# save weather type mean frequency maps:
for(p in periods){
    # select weather type data only inside period p:
    windirPeriod <- WTs[,pos.period(1,p),,]

    for(wt in WTs.code){
  
      # remove from windPeriod the days not belonging to that wd (setting its value to NA):
      windirPeriod.wt <- array(NA, dim(windirPeriod)) #windirPeriod
        
      ss <- which(windirPeriod == wt)
      #pp <- which(windirPeriod != wt)
        
      windirPeriod.wt[ss] <- 1   # set to 1 the days belonging to that wt
      #windirPeriod.wt[pp] <- NA  # set to NA the days not belonging to that wt
      rm(ss)
      gc()
          
      # mean frequency maps:
      windirDays <- apply(windirPeriod.wt, c(3,4), sum, na.rm=TRUE)
      windirFreq <- windirDays / (n.years * n.days.in.a.period(p,1))

      my.fileout <- paste0(workdir,"/txt/",rean.name,"/",rean.name,"_frequency_",period.name[p],"_type_",WTs.name[wt.num[wt]],".png")
        
      png(filename=my.fileout,width=900,height=600)
 
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))

      windirFreq[pos.lat.unused,] <- NA
      PlotEquiMap(windirFreq[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks.freq, cols=my.cols.freq, colNA="gray", drawleg=F)

      ColorBar2(my.brks.freq, cols=my.cols.freq, vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks.freq), my.labels=100*my.brks.freq, label.dist=.5)
      dev.off()

      # measure the interannual frequency series of that wind direction (for each grid point):
      windirFreqInter[wt.num[wt],p,,,] <- apply(windirPeriod.wt,c(1,3,4), sum, na.rm=TRUE) / n.days.in.a.period(p,1)
      #windirPeriod.wt[year,days,,]
        
      # plot the frequency maps for each year:
      ## for(y in year.start:year.end){
      ##     y2 <- y - year.start + 1
      ##     my.fileout <- paste0(workdir,"/txt/",rean.name,"/frequency/",rean.name,"_frequency_",period.name[p],"_year_",y,"_type_",WTs.name[wt],".png")
          
      ##     png(filename=my.fileout,width=900,height=600)
      ##     layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
          
      ##     windirFreqInter[wt.num[wt],p,y2,pos.lat.unused,] <- NA
      ##     PlotEquiMap(windirFreqInter[wt.num[wt],p,y2,,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks.freq, cols=my.cols.freq, colNA="gray", drawleg=F)
      ##     ColorBar2(my.brks.freq, cols=my.cols.freq, vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks.freq), my.labels=100*my.brks.freq, label.dist=.5)
      ##     dev.off()
      
      ## } # close for on y
        
    } # close for on wt
    
} # close for on p

save(windirFreqInter, file=paste0(workdir,"/txt/",rean.name,"/",rean.name,"_WTsFreqInter.RData"))













    


    


# save impact map of wind direction on var (average of var only during the days belonging to a particular wind direction):

# load var anomalies:
load(file=paste0(workdir,"/txt/",rean.name,"/",rean.name,"_",var.name,"365Anom.RData"))

# load lat and lon from SLP grid:
load(paste0(workdir,"/txt/",rean.name,"/metadata.RData"))  # load lat.used and lon.used

# only for compatibility with older versions (it should be already loaded):
#lat <- round(MSLP$lat,3)
#lon <- round(MSLP$lon,3)

# load daily WT classification for all years and grid points and with the same format of var365Anom:
load(paste0(workdir,"/txt/",rean.name,"/WTs.RData"))

WTs.code <- sort(unique(as.vector(WTs[1,1,,])))
n.WTs <- length(WTs.code)
WTs.name <- WTs.type[WTs.code]
WTs.num <- c(1:9,NA,NA,NA,NA,NA,NA,NA,NA,10)

## Load MDE and interpolate it to the same grid of var data:
library(ncdf4)
dem <- nc_open("/home/Earth/ncortesi/scripts/dem/elevation_512x256.nc")
dem.data <- ncvar_get(dem, dem$var$Band1) 
dem.lat <- dem$dim$lat$vals  # [-90,90]
dem.lon <- dem$dim$lon$vals  # [-180,180]

## in this case, resolution of the MDE is the same of the ERA-Interim (256x512), so we don't need to interpolate
##names(dim(dem.data)) <- c('lon','lat')
##dem.interp <- CDORemap(dem.data, dem.lon, dem.lat, 'r30x15', 'bil', crop=TRUE)
##dem.interp2 <- t(dem.interp$data_array)
##dem.interp3 <- dem.interp2[30:1,]

dem.data2 <- t(dem.data)
dem.data3 <- dem.data2[256:1,]

my.brks[[1]] <- c(-100,seq(-10,10,1),100) # % Mean anomaly of a WT for temperature
my.cols[[1]] <-  colorRampPalette(as.character(read.csv("~/scripts/palettes/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1)  # blue--yellow-red colors for temperature
my.unit[[1]] <- "degrees"

my.brks[[2]] <- seq(-3,3,0.5) # Mean wind speed anomaly in m/s
my.cols[[2]] <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks[[2]])-1)    # blue--white--red colors for wind speed impact
my.unit[[2]] <- "m/s"

impact.var <- array(NA, c(n.WTs, length(periods), n.lat.var, n.lon.var)) # array where to save the impact of each wd on var
for(p in periods){
    # select var data only inside period p:
    varPeriod <- var365Anom[,pos.period(1,p),,]

    # select wind direction data only inside period p:
    windirPeriod <- WTs[,pos.period(1,p),,]

    print(paste0("Period: ",my.period[p]))
    
    for(wt in WTs.code){
  
      # remove from varPeriod the days not belonging to that wd (setting its value to NA):
      windirPeriod.wt <- array(NA, dim(windirPeriod))
        
      ss <- which(windirPeriod == wt)
      #pp <- which(windirPeriod != wt)
        
      windirPeriod.wt[ss] <- 1   # set to 1 the days belonging to that wt
      #windirPeriod.wt[pp] <- NA  # set to NA the days not belonging to that wt
      rm(ss)
      gc()
        
      varPeriod.wt <- varPeriod * windirPeriod.wt
      var.mean.wt <- apply(varPeriod.wt, c(3,4), mean, na.rm=TRUE)
      impact.var[WTs.num[wt],p,,] <- var.mean.wt
        
      # visualize impact map of the wd on var:
      my.fileout <- paste0(workdir,"/txt/",rean.name,"/",year.start,"-",year.end,"/impact/",rean.name,"_impact_",var.name,"_",period.name[p],"_type_",WTs.name[WTs.num[wt]],".png")
        
      png(filename=my.fileout,width=900,height=600)
        
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
      #PlotEquiMap(var.mean.wt, var.lon, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], drawleg=F, colNA="gray")

      var.mean.wt[pos.lat.unused,] <- NA
      #PlotEquiMap(rescale(var.mean.wt[,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      ## show MDE with points above 1000 m:
      ss <- which(dem.data3 >= 1000, arr.ind=TRUE)
      dem.data4 <- array(FALSE, c(256,512))
      dem.data4[ss] <- TRUE

      PlotEquiMap(var.mean.wt[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F, margin_scale=c(1,4,1,4)) #, dot_symbol=15, dot_size=.5)

      ## show MDE with dots (bad):
      ## PlotEquiMap(var.mean.wt[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F, dots=dem.data4, margin_scale=c(1,4,1,4)) #, dot_symbol=15, dot_size=.5)

## show MDE with contours (bad):
      ## PlotEquiMap(var.mean.wt[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F, contours=dem.data3, brks2=c(seq(1000,3000,1000)), contour_color=c('gray50','gray30','gray10'), contour_label_scale=0)
        
      ColorBar(brks=my.brks[[var.num]][2:(l(my.brks[[var.num]])-1)], cols=my.cols[[var.num]][2:(l(my.cols[[var.num]])-1)], vert=FALSE, label_scale=1.5, bar_limits=c(my.brks[[var.num]][2],my.brks[[var.num]][l(my.brks[[var.num]])-1]), col_inf=my.cols[[var.num]][1], col_sup=my.cols[[var.num]][l(my.cols[[var.num]])], subsample=1)
      dev.off()

      ## show MDE with points above 1000 m and 2000 m:
      ##dem.data5 <- array(NA, c(2,256,512))
      ##dem.data5[1,,] <- dem.data3
      ##dem.data5[2,,] <- dem.data3

      ##dem.data6 <- array(FALSE, c(2,256,512))
      ##ss <- which(dem.data5[1,,] >= 1000, arr.ind=TRUE)
      ##tt <- which(dem.data5[2,,] >= 2000, arr.ind=TRUE)
      ##for(i in 1:l(ss)/2) dem.data6[1,ss[i,1],ss[i,2]] <- TRUE
      ##for(i in 1:l(tt)/2) dem.data6[2,tt[i,1],tt[i,2]] <- TRUE
      ##PlotEquiMap(var.mean.wt[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F, dots=dem.data6, dot_size=c(0,1), dot_symbol='12')
          
      ## windirFreq.wt <- apply(windirPeriod.wt, c(3,4), sum, na.rm=TRUE) / (n.years * n.days.in.a.period(p,1))

      ## ss <- which(windirFreq.wt < 0.03)
      ## pp <- which(windirFreq.wt >= 0.03)
        
      ## windirFreq.wt[ss] <- NA
      ## windirFreq.wt[pp] <- 1
  
      ## var.mean.wt2 <- var.mean.wt * windirFreq.wt
        
      ## rm(ss,windirFreq.wt)
      ## gc()
      rm(varPeriod.wt, windirPeriod.wt)
        
    } # close for on wd

    rm(varPeriod, windirPeriod)
    gc()
} # close for on p

save(impact.var, file=paste0(workdir,"/txt/",rean.name,"/",rean.name,"_",var.name,"_impact_WTs.RData"))









# visualize and save the reconstructed monthly/seasonal anomalies with the WTs:

# load daily WT classification for all years and grid points and with the same format of var365Anom:
load(paste0(workdir,"/txt/",rean.name,"/",rean.name,"_WTsFreqInter.RData"))
load(paste0(workdir,"/txt",rean.name,"/",rean.name,"_",var.name,"_impact_WTs.RData"))

impact.total <- array(NA, c(length(periods), n.years, n.lat.var, n.lon.var)) # array where to store the interannual frequencies

my.brks[[1]] <- seq(-10,10,1) # % Mean anomaly of a WT for temperature
my.cols[[1]] <-  colorRampPalette(as.character(read.csv("~/scripts/palettes/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1) 
my.unit[[1]] <- "degrees"

my.brks[[2]] <- seq(-3,3,0.5) # Mean wind speed anomaly in m/s
my.cols[[2]] <- colorRampPalette(rev(brewer.pal(11,"RdBu")))(length(my.brks[[2]])-1)    # blue--white--red colors for wind speed impact
my.unit[[2]] <- "m/s"

for(p in periods){
   for(y in year.start:year.end){
      #p <- 10;  y <- 2016 # for debugging
       
      #test <- impact.var[1,10,,]*windirFreqInter[1,10,32,,]+impact.var[2,10,,]*windirFreqInter[2,10,32,,]+impact.var[3,10,,]*windirFreqInter[3,10,32,,]+impact.var[4,10,,]*windirFreqInter[4,10,32,,]+impact.var[5,10,,]*windirFreqInter[5,10,32,,]+impact.var[6,10,,]*windirFreqInter[6,10,32,,]+impact.var[7,10,,]*windirFreqInter[7,10,32,,]+impact.var[8,10,,]*windirFreqInter[8,10,32,,]
      
      #PlotEquiMap(test[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      # windirFreqInter[,10,32,66,507]
      #test2 <- impact.var[3,10,,]*0.4516 # + impact.var[2,10,,]*0.225 + impact.var[8,10,,]*0.0967 + impact.var[4,10,,]*0.06451 + impact.var[6,10,,]*0.0645 + impact.var[1,10,,]*0.03225 + impact.var[5,10,,]*0.0645
      
      #PlotEquiMap(test2[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      #test3 <- impact.var[3,10,,] #*windirFreqInter[3,10,32,,]
      #PlotEquiMap(test3[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      #test4 <- impact.var[3,10,,] * windirFreqInter[3,10,32,,]
      #PlotEquiMap(test4[,lon.swapped], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)

      y2 <- y - year.start + 1
      impact.weighted <- impact.var[,p,,] * windirFreqInter[,p,y2,,]
      impact.total[p,y2,,] <- apply(impact.weighted, c(2,3), sum, na.rm=T)
  
      my.fileout <- paste0(workdir,"/txt/",rean.name,"/reconstructed/reconstructed_",var.name,"_anomalies_",period.name[p],"_year_",y,".png")
      png(filename=my.fileout,width=900,height=600)
        
      layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
       
      impact.total[p,y2,pos.lat.unused,] <- NA
      
      PlotEquiMap(impact.total[p,y2,,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]], var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
      #ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
      ColorBar(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)

      dev.off()

      for(wd in 1:n.wd){
          my.fileout <- paste0(workdir,"/windir/",rean.name,"_weighted_impact_",var.name,"_",period.name[p],"_year_",y,"_type_",WTs.name[wt],".png")
          
          png(filename=my.fileout,width=900,height=600)
        
          layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
          impact.weighted[wt,pos.lat.unused,] <- NA
          
          PlotEquiMap(rescale(impact.weighted[wt,,lon.swapped],min(my.brks[[var.num]]),max(my.brks[[var.num]])), var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], colNA="gray", drawleg=F)
          ColorBar2(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, cex=1, my.ticks=-0.5 + 1:length(my.brks[[var.num]]), my.labels=my.brks[[var.num]], label.dist=.5)
          dev.off()
      }
       
   } # close for on y
} # close for on p

save(impact.total, file=paste0(workdir,"/",rean.name,"_",var.name,"_reconstructed_anomalies.RData"))



























    














    

# Create and save monthly/seasonal/yearly climatology maps of var:

#p=17 # for the debug

# Map intervals and colors:
my.brks[[1]] <- c(-50,-40,-30,seq(-20,30,0.05),40,50)  # Surface Temperature Climatology
my.brks[[2]] <- c(0,seq(0.05,10,0.05),15)  # Precipitation Climatology
my.brks[[3]] <- c(0,seq(1.05,10,0.05),15)  # Wind speed Climatology

my.cols[[1]] <-  colorRampPalette(as.character(read.csv("/home/Earth/vtorralb/rgbhex.csv",header=F)[,1]))(length(my.brks[[1]])-1)   # blue-yellow-red colors
my.cols[[2]] <-  colorRampPalette(c("white","gray","cyan2","blue","deeppink4"))(length(my.brks[[1]])-1)  # white-gray-blue-purple colores for wind speed

n.lonr <- n.lon.var - ceiling(length(var.lon[var.lon>0 & var.lon < 180])) # count the num of lon values between 180 and 360 degrees
lon.swapped <- c((n.lonr+1):n.lon.var,1:n.lonr) # lon is always positive but rearranged
var.lon2 <-  c(var.lon[c((n.lonr+1):n.lon.var)]-360,var.lon[1:n.lonr]) # to have lon values from -180 to 180

mod.var <- 0
if(var.num == 1) mod.var <- -273.5     # for temperature, you must remove -273 after var.clim.NA.bis[p,,]:

for(p in periods){
    # Select only days of the chosen month/season:
    varPeriod <- var365[,pos.period(1,p),,,drop=FALSE]
    varPeriodMean <- apply(varPeriod,c(3,4),mean,na.rm=TRUE) 

    png(filename=paste0(workdir,"/",var.name,"_Climatology_",period.name[p],".png"),width=1000,height=700)

    layout(matrix(c(rep(1,10),2), 11, 1, byrow = TRUE))
       
    #PlotEquiMap(varPeriodMean+mod.var, var.lon, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], drawleg=F, colNA="gray")
    PlotEquiMap(varPeriodMean[,lon.swapped]+mod.num, var.lon2, var.lat, filled.continents = FALSE, brks=my.brks[[var.num]], cols=my.cols[[var.num]], drawleg=F)
    ColorBar(my.brks[[var.num]], cols=my.cols[[var.num]], vert=FALSE, subsampleg=20, cex=1)

    dev.off()
}






##
## Show Weather types composite maps for Elisa's paper:
##

   rm(list=ls())
   library(s2dverification)  # for the function Load()
   library(future)
   source('/home/Earth/ncortesi/scripts/Rfunctions.R') # for the calendar functions

   ## set the chosen season: (13: winter, 14: spring, etc)
   my.season <- 13

   ## set workdir with WT data and where to put the output:
   workdir <- "/esarchive/scratch/ncortesi/WT/Elisa"

   ## sequence of WRs to plot (from left to right and from top to bottom):
   wt.seq <- c("N","S","NW","NE","W","E","SW","SE","C","A")  
   my.title <- c("Northern","Southern","North-Western","North-Eastern","Western","Eastern","South-Western","South-Eastern","Cyclonic","Anticyclonic")

   ##################################################################################################3
   
   ## Load WTs data:
   WTs <- read.table(file=paste0(workdir, "/outputTorino_1970_2015_no_header_no_bisestili.txt"), header=F, sep=" ", col.names=c("Year","Month","Day","WT","D","F","Z"), stringsAsFactors=FALSE)

   var.name <- "psl"
   var.rean <- list(path = '/esnas/recon/noaa/ncep-reanalysis/$STORE_FREQ$_mean/$VAR_NAME$_f6h/$VAR_NAME$_$YEAR$$MONTH$.nc')

   year.start <- 1970 ##1985
   year.end <- 2015 ##2014
   
   ## load daily SLP data for all years:
   var.data <- Load(var.name, NULL, list(var.rean), paste0(year.start:year.end,'0101'), storefreq = 'daily', leadtimemax=366, output = 'lonlat')
   
   #var <- Load(var.name, NULL, list(var.rean), paste0(year.start,'0101'), storefreq = 'daily', leadtimemax=1, output = 'lonlat', nprocs=1)

   ## remove bisestile days from var to have all arrays with the same dimensions:
   cat("Removing bisestile days. Please wait...\n")
   var365 <- var.data$obs[,,,1:365,,,drop=FALSE]

   for(y in year.start:year.end){
       y2 <- y - year.start + 1        
       if(n.days.in.a.year(y) == 366) var365[,,y2,60:365,,] <- var.data$obs[,,y2,61:366,,] # take the march to december period removing the 29th of February
   }

   ##rm(var.data)
   ##gc()

   ## convert to hPa:
   var365 <- var365 / 100 
   
   ## convert var to daily anomalies:
   cat("Calculating anomalies. Please wait...\n")

   var365ClimDaily <- apply(var365, c(1,2,4,5,6), mean, na.rm=T)
   var365ClimLoess <- var365ClimDaily
   
   for(i in 1:dim(var365ClimDaily)[4]){
       for(j in 1:dim(var365ClimDaily)[5]){
           my.data <- data.frame(ens.mean=rep(var365ClimDaily[1,1,,i,j],3), day=1:(365*3))
           my.loess <- loess(ens.mean ~ day, my.data, span=0.15)
           var365ClimLoess[1,1,,i,j] <- predict(my.loess)[366:730]
       }
   }

   rm(var365ClimDaily, my.data, my.loess)
   gc()

   var365Clim <- InsertDim(var365ClimLoess, 3, year.end-year.start+1)

   rm(var365ClimLoess)
   gc()
      
   var365Anom <- var365 - var365Clim
   
   ## reclassify from 26 to 10 WTs:
   WTs$WT10 <- WTs$WT
   ss <- which(substr(WTs$WT,1,1) == "A")
   WTs$WT10[ss] <- "A"
   ss <- which(substr(WTs$WT,1,1) == "C")
   WTs$WT10[ss] <- "C"

   ## restrict ss to days in the chosen season:
   if(my.season == 13) WTs.season <- WTs[c(which(WTs$Month == 12), which(WTs$Month == 1), which(WTs$Month == 2)),]  
   if(my.season == 14) WTs.season <- WTs[c(which(WTs$Month == 3), which(WTs$Month == 4), which(WTs$Month == 5)),]  
   if(my.season == 15) WTs.season <- WTs[c(which(WTs$Month == 6), which(WTs$Month == 7), which(WTs$Month == 8)),]  
   if(my.season == 16) WTs.season <- WTs[c(which(WTs$Month == 9), which(WTs$Month == 10), which(WTs$Month == 11)),]  

   ## create WT compositions:
   meanSLP <- meanSLPanom <- array(0, c(10, 73, 144))
   for(wt in 1:10){
       
       ss <- which(WTs.season$WT10 == wt.seq[wt])       
       for(s in ss){
           my.day <- n.days.in.a.monthly.period(1, WTs.season$Month[s], 2001) + WTs.season$Day[s] - n.days.in.a.monthly.period(WTs.season$Month[s], WTs.season$Month[s], 2001)
           meanSLP[wt,,] <- meanSLP[wt,,] + var365[1,1, WTs.season$Year[s] - year.start + 1, my.day,,]
           meanSLPanom[wt,,] <- meanSLPanom[wt,,] + var365Anom[1,1, WTs.season$Year[s] - year.start + 1, my.day,,]    

       }
       
       meanSLP[wt,,] <- meanSLP[wt,,] / length(ss)  ## get the mean SLP
       meanSLPanom[wt,,] <- meanSLPanom[wt,,] / length(ss)  ## get the mean SLP

   }
       
   ## visualize WT composition:
   my.brks <-  c(1000, seq(1000,1050,5), 1100)
   my.cols <- rev(colorRampPalette(brewer.pal(11,"RdBu"))(length(my.brks)-1))
   my.brks.anom <-  c(-100, seq(-15,-1,2), 0, seq(1,15,2), 100)
   my.cols.anom <- rev(colorRampPalette(brewer.pal(11,"RdBu"))(length(my.brks.anom)-1))
   my.toptitle <- paste0("Weather types for Turin during ", my.period[my.season])
   
   EU.lon <- c(1:20, 131:144)
   EU.lat <- 5:25
       
   fileoutput <- paste0(workdir,"/WTs_composite_", my.period[my.season],".png")

   png(filename=fileoutput, width=1200, height=2001)

   ## version with no contour lines:
   ## PlotLayout(fun=PlotEquiMap, plot_dims=c(2,3), nrow=5, var=meanSLPanom[, EU.lat, EU.lon], lat=var.data$lat[EU.lat], lon=var.data$lon[EU.lon], filled.continents=FALSE, brks=my.brks.anom[2:(length(my.brks.anom)-1)], cols=my.cols.anom[2:(length(my.cols.anom)-1)], col_inf=my.cols.anom[1], col_sup=my.cols[length(my.cols.anom)], subsampleg=1, titles=my.title, sizetit=2, bar_scale=.3, units="hPa", units_scale=2, axes_label_scale=1.5, bar_label_scale=2.2, intxlon=10, intylat=10, toptitle=my.toptitle, title_scale=1.5)

   ## version with the same contour lines of the colors (both indicating mean SLP anomalies):
   ##my.var <- lapply(1:10, function(x) meanSLPanom[x, EU.lat, EU.lon])
   ##my.args <- lapply(1:10, function(x) list(contours=meanSLPanom[x, EU.lat, EU.lon]))
   ##PlotLayout(fun=PlotEquiMap, plot_dims=c('lat','lon'), nrow=5, var=my.var, lat=var.data$lat[EU.lat], lon=var.data$lon[EU.lon], filled.continents=FALSE, brks=my.brks.anom[2:(length(my.brks.anom)-1)], cols=my.cols.anom[2:(length(my.cols.anom)-1)], col_inf=my.cols.anom[1], col_sup=my.cols.anom[length(my.cols.anom)], subsampleg=1, titles=my.title, sizetit=2, bar_scale=.3, units="hPa", units_scale=2, axes_label_scale=1.5, bar_label_scale=2.2, intxlon=10, intylat=10, toptitle=my.toptitle, title_scale=1.5, special_args=my.args, brks2=my.brks[2:(length(my.brks)-1)])

   my.var <- lapply(1:10, function(x) meanSLPanom[x,EU.lat,EU.lon])
   my.args <- lapply(1:10, function(x) list(contours=meanSLP[x,EU.lat,EU.lon]))

   PlotLayout(fun=PlotEquiMap, plot_dims=c('lat','lon'), nrow=5, var=my.var, lat=var.data$lat[EU.lat], lon=var.data$lon[EU.lon], filled.continents=FALSE, brks=my.brks.anom[2:(length(my.brks.anom)-1)], cols=my.cols.anom[2:(length(my.cols.anom)-1)], col_inf=my.cols.anom[1], col_sup=my.cols.anom[length(my.cols.anom)], subsampleg=1, titles=my.title, sizetit=2, bar_scale=.3, units="hPa", units_scale=2, axes_label_scale=1.5, bar_label_scale=2.2, intxlon=10, intylat=10, toptitle=my.toptitle, title_scale=1.5, special_args=my.args, brks2=my.brks[2:(length(my.brks)-1)], contour_color="gray20")
   
   dev.off()


   
