‘KrigR’ over Brazil

Applying Kriging of ECVs on Brazil health regions

true , Otavio Ranzani https://github.com/oranzani (ISGlobal)https://www.isglobal.org
2021-07-22

1 Loading Necessary Packages

Show code
atreyu_pal <- c("#FE2C01", "#AD4625", "#AE6146", "#C8582B", "#F06B20",
    "#02B1DC", "#02729B", "#2992B9", "#2986AD", "#2C5C7F")
baroness_pal <- c("#D17775", "#9E684D", "#C76938", "#CF5E1B", "#C0703F",
    "#EE9D35", "#B37314", "#FDCC1B", "#98213B", "#9E2326")
baroness_pal_seq <- c("#9E2326", "#98213B", "#D17775", "#EE9D35", "#FDCC1B")
atreyu_pal_seq <- c("#FE2C01", "#F06B20", "#C8582B", "#02729B", "#02B1DC")
atreyu_baroness_pal <- c("#FDCC1B", "#EE9D35", "#F06B20", "#FE2C01", "#D17775",
    "#98213B")

source("functions/plot_func.R")

library("tidyr")  # for turning rasters into ggplot-dataframes
library("ggplot2")  # for plotting
library("viridis")  # colour palettes
library("cowplot")  # gridding multiple plots
library("ggmap")  # obtaining google maps
library("gimms")  # to get some pre-existing data to match in our downscaling
library("geobr")  # To get all-possible Brazilian Shapefiles
library("dplyr")  # Manipulating data

# API_user<-'XXXX' API_key<-'XXXXXXXXXXX'

## Easy to get a API_user and API_key on ERA5,
## https://confluence.ecmwf.int/display/CKB/ERA5%3A+data+documentation

Dir.Base <- getwd()  # identifying the current directory
Dir.Data <- file.path(Dir.Base, "Data")  # folder path for data
Dir.Shapes <- file.path(Dir.Data, "Shapes")  # folder path for shapefiles
Dirs <- sapply(c(Dir.Data, Dir.Shapes), function(x) if (!dir.exists(x)) dir.create(x))

2 Downloading the data for Brazil

2.1 The geobr package

The geobr package can give us a very useful way to download shapefiles from Brazil, bellow we downloaded the municipalities for the state of São Paulo

Show code
library(ggplot2)
# Remove plot axis
no_axis <- theme(axis.title = element_blank(), axis.text = element_blank(),
    axis.ticks = element_blank())

# Download all municipalities of Rio
all_muni <- read_municipality(year = 2010, showProgress = FALSE)
all_metro <- read_metro_area(year = 2018, showProgress = FALSE)

# plot
all_muni_plot <- ggplot() + geom_sf(data = all_muni, color = baroness_pal_seq[1],
    fill = baroness_pal_seq[5], size = 0.15, show.legend = FALSE, alpha = 0.5) +
    geom_sf(data = all_metro, fill = atreyu_baroness_pal[4], color = baroness_pal_seq[1],
        size = 0.15, show.legend = FALSE) + labs(subtitle = "Municipalities of Brazil, 2010, in 'Blue'",
    caption = "Metropolitan Areas of Brazil, 2018, in 'Gold'", size = 8) +
    theme_minimal() + no_axis
all_muni_plot

2.2 The KrigR shapefiles

A way to work with KrigR is by downloading shapefiles from regionalities in Brazil, as we did before. This shapefiles, or in the format of extent or simplefeature objects, can be passed to the KrigR function and with this pick the ECVs desired.

3 Kriging over Specific Regions

First we set a shape of the region we wanna, I wanna get my birth city the day in my aniversary of last year, São Paulo. I’ll get the metropolitan area around São Paulo too. So from geobr we proceed as follows:

Show code
library(rgdal)
library(dplyr)

# dir.create(path = 'Data/Shapes/geobr_municipalities/')

Dir.StateShp <- file.path(Dir.Data, "State_Shape")
dir.create(Dir.StateShp)

