###################################################################################
## Author: E. Duzenli
## Description: Example script for seasonal downscaling with full cross valuidation
###################################################################################
setwd("/gpfs/scratch/bsc32/MN4/bsc32/bsc32801/amd_gitlab/sunset/") # edit please
# Load modules
source("modules/Loading/Loading.R")
source("modules/Downscaling/Crossval_downscaling.R")
#source("modules/Saving/Saving.R")

# Input
var <- "tas"
REF <- "CERRA"
System <- "ECMWF-SEAS5.1"
Horizon <- "Seasonal"
freq <- "daily_mean" 
target_month <- 1 # 1:12
lt <- 0 # lead time
hcst_start <- 2000
hcst_end <- 2005
fcst_year <- 2020
anomaly_calc <- FALSE
dwn_type <- 'analogs'   ### 'intbc', 'intlr', 'analogs', 'logreg'
int_method <- NULL  # "NULL",'con', 'bil', 'bic', 'nn', 'con2',"dis","laf"
bc_method <- NULL # # NULL, "quantile_mapping", "bias", "evmos", "mse_min", "crps_min", "rpc-based", "qm" 
lr_method <- NULL           # 'NULL' 'basic', 'large-scale', '9nn'
log_reg_method <- NULL # "NULL" ,"ens_mean", "ens_mean_sd", "sorted_members"
nanalogs <- 1
latmin = 40.5 
latmax = 42.5 
lonmin = .5
lonmax = 2.5 
categories <- list(c(1/3, 2/3), c(1/10, 9/10))

# Read recipe
recipe_file <- "recipes/atomic_recipes/recipe_seasonal_downscaling.yml"
recipe <- prepare_outputs(recipe_file)

# Edit recipe
recipe$Analysis$Variables$name <- var
recipe$Analysis$Datasets$Reference$name <- REF
recipe$Analysis$Datasets$System$name <- System
recipe$Analysis$Horizon <- Horizon
recipe$Analysis$Variables$freq <- freq
recipe$Analysis$Time$ftime_min <- lt+1
recipe$Analysis$Time$ftime_max <- lt+1
recipe$Analysis$Time$hcst_start <- hcst_start
recipe$Analysis$Time$hcst_end <- hcst_end
recipe$Analysis$Time$fcst_year <- fcst_year
diffmon <- target_month - lt
smonth <- paste0(sprintf('%02d', ifelse(diffmon > 0, diffmon, 12 + diffmon)), '01')
recipe$Analysis$Time$sdate <-smonth
recipe$Analysis$Workflow$Anomalies$compute <- anomaly_calc
recipe$Analysis$Workflow$Downscaling$type           <- dwn_type
recipe$Analysis$Workflow$Downscaling$int_method     <- int_method
recipe$Analysis$Workflow$Downscaling$bc_method      <- bc_method
recipe$Analysis$Workflow$Downscaling$lr_method      <- lr_method
recipe$Analysis$Workflow$Downscaling$log_reg_method <- log_reg_method
recipe$Analysis$Workflow$Downscaling$nanalogs       <- nanalogs
recipe$Analysis$Region$latmin <- latmin
recipe$Analysis$Region$latmax <- latmax
recipe$Analysis$Region$lonmin <- lonmin
recipe$Analysis$Region$lonmax <- lonmax
recipe$Analysis$Workflow$Probabilities$percentiles <- NULL
for (i in 1:length(categories)) {
  recipe$Analysis$Workflow$Probabilities$percentiles[[i]] <- categories[[i]]
}

# Load datasets
data <- Loading(recipe)

# Downscale datasets
dwn_data <- Crossval_downscaling(recipe, data)
