# Load modules
source("modules/Loading/Loading.R")
source("modules/Units/Units.R")
source("modules/Indicators/Indicators.R")

# Read recipe
recipe_file <- 'recipes/examples/recipe_indicators_presentation_2024-09-12.yml'
recipe <- prepare_outputs(recipe_file)

# Load datasets
data_raw <- Loading(recipe)

# Change units: very important to estimate evapotranspiration!
data_units <- Units(recipe, data_raw)

# Obtain SPEI and Malaria indicators according to recipe
result <- Indicators(recipe, data_units)

# plot fcst ensemble mean SPEI
initialm <- as.integer(substr(recipe$Analysis$Time$sdate,1,2))
out.path <- recipe$Run$output_dir
for (mm in 1:6){
    PlotEquiMap(var = drop(MeanDims(result$SPEI$fcst$data, 'ensemble'))[mm,,],
            lon = result$SPEI$fcst$coords$longitude,
            lat = result$SPEI$fcst$coords$latitude,
            intylat = 5,
            intxlon = 4,
            brks = seq(-2,2, length.out = 11),
            cols = c('#543005', '#8c510a', '#bf812d', '#dfc27d', '#f6e8c3', '#c7eae5', '#80cdc1', '#35978f', '#01665e', '#003c30'),
            filled.continents = FALSE,
            toptitle = paste0('SPEI3 2024-', ifelse((mm+initialm-1)<10,'0',''), mm+initialm-1),
            fileout = paste0(out.path, '/user_presentation_plot_fcst_spei3_2024-', ifelse((mm+initialm-1)<10,'0',''), mm+initialm-1 , '.png'),
            colNA = 'grey'
           )
}

# plot observations climatology Malaria
initialm <- as.integer(substr(recipe$Analysis$Time$sdate,1,2))
recipe$Run$output_dir
for (mm in 1:6){
    data <- drop(MeanDims(result$Malaria$p.vivax$obs$data, 'syear'))[mm,,]
    data[which(data == 0)] <- 0.00001 # scale starts at >0
    PlotEquiMap(var = data,
            lon = result$Malaria$p.vivax$obs$coords$longitude,
            lat = result$Malaria$p.vivax$obs$coords$latitude,
            intylat = 5,
            intxlon = 4,
            brks = seq(0,1,0.1),
            triangle_ends = c(FALSE,FALSE),
            filled.continents = FALSE,
            toptitle = paste0('Climate suitability for malaria (P. vivax) 1981-2010 month ', ifelse((mm+initialm-1)<10,'0',''), mm+initialm-1),
            title_scale = 0.8,
            fileout = paste0(out.path, '/user_presentation_plot_obs_malaria-', ifelse((mm+initialm-1)<10,'0',''), mm+initialm-1, '.png'),
            colNA = 'grey'
           )
}