# --------------------------------------------------
# Appendix A – Code used for temperature downscaling
# --------------------------------------------------
# --------------- temporal code line:
# devtools::install_git("https://earth.bsc.es/gitlab/external/cstools", branch = 'rftemp',
#                        credentials = git2r::cred_user_pass("uname", getPass::getPass()))
# --------------------------------------------------
#!/usr/bin/env Rscript
# R script to downscale air temperature seasonal forecasts
library(CSTools)
library(ncdf4)
print("Load Seasonal Forecasts ECMWF S5 season 0501")
#directories for delta saved data
delta_dir <- "/work/users/giulio/temperature/downscaled/"
delta_name <- c("delta_oro", "delta_oro0", "delta_clim")
#interplation method
method <- c("bilinear", "nearest") #interpolation method name in function
lapse_rate <- c(5.5, 0.0, 6.5)
#starting dates
sd <- paste0(1993:2016, '1101')
#orography
oro_nc <- nc_open("/work/users/giulio/temperature/datasets/oro_red.nc")
oro <- s2dv_cube(data = ncvar_get(oro_nc, "topo"),
                 lat = ncvar_get(oro_nc, "lat"),
                 lon = ncvar_get(oro_nc, "lon"))
#ERA5 climatology
clim_nc <- nc_open("/work/users/giulio/temperature/datasets/era5_t2m_clim_winter_red.nc")
clim <- s2dv_cube(data = ncvar_get(clim_nc, "t2m"),
                  lat = ncvar_get(clim_nc, "lat"),
                  lon = ncvar_get(clim_nc, "lon"))
# seasonal forecast loading
tas_in <- "/work/users/giulio/temperature/$VAR_NAME$/ecmwfS5/$VAR_NAME$_$START_DATE$.nc"
tas_data <- CST_Load(var = 'tas',
                     exp = list(list(path = tas_in)),
                     obs = NULL, sdates = sd, nmember = 25,
                     storefreq = "daily", sampleperiod = 1,
                     latmin = 19, latmax = 53,
                     lonmin = -18, lonmax = 41,
                     output = 'lonlat', nprocs = 6)
for (l in 1:length(method)) {
  for (m in 1:length(delta_name)) {
    if (m == 3) {
      ref <- clim
      lapse_r <- TRUE
    } else {
      ref <- oro
      lapse_r <- FALSE
    }
    lr <- lapse_rate[m]
    # Delta computation
    delta <- CST_RFTemp(tas_data, ref, xlim = c(-11, 40), ylim = c(20, 52.5),
                        lapse = lr, lon_dim = "lon", lat_dim = "lat",
                        time_dim = c("member", "sdate", "ftime"),
                        nolapse = lapse_r, verbose = TRUE,
                        compute_delta = TRUE, method = method[l])
    for (n in 1:length(ssd)) {
      #seasonal forecast loading
      print(paste("Load Seasonal Forecasts ECMWF S5 season 0511 method", 
                  method[l], "delta", delta_name[m]))
      tas_sd_in <- paste0("/work/users/giulio/temperature/$VAR_NAME$/ecmwfS5/$VAR_NAME$_$START_DATE$.nc")
      tas_sd_data <- CST_Load(var = 'tas',
                              exp = list(list(path = tas_sd_in)),
                              obs = NULL, sdates = sd[n],
                              nmember = 25,
                              storefreq = "daily",
                              sampleperiod = 1,
                              latmin = 19, latmax = 53,
                              lonmin = -18, lonmax = 41,
                              output = 'lonlat', nprocs = 6)
      temp_ds <- CST_RFTemp(tas_sd_data, ref,
                            xlim = c(-11, 40), ylim = c(20, 52.5),
                            lapse = lr, lon_dim = "lon", lat_dim = "lat",
                            time_dim = c("member", "sdate", "ftime"),
                            nolapse = lapse_r, verbose = TRUE,
                            delta = delta, method = method[l])
      save_name <- paste0(delta_dir, delta_name[m], "/ecmwfS5/", method[l], "/")
      #saving data
      CST_SaveExp(temp_ds, destination = save_name)   
    }
  }
}