# São Paulo City
sp_name_muni <- which(all_muni$name_muni == "São Paulo")
sp_sf_muni <- all_muni[sp_name_muni, ]
sp_metro_name <- which(all_metro$name_metro == "RM São Paulo")
sp_sf_metro <- all_metro[sp_metro_name, ]
sp_sf_plt <- ggplot() + geom_sf(data = sp_sf_metro, fill = baroness_pal_seq[5],
    color = baroness_pal_seq[1], size = 0.15, show.legend = FALSE) + geom_sf(data = sp_sf_muni,
    color = baroness_pal_seq[5], fill = baroness_pal_seq[1], size = 0.15,
    show.legend = FALSE) + labs(subtitle = "Municipalities of São Paulo, 2010",
    caption = "Metro Area of São Paulo, 2018", size = 8) + theme_minimal() +
    no_axis
sp_sf_plt

3.1 ERA5 Downloading data

Now we take the climate data from ERA5 dataset.

First for the São Paulo Municipality:

Show code
library(KrigR)
# Converting sf into extent
sp_sf_muni_extent<-extent(x = sp_sf_muni) # Transforming sf into a extent object
sp_sf_muni_raw<-download_ERA(
  Variable = '2m_temperature', # Specifying the climate variable
  DataSet = 'era5-land', # specifying the DataSet
  DateStart = '1989-10-12', # Date Start
  DateStop = '1989-10-14', # Date Stop
  TResolution = 'day', # Time Resolution
  TStep = 1, # Time Step
  Extent = sp_sf_muni_extent, # Passing the extent object, or shape.file object
  Dir = Dir.StateShp, # Directory to be saved the .nc files
  API_User = API_user, # User API
  API_Key = API_key, # Key API
  verbose = FALSE)

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |============================================================| 100%
Show code
sp_muni_raw_plt<-Plot_Raw(sp_sf_muni_raw, 
                          Shp = sp_sf_muni, 
                          Dates = c("1989-10-12", "1989-10-13", "1989-10-14"))
sp_muni_raw_plt

Secondly, for the São Paulo metropolitan area:

Show code
sp_sf_metro_extent <- extent(x = sp_sf_metro)  # Transforming sf into a extent object
sp_sf_metro_raw <- download_ERA(Variable = "2m_temperature", DataSet = "era5-land",
    DateStart = "1989-10-12", DateStop = "1989-10-14", TResolution = "day",
    TStep = 1, Extent = sp_sf_metro_extent, Dir = Dir.StateShp, API_User = API_user,
    API_Key = API_key, verbose = FALSE)

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |=================                                           |  29%
  |                                                                  
  |===================================                         |  59%
  |                                                                  
  |============================================================| 100%
Show code
sp_metro_raw_plt <- Plot_Raw(sp_sf_metro_raw, Shp = sp_sf_metro, Dates = c("1989-10-12",
    "1989-10-13", "1989-10-14"))
sp_metro_raw_plt

3.2 DEM Downloading data

After this we get the covariates to help on kriging from the same shape, we use here the tutorial standard, which is the elevation data from the USGS DEM, a global elevation model. With the help from the elevation we can now downscale the temperature to a more grained resolution, the way to do it is by taking the elevation resolution, which is more fine and give this resolution as a helper to the estimate the temperature, or the ECV used, standard error in the starting resolution. By knowing this relation we can estimate back the temperature in the wanted finer resolution, which is given by the finer elevation resolution here.

The Kriging process follows as bellow:

First we take the elevation data at the same polygon area of the temperature data we got:

Show code
Covs_ls_sp_muni <- download_DEM(
  Train_ras = sp_sf_muni_raw, # Start resolution, we give the temperature raw ERA5 resolution
  Target_res = .02, # Resolution wanted
  Shape = sp_sf_muni, # Shape file as before
  Dir = Dir.StateShp, # Directory to save
  Keep_Temporary = TRUE) # Keep the files
