

# Add check? "probabilities should have a bin dimension, even if it's just 1?"

source("modules/Loading/Loading.R")
source("modules/Units/Units.R")
source("modules/Calibration/Calibration.R")
source("modules/Skill/Skill.R")
source("modules/Anomalies/Anomalies.R")
source("modules/Saving/Saving.R")
source("modules/Visualization/Visualization.R")

# recipe_file_random <- "./tests/recipes/recipe_test_crossval-Ari.yml" # -seasonal_visualization.yml" # dev-plot_extremes.yml"
# recipe_random <- prepare_outputs(recipe_file, disable_checks = FALSE)

# data <- Loading(recipe_random)
# data <- Units(recipe_random, data)
# data <- Calibration(recipe_random, data)

# skill_metrics <- Skill(recipe_random, data)
# probabilities <- Probabilities(recipe_random, data)

outdir <- "./modules/Visualization/R/"
output_conf <- read_yaml("modules/Visualization/output_size.yml",
                         eval.exp = TRUE)$region



# ------------------------------------------------------------------------------
#### Random data ####
source("./modules/Visualization/R/plot_extreme_probs.R")
source("./modules/Visualization/R/tmp/ColorBar.R")
plot_extreme_probs(recipe = recipe, fcst = data$fcst,
                   probabilities = prob_array_bin, threshold = 0.8,
                   outdir = outdir, output_conf = output_conf)


# ------------------------------------------------------------------------------
#### Real data ####

source("./modules/Visualization/R/plot_extreme_probs.R")
plot_extreme_probs(recipe = recipe, fcst = data9over10$fcst,
                   probabilities = data9over10$probs$fcst[[1]],
                   dots = NULL,
                   outdir = outdir, output_conf = output_conf)

source("./modules/Visualization/R/plot_extreme_probs.R")
plot_extreme_probs(recipe = recipe, fcst = multiprobs_global$fcst,
                   probabilities = multiprobs_global$probs$fcst,
                   outdir = outdir, output_conf = output_conf)

# recipe_file <- "recipe_test_crossval.yml" 
# recipe <- prepare_outputs(recipe_file) ## needs to be executed from dev_cross-save-probabilities
data9over10 <- readRDS("~/SUNSET_RS_GIT/sunset/Ariadna_9over10_data.Rds")
multiprobs_global <- readRDS("~/SUNSET_RS_GIT/sunset/Ari_multiprobs_global.Rds")

dim(data9over10$probs$fcst[[1]])
1:dim(data9over10$probs$fcst[[1]])["bin"]

# > dim(data9over10$fcst$data)
# dat       var      sday     sweek     syear      time  latitude longitude  ensemble 
# 1         1         1         1         1         1        20        20        51 
# fem que data9over10$probs$fcst sigui un array
# dims <- c(bin = 2, dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 20, longitude = 20)
# data9over10_probs <- array(unlist(data9over10$probs$fcst), dim = dims)
# dim(data9over10_probs)
# unique(as.vector(apply(data9over10_probs, c(2:9), sum))) # son probabilitiats complementàries!
# solució: bin hauria de ser una dimensió més a dim(data9over10$fcst$data)?
# comprovar que si l'afegeixo el codi funciona. No les tinc totes perque data9over10$probs$fcst és una llista



dims_array_2 <- c(bin = 2, dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 20, longitude = 20)
dims_array <- c(dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 20, longitude = 20) # remove bin = 2
mask_array_2 <- array(rep(c(0, 0, 1, 1), 200), dim = dims_array_2)
mask_array <- array(c(rep(0, 20*10), rep(1, 20*10), 10), dim = dims_array)
dim(mask_array_2)

recipe$Analysis$Workflow$Probabilities$percentiles
dim(data9over10_probs)
prova_list <- list(c("1/3", "2/3"), "9/10", "2/10", c("2/10", "8/10"))
prova_list[vapply(prova_list, length, FUN.VALUE = integer(1)) == 1]

dim(data9over10$probs)
dim(prob_array_bin)
dim(data9over10$fcst)
dim(data9over10$hcst)

# Ordered
# plot_extreme_probs(recipe = recipe, fcst = data$fcst,
#                    probabilities = prob_array_sorted, threshold = 0.8,
#                    outdir = outdir, output_conf = output_conf)

# Warning comes from lines 74-76 calling .get_variable_longname(). Has note:  ## TODO: change


# ------------------------------------------------------------------------------
# PROBS VALUES FROM 0 TO 0.5: 
source("./modules/Visualization/R/plot_extreme_probs.R")
source("./modules/Visualization/R/tmp/ColorBar.R")
plot_extreme_probs(recipe = recipe, fcst = data$fcst,
                   probabilities = prob_array_05, #threshold = 0.9,
                   outdir = outdir, output_conf = output_conf)

