Skip to content

Commit

Permalink
Add BDN grids (#61)
Browse files Browse the repository at this point in the history
  • Loading branch information
dieghernan committed Jan 5, 2022
1 parent 513f6b7 commit 614d06f
Show file tree
Hide file tree
Showing 11 changed files with 409 additions and 7 deletions.
4 changes: 0 additions & 4 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,6 @@ keywords:
- administrative-boundaries
- ccaa
- static-tiles
- cran
- ggplot2
- ropenspain
- spain
references:
- type: software
title: 'R: A Language and Environment for Statistical Computing'
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export(esp_get_capimun)
export(esp_get_ccaa)
export(esp_get_ccaa_siane)
export(esp_get_country)
export(esp_get_grid_BDN)
export(esp_get_grid_BDN_ccaa)
export(esp_get_grid_MTN)
export(esp_get_grid_ccaa)
export(esp_get_grid_prov)
Expand Down
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
- Rebuild coding database to avoid errors due to encoding.
- New grid functions (#61):
- `esp_get_grid_MTN()`
- `esp_get_grid_BDN()`



Expand Down
145 changes: 145 additions & 0 deletions R/esp_get_grid_BDN.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
#' Get `sf` polygons of the national geographic grids provided by BDN
#'
#' @description
#' Loads a `sf` polygon with the geographic grids of Spain as provided on
#' the Banco de Datos de la Naturaleza (Nature Data Bank), by the
#' Ministry of Environment (MITECO):
#' * [esp_get_grid_BDN()] extracts country-wide grids with resolutions
#' 5x5 or 10x10 kms.
#' * [esp_get_grid_BDN_ccaa()] extracts grids by Autonomous Community with
#' resolution 1x1 km.
#'
#' @family grids
#'
#' @return A `sf` polygon
#'
#'
#' @source BDN data via a custom CDN (see
#' <https://github.com/rOpenSpain/mapSpain/tree/sianedata/MTN>).
#'
#' See original metadata and source on
#' <https://www.miteco.gob.es/es/biodiversidad/servicios/banco-datos-naturaleza/informacion-disponible/bdn-cart-aux-descargas-ccaa.aspx>
#'
#' @export
#'
#' @param resolution Resolution of the grid in kms. Could be `5` or `10`.
#' @param type The scope of the grid. It could be mainland Spain (`"main"`) or
#' the Canary Islands (`"canary"`).
#'
#' @inheritParams esp_get_nuts
#'
#' @inheritSection esp_get_nuts About caching
#' @examplesIf esp_check_access()
#' \donttest{
#' grid <- esp_get_grid_BDN(resolution = "10", type = "main")
#'
#' library(ggplot2)
#'
#' ggplot(grid) +
#' geom_sf() +
#' theme_light() +
#' labs(title = "BDN Grid for Spain")
#' }
esp_get_grid_BDN <- function(resolution = 10,
type = "main",
update_cache = FALSE,
cache_dir = NULL,
verbose = FALSE) {

# Check grid
res <- as.numeric(resolution)

if (!res %in% c(5, 10)) {
stop(
"resolution should be one of 5, 10"
)
}

if (!type %in% c("main", "canary")) {
stop(
"type should be one of 'main', 'canary'"
)
}




# Url
api_entry <- "https://github.com/rOpenSpain/mapSpain/raw/sianedata/MITECO/dist/"

# Filename
if (res == 10) {
filename <- switch(type,
"main" = "Malla10x10_Ter_p.gpkg",
"Malla10x10_Ter_c.gpkg"
)
} else {
filename <- switch(type,
"main" = "Malla_5x5_tierra_p.gpkg",
"Malla_5x5_tierra_c.gpkg"
)
}
result <- esp_hlp_dwnload_sianedata(
api_entry = api_entry,
filename = filename,
cache_dir = cache_dir,
verbose = verbose,
update_cache = update_cache,
cache = TRUE
)

return(result)
}

#' @rdname esp_get_grid_BDN
#' @export
#' @param ccaa A vector of names and/or codes for autonomous communities.
#' See **Details** on [esp_get_ccaa()].
#' @seealso [esp_get_ccaa()]

esp_get_grid_BDN_ccaa <- function(ccaa,
update_cache = FALSE,
cache_dir = NULL,
verbose = FALSE) {


# Get region id

ccaa <- ccaa[!is.na(ccaa)]


region <- ccaa
if (is.null(region)) {
stop("ccaa can't be null")
} else {
nuts_id <- esp_hlp_all2ccaa(region)

nuts_id <- unique(nuts_id)
}

# Check if it is a valid NUTS, if not throws an error

data <- esp_codelist

if (!nuts_id %in% data$nuts2.code) stop(ccaa, " is not a CCAA")


# Switch name. The ids are the same than the NUTS code removing the "ES" part
id <- gsub("ES", "", nuts_id)


api_entry <- "https://github.com/rOpenSpain/mapSpain/raw/sianedata/MITECO/dist/"
filename <- paste0("malla1x1_", id, ".gpkg")

result <- esp_hlp_dwnload_sianedata(
api_entry = api_entry,
filename = filename,
cache_dir = cache_dir,
verbose = verbose,
update_cache = update_cache,
cache = TRUE
)


return(result)
}
100 changes: 100 additions & 0 deletions R/utils_download_sianedata.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
esp_hlp_dwnload_sianedata <- function(api_entry, filename, cache_dir,
verbose, update_cache, cache) {
url <- file.path(api_entry, filename)

cache_dir <- esp_hlp_cachedir(cache_dir)

if (verbose) message("Cache dir is ", cache_dir)

# Create filepath
filepath <- file.path(cache_dir, filename)
localfile <- file.exists(filepath)

if (isFALSE(cache)) {
dwnload <- FALSE
filepath <- url
if (verbose) {
message("Try loading from ", filepath)
}
} else if (update_cache | isFALSE(localfile)) {
dwnload <- TRUE
if (verbose) {
message(
"Downloading file from ",
url,
"\n\nSee https://github.com/rOpenSpain/mapSpain/tree/sianedata/ ",
"for more info"
)
}
if (verbose & update_cache) {
message("\nUpdating cache")
}
} else if (localfile) {
dwnload <- FALSE
if (verbose & isFALSE(update_cache)) {
message("File already available on ", filepath)
}
}

# Downloading
if (dwnload) {
err_dwnload <- try(download.file(url, filepath,
quiet = isFALSE(verbose),
mode = "wb"
), silent = TRUE)

if (inherits(err_dwnload, "try-error")) {
if (verbose) message("Retrying query")
err_dwnload <- try(download.file(url, filepath,
quiet = isFALSE(verbose),
mode = "wb"
), silent = TRUE)
}

# If not then message
if (inherits(err_dwnload, "try-error")) {
message(
"Download failed",
"\n\nurl \n ",
url,
" not reachable.\n\nPlease try with another options. ",
"If you think this ",
"is a bug please consider opening an issue on:",
"\nhttps://github.com/rOpenSpain/mapSpain/issues"
)
stop("\nExecution halted")
} else if (verbose) {
message("Download succesful")
}
}


if (verbose & isTRUE(cache)) {
message("Reading from local file ", filepath)
size <- file.size(filepath)
class(size) <- "object_size"
message(format(size, units = "auto"))
}

# Load

err_onload <- try(
data_sf <- sf::st_read(
filepath,
quiet = isFALSE(verbose),
stringsAsFactors = FALSE
),
silent = TRUE
)

if (inherits(err_onload, "try-error")) {
message(
"File may be corrupt. Please try again using cache = TRUE ",
"and update_cache = TRUE"
)
stop("\nExecution halted")
}

if (verbose) message("File loaded")
return(err_onload)
}
5 changes: 2 additions & 3 deletions codemeta.json
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,8 @@
},
"applicationCategory": "cartography",
"isPartOf": "https://ropenspain.es/",
"keywords": ["rOpenSpain", "tiles", "r", "maps", "spatial", "rstats", "r-package", "municipalities", "Spain", "gisco", "provinces", "ign", "administrative-boundaries", "ccaa", "static-tiles", "spain", "cran", "ropenspain", "ggplot2"],
"fileSize": "2542.155KB",
"keywords": ["rOpenSpain", "tiles", "r", "maps", "spatial", "rstats", "r-package", "municipalities", "Spain", "gisco", "provinces", "ign", "administrative-boundaries", "ccaa", "static-tiles"],
"fileSize": "2545.247KB",
"citation": [
{
"@type": "SoftwareSourceCode",
Expand All @@ -266,7 +266,6 @@
}
],
"releaseNotes": "https://github.com/rOpenSpain/mapSpain/blob/master/NEWS.md",
"readme": "https://github.com/rOpenSpain/mapSpain/blob/main/README.md",
"contIntegration": ["https://github.com/rOpenSpain/mapSpain/actions?query=workflow%3AR-CMD-check", "https://app.codecov.io/gh/rOpenSpain/mapSpain"],
"developmentStatus": "https://www.repostatus.org/#active"
}
Binary file modified data/esp_codelist.rda
Binary file not shown.
Binary file modified data/leaflet.providersESP.df.rda
Binary file not shown.
92 changes: 92 additions & 0 deletions man/esp_get_grid_BDN.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions man/esp_get_grid_MTN.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 614d06f

Please sign in to comment.