Covs_ls_sp_metro <- download_DEM(
  Train_ras = sp_sf_metro_raw,
  Target_res = .02,
  Shape = sp_sf_metro,
  Dir = Dir.StateShp,
  Keep_Temporary = TRUE)

São Paulo elevation data for the municipality and the metropolitan area:

Show code
sp_muni_covs_plt<-Plot_Covs(
  Covs_ls_sp_muni, # Covariable data
  Shp = sp_sf_muni) # Shape file data
sp_metro_covs_plt<-Plot_Covs(
  Covs_ls_sp_metro, 
  Shp = sp_sf_metro)
sp_muni_covs_plt # SP Municipality elevation data
Show code
sp_metro_covs_plt # SP Metropolitan area elevation data

3.3 Kriging

Now we input those elevation data into the KrigR function, as said before, this we take the resolution for the elevation data, given at the same resolution for the temperature and for a finer resolution, learn the relationship between this two data and its errors, and applying a statistical downscalling to the temperature data, aiming to gain finer resolution.

Show code
sp_muni_Krig <- krigR(
  Data = sp_sf_muni_raw, # what to krig
  Covariates_coarse = Covs_ls_sp_muni[[1]], # covariates at training resolution
  Covariates_fine = Covs_ls_sp_muni[[2]], # covariates at target resolution
  Keep_Temporary = FALSE, # delete temporary krigs of layers
  Cores = 1, # only run this on 1 core
  FileName = "sp_muni_Shape.nc", # save the finished file as this
  Dir = Dir.StateShp, # where to save the output
  verbose = FALSE # Stop Talking
  )
[1] "Commencing Kriging"
[1] "Kriging of remaining 2 data layers should finish around: 2021-07-22 16:16:57"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%
Show code
sp_metro_Krig <- krigR(
  Data = sp_sf_metro_raw, # what to krig
  Covariates_coarse = Covs_ls_sp_metro[[1]], # covariates at training resolution
  Covariates_fine = Covs_ls_sp_metro[[2]], # covariates at target resolution
  Keep_Temporary = FALSE, # delete temporary krigs of layers
  Cores = 1, # only run this on 1 core
  FileName = "sp_metro_Shape.nc", # save the finished file as this
  Dir = Dir.StateShp, # where to save the output
  verbose = FALSE # Stop Talking
)
[1] "Commencing Kriging"
[1] "Kriging of remaining 2 data layers should finish around: 2021-07-22 16:16:58"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%

And we plot the final resolution for the 2m temperature for the two regions, note that are some patterns in the standard error estimation, this is normal due to the nature of the downscalling process, which assumes constant relation over the whole area. Areas with less data will suffer and can generate those patterns, besides this the amount of this patterns and its deviation are of the scale of centigrade of Celsius.

Show code
sp_muni_krig_plt <- Plot_Krigs(sp_muni_Krig, Shp = sp_sf_muni, Dates = c("1989-10-12",
    "1989-10-13", "1989-10-14"))
sp_metro_krig_plt <- Plot_Krigs(sp_metro_Krig, Shp = sp_sf_metro, Dates = c("1989-10-12",
    "1989-10-13", "1989-10-14"))
sp_muni_krig_plt
Show code
sp_metro_krig_plt

4 Kriging by Pipeline

Now, we wanna make all the kriging process in one step, to do so we use the features implemented in the function that makes the previous steps to be wrapped inside the KrigR function:

First we set a directory where the function will leak the files produced in each step of the process, the files for temperature, elevation and finally the kriging:

Show code
# We create a directory to krigR function leak on
Dir.StatePipe <- file.path(Dir.Data, "Sp_Pipe")
dir.create(Dir.StatePipe)

And we proceed to the specification to the KrigR pipeline, inside the function:

