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

# Calibrate with cross-validation
# Full-cross-val workflow

sdate_dim <- dim(hcst$data)['syear']
nmemb <- dim(hcst$data)['ensemble']
nftime <- dim(hcst$data)['time']
nlats <- dim(hcst$data)['latitude']
nlons <- dim($hcst$data)['longitude']







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


# 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 = "ensemble", values = 1)

test_hcst <- CST_MergeDims(hcst, 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 = 'ensemble', cross.val = TRUE, na.rm=TRUE)
bias <- s2dv::Bias(test_hcst$data, test_obs$data, time_dim = 'syear', memb_dim = 'ensemble', na.rm=TRUE)
cor <-  s2dv::Corr(test_hcst$data, test_obs$data, time_dim = 'syear', memb_dim = 'ensemble', memb = FALSE, sign = TRUE)
crpss <- s2dv::CRPSS(test_hcst$data, test_obs$data, time_dim = 'syear', memb_dim = 'ensemble')

skill_metrics  <- list(rpss = rpss$rpss, rpss_significance = rpss$sign,
                             mean_bias = bias, 
                             corr = cor$cor, corr_significance = cor$sign,
                             crpss = crpss$crpss, cprss_significance = crpss$sign)

# editar segun el numero de latitudes y longitudes
skill_metrics <- lapply(skill_metrics, function(x) {
                      dim(x) <- c(var = 1, time = 4, latitude = 6, longitude =5)
                      return(x)})
