################## Excess heat obs + forecast
# This script aims to obtain a forecast of the
# excess heat accumulated by weeks
# first it shows the observations until a certain date
# then it shows the forecast plume and ensemble mean
# Created by Paloma Trascasa-Castro


Sys.setenv(LANG = "en")
Sys.setlocale("LC_TIME","en_GB")
library(startR)
library(s2dverification)
library(abind)
library(CSTools)
library(zeallot)
library(s2dv)
library(easyVerification)
library(ClimProjDiags)
library(ggplot2)
library(CSIndicators)

# Test for 2022 just because there's data 
# Now I'm just using mean daily temperature but the average of tmin and tmax should be taken instead

path <- "/esarchive/recon/ecmwf/era5land/daily_mean/tas_f1h/tas_202205.nc"
path <- paste0(path)

# Select 1 point
Granollers <- c(lat = 41.61, lon = 2.3)

day <- Start(dat = path,
                  var= 'tas',
                  lat = values(Granollers[[1]]),
                  lon = values(Granollers[[2]]),
                  time = 'all',
                  retrieve = T)
                  as.vector(attributes(day)$Variables$common$lat)
                  as.vector(attributes(day)$Variables$common$lon)

# Now I have an array with just 1 dimension: time

# Convert to Celsius
day <- as.s2dv_cube(day)

day$data = day$data - 273.15

# If threshold is 10C, calculate exceeding temperature values and accumulate.

# Step 1, calculate excess heat above 10C and remove anything below 10

day$data <- day$data - 10

# Replace negative anomalies with 0
day$data[day$data < 0] <- 0

# Now accumulate degrees:
# object needs to be an s2dv_cube

day$data <- cumsum(day$data)

dev.new()
matplot(1:31,day$data, type = 'l', lwd = 2)
