rm(list=ls())
library(startR)
library(multiApply)

working_dir <- "/esarchive/scratch/nperez/git/Flor/ArticXchange/"
path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/climograph'
setwd(path)

mask_era5L <- readRDS(paste0(working_dir, "masks/ERA5_Lapland_mask.RDS"))


vars <- c('tasmax', 'tasmin', 'tas', 'prlr')

# ERA5Land Subset region
lat_min <- 65#59
lat_max <- 71
lon_min <- 20
lon_max <- 31

reference_period <- 1993:2016

result <- NULL
for (v in 1:length(vars)) {
  if (vars[v] %in% c('tas', 'prlr')) {
    path <- "/esarchive/recon/ecmwf/era5land/monthly_mean/$var$_f1h/$var$_$year$$month$.nc"
  } else {
    path <- "/esarchive/recon/ecmwf/era5land/monthly_mean/$var$_f24h/$var$_$year$$month$.nc"
  }
  datos <- Start(
               dat = path,
               var = vars[v],
               year = as.character(reference_period),
               month = sprintf("%02d", 1:12),
               time = 'all',
               lat = values(list(lat_min, lat_max)),
               lat_reorder = Sort(),
               lon = values(list(lon_min, lon_max)),
               lon_reorder = CircularSort(-180, 180),
               synonims = list(lat = c('lat','latitude'),
                               lon = c('lon','longitude')),
               num_procs = 1,
               return_vars = list(lat = NULL, lon = NULL),
               retrieve = TRUE)
  # Subset Lappland region:
  lats <- attributes(datos)$Variable$common$lat
  lons <- attributes(datos)$Variable$common$lon
  if (vars[v] != 'prlr') {
    clim <- Apply(list(datos, mask_era5L$mask),
                       target_dims = c('lon', 'lat'),
                       function(x, y) {
                          mean(x[which(y == 1)], na.rm = TRUE)})$output1
    clim <- Apply(list(clim), target_dims = 'year', function (x) {
                          mean(x) - 273.15})$output1
  } else {
    clim <- Apply(list(datos, mask_era5L$mask),
                       target_dims = c('lon', 'lat'),
                       function(x, y) {
                          sum(x[which(y == 1)], na.rm = TRUE)})$output1
    clim <- Apply(list(clim), target_dims = 'year', function(x) {
                          mean(x) * 86400000})$output1
  }
print(range(clim))
print(dim(clim))
  result <- abind::abind(result, as.vector(clim), along = 2)  
}

#----------------- CLIMOGRAPH -------------------------
par(mar = c(5.5, 4, 4, 4))
barplot(result[,4], col = "lightgreen", ylab = "Precipitation (mm)",
        names = month.abb[1:12], border = "darkgreen", ylim = c(0, 6000), las = 2)
par(new = TRUE)
plot(1:12, result[,3], col = "darkred", typ = "l",  lwd = 3,
     xaxt = 'n', yaxt = 'n',  ylab = '', xlab = '')
axis(side = 4, at = pretty(range(result[,1])))
mtext("Temperature (ºC)", side = 4, line = 3)
dev.new()
# -------------- Plot Climogrpah -----------------------
#  Including tasmax and tasmin -------------------------
par(mar = c(5.5, 4, 4, 4))
matplot(1:12, result[,1:3], type = 'l', xaxt = 'n',
        col = c('darkred', 'darkblue', 'orange'), xlab = '',
        ylab = 'temperature (degreesC)',
        main = paste('Rovanievi Climatology',
                     paste(range(reference_period), collapse = '-')))
par(new = TRUE)
plot(1:12, result[,4], type = 'h', xaxt = 'n', yaxt = 'n',  ylab = '',
     lwd = 3, col = 'darkgreen', xlab = '')
axis(side = 4, at = pretty(range(result[,4])))
mtext("Total precipitation (mm)", side=4, line = 3)
axis(1, 1:12, month.name, las = 2)
legend('topleft', vars, col = c('darkred', 'darkblue', 'orange', 'darkgreen'),
       pch = 16, bty = 'n')
# -------------------------------------
dev.new()
par(mar = c(5.5, 4, 4, 4))
barplot(result[,4], col = "lightgreen", ylab = "Precipitation (mm)",
        names = month.abb[1:12], border = "darkgreen", ylim = c(0, 6000), las = 2,
        main = "ERA5 Land (1993-2016) Rovaniemi")
par(new = TRUE)
matplot(1:12, result[,1:3], col = c("darkred", "darkblue", "orange"), 
        typ = "l",  lwd = 3,
        xaxt = 'n', yaxt = 'n',  ylab = '', xlab = '')
axis(side = 4, at = pretty(range(result[,1])))
mtext("Temperature (ºC)", side = 4, line = 3)

