diff --git a/CLAUDE.md b/CLAUDE.md index e1b0ad2..23c7d1d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -93,19 +93,21 @@ serialization cheap. `stopForInvalidBackend()` centralizes the error path. ### SQLite schema -The index at `inst/extdata/ClimateNA_tiles.sqlite` holds four tile tables, -`tiles_historical`, `tiles_historical_normals`, `tiles_future`, `tiles_future_normals`: one row -per tile, subset and year or period, referring to its zip in the `archives` table by id -(`archive`). Archives are grouped by decade, so many rows share one. A view named for each type -(`historical`, ...) joins them back into the columns readers use (`zipfile`, `archived`, `key`, -`uploaded`); `ClimateNA_sql()` reads the view, and writers append to `tiles_`. `key` is the -archive's object key in the bucket (its URL is `release.base_url` + `/` + `key`). Storing the -paths once per archive, not once per row, keeps the index at 20 MB, from 52 MB. -`sqlite_connect_db()` -sets a 60s busy timeout before anything else; lookups (`readonly = TRUE`) open the file -read-only, and writing connections switch a file to WAL only when they create it. The shipped -index is left in rollback-journal mode (`build_index()` in `data-raw/pipeline/R/index.R`), so -read-only lookups work from a library folder the user cannot write to. +Each data release has its own index: `inst/extdata/ClimateNA_tiles_1arcmin.sqlite` and +`ClimateNA_tiles_3arcmin.sqlite`. `ClimateNA_tiles_sqlite()` returns the one +`options(climateData.resolution)` names (`"1arcmin"` by default, set in `.onLoad()`). Each holds +four tile tables, `tiles_historical`, `tiles_historical_normals`, `tiles_future`, +`tiles_future_normals`: one row per tile, subset and year or period, referring to its zip in the +`archives` table by id (`archive`). Archives are grouped by decade, so many rows share one. A view +named for each type (`historical`, ...) joins them back into the columns readers use (`zipfile`, +`archived`, `key`, `uploaded`); `ClimateNA_sql()` reads the view, and writers append to +`tiles_`. `key` is the archive's object key in the bucket (its URL is `release.base_url` + +`/` + `key`). Storing the paths once per archive, not once per row, keeps each index at about +20 MB, from 52 MB. `sqlite_connect_db()` opens lookups (`readonly = TRUE`) with SQLite's +`immutable=1` (no locks, nothing written beside the file); writing connections set a 60s busy +timeout first and switch a file to WAL only when they create it. The shipped indexes are left in +rollback-journal mode (`build_index()` in `data-raw/pipeline/R/index.R`), so read-only lookups work +from a library folder the user cannot write to. Indexes from before climateData 2.3.0 may hold `checksums_` tables, written by the Windows-era build scripts (removed in 2.3.0); the pipeline's index has none. Don't assume they diff --git a/NEWS.md b/NEWS.md index a7cac39..f88a118 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,20 @@ # climateData (development version) +- **The default data are now the 1 arcmin release** (`cna-v7.70-1arcmin`; cells about 1.85 km + north to south), built from the same years and scenarios as the 3 arcmin release. + `options(climateData.resolution = "3arcmin")` selects the 3 arcmin release; set it in every R + process that calls climateData (a new process, such as a parallel or targets worker, starts with + the default). Each release has its own tile index: `ClimateNA_tiles_sqlite()` gets a + `resolution` argument, which defaults to the option. The 1 arcmin archives are about 6 times + larger than the 3 arcmin ones (958 GiB against 150 GiB for the whole release). +- `inst/extdata/ClimateNA_tiles.sqlite` is replaced by `ClimateNA_tiles_1arcmin.sqlite` and + `ClimateNA_tiles_3arcmin.sqlite`; code that used the file's path should call + `ClimateNA_tiles_sqlite()` instead. +- `prepClimateLayers()` writes its rasters to a subfolder of `dstdir` named for the data release + (e.g. `/cna-v7.70-1arcmin/`), as it does for downloads in `srcdir`, so the two + resolutions' results never mix. Rasters written to `dstdir` itself by earlier versions are not + used again. + - The climate archives now download over HTTPS from a public bucket on Arbutus, the Digital Research Alliance of Canada's object storage. No Google account or `googledrive::drive_auth()` is needed, so downloads no longer fail on Google logins or service accounts (#13). Each diff --git a/R/ClimateNA_createTiles.R b/R/ClimateNA_createTiles.R index 95f12f1..968e34c 100644 --- a/R/ClimateNA_createTiles.R +++ b/R/ClimateNA_createTiles.R @@ -1,15 +1,30 @@ #' Paths to ClimateNA tile data #' -#' - `ClimateNA_tiles_sqlite()`: path to a SQLite database used to look up e.g. urls to climate data -#' for each tile. +#' - `ClimateNA_tiles_sqlite()`: path to the SQLite database (the tile index) used to look up e.g. +#' urls to climate data for each tile. Each data release has its own: one per resolution. #' - `ClimateNA_tiles_gpkg()`: path to a GeoPackage file defining the tile locations and extents. #' +#' @param resolution character. The resolution of the data release: `"1arcmin"` or `"3arcmin"`. +#' Defaults to `options(climateData.resolution)`, which is `"1arcmin"` unless set. Set the +#' option in every R process that uses climateData: a new process (e.g. a parallel or targets +#' worker) starts with the default. +#' #' @return character. file path. #' #' @export #' @rdname ClimateNA_tiles_data -ClimateNA_tiles_sqlite <- function() { - system.file("extdata/ClimateNA_tiles.sqlite", package = "climateData") +ClimateNA_tiles_sqlite <- function(resolution = getOption("climateData.resolution", "1arcmin")) { + valid <- c("1arcmin", "3arcmin") + if (length(resolution) != 1L || !isTRUE(resolution %in% valid)) { + stop( + "`resolution` (options(climateData.resolution)) must be \"", + paste(valid, collapse = "\" or \""), + "\", not ", + deparse(resolution), + call. = FALSE + ) + } + system.file("extdata", paste0("ClimateNA_tiles_", resolution, ".sqlite"), package = "climateData") } #' @export diff --git a/R/ClimateNA_useTiles.R b/R/ClimateNA_useTiles.R index 0cb7d1b..a56cd28 100644 --- a/R/ClimateNA_useTiles.R +++ b/R/ClimateNA_useTiles.R @@ -17,7 +17,10 @@ whereAmI <- function(studyArea) { (function(x) x$id)() } -#' Extract a table from the ClimateNA sqlite databose +#' Extract a table from the ClimateNA sqlite database +#' +#' Reads the tile index of the data release that `options(climateData.resolution)` selects (see +#' [ClimateNA_tiles_sqlite()]). #' #' @template ClimateNA_type #' @template ClimateNA_tile @@ -111,6 +114,9 @@ getNormalsPeriods <- function(type = NULL, tile = NULL, msy = "Y", gcm = NULL, s #' Look up the URLs for a set of climate tiles #' +#' Reads the tile index of the data release that `options(climateData.resolution)` selects (see +#' [ClimateNA_tiles_sqlite()]). +#' #' @template ClimateNA_type #' @template ClimateNA_tile #' @template ClimateNA_years @@ -188,7 +194,10 @@ getClimateURLs <- function( #' @param climateURLs list of data frames of tile archives (`url` and `md5`, as returned by #' [getClimateURLs()]), named by tile id. #' -#' @param climatePath character string specifying the directory path to put climate data. +#' @param climatePath character string specifying the directory path to put climate data. Use a +#' folder per data release, as `prepClimateLayers()` does: the two resolutions' archives and +#' files have the same names, and an extraction is cached by the archive's MD5, the variables +#' and this folder, so a folder shared by both can be left holding the other release's files. #' #' @param needVars A character vector of the climate variables to extract from the zip files, #' with a prefix of either `historical_` or `future_`. diff --git a/R/dataRelease.R b/R/dataRelease.R index 13b70c5..bbe9fb2 100644 --- a/R/dataRelease.R +++ b/R/dataRelease.R @@ -1,12 +1,13 @@ -#' Identify the climate data release behind the installed package +#' Identify the climate data release in use #' -#' Each climateData release ships a tile index pointing at one release of the ClimateNA -#' archives in the Arbutus bucket. Use this to tell releases apart, e.g. in the cache key of -#' code that caches `prepClimateLayers()` results, so a new data release isn't served from an -#' old cache. +#' climateData ships one tile index per data release of the ClimateNA archives in the Arbutus +#' bucket, one per resolution; `options(climateData.resolution)` chooses which is used (see +#' [ClimateNA_tiles_sqlite()]). Use this to tell releases apart, e.g. in the cache key of code +#' that caches `prepClimateLayers()` results, so a new data release, or the other resolution, +#' isn't served from an old cache. #' -#' @return a list with `release_id` (e.g. `"cna-v7.70-3arcmin"`), `climatena_version` (the -#' ClimateNA release that produced the data) and `dem_resolution` (e.g. `"3arcmin"`). Indexes +#' @return a list with `release_id` (e.g. `"cna-v7.70-1arcmin"`), `climatena_version` (the +#' ClimateNA release that produced the data) and `dem_resolution` (e.g. `"1arcmin"`). Indexes #' made before releases were recorded (before climateData 2.3.0) give `release_id = "pre-2.3.0"`. #' #' @export diff --git a/R/filledCells.R b/R/filledCells.R index f15b17f..2e78c46 100644 --- a/R/filledCells.R +++ b/R/filledCells.R @@ -2,8 +2,9 @@ #' #' ClimateNA writes no values at some land cells: its future climate data miss some coastal #' cells, and a few cells get no values at all. In the archives, each such cell holds -#' ClimateNA's values for the nearest land cell it covers (a median of about 5 km away), -#' computed at the empty cell's own elevation. `filledCells()` lists those cells, so they can be +#' ClimateNA's values for the nearest land cell it covers (a median of about 2 km away at 1 +#' arcmin, 3.5 km at 3 arcmin), computed at the empty cell's own elevation. `filledCells()` lists +#' those cells in the data release in use (see [ClimateNA_tiles_sqlite()]), so they can be #' mapped, or masked out of an analysis. #' #' `class` says which archives a cell was filled in: `"historical"` (historical years and diff --git a/R/latestHistoricalYear.R b/R/latestHistoricalYear.R index a953268..da4cb48 100644 --- a/R/latestHistoricalYear.R +++ b/R/latestHistoricalYear.R @@ -1,7 +1,8 @@ #' Latest historical year available as climate tiles #' -#' The last year for which the bundled tile index lists historical climate data for every -#' requested tile. ClimateNA's annual releases are processed into tiles separately, so this is +#' The last year for which the tile index of the data release in use (see +#' [ClimateNA_tiles_sqlite()]) lists historical climate data for every requested tile. +#' ClimateNA's annual releases are processed into tiles separately, so this is #' the latest year that `prepClimateLayers()` can fetch, which can be earlier than the latest #' year ClimateNA itself has published. It needs no network access. #' diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index 194e76b..5032485 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -88,9 +88,13 @@ extractTimes <- function(climateVarsList, type) { #' Prepare rasters for derived and 'as-is' climate variables #' #' Archives are downloaded and extracted to a subfolder of `srcdir` named for the data release -#' (`climateDataRelease()$release_id`, e.g. `cna-v7.70-3arcmin`). A new release's archives keep -#' the earlier names, so they would otherwise not replace files already in `srcdir`. Folders -#' from earlier releases are not used again and can be deleted. +#' (`climateDataRelease()$release_id`, e.g. `cna-v7.70-1arcmin`), and the rasters are written to +#' the subfolder of `dstdir` of the same name. A new release's archives keep the earlier names, +#' and the 1 and 3 arcmin releases' files have the same names, so they would otherwise not +#' replace files already there. Folders from earlier releases are not used again and can be +#' deleted. `options(climateData.resolution)` chooses the release (see [ClimateNA_tiles_sqlite()]); +#' set it in the R process that calls `prepClimateLayers()`, as a new process (e.g. a targets +#' worker) starts with the default, 1 arcmin. #' #' @template climVarsList #' @@ -203,10 +207,11 @@ prepClimateLayers <- function( (is.null(tile) && !is.null(studyArea) && !is.null(rasterToMatch)) ## pass sA/RTM but not tile ) - ## one folder per data release: a new release's zips keep the old names, and reproducible skips - ## the download when a zip of that name and its files are already in the folder - climatePath <- file.path(srcdir, climateDataRelease()$release_id) - climatePathOut <- dstdir + ## one folder per data release, for downloads and outputs: a new release's zips keep the old + ## names, and the two resolutions' files have the same names + releaseId <- climateDataRelease()$release_id + climatePath <- file.path(srcdir, releaseId) + climatePathOut <- file.path(dstdir, releaseId) ## need full study area perimeter w/o subpolygons if (!is.null(studyArea)) { @@ -417,14 +422,18 @@ prepClimateLayers <- function( tifs_msy <- append(tifs_hist_msy, tifs_futu_msy) tifs_nrm <- append(tifs_hist_nrm, tifs_futu_nrm) tifs <- append(tifs_msy, tifs_nrm) - if (!all(file.exists(unlist(tifs)))) { + tifFiles <- unlist(tifs) + lost <- tifFiles[!file.exists(tifFiles)] + if (length(lost) > 0) { stop( - "The following mosaic rasters could not be found:\n", - paste(basename(tifs[!file.exists(tifs)]), collapse = ", "), - ".\n", - "Please check that all source data files are present in ", - dstdir, - "." + "These mosaic rasters were not written to ", + climatePathOut, + ": ", + paste(basename(lost), collapse = ", "), + ". Check that their archives were downloaded and extracted in ", + climatePath, + ".", + call. = FALSE ) } @@ -511,6 +520,7 @@ prepClimateLayers <- function( digest4cache <- c( "climatePathOut", "currentModuleName", + "releaseId", .allowedClimDotsNames, "rasterToMatch", "studyArea", diff --git a/R/zzz.R b/R/zzz.R index 72bdd3a..d03784a 100644 --- a/R/zzz.R +++ b/R/zzz.R @@ -12,7 +12,8 @@ stopForInvalidBackend <- function() { ## set options using the approach used by devtools opts <- options() opts.climateData <- list( - climateData.parallel.backend = "parallel" ## "future" also supported + climateData.parallel.backend = "parallel", ## "future" also supported + climateData.resolution = "1arcmin" ## the data release; "3arcmin" also supported ) toset <- !(names(opts.climateData) %in% names(opts)) if (any(toset)) options(opts.climateData[toset]) diff --git a/data-raw/pipeline/R/out_root.R b/data-raw/pipeline/R/out_root.R new file mode 100644 index 0000000..fc2359a --- /dev/null +++ b/data-raw/pipeline/R/out_root.R @@ -0,0 +1,53 @@ +## Each resolution's release needs its own out_root: the two releases' raw outputs have the same +## names but different DEM tiles, so a run at the other resolution would delete and rerun every +## period, overwriting the first release's outputs. + +## Stops, naming both resolutions, unless `outRoot` holds the release at `demResolution`. The first +## run stamps it (/dem_resolution); an out_root from before the stamp takes the +## resolution from its index. _targets.R calls this only under tar_make(), as it writes the stamp. +pipeline_check_out_root <- function(outRoot, demResolution) { + stamp <- file.path(outRoot, "dem_resolution") + have <- if (file.exists(stamp)) { + trimws(readLines(stamp, n = 1L, warn = FALSE)) + } else { + pipeline_index_resolution(file.path(outRoot, "ClimateNA_tiles.sqlite")) + } + if (length(have) == 1L && !is.na(have) && !identical(have, demResolution)) { + stop( + "out_root ", + outRoot, + " holds the ", + have, + " release, but this release's dem_resolution is ", + demResolution, + ": give each resolution its own out_root in _local.R (a run here would rerun every period ", + "and overwrite the ", + have, + " outputs)", + call. = FALSE + ) + } + if (!file.exists(stamp)) { + dir.create(outRoot, recursive = TRUE, showWarnings = FALSE) + writeLines(demResolution, stamp) + } + invisible(outRoot) +} + +## The dem_resolution an index records (release table), or NA when there is no index or none is +## recorded. Opened read-only. +pipeline_index_resolution <- function(index) { + if (!file.exists(index)) { + return(NA_character_) + } + db <- DBI::dbConnect(RSQLite::SQLite(), index, flags = RSQLite::SQLITE_RO) + on.exit(DBI::dbDisconnect(db)) + if (!"release" %in% DBI::dbListTables(db)) { + return(NA_character_) + } + if (!"dem_resolution" %in% DBI::dbListFields(db, "release")) { + return(NA_character_) + } + x <- DBI::dbGetQuery(db, "SELECT dem_resolution FROM release LIMIT 1")$dem_resolution + if (length(x) == 1L) x else NA_character_ +} diff --git a/data-raw/pipeline/_local.R.example b/data-raw/pipeline/_local.R.example index 91fa830..6389c53 100644 --- a/data-raw/pipeline/_local.R.example +++ b/data-raw/pipeline/_local.R.example @@ -2,7 +2,8 @@ ## Run the pipeline from the package root: every process loads the package from there. local <- list( - ## the release settings; NULL for the committed data-raw/pipeline/release.yml + ## the release settings; NULL for the committed data-raw/pipeline/release.yml (3 arcmin), or + ## "data-raw/pipeline/release-1arcmin.yml" for the 1 arcmin release release_file = NULL, ## an unpacked ClimateNA release, mounted read-only into the containers diff --git a/data-raw/pipeline/_targets.R b/data-raw/pipeline/_targets.R index f1bda07..fb7c3f3 100644 --- a/data-raw/pipeline/_targets.R +++ b/data-raw/pipeline/_targets.R @@ -29,9 +29,11 @@ dry_run <- local$dry_run ## refers to); otherwise that stops replace_changed <- isTRUE(local$replace_changed) run_timeout <- local$run_timeout %||% 3600 # seconds per ClimateNA run -## the previous release's index, whose identical zips are reused rather than uploaded again -## (relative, so it is the same path in any checkout) -previous_index_path <- local$previous_index %||% "inst/extdata/ClimateNA_tiles.sqlite" +## the previous release's index at this resolution, whose identical zips are reused rather than +## uploaded again: the shipped ClimateNA_tiles_.sqlite (relative, so it is the +## same path in any checkout) +previous_index_path <- local$previous_index %||% + sprintf("inst/extdata/ClimateNA_tiles_%s.sqlite", cfg[["dem_resolution"]]) ## node-local directory for ClimateNA's output before it is copied to out_root (an environment ## variable, so it is no target's dependency; local crew workers inherit it) if (!is.null(local$work_dir)) { @@ -89,6 +91,11 @@ tar_source("data-raw/pipeline/R") ## paths reach zip, docker and rclone through the shell unquoted (paths.R) pipeline_check_paths(local) +## each resolution has its own out_root (out_root.R); checked and stamped by tar_make() only +if (identical(targets::tar_call(), "tar_make")) { + pipeline_check_out_root(out_root_path, cfg[["dem_resolution"]]) +} + ## one set of targets per archive type mapped <- tar_map( values = data.frame(type = unlist(cfg$types)), diff --git a/data-raw/pipeline/release-1arcmin.yml b/data-raw/pipeline/release-1arcmin.yml new file mode 100644 index 0000000..a9ab1df --- /dev/null +++ b/data-raw/pipeline/release-1arcmin.yml @@ -0,0 +1,51 @@ +## The 1 arcmin data release of the ClimateNA archives (committed): release.yml with the 1 arcmin +## DEM. Use it with release_file in _local.R. Machine-specific paths go in _local.R. + +release_id: cna-v7.70-1arcmin +climatena_exe: ClimateNA_v7.70.exe +climatena_version: "7.70" +dem_resolution: 1arcmin + +## which archive types to build +types: [historical, future, historical_normals, future_normals] + +## ranges as [first, last] (inclusive) +historical_years: [1901, 2025] +future_years: [2011, 2100] +gcms: [CanESM5, CNRM-ESM2-1] +ssps: ["245", "370", "585"] +## quoted: YAML reads 1901_1930 as the integer 19011930 +historical_periods: ["1901_1930", "1911_1940", "1921_1950", "1931_1960", "1941_1970", "1951_1980", "1971_2000", "1981_2010", "1991_2020"] +future_periods: ["2011_2040", "2041_2070", "2071_2100"] + +## a land cell ClimateNA leaves empty is filled from the nearest land cell it covers, if that is +## within this many km +fill_max_km: 50 + +## a stamped period is reused if its ClimateNA version is at least this; raising it for a type +## regenerates that type (do this when compat_ reports "changed") +min_version: + historical: "7.70" + future: "7.70" + historical_normals: "7.70" + future_normals: "7.70" + +image: ghcr.io/predictiveecology/climatena-wine:latest + +## The bucket holding the archives (Arbutus object storage, S3): each zip is the object +## //, public at //. The container is +## the project id and the bucket name, as in the public URL. +bucket: + endpoint: https://object-arbutus.alliancecan.ca + container: "529feda02d404836b0e91b1d360b4df0:predictiveecology" + prefix: climateData + +## The bucket's browsable catalogue (buckethost::generateIndexes()), refreshed after uploads. It +## rewrites every page outside the excluded folders, so these match the settings of the bucket's +## other users: a heading of null shows the bucket's name. `exclude`: folders left out of the +## catalogue (the live catalogue leaves out wbi/, about 2.9 million objects). +catalogue: + heading: null + disclaimer_html: "" + host_note: "Hosted on an S3-compatible object store." + exclude: [wbi] diff --git a/data-raw/pipeline/release.yml b/data-raw/pipeline/release.yml index 1ce3e08..dd8ebd6 100644 --- a/data-raw/pipeline/release.yml +++ b/data-raw/pipeline/release.yml @@ -42,8 +42,8 @@ bucket: ## The bucket's browsable catalogue (buckethost::generateIndexes()), refreshed after uploads. It ## rewrites every page outside the excluded folders, so these match the settings of the bucket's -## other users: a heading of null shows the bucket's name. `exclude`: folders left out of the catalogue (the -## live catalogue leaves out wbi/, about 2.9 million objects). +## other users: a heading of null shows the bucket's name. `exclude`: folders left out of the +## catalogue (the live catalogue leaves out wbi/, about 2.9 million objects). catalogue: heading: null disclaimer_html: "" diff --git a/inst/extdata/ClimateNA_tiles_1arcmin.sqlite b/inst/extdata/ClimateNA_tiles_1arcmin.sqlite new file mode 100644 index 0000000..b8a01a9 Binary files /dev/null and b/inst/extdata/ClimateNA_tiles_1arcmin.sqlite differ diff --git a/inst/extdata/ClimateNA_tiles.sqlite b/inst/extdata/ClimateNA_tiles_3arcmin.sqlite similarity index 100% rename from inst/extdata/ClimateNA_tiles.sqlite rename to inst/extdata/ClimateNA_tiles_3arcmin.sqlite diff --git a/man/ClimateNA_tiles_data.Rd b/man/ClimateNA_tiles_data.Rd index a596dd4..7f5b476 100644 --- a/man/ClimateNA_tiles_data.Rd +++ b/man/ClimateNA_tiles_data.Rd @@ -5,17 +5,25 @@ \alias{ClimateNA_tiles_gpkg} \title{Paths to ClimateNA tile data} \usage{ -ClimateNA_tiles_sqlite() +ClimateNA_tiles_sqlite( + resolution = getOption("climateData.resolution", "1arcmin") +) ClimateNA_tiles_gpkg() } +\arguments{ +\item{resolution}{character. The resolution of the data release: \code{"1arcmin"} or \code{"3arcmin"}. +Defaults to \code{options(climateData.resolution)}, which is \code{"1arcmin"} unless set. Set the +option in every R process that uses climateData: a new process (e.g. a parallel or targets +worker) starts with the default.} +} \value{ character. file path. } \description{ \itemize{ -\item \code{ClimateNA_tiles_sqlite()}: path to a SQLite database used to look up e.g. urls to climate data -for each tile. +\item \code{ClimateNA_tiles_sqlite()}: path to the SQLite database (the tile index) used to look up e.g. +urls to climate data for each tile. Each data release has its own: one per resolution. \item \code{ClimateNA_tiles_gpkg()}: path to a GeoPackage file defining the tile locations and extents. } } diff --git a/man/climateDataRelease.Rd b/man/climateDataRelease.Rd index d6929d2..22a6065 100644 --- a/man/climateDataRelease.Rd +++ b/man/climateDataRelease.Rd @@ -2,20 +2,21 @@ % Please edit documentation in R/dataRelease.R \name{climateDataRelease} \alias{climateDataRelease} -\title{Identify the climate data release behind the installed package} +\title{Identify the climate data release in use} \usage{ climateDataRelease() } \value{ -a list with \code{release_id} (e.g. \code{"cna-v7.70-3arcmin"}), \code{climatena_version} (the -ClimateNA release that produced the data) and \code{dem_resolution} (e.g. \code{"3arcmin"}). Indexes +a list with \code{release_id} (e.g. \code{"cna-v7.70-1arcmin"}), \code{climatena_version} (the +ClimateNA release that produced the data) and \code{dem_resolution} (e.g. \code{"1arcmin"}). Indexes made before releases were recorded (before climateData 2.3.0) give \code{release_id = "pre-2.3.0"}. } \description{ -Each climateData release ships a tile index pointing at one release of the ClimateNA -archives in the Arbutus bucket. Use this to tell releases apart, e.g. in the cache key of -code that caches \code{prepClimateLayers()} results, so a new data release isn't served from an -old cache. +climateData ships one tile index per data release of the ClimateNA archives in the Arbutus +bucket, one per resolution; \code{options(climateData.resolution)} chooses which is used (see +\code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}). Use this to tell releases apart, e.g. in the cache key of code +that caches \code{prepClimateLayers()} results, so a new data release, or the other resolution, +isn't served from an old cache. } \examples{ climateDataRelease()$release_id diff --git a/man/filledCells.Rd b/man/filledCells.Rd index 27de788..c0373d2 100644 --- a/man/filledCells.Rd +++ b/man/filledCells.Rd @@ -21,8 +21,9 @@ cell's elevation, m), \code{filled}, \code{src_lon} and \code{src_lat} (where Cl \description{ ClimateNA writes no values at some land cells: its future climate data miss some coastal cells, and a few cells get no values at all. In the archives, each such cell holds -ClimateNA's values for the nearest land cell it covers (a median of about 5 km away), -computed at the empty cell's own elevation. \code{filledCells()} lists those cells, so they can be +ClimateNA's values for the nearest land cell it covers (a median of about 2 km away at 1 +arcmin, 3.5 km at 3 arcmin), computed at the empty cell's own elevation. \code{filledCells()} lists +those cells in the data release in use (see \code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}), so they can be mapped, or masked out of an analysis. } \details{ diff --git a/man/getClimateTable.Rd b/man/getClimateTable.Rd index a7cf638..a00b5be 100644 --- a/man/getClimateTable.Rd +++ b/man/getClimateTable.Rd @@ -2,7 +2,7 @@ % Please edit documentation in R/ClimateNA_useTiles.R \name{getClimateTable} \alias{getClimateTable} -\title{Extract a table from the ClimateNA sqlite databose} +\title{Extract a table from the ClimateNA sqlite database} \usage{ getClimateTable( type = NULL, @@ -31,7 +31,8 @@ one of 'historical', 'future', 'historical_normals', or 'future_normals'.} \code{data.frame} } \description{ -Extract a table from the ClimateNA sqlite databose +Reads the tile index of the data release that \code{options(climateData.resolution)} selects (see +\code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}). } \examples{ (getClimateTable(type = "historical", tile = 1, msy = "M", years = 2011:2020)) diff --git a/man/getClimateTiles.Rd b/man/getClimateTiles.Rd index 5da03e8..d9470ee 100644 --- a/man/getClimateTiles.Rd +++ b/man/getClimateTiles.Rd @@ -12,7 +12,10 @@ getClimateTiles(tile, climateURLs, climatePath, needVars = NULL) \item{climateURLs}{list of data frames of tile archives (\code{url} and \code{md5}, as returned by \code{\link[=getClimateURLs]{getClimateURLs()}}), named by tile id.} -\item{climatePath}{character string specifying the directory path to put climate data.} +\item{climatePath}{character string specifying the directory path to put climate data. Use a +folder per data release, as \code{prepClimateLayers()} does: the two resolutions' archives and +files have the same names, and an extraction is cached by the archive's MD5, the variables +and this folder, so a folder shared by both can be left holding the other release's files.} \item{needVars}{A character vector of the climate variables to extract from the zip files, with a prefix of either \code{historical_} or \code{future_}. diff --git a/man/getClimateURLs.Rd b/man/getClimateURLs.Rd index 169f677..fbdb178 100644 --- a/man/getClimateURLs.Rd +++ b/man/getClimateURLs.Rd @@ -32,5 +32,6 @@ list of data frames, one per tile (named by tile id), with one row per archive: \code{url}, the archive's public URL, and \code{md5}, its MD5 checksum as recorded in the tile index. } \description{ -Look up the URLs for a set of climate tiles +Reads the tile index of the data release that \code{options(climateData.resolution)} selects (see +\code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}). } diff --git a/man/latestHistoricalYear.Rd b/man/latestHistoricalYear.Rd index 3ecdd95..5ce18ff 100644 --- a/man/latestHistoricalYear.Rd +++ b/man/latestHistoricalYear.Rd @@ -15,8 +15,9 @@ latestHistoricalYear(tile = NULL, msy = "MSY") integer } \description{ -The last year for which the bundled tile index lists historical climate data for every -requested tile. ClimateNA's annual releases are processed into tiles separately, so this is +The last year for which the tile index of the data release in use (see +\code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}) lists historical climate data for every requested tile. +ClimateNA's annual releases are processed into tiles separately, so this is the latest year that \code{prepClimateLayers()} can fetch, which can be earlier than the latest year ClimateNA itself has published. It needs no network access. } diff --git a/man/prepClimateLayers.Rd b/man/prepClimateLayers.Rd index 9501f60..9d56946 100644 --- a/man/prepClimateLayers.Rd +++ b/man/prepClimateLayers.Rd @@ -68,9 +68,13 @@ used to tag \code{Cache} entries.} } \description{ Archives are downloaded and extracted to a subfolder of \code{srcdir} named for the data release -(\code{climateDataRelease()$release_id}, e.g. \verb{cna-v7.70-3arcmin}). A new release's archives keep -the earlier names, so they would otherwise not replace files already in \code{srcdir}. Folders -from earlier releases are not used again and can be deleted. +(\code{climateDataRelease()$release_id}, e.g. \verb{cna-v7.70-1arcmin}), and the rasters are written to +the subfolder of \code{dstdir} of the same name. A new release's archives keep the earlier names, +and the 1 and 3 arcmin releases' files have the same names, so they would otherwise not +replace files already there. Folders from earlier releases are not used again and can be +deleted. \code{options(climateData.resolution)} chooses the release (see \code{\link[=ClimateNA_tiles_sqlite]{ClimateNA_tiles_sqlite()}}); +set it in the R process that calls \code{prepClimateLayers()}, as a new process (e.g. a targets +worker) starts with the default, 1 arcmin. } \examples{ if (require("archive", quietly = TRUE) && diff --git a/tests/testthat/test-dataRelease.R b/tests/testthat/test-dataRelease.R index c0edfff..95ed31a 100644 --- a/tests/testthat/test-dataRelease.R +++ b/tests/testthat/test-dataRelease.R @@ -38,7 +38,7 @@ test_that("climateDataRelease reads the shipped index in place, read-only", { skip_if_not_installed("withr") d <- withr::local_tempdir() f <- file.path(d, "ClimateNA_tiles.sqlite") - file.copy(ClimateNA_tiles_sqlite(), f) + file.copy(ClimateNA_tiles_sqlite("3arcmin"), f) Sys.chmod(d, "0555") withr::defer(Sys.chmod(d, "0755")) @@ -97,20 +97,19 @@ test_that(".releaseWrite stores the bucket's base URL", { ## A new release's zips keep the old names. In a srcdir filled from the old index, reproducible ## found 39_Y_2020.zip and its extracted files present, skipped the new download, and the old ## data (MAR, no rsds) were used (checked 2026-11-05). -test_that("prepClimateLayers downloads and mosaics in a folder named for the data release", { +## downloads, mosaics and outputs of one data release never mix with another's: with both +## resolutions installed, a dstdir used for one must not serve the other's rasters +## a mosaic that wasn't written is named, with the release's output folder it should be in (the +## check called file.exists() on a list, so it failed before it could say which) +test_that("prepClimateLayers names the mosaics it couldn't find", { skip_if_not_installed("withr") - d <- withr::local_tempdir("test_releaseSrcdir_") - got <- character(0) + d <- withr::local_tempdir("test_missingMosaics_") testthat::local_mocked_bindings( getClimateURLs = function(...) character(0), - getClimateTiles = function(tile, climateURLs, climatePath, needVars = NULL) { - got <<- c(got, download = climatePath) - NULL - }, + getClimateTiles = function(...) NULL, .stopIfMissingClimateDirs = function(allDirs) invisible(allDirs), buildClimateMosaics = function(...) { - got <<- c(got, mosaic = list(...)$srcdir) - stop("stop after mosaics") + list(MAT = file.path(list(...)$dstdir, "MAT_historical_2020_t_39.tif")) } ) vars <- list( @@ -120,10 +119,44 @@ test_that("prepClimateLayers downloads and mosaics in a folder named for the dat .dots = list(historical_years = 2020) ) ) - expect_error( - prepClimateLayers(vars, srcdir = d, dstdir = file.path(d, "out"), tile = 39), - "stop after mosaics" - ) - want <- file.path(d, climateDataRelease()$release_id, "historical") - expect_identical(unname(got), c(want, want)) + out <- file.path(d, "out", climateDataRelease()$release_id) + run <- function() prepClimateLayers(vars, srcdir = d, dstdir = file.path(d, "out"), tile = 39) + expect_error(run(), "MAT_historical_2020_t_39.tif", fixed = TRUE) + expect_error(run(), out, fixed = TRUE) +}) + +test_that("prepClimateLayers downloads and mosaics in a folder named for the data release", { + skip_if_not_installed("withr") + for (res in c("1arcmin", "3arcmin")) { + withr::local_options(climateData.resolution = res) + d <- withr::local_tempdir("test_releaseSrcdir_") + got <- character(0) + testthat::local_mocked_bindings( + getClimateURLs = function(...) character(0), + getClimateTiles = function(tile, climateURLs, climatePath, needVars = NULL) { + got <<- c(got, download = climatePath) + NULL + }, + .stopIfMissingClimateDirs = function(allDirs) invisible(allDirs), + buildClimateMosaics = function(...) { + got <<- c(got, mosaic = list(...)$srcdir, out = list(...)$dstdir) + stop("stop after mosaics") + } + ) + vars <- list( + MAT = list( + vars = "historical_MAT", + fun = quote(calcAsIs), + .dots = list(historical_years = 2020) + ) + ) + expect_error( + prepClimateLayers(vars, srcdir = d, dstdir = file.path(d, "out"), tile = 39), + "stop after mosaics" + ) + id <- climateDataRelease()$release_id + expect_match(id, res, fixed = TRUE) + want <- file.path(d, id, "historical") + expect_identical(unname(got), c(want, want, file.path(d, "out", id))) + } }) diff --git a/tests/testthat/test-download.R b/tests/testthat/test-download.R index 13e9b04..6cc1c2e 100644 --- a/tests/testthat/test-download.R +++ b/tests/testthat/test-download.R @@ -222,18 +222,21 @@ test_that("getClimateTiles extracts only the requested variables", { expect_false(file.exists(file.path(d, "39", "2011", "PPT01.asc"))) }) -test_that("one zip downloads from the bucket and matches the shipped index", { +test_that("one zip downloads from the bucket and matches the shipped index, at each resolution", { skip_on_cran() skip_if_not_installed("withr") skip_if_offline("object-arbutus.alliancecan.ca") - db <- sqlite_connect_db(ClimateNA_tiles_sqlite(), readonly = TRUE) - row <- DBI::dbGetQuery( - db, - "SELECT key, md5 FROM archives WHERE type = 'historical_normals' ORDER BY size LIMIT 1" - ) - DBI::dbDisconnect(db) - p <- .fetchArchive(paste0(.indexBaseUrl(), "/", row$key), row$md5, withr::local_tempdir()) - expect_identical(unname(tools::md5sum(p)), row$md5) + for (res in c("1arcmin", "3arcmin")) { + f <- ClimateNA_tiles_sqlite(res) + db <- sqlite_connect_db(f, readonly = TRUE) + row <- DBI::dbGetQuery( + db, + "SELECT key, md5 FROM archives WHERE type = 'historical_normals' ORDER BY size LIMIT 1" + ) + DBI::dbDisconnect(db) + p <- .fetchArchive(paste0(.indexBaseUrl(f), "/", row$key), row$md5, withr::local_tempdir()) + expect_identical(unname(tools::md5sum(p)), row$md5) + } }) ## a DNS or connection failure (curl error, no HTTP status) is retried, not only HTTP errors diff --git a/tests/testthat/test-pipelineOutRoot.R b/tests/testthat/test-pipelineOutRoot.R new file mode 100644 index 0000000..280bd7c --- /dev/null +++ b/tests/testthat/test-pipelineOutRoot.R @@ -0,0 +1,55 @@ +## Each resolution's release needs its own out_root (data-raw/pipeline/R/out_root.R): the two +## releases' raw outputs have the same names but different DEM tiles, so a run at the other +## resolution would delete and rerun every period, overwriting the first release's outputs. +outRootEnv <- function() { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "out_root.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + e +} + +test_that("a new out_root is stamped with the release's resolution", { + skip_if_not_installed("withr") + e <- outRootEnv() + d <- file.path(withr::local_tempdir(), "out") + e$pipeline_check_out_root(d, "1arcmin") + expect_identical(readLines(file.path(d, "dem_resolution")), "1arcmin") + expect_no_error(e$pipeline_check_out_root(d, "1arcmin")) +}) + +test_that("an out_root stamped with the other resolution stops the run, naming both", { + skip_if_not_installed("withr") + e <- outRootEnv() + d <- withr::local_tempdir() + writeLines("1arcmin", file.path(d, "dem_resolution")) + expect_error(e$pipeline_check_out_root(d, "3arcmin"), "1arcmin.*3arcmin.*own out_root") + expect_identical(readLines(file.path(d, "dem_resolution")), "1arcmin") +}) + +## the 1 and 3 arcmin out_roots predate the stamp: their indexes record the resolution +test_that("an out_root without a stamp takes the resolution from its index", { + skip_if_not_installed("withr") + e <- outRootEnv() + d <- withr::local_tempdir() + db <- DBI::dbConnect(RSQLite::SQLite(), file.path(d, "ClimateNA_tiles.sqlite")) + DBI::dbExecute(db, "CREATE TABLE release (release_id TEXT, dem_resolution TEXT)") + DBI::dbExecute(db, "INSERT INTO release VALUES ('cna-v7.70-3arcmin', '3arcmin')") + DBI::dbDisconnect(db) + expect_error(e$pipeline_check_out_root(d, "1arcmin"), "3arcmin.*1arcmin") + expect_false(file.exists(file.path(d, "dem_resolution"))) + e$pipeline_check_out_root(d, "3arcmin") + expect_identical(readLines(file.path(d, "dem_resolution")), "3arcmin") +}) + +## the check writes the stamp, so it runs only for tar_make(), not for tar_manifest() and the +## like (which the pipeline tests call) +test_that("_targets.R checks out_root only under tar_make()", { + f <- test_path("..", "..", "data-raw", "pipeline", "_targets.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + x <- paste(readLines(f), collapse = "\n") + expect_match( + x, + "if \\(identical\\(targets::tar_call\\(\\), \"tar_make\"\\)\\) \\{\\s*pipeline_check_out_root\\(out_root_path, cfg\\[\\[\"dem_resolution\"\\]\\]\\)" + ) +}) diff --git a/tests/testthat/test-pipelineSpecs.R b/tests/testthat/test-pipelineSpecs.R index 6d1ad4d..9a6c603 100644 --- a/tests/testthat/test-pipelineSpecs.R +++ b/tests/testthat/test-pipelineSpecs.R @@ -73,3 +73,20 @@ test_that("pipeline_tile_masks names each tile's mask and land cells by its DEM expect_identical(m[["2"]]$land, c(2L, 3L)) expect_identical(m[["2"]]$cells, 4L) }) + +## the two releases are built from the same years, scenarios and ClimateNA version; only the DEM +## tiles' resolution differs +test_that("the committed 1 arcmin settings differ from the 3 arcmin ones only in release and resolution", { + skip_if_not_installed("yaml") + d <- test_path("..", "..", "data-raw", "pipeline") + skip_if_not(dir.exists(d), "data-raw/pipeline not available") + a <- yaml::read_yaml(file.path(d, "release.yml")) + b <- yaml::read_yaml(file.path(d, "release-1arcmin.yml")) + ## the same release id but for its resolution, whatever the ClimateNA version + expect_identical(a$dem_resolution, "3arcmin") + expect_identical(b$dem_resolution, "1arcmin") + expect_match(a$release_id, "-3arcmin$") + expect_identical(b$release_id, sub("-3arcmin$", "-1arcmin", a$release_id)) + same <- setdiff(union(names(a), names(b)), c("release_id", "dem_resolution")) + expect_identical(b[same], a[same]) +}) diff --git a/tests/testthat/test-prepClimateLayers.R b/tests/testthat/test-prepClimateLayers.R index d4566df..9445b07 100644 --- a/tests/testthat/test-prepClimateLayers.R +++ b/tests/testthat/test-prepClimateLayers.R @@ -88,7 +88,7 @@ test_that("prepClimateLayers works for multiple variable types", { fn1 <- fn[[1]] fn2 <- fn[[2]] names(fn2) <- names(fn1) ## compare values, not layer names - expect_false(isTRUE(terra::all.equal(fn1, fn2))) + expect_false(isTRUE(terra::all.equal(fn1, fn2, maxcell = terra::ncell(fn1)))) #new climate variables @@ -135,9 +135,9 @@ test_that("prepClimateLayers works for multiple variable types", { names(ras2a) <- names(ras1a) #check same var diff normal period - expect_false(isTRUE(terra::all.equal(ras1a, ras1b))) + expect_false(isTRUE(terra::all.equal(ras1a, ras1b, maxcell = terra::ncell(ras1a)))) #check diff var same normal period - expect_false(isTRUE(terra::all.equal(ras1a, ras2a))) + expect_false(isTRUE(terra::all.equal(ras1a, ras2a, maxcell = terra::ncell(ras1a)))) } ## now test with studyArea and rasterTaMatch diff --git a/tests/testthat/test-resolution.R b/tests/testthat/test-resolution.R new file mode 100644 index 0000000..6e26a7b --- /dev/null +++ b/tests/testthat/test-resolution.R @@ -0,0 +1,62 @@ +## options(climateData.resolution) picks the data release: "1arcmin" (the default) or "3arcmin". +## Each has its own shipped tile index, inst/extdata/ClimateNA_tiles_.sqlite, and both +## use the tiles of tiles.gpkg. +test_that("the default resolution is 1 arcmin", { + skip_if_not_installed("withr") + withr::local_options(climateData.resolution = NULL) + expect_match(ClimateNA_tiles_sqlite(), "ClimateNA_tiles_1arcmin[.]sqlite$") + expect_identical(climateDataRelease()$release_id, "cna-v7.70-1arcmin") +}) + +test_that("climateData.resolution = '3arcmin' switches every lookup", { + skip_if_not_installed("withr") + withr::local_options(climateData.resolution = "3arcmin") + expect_match(ClimateNA_tiles_sqlite(), "ClimateNA_tiles_3arcmin[.]sqlite$") + expect_identical(climateDataRelease()$release_id, "cna-v7.70-3arcmin") + expect_identical(climateDataRelease()$dem_resolution, "3arcmin") + expect_match(.indexBaseUrl(), "^https://object-arbutus[.]alliancecan[.]ca/") + u <- getClimateURLs("historical", tile = 39, years = 2020, msy = "MSY")[["39"]]$url + expect_match(u, "/climateData/cna-v7[.]70-3arcmin/") +}) + +## the user-facing lookups all read the index the option names (filledCells() has 608 rows at +## 3 arcmin and 4,928 at 1 arcmin) +test_that("every lookup opens the index the option names", { + skip_if_not_installed("withr") + withr::local_options(climateData.resolution = "3arcmin") + realConnect <- sqlite_connect_db + opened <- character(0) + testthat::local_mocked_bindings(sqlite_connect_db = function(dbfile, ...) { + opened <<- c(opened, dbfile) + realConnect(dbfile, ...) + }) + climateDataRelease() + .indexBaseUrl() + getClimateURLs("historical", tile = 39, years = 2020, msy = "MSY") + filledCells(tiles = 39) + latestHistoricalYear(tile = 39) + expect_gte(length(opened), 5) + expect_true(all(grepl("ClimateNA_tiles_3arcmin[.]sqlite$", opened)), label = toString(opened)) +}) + +test_that("an unknown climateData.resolution stops with the valid values", { + skip_if_not_installed("withr") + withr::local_options(climateData.resolution = "1 arcmin") + expect_error(ClimateNA_tiles_sqlite(), "climateData.resolution.*1arcmin.*3arcmin") +}) + +## a bad value passed as the argument is reported as the argument, not only as the option +test_that("an unknown resolution argument is named as the argument", { + expect_error(ClimateNA_tiles_sqlite("1arcsec"), "`resolution`", fixed = TRUE) +}) + +test_that("both shipped indexes' tiles are tiles of tiles.gpkg", { + ids <- sf::st_read(ClimateNA_tiles_gpkg(), quiet = TRUE)$id + for (r in c("1arcmin", "3arcmin")) { + db <- sqlite_connect_db(ClimateNA_tiles_sqlite(r), readonly = TRUE) + tiles <- DBI::dbGetQuery(db, "SELECT DISTINCT tileid FROM historical")$tileid + DBI::dbDisconnect(db) + expect_gt(length(tiles), 0) + expect_true(all(tiles %in% ids)) + } +}) diff --git a/vignettes/climateData.Rmd b/vignettes/climateData.Rmd index 1765198..67ae10c 100644 --- a/vignettes/climateData.Rmd +++ b/vignettes/climateData.Rmd @@ -38,10 +38,23 @@ available("historical_normals")$periods available("future")[c("gcms", "ssps")] available("future_normals")$periods -## the data release behind this version of the package +## the data release in use (see "Resolution" below) climateDataRelease()$release_id ``` +## Resolution + +Two data releases are available, built from the same years and scenarios with DEM tiles of different resolution: 1 arcmin (cells about 1.85 km north to south; the default) and 3 arcmin (about 5.6 km). Choose one with an option, before calling climateData's functions: + +```{r, eval = FALSE} +options(climateData.resolution = "3arcmin") +climateDataRelease()$release_id # "cna-v7.70-3arcmin" +``` + +Downloads and results go into subfolders of `srcdir` and `dstdir` named for the release, so the two never mix. The 1 arcmin archives are about 6 times larger than the 3 arcmin ones (958 GiB against 150 GiB for the whole release), so check your disk space and quota before downloading many tiles or years. + +The option must be set in every R process that calls climateData. A new R process, such as a parallel worker, a `callr` process or a targets worker, starts with the default (1 arcmin) unless the option is set there too, for example in a project `.Rprofile`. `climateDataRelease()$release_id`, and the name of the output folder, show which release was used. + ## Naming climate variables Each variable is named `_`, adding `_normal` for a 30-year normal: @@ -125,7 +138,7 @@ Instead of a study area and a raster to match, you can pass `tile =` with one or ## Filled cells -ClimateNA writes no values at some land cells. Its future climate data miss some coastal cells (for example along the east coast of Baffin Island), and a few cells get no values at all. In the archives, each such cell holds ClimateNA's values for the nearest land cell it covers within 50 km, computed at the empty cell's own elevation. In the 3 arcmin release that point is a median of 3.5 km away, and 90% are within 10 km. Where both have values, a point that close gives nearly the same climate: mean annual temperature differs by 0.05 degrees C on average (at most 0.5) and annual precipitation by about 1%. The 48 cells with no covered land cell within 50 km stay empty (`filled` is `FALSE`). +ClimateNA writes no values at some land cells. Its future climate data miss some coastal cells (for example along the east coast of Baffin Island), and a few cells get no values at all. In the archives, each such cell holds ClimateNA's values for the nearest land cell it covers within 50 km, computed at the empty cell's own elevation. That point is a median of 1.9 km away in the 1 arcmin release (91% within 10 km), and 3.5 km in the 3 arcmin release (88% within 10 km). Where both have values, a point that close gives nearly the same climate: mean annual temperature differs by 0.05 degrees C on average (at most 0.5) and annual precipitation by about 1%. The cells with no covered land cell within 50 km stay empty (`filled` is `FALSE`): 365 in the 1 arcmin release and 48 in the 3 arcmin release. `filledCells()` lists these cells as points, with where ClimateNA was run for each, so you can map them or leave them out: @@ -139,5 +152,5 @@ table(fc$class, fc$filled) # class: "historical" or "future" archives - **What gets downloaded:** the archives are grouped by tile and decade. climateData downloads only the archives it needs for your variables and years: - only monthly or only annual variables use their own archives; - any request with seasonal variables uses the archive with all variables. -- **Downloads are kept:** downloaded archives stay in a subfolder of `srcdir` named for the data release (e.g. `climate/inputs/cna-v7.70-3arcmin/`), so later calls reuse them. A new data release downloads into a new subfolder; older ones can be deleted. +- **Downloads are kept:** downloaded archives stay in a subfolder of `srcdir` named for the data release (e.g. `climate/inputs/cna-v7.70-1arcmin/`), so later calls reuse them, and the rasters go to the same-named subfolder of `dstdir`. A new data release, or the other resolution, uses new subfolders; older ones can be deleted. - **Results are cached:** with the reproducible package. If you cache results yourself (as `canClimateData` does), add `climateDataRelease()$release_id` to your cache key, so a new data release replaces your old results. diff --git a/vignettes/maintaining-climate-data.Rmd b/vignettes/maintaining-climate-data.Rmd index 186d5a0..d38edd3 100644 --- a/vignettes/maintaining-climate-data.Rmd +++ b/vignettes/maintaining-climate-data.Rmd @@ -18,11 +18,11 @@ This vignette is for the package's maintainers and developers. It explains how t A *data release* is one full set of ClimateNA outputs, built by one ClimateNA version from DEM tiles at one resolution. It is identified by a `release_id`, such as `cna-v7.70-3arcmin`. A release consists of: - zip archives in a public bucket on Arbutus, the Digital Research Alliance of Canada's object storage: one per tile and decade (historical and future years) or per tile (normals), each in four variable subsets: `MSY` (all), `M` (monthly), `S` (seasonal) and `Y` (annual); -- the tile index, `inst/extdata/ClimateNA_tiles.sqlite`, which maps each tile, year or period and subset to an object in the bucket (its `key`, and its MD5), and holds the bucket's address (`base_url` in the `release` table). +- the tile index, `inst/extdata/ClimateNA_tiles_.sqlite` (one per resolution), which maps each tile, year or period and subset to an object in the bucket (its `key`, and its MD5), and holds the bucket's address (`base_url` in the `release` table). Releases before climateData 2.3.0 kept their archives on Google Drive, and their indexes hold Drive file IDs instead. -Users get a release through the index shipped in the package. `climateDataRelease()` reports which release that is; modules that cache climate layers (such as canClimateData) should put `climateDataRelease()$release_id` in their cache keys. +Users get a release through the indexes shipped in the package, one per resolution; `options(climateData.resolution)` chooses which. `climateDataRelease()` reports which release that is; modules that cache climate layers (such as canClimateData) should put `climateDataRelease()$release_id` in their cache keys. A [targets](https://docs.ropensci.org/targets/) pipeline in `data-raw/pipeline/` builds a release: @@ -68,7 +68,7 @@ Download each ClimateNA release from [climatena.ca](https://climatena.ca/) and u The pipeline reads two files: -- `data-raw/pipeline/release.yml` (committed) defines the release: `release_id`, the ClimateNA executable and version, the DEM resolution, the archive types, the years, GCMs, SSPs and normals periods, the minimum ClimateNA version to keep per type (`min_version`), the image, and the bucket (`bucket`: its endpoint, its container, which is the project id and the bucket name, and the key prefix). +- `data-raw/pipeline/release.yml` (committed) defines the release: `release_id`, the ClimateNA executable and version, the DEM resolution, the archive types, the years, GCMs, SSPs and normals periods, the minimum ClimateNA version to keep per type (`min_version`), the image, and the bucket (`bucket`: its endpoint, its container, which is the project id and the bucket name, and the key prefix). It is the 3 arcmin release; `data-raw/pipeline/release-1arcmin.yml` is the 1 arcmin release, the same in all but `release_id` and `dem_resolution` (set `release_file` in `_local.R` to use it). The previous release's index (`previous_index`) defaults to the shipped `inst/extdata/ClimateNA_tiles_.sqlite`. - `data-raw/pipeline/_local.R` (gitignored; copy `_local.R.example`) holds what depends on the machine: paths (ClimateNA directory, DEM tiles, output root, and a node-local `work_dir`), the container user, an optional tile subset, `dry_run`, `replace_changed`, `run_timeout`, `previous_index`, the rclone remote for the bucket (`rclone_remote`), `upload_workers`, and how many ClimateNA runs go at once (`workers`, or `ssh_nodes` across machines). The checkout's own path is in neither file and no target depends on it, so running from a different checkout rebuilds nothing. The paths must not hold spaces or quotes: the pipeline passes them to zip, docker and rclone through the shell, and stops before anything runs if one does. ClimateNA writes each output into `work_dir` (by default each worker's temporary directory) on the node's own disk. The pipeline checks it there and stores it in `out_root` as a single zip per tile and year or period. ClimateNA writes very slowly straight to an NFS share, and copying hundreds of small files per run overloads the file server; one zip per run avoids both. @@ -77,7 +77,7 @@ The DEM tiles have no elevation for some cells (`nan`), and ClimateNA writes val ClimateNA also leaves some land cells (cells with a DEM elevation) empty: its future data miss some coastal cells, and a few cells get no values at all. The pipeline fills each one with ClimateNA's point-mode output at the nearest land cell it covers, run with the empty cell's elevation, if that cell is within `fill_max_km` (`release.yml`, default 50). `fill_points` finds the empty cells and their sources once per release, from one reference period per class (historical: the last historical year; future: the first scenario's first year), and checks each source with a point run; the next nearest is tried when one gives no values. `fills_` runs ClimateNA in point mode for every period of a tile with empty cells and stores the output beside the raw period zip (`.fill-.csv`); `zip_batch()` writes those values into the zips, after the mask. A land cell still empty when a zip is cut is reported as a warning (it appears in `report.csv`). The index lists every filled cell, and any left empty, in `filled_cells`; users read it with `filledCells()`. -`out_root` in `_local.R` holds everything a release writes: raw ClimateNA outputs (`raw/`, one zip and one stamp per tile and year or period), the published zips (`zips/`), the targets store (`_targets/`), logs, the index and the report. **Keep the same `out_root` from one release to the next**: the next release then reuses the raw outputs and zips that haven't changed, and their objects in the bucket. +`out_root` in `_local.R` holds everything a release writes: raw ClimateNA outputs (`raw/`, one zip and one stamp per tile and year or period), the published zips (`zips/`), the targets store (`_targets/`), logs, the index and the report. **Keep the same `out_root` from one release to the next**: the next release then reuses the raw outputs and zips that haven't changed, and their objects in the bucket. **Give each resolution its own `out_root`**, and never point the other resolution's run at it: their raw outputs have the same names but different DEM tiles, so that run would delete and rerun every period, overwriting the first resolution's outputs. `tar_make()` checks this: the first run writes the resolution to `/dem_resolution` (an older `out_root` takes it from its index), and a run at the other resolution stops before anything runs. ## Tiles and DEM tiles @@ -167,12 +167,12 @@ Fix the cause and run `tar_make()` again. Only what failed reruns. Every run als ## Adding a year -Each new year of data comes with a new ClimateNA release. +Each new year of data comes with a new ClimateNA release. Each resolution is a release of its own, so every change below goes into both `release.yml` (3 arcmin) and `release-1arcmin.yml` (a test checks that they differ only in `release_id` and `dem_resolution`), and the pipeline runs once for each, with that resolution's `release_file`, `dem_dir` and `out_root` in `_local.R`. 1. Unpack the new ClimateNA next to the old one, and point `climatena_dir` in `_local.R` at it. -2. In `release.yml`, set a new `release_id` (e.g. `cna-v7.80-3arcmin`), `climatena_exe`, `climatena_version`, and extend `historical_years`. Leave `min_version` alone. +2. In both release files, set a new `release_id` (e.g. `cna-v7.80-3arcmin` and `cna-v7.80-1arcmin`), `climatena_exe`, `climatena_version`, and extend `historical_years`. Leave `min_version` alone. 3. In `R/available.R`, extend the historical years in `available()`. -4. Run the pipeline as above (dry run first). +4. Run the pipeline as above (dry run first), once per resolution, and ship both indexes. Before any batch runs, `compat_` reruns a sample of the stored outputs with the new ClimateNA (tiles 6, 39 and 77 when present; each tile's first and last year or period) and compares them with the stored ones: @@ -181,7 +181,7 @@ Before any batch runs, `compat_` reruns a sample of the stored outputs wit ## Adding a GCM or SSP -Add it to `gcms` or `ssps` in `release.yml`, and to the lists in `available()` (`R/available.R`). Only the new scenario's batches run; existing scenarios are untouched. +Add it to `gcms` or `ssps` in both release files, and to the lists in `available()` (`R/available.R`), then run the pipeline for each resolution. Only the new scenario's batches run; existing scenarios are untouched. ## Access to the bucket @@ -229,14 +229,16 @@ The bucket has a browsable catalogue: an `index.html` in every folder, at `