rm(list=ls())
library(ncdf4)
library(abind)
library(fields)
library(CSTools)
library(RColorBrewer)
library(s2dv)
library(ggplot2)
library(startR)
library(multiApply)

# Load 4 start dates

week <- c("20230727", "20230803", "20230810", "20230817") 
path <- "/esarchive/exp/VITIGEOSS/subseasonal/"
var = 't2'
region = 'cat'
path <- paste0(path, var, "/$sdates$/", var, "_", region, "_$sdates$.nc")
res <- Start(dat = path, var='t2', sdates = week, latitude = 'all', longitude = 'all', ensemble = 'all', time = 'all', retrieve = T)
res <- as.s2dv_cube(res)

# Extract Barcelona 

bcn_lt4 <- res$data[1,1,1,15,32,,4]
bcn_lt3 <- res$data[1,1,2,15,32,,3]
bcn_lt2 <- res$data[1,1,3,15,32,,2]
bcn_lt1 <- res$data[1,1,4,15,32,,1]

# Load probabilities with the ERA5land climatologies

# For this I'm only taking the week I'm interested in (week34)

# Load probabilities
# calcular terciles con ERA5 LAND con el periodo del hindcast
# For this I'm only taking the week prior to the one I'm interested in (20230817)
week <- c("20230817")
path <- "/esarchive/exp/VITIGEOSS/subseasonal/"
var = c("p33","p66","p10","p90")
region = 'cat'
path <- paste0(path,"t2/$sdates$/t2_", region, "_percentiles_week33.nc")
per <- Start(dat = path, var= var, sdates=week, latitude = 'all', longitude = 'all', time = 'all', retrieve = T)
per <- as.s2dv_cube(per)

#take only first timestep because I've loaded the target week?
per33 <- per$data[1,1,1,15,32,1]
per66 <- per$data[1,2,1,15,32,1]
per10 <- per$data[1,3,1,15,32,1]
per90 <- per$data[1,4,1,15,32,1]


# Add the skill

week <- c("20230727", "20230803", "20230810", "20230817")
weekn <- c("30","31","32","33")
path <- "/esarchive/exp/VITIGEOSS/subseasonal/"
var = c('rpss', 'bsp10', 'bsp90')
region = 'cat'
path <- paste0(path, "t2/$sdates$/t2_", region, "_skill_week$weekn$.nc")
skill <- Start(dat = path, var=var, sdates = week, weekn = weekn, latitude = 'all', longitude = 'all', time = 'all', retrieve = T)
skill <- as.s2dv_cube(skill)

rpss4 <- skill$data[1,1,1,1,15,32,4]
rpss3 <- skill$data[1,1,2,2,15,32,3]
rpss2 <- skill$data[1,1,3,3,15,32,2]
rpss1 <- skill$data[1,1,4,4,15,32,1]

rpss4 <- round(rpss4/100,digits=2)
rpss3 <- round(rpss3/100,digits=2)
rpss2 <- round(rpss2/100,digits=2)
rpss1 <- round(rpss1/100,digits=2)

# Add observations:

path_obs <- "/esarchive/recon/ecmwf/era5land/daily_mean/tas_f1h/tas_202308.nc"
variable <- "tas"
regions <-  c(lat = 41.39, lon = 2.1)
obs <- Start(dat = path_obs, var = variable, time = 'all', lat = values(regions[1]), lon = values(regions[2]), return_vars = list(lat = NULL, lon = NULL), retrieve = T)      
#obs <- as.s2dv_cube(obs)

as.vector(attributes(obs)$Variables$common$lat)
as.vector(attributes(obs)$Variables$common$lon)

# Extract Barcelona and average from day 21 to day 27
obs <- obs[1,1,21:27,1,1]
obs <- obs -273.15
obs <- mean(obs)

# Plot forecast PDF

fcst <- data.frame(fcst1 = bcn_lt4, fcst2 = bcn_lt3, fcst3 = bcn_lt2, fcst4 = bcn_lt1)

plot <-PlotForecastPDF(fcst,tercile.limits = c(terciles[2],terciles[3]), extreme.limits = c(terciles[1], terciles[4]), 
     var.name = "Temperatura diaria (C)",fcst.names = c(paste0("ftime: days 26-32\n sdate: 27/07/23\nRPSS: ",rpss4),
     paste0("ftime: days 19-25\n sdate: 03/08/23\nRPSS: ",rpss3),paste0("ftime: days 12-18\n sdate: 10/08/23\nRPSS: ",rpss2),
     paste0("ftime: days 5-11\n sdate: 17/08/23\nRPSS: ",rpss1)) , obs = c(obs,obs,obs,obs),
     title = "Prediccion subestacional de la ola de calor de 2023 - Barcelona")

