library(CSTools)
library(s2dv)
library(zeallot)
library(easyVerification)
library(ClimProjDiags)

# After loading the data, we now follow an adapted version of a script to plot most likely terciles in subseasonal data

# define latitude and longitude:

Lat <- hcst$coords$lat
Lon <- hcst$coords$lon

# specify hindcast years
ini <- hcst_start_year
fin <- hcst_end_year
numyears <- fin - ini +1

source("https://earth.bsc.es/gitlab/external/cstools/-/raw/d6914a40c11d09168b9b4a191e9a0362b56a5f0c/R/CST_MergeDims.R")

cal <- CST_Calibration(hcst, obs, cal.method = 'evmos', eval.method = 'leave-one-out', multi.model = FALSE, na.rm = TRUE, sdate_dim = 'syear', memb_dim = 'member')

# Calculate anomalies

# Plot anomalies

anom <- CST_Anomaly(cal, obs, memb_dim = 'ensemble', dim_anom = 'syear', dat_dim = c('dat','member'), ftime_dim = 'time')
PlotEquiMap(anom$obs$data[1,1,1,1,5,1,,],Lon,Lat,coast_width=1.5, filled.continents = FALSE, brks = 21, bar_limits = c(-10,10), toptitle = paste(variable, fcst.sdate),width=10, height= 10,units = "Pa", country.borders=TRUE, bar_extra_margin = c(1, 0, 1, 0), fileout = "obs_psl_060803.png",triangle_ends = c(TRUE,TRUE),intylat=10,intxlon=10)




# Probabilities of each tercile are computed by evaluating which tercile is forecasted by each ensemble member for the latest forecast.

PB <- ProbBins(cal$data[1,1,5,1,,,,,], fcyr = numyears, time_dim = "syear", thr = c(1/3, 2/3), compPeriod = "Without fcyr")

# make the probability map:


prob_map <- MeanDims(PB, c('member'))

#Plot the most likely tercile maps, change 4th dimension according to the leadime that you want to plot. lt0 = 1, etc.

#PlotMostLikelyQuantileMap(probs = prob_map[,1,1,,], lon = Lon, lat = Lat, coast_width = 1.5, legend_scale = 0.5, toptitle = paste0('Most likely tercile -', variable, ' - ECMWF, System5 -lt0 - 23 August 2023'), width = 10, height = 8)

# Add RPSS to the plot
# create a new s2dv cube, "obsd" to add member dimension to observations
obs <- CST_InsertDim(obs, posdim = 9, lendim = 1, name = "member", values = 1)

test_hcst <- CST_MergeDims(cal, c('syear', 'sweek'))
test_obs <- CST_MergeDims(obs, c('syear', 'sweek'))
#RPSS <- CST_MultiMetric(test_hcst, test_obs, metric = 'rpss', multimodel = FALSE, time_dim = 'time', memb_dim = 'member', sdate_dim = 'syear')
RPSS <- s2dv::RPSS(test_hcst$data, test_obs$data, time_dim = 'syear', memb_dim = 'member', cross.val = TRUE, na.rm=TRUE)

#PlotEquiMap(RPSS$rpss[1,1,1,1,,], lat = Lat, lon = Lon, brks = seq(-1, 1, by = 0.1), filled.continents = FALSE)

# Mask rpss to show it in grey on tope of the terciles
mask_rpss <- ifelse((RPSS$rpss <= 0) | is.na(RPSS$rpss),1,0)

# plot most likely terciles with shader areas where there's no skill

PlotMostLikelyQuantileMap(probs = prob_map[,1,1,,], toptitle = 'T2m 21-27 Aug, issued 17 Aug', lon = Lon, lat = Lat, coast_width = 1.5, legend_scale = 0.5, mask = mask_rpss[1,1,1,1,,], width=10, height = 8)
