# Try to select closer management regions to LAUs


path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/region_exploration'
setwd(path)
rm(list=ls())
library(abind)
library(multiApply)
library(s2dv)
library(s2dverification)
library(rgdal)
library(plyr)
library(ggplot2)
library(maptools)

path <- '/esarchive/scratch/nperez/git/Flor/ArticXchange/region_exploration'
setwd(path)

mask.file_4 <- paste0(path, '/LAU/LAU_RG_01M_2020_4326.shp')
shp_4 <- rgdal::readOGR(mask.file_4)
shp_4 <- subset(shp_4, CNTR_CODE == "FI")

IDs <- read.table("LAUs_NorthFinland.csv", sep = ',', header = TRUE)
shp_4 <- subset(shp_4, as.numeric(LAU_ID) %in% IDs$LAU.CODE)

shp_Estela <- subset(shp_4, LAU_ID %in% 
                     IDs[which(IDs[,1] == 'FI1D1'), 2])
shp_Pohjois_Savo <- subset(shp_4, LAU_ID %in%
                     IDs[which(IDs[,1] == 'FI1D2'), 2])
shp_Pohjois_Karjala <- subset(shp_4, LAU_ID %in%
                     IDs[which(IDs[,1] == 'FI1D3'), 2])
shp_Keski <- subset(shp_4, LAU_ID %in%
                     IDs[which(IDs[,1] == 'FI1D5'), 2])
shp_Lappi <- subset(shp_4, as.numeric(LAU_ID) %in%
                     IDs[which(IDs[,1] == 'FI1D7'), 2])
shp_Kainuu <- subset(shp_4, as.numeric(LAU_ID) %in%
                     IDs[which(IDs[,1] == 'FI1D8'), 2])
shp_Pohjois_Pohjanmaa <- subset(shp_4, as.numeric(LAU_ID) %in%
                     IDs[which(IDs[,1] == 'FI1D9'), 2])

plot(shp_4)
plot(shp_Estela, col = 'lightblue', add = TRUE)
plot(shp_Pohjois_Savo, col = 'lightgreen', add = TRUE)
plot(shp_Pohjois_Karjala, col = 'lightpink', add = TRUE)
plot(shp_Keski, col = 'orange', add = TRUE)
plot(shp_Lappi, col = 'blue', add = TRUE)
plot(shp_Kainuu, col = 'darkgreen', add = TRUE)
plot(shp_Pohjois_Pohjanmaa, col = 'darkred', add = TRUE)

# Zoom in the north
shp_Pohjois <- shp_Pohjois_Pohjanmaa[c(2, 5, 6, 9, 23, 30),] 
shp_Kainuu_sel <- shp_Kainuu[c(3:5,8),]
shp_4 <- subset(shp_4, as.numeric(LAU_ID) %in% 
                IDs[IDs[,1] %in% c('FI1D7', 'FI1D8', 'FI1D9'),2])
plot(shp_4, main = 'Lappi, Kainuu and Pohjois-Pohjanmaa')
plot(shp_Lappi, col = 'lightblue', add = TRUE)
plot(shp_Pohjois, col = 1:6, add = TRUE)
plot(shp_Kainuu_sel, col = 7:10, add = TRUE)
legend('topright', shp_Pohjois@data$LAU_NAME, 
       title = 'Pohjois-Pohjanmaa', fill = 1:6, bty = 'n')
legend('topleft', shp_Kainuu_sel@data$LAU_NAME, fill = 7:10, bty = 'n',
       title = 'Kainuu')
LAUs_IDs_selected <- c(shp_Lappi@data$LAU_ID, shp_Pohjois@data$LAU_ID,
                       shp_Kainuu_sel@data$LAU_ID)
write.table(LAUs_IDs_selected, "LAUS_IDs_selected.csv", row.names = FALSE,
            col.names = FALSE)
