library(urbanR)
library(ncdf4)
# -----  NO2 data:
output_path <- "/esarchive/scratch/nperez/git/Flor/Jan4Nuria/test_regrid_nord3/"
results <- readRDS(paste0(output_path, "bcn_NonUniformGrid.rds"))
receptor <- readRDS(paste0(output_path, "target_uniform_grid_bcn.rds"))
dates <- unique(results$date)

source("/esarchive/scratch/nperez/git/Flor/Jan4Nuria/test_regrid_nord3/regrid_function.R")

index <- array(1:length(dates), c(pos_index = length(dates)))
start.time <- Sys.time()
res <- multiApply::Apply(list(index), fun = regrid, non_uniform_data = results,
                         target_grid = receptor, date = dates, margins = 'pos_index',
                         ncores = 16)
end.time <- Sys.time()
time.taken <- end.time - start.time
time.taken

# Save file:
 nc_path <- output_path
 var_name <- 'NO2'
 var_long_name <- "Nitrogen Dioxide Concentration"
 var_units <- "concentration in percentage"
 proj <- "+proj=longlat +datum=WGS84 +no_defs"
 timedim <- ncdim_def("time", paste("hours since", as.Date(dates[1]), "00:00:00"),
                       index - 1)
  londim <- ncdim_def("lon", "degrees_east", res$lon[,1], longname = 'longitude')
  latdim <- ncdim_def("lat", "degrees_north", res$lat[,1], longname = 'latitude')
  var_def <- ncvar_def(var_name, var_units, list(londim, latdim, timedim),
                       longname = var_long_name)
  ncout <- nc_create(file.path(nc_path, paste0(var_name, "_uniform_mesh_",
                               dates[1], ".nc")),
                     vars = var_def, force_v4 = FALSE)
  ncvar_put(ncout, var_def, res$regular)
  ncatt_put(ncout, var_name, "grid_mapping", "crs")
  ncatt_put(ncout, var_name, "proj4", proj)
  ncatt_put(ncout, 0, "date", as.character(Sys.time()))
  ncatt_put(ncout, 0, "created_by", "regrid development R function CALIOPE-urbanR")
  nc_close(ncout)