Show code
pipe_sp_muni<-krigR(
  Variable = '2m_temperature', # Variable we want to krig
  Type = 'reanalysis', # Type of the product we are taking
  DataSet = 'era5-land', # DataSet
  DateStart = '2020-10-12', # Date Start
  DateStop = '2020-10-14', # Date Stop 
  TResolution = 'day', # Time Resolution
  TStep = 1, # Time Step
  Extent = sp_sf_muni_extent, # Shape.file or extent of the area to be Krig
  API_User = API_user, # USER API
  API_Key = API_key, # Key API 
  Target_res = .02, # Target resolution for the variable
  Cores = 1, # Cores to be used in the process
  FileName = "Sp_pipe_muni.nc", # File names
  Dir = Dir.StatePipe, verbose = FALSE) # Directory and Verbose parameter

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |============================================================| 100%
[1] "Commencing Kriging"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%
Show code
pipe_sp_metro<-krigR(
  Variable = '2m_temperature',
  Type = 'reanalysis',
  DataSet = 'era5-land',
  DateStart = '2020-10-12',
  DateStop = '2020-10-14',
  TResolution = 'day',
  TStep = 1,
  Extent = sp_sf_metro_extent,
  API_User = API_user,
  API_Key = API_key,
  Target_res = .02,
  Cores = 1,
  FileName = "Sp_pipe_metro.nc",
  Dir = Dir.StatePipe, verbose = FALSE)

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |=================                                           |  29%
  |                                                                  
  |===================================                         |  59%
  |                                                                  
  |============================================================| 100%
[1] "Commencing Kriging"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%

Before we plot, we can take a look on the objects generated in the process of kriging by the pipeline into the function, it is the same of the section 3.3, the file has one more element on it. This element is the Calls list, and keep track of the whole process did in the pipeline way with the KrigR function.

Show code
pipe_sp_muni$Call
$Data
$Data$Class
[1] "RasterBrick"
attr(,"package")
[1] "raster"

$Data$Dimensions
$Data$Dimensions$nrow
[1] 9

$Data$Dimensions$ncol
[1] 7

$Data$Dimensions$ncell
[1] 63


$Data$Extent
class      : Extent 
xmin       : -46.97708 
xmax       : -46.27592 
ymin       : -24.158 
ymax       : -23.258 

$Data$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Data$layers
[1] "index_1" "index_2" "index_3"


$Covariates_coarse
$Covariates_coarse$Class
[1] "RasterLayer"
attr(,"package")
[1] "raster"

$Covariates_coarse$Dimensions
$Covariates_coarse$Dimensions$nrow
[1] 9

$Covariates_coarse$Dimensions$ncol
[1] 7

$Covariates_coarse$Dimensions$ncell
[1] 63


$Covariates_coarse$Extent
class      : Extent 
xmin       : -46.97708 
xmax       : -46.27592 
ymin       : -24.158 
ymax       : -23.258 

$Covariates_coarse$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Covariates_coarse$layers
[1] "DEM"


$Covariates_fine
$Covariates_fine$Class
[1] "RasterLayer"
attr(,"package")
[1] "raster"

$Covariates_fine$Dimensions
$Covariates_fine$Dimensions$nrow
[1] 54

$Covariates_fine$Dimensions$ncol
[1] 42

$Covariates_fine$Dimensions$ncell
[1] 2268


$Covariates_fine$Extent
class      : Extent 
xmin       : -46.97514 
xmax       : -46.27514 
ymin       : -24.15847 
ymax       : -23.25847 

$Covariates_fine$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Covariates_fine$layers
[1] "DEM"


$KrigingEquation
ERA ~ DEM
<environment: 0x5601fb87ba28>

$Cores
[1] 1

$FileName
[1] "Sp_pipe_muni.nc"

$Keep_Temporary
[1] TRUE

$nmax
[1] Inf

$Data_Retrieval
$Data_Retrieval$Variable
[1] "2m_temperature"

$Data_Retrieval$Type
[1] "reanalysis"

$Data_Retrieval$PrecipFix
[1] FALSE

