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

#calibrate data
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')

# Merge time dimension
test_hcst <- CST_MergeDims(cal, c('syear', 'sweek'))
test_obs <- CST_MergeDims(obs, c('syear', 'sweek'))


# leave dimensions with time and weeks
# estimate terciles from observations
terciles <-quantile(testobs, probs = c(.1,.33,.66,.9), na.rm = TRUE)


#make the plot
fcst <- data.frame(test_hcst$data[1,1,1,5,1,1,1,]-273.15)

PlotForecastPDF(fcst,tercile.limits = c(terciles[2],terciles[3]),extreme.limits = c(terciles[1], terciles[4]),var.name = "Temperature (C)", title = paste("Test Forecast ini ",fcst.sdate," valid for ",fcst.sdate))






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)


