library(startR)
library(multiApply)
library(lubridate)
library(CSTools)

# Load data
sdates <- format(ymd("20000501") + rep(years(0:20), each=1),"%Y%m%d")
exp <- startR::Start(dat = '/esarchive/exp/ecmwf/system5c3s/monthly_mean/$var$_f6h/$var$_$sdate$.nc',
                     var = 'tas', time = indices(1:3), member = 'all', sdate = sdates,
                     latitude = 'all', latitude_reorder = Sort(decreasing = FALSE),
                     longitude = 'all', longitude_reorder = CircularSort(-180, 180),
                     synonims = list(var = c('var','variable'), longitude = c('lon', 'longitude'),
                     latitude = c('lat', 'latitude'), member = c('member','ensemble')),
                     return_vars = list(latitude = 'dat', longitude = 'dat'),
                     num_procs = 1, retrieve = TRUE)

# Compute terciles
terciles <- apply(exp, c(6,7), quantile, probs = c(1/3, 2/3))

# Plot Probability Forecast Distribution
PlotForecastPDF(exp[,,1,,,1,1], tercile.limits=terciles[,1,1], memb_dim = "member", fcst.names = 2000:2020)





