## ############################################################################
##
## The 2024 Lancet Countdown in Europe report
## Indicator 1.3.6: Climatic Suitability for Ticks
##
## Script 03: Collect environmental suitability weights
## 
## Authors: 
## - Martín Lotto Batista, ORCID: 0000-0002-9437-5270
## - Prof. Rachel Lowe, ORCID: 0000-0003-3939-7343
##
## Contact: martin.lotto@bsc.es
## 
## ############################################################################

#' NOT RUN
#' This script is designed for parallelisation using SLURM. It calculates the 
#' number of suitable CORINE Land Cover cells (resolution 100m) within each 
#' ERA5-Land cell (resolution 9km), representing the proportion of environmental 
#' suitability used as weights in computing the overall suitability of the 
#' tick indicator.

args = commandArgs(trailingOnly=TRUE)

# Package
library(raster)

# Data
env <- raster("copernicus_4326_2019.tif")
era5 <- raster("era5_template.tif")  # ERA5-Land template

# Arguments to split the map
xmin <- as.integer(args[1])
xmax <- as.integer(args[2])
ymin <- as.integer(args[3])
ymax <- as.integer(args[4])

bit <- crop(env, extent(xmin, xmax, ymin, ymax))
bit.template <- crop(era5, extent(xmin, xmax, ymin, ymax))

m <- c(-1, 1,NA, 
       1,2,1, # Discontinuous urban fabric (9.4%)
       2,17,NA,
       17,18,1, # Pastures (5.4%)
       18,22,NA,
       22,24,1, # Board-leaf and coniferous forests (23%)
       24,26,NA,
       26,27,1, # Moors and heathland (29%)
       27,150,NA)

rclmat <- matrix(m, ncol=3, byrow=TRUE)
suit <- reclassify(bit, rclmat)

# Count all the points of CORINE per ERA5-Land cell
baseSuitCoords <- coordinates(suit)

baseCounts <- table(cellFromXY(bit.template, baseSuitCoords))

baseBG <- bit.template
baseBG[] <- 0 
baseBG[as.numeric(names(baseCounts))] <- baseCounts
rm(baseSuitCoords)
rm(baseCounts)
gc()

# Count CORINE suitable points ERA5-Land cell
suitCoords <- coordinates(suit)[!is.na(as.vector(suit)),]
counts <- table(cellFromXY(bit.template, suitCoords))

bg <- bit.template
bg[] <- 0 
bg[as.numeric(names(counts))] <- counts
rm(suitCoords)
rm(counts)
gc()

# Calculate weights
w <- bg/baseBG
w[w==0] <- NA

# Save raster
writeRaster(w, paste0("out/weight_", args[5], ".tif"), 
            format="GTiff",     
            options=c("INTERLEAVE=BAND","COMPRESS=LZW"),
            overwrite=TRUE)

# END