$Data_Retrieval$DataSet
[1] "era5-land"

$Data_Retrieval$DateStart
[1] "2020-10-12"

$Data_Retrieval$DateStop
[1] "2020-10-14"

$Data_Retrieval$TResolution
[1] "day"

$Data_Retrieval$TStep
[1] 1

$Data_Retrieval$Extent
class      : Extent 
xmin       : -46.82619 
xmax       : -46.36531 
ymin       : -24.00826 
ymax       : -23.35629 
Show code
pipe_sp_metro$Call
$Data
$Data$Class
[1] "RasterBrick"
attr(,"package")
[1] "raster"

$Data$Dimensions
$Data$Dimensions$nrow
[1] 10

$Data$Dimensions$ncol
[1] 18

$Data$Dimensions$ncell
[1] 180


$Data$Extent
class      : Extent 
xmin       : -47.35903 
xmax       : -45.55797 
ymin       : -24.114 
ymax       : -23.114 

$Data$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Data$layers
[1] "index_1" "index_2" "index_3"


$Covariates_coarse
$Covariates_coarse$Class
[1] "RasterLayer"
attr(,"package")
[1] "raster"

$Covariates_coarse$Dimensions
$Covariates_coarse$Dimensions$nrow
[1] 10

$Covariates_coarse$Dimensions$ncol
[1] 18

$Covariates_coarse$Dimensions$ncell
[1] 180


$Covariates_coarse$Extent
class      : Extent 
xmin       : -47.35903 
xmax       : -45.55797 
ymin       : -24.114 
ymax       : -23.114 

$Covariates_coarse$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Covariates_coarse$layers
[1] "DEM"


$Covariates_fine
$Covariates_fine$Class
[1] "RasterLayer"
attr(,"package")
[1] "raster"

$Covariates_fine$Dimensions
$Covariates_fine$Dimensions$nrow
[1] 60

$Covariates_fine$Dimensions$ncol
[1] 108

$Covariates_fine$Dimensions$ncell
[1] 6480


$Covariates_fine$Extent
class      : Extent 
xmin       : -47.35847 
xmax       : -45.55847 
ymin       : -24.11681 
ymax       : -23.11681 

$Covariates_fine$CRS
CRS arguments: +proj=longlat +datum=WGS84 +no_defs 

$Covariates_fine$layers
[1] "DEM"


$KrigingEquation
ERA ~ DEM
<environment: 0x560200f52438>

$Cores
[1] 1

$FileName
[1] "Sp_pipe_metro.nc"

$Keep_Temporary
[1] TRUE

$nmax
[1] Inf

$Data_Retrieval
$Data_Retrieval$Variable
[1] "2m_temperature"

$Data_Retrieval$Type
[1] "reanalysis"

$Data_Retrieval$PrecipFix
[1] FALSE

$Data_Retrieval$DataSet
[1] "era5-land"

$Data_Retrieval$DateStart
[1] "2020-10-12"

$Data_Retrieval$DateStop
[1] "2020-10-14"

$Data_Retrieval$TResolution
[1] "day"

$Data_Retrieval$TStep
[1] 1

$Data_Retrieval$Extent
class      : Extent 
xmin       : -47.20852 
xmax       : -45.69481 
ymin       : -24.06425 
ymax       : -23.18344 
Show code
sp_pipe_muni_plt<-Plot_Krigs(
  pipe_sp_muni[-3], # Excluding the named list that come with the krig function, its relates all of the parameters used in the process   
  Shp = sp_sf_muni, 
  Dates = c("2020-10-12", "2020-10-13", "2020-10-14"))
sp_pipe_metro_plt<-Plot_Krigs(
  pipe_sp_metro[-3], 
  Shp = sp_sf_metro, 
  Dates = c("2020-10-12", "2020-10-13", "2020-10-14"))
sp_pipe_muni_plt
Show code
sp_pipe_metro_plt

5 Kriging with point data

