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

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')

# 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)

# Try SUNSET visualization module:
Sys.setenv(LANG = "en")
source("modules/Loading/Loading.R")
source("modules/Calibration/Calibration.R")
source("modules/Anomalies/Anomalies.R")
source("modules/Skill/Skill.R")
source("modules/Saving/Saving.R")
source("modules/Units/Units.R")
source("modules/Scorecards/Scorecards.R")
source("modules/Visualization/Visualization.R")
source("modules/Downscaling/Downscaling.R")

recipe_file <- "recipe_subseasonal.yml"
recipe <- prepare_outputs(recipe_file)

# need to edit visualization from SUNSET
Visualization(recipe,test_hcst, skill_metrics=RPSS, prob_map[,1,1,,], significance = T)





# 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)
