# Explore FMI dataset:
## This code has worked under R3.6.1 with module 
## module load GDAL/2.2.1-foss-2015a-GEOS-3.8.0
## on the 14th of October 2022
## Compute climatology for the Herding region by LAUs
rm(list=ls())
# library(maptools) # to plot shp files

library(maptools)
library(CSTools)
library(s2dv)
library(ragg)
library(multiApply)
library(startR)
library(sf)
library(rgeos)
library(multiApply)
library(lubridate)
library(ClimProjDiags)
working_dir <- "/esarchive/scratch/nperez/git/Flor/ArticXchange/"
output_dir <- "/esarchive/scratch/nperez/ArticXChange/"
setwd(working_dir)

mask_fmi <- readRDS(paste0(working_dir, "masks/FMI_Herding_mask.RDS"))
polys <- unique(as.vector(mask_fmi$mask))[-1]
dim(polys) <- c(poly = length(polys))


mask.file_4 <- paste0('region_exploration/LAU/LAU_RG_01M_2020_4326.shp')
shp_4 <- rgdal::readOGR(mask.file_4)
shp_4 <- subset(shp_4, CNTR_CODE == "FI")
## shp_herding <- subset(shp_4, as.numeric(LAU_ID) %in% polys) # R4.1 used to work
# R3.6.1:
shp_herding <- subset(shp_4, LAU_ID %in% sprintf("%03d", polys))
# Subset region
lat_min <- 64#59
lat_max <- 71
lon_min <- 20
lon_max <- 31

library(startR)
path <- "/esarchive/obs/fmi/climgrid/monthly_mean/$var$/$var$_$year$$month$.nc"

tas <- Start(dat = path,
             var = 'tas',
             year = as.character(1993:2021),
             month = sprintf("%02d", 1:12),
             y = 'all',
             x = 'all',
             synonims = list(y = c('y', 'lat', 'latitude'),
                             x = c('x', 'lon', 'longitude')),
             return_vars = list(y = NULL, x = NULL),
             retrieve = TRUE)

ys <- attributes(tas)$Variable$common$y
xs <- attributes(tas)$Variable$common$x

tas_polys <- Apply(list(tas, mask_fmi$mask, polys), 
                   target_dims = list(c('x', 'y'), c('x', 'y'), NULL),
                   function(x, y, z) {
                     mean(x[which(y == z)], na.rm = TRUE)},
                   ncores = 6)$output1
tas_polys <- tas_polys[1,1,,,match(shp_herding@data$LAU_ID, sprintf("%03d", polys))]
tas_polys_clim <- Apply(list(tas_polys), target_dims = 'year', 
                        fun = mean)$output1

library(sf)
library(ggplot2)
#library(ggplot2, lib.loc = .libPaths()[2])
library(RColorBrewer)
library(rgeos)

gusa <- map_data("world")

pals <- brewer.pal(9, 'Reds')[3:9]
pals <- c("#ffffb3",pals,'#525252')

brks <- 0:5
brks <- seq(258, 274, 2)

# LOOP on MONTHS:
plot_poly <- list()
polys_data <- NULL
for (mon in 1:12) { 
## Now fill each polygon with the mean value
  data_pol <- data.frame(data = as.vector(tas_polys_clim[mon,]) - 273.15, 
                         LAU_ID = shp_herding@data$LAU_ID)
  shp_data <- merge(shp_herding, data_pol, by.x="LAU_ID", by.y="LAU_ID")

# Magic lines below that converts SpatialPolygonsDataFrame to normal data frame
  shp_data@data$id <- rownames(shp_data@data)
  df.points <- fortify(shp_data, region = "id")
  df.df <- plyr::join(df.points, shp_data@data, by = "id")

  plot_poly[[mon]] <- ggplot(data = df.df) + 
        geom_polygon(aes(long, lat, group = group),fill = "lightgrey", data = gusa) +
        coord_map(projection = "stereographic",
                  xlim = c(lon_min, lon_max),
                  ylim = c(lat_min, lat_max)) +
        geom_polygon(aes(x = long, y = lat, fill = cut(data, breaks = seq(-14, 18, 2)),
                     group = group), color = "grey",size = 0.08) +
        geom_polygon(aes(x = long, y = lat, group = group), fill = NA,
                    color = "grey", size = 0.5, data = shp_herding) +
        theme_bw() +
        scale_fill_manual(values = c(rev(brewer.pal(9, 'Blues')),  
                                     brewer.pal(8, 'Reds'), "black"), 
                          drop = FALSE, name = 'tas(ºC)') +
        theme(panel.background = element_rect(fill = 'azure'),
              text = element_text(family = "Times")) +  # Colour of ocean
        xlab('Longitude') + ylab('Latitude') +
        scale_x_continuous(breaks = seq(-12, 45, 4),labels = waiver()) +
        scale_y_continuous(breaks = seq(32, 70, 4),labels = waiver()) +
        ggtitle(month.name[mon])# +

  df.df <- cbind(df.df, mon = rep(mon, nrow(df.df)))
  polys_data <- rbind(polys_data, df.df)
print("MON")
print(mon)
print(dim(df.df))
print(dim(polys_data))
}
library(ggpubr)

plot <- ggarrange(plotlist = plot_poly, ncol = 6, nrow = 2, common.legend = TRUE, legend = "bottom")
plot <- annotate_figure(plot, top = text_grob("FMI Grided dataset Monthly clim 1993-2021",
                        color = "black", face = "bold", size = 14))
ggsave("FMI_Herding_clim_polys.jpg", plot, width = 18, height = 13, bg = 'white')

saveRDS(polys_data, file = "FMI_herding_monthly_clim_polygons.RDS")

test <- readRDS("esarchive_exploration/FMI_monthly_clim_polygons.RDS")