# source("./modules/Visualization/R/plot_extreme_probabilities.R")
# plot_extreme_probabilities(recipe = recipe, fcst = data$fcst,
#                            outdir = outdir, output_conf = output_conf,
#                            method = "mean")



dims <- c(dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 12, longitude = 15)
set.seed(1)
prob_array_05 <- array(runif(prod(dims), min = 0, max = 0.5), dim = dims)

prob_array_sorted <- array(sort(prob_array), dim = dims)

# Colorbar

# Browse[2]> brks; cols; bar_limits; var_limits
# [1] 0.00 0.86 1.00
# [1] "#33BFD1" "#FF764D"
# [1] 0 1
# [1] 0.1 1.0
# 
# 
# # taking the first ensemble member:
# data_ens1 <- data$fcst$data[, , , , , , , , 1]
# # ensemble mean
# ensemble_mean <- s2dv::MeanDims(data$fcst$data, 'ensemble')
# 
# # making a probability array with the same dimensions as ensemble_mean:
dims <- c(dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 12, longitude = 15)
# prob_array <- array(runif(prod(dims), min = 0, max = 1), dim = dims)
dim(prob_array)
prob_array_1 <- array(1, dim = dims)
prob_array_comp <- prob_array_1 - prob_array
prob_array_bin <- abind(prob_array, prob_array_comp, along = 0)
dim(prob_array_bin)
dim(prob_array_bin) <- c(bin = 2, dat = 1, var = 1, sday = 1, sweek = 1, syear = 1, time = 1, latitude = 12, longitude = 15)





# values in 1st loop: var_fcst[1,1,1,1:10]
# [1] 0.9875075 0.7175141 0.7299400 0.8163526 0.4743093 0.7776391 0.9345973
# [8] 0.1415915 0.4442519 0.4059477

# values in 2nd loop: var_fcst[1,1,1,1:10]
# [1] -0.01249249 -0.28248588 -0.27006003 -0.18364745 -0.52569070 -0.22236094
# [7] -0.06540267 -0.85840851 -0.55574811 -0.59405233






# making an ordered probability array:
# 
# Browse[2]> all(unique(var_ens_mean) %in% c(0, 1))
# [1] TRUE
# 
# 
# 
# data$fcst["ensemble"]
# 
# # BROWSER:
# 
# Browse[2]> dim(fcst$data)
# dat       var      sday     sweek     syear      time  latitude longitude  ensemble 
# 1         1         1         1         1         1        12        15        51 
# 
# Browse[2]> dim(ensemble_mean)
# dat       var      sday     sweek     syear      time  latitude longitude 
# 1         1         1         1         1         1        12        15 
# 
# Browse[2]> dim(var_ens_mean)
# syear      time  latitude longitude
# 1         1        12        15
# 
# # exemple:
# # ...
# # , , 14, 12
# # 
# # [,1]
# # [1,] 290.2433
# # 
# # , , 15, 12
# # 
# # [,1]
# # [1,] 291.326
# 
# 
# 
# Browse[2]> dim(i_var_ens_mean)
# time longitude  latitude
# 1        15        12
# 
# # exemple:
# # , , 12
# # 
# # [,1]     [,2]     [,3]     [,4]     [,5]     [,6]     [,7]     [,8]     [,9]    [,10]
# # [1,] 291.5779 291.6805 291.7167 291.8615 292.2305 292.6121 292.9793 293.2251 292.8278 293.8573
# # [,11]    [,12]    [,13]    [,14]   [,15]
# # [1,] 293.0403 292.0609 288.9186 290.2433 291.326
# 



# ------------------------------------------------------------------------------
# Browse[2]> outfile

# Branch dev_cross-save-probabilities

source("modules/Loading/Loading.R")
source("modules/Saving/Saving.R")
source("modules/Units/Units.R")
source("modules/Visualization/Visualization.R")
source("modules/Aggregation/Aggregation.R")
recipe_file_r <- "recipe_test_crossval.yml" # "recipe_tas_singl_cal_seas.yml"
# output_dir: /home/Earth/abatalla/SUNSET_RS_GIT/outputs_ari/
#       percentiles: [[9/10]]
#       method: mse_min
recipe_r <- prepare_outputs(recipe_file_r)

# Load datasets
data <- Loading(recipe_r)
data <- Units(recipe_r, data)

source("modules/Crossval/Crossval_Calibration.R")
library(CSTools)
Calibration <- CSTools::Calibration()
Calibration <- CSTools::Calibration
res <- Crossval_Calibration(recipe = recipe_r, data = data)
saveRDS(res, file = "Ariadna_9over10_data.Rds")
# res <- readRDS("Ariadna_9over10_data.Rds")



# recipe$Analysis$Workflow$Calibration$method
# /home/Earth/abatalla/SUNSET_RS_GIT/sunset/ #