ggsave("tsubseasonal_vit_BCN_aug23_t2_rpss.png", plot, width = 7, height = 5)


##### SAME WITH SEASONAL ####

# Load 3 start dates, max fcst time = 3?

month <- c("20230501", "20230601", "20230701")
path <- "/esarchive/exp/VITIGEOSS/seasonal/"
var = 't2'
region = 'cat'
path <- paste0(path, var, "/$sdates$/", var, "_", region, "_$sdates$.nc")
res <- Start(dat = path, var='t2', sdates = month, latitude = 'all', longitude = 'all', ensemble = 'all', time = 'all', retrieve = T)
res <- as.s2dv_cube(res)

# Extract Barcelona

bcn_lt3 <- res$data[1,1,1,15,32,,3]
bcn_lt2 <- res$data[1,1,2,15,32,,2]
bcn_lt1 <- res$data[1,1,3,15,32,,1]

# Load probabilities
# calcular terciles con ERA5 LAND con el periodo del hindcast
# For this I'm only taking the week I'm interested in (20230817), is that correct?
month <- c("202307")
path <- "/esarchive/exp/VITIGEOSS/seasonal/"
var = c("p33","p66","p10","p90")
region = 'cat'
path <- paste0(path,"t2/$sdates$/t2_", region, "_percentiles_month07.nc")
per <- Start(dat = path, var= var, sdates=month, latitude = 'all', longitude = 'all', time = 'all', retrieve = T)
per <- as.s2dv_cube(per)

#take only first timestep because I've loaded the target week?
per33 <- per$data[1,1,1,15,32,1]
per66 <- per$data[1,2,1,15,32,1]
per10 <- per$data[1,3,1,15,32,1]
per90 <- per$data[1,4,1,15,32,1]

# Add the skill

month <- c("20230501", "20230601", "20230701")
monthn <- c("05","06","07")
path <- "/esarchive/exp/VITIGEOSS/seasonal/"
var = c('rpss', 'bsp10', 'bsp90')
region = 'cat'
path <- paste0(path, "t2/$sdates$/t2_", region, "_skill_month$monthn$.nc")
skill <- Start(dat = path, var = var, sdates = month, monthn = monthn,
               latitude = 'all', longitude = 'all', time = 'all', retrieve = T)
skill <- as.s2dv_cube(skill)

rpss3 <- skill$data[1,1,1,1,15,32,3]
rpss2 <- skill$data[1,1,2,2,15,32,2]
rpss1 <- skill$data[1,1,3,3,15,32,1]

rpss3 <- round(rpss3/100,digits=2)
rpss2 <- round(rpss2/100,digits=2)
rpss1 <- round(rpss1/100,digits=2)

# Add observations:

path_obs <- "/esarchive/recon/ecmwf/era5land/monthly_mean/tas_f1h/tas_202308.nc"
variable <- "tas"
regions <-  c(lat = 41.39, lon = 2.1)
obs <- Start(dat = path_obs, var = variable, time = 'all', lat = values(regions[1]),
             lon = values(regions[2]), return_vars = list(lat = NULL, lon = NULL), retrieve = T)
#obs <- as.s2dv_cube(obs)
obs <- obs -273.15

# PlotForecastPDF

fcst <- data.frame(fcst1 = bcn_lt3, fcst2 = bcn_lt2, fcst3 = bcn_lt1)

plot <-PlotForecastPDF(fcst,tercile.limits = c(per33,per66), extreme.limits = c(per10, per90),
     var.name = "Temperatura diaria (C)",fcst.names = c(paste0("Valid for: Aug23\nIssued: May23\nRPSS: ",rpss3),
      paste0("Valid for: Aug23\nIssued: June23\nRPSS: ",rpss2),paste0("Valid for: Aug23\nIssued: July23\nRPSS: ",rpss1)) ,
       obs = c(obs,obs,obs),title = "Prediccion estacional de la ola de calor de 2023 - Barcelona")

ggsave("seasonal_vit_BCN_aug23_t2_rpss.png", plot, width = 7, height = 5)

