# ----------- The target grid is already created and saved with this code ---------------------
# ---- Create uniform grid:I
crs_sim = "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"
spatial_context <- context_sp(geom_path = '/esarchive/scratch/jbenavides/data/geom/')
config <- NULL
config$crs_sim <- "+proj=utm +zone=31 +ellps=intl +units=m +no_defs"
receptor_grid <- sf::st_sf(geom=sf::st_make_grid(spatial_context,
                     cellsize = 10, what = "centers"), crs=config$crs_sim)
## add coordinates required for plotting
receptor_grid$data <- cbind(receptor_grid$data,
                            Coord_X = sf::st_coordinates(receptor_grid)[,1],
                            Coord_Y = sf::st_coordinates(receptor_grid)[,2])
receptor_grid$Coord_X <- sf::st_coordinates(receptor_grid)[,1]
receptor_grid$Coord_Y <- sf::st_coordinates(receptor_grid)[,2]
receptor <- data.frame(receptor_grid$data[,c("Coord_X", "Coord_Y")],
                     NO2 = rep(NA, 2383800))
receptor <- sp::SpatialPointsDataFrame(receptor[,c("Coord_X", "Coord_Y")],
             receptor)
sp::proj4string(receptor) <- crs_sim
receptor <- sp::spTransform(receptor, sp::CRS("+proj=longlat"))
lon_min <- 2.051908 # min(receptor@coords[,1])
lon_max <- 2.22716 # max(receptor@coords[,1])
lat_min <- 41.31932 # min(receptor@coords[,2])
lat_max <- 41.46859 # max(receptor@coords[,2])

lon <- seq(lon_min, lon_max, (lon_max - lon_min)/1449)
lat <- seq(lat_min, lat_max, (lat_max - lat_min)/1643)

lons <- rep(lon, length(lat))
lats <- sort(rep(lat, length(lon)))
receptor <- data.frame(lon = lons, lat = lats, NO2 = rep(NA, length(lons)))
receptor <- sp::SpatialPointsDataFrame(receptor[,c("lon", "lat")],
             receptor)
sp::proj4string(receptor) <- sp::CRS("+proj=longlat")
receptor <- sp::spTransform(receptor, crs_sim)
output_path <- "/esarchive/scratch/nperez/git/Flor/Jan4Nuria/"
saveRDS(receptor, file = paste0(output_path, "target_uniform_grid_bcn.rds"))
library(ggplot2)
ggplot(data = receptor@data, aes(x = lon, y = lat)) + geom_point()

