#Appendix A – Code used for temperature downscaling
#!/usr/bin/env Rscript
# R script to downscale air temperature seasonal forecasts
library(devtools)
library(zeallot)
library(fields)
library(raster)
library(ncdf4)
oad_all("/work/users/giulio/git/cstools")
md <- c("0501","1101") #season - starting date
var <- "tas" #variable name
model <- c("ecmwfS5","mfS6") #model name
clim_name <- c("era5_t2m_clim_summer_red.nc",
               "era5_t2m_clim_winter_red.nc") #climatology name
 #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("bil", "nearn") #interpolation method name directories
met_n <- c("bilinear", "nearest") #interpolation method name in function
ne <- 25 #number of ensemble members
coo_geo1 <- c(-18,41,19,53) #coarse domain ECMWF
coo_geo2 <- c(-19.5,42.5,17.5,54.5) #coarse domain MeteoFrance
lapse_rate <- c(5.5,0.0,6.5)
#starting dates
ys <- 1993
ye <- 2016
ssd <- ys:ye
s <- length(ssd)
sd <- array("", s)
#orography
oro_in <- "/work/users/giulio/temperature/datasets/oro_red.nc"
oro_nc <- nc_open(oro_in)
oro_data <- ncvar_get(oro_nc, "topo")
oro_lon <- ncvar_get(oro_nc, "lon")
oro_lat <- ncvar_get(oro_nc, "lat")
oro <- list(data = oro_data, lat = oro_lat, lon = oro_lon)
attr(oro, 'class') <- 's2dv_cube'
for (i in 1:length(md)) {
  #starting dates selection
  for (k in 1:s) {
    sd[k] <- paste0(ssd[k], md[i])
  }
  #ERA5 climatology
  clim_in <- paste0("/work/users/giulio/temperature/datasets/", clim_name[i])
  clim_nc <- nc_open(clim_in)
  clim_data <- ncvar_get(clim_nc, "t2m")
  clim_lon <- ncvar_get(clim_nc, "lon")
  clim_lat <- ncvar_get(clim_nc, "lat")
  clim <- list(data = clim_data, lat = clim_lat, lon = clim_lon)
  attr(clim, 'class') <- 's2dv_cube'
  for (j in 1:length(model)) {
    if (j == 1) {
      coo_geo <- coo_geo1
    } else {
      coo_geo <- coo_geo2
    }
    # seasonal forecast loading
    print(paste0("Load Seasonal Forecasts ",model[j]," season ", md[i]))
    tas_in <- paste0("/work/users/giulio/temperature/", var, "/", model[j], 
                     "/$VAR_NAME$_$START_DATE$.nc")
    tas_data <- CST_Load(var,
                         exp = list(list(path = tas_in)),
                         obs = NULL, sdates = sd, nmember = ne,
                         storefreq = "daily", sampleperiod = 1,
                         latmin = coo_geo[3], latmax = coo_geo[4],
                         lonmin = coo_geo[1], lonmax = coo_geo[2],
                         output = 'lonlat', nprocs = 6)
dim(tas_data$data)
    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 = met_n[l])
        for (n in 1:s) {
          #seasonal forecast loading
          print(paste0("Load Seasonal Forecasts ", model[j], " season ", md[i], 
                       " method ", method, " delta ", delta_name[m]))
          tas_sd_in <- paste0("/work/users/giulio/temperature/", var, "/", model[j],
                              "/$VAR_NAME$_$START_DATE$.nc")
          tas_sd_data <- CST_Load(var,
                                  exp = list(list(path = tas_sd_in)),
                                  obs = NULL, sdates = sd[n],
                                  nmember = ne,
                                  storefreq = "daily",
                                  sampleperiod = 1,
                                  latmin = coo_geo[3], latmax = coo_geo[4],
                                  lonmin = coo_geo[1], lonmax = coo_geo[2],
                                  output = 'lonlat', nprocs = 6)
dim(tas_sd_data$data)
          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 = met_n[l])
          save_name <- paste0(delta_dir, delta_name[m], "/", model[j], "/",
                              method[l], "/")
          #saving data
          CST_SaveExp(temp_ds,save_name)
          rm(tas_sd_data,temp_ds)
        }
        rm(delta)
      }
    }
    rm(tas_data)
  }
  rm(clim_nc,clim_data,clim_lon,clim_lat,clim)
}