We can make use of point data to krig too, for our interests we can, for example, kriging around a specified hospital. This will give us a more accurate kriging around the point data specified and will give us a way to validate those data.

First we take and plot hospitals point data for Brazil as whole:

Show code
# Loading all hospitals and healt facilities of Brazil
all_hosp <- read_health_facilities(showProgress = FALSE)
all_hosp_plt <- ggplot() + geom_sf(data = all_muni, color = baroness_pal_seq[1],
    fill = baroness_pal_seq[5], size = 0.15, show.legend = FALSE, alpha = 0.5) +
    geom_sf(data = all_hosp, color = atreyu_baroness_pal[4], size = 0.01,
        show.legend = FALSE) + labs(subtitle = "Municipalities of Brazil, 2010, in 'Yellow'",
    caption = "Hospital and Health facilities of Brazil, 2015, 'Orange'",
    size = 8) + theme_minimal() + no_axis
all_hosp_plt

Yeah! There are too many facilities, but remember there not only hospitals but any health facilities.

After for the areas we are working, São Paulo municipality and São Paulo metropolitan area:

Show code
# Loading São Paulo municipality and metropolitan area SP
# municipality hospitals and health units
sp_muni_hosp <- which(all_hosp$code_muni == 355030)
sp_muni_hosp <- all_hosp[sp_muni_hosp, ]

# SP metropolitan area hospitals and health units
sp_metro_hosp <- as.numeric(substr(sp_sf_metro$code_muni, start = 1, stop = 6))
sp_metro_hosp <- which(all_hosp$code_muni %in% sp_metro_hosp)
sp_metro_hosp <- all_hosp[sp_metro_hosp, ]

# sp municipality map and hospitals
sp_muni_hosp_plt <- ggplot() + geom_sf(data = sp_sf_muni, color = baroness_pal_seq[1],
    fill = baroness_pal_seq[5], size = 0.15, show.legend = FALSE, alpha = 0.5) +
    geom_sf(data = sp_muni_hosp, color = atreyu_baroness_pal[4], size = 0.01,
        show.legend = FALSE) + labs(subtitle = "São Paulo Municipality, 2010, in 'Yellow'",
    caption = "Hospital and Health facilities, 2015, 'Orange'", size = 8) +
    theme_minimal() + no_axis

# sp metropolitan area map and hospitals
sp_metro_hosp_plt <- ggplot() + geom_sf(data = sp_sf_metro, color = baroness_pal_seq[1],
    fill = baroness_pal_seq[5], size = 0.15, show.legend = FALSE, alpha = 0.5) +
    geom_sf(data = sp_metro_hosp, color = atreyu_baroness_pal[4], size = 0.01,
        show.legend = FALSE) + labs(subtitle = "São Paulo Metropolitan Area, 2010, in 'Yellow'",
    caption = "Hospital and Health facilities, 2015, 'Orange'", size = 8) +
    theme_minimal() + no_axis

sp_muni_hosp_plt
Show code
sp_metro_hosp_plt

Now let’s Krig with those points data, we use the pipeline scheme from the section 4. We had to add some features, to specify that we are kriging over data points in the pipe, so we have the following.

First for a sample of health facilities in the municipality of São Paulo:

Show code
# A directory to keep the leak of the pipe
Dir.Points <- file.path(Dir.Data, "Point_Data")
dir.create(Dir.Points)

sp_muni_hosp_test<-sample(sp_muni_hosp$code_cnes, size = 60)
sp_muni_hosp_test<-sp_muni_hosp[sp_muni_hosp$code_cnes %in% sp_muni_hosp_test,]
sp_muni_hosp_df<-as.data.frame(as(sp_muni_hosp_test, "Spatial"))
sp_muni_hosp_df<-sp_muni_hosp_df %>% 
  select(code_cnes, coords.x1, coords.x2) %>% 
  setNames(c("ID", "Lon", "Lat"))

