library(CSIndicators)
library(CSTools)
library(zeallot)
library(s2dv)

###############################################################
##### GROWING DEGREE DAYS CALCULATION FROM OBSERVATIONS #######
###############################################################

sdates <- paste0(2024, '04', '01')

lat_min = 34
lat_max = 46
lon_min = -10
lon_max = 5


# Load days from 1st of April to 31st of October

dates <- format(seq(as.Date("20240401", "%Y%m%d"), as.Date("20241031", "%Y%m%d"), 1), "%Y%m%d")

locations <- list(
   vriotajo = c(lat = 39.87, lon = 355.87)
)


ERA5path <- paste0("/esarchive/recon/ecmwf/era5/daily_mean/$var$_f1h-r1440x721cds/$var$_$date$.nc")
tas_obs <- CST_Start(dataset = ERA5path,
                     var = "tas",
                     date = unique(format(dates_exp, '%Y%m')),
                     ftime = startR::values(dates_exp), 
                     ftime_across = 'date',
                     ftime_var = 'ftime',
                     merge_across_dims = TRUE,
                     split_multiselected_dims = TRUE,
                     lat = startR::values(list(lat_min, lat_max)),
                     lat_reorder = startR::Sort(decreasing = TRUE),
                     lon = startR::values(list(lon_min, lon_max)),
                     lon_reorder = startR::CircularSort(0, 360),
                     synonims = list(lon = c('lon', 'longitude'),
                                     lat = c('lat', 'latitude'),
                                     ftime = c('ftime', 'time')),
                     transform = startR::CDORemapper,
                     transform_extra_cells = 2,
                     transform_params = list(grid = "r1440x721",
                                             method = "bicubic"),
                     transform_vars = c('lat', 'lon'),
                     return_vars = list(lon = NULL,
                                        lat = NULL,
                                        ftime = 'date'),
                     retrieve = TRUE)


# change the unit of temperature from °C to K

tas_obs$data <- tas_obs$data - 273.15

GDD_obs <- CST_AccumulationExceedingThreshold(tas_obs, threshold = 10, diff = TRUE)

# reorder the dimension
fcst <- Reorder(drop(GDD_exp$data), c(4, 3, 2, 1))
obs <- Reorder(drop(GDD_obs$data), c(3, 2, 1))

EnsCorr <- veriApply('EnsCorr', fcst = fcst, obs = obs, ensdim = 4, tdim = 3)
GDD_Corr <- Reorder(EnsCorr, c(2, 1))


cols <- c("#f7fcf5", "#e5f5e0", "#c7e9c0", "#a1d99b", "#74c476")
toptitle <- '2013-2016 correlation coefficient of GDD'
dev.new()
PlotEquiMap(GDD_Corr, lon = tas_obs$coords$lon, lat = tas_obs$coords$lat, 
            intylat = 1, intxlon = 1, width = 6, height = 6, 
            filled.continents = FALSE, units = 'correlation', 
            title_scale = .8, axes_label_scale = 1, axes_tick_scale = 1, 
            margin_scale = c(1, 1, 1, 1), cols = cols, brks = seq(0.5, 1, 0.1), 
            toptitle = toptitle, bar_label_scale = 1.5, 
            bar_extra_margin = c(0, 0, 0, 0), units_scale = 2)



