Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<type>`. `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_<type>`. `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_<type>` tables, written by the
Windows-era build scripts (removed in 2.3.0); the pipeline's index has none. Don't assume they
Expand Down
15 changes: 15 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -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. `<dstdir>/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
Expand Down
23 changes: 19 additions & 4 deletions R/ClimateNA_createTiles.R
Original file line number Diff line number Diff line change
@@ -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
Expand Down
13 changes: 11 additions & 2 deletions R/ClimateNA_useTiles.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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_`.
Expand Down
15 changes: 8 additions & 7 deletions R/dataRelease.R
Original file line number Diff line number Diff line change
@@ -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
Expand Down
5 changes: 3 additions & 2 deletions R/filledCells.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions R/latestHistoricalYear.R
Original file line number Diff line number Diff line change
@@ -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.
#'
Expand Down
38 changes: 24 additions & 14 deletions R/prepClimateLayers.R
Original file line number Diff line number Diff line change
Expand Up @@ -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
#'
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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
)
}

Expand Down Expand Up @@ -511,6 +520,7 @@ prepClimateLayers <- function(
digest4cache <- c(
"climatePathOut",
"currentModuleName",
"releaseId",
.allowedClimDotsNames,
"rasterToMatch",
"studyArea",
Expand Down
3 changes: 2 additions & 1 deletion R/zzz.R
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
53 changes: 53 additions & 0 deletions data-raw/pipeline/R/out_root.R
Original file line number Diff line number Diff line change
@@ -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 (<out_root>/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_
}
3 changes: 2 additions & 1 deletion data-raw/pipeline/_local.R.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions data-raw/pipeline/_targets.R
Original file line number Diff line number Diff line change
Expand Up @@ -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_<dem_resolution>.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)) {
Expand Down Expand Up @@ -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)),
Expand Down
51 changes: 51 additions & 0 deletions data-raw/pipeline/release-1arcmin.yml
Original file line number Diff line number Diff line change
@@ -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_<type> 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
## <prefix>/<release_id>/<zip path>, public at <endpoint>/<container>/<key>. 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]
Loading