# The pipe kriging
## SP municipality
sp_muni_hosp_krig<-krigR(Variable = '2m_temperature',
    DataSet = 'era5-land',
    Type = "reanalysis", 
    DateStart = '2020-10-12',
    DateStop = '2020-10-14',
    TResolution = 'day', # This has to match in integer time steps with the interval give above
    TStep = 1, 
    Extent = sp_muni_hosp_df, # the point data with Lon and Lat columns
    Buffer = 0.001, # a 0.001 degree buffer should be drawn around each point
    ID = "ID", # this is the column which holds point IDs
    API_User = API_user,
    API_Key = API_key,
    Target_res = .02,
    Cores = 1, # to accelerate things we are using all disposable cores minus 1
    maxdist = 0.1,
    FileName = "sp_muni_points.nc",
    Keep_Temporary = TRUE, # We choose to not keep the temporary files for the kriging with buffer
    verbose = FALSE)

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |=============                                               |  22%
  |                                                                  
  |===========================                                 |  45%
  |                                                                  
  |============================================================| 100%
[1] "Commencing Kriging"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%

And for the metropolitan São Paulo area:

Show code
sp_metro_hosp_test<-sample(sp_metro_hosp$code_cnes, size = 60)
sp_metro_hosp_test<-sp_metro_hosp[sp_metro_hosp$code_cnes %in% sp_metro_hosp_test,]
sp_metro_hosp_df<-as.data.frame(as(sp_metro_hosp_test, "Spatial"))
sp_metro_hosp_df<-sp_metro_hosp_df %>% 
  select(code_cnes, coords.x1, coords.x2) %>% 
  setNames(c("ID", "Lon", "Lat"))

## SP metropolitan Area
sp_metro_hosp_krig<-krigR(Variable = '2m_temperature',
    DataSet = 'era5-land',
    Type = "reanalysis", 
    DateStart = '2020-10-12',
    DateStop = '2020-10-14',
    TResolution = 'day', # This has to match in integer time steps with the interval give above
    TStep = 1, 
    Extent = sp_metro_hosp_df, # the point data with Lon and Lat columns
    Buffer = 0.001, # a 0.1 degree buffer should be drawn around each point
    ID = "ID", # this is the column which holds point IDs
    API_User = API_user,
    API_Key = API_key,
    Target_res = .02,
    Cores = 1, # to accelerate things we are using all disposable cores minus 1
    maxdist = 0.1,
    FileName = "sp_metro_points.nc",
    Keep_Temporary = TRUE, verbose = FALSE)

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |=========                                                   |  16%
  |                                                                  
  |===================                                         |  32%
  |                                                                  
  |=================================================           |  81%
  |                                                                  
  |=========================================================== |  98%
  |                                                                  
  |============================================================| 100%
[1] "Commencing Kriging"

  |                                                                  
  |                                                            |   0%
  |                                                                  
  |====================                                        |  33%
  |                                                                  
  |========================================                    |  67%
  |                                                                  
  |============================================================| 100%

The plots of each region that we buffered:

Show code
sp_muni_hosp_krig_plot <- Plot_Krigs(sp_muni_hosp_krig, Shp = sp_sf_muni,
    Dates = c("2020-10-12", "2020-10-13", "2020-10-14"), Shp.Col = baroness_pal_seq[1])
sp_metro_hosp_krig_plot <- Plot_Krigs(sp_metro_hosp_krig, Shp = sp_sf_metro,
    Dates = c("2020-10-12", "2020-10-13", "2020-10-14"), Shp.Col = baroness_pal_seq[1])
sp_muni_hosp_krig_plot
Show code
sp_metro_hosp_krig_plot

So we have a krigged around a sample of points for the health facilities of São Paulo Municipality and São Paulo Metropolitan Area. It is difficult to note and compare, but using the buffer pipeline, we can take more accurate kriging downscalling for the temperature around the health unit. This will help a more accurate association between mortality and temperature, for example.