diff --git a/.Rbuildignore b/.Rbuildignore index dd8983d..8f3686f 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -15,3 +15,6 @@ ^\.claude$ ^_tmp$ ^docker$ +^_pkgdown\.yml$ +^docs$ +^pkgdown$ diff --git a/.github/workflows/pkgdown.yaml b/.github/workflows/pkgdown.yaml new file mode 100644 index 0000000..d91834a --- /dev/null +++ b/.github/workflows/pkgdown.yaml @@ -0,0 +1,20 @@ +## Thin caller -- the pkgdown build and the gh-pages deploy live in PredictiveEcology/actions. + +name: pkgdown + +on: + push: + branches: [main, master] + pull_request: + branches: [main, master] + release: + types: [published] + workflow_dispatch: + +permissions: + contents: write + +jobs: + pkgdown: + uses: PredictiveEcology/actions/.github/workflows/pkgdown.yaml@main + ## No `secrets:` block: the shared workflow uses only the automatic GITHUB_TOKEN. diff --git a/.gitignore b/.gitignore index 5d46317..15023ac 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,9 @@ tmp/ ## scratch: drafts, plans, handoffs _tmp/ + +## pkgdown site (built by GitHub Actions) +docs/ + +## per-machine pipeline settings +data-raw/pipeline/_local.R diff --git a/CLAUDE.md b/CLAUDE.md index 28426a0..12dad73 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -91,8 +91,11 @@ serialization cheap. `stopForInvalidBackend()` centralizes the error path. The index at `inst/extdata/ClimateNA_tiles.sqlite` holds four main tables — `historical`, `historical_normals`, `future`, `future_normals`. `gid` is the Google Drive -file ID; archives are grouped by decade, so many rows share a `gid`. The connection opens in -WAL mode with a 60s busy timeout to allow concurrent writers from the `data-raw/` scripts. +file ID; archives are grouped by decade, so many rows share a `gid`. `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. Optional `checksums_` tables are created by `checksums_sql()` when a maintainer runs the `data-raw/` checksum loops; they may or may not be present in a given copy of the bundled diff --git a/DESCRIPTION b/DESCRIPTION index d135c4f..b5a11a7 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: climateData Title: Utilities For Working With North American Climate Data -Version: 2.2.3.9011 +Version: 2.2.3.9012 Date: 2026-04-15 Authors@R: c( person("Alex M", "Chubaty", email = "achubaty@for-cast.ca", @@ -13,7 +13,8 @@ Authors@R: c( Description: Utilities for working with North American climate data from 'ClimateNA' . License: GPL-3 -URL: https://github.com/PredictiveEcology/climateData +URL: https://predictiveecology.github.io/climateData/, + https://github.com/PredictiveEcology/climateData BugReports: https://github.com/PredictiveEcology/climateData/issues Depends: R (>= 4.4) @@ -50,10 +51,12 @@ Suggests: rprojroot, SpaDES.tools (>= 2.0.4), sys, + targets, testthat (>= 3.0.0), withr VignetteBuilder: - knitr + knitr, + rmarkdown Remotes: PredictiveEcology/reproducible@development, PredictiveEcology/SpaDES.tools@development diff --git a/NAMESPACE b/NAMESPACE index 6e41c4c..649106a 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -13,10 +13,12 @@ export(calcMDC) export(calcStackLayersType) export(checkCalcStackLayers) export(checksums_sql) +export(climateDataRelease) export(climateLayers) export(climateStacksByPeriod) export(climateStacksByYear) export(extractTimes) +export(filledCells) export(getClimateTable) export(getClimateTiles) export(getClimateURLs) diff --git a/NEWS.md b/NEWS.md index dd311a7..4ed045c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,24 @@ # climateData (development version) +- Land cells where ClimateNA writes no values now hold ClimateNA's own values for the nearest land + cell it covers within 50 km, computed at the empty cell's elevation (in the 3 arcmin release, a + median of 3.5 km away; 90% within 10 km). ClimateNA's future data miss some coastal cells (e.g. + every land cell of tile 63, on Baffin Island's east coast), and a few cells had no values at all. + Of 608 such cells, 48 have no covered land cell within 50 km and stay empty. New `filledCells()` + lists these cells, with where ClimateNA was run for each. +- The 3 arcmin release no longer has a tile 53: at 3 arcmin it has no land cell, and its archives + had been built from the 1 arcmin DEM tile. + +- New `climateDataRelease()` identifies the climate data release behind the installed package + (e.g. `"cna-v7.70-3arcmin"`). Code that caches `prepClimateLayers()` results can add it to the + cache key, so a new data release isn't served from an old cache. +- Historical data now run to 2025 (ClimateNA v7.70). +- Future climate normals (2011-2040, 2041-2070, 2071-2100) can be requested, e.g. `future_MAT_normal` + with `future_period`. `prepClimateLayers()` used to stop with "future normals not yet implemented". +- `prepClimateLayers()` downloads and extracts archives to a subfolder of `srcdir` named for the + data release (e.g. `/cna-v7.70-3arcmin/historical/39/`). A new release's archives keep + the earlier file names: in a `srcdir` that already held them, the download was skipped and the + old data were used. Folders from earlier releases are not read and can be deleted. - Reading the bundled tile index (`latestHistoricalYear()`, the tile lookup in `ClimateNA_useTiles()`) no longer writes `-wal`/`-shm` files into the installed package folder. Read-only `ClimateNA_sql()` connections open the file with SQLite's `immutable=1`, and the bundled index is shipped in rollback-journal mode instead of WAL. @@ -8,22 +27,27 @@ and set the SQLite busy timeout before any other statement. Before, many processes opening it together (e.g. parallel hindcast jobs parsing fireSense modules on NFS) could fail with "database is locked". `ClimateNA_sql()` gets a `readonly` argument; writing connections set WAL only when they create the file. - + The bundled index is no longer in WAL mode, so these lookups also work from a library folder the user + cannot write to, and leave no `-wal`/`-shm` files in it. - Solar radiation variables now use the ClimateNA v7.60+ names: `rsds` (annual; was `MAR`), `rsds_wt`, `rsds_sp`, `rsds_sm`, `rsds_at` (seasonal; were `Rad_*`) and `rsds01`-`rsds12` (monthly; were `Rad01`-`Rad12`). - ClimateNA v7.60 (April 2025) replaced its RAD variables with rsds, based on CHELSA. Only the historical - 2023 and 2024 data were made with v7.60, so radiation can't be requested for other years or for future - scenarios until those archives are regenerated. The old radiation layers held values only for 1948-2010. - + ClimateNA v7.60 (April 2025) replaced its RAD variables with rsds, based on CHELSA. All archives were + rebuilt with ClimateNA v7.70 (data release `cna-v7.70-3arcmin`), so radiation now has values for every + historical year and future scenario. The old radiation layers held values only for 1948-2010. - The `prepClimateLayers()` cache key now includes the bodies of the functions that build the layers - (`maskInvalidPPT()`, `climateMosaicsParallel()`, the `calc*()` functions ...). Before, layers cached - before the PPT guard or before the `reproducible` 3.2.1.9060 `postProcessTo()` smoothing fix kept - coming back from the cache. Every existing entry is rebuilt once. Mosaics themselves were always rebuilt + (`climateMosaicsParallel()`, the `calc*()` functions ...). Before, layers cached before a change to + them, or before the `reproducible` 3.2.1.9060 `postProcessTo()` smoothing fix, kept coming back from + the cache. Every existing entry is rebuilt once. Mosaics themselves were always rebuilt (`overwrite = TRUE`); only the final cached `postProcessTo()` step was stale. - -- `climateMosaicsParallel()` sets every variable to NA, for that year, in cells where all 12 monthly `PPT` values are - exactly 0. ClimateNA tiles 6 and 7 have such cells south of the Canada/US border (45.8-49 N), where the DEM is - not valid and temperatures are nonsense (Tmax up to 42.7 C); they gave absurd `cumMDC` and `CMD`. +- Cells outside Canada that have no DEM elevation are NA (#40). The DEM tiles cover Canada and a 3 arcmin + margin, but ClimateNA still wrote values beyond it, computed at the wrong elevation: next to the border, + US cells were a median 4.5 C warmer than the Canadian cells beside them (tile 6, 1991-2020 normals), and + tiles 6 and 7 had cells with no precipitation at all and Tmax up to 42.7 C, which gave absurd `cumMDC` + and `CMD`. In data release `cna-v7.70-3arcmin` these cells are NA in every archive, normals included. + Canadian coast and lakeshore cells with no DEM value keep their values. This replaces a check on reading + (cells whose 12 monthly `PPT` were all 0), which found only the zero-precipitation cells, and only when + the monthly files were downloaded. Seasonal variables requested alone now come from the smaller S + archives. - When a seasonal variable is needed, monthly and yearly variables now come from the same MSY ("all") archive, which contains all their files. Before, they were also downloaded from their own M and Y archives diff --git a/R/ClimateNA_createTiles.R b/R/ClimateNA_createTiles.R index 620f708..c5039a0 100644 --- a/R/ClimateNA_createTiles.R +++ b/R/ClimateNA_createTiles.R @@ -160,6 +160,10 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { ## dbplyr is an Import: without it every tile lookup fails, as R CMD check without Suggests showed. ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { db <- sqlite_connect_db(dbfile, readonly = readonly) + ## the caller owns the connection once it is returned; close it if anything below fails + ## (e.g. a read-only lookup of a table the file lacks) + returned <- FALSE + on.exit(if (!returned) DBI::dbDisconnect(db), add = TRUE) df_template <- switch( type, @@ -172,7 +176,8 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { zipfile = "CHARACTER", ## relative file path archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME" ## timestamp of when archive uploaded to google drive + uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive + climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period ), future_normals = c( id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", @@ -185,7 +190,8 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { zipfile = "CHARACTER", ## relative file path archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME" ## timestamp of when archive uploaded to google drive + uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive + climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period ), historical = c( id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", @@ -196,7 +202,8 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { zipfile = "CHARACTER", ## relative file path archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME" ## timestamp of when archive uploaded to google drive + uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive + climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period ), future = c( id = "INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE", @@ -209,7 +216,8 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { zipfile = "CHARACTER", ## relative file path archived = "DATETIME", ## timestamp of when tile set archive was created (zipped) gid = "CHARACTER", ## google drive file id; archives built by decade, so there will be dupe gids - uploaded = "DATETIME" ## timestamp of when archive uploaded to google drive + uploaded = "DATETIME", ## timestamp of when archive uploaded to google drive + climatena_version = "CHARACTER" ## ClimateNA version that produced this year/period ) ) @@ -221,6 +229,7 @@ ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { df <- dplyr::tbl(db, tbl) + returned <- TRUE return(list(db = db, df = df)) } @@ -280,6 +289,92 @@ checksums_sql <- function(dbfile, type) { return(list(db = db, df = df)) } +## The data release behind an index: one row, written by the pipeline (data-raw/pipeline/) and +## read by climateDataRelease(). Written with explicit SQL types. +.releaseCreate <- function(db) { + DBI::dbExecute( + db, + "CREATE TABLE IF NOT EXISTS release ( + release_id TEXT NOT NULL, -- e.g. cna-v7.70-3arcmin + climatena_version TEXT NOT NULL, -- ClimateNA release that produced the data + dem_resolution TEXT NOT NULL, -- e.g. 3arcmin, 1arcmin + created REAL NOT NULL -- epoch seconds + )" + ) + invisible(db) +} + +.releaseWrite <- function(db, df) { + DBI::dbExecute(db, "DELETE FROM release") + DBI::dbExecute( + db, + "INSERT INTO release (release_id, climatena_version, dem_resolution, created) VALUES (?, ?, ?, ?)", + params = unname(as.list(df[ + 1, + c("release_id", "climatena_version", "dem_resolution", "created") + ])) + ) + invisible(db) +} + +## Land cells ClimateNA left empty, filled from its point-mode output at the nearest land cell it +## covers (data-raw/pipeline/R/fill.R): one row per cell and class (historical: historical years +## and normals; future: future years and normals). A cell left empty (no source within reach) +## has NULL src_lon, src_lat and km. Written by the pipeline, read by filledCells(). +.filledCellsColumns <- c( + "class", + "tileid", + "cell", + "lon", + "lat", + "elev", + "src_lon", + "src_lat", + "km" +) + +.filledCellsCreate <- function(db) { + DBI::dbExecute( + db, + "CREATE TABLE IF NOT EXISTS filled_cells ( + class TEXT NOT NULL, -- historical | future + tileid INTEGER NOT NULL, + cell INTEGER NOT NULL, -- cell in the tile's DEM grid, row by row from the top left + lon REAL NOT NULL, -- cell centre + lat REAL NOT NULL, + elev REAL NOT NULL, -- the cell's DEM elevation (m), which ClimateNA was run with + src_lon REAL, -- where ClimateNA was run; NULL if the cell is left empty + src_lat REAL, + km REAL, -- distance from the cell's centre to the source + PRIMARY KEY (class, tileid, cell) + )" + ) + invisible(db) +} + +## Replace the table's rows with `df` (as pipeline_fill_points() gives it: `tile` for tileid, and +## the elevation as text). +.filledCellsWrite <- function(db, df) { + if (!"tileid" %in% names(df)) { + df$tileid <- df$tile + } + df$tileid <- as.integer(df$tileid) + df$cell <- as.integer(df$cell) + df$elev <- as.numeric(df$elev) + DBI::dbExecute(db, "DELETE FROM filled_cells") + if (nrow(df) > 0) { + sql <- paste0( + "INSERT INTO filled_cells (", + paste(.filledCellsColumns, collapse = ", "), + ") VALUES (", + paste(rep("?", length(.filledCellsColumns)), collapse = ", "), + ")" + ) + DBI::dbExecute(db, sql, params = unname(as.list(df[.filledCellsColumns]))) + } + invisible(db) +} + ## One fingerprint per published zip (see data-raw/06-archive_fingerprints.R). ## Written with explicit SQL types: dplyr::rows_*() would remap them. .archivesColumns <- c("gid", "type", "zipfile", "md5", "n_files", "size", "verified") diff --git a/R/ClimateNA_useTiles.R b/R/ClimateNA_useTiles.R index 5c5f29e..ec3bb3f 100644 --- a/R/ClimateNA_useTiles.R +++ b/R/ClimateNA_useTiles.R @@ -295,25 +295,6 @@ extractJustAFew <- function(workingPath, archiveFile, climateVarsGrep) { lala } -#' Read a tile's climate file, with invalid cells set to NA -#' -#' ClimateNA tiles 6 and 7 have cells south of the Canada/US border where the DEM is not valid: -#' all 12 monthly `PPT` values are exactly 0 and temperatures are nonsense. Such cells are set -#' to NA, for every variable, so an overlapping valid tile can show through in the mosaic. -#' The `PPT01`-`PPT12` files are read from the same year directory as `file`. -#' -#' @param file character. A single tile-year climate file. -#' @return a `SpatRaster`. -#' @keywords internal -maskInvalidPPT <- function(file) { - r <- terra::rast(file) - ppt <- file.path(dirname(file), sprintf("PPT%02d.asc", 1:12)) - if (all(file.exists(ppt))) { - r <- terra::mask(r, sum(terra::rast(ppt)) == 0, maskvalues = TRUE) - } - r -} - #' Build climate mosaic rasters from ClimateNA tiles #' #' Internal functions run in parallel by `buildClimateMosaics()` and @@ -351,10 +332,11 @@ climateMosaicsParallel <- function(y, climVars, tile, srcdir, dstdir) { # ss <- mget(ls()) # save(ss, file = paste0("~/tmp/stuff", basename(tempfile()), ".rda")) + ## cells ClimateNA computed without a DEM elevation are already NA in the archives if (length(srcfiles) == 1) { - newMosaic <- maskInvalidPPT(srcfiles) + newMosaic <- terra::rast(srcfiles) } else { - newMosaic <- lapply(srcfiles, maskInvalidPPT) |> terra::sprc() |> terra::mosaic() + newMosaic <- lapply(srcfiles, terra::rast) |> terra::sprc() |> terra::mosaic() } writeRaster(newMosaic, filename = dsttif, overwrite = TRUE) @@ -472,13 +454,29 @@ buildClimateMosaics <- function( #' #' @keywords internal #' @rdname climateMosaicsParallel -climateMosaicsNormalsParallel <- function(p, climVars, tile, srcdir, dstdir) { +climateMosaicsNormalsParallel <- function( + p, + climVars, + tile, + srcdir, + dstdir, + gcm = NULL, + ssp = NULL +) { + ## future normals: several scenarios share a tile folder, so select this scenario's period + ## folder exactly (named as ClimateNA writes it, e.g. CanESM5_ssp245_2011-2040Y) + periodRegexp <- if (is.null(gcm)) { + paste0("[^/\\\\]*", p, "[^/\\\\]*$") + } else { + paste0("(/|\\\\)", .periodFolder("future_normals", p, "Y", gcm, ssp), "$") + } + scenario <- if (is.null(gcm)) NULL else paste0(gcm, "_ssp", ssp) lapply(climVars, function(v) { nv <- strsplit(v, "_normal")[[1]] srcfiles <- srcdir |> ## anchor at the path separator: "6$" alone also matches tile directories 16, 26, ... fs::dir_ls(regexp = paste0("(/|\\\\)", tile, "$", collapse = "|"), type = "directory") |> - fs::dir_ls(regexp = paste0("[^/\\\\]*", p, "[^/\\\\]*$"), type = "directory") |> + fs::dir_ls(regexp = periodRegexp, type = "directory") |> fs::dir_ls(regexp = paste0("(/|\\\\)", nv, "[.]asc$"), type = "file") stopifnot(length(srcfiles) > 0) @@ -486,7 +484,10 @@ climateMosaicsNormalsParallel <- function(p, climVars, tile, srcdir, dstdir) { ## vrts must be a single layer, so need to do e.g. monthly climVars by each month lapply(unique(basename(srcfiles)), function(mv) { mv <- tools::file_path_sans_ext(mv) - fname <- paste(mv, basename(basename(srcdir)), p, "t", paste(tile, collapse = "-"), sep = "_") + fname <- paste( + c(mv, basename(srcdir), scenario, p, "t", paste(tile, collapse = "-")), + collapse = "_" + ) dstvrt <- file.path(tempdir(), paste0(fname, ".vrt")) dsttif <- file.path(dstdir, paste0(fname, ".tif")) @@ -554,7 +555,9 @@ buildClimateMosaicsNormals <- function( climVars = climVars, tile = tile, srcdir = srcdir, - dstdir = dstdir + dstdir = dstdir, + gcm = gcm, + ssp = ssp ) } else if (getOption("climateData.parallel.backend") == "future") { tifs <- future.apply::future_lapply( @@ -563,7 +566,9 @@ buildClimateMosaicsNormals <- function( climVars = climVars, tile = tile, srcdir = srcdir, - dstdir = dstdir + dstdir = dstdir, + gcm = gcm, + ssp = ssp ) } else { stopForInvalidBackend() diff --git a/R/archiveCheck.R b/R/archiveCheck.R index 7cd4d76..397db6c 100644 --- a/R/archiveCheck.R +++ b/R/archiveCheck.R @@ -9,7 +9,7 @@ ## Member paths ("/.asc") that the zip holding these index rows should contain. .archiveExpected <- function(rows, type) { - stopifnot(type %in% c("historical", "historical_normals", "future")) + stopifnot(type %in% c("historical", "historical_normals", "future", "future_normals")) keys <- intersect(c("zipfile", "tileid", "msy", "gcm", "ssp"), names(rows)) multi <- keys[vapply(rows[keys], \(x) length(unique(x)) > 1, logical(1))] @@ -26,16 +26,10 @@ } msy <- rows$msy[1] - folders <- switch( - type, - historical = paste0("Year_", rows$year, msy), - historical_normals = paste0("Normal_", rows$period, msy), - future = paste0(rows$gcm[1], "_ssp", rows$ssp[1], "@", rows$year, msy) - ) |> - unique() |> - sort() - - vars <- if (type == "historical_normals") { + period <- if (type %in% c("historical", "future")) rows$year else rows$period + folders <- .periodFolder(type, period, msy, rows$gcm[1], rows$ssp[1]) |> unique() |> sort() + + vars <- if (type %in% c("historical_normals", "future_normals")) { .allowedClimateVars_nrm } else { switch( @@ -145,7 +139,7 @@ av <- available(type) when <- if (is.null(av$years)) "period" else "year" grid <- list(tileid = unique(index$tileid), msy = unique(index$msy)) - if (type == "future") { + if (type %in% c("future", "future_normals")) { grid <- c(grid, list(gcm = av$gcms, ssp = av$ssps)) } grid[[when]] <- if (when == "year") av$years else av$periods diff --git a/R/available.R b/R/available.R index 838d077..00fd3c8 100644 --- a/R/available.R +++ b/R/available.R @@ -2,7 +2,7 @@ ## Solar radiation is named as in ClimateNA v7.60 (April 2025), which replaced its RAD ## variables (Rad01-Rad12, Rad_at/sm/sp/wt, MAR) with rsds (rsds01-rsds12, rsds_at/sm/sp/wt, -## rsds). Archives made with earlier versions still hold the old names until regenerated. +## rsds). Every archive in the cna-v7.70-3arcmin data release was made with v7.70. # dir("~/data/climate/ClimateNA_data/historical/normals/yearly/16/Normal_1991_2020Y") |> # tools::file_path_sans_ext() |> @@ -114,7 +114,7 @@ available <- function(type) { ## fmt: skip switch(type, historical = list( - years = 1901L:2024L + years = 1901L:2025L ), historical_normals = list( periods = c( diff --git a/R/climatenaDocker.R b/R/climatenaDocker.R new file mode 100644 index 0000000..5be838d --- /dev/null +++ b/R/climatenaDocker.R @@ -0,0 +1,107 @@ +## Docker arguments for one ClimateNA run in the climatena-wine image (docker/climatena/). +## +## ClimateNA is mounted read-only; the DEM tile's folder and the tile's raw-output folder are +## mounted at /data/dem and /data/out, and ClimateNA writes //. The +## container runs as the image's user (`--user`), with one CPU and a memory cap. +.climatenaDockerArgs <- function( + name, + image, + climatenaDir, + demFile, + outDir, + exe, + msy, + periodArg, + uid, + gid, + cpus = 1, + memory = "1g" +) { + c( + "run", + "--rm", + "--name", + name, + "--user", + paste0(uid, ":", gid), + "--cpus", + as.character(cpus), + "--memory", + memory, + "-v", + paste0(climatenaDir, ":/opt/climatena:ro"), + "-v", + paste0(dirname(demFile), ":/data/dem:ro"), + "-v", + paste0(outDir, ":/data/out"), + image, + exe, + msy, + periodArg, + file.path("/data/dem", basename(demFile)), + "/data/out" + ) +} + +## Docker arguments for one ClimateNA point-mode run: ClimateNA reads `inCsv` (columns id1, id2, +## lat, long, elev) and writes `outCsv`, both in `workDir`, mounted at /data/w. The image's +## climatena-run wrapper would create the output path as a folder, so `sh` runs Wine the same +## way here: the user check, ClimateNA's own directory, xvfb-run, then waiting for wineserver. +## The script is shell-quoted, ready for system2(). +.climatenaPointDockerArgs <- function( + name, + image, + climatenaDir, + workDir, + exe, + msy, + periodArg, + inCsv, + outCsv, + uid, + gid, + cpus = 1, + memory = "1g" +) { + winPath <- function(f) paste0('"/Z:\\data\\w\\', f, '"') + script <- paste( + 'owner=$(stat -c %u "$WINEPREFIX")', + 'if [ "$(id -u)" != "$owner" ]; then', + ' echo "run with --user matching the image (Wine prefix owned by uid $owner)" >&2; exit 64', + "fi", + "cd /opt/climatena", + paste( + "xvfb-run -a wine", + exe, + paste0("/", msy), + paste0("/", periodArg), + winPath(inCsv), + winPath(outCsv) + ), + "rc=$?", + "wineserver -w || true", + "exit $rc", + sep = "\n" + ) + c( + "run", + "--rm", + "--name", + name, + "--user", + paste0(uid, ":", gid), + "--cpus", + as.character(cpus), + "--memory", + memory, + "-v", + paste0(climatenaDir, ":/opt/climatena:ro"), + "-v", + paste0(workDir, ":/data/w"), + "--entrypoint", + "sh", + image, + "-c", + shQuote(script) # system2() passes arguments to the host shell as they are + ) +} diff --git a/R/dataRelease.R b/R/dataRelease.R new file mode 100644 index 0000000..86fbc2c --- /dev/null +++ b/R/dataRelease.R @@ -0,0 +1,31 @@ +#' Identify the climate data release behind the installed package +#' +#' Each climateData release ships a tile index pointing at one release of the ClimateNA +#' archives on Google Drive. 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. +#' +#' @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 +#' made before releases were recorded give `release_id = "pre-3.0.0"`. +#' +#' @export +#' @examples +#' climateDataRelease()$release_id +climateDataRelease <- function() { + ## read-only, in place: called on every run of code that caches, often by many processes at once + db <- sqlite_connect_db(ClimateNA_tiles_sqlite(), readonly = TRUE) + on.exit(DBI::dbDisconnect(db), add = TRUE) + + if (!DBI::dbExistsTable(db, "release")) { + return(list( + release_id = "pre-3.0.0", + climatena_version = NA_character_, + dem_resolution = "3arcmin" + )) + } + r <- DBI::dbGetQuery( + db, + "SELECT release_id, climatena_version, dem_resolution FROM release LIMIT 1" + ) + as.list(r[1, ]) +} diff --git a/R/filledCells.R b/R/filledCells.R new file mode 100644 index 0000000..f15b17f --- /dev/null +++ b/R/filledCells.R @@ -0,0 +1,75 @@ +#' Land cells filled from a nearby point +#' +#' 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 +#' mapped, or masked out of an analysis. +#' +#' `class` says which archives a cell was filled in: `"historical"` (historical years and +#' normals) or `"future"` (future years and normals). A cell with `filled = FALSE` had no +#' covered land cell within reach, and has no values. +#' +#' @param studyArea optional `sf`, `sfc` or `SpatVector` polygon(s), in any CRS: only cells +#' inside are returned. +#' @param tiles optional integer tile IDs. +#' +#' @return an `sf` of points (the cells' centres, EPSG:4326) with columns `class`, `tile`, +#' `cell` (the cell number in the tile's grid, row by row from the top left), `elev` (the +#' cell's elevation, m), `filled`, `src_lon` and `src_lat` (where ClimateNA was run) and `km` +#' (the distance to it). No rows for a data release without filled cells. +#' +#' @export +#' @examples +#' \donttest{ +#' fc <- filledCells() +#' table(fc$class, fc$filled) +#' } +filledCells <- function(studyArea = NULL, tiles = NULL) { + db <- sqlite_connect_db(ClimateNA_tiles_sqlite(), readonly = TRUE) + on.exit(DBI::dbDisconnect(db), add = TRUE) + + x <- if (DBI::dbExistsTable(db, "filled_cells")) { + DBI::dbGetQuery( + db, + "SELECT class, tileid, cell, lon, lat, elev, src_lon, src_lat, km + FROM filled_cells ORDER BY class, tileid, cell" + ) + } else { + data.frame( + class = character(0), + tileid = integer(0), + cell = integer(0), + lon = numeric(0), + lat = numeric(0), + elev = numeric(0), + src_lon = numeric(0), + src_lat = numeric(0), + km = numeric(0) + ) + } + names(x)[names(x) == "tileid"] <- "tile" + if (!is.null(tiles)) { + x <- x[x$tile %in% as.integer(tiles), , drop = FALSE] + } + x$filled <- !is.na(x$src_lon) + x <- x[c("class", "tile", "cell", "lon", "lat", "elev", "filled", "src_lon", "src_lat", "km")] + ## built from sfc points: st_as_sf(coords =) warns when there are none + pts <- sf::st_sf( + x[setdiff(names(x), c("lon", "lat"))], + geometry = sf::st_sfc( + lapply(seq_len(nrow(x)), \(i) sf::st_point(c(x$lon[i], x$lat[i]))), + crs = 4326 + ) + ) + + if (!is.null(studyArea)) { + if (inherits(studyArea, "SpatVector")) { + studyArea <- sf::st_as_sf(studyArea) + } + within <- sf::st_intersects(sf::st_transform(pts, sf::st_crs(studyArea)), studyArea) + pts <- pts[lengths(within) > 0, ] + } + rownames(pts) <- NULL + pts +} diff --git a/R/pipelineBatches.R b/R/pipelineBatches.R new file mode 100644 index 0000000..e24db30 --- /dev/null +++ b/R/pipelineBatches.R @@ -0,0 +1,102 @@ +## Batch specs and ClimateNA names for the data pipeline (data-raw/pipeline/). +## +## A batch is the unit that becomes one zip per subset: a tile's decade (historical, future) or +## all of a tile's normals periods. Each spec is a plain list whose content alone identifies it, +## so the pipeline's dynamic branches keep their identity when years, GCMs or SSPs are added. + +.batchTypes <- c("historical", "future", "historical_normals", "future_normals") + +## The folder ClimateNA writes for one period (checked against ClimateNA v7.70 output). +.periodFolder <- function(type, period, msy, gcm = NULL, ssp = NULL) { + stopifnot(type %in% .batchTypes) + switch( + type, + historical = paste0("Year_", period, msy), + future = paste0(gcm, "_ssp", ssp, "@", period, msy), + historical_normals = paste0("Normal_", period, msy), + future_normals = paste0(gcm, "_ssp", ssp, "_", gsub("_", "-", period), msy) + ) +} + +## The period argument ClimateNA takes for one period. +.periodArg <- function(type, period, gcm = NULL, ssp = NULL) { + stopifnot(type %in% .batchTypes) + switch( + type, + historical = paste0("Year_", period, ".ann"), + future = paste0(gcm, "_ssp", ssp, "@", period, ".gcm"), + historical_normals = paste0("Normal_", period, ".nrm"), + future_normals = paste0(gcm, "_ssp", ssp, "_", gsub("_", "-", period), ".gcm") + ) +} + +## One spec per batch: list(id, type, tile, gcm, ssp, msy, decade, periods), ordered by tile, +## gcm, ssp and decade. Historical and future batches hold a decade's years; normals batches +## hold all of a tile's (or tile-scenario's) periods. +.batchSpecs <- function(type, tiles, gcms = NULL, ssps = NULL, years = NULL, periods = NULL) { + stopifnot(type %in% .batchTypes) + future <- type %in% c("future", "future_normals") + normals <- type %in% c("historical_normals", "future_normals") + scen <- if (future) { + expand.grid(gcm = gcms, ssp = as.character(ssps), stringsAsFactors = FALSE) + } else { + data.frame(gcm = NA_character_, ssp = NA_character_) + } + scen <- scen[order(scen$gcm, scen$ssp), , drop = FALSE] + + specs <- list() + for (tile in sort(as.integer(tiles))) { + for (s in seq_len(nrow(scen))) { + gcm <- scen$gcm[s] + ssp <- scen$ssp[s] + prefix <- if (future) paste(type, tile, gcm, ssp, sep = "_") else paste(type, tile, sep = "_") + if (normals) { + specs[[length(specs) + 1]] <- list( + id = prefix, + type = type, + tile = tile, + gcm = gcm, + ssp = ssp, + msy = "Y", + decade = NA_integer_, + periods = periods + ) + } else { + yrs <- as.integer(years) + for (dcd in sort(unique(yrs %/% 10L * 10L))) { + specs[[length(specs) + 1]] <- list( + id = paste(prefix, dcd, sep = "_"), + type = type, + tile = tile, + gcm = gcm, + ssp = ssp, + msy = "MSY", + decade = dcd, + periods = yrs[yrs %/% 10L * 10L == dcd] + ) + } + } + } + } + specs +} + +## Tile IDs that have a DEM tile (can_dem_.asc) in `demDir`, or the requested `tiles`, all +## of which must have one. Stops rather than return no tiles: no batches would give an empty +## index and an empty report, which reads as a clean release. +.demTiles <- function(demDir, tiles = NULL) { + f <- list.files(demDir, pattern = "^can_dem_[0-9]+[.]asc$") + have <- sort(as.integer(sub("^can_dem_([0-9]+)[.]asc$", "\\1", f))) + if (length(have) == 0) { + stop("No DEM tiles (can_dem_.asc) in ", demDir, call. = FALSE) + } + if (is.null(tiles)) { + return(have) + } + tiles <- as.integer(tiles) + missing <- setdiff(tiles, have) + if (length(missing) > 0) { + stop("No DEM tile in ", demDir, " for tile(s) ", paste(missing, collapse = ", "), call. = FALSE) + } + sort(tiles) +} diff --git a/R/pipelineCompat.R b/R/pipelineCompat.R new file mode 100644 index 0000000..c82dfaf --- /dev/null +++ b/R/pipelineCompat.R @@ -0,0 +1,48 @@ +## Compatibility check of a new ClimateNA release against stored outputs (data-raw/pipeline/). +## +## ClimateNA writes ESRI ASCII grids: 6 header lines, then the cell values as text. The values +## are compared as text-parsed numbers (not via terra), so the check sees exactly what ClimateNA +## wrote. Windows line endings are ignored; any header difference counts as every cell differing. + +.readAsc <- function(path) { + lines <- sub("\r$", "", readLines(path, warn = FALSE)) + list( + header = gsub("[[:space:]]+", " ", trimws(lines[1:6])), + values = scan(text = lines[-(1:6)], quiet = TRUE) + ) +} + +.compareAsc <- function(a, b) { + x <- .readAsc(a) + y <- .readAsc(b) + if (!identical(x$header, y$header) || length(x$values) != length(y$values)) { + n <- max(length(x$values), length(y$values)) + return(data.frame(cells = n, differing = as.integer(n), max_abs = Inf)) + } + d <- abs(x$values - y$values) + data.frame(cells = length(d), differing = sum(d != 0), max_abs = if (length(d) > 0) max(d) else 0) +} + +## One row per .asc file in either folder; a file on only one side has NA counts. +.compareFolders <- function(dirA, dirB) { + files <- sort(union(list.files(dirA, pattern = "[.]asc$"), list.files(dirB, pattern = "[.]asc$"))) + rows <- lapply(files, function(f) { + a <- file.path(dirA, f) + b <- file.path(dirB, f) + if (!file.exists(a) || !file.exists(b)) { + return(data.frame(file = f, cells = NA_integer_, differing = NA_integer_, max_abs = NA_real_)) + } + cbind(file = f, .compareAsc(a, b)) + }) + do.call(rbind, rows) +} + +## "compatible" when the file sets match, at most `maxFrac` of all cells differ, and no +## difference exceeds `maxAbs`; otherwise "changed". +.compatVerdict <- function(comparisons, maxFrac = 1e-5, maxAbs = 1) { + if (nrow(comparisons) == 0 || anyNA(comparisons$cells)) { + return("changed") + } + frac <- sum(comparisons$differing) / sum(comparisons$cells) + if (frac <= maxFrac && all(comparisons$max_abs <= maxAbs)) "compatible" else "changed" +} diff --git a/R/pipelineFill.R b/R/pipelineFill.R new file mode 100644 index 0000000..c7b4396 --- /dev/null +++ b/R/pipelineFill.R @@ -0,0 +1,188 @@ +#' Candidate sources for land cells ClimateNA leaves empty +#' +#' For each target (a land cell with no ClimateNA values), the nearest land cells that have +#' values, within `maxKm` (geodesic distance), nearest first. +#' +#' @param targets,sources data.frames with `id`, `lon` and `lat` (cell centres, degrees). +#' @param maxKm numeric. Farthest a source may be, in km. +#' @param maxCandidates integer. Most candidates kept per target. +#' +#' @return data.frame with `id` (the target's), `rank` (1 = nearest), `src_lon`, `src_lat` and +#' `km`; a target with no source within `maxKm` has no rows. +#' +#' @keywords internal +.fillCandidates <- function(targets, sources, maxKm, maxCandidates = 10L) { + sources <- sources[order(sources$lat), ] + dLat <- maxKm / 110 # a degree of latitude is at least 110 km + out <- lapply(seq_len(nrow(targets)), function(i) { + lon <- targets$lon[i] + lat <- targets$lat[i] + lo <- findInterval(lat - dLat, sources$lat) + 1L + hi <- findInterval(lat + dLat, sources$lat) + rows <- if (hi >= lo) lo:hi else integer(0) + dLon <- min(180, dLat / max(cos((abs(lat) + dLat) * pi / 180), 1e-6)) + rows <- rows[abs(sources$lon[rows] - lon) <= dLon] + if (length(rows) == 0) { + return(NULL) + } + km <- terra::distance( + cbind(lon, lat), + cbind(sources$lon[rows], sources$lat[rows]), + lonlat = TRUE + )[1, ] / + 1000 + keep <- utils::head(order(km)[km[order(km)] <= maxKm], maxCandidates) + if (length(keep) == 0) { + return(NULL) + } + data.frame( + id = targets$id[i], + rank = seq_along(keep), + src_lon = sources$lon[rows[keep]], + src_lat = sources$lat[rows[keep]], + km = km[keep] + ) + }) + out <- do.call(rbind, out) + if (is.null(out)) { + out <- data.frame( + id = character(0), + rank = integer(0), + src_lon = numeric(0), + src_lat = numeric(0), + km = numeric(0) + ) + } + out +} + +#' Write a ClimateNA point-mode input file +#' +#' One row per point: `id1` the tile, `id2` the cell, `lat`/`long` the source location and +#' `elev` the target cell's elevation, written as given (the DEM's text, unrounded). Lines end +#' in CRLF, as ClimateNA's own examples do. +#' +#' @param file character. The CSV to write. +#' @param df data.frame with `tile`, `cell`, `src_lat`, `src_lon` and `elev` (character). +#' +#' @return `file`, invisibly. +#' +#' @keywords internal +.writePointCsv <- function(file, df) { + lines <- c( + "id1,id2,lat,long,elev", + paste(df$tile, df$cell, as.character(df$src_lat), as.character(df$src_lon), df$elev, sep = ",") + ) + writeBin(charToRaw(paste0(lines, "\r\n", collapse = "")), file) + invisible(file) +} + +#' Read the values ClimateNA's point mode wrote +#' +#' Rows are identified by their `id1` (tile) and `id2` (cell), never by position. A row with +#' `-9999` in any of `vars` gave no values and is dropped, with a warning naming its cells. +#' +#' @param file character. The CSV ClimateNA wrote. +#' @param vars character. The variables (columns) wanted. +#' +#' @return list: `tile` and `cells` (integer, one per kept row) and `values`, a character matrix +#' (rows as `cells`, columns `vars`) holding the values as ClimateNA wrote them. +#' +#' @keywords internal +.pointValues <- function(file, vars) { + x <- utils::read.csv(file, colClasses = "character", check.names = FALSE) + missingVars <- setdiff(vars, names(x)) + if (length(missingVars) > 0) { + stop(basename(file), ": no column for ", paste(missingVars, collapse = ", ")) + } + v <- as.matrix(x[vars]) + dimnames(v) <- list(NULL, vars) + empty <- rowSums(v == "-9999" | is.na(v)) > 0 + if (any(empty)) { + warning( + basename(file), + ": no values for tile ", + paste0(x[[1]][empty], " cell ", x[[2]][empty], collapse = ", ") + ) + } + list( + tile = as.integer(x[[1]][!empty]), + cells = as.integer(x[[2]][!empty]), + values = v[!empty, , drop = FALSE] + ) +} + +#' Fill a period folder's empty land cells from ClimateNA's point-mode output +#' +#' Writes each variable's values from `fillCsv` ([.pointValues()]) into `/.asc` +#' ([.fillAsc()]), for every `.asc` file in `dir`. +#' +#' @param dir character. One period's folder (e.g. `Year_2020MSY`), extracted. +#' @param fillCsv character. That period's point-mode output for the folder's tile. +#' @param grid the tile's grid (as from [.maskCells()]). +#' +#' @return integer: how many files changed. +#' +#' @keywords internal +.fillAscDir <- function(dir, fillCsv, grid) { + files <- list.files(dir, "[.]asc$", full.names = TRUE) + vars <- sub("[.]asc$", "", basename(files)) + v <- .pointValues(fillCsv, vars) + changed <- vapply( + seq_along(files), + function(i) { + .fillAsc(files[i], list(grid = grid, cells = v$cells, values = v$values[, vars[i]])) + }, + logical(1) + ) + sum(changed) +} + +#' Land cells still empty in a period folder +#' +#' A ClimateNA output is empty in all its variables at once, so `MAT.asc` tells. +#' +#' @param dir character. One period's folder, extracted. +#' @param land integer. The tile's land cells (as from [.maskCells()]). +#' @param grid the tile's grid. +#' +#' @return integer: the land cells whose `MAT.asc` value is NODATA. +#' +#' @keywords internal +.emptyLandCells <- function(dir, land, grid) { + a <- .ascRead(file.path(dir, "MAT.asc"), grid) + land[substring(a$data, a$start[land], a$end[land] - 1L) == a$header[["nodata_value"]]] +} + +#' Choose each target's source: the nearest candidate ClimateNA gives values at +#' +#' Tries every target's nearest candidate in one `check`, then the next candidate for the +#' targets whose check gave no values, and so on until each has a source or has no candidates +#' left. +#' +#' @param candidates data.frame from [.fillCandidates()]. +#' @param check function taking rows of `candidates` (one per target) and returning the `id`s +#' whose source gave values (a ClimateNA point-mode run, in the pipeline). +#' @param ids character. All targets, including any without candidates. +#' +#' @return data.frame with `id`, `src_lon`, `src_lat` and `km`, one row per id; `NA` source and +#' `km` for a target left without one. +#' +#' @keywords internal +.chooseSources <- function(candidates, check, ids = unique(candidates$id)) { + chosen <- data.frame(id = ids, src_lon = NA_real_, src_lat = NA_real_, km = NA_real_) + pending <- ids + r <- 1L + while (length(pending) > 0) { + try <- candidates[candidates$id %in% pending & candidates$rank == r, , drop = FALSE] + if (nrow(try) == 0) { + break + } + ok <- try[try$id %in% check(try), , drop = FALSE] + i <- match(ok$id, chosen$id) + chosen[i, c("src_lon", "src_lat", "km")] <- ok[c("src_lon", "src_lat", "km")] + pending <- setdiff(try$id, ok$id) + r <- r + 1L + } + chosen +} diff --git a/R/pipelineMask.R b/R/pipelineMask.R new file mode 100644 index 0000000..eb470f6 --- /dev/null +++ b/R/pipelineMask.R @@ -0,0 +1,177 @@ +#' Cells to blank in a tile's ClimateNA output +#' +#' The DEM tiles mark cells with no elevation as NA, and ClimateNA writes values for those cells +#' anyway, computed at the wrong elevation. They are blanked when the zips are cut, except where +#' the cell centre lies inside `boundary` (Canadian coast and lakeshore cells, which are kept). +#' +#' @param dem single-layer `SpatRaster`: the DEM tile, in longitude/latitude. +#' @param boundary `SpatVector` in the same coordinates: the area whose no-DEM cells are kept +#' (Canada). Holes are filled first. +#' +#' @return list: `grid`, the tile's ASCII-grid header values (named `ncols`, `nrows`, +#' `xllcorner`, `yllcorner`, `cellsize`); `cells`, the cell numbers to blank (row by row from +#' the top left, ascending); and `land`, the cells with a DEM elevation, which the zips must +#' have values for (ascending). +#' +#' @keywords internal +.maskCells <- function(dem, boundary) { + inside <- terra::rasterize(terra::fillHoles(boundary), dem, touches = FALSE) + noDem <- is.na(terra::values(dem, mat = FALSE)) + cells <- which(noDem & is.na(terra::values(inside, mat = FALSE))) + e <- as.vector(terra::ext(dem)) + list( + land = which(!noDem), + grid = c( + ncols = terra::ncol(dem), + nrows = terra::nrow(dem), + xllcorner = e[["xmin"]], + yllcorner = e[["ymin"]], + cellsize = terra::xres(dem) + ), + cells = as.integer(cells) + ) +} + +#' Blank cells in a ClimateNA ASCII grid, in place +#' +#' Sets the cells listed in `mask` to the file's `NODATA_value`. Only those values' text +#' changes: every other byte (other values, spacing, line endings) is left as ClimateNA wrote +#' it. A file with nothing to blank is not rewritten. A rewritten file keeps its modification +#' time, so zips cut from it are byte-identical each time they are rebuilt. +#' +#' Cells are counted in the order the values appear after the header, as GDAL reads them, not +#' by line: ClimateNA wraps some files' rows across lines (e.g. 100 values, then 77) and +#' sometimes writes a run of spaces between two values. +#' +#' @param file character. A ClimateNA `.asc` file. +#' @param mask list from [.maskCells()] for the file's tile. +#' +#' @return `TRUE` if the file changed, else `FALSE`, invisibly. +#' +#' @keywords internal +.maskAsc <- function(file, mask) { + if (length(mask$cells) == 0) { + return(invisible(FALSE)) + } + a <- .ascRead(file, mask$grid) + cells <- sort(unique(mask$cells)) + invisible(.ascSplice(file, a, cells, rep(a$header[["nodata_value"]], length(cells)))) +} + +#' Write values into empty cells of a ClimateNA ASCII grid, in place +#' +#' Replaces the text of each listed cell, which must be the file's `NODATA_value`, with the given +#' value, as ClimateNA's point mode wrote it. Every other byte is left as ClimateNA wrote it, and +#' the file keeps its modification time (see [.maskAsc()]). Stops, leaving the file unchanged, +#' if a listed cell has a value (ClimateNA's own values are never overwritten) or a given value +#' is missing (`-9999` or the file's `NODATA_value`). +#' +#' @param file character. A ClimateNA `.asc` file. +#' @param fill list: `grid` (as from [.maskCells()]) for the file's tile; `cells`, the cell +#' numbers to fill; `values`, character, one per cell. +#' +#' @return `TRUE` if the file changed, else `FALSE`, invisibly. +#' +#' @keywords internal +.fillAsc <- function(file, fill) { + stopifnot(length(fill$cells) == length(fill$values), !anyDuplicated(fill$cells)) + if (length(fill$cells) == 0) { + return(invisible(FALSE)) + } + a <- .ascRead(file, fill$grid) + nodata <- a$header[["nodata_value"]] + missing <- fill$values %in% c("-9999", nodata) | is.na(fill$values) + if (any(missing)) { + stop(basename(file), ": no value for cell ", paste(fill$cells[missing], collapse = ", ")) + } + have <- substring(a$data, a$start[fill$cells], a$end[fill$cells] - 1L) + if (any(have != nodata)) { + stop( + basename(file), + ": cell ", + paste(fill$cells[have != nodata], collapse = ", "), + " has a value (not NODATA)" + ) + } + o <- order(fill$cells) + invisible(.ascSplice(file, a, fill$cells[o], fill$values[o])) +} + +## Read a ClimateNA ASCII grid for .maskAsc() / .fillAsc(): the raw bytes, the header (named by +## lower-case keyword), the data text and each value's start and end (end exclusive) in it. +## Stops if the header's grid differs from `grid` (corners within cellsize / 1000) or the value +## count is not ncols x nrows. Values are counted in order, whatever the line breaks. +.ascRead <- function(file, grid) { + bytes <- readBin(file, "raw", file.size(file)) + text <- rawToChar(bytes) + nl <- gregexpr("\n", text, fixed = TRUE)[[1]] + if (length(nl) < 6) { + stop(basename(file), ": no ASCII grid header") + } + + kv <- strsplit(trimws(strsplit(substr(text, 1, nl[6]), "\n", fixed = TRUE)[[1]]), "[ \t]+") + header <- stats::setNames(vapply(kv, `[`, "", 2), tolower(vapply(kv, `[`, "", 1))) + g <- suppressWarnings(as.numeric(header[names(grid)])) + tol <- grid[["cellsize"]] / 1000 + if ( + anyNA(g) || + !is.element("nodata_value", names(header)) || + any(g[1:2] != grid[1:2]) || + any(abs(g[3:5] - grid[3:5]) > tol) + ) { + stop( + basename(file), + ": its grid (", + paste(header, collapse = " "), + ") differs from the DEM tile's (", + paste(grid, collapse = " "), + ")" + ) + } + + data <- substr(text, nl[6] + 1L, nchar(text)) + m <- gregexpr("[^ \t\r\n]+", data)[[1]] + n <- grid[["ncols"]] * grid[["nrows"]] + if (length(m) != n) { + stop(basename(file), ": ", length(m), " values, not ", n) + } + list( + bytes = bytes, + head = substr(text, 1, nl[6]), + header = header, + data = data, + start = as.integer(m), + end = as.integer(m) + attr(m, "match.length") + ) +} + +## Put `values` in place of the given cells' text (cells ascending, unique) and write the file if +## that changes it, keeping its modification time. TRUE if the file changed. +.ascSplice <- function(file, a, cells, values) { + pieces <- substring(a$data, c(1L, a$end[cells]), c(a$start[cells] - 1L, nchar(a$data))) + data <- paste(c(rbind(pieces[-length(pieces)], values), pieces[length(pieces)]), collapse = "") + out <- charToRaw(paste0(a$head, data)) + changed <- !identical(out, a$bytes) + if (changed) { + mtime <- file.mtime(file) + writeBin(out, file) + Sys.setFileTime(file, mtime) + } + changed +} + +#' Blank cells in every ClimateNA ASCII grid below a folder, in place +#' +#' @param dir character. A folder, e.g. a batch's extracted period folders. +#' @param mask list from [.maskCells()] for the folder's tile. +#' +#' @return integer: how many files changed. +#' +#' @keywords internal +.maskAscDir <- function(dir, mask) { + if (is.null(mask)) { + stop("no mask for the tile of ", dir) + } + files <- list.files(dir, "[.]asc$", recursive = TRUE, full.names = TRUE) + sum(vapply(files, .maskAsc, logical(1), mask = mask)) +} diff --git a/R/pipelineStamps.R b/R/pipelineStamps.R new file mode 100644 index 0000000..8451a5d --- /dev/null +++ b/R/pipelineStamps.R @@ -0,0 +1,65 @@ +## Period stamps for the data pipeline (data-raw/pipeline/). +## +## Each stored ClimateNA output (`.zip`) gets a sibling `.stamp` file (DCF) +## recording the ClimateNA version, the DEM tile's hash and the Docker image digest that produced +## it. The stamp sits next to the zip, not inside it, so it never ends up in a published zip. + +.stampPath <- function(tileDir, folder) { + file.path(tileDir, paste0(folder, ".stamp")) +} + +.writeStamp <- function(tileDir, folder, climatenaVersion, demHash, image) { + path <- .stampPath(tileDir, folder) + write.dcf( + data.frame( + climatena_version = climatenaVersion, + dem_hash = demHash, + image = image, + time = as.numeric(Sys.time()) + ), + path + ) + invisible(path) +} + +.readStamp <- function(tileDir, folder) { + path <- .stampPath(tileDir, folder) + if (!file.exists(path)) { + return(NULL) + } + as.list(read.dcf(path)[1, ]) +} + +## Each finished period is stored as one zip, `.zip` (holding `/.asc`), next +## to its stamp: a single file per period keeps the raw tree small and cheap on a network share. +.periodZip <- function(tileDir, folder) { + file.path(tileDir, paste0(folder, ".zip")) +} + +## A period is done when its stored zip passes the archive check and its stamp shows a ClimateNA +## version at or above `minVersion` and the same DEM. Anything else is rerun, including a stamp +## or zip that can't be read (cut short by a crash, or damaged): an error here would fail the +## batch on every run instead. +.periodDone <- function(tileDir, folder, expected, minVersion, demHash) { + stamp <- tryCatch(.readStamp(tileDir, folder), error = function(e) NULL) + if (is.null(stamp)) { + return(FALSE) + } + version <- numeric_version(stamp$climatena_version %||% "", strict = FALSE) + if (is.na(version) || version < numeric_version(minVersion)) { + return(FALSE) + } + if (!identical(stamp$dem_hash, demHash)) { + return(FALSE) + } + zip <- .periodZip(tileDir, folder) + if (!file.exists(zip)) { + return(FALSE) + } + listing <- tryCatch(.zipListing(zip), error = function(e) NULL) + if (is.null(listing)) { + return(FALSE) + } + e <- .archiveExpectedByVersion(listing, expected)$expected + .archiveComplete(.archiveCheck(listing, e)) +} diff --git a/R/pipelineUpload.R b/R/pipelineUpload.R new file mode 100644 index 0000000..8fe4078 --- /dev/null +++ b/R/pipelineUpload.R @@ -0,0 +1,45 @@ +#' What to do with a zip on Drive +#' +#' Given the files of the same name already in the zip's release folder: reuse one with the same +#' MD5 (`"found"`); else, if `replace`, replace a differing one in place (`"update"`), so its +#' Drive ID, which the index holds as `gid`, stays the same; else upload a new file (`"upload"`). +#' When several same-named files differ, the one with ID `gid` is updated; if none has it, this +#' stops. Without `replace`, a differing same-named file stops the upload, so a shipped +#' release's files change only when the maintainer asks (`replace_changed` in `_local.R`). +#' +#' @param there data.frame with columns `id` and `md5` (`NA` when Drive gives none). +#' @param md5 character. The zip's MD5. +#' @param gid character or `NULL`. The zip's Drive ID in the index, if it has one. +#' @param replace logical. Replace a differing same-named file in place? +#' +#' @return list: `action` (`"found"`, `"update"` or `"upload"`) and `id` (`NA` for `"upload"`). +#' +#' @keywords internal +.uploadAction <- function(there, md5, gid = NULL, replace = FALSE) { + same <- which(there$md5 %in% md5) + if (length(same) > 0) { + return(list(action = "found", id = there$id[same[1]])) + } + if (nrow(there) == 0) { + return(list(action = "upload", id = NA_character_)) + } + id <- if (!is.null(gid) && any(there$id %in% gid)) { + gid + } else if (nrow(there) == 1) { + there$id + } else { + stop( + "several same-named files differ from the zip (", + paste(there$id, collapse = ", "), + ") and none is the index's; remove the stray ones" + ) + } + if (!isTRUE(replace)) { + stop( + "the release folder's file of that name (", + id, + ") differs from the zip; set replace_changed = TRUE in _local.R to replace it in place" + ) + } + list(action = "update", id = id) +} diff --git a/R/pipelineWorkers.R b/R/pipelineWorkers.R new file mode 100644 index 0000000..b0b8c17 --- /dev/null +++ b/R/pipelineWorkers.R @@ -0,0 +1,33 @@ +#' How many pipeline workers a node may run +#' +#' The data pipeline uses at most half of a node's cores. Each ClimateNA run is limited to one +#' CPU (`--cpus 1`), so its CPU use is the number of workers plus `reserved` (on the controlling +#' node: the upload workers and the main process). +#' +#' @param requested integer. Workers asked for. +#' @param cores integer. The node's cores. +#' @param reserved integer. Cores already in use by the pipeline on that node. +#' @param where character. The node, for the message. +#' +#' @return integer: `requested`, or the cap when it is lower (with a message), and at least 1. +#' +#' @keywords internal +.cappedWorkers <- function(requested, cores, reserved, where = "this node") { + cap <- max(1L, as.integer(floor(cores / 2) - reserved)) + if (requested > cap) { + message( + "Using ", + cap, + " workers on ", + where, + ", not ", + requested, + ": the pipeline uses at most half of its ", + cores, + " cores (", + reserved, + " already in use)." + ) + } + as.integer(min(requested, cap)) +} diff --git a/R/prepClimateLayers.R b/R/prepClimateLayers.R index e2884e2..2b90417 100644 --- a/R/prepClimateLayers.R +++ b/R/prepClimateLayers.R @@ -1,11 +1,11 @@ .allowedClimDotsNames <- c("historical_period", "historical_years", "future_period", "future_years") ## Internal functions that build the layers `prepClimateLayers()` caches. Their bodies are part of the -## cache key, so a change to any of them (e.g. `maskInvalidPPT()`) rebuilds the cached layers. +## cache key, so a change to any of them (e.g. `climateMosaicsParallel()`) rebuilds the cached +## layers. .climateBuilders <- c( "climateMosaicsParallel", "climateMosaicsNormalsParallel", - "maskInvalidPPT", "climateStacksByYear", "climateStacksByPeriod", "calcStackLayersType", @@ -87,6 +87,11 @@ 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. +#' #' @template climVarsList #' #' @template ClimateNA_srcdstdir @@ -199,7 +204,9 @@ prepClimateLayers <- function( (is.null(tile) && !is.null(studyArea) && !is.null(rasterToMatch)) ## pass sA/RTM but not tile ) - climatePath <- srcdir + ## 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 ## need full study area perimeter w/o subpolygons @@ -295,7 +302,6 @@ prepClimateLayers <- function( ) |> sort() } else if (type_msyn == "future_N") { - stop("future normals not yet implemented") ## TODO: get data, implement and verify type <- "future_normals" climatePath_type <- file.path(climatePath, "future", "normals") urls <- getClimateURLs(type = type, tile = tile, msy = "Y", gcm = gcm, ssp = ssp) @@ -305,13 +311,13 @@ prepClimateLayers <- function( climatePath = climatePath_type, needVars = needVars ) + ## every tile x period, with the folder name ClimateNA writes (e.g. CanESM5_ssp245_2011-2040Y) allDirs <- file.path( climatePath_type, - rep(tile, length(future_period)), - paste0(gcm, "_ssp", ssp), - paste0("Normal_", future_period, "Y") + rep(tile, each = length(future_period)), + rep(.periodFolder("future_normals", future_period, "Y", gcm, ssp), times = length(tile)) ) |> - sort() ## TODO: verify paths + sort() } else { stop("unknown climate variable type: ", type_msyn) } @@ -544,13 +550,18 @@ prepClimateLayers <- function( return(climData) } -## Which archives to download, from the needed "_" types. Seasonal variables exist -## only in the MSY ("all") archives, and an MSY archive holds every file of the M and Y archives -## (checked: 180 monthly and 25 yearly files per year, historical and future). So once MSY is needed, -## M and Y come from it too; downloading them separately is redundant, and some M archives on the -## server are incomplete (e.g. tile 46's future 2080s lacks 2085), which stopped runs. +## Which archives to download, from the needed "_" types. An MSY ("all") archive +## holds every file of the M, S and Y archives (checked: 180 monthly, 60 seasonal and 25 yearly +## files per year). Seasonal variables alone come from the S archives that v3.0.0 data releases +## publish; with monthly or yearly ones, from MSY. Once MSY is needed, M and Y come from it too -- +## downloading them separately is redundant, and some older M archives on the server are +## incomplete (e.g. tile 46's future 2080s lacks 2085), which stopped runs. .consolidateClimateTypes <- function(types) { - types <- sub("_S$", "_MSY", types) + for (tp in c("historical", "future")) { + if (paste0(tp, "_S") %in% types && any(paste0(tp, c("_M", "_Y")) %in% types)) { + types[types == paste0(tp, "_S")] <- paste0(tp, "_MSY") + } + } for (tp in c("historical", "future")) { if (paste0(tp, "_MSY") %in% types) { types <- sub(paste0("^", tp, "_(M|Y)$"), paste0(tp, "_MSY"), types) diff --git a/_pkgdown.yml b/_pkgdown.yml new file mode 100644 index 0000000..3132719 --- /dev/null +++ b/_pkgdown.yml @@ -0,0 +1,50 @@ +url: https://predictiveecology.github.io/climateData/ + +template: + bootstrap: 5 + +articles: + - title: Using climateData + navbar: ~ + contents: + - climateData + - title: Maintaining climateData + contents: + - maintaining-climate-data + +reference: + - title: Getting climate data + contents: + - prepClimateLayers + - climateLayers + - available + - climateDataRelease + - filledCells + - latestHistoricalYear + - whereAmI + - title: Derived variables + contents: + - calcAsIs + - calcStackLayersType + - checkCalcStackLayers + - whichMSYN + - extractTimes + - title: Archives and the tile index + contents: + - getClimateURLs + - getClimateTiles + - getClimateTable + - getNormalsPeriods + - ClimateNA_tiles_sqlite + - title: Mosaics and stacks + contents: + - buildClimateMosaics + - climateStacksByYear + - title: Maintainer tools + desc: For building the climate archives and the tile index. + contents: + - ClimateNA_path + - ClimateNA_sql + - makeClimateDEM + - rewrite_asc + - tileID diff --git a/data-raw/03-ClimateNA_future.R b/data-raw/03-ClimateNA_future.R index c5953f7..2ead410 100644 --- a/data-raw/03-ClimateNA_future.R +++ b/data-raw/03-ClimateNA_future.R @@ -2,6 +2,12 @@ ## 2. Download and process historical, projected, and normals data for each tile using ClimateNA; ## 3. Archive and upload each set of tiles for use with canClimateData. +stop( + "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", + "This script ends by copying its working index over the shipped release index.", + call. = FALSE +) + # setup --------------------------------------------------------------------------------------- source("data-raw/01-ClimateNA_setup.R") diff --git a/data-raw/03-ClimateNA_future_normals.R b/data-raw/03-ClimateNA_future_normals.R index 40d87b3..04c7b47 100644 --- a/data-raw/03-ClimateNA_future_normals.R +++ b/data-raw/03-ClimateNA_future_normals.R @@ -2,6 +2,12 @@ ## 2. Download and process data for each tile using ClimateNA; ## 3. Archive and upload each set of tiles for use with canClimateData. +stop( + "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", + "This script ends by copying its working index over the shipped release index.", + call. = FALSE +) + # setup --------------------------------------------------------------------------------------- source("data-raw/01-ClimateNA_setup.R") @@ -179,7 +185,12 @@ checksums_futu_normals <- future.apply::future_lapply( dplyr::bind_rows() if (!"id" %in% colnames(checksums_futu_normals)) { - dplyr::rows_append(checksums_futu_normals_df, checksums_futu_normals, copy = TRUE, in_place = TRUE) + dplyr::rows_append( + checksums_futu_normals_df, + checksums_futu_normals, + copy = TRUE, + in_place = TRUE + ) } else { dplyr::rows_update( checksums_futu_normals_df, diff --git a/data-raw/03-ClimateNA_historical.R b/data-raw/03-ClimateNA_historical.R index 47cf0fd..c642f57 100644 --- a/data-raw/03-ClimateNA_historical.R +++ b/data-raw/03-ClimateNA_historical.R @@ -2,6 +2,12 @@ ## 2. Download and process data for each tile using ClimateNA; ## 3. Archive and upload each set of tiles for use with canClimateData. +stop( + "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", + "This script ends by copying its working index over the shipped release index.", + call. = FALSE +) + # setup --------------------------------------------------------------------------------------- source("data-raw/01-ClimateNA_setup.R") @@ -277,7 +283,14 @@ if (createZips) { return(z) }, - future.globals = c("ClimateNAdata", "climateType", "historical_decades", "MSYs", "p", "wrkngDBfile"), + future.globals = c( + "ClimateNAdata", + "climateType", + "historical_decades", + "MSYs", + "p", + "wrkngDBfile" + ), future.seed = NULL ) }) @@ -323,7 +336,12 @@ if (uploadArchives) { tile <- normalizePath(f) |> climateData::tileID() z <- lapply(MSYs, function(msy) { - ClimateNAout <- climateData::ClimateNA_path(ClimateNAdata, tile = tile, type = climateType, msy) + ClimateNAout <- climateData::ClimateNA_path( + ClimateNAdata, + tile = tile, + type = climateType, + msy + ) gid <- googledrive::as_id(gids_historic[[msy]]) drivefiles <- googledrive::drive_ls(gid) @@ -362,8 +380,18 @@ if (uploadArchives) { return(z) }, - future.globals = c("ClimateNAdata", "climateType", "gids_historic", "historical_decades", - "MSYs", "oauthCachePath", "p", "reuploadArchives", "userEmail", "wrkngDBfile"), + future.globals = c( + "ClimateNAdata", + "climateType", + "gids_historic", + "historical_decades", + "MSYs", + "oauthCachePath", + "p", + "reuploadArchives", + "userEmail", + "wrkngDBfile" + ), future.seed = NULL ) }) diff --git a/data-raw/03-ClimateNA_historical_normals.R b/data-raw/03-ClimateNA_historical_normals.R index 5e02820..1291169 100644 --- a/data-raw/03-ClimateNA_historical_normals.R +++ b/data-raw/03-ClimateNA_historical_normals.R @@ -2,6 +2,12 @@ ## 2. Download and process data for each tile using ClimateNA; ## 3. Archive and upload each set of tiles for use with canClimateData. +stop( + "Superseded by the targets pipeline in data-raw/pipeline/ (vignette 'maintaining-climate-data'). ", + "This script ends by copying its working index over the shipped release index.", + call. = FALSE +) + # setup --------------------------------------------------------------------------------------- source("data-raw/01-ClimateNA_setup.R") diff --git a/data-raw/04-audit_archives.R b/data-raw/04-audit_archives.R index a1c5419..9ff4bb8 100644 --- a/data-raw/04-audit_archives.R +++ b/data-raw/04-audit_archives.R @@ -16,7 +16,25 @@ ## Nothing is changed on Google Drive, in the index, or on the share outside `auditDir`. ## Repairs are made by 05-repair_archives.R, from a reviewed zips.csv. -source("data-raw/01-ClimateNA_setup.R") +## To audit a release built by the pipeline (data-raw/pipeline/), set these before sourcing this +## script, after authenticating googledrive, from the package root: +## auditIndex <- "/ClimateNA_tiles.sqlite" # the release's index +## auditZipRoot <- "/zips" # its local zips, by the index's zipfile +## auditDriveFolders <- list(release = "") +## auditDir <- "/_audit/" +## auditTypes <- c("historical", "historical_normals", "future", "future_normals") +## The raw-output check (repair classes) applies only to the pre-pipeline share layout; for a +## release, an incomplete zip is classed "rerun_pipeline". +releaseAudit <- exists("auditIndex") +if (releaseAudit) { + stopifnot(exists("auditZipRoot"), exists("auditDriveFolders"), exists("auditDir")) + devtools::load_all(".", quiet = TRUE) +} else { + source("data-raw/01-ClimateNA_setup.R") + auditIndex <- wrkngDBfile + auditZipRoot <- ClimateNAdata + auditDir <- file.path(ClimateNAdata, "_audit", format(Sys.Date())) +} ## set these before sourcing this script to audit a subset if (!exists("auditTypes")) { @@ -26,8 +44,6 @@ if (!exists("auditTiles")) { auditTiles <- NULL ## NULL means all tiles; otherwise an integer vector of tile IDs } nCores <- 16L ## parallel workers for reading local zips and raw folders on the share - -auditDir <- file.path(ClimateNAdata, "_audit", format(Sys.Date())) downloadDir <- file.path(auditDir, "downloads") dir.create(downloadDir, recursive = TRUE, showWarnings = FALSE) checked <- as.numeric(Sys.time()) @@ -42,10 +58,13 @@ driveFolders <- list( historical_normals = c(Y = "1FStzgwcLMz4gky2UJtt9z5U8MWR1A94k"), future = c(all = "1DH_JF6ZluYsZUpHGRXpXI8Q-DOUOE9AY") ## one subfolder per GCM x SSP ) +if (!releaseAudit) { + auditDriveFolders <- driveFolders[auditTypes] +} # index --------------------------------------------------------------------------------------- -db <- DBI::dbConnect(RSQLite::SQLite(), wrkngDBfile, flags = RSQLite::SQLITE_RO) +db <- DBI::dbConnect(RSQLite::SQLite(), auditIndex, flags = RSQLite::SQLITE_RO) index <- lapply(auditTypes, function(type) { x <- DBI::dbReadTable(db, type) if (!is.null(auditTiles)) { @@ -112,7 +131,7 @@ driveMeta <- function(d) { ) } -meta <- unlist(driveFolders[auditTypes], use.names = FALSE) |> +meta <- unlist(auditDriveFolders, use.names = FALSE) |> lapply(\(f) googledrive::drive_ls(googledrive::as_id(f), recursive = TRUE)) |> dplyr::bind_rows() |> driveMeta() @@ -169,7 +188,7 @@ readListing <- function(f) { message("Reading local zips") local <- parallel::mclapply( - file.path(ClimateNAdata, zips$zipfile), + file.path(auditZipRoot, zips$zipfile), function(f) { if (!file.exists(f)) { return(list(md5 = NA_character_, listing = NULL, error = NA_character_)) @@ -252,16 +271,21 @@ folderTime <- function(folder, msy) { } incomplete <- which(zips$complete %in% FALSE) -message("Checking raw outputs for ", length(incomplete), " incomplete zips") -raw <- parallel::mclapply( - incomplete, - function(i) { - folders <- unique(dirname(expected[[i]])) - checkListing(.dirListing(tileDirOf(i), folders), expected[[i]])$problems - }, - mc.cores = nCores -) |> - stopOnWorkerErrors("Checking the raw outputs") +## a release's raw outputs are the pipeline's, in its own layout: it reruns anything missing +raw <- if (releaseAudit) { + list() +} else { + message("Checking raw outputs for ", length(incomplete), " incomplete zips") + parallel::mclapply( + incomplete, + function(i) { + folders <- unique(dirname(expected[[i]])) + checkListing(.dirListing(tileDirOf(i), folders), expected[[i]])$problems + }, + mc.cores = nCores + ) |> + stopOnWorkerErrors("Checking the raw outputs") +} ## complete zips made before ClimateNA v7.60 need regenerating for the rsds names ## zips not checked (missing on Drive, or the download failed) get no repair class zips$repair <- ifelse( @@ -269,13 +293,13 @@ zips$repair <- ifelse( NA_character_, ifelse(zips$legacy_folders %in% 0L, "none", "regenerate_v760") ) -zips$repair[incomplete] <- ifelse( - vapply(raw, .archiveComplete, logical(1)), - "repairable", - "needs_climatena" -) +zips$repair[incomplete] <- if (releaseAudit) { + rep("rerun_pipeline", length(incomplete)) +} else { + ifelse(vapply(raw, .archiveComplete, logical(1)), "repairable", "needs_climatena") +} -reruns <- lapply(seq_along(incomplete), function(k) { +reruns <- lapply(seq_along(raw), function(k) { i <- incomplete[k] p <- raw[[k]] p <- p[p$problem %in% .archiveFailing, , drop = FALSE] @@ -385,6 +409,7 @@ summaryLines <- c( paste0("- Incomplete: ", sum(zips$complete %in% FALSE)), paste0(" - repairable from raw outputs: ", sum(zips$repair %in% "repairable")), paste0(" - needing ClimateNA reruns: ", sum(zips$repair %in% "needs_climatena")), + paste0(" - needing a pipeline rerun (a release): ", sum(zips$repair %in% "rerun_pipeline")), paste0("- Raw folders to rerun in ClimateNA: ", nrow(reruns)), paste0("- Total size on Drive: ", round(sum(zips$size, na.rm = TRUE) / 1024^3, 1), " GiB"), "", diff --git a/data-raw/06-archive_fingerprints.R b/data-raw/06-archive_fingerprints.R index 2b3edc5..f7eae35 100644 --- a/data-raw/06-archive_fingerprints.R +++ b/data-raw/06-archive_fingerprints.R @@ -7,6 +7,12 @@ ## (`addlDBfile`) is left alone: it holds the per-file checksum tables (millions of rows), ## which the package copy does not. +stop( + "Superseded by the targets pipeline in data-raw/pipeline/, whose index has the archives ", + "table. This script copies the pre-pipeline working index over the shipped release index.", + call. = FALSE +) + source("data-raw/01-ClimateNA_setup.R") if (!exists("finalZips")) { diff --git a/data-raw/pipeline/R/compat.R b/data-raw/pipeline/R/compat.R new file mode 100644 index 0000000..cd956ed --- /dev/null +++ b/data-raw/pipeline/R/compat.R @@ -0,0 +1,112 @@ +## Does a new ClimateNA release reproduce the stored outputs of one archive type? + +## ClimateNA's period argument and variable set for an existing period folder. +pipeline_folder_arg <- function(type, folder) { + msy <- regmatches(folder, regexpr("(MSY|M|S|Y)$", folder)) + stem <- sub("(MSY|M|S|Y)$", "", folder) + ext <- switch(type, historical = ".ann", historical_normals = ".nrm", ".gcm") + list(arg = paste0(stem, ext), msy = msy) +} + +## Rerun a sample of the stored periods this release would keep (made by an older ClimateNA +## version, but not older than min_version) and compare them with the stored outputs: tiles 6, +## 39 and 77 when present, otherwise the first and last tile; each tile's earliest and latest +## period. "compatible" when there is no such output, so raising min_version (which regenerates +## the older periods) lets the pipeline go on. Stops on "changed": raising min_version for this +## type in release.yml is the maintainer's decision. +compat_check <- function( + type, + climatenaExe, + climatenaVersion, + minVersion, + image, + climatenaDir, + demDir, + outRoot, + uid, + gid, + timeout = 3600 +) { + pipeline_load() + stamps <- list.files( + file.path(outRoot, "raw", type), + pattern = "[.]stamp$", + recursive = TRUE, + full.names = TRUE + ) + versions <- numeric_version(vapply( + stamps, + \(s) read.dcf(s)[1, "climatena_version"], + character(1) + )) + older <- stamps[ + versions < numeric_version(climatenaVersion) & versions >= numeric_version(minVersion) + ] + if (length(older) == 0) { + return("compatible") + } + + tile <- basename(dirname(older)) + pick <- intersect(c("6", "39", "77"), tile) + if (length(pick) == 0) { + pick <- unique(c(tile[1], tile[length(tile)])) + } + sample <- unlist(lapply(pick, function(t) { + s <- sort(older[tile == t]) + unique(c(s[1], s[length(s)])) + })) + + ## reruns go to the node-local work directory (see pipeline_work_dir()); the log to outRoot + scratchRoot <- file.path(pipeline_work_dir(), "compat", climatenaVersion, type) + logDir <- file.path(outRoot, "logs") + dir.create(logDir, recursive = TRUE, showWarnings = FALSE) + comparisons <- lapply(sample, function(stamp) { + tileDir <- dirname(stamp) + folder <- sub("[.]stamp$", "", basename(stamp)) + a <- pipeline_folder_arg(type, folder) + scratch <- file.path(scratchRoot, basename(tileDir)) + dir.create(scratch, recursive = TRUE, showWarnings = FALSE) + name <- paste0( + "cna-compat-", + gsub("[^A-Za-z0-9_.-]", "-", paste(type, basename(tileDir), folder)) + ) + args <- .climatenaDockerArgs( + name = name, + image = image, + climatenaDir = climatenaDir, + demFile = pipeline_dem_file(demDir, basename(tileDir)), + outDir = scratch, + exe = climatenaExe, + msy = a$msy, + periodArg = a$arg, + uid = uid, + gid = gid + ) + runLog <- file.path(scratch, paste0(folder, ".log")) + ok <- pipeline_run_climatena(args, name, runLog, timeout) + pipeline_append_log(file.path(logDir, paste0("compat_", type, ".log")), runLog) + if (!ok) { + stop("ClimateNA ", climatenaVersion, " failed for the compatibility sample ", folder) + } + stored <- file.path(scratch, "stored") + utils::unzip(.periodZip(tileDir, folder), exdir = stored) + cmp <- .compareFolders(file.path(scratch, folder), file.path(stored, folder)) + unlink(c(file.path(scratch, folder), stored), recursive = TRUE) + cmp + }) + verdict <- .compatVerdict(do.call(rbind, comparisons)) + if (verdict == "changed") { + stop( + "ClimateNA ", + climatenaVersion, + " changes ", + type, + " outputs; set min_version: ", + type, + ': "', + climatenaVersion, + '" in release.yml to regenerate' + ) + } + verdict +} diff --git a/data-raw/pipeline/R/fill.R b/data-raw/pipeline/R/fill.R new file mode 100644 index 0000000..b303278 --- /dev/null +++ b/data-raw/pipeline/R/fill.R @@ -0,0 +1,232 @@ +## Filling the land cells ClimateNA leaves empty (cells with a DEM elevation but no values). +## +## ClimateNA's data don't cover some land cells: its future (GCM) data miss some coastal cells, +## and a few cells have no values at all. Such a cell gets ClimateNA's own point-mode output at +## the nearest land cell it covers, run with the empty cell's elevation. Two classes, each with +## one reference period: historical (historical years and normals) and future (future years and +## normals). Point-mode outputs are stored beside the raw period zips, as +## .fill-.csv, and written into the zips when they are cut (zip_batch()). + +## Which fill class an archive type belongs to. +pipeline_fill_class <- function(type) { + if (type %in% c("historical", "historical_normals")) "historical" else "future" +} + +## Each class's reference period, whose raw outputs tell which land cells are empty: the last +## historical year, and the first GCM's and SSP's first future year. A class whose release has +## no yearly archives uses its normals (the last historical period; the first future one), and +## a class with neither has no reference. +pipeline_fill_reference <- function(cfg) { + types <- unlist(cfg[["types"]]) + scen <- list(gcm = as.character(cfg[["gcms"]][[1]]), ssp = as.character(cfg[["ssps"]][[1]])) + ref <- list( + historical = if ("historical" %in% types) { + list( + type = "historical", + period = as.integer(cfg[["historical_years"]][[2]]), + msy = "MSY", + gcm = NA_character_, + ssp = NA_character_ + ) + } else if ("historical_normals" %in% types) { + list( + type = "historical_normals", + period = as.character(utils::tail(unlist(cfg[["historical_periods"]]), 1)), + msy = "Y", + gcm = NA_character_, + ssp = NA_character_ + ) + }, + future = if ("future" %in% types) { + c(list(type = "future", period = as.integer(cfg[["future_years"]][[1]]), msy = "MSY"), scen) + } else if ("future_normals" %in% types) { + c( + list( + type = "future_normals", + period = as.character(cfg[["future_periods"]][[1]]), + msy = "Y" + ), + scen + ) + } + ) + ref[!vapply(ref, is.null, logical(1))] +} + +## A ClimateNA point-mode runner for this release: function(points, msy, periodArg) that writes +## `points` (.writePointCsv()) into a fresh folder in the node-local work directory, runs +## ClimateNA there in the image, and returns the path of the CSV it wrote. The caller removes +## that folder. +pipeline_point_runner <- function(image, climatenaExe, climatenaDir, uid, gid, timeout) { + force(image) + force(climatenaExe) + force(climatenaDir) + force(uid) + force(gid) + force(timeout) + function(points, msy, periodArg) { + work <- tempfile("fill-", tmpdir = pipeline_work_dir()) + dir.create(work, recursive = TRUE) + .writePointCsv(file.path(work, "in.csv"), points) + name <- paste0("cna-", basename(work)) + args <- .climatenaPointDockerArgs( + name = name, + image = image, + climatenaDir = climatenaDir, + workDir = work, + exe = climatenaExe, + msy = msy, + periodArg = periodArg, + inCsv = "in.csv", + outCsv = "out.csv", + uid = uid, + gid = gid + ) + out <- file.path(work, "out.csv") + ok <- pipeline_run_climatena(args, name, file.path(work, "run.log"), timeout) + if (!ok || !file.exists(out)) { + stop( + "ClimateNA point mode failed for ", + periodArg, + " (log: ", + file.path(work, "run.log"), + ")" + ) + } + out + } +} + +## The land cells to fill and their sources, for every tile and class: data.frame with class, +## tile, cell, lon, lat (the cell's centre), elev (the DEM's text), src_lon, src_lat and km (NA +## when no source was found within `maxKm`). Targets are land cells with no value in the class's +## reference period; candidate sources are land cells with values in it, in any tile, and each +## target gets the nearest candidate whose point run (`run`) gives values. A tile whose +## reference output is missing (its batch failed) is skipped with a warning. `manifests` is a +## dependency only: the reference outputs are read from `outRoot`. +pipeline_fill_points <- function(manifests, tileMasks, demFiles, reference, outRoot, maxKm, run) { + pipeline_load() + demFiles <- pipeline_dem_by_tile(demFiles) + cols <- c("class", "tile", "cell", "lon", "lat", "elev", "src_lon", "src_lat", "km") + out <- lapply(names(reference), function(cls) { + ref <- reference[[cls]] + folder <- .periodFolder(ref$type, ref$period, ref$msy, ref$gcm, ref$ssp) + cells <- lapply(names(tileMasks), function(t) { + spec <- list(type = ref$type, gcm = ref$gcm, ssp = ref$ssp, tile = t) + zip <- .periodZip(pipeline_tile_dir(outRoot, spec), folder) + if (!file.exists(zip)) { + warning("no ", folder, " output for tile ", t, ": its empty land cells are not filled") + return(NULL) + } + m <- tileMasks[[t]] + if (length(m$land) == 0) { + return(NULL) + } + td <- tempfile("ref-") + on.exit(unlink(td, recursive = TRUE), add = TRUE) + utils::unzip(zip, files = file.path(folder, "MAT.asc"), exdir = td) + a <- .ascRead(file.path(td, folder, "MAT.asc"), m$grid) + d <- .ascRead(demFiles[[t]], m$grid) + xy <- terra::xyFromCell(terra::rast(demFiles[[t]]), m$land) + data.frame( + tile = as.integer(t), + cell = m$land, + lon = xy[, 1], + lat = xy[, 2], + elev = substring(d$data, d$start[m$land], d$end[m$land] - 1L), + empty = substring(a$data, a$start[m$land], a$end[m$land] - 1L) == a$header[["nodata_value"]] + ) + }) + cells <- do.call(rbind, cells) + if (is.null(cells) || !any(cells$empty)) { + return(NULL) + } + cells$id <- paste(cells$tile, cells$cell, sep = "_") + targets <- cells[cells$empty, ] + candidates <- .fillCandidates(targets, cells[!cells$empty, ], maxKm) + check <- function(df) { + t <- targets[match(df$id, targets$id), ] + pts <- data.frame( + tile = t$tile, + cell = t$cell, + src_lat = df$src_lat, + src_lon = df$src_lon, + elev = t$elev + ) + f <- run(pts, ref$msy, .periodArg(ref$type, ref$period, ref$gcm, ref$ssp)) + on.exit(unlink(dirname(f), recursive = TRUE)) + v <- suppressWarnings(.pointValues(f, "MAT")) + paste(v$tile, v$cells, sep = "_") + } + s <- .chooseSources(candidates, check, ids = targets$id) + s <- s[match(targets$id, s$id), ] + data.frame( + class = cls, + targets[c("tile", "cell", "lon", "lat", "elev")], + s[c("src_lon", "src_lat", "km")] + ) + }) + out <- do.call(rbind, out) + if (is.null(out)) { + out <- data.frame( + class = character(0), + tile = integer(0), + cell = integer(0), + lon = numeric(0), + lat = numeric(0), + elev = character(0), + src_lon = numeric(0), + src_lat = numeric(0), + km = numeric(0) + ) + } + rownames(out) <- NULL + out[cols] +} + +## One batch's point-mode outputs: for each period, /.fill-.csv, with the +## tile's points of the batch's class that have a source. The hash covers those points and the +## period's stamp, so a CSV is redone when either changes, and older CSVs of the period are +## removed. Returns the CSV paths; character(0) for a failed batch (no manifest) or a tile with +## nothing to fill. +fill_batch <- function(spec, manifest, fillPoints, outRoot, run) { + if (length(manifest) == 0) { + return(character(0)) + } + pipeline_load() + tileDir <- pipeline_tile_dir(outRoot, spec) + folders <- .periodFolder(spec$type, spec$periods, spec$msy, spec$gcm, spec$ssp) + pts <- fillPoints[ + fillPoints$class == pipeline_fill_class(spec$type) & + fillPoints$tile == as.integer(spec$tile) & + !is.na(fillPoints$src_lon), + c("tile", "cell", "elev", "src_lon", "src_lat") + ] + rownames(pts) <- NULL + old <- function(folder) { + f <- list.files(tileDir, full.names = TRUE) + f[startsWith(basename(f), paste0(folder, ".fill-")) & endsWith(f, ".csv")] + } + if (nrow(pts) == 0) { + unlink(unlist(lapply(folders, old))) + return(character(0)) + } + out <- character(length(folders)) + for (i in seq_along(folders)) { + stamp <- .readStamp(tileDir, folders[i]) + hash <- substr(digest::digest(list(pts, stamp), algo = "xxhash64"), 1, 8) + f <- file.path(tileDir, paste0(folders[i], ".fill-", hash, ".csv")) + if (!file.exists(f)) { + res <- run(pts, spec$msy, .periodArg(spec$type, spec$periods[i], spec$gcm, spec$ssp)) + part <- paste0(f, ".part") + ok <- file.copy(res, part, overwrite = TRUE) && file.rename(part, f) + unlink(dirname(res), recursive = TRUE) + if (!ok) { + stop("could not store ", basename(f), " in ", tileDir) + } + } + unlink(setdiff(old(folders[i]), f)) + out[i] <- f + } + out +} diff --git a/data-raw/pipeline/R/index.R b/data-raw/pipeline/R/index.R new file mode 100644 index 0000000..08ea988 --- /dev/null +++ b/data-raw/pipeline/R/index.R @@ -0,0 +1,134 @@ +## The release's tile index and the run report. + +## Index rows for one batch: one per (subset zip, year or period), for every subset zip that was +## uploaded. NULL when the batch has no manifest (it failed). +pipeline_index_rows <- function(spec, uploads, manifestById, outRoot) { + manifest <- manifestById[[spec$id]] + if (is.null(manifest)) { + return(NULL) + } + m <- utils::read.delim(manifest, colClasses = "character") + folders <- .periodFolder(spec$type, spec$periods, spec$msy, spec$gcm, spec$ssp) + created <- as.numeric(m$time[match(folders, m$folder)]) + version <- m$climatena_version[match(folders, m$folder)] + normals <- spec$type %in% c("historical_normals", "future_normals") + + rows <- lapply(pipeline_subsets(spec$type), function(subset) { + rel <- pipeline_zip_relpath(spec, subset) + up <- uploads[uploads$zipfile == rel, , drop = FALSE] + if (nrow(up) == 0) { + return(NULL) + } + df <- data.frame( + gcm = spec$gcm, + ssp = spec$ssp, + msy = subset, + period = as.character(spec$periods), + year = suppressWarnings(as.integer(spec$periods)), + tileid = as.integer(spec$tile), + created = unname(created), + zipfile = rel, + archived = as.numeric(file.mtime(pipeline_zip_path(outRoot, spec, subset))), + gid = up$gid[1], + uploaded = up$uploaded[1], + climatena_version = version + ) + drop <- c(if (is.na(spec$gcm)) c("gcm", "ssp"), if (normals) "year" else "period") + df[setdiff(names(df), drop)] + }) + do.call(rbind, rows) +} + +## Build /ClimateNA_tiles.sqlite for the release, from scratch: the four tile tables (via +## ClimateNA_sql(), with each row's ClimateNA version), the archives fingerprints, the release +## table and the filled land cells (`fillPoints`, from pipeline_fill_points()). Written to a +## temporary name and renamed, and left in rollback-journal mode with no -wal/-shm files. +## `uploads`, `specs` and `manifests` are all types' targets combined. +build_index <- function( + uploads, + specs, + manifests, + outRoot, + releaseId, + climatenaVersion, + demResolution, + fillPoints +) { + manifestById <- as.list(manifests) + names(manifestById) <- sub("[.]tsv$", "", basename(manifests)) + path <- file.path(outRoot, "ClimateNA_tiles.sqlite") + tmp <- tempfile("index-", tmpdir = outRoot, fileext = ".sqlite") + on.exit(unlink(paste0(tmp, c("", "-wal", "-shm"))), add = TRUE) + + types <- vapply(specs, `[[`, character(1), "type") + for (type in .batchTypes) { + rows <- lapply(specs[types == type], pipeline_index_rows, uploads, manifestById, outRoot) + rows <- do.call(rbind, rows) + con <- ClimateNA_sql(tmp, type) # creates the table even when the release has no such rows + if (!is.null(rows) && nrow(rows) > 0) { + DBI::dbAppendTable(con$db, type, rows) + } + DBI::dbDisconnect(con$db) + } + + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + .releaseCreate(db) + .releaseWrite( + db, + data.frame( + release_id = releaseId, + climatena_version = climatenaVersion, + dem_resolution = demResolution, + created = as.numeric(Sys.time()) + ) + ) + .archivesCreate(db) + if (nrow(uploads) > 0) { + zips <- file.path(outRoot, "zips", uploads$zipfile) + .archivesUpsert( + db, + data.frame( + gid = uploads$gid, + type = sub("/.*", "", uploads$zipfile), + zipfile = uploads$zipfile, + md5 = uploads$md5, + n_files = vapply(zips, \(z) nrow(.zipListing(z)), integer(1)), + size = as.numeric(file.size(zips)), + verified = uploads$uploaded # MD5 checked against Drive at upload + ) + ) + } + .filledCellsCreate(db) + .filledCellsWrite(db, fillPoints) + DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)") + DBI::dbExecute(db, "PRAGMA journal_mode = DELETE") + DBI::dbDisconnect(db) + + stopifnot(!file.exists(paste0(tmp, c("-wal", "-shm")))) + file.rename(tmp, path) + path +} + +## Write /report.csv: every error and warning targets has recorded, and every subset zip +## that is missing from the uploads (its batch, zip or upload failed). Empty when all is well. +build_report <- function(index, specs, uploads, outRoot) { + meta <- targets::tar_meta(fields = c("error", "warnings"), store = targets::tar_path_store()) + problems <- rbind( + data.frame(target = meta$name, kind = "error", message = meta$error)[!is.na(meta$error), ], + data.frame(target = meta$name, kind = "warning", message = meta$warnings)[ + !is.na(meta$warnings), + ] + ) + missing <- lapply(specs, function(spec) { + rel <- vapply(pipeline_subsets(spec$type), \(s) pipeline_zip_relpath(spec, s), character(1)) + rel <- setdiff(rel, uploads$zipfile) + if (length(rel) == 0) { + return(NULL) + } + data.frame(target = spec$id, kind = "incomplete", message = paste("not uploaded:", rel)) + }) + problems <- do.call(rbind, c(list(problems), missing)) + out <- file.path(outRoot, "report.csv") + utils::write.csv(problems, out, row.names = FALSE) + out +} diff --git a/data-raw/pipeline/R/run_batch.R b/data-raw/pipeline/R/run_batch.R new file mode 100644 index 0000000..b5e28b5 --- /dev/null +++ b/data-raw/pipeline/R/run_batch.R @@ -0,0 +1,166 @@ +## Running ClimateNA for one batch, in the climatena-wine Docker image. + +## Raw outputs: /raw/[/_ssp]//.zip, with a sibling +## .stamp, for each finished period. +pipeline_tile_dir <- function(outRoot, spec) { + scen <- if (is.na(spec$gcm)) character(0) else paste0(spec$gcm, "_ssp", spec$ssp) + do.call(file.path, as.list(c(outRoot, "raw", spec$type, scen, spec$tile))) +} + +pipeline_dem_file <- function(demDir, tile) { + file.path(demDir, paste0("can_dem_", tile, ".asc")) +} + +## The image's registry digest when it has one (pulled from ghcr.io), otherwise its local ID. +pipeline_image_digest <- function(image) { + d <- suppressWarnings(system2( + "docker", + c("image", "inspect", "--format", "{{index .RepoDigests 0}}", image), + stdout = TRUE, + stderr = FALSE + )) + if (length(d) == 0 || !nzchar(d[1]) || !is.null(attr(d, "status"))) { + d <- system2("docker", c("image", "inspect", "--format", "{{.Id}}", image), stdout = TRUE) + } + d[1] +} + +## A node-local directory for ClimateNA to write into. Writing straight to an NFS share is very +## slow: ClimateNA checks its open files as it writes, which forces every write out to the +## server, and 90 such runs at once stall in I/O wait. CLIMATENA_WORK_DIR when set (local crew +## workers inherit it from the main process), otherwise the worker's tempdir(). +pipeline_work_dir <- function() { + d <- Sys.getenv("CLIMATENA_WORK_DIR") + if (nzchar(d)) d else tempdir() +} + +## Store a checked output folder from the work directory as one zip in the tile's raw folder +## (`.periodZip()`): zipped locally (byte-identical for identical files), copied, and checked by +## MD5. One file per period instead of a few hundred keeps the share fast and the raw tree small. +pipeline_store_period <- function(workDir, tileDir, folder) { + local <- file.path(workDir, paste0(folder, ".zip")) + unlink(local) + pipeline_write_zip(local, workDir, file.path(folder, list.files(file.path(workDir, folder)))) + dir.create(tileDir, recursive = TRUE, showWarnings = FALSE) + dest <- .periodZip(tileDir, folder) + ok <- file.copy(local, dest, overwrite = TRUE, copy.date = TRUE) + ok <- isTRUE(ok) && identical(unname(tools::md5sum(local)), unname(tools::md5sum(dest))) + unlink(local) + ok +} + +## Append a run's log to a batch log, and remove it. +pipeline_append_log <- function(log, runLog) { + if (file.exists(runLog)) { + file.append(log, runLog) + unlink(runLog) + } +} + +## Run ClimateNA once in a container; TRUE on a clean exit. A timed-out run's container (which +## this function started and named) is removed, so it can't keep running in the background. +pipeline_run_climatena <- function(args, name, log, timeout) { + rc <- suppressWarnings(system2("docker", args, stdout = log, stderr = log, timeout = timeout)) + if (identical(as.integer(rc), 124L)) { + system2("docker", c("rm", "-f", name), stdout = FALSE, stderr = FALSE) + cat("timed out after", timeout, "s:", name, "\n", file = log, append = TRUE) + } + identical(as.integer(rc), 0L) +} + +## Run every period of a batch that isn't already done, check each output, stamp it, and write +## the batch's manifest. Each run writes to the node-local work directory; its output is checked +## there, stored as one zip in the tile's raw folder, and stamped once the copy is checked. Stops +## (so the target errors and is retried next time) naming any periods that failed. The target +## runs on every tar_make() (cue "always"), so a damaged or deleted period zip is found and rerun; +## finished periods cost only reading the zip's listing. +run_batch <- function( + spec, + climatenaExe, + climatenaVersion, + image, + climatenaDir, + demDir, + outRoot, + minVersion, + uid, + gid, + timeout = 3600 +) { + pipeline_load() + tileDir <- pipeline_tile_dir(outRoot, spec) + dir.create(tileDir, recursive = TRUE, showWarnings = FALSE) + logDir <- file.path(outRoot, "logs") + dir.create(logDir, showWarnings = FALSE) + log <- file.path(logDir, paste0(spec$id, ".log")) + demFile <- pipeline_dem_file(demDir, spec$tile) + demHash <- digest::digest(demFile, file = TRUE, algo = "xxhash64") + normals <- spec$type %in% c("historical_normals", "future_normals") + vars <- if (normals) .allowedClimateVars_nrm else .allowedClimateVars_MSY + + imageDigest <- NULL + failed <- character(0) + workDir <- file.path(pipeline_work_dir(), spec$id) + for (p in spec$periods) { + folder <- .periodFolder(spec$type, p, spec$msy, spec$gcm, spec$ssp) + expected <- file.path(folder, paste0(vars, ".asc")) + if (.periodDone(tileDir, folder, expected, minVersion, demHash)) { + next + } + if (is.null(imageDigest)) { + imageDigest <- pipeline_image_digest(image) + Sys.sleep(stats::runif(1, 0, 30)) # stagger container starts across batches + } + unlink(.stampPath(tileDir, folder)) # no stamp until a checked copy is in place + unlink(.periodZip(tileDir, folder)) + unlink(file.path(tileDir, folder), recursive = TRUE) # a folder from the earlier layout + unlink(file.path(workDir, folder), recursive = TRUE) + dir.create(workDir, recursive = TRUE, showWarnings = FALSE) + runLog <- file.path(workDir, paste0(folder, ".log")) + name <- paste0("cna-", gsub("[^A-Za-z0-9_.-]", "-", paste(spec$id, p, sep = "-"))) + args <- .climatenaDockerArgs( + name = name, + image = image, + climatenaDir = climatenaDir, + demFile = demFile, + outDir = workDir, + exe = climatenaExe, + msy = spec$msy, + periodArg = .periodArg(spec$type, p, spec$gcm, spec$ssp), + uid = uid, + gid = gid + ) + ok <- pipeline_run_climatena(args, name, runLog, timeout) && + .archiveComplete(.archiveCheck(.dirListing(workDir, folder), expected)) && + pipeline_store_period(workDir, tileDir, folder) + pipeline_append_log(log, runLog) + unlink(file.path(workDir, folder), recursive = TRUE) + if (ok) { + .writeStamp(tileDir, folder, climatenaVersion, demHash, imageDigest) + } else { + failed <- c(failed, folder) + } + } + if (length(failed) > 0) { + stop( + "ClimateNA failed or wrote incomplete output for ", + spec$id, + ": ", + paste(failed, collapse = ", ") + ) + } + + ## the stamp fields make any regenerated period change the manifest, so its zips are recut + folders <- .periodFolder(spec$type, spec$periods, spec$msy, spec$gcm, spec$ssp) + stamps <- lapply(folders, \(f) .readStamp(tileDir, f)) + manifest <- data.frame( + folder = folders, + n_files = vapply(folders, \(f) nrow(.zipListing(.periodZip(tileDir, f))), integer(1)), + climatena_version = vapply(stamps, `[[`, character(1), "climatena_version"), + dem_hash = vapply(stamps, `[[`, character(1), "dem_hash"), + time = vapply(stamps, `[[`, character(1), "time") + ) + out <- file.path(outRoot, "raw", paste0(spec$id, ".tsv")) + utils::write.table(manifest, out, sep = "\t", quote = FALSE, row.names = FALSE) + out +} diff --git a/data-raw/pipeline/R/specs.R b/data-raw/pipeline/R/specs.R new file mode 100644 index 0000000..3e81e1a --- /dev/null +++ b/data-raw/pipeline/R/specs.R @@ -0,0 +1,88 @@ +## Release settings -> batch specs, and loading the package checkout in worker processes. + +## Workers are separate R processes and climateData may not be installed: load the checkout +## once per process, so the package's internal pipeline functions are available. Workers start +## in the package root (local workers inherit the main process's directory; crew.ssh workers cd +## to `projdir`), so the checkout's path is never a target dependency: moving the checkout +## rebuilds nothing. +pipeline_load <- function() { + if (!"climateData" %in% loadedNamespaces()) { + devtools::load_all(".", quiet = TRUE) + } + invisible(TRUE) +} + +## Tiles with a DEM tile, optionally limited to a subset (for testing); stops if there are none, +## or if a subset tile has no DEM. +pipeline_tiles <- function(demDir, subset = NULL) { + .demTiles(demDir, subset) +} + +## Canada, whose cells keep ClimateNA's values where the DEM has none: GADM 4.1, level 0, at its +## highest resolution, as data-raw/02-ClimateNA_tiles.R uses for the tiles. Downloaded once into +## /boundary/; returns the file. +pipeline_canada <- function(outRoot) { + dir <- file.path(outRoot, "boundary") + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + geodata::gadm("CAN", level = 0, path = dir, version = "4.1", resolution = 1) + f <- file.path(dir, "gadm", "gadm41_CAN_0_pk.rds") + if (!file.exists(f)) { + stop("geodata::gadm() did not write ", f) + } + f +} + +## Each tile's DEM file, named by tile; stops naming tiles without one. As a `format = "file"` +## target, it makes the targets built from the DEMs depend on the files' contents. +pipeline_dem_files <- function(demDir, tiles) { + f <- stats::setNames(pipeline_dem_file(demDir, tiles), as.character(tiles)) + missing <- names(f)[!file.exists(f)] + if (length(missing) > 0) { + stop("no DEM tile in ", demDir, " for tile(s) ", paste(missing, collapse = ", ")) + } + f +} + +## DEM file paths named by tile, from their file names (can_dem_.asc): the dem_files +## target returns its paths without names, as every format = "file" target does. +pipeline_dem_by_tile <- function(demFiles) { + stats::setNames(demFiles, sub("^can_dem_([0-9]+)[.]asc$", "\\1", basename(demFiles))) +} + +## Each tile's cells to set to NODATA when its zips are cut, and its land cells (.maskCells()), +## named by tile. +pipeline_tile_masks <- function(canadaFile, demFiles) { + canada <- readRDS(canadaFile) + if (inherits(canada, "PackedSpatVector")) { + canada <- terra::unwrap(canada) + } + lapply(pipeline_dem_by_tile(demFiles), function(f) .maskCells(terra::rast(f), canada)) +} + +## The batch specs for one archive type, from the release settings. +pipeline_specs <- function(type, tiles, cfg) { + span <- function(x) seq(as.integer(x[[1]]), as.integer(x[[2]])) + switch( + type, + historical = .batchSpecs("historical", tiles, years = span(cfg$historical_years)), + future = .batchSpecs( + "future", + tiles, + gcms = unlist(cfg$gcms), + ssps = unlist(cfg$ssps), + years = span(cfg$future_years) + ), + historical_normals = .batchSpecs( + "historical_normals", + tiles, + periods = unlist(cfg$historical_periods) + ), + future_normals = .batchSpecs( + "future_normals", + tiles, + gcms = unlist(cfg$gcms), + ssps = unlist(cfg$ssps), + periods = unlist(cfg$future_periods) + ) + ) +} diff --git a/data-raw/pipeline/R/upload_drive.R b/data-raw/pipeline/R/upload_drive.R new file mode 100644 index 0000000..3721ad2 --- /dev/null +++ b/data-raw/pipeline/R/upload_drive.R @@ -0,0 +1,255 @@ +## Publishing a batch's zips to Google Drive, as files in the release's folder +## //[/_ssp]//, or as an earlier release's file +## when the zip is identical. This is the only Drive-specific code: another store (e.g. S3) would +## be an upload_.R with the same signature and result. +## +## Uploads run on the main node (where the maintainer's OAuth token is cached), in parallel on the +## "uploads" crew controller; `drive_email` in _local.R tells googledrive which token to use. The +## release's folders are created first, on the main process, so parallel uploads never race to +## create the same folder. + +## Drive folder ids looked up or created in this session, keyed by path below the parent. +pipeline_drive_folders <- new.env(parent = emptyenv()) + +## The id of the folder ///..., creating any that are missing. +pipeline_drive_folder <- function(parentId, segments) { + id <- parentId + for (i in seq_along(segments)) { + key <- paste(c(parentId, segments[seq_len(i)]), collapse = "/") + if (is.null(pipeline_drive_folders[[key]])) { + found <- googledrive::drive_ls(googledrive::as_id(id), type = "folder") + found <- found[found$name == segments[i], ] + if (nrow(found) > 1) { + stop("several Drive folders named ", key) + } + pipeline_drive_folders[[key]] <- if (nrow(found) == 1) { + as.character(found$id) + } else { + googledrive::with_drive_quiet(googledrive::drive_mkdir( + segments[i], + path = googledrive::as_id(id) + ))$id |> + as.character() + } + } + id <- pipeline_drive_folders[[key]] + } + id +} + +## Create the release's Drive folder for every zip directory it can produce (e.g. +## "historical/MSY"), and write their ids (NA in a dry run), named by the directory below the +## release folder, to /drive_folders.rds. Returns only the map's path, the release and +## the dry-run flag, so adding folders (a new GCM or SSP) changes nothing the existing upload +## branches depend on. +pipeline_release_folders <- function(specs, releaseId, driveParent, dryRun, outRoot) { + dirs <- unique(dirname(unlist(lapply(specs, pipeline_zip_relpaths)))) + ids <- if (isTRUE(dryRun)) { + rep(NA_character_, length(dirs)) + } else { + vapply( + dirs, + \(d) pipeline_drive_folder(driveParent, c(releaseId, strsplit(d, "/")[[1]])), + character(1) + ) + } + path <- file.path(outRoot, "drive_folders.rds") + saveRDS(stats::setNames(ids, dirs), path) + list(path = path, release_id = releaseId, dry_run = dryRun) +} + +## Every zip path below the release folder that a batch can produce. +pipeline_zip_relpaths <- function(spec) { + vapply(pipeline_subsets(spec$type), \(s) pipeline_zip_relpath(spec, s), character(1)) +} + +## The previous release's archives rows that this release could reuse, written once to a small +## lookup database (indexed, rollback-journal mode, so upload workers can open it read-only and +## query only their own zips). Returns only the path, so its value never changes: the rows change +## whenever a scenario is added (they are cut to specs_all), and a value that followed them would +## rerun every upload branch. An upload that already ran needs no new lookup. +pipeline_previous_lookup <- function(index, specs, outRoot) { + prev <- pipeline_previous_archives(index) + prev <- prev[prev$zipfile %in% unlist(lapply(specs, pipeline_zip_relpaths)), , drop = FALSE] + prev <- prev[order(prev$zipfile), , drop = FALSE] + path <- file.path(outRoot, "previous_archives.sqlite") + tmp <- paste0(path, ".tmp") + unlink(tmp) + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + DBI::dbExecute(db, "CREATE TABLE prev (zipfile TEXT, gid TEXT, md5 TEXT)") + DBI::dbAppendTable(db, "prev", prev[c("zipfile", "gid", "md5")]) + DBI::dbExecute(db, "CREATE INDEX prev_zipfile ON prev (zipfile)") + DBI::dbDisconnect(db) + file.rename(tmp, path) + list(path = path) +} + +## The previous release's rows for one batch's zips, from pipeline_previous_lookup(). +pipeline_previous_rows <- function(lookup, spec) { + db <- DBI::dbConnect(RSQLite::SQLite(), lookup$path, flags = RSQLite::SQLITE_RO) + on.exit(DBI::dbDisconnect(db)) + DBI::dbGetQuery( + db, + "SELECT gid, zipfile, md5 FROM prev WHERE zipfile = ?", + params = list(unname(pipeline_zip_relpaths(spec))) + ) +} + +## Drive's createdTime (or, for a file replaced in place, modifiedTime; RFC 3339, UTC) as epoch +## seconds. +pipeline_drive_time <- function(resource, field = "createdTime") { + as.numeric(as.POSIXct(resource[[field]], format = "%Y-%m-%dT%H:%M:%OS", tz = "UTC")) +} + +## The `archives` rows (gid, zipfile, md5) of an earlier release's index, for reusing its Drive +## files; none when the file is missing or has no archives table. Read from a copy: the shipped +## index is in WAL mode, which a read-only connection can't open in place. +pipeline_previous_archives <- function(index) { + none <- data.frame(gid = character(0), zipfile = character(0), md5 = character(0)) + if (length(index) == 0 || !file.exists(index)) { + return(none) + } + tmp <- tempfile(fileext = ".sqlite") + on.exit(unlink(paste0(tmp, c("", "-wal", "-shm"))), add = TRUE) + for (ext in c("", "-wal", "-shm")) { + if (file.exists(paste0(index, ext))) { + file.copy(paste0(index, ext), paste0(tmp, ext)) + } + } + db <- DBI::dbConnect(RSQLite::SQLite(), tmp) + on.exit(DBI::dbDisconnect(db), add = TRUE, after = FALSE) + if (!DBI::dbExistsTable(db, "archives")) { + return(none) + } + x <- DBI::dbGetQuery(db, "SELECT gid, zipfile, md5 FROM archives WHERE gid IS NOT NULL") + if (nrow(x) == 0) none else x +} + +## An earlier release's Drive file for this zip: same path below the release folder and same MD5, +## and still on Drive (not trashed) with that MD5. NULL when there is none. +pipeline_reusable_file <- function(previous, rel, md5) { + prev <- previous[previous$zipfile == rel & previous$md5 == md5, , drop = FALSE] + if (nrow(prev) == 0) { + return(NULL) + } + file <- tryCatch(googledrive::drive_get(googledrive::as_id(prev$gid[1])), error = \(e) NULL) + r <- if (!is.null(file) && nrow(file) == 1) file$drive_resource[[1]] + if (is.null(r) || isTRUE(r$trashed) || !identical(r$md5Checksum, md5)) { + return(NULL) + } + file +} + +## Upload one batch's zips. Each zip is, in order of preference: +## - "reused": an earlier release (`lookup`, from pipeline_previous_lookup()) has the identical +## zip on Drive; +## - "found": the release folder already has a file of that name and MD5 (an interrupted run); +## - "updated": the release folder has a file of that name with another MD5 (the zip was +## rebuilt, e.g. with masked cells), replaced in place so its Drive ID stays the same +## (.uploadAction() decides which file when there are several). Only with replaceChanged +## (replace_changed in _local.R); otherwise the upload stops, naming the zip; +## - "uploaded" as a new file. +## With dryRun nothing on Drive is read or written: `source` is "reused" (gid from `lookup`, not +## checked) or "dry run" (gid NA). `folders` is pipeline_release_folders(). Returns one row per +## zip: subset, gid, md5, zipfile (path below the release folder), uploaded (Drive's createdTime, +## epoch seconds; NA in a dry run) and source. +upload_zips <- function( + zips, + spec, + folders, + dryRun, + lookup, + driveEmail = NULL, + replaceChanged = FALSE +) { + pipeline_load() # .uploadAction(); an upload worker starts without the package + if (!is.null(driveEmail)) { + options(gargle_oauth_email = driveEmail) # a worker process doesn't see _local.R's options + } + previous <- if (length(zips) > 0) pipeline_previous_rows(lookup, spec) + rows <- lapply(zips, function(zip) { + subset <- basename(dirname(zip)) + rel <- pipeline_zip_relpath(spec, subset) + out <- data.frame( + subset = subset, + gid = NA_character_, + md5 = unname(tools::md5sum(zip)), + zipfile = rel, + uploaded = NA_real_, + source = "dry run" + ) + if (isTRUE(dryRun)) { + prev <- previous$gid[previous$zipfile == rel & previous$md5 == out$md5] + if (length(prev) > 0) { + out$gid <- prev[1] + out$source <- "reused" + } + return(out) + } + + file <- pipeline_reusable_file(previous, rel, out$md5) + out$source <- "reused" + if (is.null(file)) { + folder <- unname(readRDS(folders$path)[dirname(rel)]) + if (length(folder) != 1 || is.na(folder)) { + stop("no release folder for ", dirname(rel)) + } + there <- googledrive::drive_ls( + googledrive::as_id(folder), + q = sprintf("name = '%s'", basename(zip)) + ) + md5s <- vapply(there$drive_resource, \(r) r$md5Checksum %||% NA_character_, character(1)) + ## a changed zip replaces its file in this release's folder in place, keeping the Drive ID + ## the index holds; files outside this folder (earlier releases) are never touched + gid <- previous$gid[previous$zipfile == rel] + act <- tryCatch( + .uploadAction( + data.frame(id = as.character(there$id), md5 = md5s), + out$md5, + if (length(gid) > 0) gid[1], + replace = replaceChanged + ), + error = \(e) stop(rel, ": ", conditionMessage(e), call. = FALSE) + ) + if (act$action == "found") { + file <- there[there$id == act$id, ] + out$source <- "found" + } else { + file <- googledrive::with_drive_quiet( + if (act$action == "update") { + googledrive::drive_update(googledrive::as_id(act$id), media = zip) + } else { + googledrive::drive_upload( + zip, + path = googledrive::as_id(folder), + name = basename(zip), + overwrite = NA + ) + } + ) + if (!identical(file$drive_resource[[1]]$md5Checksum, out$md5)) { + stop("MD5 mismatch after uploading ", rel, " (Drive file ", file$id, ")") + } + out$source <- if (act$action == "update") "updated" else "uploaded" + } + } + out$gid <- as.character(file$id) + out$uploaded <- pipeline_drive_time( + file$drive_resource[[1]], + if (identical(out$source, "updated")) "modifiedTime" else "createdTime" + ) + out + }) + if (length(rows) == 0) { + ## an errored zips branch (error = "null") + return(data.frame( + subset = character(0), + gid = character(0), + md5 = character(0), + zipfile = character(0), + uploaded = numeric(0), + source = character(0) + )) + } + do.call(rbind, rows) +} diff --git a/data-raw/pipeline/R/zips.R b/data-raw/pipeline/R/zips.R new file mode 100644 index 0000000..8bb06a0 --- /dev/null +++ b/data-raw/pipeline/R/zips.R @@ -0,0 +1,155 @@ +## Cutting a batch's published zips (MSY, M, Y, S; Y for normals) from its MSY outputs. + +pipeline_subsets <- function(type) { + if (type %in% c("historical_normals", "future_normals")) "Y" else c("MSY", "M", "Y", "S") +} + +## Zip path, using the existing names: historical 39_MSY_2020.zip, future +## 39_CanESM5_245_MSY_2020.zip, normals 39_normals_Y.zip / 39_CanESM5_245_normals_Y.zip. +pipeline_zip_path <- function(outRoot, spec, subset) { + file.path(outRoot, "zips", pipeline_zip_relpath(spec, subset)) +} + +## The zip's path below /zips (and below the release's Drive folder), e.g. +## historical/MSY/39_MSY_2020.zip; this is the index's `zipfile`. +pipeline_zip_relpath <- function(spec, subset) { + scen <- if (is.na(spec$gcm)) character(0) else paste0(spec$gcm, "_ssp", spec$ssp) + normals <- spec$type %in% c("historical_normals", "future_normals") + name <- paste( + c( + spec$tile, + if (length(scen)) c(spec$gcm, spec$ssp), + if (normals) "normals", + subset, + if (!normals) spec$decade + ), + collapse = "_" + ) + do.call(file.path, as.list(c(spec$type, scen, subset, paste0(name, ".zip")))) +} + +## Index-style rows for one zip, for .archiveExpected(). +pipeline_zip_rows <- function(spec, subset, zipfile) { + rows <- data.frame( + zipfile = zipfile, + tileid = spec$tile, + msy = subset, + gcm = spec$gcm, + ssp = spec$ssp + ) + if (spec$type %in% c("historical", "future")) { + rows <- rows[rep(1, length(spec$periods)), ] + rows$year <- spec$periods + } else { + rows <- rows[rep(1, length(spec$periods)), ] + rows$period <- spec$periods + } + rows +} + +## Write files below `dir` (`files`, relative to it; default all) into `zip` so that the zip is +## byte-identical whenever the files are (names, contents and modification times): names in +## C-locale order, no directory entries (-D), and no extra attributes such as access times or +## owners (-X). An unchanged zip then keeps its MD5 when it is rebuilt, and the next release can +## reuse its Drive file. Needs the `zip` program. +pipeline_write_zip <- function(zip, dir, files = NULL) { + zip <- normalizePath(zip, mustWork = FALSE) + owd <- setwd(dir) + on.exit(setwd(owd)) + if (is.null(files)) { + files <- list.files(".", recursive = TRUE) + } + files <- sort(files, method = "radix") + rc <- system2("zip", c("-X", "-D", "-q", "-9", zip, "-@"), input = files) + if (!identical(as.integer(rc), 0L)) { + stop("zip exited with status ", rc, " for ", zip) + } + zip +} + +## Each subset zip holds each period's folder under the subset's own name (Year_2020M, ...), as +## a ClimateNA /M, /S or /Y run would have written it and as the package's reader expects. The +## batch's stored period zips are extracted once into the node-local work directory, keeping the +## files' times; each subset is staged there by hard link, zipped, and checked. Before staging, +## the tile's cells in `masks` (pipeline_tile_masks()) are set to NODATA in the extracted copy, +## and its land cells ClimateNA left empty get the values in the period's fill CSV (`fills`, +## from fill_batch()); a land cell still empty is reported with a warning, and the zips are cut +## anyway. The stored period zips keep ClimateNA's output. +## No zips when the batch failed (manifest NULL under error = "null"). +zip_batch <- function(spec, manifest, outRoot, masks, fills = character(0)) { + if (length(manifest) == 0) { + return(character(0)) + } + pipeline_load() + tileDir <- pipeline_tile_dir(outRoot, spec) + normals <- spec$type %in% c("historical_normals", "future_normals") + work <- file.path(pipeline_work_dir(), paste0("zip-", spec$id)) + unlink(work, recursive = TRUE) # left by a killed run + on.exit(unlink(work, recursive = TRUE), add = TRUE) + raw <- file.path(work, "raw") + for (p in spec$periods) { + folder <- .periodFolder(spec$type, p, spec$msy, spec$gcm, spec$ssp) + utils::unzip(.periodZip(tileDir, folder), exdir = raw, setTimes = TRUE) + } + ## cells ClimateNA computed without a DEM elevation, outside Canada (#40) + mask <- masks[[as.character(spec$tile)]] + .maskAscDir(raw, mask) + ## land cells ClimateNA left empty: its point-mode values at the nearest land cell it covers + for (p in spec$periods) { + folder <- .periodFolder(spec$type, p, spec$msy, spec$gcm, spec$ssp) + fill <- fills[startsWith(basename(fills), paste0(folder, ".fill-"))] + if (length(fill) > 0) { + .fillAscDir(file.path(raw, folder), fill[1], mask$grid) + } + empty <- .emptyLandCells(file.path(raw, folder), mask$land, mask$grid) + if (length(empty) > 0) { + warning( + "tile ", + spec$tile, + " ", + folder, + ": ", + length(empty), + if (length(empty) == 1) " land cell" else " land cells", + " still empty (", + paste(utils::head(empty, 10), collapse = ", "), + if (length(empty) > 10) ", ...", + ")", + call. = FALSE + ) + } + } + out <- character(0) + for (subset in pipeline_subsets(spec$type)) { + vars <- if (normals) .allowedClimateVars_nrm else get(paste0(".allowedClimateVars_", subset)) + staging <- file.path(work, subset) + for (p in spec$periods) { + src <- file.path(raw, .periodFolder(spec$type, p, spec$msy, spec$gcm, spec$ssp)) + dst <- file.path(staging, .periodFolder(spec$type, p, subset, spec$gcm, spec$ssp)) + dir.create(dst, recursive = TRUE) + from <- file.path(src, paste0(vars, ".asc")) + to <- file.path(dst, paste0(vars, ".asc")) + linked <- suppressWarnings(file.link(from, to)) + if (!all(linked)) { + file.copy(from[!linked], to[!linked], copy.date = TRUE) + } + } + zip <- pipeline_zip_path(outRoot, spec, subset) + dir.create(dirname(zip), recursive = TRUE, showWarnings = FALSE) + unlink(zip) + pipeline_write_zip(zip, staging) + + expected <- .archiveExpected(pipeline_zip_rows(spec, subset, basename(zip)), spec$type) + problems <- .archiveCheck(.zipListing(zip), expected) + if (!.archiveComplete(problems)) { + stop( + "incomplete zip ", + basename(zip), + ": ", + paste(utils::head(problems$item, 5), collapse = ", ") + ) + } + out <- c(out, zip) + } + out +} diff --git a/data-raw/pipeline/README.md b/data-raw/pipeline/README.md new file mode 100644 index 0000000..f405323 --- /dev/null +++ b/data-raw/pipeline/README.md @@ -0,0 +1,42 @@ +# ClimateNA data pipeline + +A [targets](https://docs.ropensci.org/targets/) pipeline that builds one data release of climateData's tile archives. It runs ClimateNA in the Docker image from `docker/climatena/`, checks every output, cuts the zips, uploads them to Google Drive and builds the tile index. + +ClimateNA writes values even where the DEM tile has no elevation, computed at the wrong elevation. When the zips are cut, those cells are set to NODATA unless their centre lies in Canada (GADM 4.1, level 0, holes filled, downloaded once to `/boundary/`); the raw outputs keep ClimateNA's values (#40). + +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. Each such cell gets ClimateNA's point-mode output at the nearest land cell it covers (within `fill_max_km` in `release.yml`), run with the empty cell's own elevation. The cells and their sources are found once per release from one reference period per class (historical: the last historical year; future: the first scenario's first year); the point-mode outputs are stored beside the raw period zips (`.fill-.csv`) and written into the zips when they are cut. The index lists every filled cell (`filled_cells`). + +- `release.yml`: the release (committed): ClimateNA version, years, scenarios, image, Drive folder. +- `_local.R`: per machine (gitignored; copy `_local.R.example`): paths, the container user, how many workers, dry run, and whether a changed zip may replace its file on Drive (`replace_changed`, off by default). The pipeline uses at most half of each node's cores: a larger worker count is lowered, with a message. +- `_targets.R`, `R/`: the pipeline. + +Run from the package root on a compute node: + +```r +targets::tar_make( + script = "data-raw/pipeline/_targets.R", + store = file.path(local$out_root, "_targets") +) +``` + +See the maintainer vignette, `vignette("maintaining-climate-data")`, for the full workflow. + +## Prototype checks (2026-11-04) + +One tile (39) at 3 arcmin, ClimateNA v7.70, `crew_controller_local(workers = 4)`, dry run. A ClimateNA run took about 45 s per year, so a decade batch takes about 8 minutes. + +| Check | Result | +|---|---| +| Add a year: historical 2010-2024 to 2010-2025 | ClimateNA ran only 2025. The 2010s batch, zips and uploads were skipped. | +| Add a scenario: future CanESM5 2090-2100, SSP 245 to 245 + 585 | Only the 11 SSP 585 years ran. SSP 245 and historical zips and uploads were skipped. | +| Delete one `.asc` from `Year_2022MSY` | The next run found it and reran only 2022. | +| Set a 5 s run timeout | The batch failed, naming `Year_2023MSY`. Its container was removed and no zips were cut from the truncated output. The report listed the error and the four missing zips. With the timeout restored, only 2023 reran. | +| A compatible new release (v7.70 copied as "v7.71") | Both compatibility checks passed. No ClimateNA runs; no zips or uploads rebuilt. | +| A changed new release (one stored value altered) | `tar_make()` stopped before any historical batch, asking to raise `min_version`. Raising `min_version: historical` to "7.71" regenerated every historical year. | +| A real upload to a scratch release folder | 4 zips (8 MB) in 30 s, MD5s matching. | +| The same, killed 12 s into the uploads, then rerun | The zip uploaded before the kill was found and kept; the other three were uploaded. No duplicate files; MD5s and the index's Drive IDs all match. | +| A second release whose previous index is the first's | All 4 zips reused the first release's Drive files; nothing uploaded. | + +The scratch release folders were then moved to Drive's trash. + +Three of these checks found defects, fixed on this branch: a damaged output folder was never rerun, a failed batch still had its zips cut, and a failed compatibility check didn't stop the batches. diff --git a/data-raw/pipeline/_local.R.example b/data-raw/pipeline/_local.R.example new file mode 100644 index 0000000..ec0d3bf --- /dev/null +++ b/data-raw/pipeline/_local.R.example @@ -0,0 +1,60 @@ +## Machine-specific settings for the ClimateNA pipeline. Copy to _local.R (gitignored) and edit. +## 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 + release_file = NULL, + + ## an unpacked ClimateNA release, mounted read-only into the containers + climatena_dir = "/path/to/ClimateNA_v7.70", + + ## DEM tiles (can_dem_.asc, Windows line endings) at the release's resolution + dem_dir = "/path/to/ClimateNA_data/dem", + + ## everything the pipeline writes: raw/, zips/, _targets/, logs, the index and the report. + ## Keep it from one release to the next (one per DEM resolution), so unchanged outputs and + ## zips are reused. + out_root = "/path/to/ClimateNA_data/pipeline/3arcmin", + + ## node-local directory ClimateNA writes into before each output is copied to out_root + ## (ClimateNA writes very slowly to an NFS share); NULL for each worker's tempdir() + work_dir = NULL, + + ## user the containers run as (must match the image's build args) + uid = 1000L, + gid = 1000L, + + ## NULL for all tiles with a DEM, or a subset for testing, e.g. 39L + tiles = NULL, + + ## TRUE: build everything but upload nothing to Drive + dry_run = TRUE, + + ## TRUE: when a rebuilt zip differs from the file of that name in the release's Drive folder, + ## replace that file in place (same Drive ID). FALSE: such an upload stops with an error, so a + ## shipped release's files change only when you ask. + replace_changed = FALSE, + + ## the Google account for uploads: its OAuth token must be cached on this machine + ## (googledrive::drive_auth() once, interactively) + drive_email = NULL, # e.g. "you@example.org" + + ## how many uploads at once, on this machine + upload_workers = 8L, + + ## the previous release's index: zips identical to its (same path and MD5) reuse its Drive + ## files instead of being uploaded again. NULL for the package's shipped index. + previous_index = NULL, + + ## seconds before a ClimateNA run is stopped and its period counted as failed + run_timeout = 3600, + + ## how many ClimateNA runs at once on this machine. The pipeline uses at most half of each + ## node's cores, so this is lowered (with a message) to half the cores less the upload + ## workers and the main process. + workers = 4L + ## ...or across nodes (FOR-CAST/crew.ssh), each capped at half its cores, with the checkout at + ## the same path on each: + ## ssh_nodes = c(node1 = 60L, node2 = 90L), + ## projdir = "/path/to/climateData" +) diff --git a/data-raw/pipeline/_targets.R b/data-raw/pipeline/_targets.R new file mode 100644 index 0000000..706ca30 --- /dev/null +++ b/data-raw/pipeline/_targets.R @@ -0,0 +1,283 @@ +## ClimateNA data pipeline: builds one data release of climateData's tile archives. +## +## Run from the package root, on a compute node: +## targets::tar_make(script = "data-raw/pipeline/_targets.R", +## store = file.path(, "_targets")) +## Settings: release.yml (committed) and _local.R (per machine; see _local.R.example). +## +## Dependencies are kept fine-grained on purpose: no target command uses the whole `local` +## list or the crew controller, and per-field settings are their own targets, so editing the +## release (new years, GCMs or SSPs) rebuilds only the branches whose own inputs changed. + +library(targets) +library(tarchetypes) + +source("data-raw/pipeline/_local.R") # defines `local` +cfg <- yaml::read_yaml( + if (is.null(local$release_file)) "data-raw/pipeline/release.yml" else local$release_file +) + +## scalar settings as plain globals: a target that uses one depends on that value only +climatena_dir_path <- local$climatena_dir +dem_dir_path <- local$dem_dir +out_root_path <- local$out_root +container_uid <- local$uid +container_gid <- local$gid +tile_subset <- local$tiles +dry_run <- local$dry_run +## replace a release folder's file in place when its rebuilt zip differs; 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" +## 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)) { + Sys.setenv(CLIMATENA_WORK_DIR = local$work_dir) +} +drive_email <- local$drive_email # the Google account whose cached token uploads use +if (!is.null(drive_email)) { + options(gargle_oauth_email = drive_email) +} + +devtools::load_all(".", quiet = TRUE) # the main process uses the checkout too + +## The pipeline uses at most half of each node's cores (.cappedWorkers()). Each ClimateNA run is +## limited to one CPU, so on this node: ClimateNA workers + upload workers + this process. +if (!is.null(local$controller)) { + stop( + "_local.R: set `workers` (or `ssh_nodes`) instead of `controller`; ", + "the pipeline sizes its workers to at most half of each node's cores" + ) +} +upload_workers <- .cappedWorkers(local$upload_workers %||% 8L, parallelly::availableCores(), 1L) +climatena_controller <- if (is.null(local$ssh_nodes)) { + crew::crew_controller_local( + workers = .cappedWorkers( + local$workers %||% 4L, + parallelly::availableCores(), + upload_workers + 1L + ) + ) +} else { + ## other nodes (FOR-CAST/crew.ssh) run ClimateNA only + nodes <- local$ssh_nodes + for (n in names(nodes)) { + cores <- as.integer(system2("ssh", c(n, "nproc"), stdout = TRUE)) + nodes[[n]] <- .cappedWorkers(nodes[[n]], cores, 0L, where = n) + } + crew.ssh::crew_controller_ssh(nodes = nodes, projdir = local$projdir) +} + +tar_option_set( + ## nothing attached on workers: the default (the main process's attached packages) would + ## include the load_all()ed climateData, which isn't installed; pipeline_load() loads it + packages = character(0), + ## ClimateNA runs go to climatena_controller; uploads to a few local workers on this node, + ## where the Drive token is + controller = crew::crew_controller_group( + climatena_controller, + crew::crew_controller_local(name = "uploads", workers = upload_workers) + ), + deployment = "main", # small targets stay on the main process + error = "null", + storage = "worker", + retrieval = "worker" +) +tar_source("data-raw/pipeline/R") + +## one set of targets per archive type +mapped <- tar_map( + values = data.frame(type = unlist(cfg$types)), + names = type, + unlist = FALSE, + tar_target(specs, pipeline_specs(type, tiles, cfg), iteration = "list"), + tar_target(min_version, cfg[["min_version"]][[type]]), + + ## does this ClimateNA release reproduce the stored outputs it would keep? If not, the whole + ## pipeline stops (error = "stop") before any batch of this type runs + tar_target( + compat, + compat_check( + type, + climatena_exe, + climatena_version, + min_version, + image, + climatena_dir, + dem_dir, + out_root, + container_uid, + container_gid, + timeout = run_timeout + ), + deployment = "worker", + error = "stop" + ), + + ## one branch per batch (a tile's decade, or a tile's normals): run, check, stamp. + ## Runs on every tar_make() to re-check the outputs on disk; a period already done costs a + ## file listing, and an unchanged manifest leaves the zips alone. + tar_target( + batch, + { + compat + run_batch( + specs, + climatena_exe, + climatena_version, + image, + climatena_dir, + dem_dir, + out_root, + min_version, + container_uid, + container_gid, + timeout = run_timeout + ) + }, + pattern = map(specs), + format = "file", + deployment = "worker", + cue = tar_cue(mode = "always") + ), + + ## ClimateNA point-mode values for the batch's empty land cells (fill_points), one CSV per + ## period beside its raw zip; none for a tile with nothing to fill + tar_target( + fills, + fill_batch( + specs, + batch, + fill_points, + out_root, + pipeline_point_runner( + image, + climatena_exe, + climatena_dir, + container_uid, + container_gid, + run_timeout + ) + ), + pattern = map(specs, batch), + format = "file", + deployment = "worker" + ), + + ## the batch's MSY, M, Y and S zips (Y for normals), masked and filled, each checked + tar_target( + zips, + zip_batch(specs, batch, out_root, tile_masks, fills), + pattern = map(specs, batch, fills), + format = "file", + deployment = "worker" + ), + + ## each zip as an earlier release's identical file, or a file in the release's Drive folder + ## (replaced in place when the zip changed, with replace_changed; otherwise that stops) + tar_target( + uploads, + upload_zips( + zips, + specs, + release_folders, + dry_run, + previous_lookup, + drive_email, + replace_changed + ), + pattern = map(zips, specs), + deployment = "worker", + resources = tar_resources(crew = tar_resources_crew(controller = "uploads")) + ) +) + +list( + ## one target per setting + ## ([[ ]] rather than $, so no field name reads as a dependency on the target of the same name) + tar_target(release_id, cfg[["release_id"]]), + tar_target(climatena_exe, cfg[["climatena_exe"]]), + tar_target(climatena_version, cfg[["climatena_version"]]), + tar_target(dem_resolution, cfg[["dem_resolution"]]), + tar_target(image, cfg[["image"]]), + tar_target(drive_parent, cfg[["drive_parent"]]), + tar_target(climatena_dir, climatena_dir_path), + tar_target(dem_dir, dem_dir_path), + tar_target(out_root, out_root_path), + ## the DEM folder's tiles, listed on every run: adding or removing a DEM file changes neither + ## dem_dir nor the tile subset (an unchanged list rebuilds nothing) + tar_target(tiles, pipeline_tiles(dem_dir, tile_subset), cue = tar_cue(mode = "always")), + ## the DEM files themselves, so what is built from them follows their contents. This and the + ## other release-wide inputs stop the run when they fail: under error = "null" one failure + ## would become an error in every branch + tar_target(dem_files, pipeline_dem_files(dem_dir, tiles), format = "file", error = "stop"), + ## the cells each tile's zips set to NODATA (no DEM elevation, centre outside Canada; #40), + ## and its land cells + tar_target(canada, pipeline_canada(out_root), format = "file"), + tar_target(tile_masks, pipeline_tile_masks(canada, dem_files), error = "stop"), + tar_target(previous_index, previous_index_path, format = "file"), + + mapped, + + ## all types together, for the Drive folders and the index + tar_combine(specs_all, mapped[["specs"]], command = c(!!!.x), iteration = "list"), + + ## land cells ClimateNA leaves empty, and the nearest land cell it covers for each (checked + ## with a point run), from each class's reference period in the raw outputs + tar_target(fill_reference, pipeline_fill_reference(cfg)), + tar_target(fill_max_km, cfg[["fill_max_km"]] %||% 50), + tar_target( + fill_points, + pipeline_fill_points( + manifests, + tile_masks, + dem_files, + fill_reference, + out_root, + fill_max_km, + pipeline_point_runner( + image, + climatena_exe, + climatena_dir, + container_uid, + container_gid, + run_timeout + ) + ), + deployment = "worker", + error = "stop" + ), + tar_target( + release_folders, + pipeline_release_folders(specs_all, release_id, drive_parent, dry_run, out_root) + ), + tar_target(previous_lookup, pipeline_previous_lookup(previous_index, specs_all, out_root)), + tar_combine(uploads_all, mapped[["uploads"]], command = rbind(!!!.x)), + tar_combine(manifests, mapped[["batch"]], command = c(!!!.x)), + + ## the release's ClimateNA_tiles.sqlite + tar_target( + index, + build_index( + uploads_all, + specs_all, + manifests, + out_root, + release_id, + climatena_version, + dem_resolution, + fill_points + ), + format = "file" + ), + + ## errors, warnings and missing zips, refreshed on every run (empty when all is well) + tar_target( + report, + build_report(index, specs_all, uploads_all, out_root), + format = "file", + cue = tar_cue(mode = "always") + ) +) diff --git a/data-raw/pipeline/release.yml b/data-raw/pipeline/release.yml new file mode 100644 index 0000000..790179a --- /dev/null +++ b/data-raw/pipeline/release.yml @@ -0,0 +1,36 @@ +## One data release of the ClimateNA archives (committed). Machine-specific paths and the crew +## controller go in _local.R (gitignored; see _local.R.example). + +release_id: cna-v7.70-3arcmin +climatena_exe: ClimateNA_v7.70.exe +climatena_version: "7.70" +dem_resolution: 3arcmin + +## 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 + +## Drive folder holding the archives; each release gets a subfolder named release_id +drive_parent: 1ldnlPHklhJsyJ8YBdI7IqUTxX9aW6UIc diff --git a/inst/extdata/ClimateNA_tiles.sqlite b/inst/extdata/ClimateNA_tiles.sqlite index e177d06..9723134 100755 Binary files a/inst/extdata/ClimateNA_tiles.sqlite and b/inst/extdata/ClimateNA_tiles.sqlite differ diff --git a/man/climateData-package.Rd b/man/climateData-package.Rd index 63ec9ee..38c74dc 100644 --- a/man/climateData-package.Rd +++ b/man/climateData-package.Rd @@ -11,6 +11,7 @@ Utilities for working with North American climate data from 'ClimateNA' \url{htt \seealso{ Useful links: \itemize{ + \item \url{https://predictiveecology.github.io/climateData/} \item \url{https://github.com/PredictiveEcology/climateData} \item Report bugs at \url{https://github.com/PredictiveEcology/climateData/issues} } diff --git a/man/climateDataRelease.Rd b/man/climateDataRelease.Rd new file mode 100644 index 0000000..fc11136 --- /dev/null +++ b/man/climateDataRelease.Rd @@ -0,0 +1,21 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/dataRelease.R +\name{climateDataRelease} +\alias{climateDataRelease} +\title{Identify the climate data release behind the installed package} +\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 +made before releases were recorded give \code{release_id = "pre-3.0.0"}. +} +\description{ +Each climateData release ships a tile index pointing at one release of the ClimateNA +archives on Google Drive. 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. +} +\examples{ +climateDataRelease()$release_id +} diff --git a/man/climateMosaicsParallel.Rd b/man/climateMosaicsParallel.Rd index 3ec79d8..a3148ae 100644 --- a/man/climateMosaicsParallel.Rd +++ b/man/climateMosaicsParallel.Rd @@ -7,7 +7,15 @@ \usage{ climateMosaicsParallel(y, climVars, tile, srcdir, dstdir) -climateMosaicsNormalsParallel(p, climVars, tile, srcdir, dstdir) +climateMosaicsNormalsParallel( + p, + climVars, + tile, + srcdir, + dstdir, + gcm = NULL, + ssp = NULL +) } \arguments{ \item{y}{integer specifying a single data year.} diff --git a/man/dot-cappedWorkers.Rd b/man/dot-cappedWorkers.Rd new file mode 100644 index 0000000..40df30b --- /dev/null +++ b/man/dot-cappedWorkers.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineWorkers.R +\name{.cappedWorkers} +\alias{.cappedWorkers} +\title{How many pipeline workers a node may run} +\usage{ +.cappedWorkers(requested, cores, reserved, where = "this node") +} +\arguments{ +\item{requested}{integer. Workers asked for.} + +\item{cores}{integer. The node's cores.} + +\item{reserved}{integer. Cores already in use by the pipeline on that node.} + +\item{where}{character. The node, for the message.} +} +\value{ +integer: \code{requested}, or the cap when it is lower (with a message), and at least 1. +} +\description{ +The data pipeline uses at most half of a node's cores. Each ClimateNA run is limited to one +CPU (\verb{--cpus 1}), so its CPU use is the number of workers plus \code{reserved} (on the controlling +node: the upload workers and the main process). +} +\keyword{internal} diff --git a/man/dot-chooseSources.Rd b/man/dot-chooseSources.Rd new file mode 100644 index 0000000..21e8aeb --- /dev/null +++ b/man/dot-chooseSources.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.chooseSources} +\alias{.chooseSources} +\title{Choose each target's source: the nearest candidate ClimateNA gives values at} +\usage{ +.chooseSources(candidates, check, ids = unique(candidates$id)) +} +\arguments{ +\item{candidates}{data.frame from \code{\link[=.fillCandidates]{.fillCandidates()}}.} + +\item{check}{function taking rows of \code{candidates} (one per target) and returning the \code{id}s +whose source gave values (a ClimateNA point-mode run, in the pipeline).} + +\item{ids}{character. All targets, including any without candidates.} +} +\value{ +data.frame with \code{id}, \code{src_lon}, \code{src_lat} and \code{km}, one row per id; \code{NA} source and +\code{km} for a target left without one. +} +\description{ +Tries every target's nearest candidate in one \code{check}, then the next candidate for the +targets whose check gave no values, and so on until each has a source or has no candidates +left. +} +\keyword{internal} diff --git a/man/dot-emptyLandCells.Rd b/man/dot-emptyLandCells.Rd new file mode 100644 index 0000000..aeae47a --- /dev/null +++ b/man/dot-emptyLandCells.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.emptyLandCells} +\alias{.emptyLandCells} +\title{Land cells still empty in a period folder} +\usage{ +.emptyLandCells(dir, land, grid) +} +\arguments{ +\item{dir}{character. One period's folder, extracted.} + +\item{land}{integer. The tile's land cells (as from \code{\link[=.maskCells]{.maskCells()}}).} + +\item{grid}{the tile's grid.} +} +\value{ +integer: the land cells whose \code{MAT.asc} value is NODATA. +} +\description{ +A ClimateNA output is empty in all its variables at once, so \code{MAT.asc} tells. +} +\keyword{internal} diff --git a/man/dot-fillAsc.Rd b/man/dot-fillAsc.Rd new file mode 100644 index 0000000..c6605b3 --- /dev/null +++ b/man/dot-fillAsc.Rd @@ -0,0 +1,25 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineMask.R +\name{.fillAsc} +\alias{.fillAsc} +\title{Write values into empty cells of a ClimateNA ASCII grid, in place} +\usage{ +.fillAsc(file, fill) +} +\arguments{ +\item{file}{character. A ClimateNA \code{.asc} file.} + +\item{fill}{list: \code{grid} (as from \code{\link[=.maskCells]{.maskCells()}}) for the file's tile; \code{cells}, the cell +numbers to fill; \code{values}, character, one per cell.} +} +\value{ +\code{TRUE} if the file changed, else \code{FALSE}, invisibly. +} +\description{ +Replaces the text of each listed cell, which must be the file's \code{NODATA_value}, with the given +value, as ClimateNA's point mode wrote it. Every other byte is left as ClimateNA wrote it, and +the file keeps its modification time (see \code{\link[=.maskAsc]{.maskAsc()}}). Stops, leaving the file unchanged, +if a listed cell has a value (ClimateNA's own values are never overwritten) or a given value +is missing (\code{-9999} or the file's \code{NODATA_value}). +} +\keyword{internal} diff --git a/man/dot-fillAscDir.Rd b/man/dot-fillAscDir.Rd new file mode 100644 index 0000000..baebc91 --- /dev/null +++ b/man/dot-fillAscDir.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.fillAscDir} +\alias{.fillAscDir} +\title{Fill a period folder's empty land cells from ClimateNA's point-mode output} +\usage{ +.fillAscDir(dir, fillCsv, grid) +} +\arguments{ +\item{dir}{character. One period's folder (e.g. \code{Year_2020MSY}), extracted.} + +\item{fillCsv}{character. That period's point-mode output for the folder's tile.} + +\item{grid}{the tile's grid (as from \code{\link[=.maskCells]{.maskCells()}}).} +} +\value{ +integer: how many files changed. +} +\description{ +Writes each variable's values from \code{fillCsv} (\code{\link[=.pointValues]{.pointValues()}}) into \verb{/.asc} +(\code{\link[=.fillAsc]{.fillAsc()}}), for every \code{.asc} file in \code{dir}. +} +\keyword{internal} diff --git a/man/dot-fillCandidates.Rd b/man/dot-fillCandidates.Rd new file mode 100644 index 0000000..aa8006d --- /dev/null +++ b/man/dot-fillCandidates.Rd @@ -0,0 +1,24 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.fillCandidates} +\alias{.fillCandidates} +\title{Candidate sources for land cells ClimateNA leaves empty} +\usage{ +.fillCandidates(targets, sources, maxKm, maxCandidates = 10L) +} +\arguments{ +\item{targets, sources}{data.frames with \code{id}, \code{lon} and \code{lat} (cell centres, degrees).} + +\item{maxKm}{numeric. Farthest a source may be, in km.} + +\item{maxCandidates}{integer. Most candidates kept per target.} +} +\value{ +data.frame with \code{id} (the target's), \code{rank} (1 = nearest), \code{src_lon}, \code{src_lat} and +\code{km}; a target with no source within \code{maxKm} has no rows. +} +\description{ +For each target (a land cell with no ClimateNA values), the nearest land cells that have +values, within \code{maxKm} (geodesic distance), nearest first. +} +\keyword{internal} diff --git a/man/dot-maskAsc.Rd b/man/dot-maskAsc.Rd new file mode 100644 index 0000000..8b9b3b6 --- /dev/null +++ b/man/dot-maskAsc.Rd @@ -0,0 +1,28 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineMask.R +\name{.maskAsc} +\alias{.maskAsc} +\title{Blank cells in a ClimateNA ASCII grid, in place} +\usage{ +.maskAsc(file, mask) +} +\arguments{ +\item{file}{character. A ClimateNA \code{.asc} file.} + +\item{mask}{list from \code{\link[=.maskCells]{.maskCells()}} for the file's tile.} +} +\value{ +\code{TRUE} if the file changed, else \code{FALSE}, invisibly. +} +\description{ +Sets the cells listed in \code{mask} to the file's \code{NODATA_value}. Only those values' text +changes: every other byte (other values, spacing, line endings) is left as ClimateNA wrote +it. A file with nothing to blank is not rewritten. A rewritten file keeps its modification +time, so zips cut from it are byte-identical each time they are rebuilt. +} +\details{ +Cells are counted in the order the values appear after the header, as GDAL reads them, not +by line: ClimateNA wraps some files' rows across lines (e.g. 100 values, then 77) and +sometimes writes a run of spaces between two values. +} +\keyword{internal} diff --git a/man/dot-maskAscDir.Rd b/man/dot-maskAscDir.Rd new file mode 100644 index 0000000..e8314d1 --- /dev/null +++ b/man/dot-maskAscDir.Rd @@ -0,0 +1,20 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineMask.R +\name{.maskAscDir} +\alias{.maskAscDir} +\title{Blank cells in every ClimateNA ASCII grid below a folder, in place} +\usage{ +.maskAscDir(dir, mask) +} +\arguments{ +\item{dir}{character. A folder, e.g. a batch's extracted period folders.} + +\item{mask}{list from \code{\link[=.maskCells]{.maskCells()}} for the folder's tile.} +} +\value{ +integer: how many files changed. +} +\description{ +Blank cells in every ClimateNA ASCII grid below a folder, in place +} +\keyword{internal} diff --git a/man/dot-maskCells.Rd b/man/dot-maskCells.Rd new file mode 100644 index 0000000..9f66bb8 --- /dev/null +++ b/man/dot-maskCells.Rd @@ -0,0 +1,26 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineMask.R +\name{.maskCells} +\alias{.maskCells} +\title{Cells to blank in a tile's ClimateNA output} +\usage{ +.maskCells(dem, boundary) +} +\arguments{ +\item{dem}{single-layer \code{SpatRaster}: the DEM tile, in longitude/latitude.} + +\item{boundary}{\code{SpatVector} in the same coordinates: the area whose no-DEM cells are kept +(Canada). Holes are filled first.} +} +\value{ +list: \code{grid}, the tile's ASCII-grid header values (named \code{ncols}, \code{nrows}, +\code{xllcorner}, \code{yllcorner}, \code{cellsize}); \code{cells}, the cell numbers to blank (row by row from +the top left, ascending); and \code{land}, the cells with a DEM elevation, which the zips must +have values for (ascending). +} +\description{ +The DEM tiles mark cells with no elevation as NA, and ClimateNA writes values for those cells +anyway, computed at the wrong elevation. They are blanked when the zips are cut, except where +the cell centre lies inside \code{boundary} (Canadian coast and lakeshore cells, which are kept). +} +\keyword{internal} diff --git a/man/dot-pointValues.Rd b/man/dot-pointValues.Rd new file mode 100644 index 0000000..211d720 --- /dev/null +++ b/man/dot-pointValues.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.pointValues} +\alias{.pointValues} +\title{Read the values ClimateNA's point mode wrote} +\usage{ +.pointValues(file, vars) +} +\arguments{ +\item{file}{character. The CSV ClimateNA wrote.} + +\item{vars}{character. The variables (columns) wanted.} +} +\value{ +list: \code{tile} and \code{cells} (integer, one per kept row) and \code{values}, a character matrix +(rows as \code{cells}, columns \code{vars}) holding the values as ClimateNA wrote them. +} +\description{ +Rows are identified by their \code{id1} (tile) and \code{id2} (cell), never by position. A row with +\code{-9999} in any of \code{vars} gave no values and is dropped, with a warning naming its cells. +} +\keyword{internal} diff --git a/man/dot-uploadAction.Rd b/man/dot-uploadAction.Rd new file mode 100644 index 0000000..456b39d --- /dev/null +++ b/man/dot-uploadAction.Rd @@ -0,0 +1,29 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineUpload.R +\name{.uploadAction} +\alias{.uploadAction} +\title{What to do with a zip on Drive} +\usage{ +.uploadAction(there, md5, gid = NULL, replace = FALSE) +} +\arguments{ +\item{there}{data.frame with columns \code{id} and \code{md5} (\code{NA} when Drive gives none).} + +\item{md5}{character. The zip's MD5.} + +\item{gid}{character or \code{NULL}. The zip's Drive ID in the index, if it has one.} + +\item{replace}{logical. Replace a differing same-named file in place?} +} +\value{ +list: \code{action} (\code{"found"}, \code{"update"} or \code{"upload"}) and \code{id} (\code{NA} for \code{"upload"}). +} +\description{ +Given the files of the same name already in the zip's release folder: reuse one with the same +MD5 (\code{"found"}); else, if \code{replace}, replace a differing one in place (\code{"update"}), so its +Drive ID, which the index holds as \code{gid}, stays the same; else upload a new file (\code{"upload"}). +When several same-named files differ, the one with ID \code{gid} is updated; if none has it, this +stops. Without \code{replace}, a differing same-named file stops the upload, so a shipped +release's files change only when the maintainer asks (\code{replace_changed} in \verb{_local.R}). +} +\keyword{internal} diff --git a/man/dot-writePointCsv.Rd b/man/dot-writePointCsv.Rd new file mode 100644 index 0000000..909bf8b --- /dev/null +++ b/man/dot-writePointCsv.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/pipelineFill.R +\name{.writePointCsv} +\alias{.writePointCsv} +\title{Write a ClimateNA point-mode input file} +\usage{ +.writePointCsv(file, df) +} +\arguments{ +\item{file}{character. The CSV to write.} + +\item{df}{data.frame with \code{tile}, \code{cell}, \code{src_lat}, \code{src_lon} and \code{elev} (character).} +} +\value{ +\code{file}, invisibly. +} +\description{ +One row per point: \code{id1} the tile, \code{id2} the cell, \code{lat}/\code{long} the source location and +\code{elev} the target cell's elevation, written as given (the DEM's text, unrounded). Lines end +in CRLF, as ClimateNA's own examples do. +} +\keyword{internal} diff --git a/man/filledCells.Rd b/man/filledCells.Rd new file mode 100644 index 0000000..27de788 --- /dev/null +++ b/man/filledCells.Rd @@ -0,0 +1,38 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/filledCells.R +\name{filledCells} +\alias{filledCells} +\title{Land cells filled from a nearby point} +\usage{ +filledCells(studyArea = NULL, tiles = NULL) +} +\arguments{ +\item{studyArea}{optional \code{sf}, \code{sfc} or \code{SpatVector} polygon(s), in any CRS: only cells +inside are returned.} + +\item{tiles}{optional integer tile IDs.} +} +\value{ +an \code{sf} of points (the cells' centres, EPSG:4326) with columns \code{class}, \code{tile}, +\code{cell} (the cell number in the tile's grid, row by row from the top left), \code{elev} (the +cell's elevation, m), \code{filled}, \code{src_lon} and \code{src_lat} (where ClimateNA was run) and \code{km} +(the distance to it). No rows for a data release without filled cells. +} +\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 +mapped, or masked out of an analysis. +} +\details{ +\code{class} says which archives a cell was filled in: \code{"historical"} (historical years and +normals) or \code{"future"} (future years and normals). A cell with \code{filled = FALSE} had no +covered land cell within reach, and has no values. +} +\examples{ +\donttest{ +fc <- filledCells() +table(fc$class, fc$filled) +} +} diff --git a/man/maskInvalidPPT.Rd b/man/maskInvalidPPT.Rd deleted file mode 100644 index 58f0c3d..0000000 --- a/man/maskInvalidPPT.Rd +++ /dev/null @@ -1,21 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/ClimateNA_useTiles.R -\name{maskInvalidPPT} -\alias{maskInvalidPPT} -\title{Read a tile's climate file, with invalid cells set to NA} -\usage{ -maskInvalidPPT(file) -} -\arguments{ -\item{file}{character. A single tile-year climate file.} -} -\value{ -a \code{SpatRaster}. -} -\description{ -ClimateNA tiles 6 and 7 have cells south of the Canada/US border where the DEM is not valid: -all 12 monthly \code{PPT} values are exactly 0 and temperatures are nonsense. Such cells are set -to NA, for every variable, so an overlapping valid tile can show through in the mosaic. -The \code{PPT01}-\code{PPT12} files are read from the same year directory as \code{file}. -} -\keyword{internal} diff --git a/man/prepClimateLayers.Rd b/man/prepClimateLayers.Rd index 38aa26a..7f89698 100644 --- a/man/prepClimateLayers.Rd +++ b/man/prepClimateLayers.Rd @@ -67,7 +67,10 @@ used to tag \code{Cache} entries.} \item{...}{additional arguments (not used)} } \description{ -Prepare rasters for derived and 'as-is' climate variables +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. } \examples{ if (require("archive", quietly = TRUE) && diff --git a/tests/testthat/helper-shell.R b/tests/testthat/helper-shell.R new file mode 100644 index 0000000..fbed475 --- /dev/null +++ b/tests/testthat/helper-shell.R @@ -0,0 +1,9 @@ +## The text shQuote() quoted: sh wraps it in single quotes; cmd (the default on Windows) wraps it +## in double quotes, with \" for each double quote inside. +.unquoteShell <- function(x, type = if (.Platform$OS.type == "windows") "cmd" else "sh") { + if (type == "cmd") { + gsub('\\"', '"', sub('^"(.*)"$', "\\1", x), fixed = TRUE) + } else { + sub("^'(.*)'$", "\\1", x) + } +} diff --git a/tests/testthat/test-archiveCheck.R b/tests/testthat/test-archiveCheck.R index 16fa6a6..10ade2a 100644 --- a/tests/testthat/test-archiveCheck.R +++ b/tests/testthat/test-archiveCheck.R @@ -123,6 +123,22 @@ test_that(".zipListing reads an empty zip as an empty listing", { expect_equal(p$item, "Year_2100Y") }) +test_that(".archiveExpected names future normals folders as ClimateNA writes them", { + e <- .archiveExpected( + data.frame( + zipfile = "z", + tileid = 39L, + msy = "Y", + gcm = "CanESM5", + ssp = "245", + period = c("2011_2040", "2041_2070") + ), + "future_normals" + ) + expect_length(e, 50) + expect_contains(e, "CanESM5_ssp245_2011-2040Y/rsds.asc") +}) + test_that(".archiveIndexGaps finds years the index lacks", { idx <- rowsH(setdiff(available("historical")$years, 2013L)) g <- .archiveIndexGaps(idx, "historical") @@ -130,6 +146,23 @@ test_that(".archiveIndexGaps finds years the index lacks", { expect_equal(g$tileid, 39L) }) +test_that(".archiveIndexGaps finds future normals scenarios the index lacks", { + av <- available("future_normals") + full <- expand.grid( + tileid = 39L, + msy = "Y", + gcm = av$gcms, + ssp = av$ssps, + period = av$periods, + stringsAsFactors = FALSE + ) + idx <- full[!(full$gcm == av$gcms[1] & full$ssp == av$ssps[1]), ] + g <- .archiveIndexGaps(idx, "future_normals") + expect_equal(nrow(g), length(av$periods)) + expect_equal(unique(g$gcm), av$gcms[1]) + expect_equal(unique(g$ssp), av$ssps[1]) +}) + test_that(".driveProblems classifies missing, trashed and renamed files", { zips <- data.frame( gid = c("a", "b", "c", "d"), diff --git a/tests/testthat/test-archivesTable.R b/tests/testthat/test-archivesTable.R index a37389a..7427d58 100644 --- a/tests/testthat/test-archivesTable.R +++ b/tests/testthat/test-archivesTable.R @@ -38,14 +38,19 @@ test_that("shipped index: one archives row per published zip", { con <- DBI::dbConnect(RSQLite::SQLite(), f, flags = RSQLite::SQLITE_RO) withr::defer(DBI::dbDisconnect(con)) skip_if_not("archives" %in% DBI::dbListTables(con), "archives table not yet filled") - gids <- DBI::dbGetQuery( - con, - paste( - "SELECT gid FROM historical UNION SELECT gid FROM historical_normals", - "UNION SELECT gid FROM future" - ) - )$gid + types <- intersect(.allowedClimateTypes, DBI::dbListTables(con)) + gids <- DBI::dbGetQuery(con, paste("SELECT gid FROM", types, collapse = " UNION "))$gid a <- DBI::dbGetQuery(con, "SELECT gid, md5 FROM archives") expect_setequal(a$gid, gids) expect_match(a$md5, "^[0-9a-f]{32}$") }) + +test_that("index tables declare a climatena_version column", { + skip_if_not_installed("withr") + f <- file.path(withr::local_tempdir(), "t.sqlite") + for (type in c("historical", "historical_normals", "future", "future_normals")) { + x <- ClimateNA_sql(f, type) + expect_contains(DBI::dbListFields(x$db, type), "climatena_version") + DBI::dbDisconnect(x$db) + } +}) diff --git a/tests/testthat/test-available.R b/tests/testthat/test-available.R index bc83742..cac71ad 100644 --- a/tests/testthat/test-available.R +++ b/tests/testthat/test-available.R @@ -9,3 +9,7 @@ test_that("radiation variables use the ClimateNA v7.60 name rsds", { expect_length(intersect(.allowedClimateVars, legacy), 0) expect_length(.allowedClimateVars_MSY, 265) }) + +test_that("historical years run to 2025 (ClimateNA v7.70)", { + expect_identical(available("historical")$years, 1901L:2025L) +}) diff --git a/tests/testthat/test-climateMosaicsParallel.R b/tests/testthat/test-climateMosaicsParallel.R index 69fa8f3..c5421df 100644 --- a/tests/testthat/test-climateMosaicsParallel.R +++ b/tests/testthat/test-climateMosaicsParallel.R @@ -8,16 +8,30 @@ test_that("climateMosaicsParallel only mosaics the requested tiles", { src <- withr::local_tempdir("historical") dst <- withr::local_tempdir("mosaics") tileRaster <- function(tile, xmin) { - r <- terra::rast(nrows = 2, ncols = 2, xmin = xmin, xmax = xmin + 2, ymin = 0, ymax = 2, crs = "EPSG:4326") + r <- terra::rast( + nrows = 2, + ncols = 2, + xmin = xmin, + xmax = xmin + 2, + ymin = 0, + ymax = 2, + crs = "EPSG:4326" + ) terra::values(r) <- tile dir.create(file.path(src, tile, "Year_2000MSY"), recursive = TRUE) terra::writeRaster(r, file.path(src, tile, "Year_2000MSY", "CMD_sm.asc"), overwrite = TRUE) } tileRaster(6, xmin = 0) - tileRaster(16, xmin = 10) # a stray directory whose name ends in 6 + tileRaster(16, xmin = 10) # a stray directory whose name ends in 6 tileRaster(26, xmin = 20) - out <- climateMosaicsParallel(y = "2000", climVars = "CMD_sm", tile = 6, srcdir = src, dstdir = dst) + out <- climateMosaicsParallel( + y = "2000", + climVars = "CMD_sm", + tile = 6, + srcdir = src, + dstdir = dst + ) expect_length(out, 1) expect_match(basename(out), "_t_6[.]tif$") @@ -36,36 +50,76 @@ test_that("climateMosaicsParallel matches the year in the directory name, not el src <- file.path(root, "1990-2020", "historical") dst <- withr::local_tempdir("mosaics") yearRaster <- function(year, value) { - r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 2, ymin = 0, ymax = 2, crs = "EPSG:4326") + r <- terra::rast( + nrows = 2, + ncols = 2, + xmin = 0, + xmax = 2, + ymin = 0, + ymax = 2, + crs = "EPSG:4326" + ) terra::values(r) <- value dir.create(file.path(src, 6, sprintf("Year_%dMSY", year)), recursive = TRUE) - terra::writeRaster(r, file.path(src, 6, sprintf("Year_%dMSY", year), "CMD_sm.asc"), overwrite = TRUE) + terra::writeRaster( + r, + file.path(src, 6, sprintf("Year_%dMSY", year), "CMD_sm.asc"), + overwrite = TRUE + ) } yearRaster(1990, 100) yearRaster(2000, 300) - m1990 <- terra::rast(climateMosaicsParallel(y = "1990", climVars = "CMD_sm", tile = 6, srcdir = src, dstdir = dst)) - m2000 <- terra::rast(climateMosaicsParallel(y = "2000", climVars = "CMD_sm", tile = 6, srcdir = src, dstdir = dst)) + m1990 <- terra::rast(climateMosaicsParallel( + y = "1990", + climVars = "CMD_sm", + tile = 6, + srcdir = src, + dstdir = dst + )) + m2000 <- terra::rast(climateMosaicsParallel( + y = "2000", + climVars = "CMD_sm", + tile = 6, + srcdir = src, + dstdir = dst + )) expect_true(all(terra::values(m1990) == 100)) expect_true(all(terra::values(m2000) == 300)) }) -## ClimateNA tiles 6 and 7 hold cells south of the border where PPT01-PPT12 are all 0 and temperatures -## are nonsense (the DEM is not valid there). They reached the mosaics and gave absurd cumMDC and CMD. -test_that("climateMosaicsParallel sets every variable to NA where all 12 monthly PPT are 0", { +## Several scenarios' future normals are extracted into one tile folder, named as ClimateNA +## writes them (CanESM5_ssp245_2011-2040Y). Each must be mosaicked on its own, to its own file. +test_that("future normals mosaic only the requested scenario, with distinct names", { skip_if_not_installed("withr") - src <- withr::local_tempdir("historical") + src <- withr::local_tempdir("normals") dst <- withr::local_tempdir("mosaics") - yd <- file.path(src, 6, "Year_2000MSY") - dir.create(yd, recursive = TRUE) - mk <- function(v, f) { - r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 2, ymin = 0, ymax = 2, crs = "EPSG:4326") - terra::values(r) <- v - terra::writeRaster(r, file.path(yd, f), overwrite = TRUE) + r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 2, ymin = 0, ymax = 2, crs = "EPSG:4326") + for (s in c("245", "370")) { + d <- file.path(src, 39, paste0("CanESM5_ssp", s, "_2011-2040Y")) + dir.create(d, recursive = TRUE) + terra::values(r) <- as.numeric(s) + terra::writeRaster(r, file.path(d, "MAT.asc"), overwrite = TRUE) } - for (m in 1:12) mk(c(0, 5, 5, 5), sprintf("PPT%02d.asc", m)) # cell 1: all months 0 - mk(c(40, 10, 10, 10), "Tmax_sm.asc") - - out <- climateMosaicsParallel(y = "2000", climVars = "Tmax_sm", tile = 6, srcdir = src, dstdir = dst) - expect_equal(as.vector(terra::values(terra::rast(out))), c(NA, 10, 10, 10)) + o245 <- climateMosaicsNormalsParallel( + "2011_2040", + "MAT_normal", + 39, + src, + dst, + gcm = "CanESM5", + ssp = "245" + ) + o370 <- climateMosaicsNormalsParallel( + "2011_2040", + "MAT_normal", + 39, + src, + dst, + gcm = "CanESM5", + ssp = "370" + ) + expect_false(identical(o245, o370)) + expect_equal(unique(terra::values(terra::rast(o245), mat = FALSE)), 245) + expect_equal(unique(terra::values(terra::rast(o370), mat = FALSE)), 370) }) diff --git a/tests/testthat/test-climatenaDocker.R b/tests/testthat/test-climatenaDocker.R new file mode 100644 index 0000000..2f25192 --- /dev/null +++ b/tests/testthat/test-climatenaDocker.R @@ -0,0 +1,29 @@ +test_that(".climatenaDockerArgs mounts ClimateNA read-only and passes container paths", { + a <- .climatenaDockerArgs( + name = "cna-r1-historical_39_2020", + image = "ghcr.io/predictiveecology/climatena-wine:latest", + climatenaDir = "/share/ClimateNA_v7.70", + demFile = "/share/dem/can_dem_39.asc", + outDir = "/share/raw/historical/39", + exe = "ClimateNA_v7.70.exe", + msy = "MSY", + periodArg = "Year_2025.ann", + uid = 1000L, + gid = 1000L + ) + expect_identical(a[1:4], c("run", "--rm", "--name", "cna-r1-historical_39_2020")) + expect_contains(a, c("--cpus", "1", "--memory", "1g", "--user", "1000:1000")) + expect_contains(a, "/share/ClimateNA_v7.70:/opt/climatena:ro") + expect_contains(a, c("/share/dem:/data/dem:ro", "/share/raw/historical/39:/data/out")) + expect_identical( + tail(a, 6), + c( + "ghcr.io/predictiveecology/climatena-wine:latest", + "ClimateNA_v7.70.exe", + "MSY", + "Year_2025.ann", + "/data/dem/can_dem_39.asc", + "/data/out" + ) + ) +}) diff --git a/tests/testthat/test-consolidateClimateTypes.R b/tests/testthat/test-consolidateClimateTypes.R index 4baa7ef..80b2fed 100644 --- a/tests/testthat/test-consolidateClimateTypes.R +++ b/tests/testthat/test-consolidateClimateTypes.R @@ -9,14 +9,34 @@ test_that("M and Y come from the MSY archive whenever MSY is needed", { expect_setequal(.consolidateClimateTypes(c("future_Y", "future_S")), "future_MSY") expect_setequal(.consolidateClimateTypes(c("future_M", "future_S", "future_Y")), "future_MSY") expect_setequal(.consolidateClimateTypes(c("historical_M", "historical_S")), "historical_MSY") - expect_setequal(.consolidateClimateTypes(c("historical_M", "historical_S", "future_M")), - c("historical_MSY", "future_M")) + expect_setequal( + .consolidateClimateTypes(c("historical_M", "historical_S", "future_M")), + c("historical_MSY", "future_M") + ) }) test_that("without a seasonal variable, M and Y keep their own archives", { expect_setequal(.consolidateClimateTypes("future_M"), "future_M") - expect_setequal(.consolidateClimateTypes(c("historical_M", "historical_Y")), c("historical_M", "historical_Y")) - expect_setequal(.consolidateClimateTypes(c("historical_N", "historical_S")), c("historical_N", "historical_MSY")) + expect_setequal( + .consolidateClimateTypes(c("historical_M", "historical_Y")), + c("historical_M", "historical_Y") + ) +}) + +## v3.0.0 data releases publish S archives; a seasonal-only request no longer needs the whole +## MSY archive. S plus M or Y still uses MSY (above). The cells ClimateNA computed without a DEM +## elevation are blanked in every archive when it is built, so S needs no monthly PPT to mask +## them (maskInvalidPPT() did, and is gone). +test_that("seasonal-only requests use the S archive", { + expect_setequal(.consolidateClimateTypes("future_S"), "future_S") + expect_setequal( + .consolidateClimateTypes(c("historical_S", "future_M")), + c("historical_S", "future_M") + ) + expect_setequal( + .consolidateClimateTypes(c("historical_N", "historical_S")), + c("historical_N", "historical_S") + ) }) test_that("prepClimateLayers downloads only the MSY archive for monthly plus seasonal variables", { @@ -33,19 +53,66 @@ test_that("prepClimateLayers downloads only the MSY archive for monthly plus sea buildClimateMosaics = function(...) stop("stop after downloads") ) vars <- list( - future_cumMDC = list(vars = c("future_PPT05", "future_Tmax05"), fun = quote(calcAsIs), - .dots = list(future_years = 2083:2085)), - future_CMD_sm = list(vars = "future_CMD_sm", fun = quote(calcAsIs), - .dots = list(future_years = 2083:2085)) + future_cumMDC = list( + vars = c("future_PPT05", "future_Tmax05"), + fun = quote(calcAsIs), + .dots = list(future_years = 2083:2085) + ), + future_CMD_sm = list( + vars = "future_CMD_sm", + fun = quote(calcAsIs), + .dots = list(future_years = 2083:2085) + ) ) expect_error( - prepClimateLayers(vars, srcdir = d, dstdir = file.path(d, "out"), tile = 46, - gcm = "CNRM-ESM2-1", ssp = 370), + prepClimateLayers( + vars, + srcdir = d, + dstdir = file.path(d, "out"), + tile = 46, + gcm = "CNRM-ESM2-1", + ssp = 370 + ), "stop after downloads" ) expect_identical(unique(requested), "future_MSY") }) +## prepClimateLayers() used to stop with "future normals not yet implemented". +test_that("prepClimateLayers asks for future normals archives instead of stopping", { + skip_if_not_installed("withr") + d <- withr::local_tempdir("test_futureNormals_") + requested <- list() + testthat::local_mocked_bindings( + getClimateURLs = function(type, tile, years = NULL, msy = NULL, gcm = NULL, ssp = NULL) { + requested[[length(requested) + 1]] <<- list(type = type, gcm = gcm, ssp = as.character(ssp)) + character(0) + }, + getClimateTiles = function(...) NULL, + .stopIfMissingClimateDirs = function(allDirs) invisible(allDirs), + buildClimateMosaicsNormals = function(...) stop("stop after downloads") + ) + vars <- list( + future_MAT_normal = list( + vars = "future_MAT_normal", + fun = quote(calcAsIs), + .dots = list(future_period = "2011_2040") + ) + ) + expect_error( + prepClimateLayers( + vars, + srcdir = d, + dstdir = file.path(d, "out"), + tile = 39, + gcm = "CanESM5", + ssp = 245 + ), + "stop after downloads" + ) + expect_identical(requested[[1]], list(type = "future_normals", gcm = "CanESM5", ssp = "245")) +}) + test_that("monthly variables load from an MSY folder", { skip_if_not_installed("withr") src <- withr::local_tempdir("future") @@ -56,7 +123,13 @@ test_that("monthly variables load from an MSY folder", { dir.create(msy, recursive = TRUE) terra::writeRaster(r, file.path(msy, "PPT05.asc"), overwrite = TRUE) - out <- climateMosaicsParallel(y = "2085", climVars = "PPT05", tile = 46, srcdir = src, dstdir = dst) + out <- climateMosaicsParallel( + y = "2085", + climVars = "PPT05", + tile = 46, + srcdir = src, + dstdir = dst + ) expect_length(out, 1) expect_true(all(terra::values(terra::rast(out)) == 5)) }) diff --git a/tests/testthat/test-dataRelease.R b/tests/testthat/test-dataRelease.R new file mode 100644 index 0000000..d28bb1f --- /dev/null +++ b/tests/testthat/test-dataRelease.R @@ -0,0 +1,106 @@ +## canClimateData caches prepClimateLayers() results; it needs an identifier that changes with +## each data release so a new release isn't served from an old cache. +test_that("climateDataRelease reads the release table", { + skip_if_not_installed("withr") + f <- file.path(withr::local_tempdir(), "t.sqlite") + db <- sqlite_connect_db(f) + .releaseCreate(db) + .releaseWrite( + db, + data.frame( + release_id = "cna-v7.70-3arcmin", + climatena_version = "7.70", + dem_resolution = "3arcmin", + created = 1.7e9 + ) + ) + DBI::dbDisconnect(db) + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + r <- climateDataRelease() + expect_identical(r$release_id, "cna-v7.70-3arcmin") + expect_identical(r$climatena_version, "7.70") + expect_identical(r$dem_resolution, "3arcmin") +}) + +test_that("climateDataRelease reports an index without a release table as pre-3.0.0", { + skip_if_not_installed("withr") + f <- file.path(withr::local_tempdir(), "t.sqlite") + DBI::dbDisconnect(sqlite_connect_db(f)) + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + expect_identical(climateDataRelease()$release_id, "pre-3.0.0") +}) + +## canClimateData calls it on every run, in many processes at once: it must read the shipped +## index where it is, read-only (no 40 MB copy), and leave the package folder as it was. +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) + Sys.chmod(d, "0555") + withr::defer(Sys.chmod(d, "0755")) + + realConnect <- sqlite_connect_db + opened <- list() + testthat::local_mocked_bindings( + ClimateNA_tiles_sqlite = function() f, + sqlite_connect_db = function(dbfile, readonly = FALSE) { + opened[[length(opened) + 1]] <<- list(dbfile = dbfile, readonly = readonly) + realConnect(dbfile, readonly = readonly) + } + ) + expect_identical(climateDataRelease()$release_id, "cna-v7.70-3arcmin") + expect_identical(opened, list(list(dbfile = f, readonly = TRUE))) + expect_identical(list.files(d), "ClimateNA_tiles.sqlite") +}) + +test_that(".releaseWrite keeps a single row", { + skip_if_not_installed("withr") + db <- sqlite_connect_db(file.path(withr::local_tempdir(), "t.sqlite")) + withr::defer(DBI::dbDisconnect(db)) + .releaseCreate(db) + row <- data.frame( + release_id = "a", + climatena_version = "7.70", + dem_resolution = "3arcmin", + created = 1 + ) + .releaseWrite(db, row) + row$release_id <- "b" + .releaseWrite(db, row) + expect_identical(DBI::dbGetQuery(db, "SELECT release_id FROM release")$release_id, "b") +}) + +## 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", { + skip_if_not_installed("withr") + 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) + 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" + ) + want <- file.path(d, climateDataRelease()$release_id, "historical") + expect_identical(unname(got), c(want, want)) +}) diff --git a/tests/testthat/test-filledCells.R b/tests/testthat/test-filledCells.R new file mode 100644 index 0000000..2eb7d61 --- /dev/null +++ b/tests/testthat/test-filledCells.R @@ -0,0 +1,68 @@ +## filledCells(): the land cells whose values came from ClimateNA's point mode at a nearby land +## cell (or were left empty), read from the bundled index. +filledIndex <- function(rows = TRUE) { + f <- file.path(withr::local_tempdir(.local_envir = parent.frame()), "index.sqlite") + db <- sqlite_connect_db(f) + on.exit(DBI::dbDisconnect(db)) + .releaseCreate(db) + if (rows) { + .filledCellsCreate(db) + .filledCellsWrite( + db, + data.frame( + class = c("future", "future", "historical"), + tile = c(63L, 63L, 52L), + cell = c(13905L, 14081L, 100L), + lon = c(-61.425, -61.425, -64.175), + lat = c(66.725, 66.675, 63.625), + elev = c("204.7481", "461.6809", "17.3577"), + src_lon = c(-61.525, NA, -64.175), + src_lat = c(66.725, NA, 63.475), + km = c(4.41, NA, 16.7) + ) + ) + } + f +} + +test_that("filledCells returns sf points with the documented columns", { + f <- filledIndex() + local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + x <- filledCells() + expect_s3_class(x, "sf") + expect_identical(nrow(x), 3L) + expect_identical( + setdiff(names(x), attr(x, "sf_column")), + c("class", "tile", "cell", "elev", "filled", "src_lon", "src_lat", "km") + ) + expect_identical(x$filled, c(TRUE, FALSE, TRUE)) + expect_identical(sf::st_crs(x)$epsg, 4326L) + expect_equal(unname(sf::st_coordinates(x)[1, ]), c(-61.425, 66.725)) +}) + +test_that("filledCells filters by tiles", { + f <- filledIndex() + local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + expect_identical(filledCells(tiles = 52)$tile, 52L) +}) + +test_that("filledCells keeps points inside a projected study area", { + f <- filledIndex() + local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + ## a 5 km square (Canada Atlas Lambert) around tile 63's first cell + p <- sf::st_transform(sf::st_sfc(sf::st_point(c(-61.425, 66.725)), crs = 4326), 3978) + sa <- sf::st_buffer(p, 2500, endCapStyle = "SQUARE") + x <- filledCells(studyArea = sa) + expect_identical(x$cell, 13905L) + ## a SpatVector works too + expect_identical(filledCells(studyArea = terra::vect(sa))$cell, 13905L) +}) + +test_that("filledCells returns no rows for an index without filled_cells", { + f <- filledIndex(rows = FALSE) + local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + expect_no_warning(x <- filledCells()) + expect_s3_class(x, "sf") + expect_identical(nrow(x), 0L) + expect_true(all(c("class", "tile", "cell", "filled") %in% names(x))) +}) diff --git a/tests/testthat/test-pipelineBatches.R b/tests/testthat/test-pipelineBatches.R new file mode 100644 index 0000000..8e6191e --- /dev/null +++ b/tests/testthat/test-pipelineBatches.R @@ -0,0 +1,92 @@ +test_that(".periodFolder and .periodArg follow ClimateNA v7.70 naming", { + expect_identical(.periodFolder("historical", 2025L, "MSY"), "Year_2025MSY") + expect_identical( + .periodFolder("future", 2025L, "MSY", "CanESM5", "245"), + "CanESM5_ssp245@2025MSY" + ) + expect_identical(.periodFolder("historical_normals", "1991_2020", "Y"), "Normal_1991_2020Y") + expect_identical( + .periodFolder("future_normals", "2011_2040", "Y", "CanESM5", "245"), + "CanESM5_ssp245_2011-2040Y" + ) + expect_identical(.periodArg("historical", 2025L), "Year_2025.ann") + expect_identical(.periodArg("future", 2025L, "CanESM5", "245"), "CanESM5_ssp245@2025.gcm") + expect_identical(.periodArg("historical_normals", "1991_2020"), "Normal_1991_2020.nrm") + expect_identical( + .periodArg("future_normals", "2011_2040", "CanESM5", "245"), + "CanESM5_ssp245_2011-2040.gcm" + ) +}) + +test_that(".batchSpecs makes one batch per decade, with stable ids", { + b <- .batchSpecs("historical", tiles = 39L, years = 2011:2025) + expect_identical(vapply(b, `[[`, "", "id"), c("historical_39_2010", "historical_39_2020")) + expect_identical(b[[2]]$periods, 2020:2025) + expect_identical(b[[2]]$msy, "MSY") + b26 <- .batchSpecs("historical", tiles = 39L, years = 2011:2026) + expect_identical(b26[[1]], b[[1]]) # adding 2026 leaves the 2010s batch identical + expect_identical(b26[[2]]$periods, 2020:2026) +}) + +test_that("adding a GCM or SSP leaves the existing batch specs identical", { + old <- .batchSpecs("future", tiles = 39L, gcms = "CanESM5", ssps = "245", years = 2011:2030) + new <- .batchSpecs( + "future", + tiles = 39L, + gcms = c("CanESM5", "MIROC6"), + ssps = c("245", "585"), + years = 2011:2030 + ) + ids <- vapply(new, `[[`, "", "id") + for (o in old) { + expect_identical(new[[match(o$id, ids)]], o) + } +}) + +test_that(".batchSpecs covers future and normals", { + f <- .batchSpecs( + "future", + tiles = 39L, + gcms = "CanESM5", + ssps = c("245", "370"), + years = 2091:2100 + ) + expect_identical( + vapply(f, `[[`, "", "id"), + c( + "future_39_CanESM5_245_2090", + "future_39_CanESM5_245_2100", + "future_39_CanESM5_370_2090", + "future_39_CanESM5_370_2100" + ) + ) + n <- .batchSpecs( + "future_normals", + tiles = 39L, + gcms = "CanESM5", + ssps = "245", + periods = c("2011_2040", "2041_2070", "2071_2100") + ) + expect_length(n, 1) + expect_identical(n[[1]]$id, "future_normals_39_CanESM5_245") + expect_identical(n[[1]]$msy, "Y") + expect_identical(n[[1]]$periods, c("2011_2040", "2041_2070", "2071_2100")) +}) + +test_that(".demTiles lists only tiles with a DEM file", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + file.create(file.path(d, c("can_dem_1.asc", "can_dem_39.asc", "notes.txt"))) + expect_identical(.demTiles(d), c(1L, 39L)) + expect_identical(.demTiles(d, tiles = 39), 39L) +}) + +## A wrong dem_dir, or a requested tile without a DEM, gave no batches: an empty index and an +## empty report, which reads as a clean release. +test_that(".demTiles stops when there are no DEM tiles or a requested tile has none", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + expect_error(.demTiles(d), "No DEM tiles") + file.create(file.path(d, c("can_dem_1.asc", "can_dem_39.asc"))) + expect_error(.demTiles(d, tiles = c(39, 43)), "43") +}) diff --git a/tests/testthat/test-pipelineCompat.R b/tests/testthat/test-pipelineCompat.R new file mode 100644 index 0000000..72dc772 --- /dev/null +++ b/tests/testthat/test-pipelineCompat.R @@ -0,0 +1,45 @@ +ascLines <- function(v) { + c( + "ncols 3", + "nrows 1", + "xllcorner 0", + "yllcorner 0", + "cellsize 1", + "NODATA_value -9999", + paste(v, collapse = " ") + ) +} + +## A new ClimateNA release that only differs by last-digit rounding (the Wine spike: 3 of 3.9 +## million cells, each off by 1) reuses the existing outputs; a real change regenerates them. +test_that(".compatVerdict accepts last-digit rounding and rejects real changes", { + skip_if_not_installed("withr") + a <- withr::local_tempdir() + b <- withr::local_tempdir() + writeLines(ascLines(c(374, 10.5, 3)), file.path(a, "DD_0_at.asc")) + writeLines(ascLines(c(375, 10.5, 3)), file.path(b, "DD_0_at.asc")) + big <- seq_len(300000) + writeLines(ascLines(big), file.path(a, "MAT.asc")) + writeLines(ascLines(big), file.path(b, "MAT.asc")) + cmp <- .compareFolders(a, b) + expect_identical(cmp$differing[cmp$file == "DD_0_at.asc"], 1L) + expect_identical(.compatVerdict(cmp), "compatible") + + writeLines(ascLines(c(374, 12, 3)), file.path(b, "DD_0_at.asc")) # off by more than 1 + expect_identical(.compatVerdict(.compareFolders(a, b)), "changed") + file.remove(file.path(b, "MAT.asc")) # file set differs + expect_identical(.compatVerdict(.compareFolders(a, b)), "changed") +}) + +test_that(".compareAsc ignores Windows line endings but not header changes", { + skip_if_not_installed("withr") + d <- withr::local_tempdir() + writeLines(ascLines(c(1, 2, 3)), file.path(d, "lf.asc")) + writeBin( + charToRaw(paste0(paste(ascLines(c(1, 2, 3)), collapse = "\r\n"), "\r\n")), + file.path(d, "crlf.asc") + ) + expect_identical(.compareAsc(file.path(d, "lf.asc"), file.path(d, "crlf.asc"))$differing, 0L) + writeLines(sub("cellsize 1", "cellsize 2", ascLines(c(1, 2, 3))), file.path(d, "other.asc")) + expect_identical(.compareAsc(file.path(d, "lf.asc"), file.path(d, "other.asc"))$differing, 3L) +}) diff --git a/tests/testthat/test-pipelineFill.R b/tests/testthat/test-pipelineFill.R new file mode 100644 index 0000000..9ab609a --- /dev/null +++ b/tests/testthat/test-pipelineFill.R @@ -0,0 +1,450 @@ +## Land cells ClimateNA leaves empty are filled with its point-mode output at the nearest land +## cell it covers, run with the empty cell's own elevation. + +test_that(".fillCandidates orders sources by distance and drops those beyond maxKm", { + t <- data.frame(id = "a", lon = 0, lat = 60) + s <- data.frame(id = c("far", "near", "out"), lon = c(0.2, 0.05, 2), lat = 60) + cand <- .fillCandidates(t, s, maxKm = 50) + expect_identical(cand$id, c("a", "a")) + expect_identical(cand$rank, 1:2) + expect_equal(cand$src_lon, c(0.05, 0.2)) + expect_equal(cand$km[1], terra::distance(cbind(0, 60), cbind(0.05, 60), lonlat = TRUE)[1] / 1000) +}) + +test_that(".fillCandidates gives a target with no source in reach no rows", { + t <- data.frame(id = c("a", "b"), lon = c(0, 10), lat = 60) + s <- data.frame(id = "s", lon = 0.01, lat = 60) + cand <- .fillCandidates(t, s, maxKm = 50) + expect_identical(unique(cand$id), "a") +}) + +test_that(".chooseSources moves to the next candidate when a point run is empty", { + cand <- data.frame( + id = c("a", "a", "b"), + rank = c(1L, 2L, 1L), + src_lon = c(1, 2, 3), + src_lat = 60, + km = c(1, 2, 3) + ) + tried <- list() + check <- function(df) { + tried[[length(tried) + 1]] <<- df$id + df$id[df$src_lon != 1] # the first source of "a" gives no values + } + s <- .chooseSources(cand, check) + expect_equal(s$src_lon[s$id == "a"], 2) + expect_equal(s$km[s$id == "a"], 2) + expect_equal(s$src_lon[s$id == "b"], 3) + ## rank 1 for both, then rank 2 only for the one that failed + expect_identical(tried, list(c("a", "b"), "a")) +}) + +## ClimateNA's point mode reads a CSV of points and writes one, under Wine in the same image; +## the image's climatena-run wrapper would make the output path a folder, so sh runs wine itself +test_that(".climatenaPointDockerArgs mounts the work dir and runs wine on the CSVs", { + a <- .climatenaPointDockerArgs( + name = "cna-fill-1", + image = "ghcr.io/predictiveecology/climatena-wine:latest", + climatenaDir = "/share/ClimateNA_v7.70", + workDir = "/scratch/work/fill-1", + exe = "ClimateNA_v7.70.exe", + msy = "MSY", + periodArg = "Year_2020.ann", + inCsv = "in.csv", + outCsv = "out.csv", + uid = 1000L, + gid = 1000L + ) + expect_identical(a[1:4], c("run", "--rm", "--name", "cna-fill-1")) + expect_contains(a, c("--cpus", "1", "--memory", "1g", "--user", "1000:1000")) + expect_contains(a, c("/share/ClimateNA_v7.70:/opt/climatena:ro", "/scratch/work/fill-1:/data/w")) + i <- match("--entrypoint", a) + expect_identical(a[i + 1], "sh") + expect_identical(a[length(a) - 2], "ghcr.io/predictiveecology/climatena-wine:latest") + expect_identical(a[length(a) - 1], "-c") + ## system2() passes arguments to the host shell as they are: the script must reach the + ## container whole, with $WINEPREFIX unexpanded. shQuote() quotes for the host's shell: + ## single quotes for sh; double quotes, with \" for each quote inside, for cmd (Windows) + script <- a[length(a)] + script_text <- .unquoteShell(script) + expect_identical(script, shQuote(script_text)) + expect_match( + script_text, + 'wine ClimateNA_v7.70.exe /MSY /Year_2020.ann "/Z:\\data\\w\\in.csv" "/Z:\\data\\w\\out.csv"', + fixed = TRUE + ) + expect_match(script_text, "cd /opt/climatena", fixed = TRUE) + expect_match(script_text, '"$WINEPREFIX"', fixed = TRUE) + ## both quotings give back the script, whichever platform runs this + for (type in c("sh", "cmd")) { + expect_identical(.unquoteShell(shQuote(script_text, type = type), type), script_text) + } +}) + +test_that(".writePointCsv writes CRLF lines and the elevation text as given", { + f <- withr::local_tempfile(fileext = ".csv") + .writePointCsv( + f, + data.frame( + tile = c(53L, 53L), + cell = c(534L, 1591L), + src_lat = c(66.51, 66.47), + src_lon = c(-61.52, -61.525), + elev = c("32", "280.4286") + ) + ) + expect_identical( + rawToChar(readBin(f, "raw", file.size(f))), + "id1,id2,lat,long,elev\r\n53,534,66.51,-61.52,32\r\n53,1591,66.47,-61.525,280.4286\r\n" + ) +}) + +pointCsv <- function(lines) { + f <- withr::local_tempfile(fileext = ".csv", .local_envir = parent.frame()) + writeBin( + charToRaw(paste0( + c("id1,id2,Latitude,Longitude,Elevation,MAT,MAP", lines), + "\r\n", + collapse = "" + )), + f + ) + f +} + +test_that(".pointValues matches rows by cell, not position", { + f <- pointCsv(c("53,7,66.5,-61.5,32,-6.8,250", "63,3,66.4,-61.5,280,-7.9,260")) + v <- .pointValues(f, c("MAP", "MAT")) + expect_identical(v$tile, c(53L, 63L)) + expect_identical(v$cells, c(7L, 3L)) + expect_identical( + v$values, + matrix(c("250", "260", "-6.8", "-7.9"), 2, dimnames = list(NULL, c("MAP", "MAT"))) + ) +}) + +test_that(".pointValues drops -9999 rows with a warning", { + f <- pointCsv(c("53,7,66.5,-61.5,32,-6.8,250", "53,3,66.4,-61.5,280,-9999,-9999")) + expect_warning(v <- .pointValues(f, c("MAT", "MAP")), "no values.*cell 3") + expect_identical(v$cells, 7L) + expect_identical(unname(v$values[1, ]), c("-6.8", "250")) +}) + +test_that(".chooseSources leaves a target without a working candidate unfilled", { + cand <- data.frame(id = "a", rank = 1L, src_lon = 1, src_lat = 60, km = 1) + s <- .chooseSources(cand, function(df) character(0)) + expect_identical(s$id, "a") + expect_true(is.na(s$src_lon) && is.na(s$src_lat) && is.na(s$km)) +}) + +## the pipeline side (data-raw/pipeline/R/fill.R), with ClimateNA replaced by a stub +fillEnv <- function() { + d <- test_path("..", "..", "data-raw", "pipeline", "R") + skip_if_not(dir.exists(d), "data-raw/pipeline not available") + skip_if(Sys.which("zip") == "", "no zip program") + e <- new.env() + for (f in c("specs.R", "run_batch.R", "fill.R")) { + sys.source(file.path(d, f), envir = e) + } + e$pipeline_load <- function() invisible(TRUE) + e +} + +## a 2 x 2 tile at x 0-2 (or 2-4), y 0-2; values row by row from the top left +writeGrid <- function(file, values, xmin = 0) { + r <- terra::rast(nrows = 2, ncols = 2, xmin = xmin, xmax = xmin + 2, ymin = 0, ymax = 2) + terra::crs(r) <- "EPSG:4326" + terra::values(r) <- values + dir.create(dirname(file), recursive = TRUE, showWarnings = FALSE) + terra::writeRaster(r, file, NAflag = -9999, overwrite = TRUE) + unlink(paste0(file, ".aux.xml")) + file +} + +## a stored raw period (/.zip holding /MAT.asc) and its stamp +writePeriod <- function(tileDir, folder, mat, xmin = 0) { + stage <- withr::local_tempdir(.local_envir = parent.frame()) + writeGrid(file.path(stage, folder, "MAT.asc"), mat, xmin) + dir.create(tileDir, recursive = TRUE, showWarnings = FALSE) + withr::with_dir( + stage, + utils::zip( + file.path(tileDir, paste0(folder, ".zip")), + file.path(folder, "MAT.asc"), + flags = "-q" + ) + ) + .writeStamp(tileDir, folder, "7.70", "dem", "image") +} + +## stands in for ClimateNA's point mode: MAT = -1.5 at every point, and records each call +stubRunner <- function(calls) { + function(points, msy, periodArg) { + calls$n <- c(calls$n, periodArg) + d <- tempfile("stub-") + dir.create(d) + out <- file.path(d, "out.csv") + writeLines( + c( + "id1,id2,Latitude,Longitude,Elevation,MAT", + paste( + points$tile, + points$cell, + points$src_lat, + points$src_lon, + points$elev, + "-1.5", + sep = "," + ) + ), + out + ) + out + } +} + +test_that("pipeline_fill_reference picks the last historical year and the first scenario year", { + e <- fillEnv() + cfg <- list( + historical_years = list(1901, 2025), + future_years = list(2011, 2100), + gcms = list("CanESM5", "CNRM-ESM2-1"), + ssps = list("245", "370") + ) + cfg$types <- list("historical", "future", "historical_normals", "future_normals") + cfg$historical_periods <- list("1901_1930", "1991_2020") + cfg$future_periods <- list("2011_2040", "2071_2100") + r <- e$pipeline_fill_reference(cfg) + expect_identical(r$historical$period, 2025L) + expect_identical( + r$future[c("gcm", "ssp", "period")], + list(gcm = "CanESM5", ssp = "245", period = 2011L) + ) + expect_identical(c(r$historical$msy, r$future$msy), c("MSY", "MSY")) + + ## only the release's types: a class without yearly archives uses its normals; a class with + ## neither has no reference (nothing to fill) + cfg$types <- list("historical_normals") + r <- e$pipeline_fill_reference(cfg) + expect_named(r, "historical") + expect_identical( + r$historical[c("type", "period", "msy")], + list(type = "historical_normals", period = "1991_2020", msy = "Y") + ) +}) + +test_that("pipeline_fill_points finds land cells empty in the reference and gives each a source", { + e <- fillEnv() + out <- withr::local_tempdir() + demDir <- withr::local_tempdir() + ## tile 1 is all land; tile 2's top-left cell has no DEM (ocean) but a ClimateNA value + demFiles <- c( + "1" = writeGrid(file.path(demDir, "can_dem_1.asc"), c(10, 20, 30, 40)), + "2" = writeGrid(file.path(demDir, "can_dem_2.asc"), c(NA, 5, 6, 7), xmin = 2) + ) + canada <- terra::vect("POLYGON ((-1 -1, 5 -1, 5 3, -1 3, -1 -1))", crs = "EPSG:4326") + masks <- lapply(demFiles, \(f) .maskCells(terra::rast(f), canada)) + writePeriod(file.path(out, "raw", "historical", "1"), "Year_2025MSY", c(1, NA, 3, 4)) + writePeriod(file.path(out, "raw", "historical", "2"), "Year_2025MSY", c(9, 5, 6, 7), xmin = 2) + ref <- list( + historical = list(type = "historical", period = 2025L, msy = "MSY", gcm = NA, ssp = NA) + ) + calls <- new.env() + + p <- e$pipeline_fill_points( + "m.tsv", + masks, + unname(demFiles), # as the format = "file" target gives them + + ref, + out, + maxKm = 200, + run = stubRunner(calls) + ) + expect_identical(nrow(p), 1L) + expect_identical(p$class, "historical") + expect_identical(c(p$tile, p$cell), c(1L, 2L)) + expect_identical(p$elev, "20") + ## nearest land cell with values: tile 1's cell 4 (1.5, 0.5), not tile 2's ocean cell (2.5, 1.5) + expect_equal(c(p$lon, p$lat, p$src_lon, p$src_lat), c(1.5, 1.5, 1.5, 0.5)) + expect_identical(calls$n, "Year_2025.ann") +}) + +test_that("fill_batch runs each period once, reuses its CSV, and skips tiles without points", { + e <- fillEnv() + out <- withr::local_tempdir() + tileDir <- file.path(out, "raw", "historical", "1") + for (y in 2020:2021) { + writePeriod(tileDir, paste0("Year_", y, "MSY"), c(1, NA, 3, 4)) + } + spec <- list( + id = "h1", + type = "historical", + tile = 1L, + gcm = NA, + ssp = NA, + msy = "MSY", + decade = 2020L, + periods = 2020:2021 + ) + pts <- data.frame( + class = "historical", + tile = 1L, + cell = 2L, + lon = 1.5, + lat = 1.5, + elev = "20", + src_lon = 1.5, + src_lat = 0.5, + km = 110 + ) + calls <- new.env() + run <- stubRunner(calls) + + f <- e$fill_batch(spec, "m.tsv", pts, out, run) + expect_length(f, 2) + expect_true(all(file.exists(f))) + expect_match(basename(f), "^Year_202[01]MSY[.]fill-[0-9a-f]{8}[.]csv$") + expect_identical(calls$n, c("Year_2020.ann", "Year_2021.ann")) + + expect_identical(e$fill_batch(spec, "m.tsv", pts, out, run), f) + expect_length(calls$n, 2) # reused + + ## new sources: new files, and the old ones are removed + pts$src_lon <- 0.5 + f2 <- e$fill_batch(spec, "m.tsv", pts, out, run) + expect_false(any(f2 %in% f)) + expect_false(any(file.exists(f))) + + spec2 <- modifyList(spec, list(id = "h2", tile = 2L)) + expect_identical(e$fill_batch(spec2, "m.tsv", pts, out, run), character(0)) + expect_identical(e$fill_batch(spec, character(0), pts, out, run), character(0)) # failed batch +}) + +## applying the fills when the zips are cut +grid22 <- c(ncols = 2, nrows = 2, xllcorner = 0, yllcorner = 0, cellsize = 1) +tokensOf <- function(f) { + a <- .ascRead(f, grid22) + substring(a$data, a$start, a$end - 1L) +} +fillCsv <- function(file, cell, mat, map) { + writeLines( + c( + "id1,id2,Latitude,Longitude,Elevation,MAT,MAP", + paste(1, cell, 0.5, 0.5, 20, mat, map, sep = ",") + ), + file + ) + file +} + +test_that(".fillAscDir fills every variable of a period folder from its CSV", { + d <- withr::local_tempdir() + writeGrid(file.path(d, "MAT.asc"), c(1, NA, 3, 4)) + writeGrid(file.path(d, "MAP.asc"), c(100, NA, 300, 400)) + csv <- fillCsv(withr::local_tempfile(fileext = ".csv"), 2, "-6.8", "250") + expect_identical(.fillAscDir(d, csv, grid22), 2L) + expect_identical(tokensOf(file.path(d, "MAT.asc"))[2], "-6.8") + expect_identical(tokensOf(file.path(d, "MAP.asc"))[2], "250") +}) + +test_that(".emptyLandCells finds land cells still NODATA", { + d <- withr::local_tempdir() + writeGrid(file.path(d, "MAT.asc"), c(1, 2, NA, NA)) + expect_identical(.emptyLandCells(d, land = 1:3, grid = grid22), 3L) + expect_identical(.emptyLandCells(d, land = 1:2, grid = grid22), integer(0)) +}) + +zipEnv <- function() { + e <- fillEnv() + sys.source(test_path("..", "..", "data-raw", "pipeline", "R", "zips.R"), envir = e) + ## the fixture has only MAT.asc, not a whole ClimateNA output + e$.archiveCheck <- function(listing, expected) { + data.frame(problem = character(0), item = character(0)) + } + e +} + +normalsFixture <- function(out, mat) { + tileDir <- file.path(out, "raw", "historical_normals", "1") + writePeriod(tileDir, "Normal_1991_2020Y", mat) + list( + spec = list( + id = "hn1", + type = "historical_normals", + tile = 1L, + gcm = NA, + ssp = NA, + msy = "Y", + decade = NA, + periods = "1991_2020" + ), + masks = list("1" = list(grid = grid22, cells = integer(0), land = 1:4)), + tileDir = tileDir + ) +} + +zipMat <- function(zip) { + d <- withr::local_tempdir(.local_envir = parent.frame()) + utils::unzip(zip, exdir = d) + tokensOf(list.files(d, "^MAT[.]asc$", recursive = TRUE, full.names = TRUE)) +} + +test_that("zip_batch writes a period's fill CSV into its zip", { + e <- zipEnv() + out <- withr::local_tempdir() + withr::local_envvar(CLIMATENA_WORK_DIR = withr::local_tempdir()) + x <- normalsFixture(out, c(1, 2, NA, 4)) + csv <- fillCsv(file.path(x$tileDir, "Normal_1991_2020Y.fill-0123abcd.csv"), 3, "-7.9", "260") + expect_no_warning(z <- e$zip_batch(x$spec, "m.tsv", out, x$masks, csv)) + expect_identical(zipMat(z)[3], "-7.9") +}) + +test_that("zip_batch warns about land cells still empty", { + e <- zipEnv() + out <- withr::local_tempdir() + withr::local_envvar(CLIMATENA_WORK_DIR = withr::local_tempdir()) + x <- normalsFixture(out, c(1, 2, NA, 4)) + expect_warning( + z <- e$zip_batch(x$spec, "m.tsv", out, x$masks, character(0)), + "1 land cell.*still empty" + ) + expect_true(file.exists(z)) +}) + +## the index lists every filled land cell, and those left empty (no source within reach) +test_that("filled_cells round-trips through the index, with NULL sources for unfilled cells", { + db <- sqlite_connect_db(file.path(withr::local_tempdir(), "t.sqlite")) + withr::defer(DBI::dbDisconnect(db)) + .filledCellsCreate(db) + info <- DBI::dbGetQuery(db, "PRAGMA table_info(filled_cells)") + expect_identical( + info$name, + c("class", "tileid", "cell", "lon", "lat", "elev", "src_lon", "src_lat", "km") + ) + expect_identical( + info$type, + c("TEXT", "INTEGER", "INTEGER", "REAL", "REAL", "REAL", "REAL", "REAL", "REAL") + ) + + ## as pipeline_fill_points() gives them: `tile`, and the elevation as the DEM's text + pts <- data.frame( + class = "future", + tile = 63L, + cell = c(14081L, 13905L), + lon = -61.425, + lat = c(66.675, 66.725), + elev = c("461.6809", "204.7481"), + src_lon = c(NA, -61.525), + src_lat = c(NA, 66.725), + km = c(NA, 4.41) + ) + .filledCellsWrite(db, pts) + .filledCellsWrite(db, pts) # replaces the rows + got <- DBI::dbGetQuery(db, "SELECT * FROM filled_cells ORDER BY cell") + expect_identical(nrow(got), 2L) + expect_identical(got$tileid, c(63L, 63L)) + expect_equal(got$elev, c(204.7481, 461.6809)) + expect_equal(got$km[1], 4.41) + expect_true(is.na(got$src_lon[2]) && is.na(got$km[2])) +}) diff --git a/tests/testthat/test-pipelineLookup.R b/tests/testthat/test-pipelineLookup.R new file mode 100644 index 0000000..07a5699 --- /dev/null +++ b/tests/testthat/test-pipelineLookup.R @@ -0,0 +1,22 @@ +## Adding a GCM or SSP changes specs_all, and with it the previous release's rows the lookup +## holds. The lookup's value must not change with them, or every upload branch reruns (24,518 +## for release cna-v7.70-3arcmin). The pipeline code is in data-raw/, which R CMD check omits. +test_that("the previous-release lookup's value doesn't change when scenarios are added", { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + skip_if_not_installed("withr") + e <- new.env() + sys.source(f, envir = e) + e$pipeline_previous_archives <- function(index) { + data.frame(zipfile = c("a.zip", "b.zip"), gid = c("ga", "gb"), md5 = c("ma", "mb")) + } + e$pipeline_zip_relpaths <- function(spec) spec$zips + out <- withr::local_tempdir() + + one <- e$pipeline_previous_lookup("idx", list(list(zips = "a.zip")), out) + two <- e$pipeline_previous_lookup("idx", list(list(zips = "a.zip"), list(zips = "b.zip")), out) + expect_identical(one, two) + + rows <- e$pipeline_previous_rows(two, list(zips = "b.zip")) + expect_identical(rows$gid, "gb") +}) diff --git a/tests/testthat/test-pipelineMask.R b/tests/testthat/test-pipelineMask.R new file mode 100644 index 0000000..61be65d --- /dev/null +++ b/tests/testthat/test-pipelineMask.R @@ -0,0 +1,225 @@ +## The DEM tiles mark cells with no elevation as NA, and ClimateNA computes those cells anyway at +## the wrong elevation. Outside Canada they are blanked when zips are cut; inside Canada (coast and +## lakeshore cells) they are kept. Holes in the boundary are filled first, as for the tile grid. +test_that(".maskCells blanks no-DEM cells outside the boundary only", { + dem <- terra::rast( + nrows = 4, + ncols = 4, + xmin = 0, + xmax = 4, + ymin = 0, + ymax = 4, + crs = "EPSG:4326" + ) + terra::values(dem) <- 100 + dem[c(1, 4, 13, 16)] <- NA + ## left half, with a hole over cell 1 (x 0-1, y 3-4) + outer <- cbind(c(0, 2, 2, 0, 0), c(0, 0, 4, 4, 0)) + hole <- cbind(c(0.2, 0.8, 0.8, 0.2, 0.2), c(3.2, 3.2, 3.8, 3.8, 3.2)) + boundary <- terra::vect( + rbind(cbind(1, 1, outer, 0), cbind(1, 1, hole, 1)), + type = "polygons", + crs = "EPSG:4326" + ) + + m <- .maskCells(dem, boundary) + expect_identical(m$cells, c(4L, 16L)) + expect_equal(m$grid, c(ncols = 4, nrows = 4, xllcorner = 0, yllcorner = 0, cellsize = 1)) + ## the cells with a DEM elevation: the land cells the zips must have values for + expect_identical(m$land, setdiff(1:16, c(1L, 4L, 13L, 16L))) +}) + +## An ASCII grid as ClimateNA writes it: header lines end in CRLF; each data row is the values +## separated by single spaces, then a space and CRLF. +writeClimatenaAsc <- function(file, tokens, ncols, nrows, xll = "-123.350000000000", eol = "\r\n") { + header <- sprintf( + "%-13s%s", + c("ncols", "nrows", "xllcorner", "yllcorner", "cellsize", "NODATA_value"), + c(ncols, nrows, xll, "45.800000000000", "0.050000000000", "-9999") + ) + rows <- vapply( + split(tokens, rep(seq_len(nrows), each = ncols)), + \(x) paste0(paste(x, collapse = " "), " "), + "" + ) + writeBin(charToRaw(paste0(c(header, rows), eol, collapse = "")), file) + file +} +gridOf <- function(ncols, nrows, xll = -123.35) { + c(ncols = ncols, nrows = nrows, xllcorner = xll, yllcorner = 45.8, cellsize = 0.05) +} +bytesOf <- function(f) readBin(f, "raw", file.size(f)) + +test_that(".maskAsc sets masked cells to NODATA and changes no other byte", { + tokens <- c("8", "-0.4", "12.3", "1", "2", "3", "4", "5", "6", "7", "8", "9") + masked <- replace(tokens, c(2, 7), "-9999") + for (eol in c("\r\n", "\n")) { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), tokens, 4, 3, eol = eol) + want <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), masked, 4, 3, eol = eol) + expect_true(.maskAsc(f, list(grid = gridOf(4, 3), cells = c(2L, 7L)))) + expect_identical(bytesOf(f), bytesOf(want)) + } +}) + +## ClimateNA sometimes writes a run of spaces between two values (seen in tile 6's MAT.asc) +test_that(".maskAsc finds values by position when spaces between them vary", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 4, 3) + txt <- sub("2 3 4 ", "2 3 4 ", rawToChar(bytesOf(f)), fixed = TRUE) + writeBin(charToRaw(txt), f) + expect_true(.maskAsc(f, list(grid = gridOf(4, 3), cells = c(3L, 4L)))) + expect_identical( + rawToChar(bytesOf(f)), + sub("2 3 4 ", "2 -9999 -9999 ", txt, fixed = TRUE) + ) +}) + +## ...and wraps some files' rows across lines (CMD01.asc: 100 values, then 77, per 177-cell row); +## readers take the values in order, whatever the line breaks +test_that(".maskAsc counts values in order across wrapped lines", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 3, 4) + wrapped <- withr::local_tempfile(fileext = ".asc") + ## 4 x 3 grid written 3 values to a line: the second row starts mid-line + txt <- sub("1 2 3 \r\n4 5 6 \r\n", "1 2 \r\n3 4 5 \r\n6 ", rawToChar(bytesOf(f)), fixed = TRUE) + txt <- sub("ncols 3", "ncols 4", txt, fixed = TRUE) + txt <- sub("nrows 4", "nrows 3", txt, fixed = TRUE) + writeBin(charToRaw(txt), wrapped) + expect_true(.maskAsc(wrapped, list(grid = gridOf(4, 3), cells = c(4L, 5L)))) + expect_identical( + rawToChar(bytesOf(wrapped)), + sub("3 4 5 \r\n", "3 -9999 -9999 \r\n", txt, fixed = TRUE) + ) +}) + +test_that(".maskAsc leaves the file untouched when there is nothing to mask", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 4, 3) + before <- bytesOf(f) + Sys.setFileTime(f, as.POSIXct("2020-01-01", tz = "UTC")) + expect_false(.maskAsc(f, list(grid = gridOf(4, 3), cells = integer(0)))) + expect_identical(bytesOf(f), before) + expect_equal(as.numeric(file.mtime(f)), as.numeric(as.POSIXct("2020-01-01", tz = "UTC"))) +}) + +## a zip is byte-identical only when its files' times are (pipeline_write_zip()), so a masked file +## keeps its time: recutting a tile's zips then gives the same MD5s and nothing to upload +test_that(".maskAsc keeps the file's modification time", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 4, 3) + t0 <- as.POSIXct("2020-01-01 12:34:56", tz = "UTC") + Sys.setFileTime(f, t0) + expect_true(.maskAsc(f, list(grid = gridOf(4, 3), cells = 2L))) + expect_equal(as.numeric(file.mtime(f)), as.numeric(t0)) +}) + +test_that(".maskAsc stops when the file's grid differs from the DEM's", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 4, 3) + expect_error(.maskAsc(f, list(grid = gridOf(5, 3), cells = 1L)), basename(f), fixed = TRUE) + expect_error( + .maskAsc(f, list(grid = gridOf(4, 3, xll = -123.3), cells = 1L)), + basename(f), + fixed = TRUE + ) +}) + +test_that(".maskAsc compares corner coordinates within a tolerance", { + ## 1 arcmin tiles: the header has 12 decimals, the DEM's extent more + f <- writeClimatenaAsc( + withr::local_tempfile(fileext = ".asc"), + as.character(1:12), + 4, + 3, + xll = "-123.333333333333" + ) + expect_true(.maskAsc(f, list(grid = gridOf(4, 3, xll = -123 - 1 / 3), cells = 1L))) +}) + +## zip_batch() masks every grid of a batch's extracted periods before cutting the zips +test_that(".maskAscDir masks every .asc below a folder and nothing else", { + d <- withr::local_tempdir() + dir.create(file.path(d, "Year_2020MSY")) + dir.create(file.path(d, "Year_2021MSY")) + a <- writeClimatenaAsc(file.path(d, "Year_2020MSY", "MAT.asc"), as.character(1:12), 4, 3) + b <- writeClimatenaAsc(file.path(d, "Year_2021MSY", "MAT.asc"), as.character(1:12), 4, 3) + other <- file.path(d, "Year_2021MSY", "notes.txt") + writeLines("1 2 3", other) + want <- writeClimatenaAsc( + withr::local_tempfile(fileext = ".asc"), + replace(as.character(1:12), 2, "-9999"), + 4, + 3 + ) + + expect_identical(.maskAscDir(d, list(grid = gridOf(4, 3), cells = 2L)), 2L) + expect_identical(bytesOf(a), bytesOf(want)) + expect_identical(bytesOf(b), bytesOf(want)) + expect_identical(readLines(other), "1 2 3") +}) + +test_that(".maskAscDir stops when the tile has no mask", { + expect_error(.maskAscDir(withr::local_tempdir(), NULL), "no mask") +}) + +## Land cells ClimateNA leaves empty are filled from its point-mode output: the values are +## written in place of the NODATA text, every other byte left as it was +test_that(".fillAsc writes the given values into NODATA cells, keeping all other bytes", { + tokens <- c("1", "-9999", "3", "-9999") + for (eol in c("\r\n", "\n")) { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), tokens, 2, 2, eol = eol) + want <- writeClimatenaAsc( + withr::local_tempfile(fileext = ".asc"), + c("1", "12", "3", "-7.9"), + 2, + 2, + eol = eol + ) + expect_true(.fillAsc(f, list(grid = gridOf(2, 2), cells = c(4L, 2L), values = c("-7.9", "12")))) + expect_identical(bytesOf(f), bytesOf(want)) + } +}) + +test_that(".fillAsc counts values in order across wrapped lines", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), as.character(1:12), 3, 4) + wrapped <- withr::local_tempfile(fileext = ".asc") + ## 4 x 3 grid written 3 values to a line, with cells 4 and 5 empty + txt <- sub( + "1 2 3 \r\n4 5 6 \r\n", + "1 2 \r\n3 -9999 -9999 \r\n6 ", + rawToChar(bytesOf(f)), + fixed = TRUE + ) + txt <- sub("ncols 3", "ncols 4", txt, fixed = TRUE) + txt <- sub("nrows 4", "nrows 3", txt, fixed = TRUE) + writeBin(charToRaw(txt), wrapped) + expect_true(.fillAsc(wrapped, list(grid = gridOf(4, 3), cells = c(4L, 5L), values = c("4", "5")))) + expect_identical( + rawToChar(bytesOf(wrapped)), + sub("3 -9999 -9999 \r\n", "3 4 5 \r\n", txt, fixed = TRUE) + ) +}) + +test_that(".fillAsc refuses a cell that has a value", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), c("1", "2", "3", "4"), 2, 2) + before <- bytesOf(f) + expect_error( + .fillAsc(f, list(grid = gridOf(2, 2), cells = 2L, values = "5")), + "cell 2 .*not NODATA" + ) + expect_identical(bytesOf(f), before) +}) + +test_that(".fillAsc refuses a -9999 value", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), c("1", "-9999", "3", "4"), 2, 2) + expect_error( + .fillAsc(f, list(grid = gridOf(2, 2), cells = 2L, values = "-9999")), + "no value for cell 2" + ) +}) + +test_that(".fillAsc keeps the file's modification time and does nothing for no cells", { + f <- writeClimatenaAsc(withr::local_tempfile(fileext = ".asc"), c("1", "-9999", "3", "4"), 2, 2) + t0 <- as.POSIXct("2020-01-01 12:34:56", tz = "UTC") + Sys.setFileTime(f, t0) + before <- bytesOf(f) + expect_false(.fillAsc(f, list(grid = gridOf(2, 2), cells = integer(0), values = character(0)))) + expect_identical(bytesOf(f), before) + expect_true(.fillAsc(f, list(grid = gridOf(2, 2), cells = 2L, values = "2"))) + expect_equal(as.numeric(file.mtime(f)), as.numeric(t0)) +}) diff --git a/tests/testthat/test-pipelineSpecs.R b/tests/testthat/test-pipelineSpecs.R new file mode 100644 index 0000000..6796d7f --- /dev/null +++ b/tests/testthat/test-pipelineSpecs.R @@ -0,0 +1,48 @@ +## The pipeline's DEM inputs (data-raw/pipeline/R/specs.R): tile masks are built from the DEM +## files themselves (a `format = "file"` target), so replacing a DEM file rebuilds them. +pipelineEnv <- function() { + d <- test_path("..", "..", "data-raw", "pipeline", "R") + skip_if_not(dir.exists(d), "data-raw/pipeline not available") + e <- new.env() + for (f in c("specs.R", "run_batch.R")) { + sys.source(file.path(d, f), envir = e) + } + e +} + +writeDem <- function(dir, tile, values) { + r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 2, ymin = 0, ymax = 2, crs = "EPSG:4326") + terra::values(r) <- values + f <- file.path(dir, paste0("can_dem_", tile, ".asc")) + terra::writeRaster(r, f, NAflag = -9999, overwrite = TRUE) + f +} + +test_that("pipeline_dem_files names one file per tile and stops on a missing one", { + e <- pipelineEnv() + d <- withr::local_tempdir() + writeDem(d, 1, 1:4) + writeDem(d, 2, 1:4) + f <- e$pipeline_dem_files(d, c(1L, 2L)) + expect_named(f, c("1", "2")) + expect_true(all(file.exists(f))) + expect_error(e$pipeline_dem_files(d, c(1L, 3L)), "no DEM tile.*3") +}) + +test_that("pipeline_tile_masks names each tile's mask and land cells by its DEM file", { + e <- pipelineEnv() + d <- withr::local_tempdir() + ## tile 2: cell 1 has no elevation; Canada covers the left column, so it is kept (not masked) + demFiles <- c("1" = writeDem(d, 1, 1:4), "2" = writeDem(d, 2, c(NA, 2, 3, NA))) + canada <- terra::vect("POLYGON ((0 0, 1 0, 1 2, 0 2, 0 0))", crs = "EPSG:4326") + canadaFile <- file.path(d, "canada.rds") + saveRDS(terra::wrap(canada), canadaFile) + + m <- e$pipeline_tile_masks(canadaFile, demFiles) + expect_named(m, c("1", "2")) + ## a format = "file" target returns its paths without names: tiles come from the file names + expect_named(e$pipeline_tile_masks(canadaFile, unname(demFiles)), c("1", "2")) + expect_identical(m[["1"]]$land, 1:4) + expect_identical(m[["2"]]$land, c(2L, 3L)) + expect_identical(m[["2"]]$cells, 4L) +}) diff --git a/tests/testthat/test-pipelineStamps.R b/tests/testthat/test-pipelineStamps.R new file mode 100644 index 0000000..f81cedf --- /dev/null +++ b/tests/testthat/test-pipelineStamps.R @@ -0,0 +1,58 @@ +## A period counts as done only when its stored zip is complete and its stamp shows a ClimateNA +## version at or above the type's minimum and the same DEM. A period without a stamp, or stored +## only as a folder (the earlier layout), is rerun, not skipped. +test_that(".periodDone needs a complete period zip and a matching stamp", { + skip_if_not_installed("withr") + skip_if_not(nzchar(Sys.which("zip")), "no zip program") + tileDir <- withr::local_tempdir() + folder <- "Year_2025Y" + expected <- file.path(folder, paste0(.allowedClimateVars_Y, ".asc")) + storePeriod <- function(files) { + src <- withr::local_tempdir() + dir.create(file.path(src, folder)) + for (f in files) { + writeLines("1", file.path(src, f)) + } + unlink(.periodZip(tileDir, folder)) + withr::with_dir(src, utils::zip(.periodZip(tileDir, folder), files, flags = "-q")) + } + + storePeriod(expected) + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) # no stamp + .writeStamp(tileDir, folder, "7.70", "abc", "img@sha256:1") + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), TRUE) + expect_identical(.periodDone(tileDir, folder, expected, "7.60", "abc"), TRUE) # made after the minimum + expect_identical(.periodDone(tileDir, folder, expected, "7.80", "abc"), FALSE) # older than the minimum + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "xyz"), FALSE) # other DEM + + storePeriod(expected[-1]) + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) # incomplete + + unlink(.periodZip(tileDir, folder)) + dir.create(file.path(tileDir, folder)) + for (f in expected) { + writeLines("1", file.path(tileDir, f)) + } + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) # folder only + + expect_identical(.readStamp(tileDir, folder)$image, "img@sha256:1") + expect_identical(basename(.periodZip(tileDir, folder)), "Year_2025Y.zip") # sibling of the stamp +}) + +## An error here fails the batch on every run, so a damaged period would never be regenerated. +test_that(".periodDone sends a damaged zip or a cut-short stamp back to be rerun", { + skip_if_not_installed("withr") + tileDir <- withr::local_tempdir() + folder <- "Year_2025Y" + expected <- file.path(folder, paste0(.allowedClimateVars_Y, ".asc")) + .writeStamp(tileDir, folder, "7.70", "abc", "img") + writeBin(as.raw(c(0x50, 0x4b, 0x03, 0x04, 1:40)), .periodZip(tileDir, folder)) # not a zip + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) + + file.create(.stampPath(tileDir, folder)) # empty stamp + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) + writeLines("climatena_vers", .stampPath(tileDir, folder)) # cut mid-line + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) + writeLines("climatena_version: 7.", .stampPath(tileDir, folder)) # not a version + expect_identical(.periodDone(tileDir, folder, expected, "7.70", "abc"), FALSE) +}) diff --git a/tests/testthat/test-pipelineTargets.R b/tests/testthat/test-pipelineTargets.R new file mode 100644 index 0000000..4e27819 --- /dev/null +++ b/tests/testthat/test-pipelineTargets.R @@ -0,0 +1,21 @@ +## The pipeline's target settings (data-raw/pipeline/_targets.R). Needs a checkout with a +## _local.R (gitignored), so it runs only in a pipeline checkout. +test_that("tiles re-lists the DEM folder every run, and the DEM-wide targets stop the run", { + root <- test_path("..", "..") + skip_if_not(file.exists(file.path(root, "data-raw", "pipeline", "_local.R")), "no _local.R") + skip_if_not_installed("targets") + m <- withr::with_dir( + root, + targets::tar_manifest( + script = "data-raw/pipeline/_targets.R", + fields = c("name", "cue_mode", "error") + ) + ) + ## a DEM file added or removed changes neither dem_dir nor the tile subset + expect_identical(m$cue_mode[m$name == "tiles"], "always") + ## nothing downstream works without these; under error = "null" a failure would become one + ## error per branch + for (n in c("dem_files", "tile_masks", "fill_points")) { + expect_identical(m$error[m$name == n], "stop", label = n) + } +}) diff --git a/tests/testthat/test-pipelineUpload.R b/tests/testthat/test-pipelineUpload.R new file mode 100644 index 0000000..d392a58 --- /dev/null +++ b/tests/testthat/test-pipelineUpload.R @@ -0,0 +1,99 @@ +## What upload_zips() does with a zip, given the same-named files already in its release folder: +## reuse one with the same MD5; else, when asked (replace_changed in _local.R), replace a +## differing one in place, so its Drive ID (the index's gid) stays the same; else upload a new +## file. +noFiles <- data.frame(id = character(0), md5 = character(0)) + +test_that(".uploadAction reuses a same-named file with the same MD5", { + there <- data.frame(id = c("a", "b"), md5 = c("x", "y")) + expect_identical(.uploadAction(there, "y"), list(action = "found", id = "b")) +}) + +test_that(".uploadAction uploads a new file when none has the name", { + expect_identical(.uploadAction(noFiles, "y"), list(action = "upload", id = NA_character_)) +}) + +## a shipped release's files change only when the maintainer asks: an accidental recut stops +test_that(".uploadAction stops on a differing same-named file unless asked to replace it", { + expect_error(.uploadAction(data.frame(id = "a", md5 = "x"), "y"), "replace_changed") + expect_error( + .uploadAction(data.frame(id = c("a", "b"), md5 = c("x", "z")), "y", gid = "b"), + "replace_changed" + ) +}) + +test_that(".uploadAction updates the one same-named file in place", { + there <- data.frame(id = "a", md5 = "x") + expect_identical(.uploadAction(there, "y", replace = TRUE), list(action = "update", id = "a")) + expect_identical( + .uploadAction(data.frame(id = "a", md5 = NA_character_), "y", replace = TRUE), + list(action = "update", id = "a") + ) +}) + +test_that(".uploadAction updates the file the index points to when there are several", { + there <- data.frame(id = c("a", "b"), md5 = c("x", "z")) + expect_identical( + .uploadAction(there, "y", gid = "b", replace = TRUE), + list(action = "update", id = "b") + ) +}) + +test_that(".uploadAction stops when several same-named files differ and none is the index's", { + there <- data.frame(id = c("a", "b"), md5 = c("x", "z")) + expect_error(.uploadAction(there, "y"), "a, b") + expect_error(.uploadAction(there, "y", gid = "c"), "a, b") +}) + +## upload_zips() runs on the "uploads" workers, which start without the package, and it calls +## .uploadAction(): it must load the package first, as zip_batch() does. Without it, every +## changed zip's upload failed with "could not find function '.uploadAction'". +test_that("upload_zips loads the package on its worker", { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + loaded <- FALSE + e$pipeline_load <- function() loaded <<- TRUE + out <- e$upload_zips(character(0), list(), list(), dryRun = FALSE, lookup = NULL) + expect_true(loaded) + expect_identical(nrow(out), 0L) +}) + +## a rebuilt zip whose release folder already has a differing file of that name: replaced in +## place (same ID) only with replace_changed; otherwise the upload stops, naming the zip +test_that("upload_zips replaces a changed zip's file only when asked", { + f <- test_path("..", "..", "data-raw", "pipeline", "R", "upload_drive.R") + skip_if_not(file.exists(f), "data-raw/pipeline not available") + e <- new.env() + sys.source(f, envir = e) + rel <- "historical/MSY/6_MSY_2020.zip" + e$pipeline_load <- function() invisible(TRUE) + e$pipeline_zip_relpath <- function(spec, subset) rel + e$pipeline_previous_rows <- function(lookup, spec) { + data.frame(gid = "g1", zipfile = rel, md5 = "old") + } + d <- withr::local_tempdir() + zip <- file.path(d, "MSY", "6_MSY_2020.zip") + dir.create(dirname(zip)) + writeLines("new", zip) + md5 <- unname(tools::md5sum(zip)) + folders <- list(path = file.path(d, "folders.rds")) + saveRDS(c("historical/MSY" = "folder1"), folders$path) + there <- data.frame(name = basename(zip), id = "g1") + there$drive_resource <- list(list(md5Checksum = "old")) + updated <- data.frame(name = basename(zip), id = "g1") + updated$drive_resource <- list(list(md5Checksum = md5, modifiedTime = "2026-11-11T00:00:00Z")) + local_mocked_bindings( + drive_get = function(...) stop("no reusable file"), + drive_ls = function(...) there, + drive_update = function(...) updated, + .package = "googledrive" + ) + + expect_error(e$upload_zips(zip, list(), folders, FALSE, NULL), "6_MSY_2020.zip.*replace_changed") + out <- e$upload_zips(zip, list(), folders, FALSE, NULL, replaceChanged = TRUE) + expect_identical(out$source, "updated") + expect_identical(out$gid, "g1") + expect_identical(out$md5, md5) +}) diff --git a/tests/testthat/test-pipelineWorkers.R b/tests/testthat/test-pipelineWorkers.R new file mode 100644 index 0000000..187cdd7 --- /dev/null +++ b/tests/testthat/test-pipelineWorkers.R @@ -0,0 +1,17 @@ +## The pipeline uses at most half of each node's cores (maintainer, 2026-11-10): ClimateNA workers +## (one CPU each, `--cpus 1`), plus the upload workers and the main process on the controlling node. +## The last 1 arcmin run had 60 workers on a 96-core node, next to another project's. +test_that(".cappedWorkers clamps to half the cores, less those reserved", { + expect_message(n <- .cappedWorkers(60, 96, 9), "39") + expect_identical(n, 39L) +}) + +test_that(".cappedWorkers keeps a request within the cap, silently", { + expect_silent(n <- .cappedWorkers(10, 96, 9)) + expect_identical(n, 10L) +}) + +test_that(".cappedWorkers keeps at least one worker", { + expect_message(n <- .cappedWorkers(4, 4, 3)) + expect_identical(n, 1L) +}) diff --git a/tests/testthat/test-prepClimateLayers.R b/tests/testthat/test-prepClimateLayers.R index 0dcfa71..d16a5d4 100644 --- a/tests/testthat/test-prepClimateLayers.R +++ b/tests/testthat/test-prepClimateLayers.R @@ -43,11 +43,11 @@ test_that("prepClimateLayers works for multiple variable types", { fun = quote(calcAsIs), .dots = list(historical_years = historical_yrs) ), - # future period not supported - # future_CMD_sm_normal = list( - # vars = "future_CMD_sm_normal", - # fun = quote(calcAsIs), - # .dots = list(future_period = future_prd), + future_MAT_normal = list( + vars = "future_MAT_normal", + fun = quote(calcAsIs), + .dots = list(future_period = future_prd) + ), future_FFP = list( vars = "future_FFP", ## ensure FFP only; not bFFP nor eFFP fun = quote(calcAsIs), @@ -58,7 +58,6 @@ test_that("prepClimateLayers works for multiple variable types", { fun = quote(calcMDC), .dots = list(historical_years = historical_yrs) ) - ) ## test with all parallel backends @@ -84,56 +83,63 @@ test_that("prepClimateLayers works for multiple variable types", { expect_s4_class(x, "SpatRaster") }) + ## future normals (new in v3.0.0 data releases): one layer per period, and the periods differ + fn <- climateRasters[[backend]][["future_MAT_normal"]] + expect_equal(terra::nlyr(fn), length(future_prd)) + fn1 <- fn[[1]] + fn2 <- fn[[2]] + names(fn2) <- names(fn1) ## compare values, not layer names + expect_false(isTRUE(terra::all.equal(fn1, fn2))) - #new climate variables + #new climate variables - climateVariables <- list( - historical_PAS_normal = list( - vars = "historical_PAS_normal", ## ensure MAT only; not bMAT nor eMAT - fun = quote(calcAsIs), - .dots = list(historical_period = historical_prd) - ), - historical_CMD_normal = list( - vars = "historical_CMD_normal", ## ensure MAT only; not bFFP nor eFFP - fun = quote(calcAsIs), - .dots = list(historical_period = historical_prd) - ) + climateVariables <- list( + historical_PAS_normal = list( + vars = "historical_PAS_normal", ## ensure MAT only; not bMAT nor eMAT + fun = quote(calcAsIs), + .dots = list(historical_period = historical_prd) + ), + historical_CMD_normal = list( + vars = "historical_CMD_normal", ## ensure MAT only; not bFFP nor eFFP + fun = quote(calcAsIs), + .dots = list(historical_period = historical_prd) ) + ) - climateRasters <- list() - for (backend in .parallelBackends) { - withr::with_options(list(climateData.parallel.backend = backend), { - climateRasters[[backend]] <- prepClimateLayers( - climateVarsList = climateVariables, - srcdir = climatePath, ## 'src' is the place for raw inputs, downloaded from Google Drive - dstdir = climatePathOut, ## 'dst' is the place for intermediate + final outputs - tile = tileIDs, - gcm = GCM, - ssp = SSP, - cl = NULL, - studyArea = NULL, - studyAreaName = NULL, - rasterToMatch = NULL - ) - }) + climateRasters <- list() + for (backend in .parallelBackends) { + withr::with_options(list(climateData.parallel.backend = backend), { + climateRasters[[backend]] <- prepClimateLayers( + climateVarsList = climateVariables, + srcdir = climatePath, ## 'src' is the place for raw inputs, downloaded from Google Drive + dstdir = climatePathOut, ## 'dst' is the place for intermediate + final outputs + tile = tileIDs, + gcm = GCM, + ssp = SSP, + cl = NULL, + studyArea = NULL, + studyAreaName = NULL, + rasterToMatch = NULL + ) + }) - lapply(climateRasters[[backend]], function(x) { - expect_s4_class(x, "SpatRaster") - }) + lapply(climateRasters[[backend]], function(x) { + expect_s4_class(x, "SpatRaster") + }) - ras1a <- climateRasters[[backend]][[1]][[1]] - ras1b <- climateRasters[[backend]][[1]][[2]] - ras2a <- climateRasters[[backend]][[2]][[1]] + ras1a <- climateRasters[[backend]][[1]][[1]] + ras1b <- climateRasters[[backend]][[1]][[2]] + ras2a <- climateRasters[[backend]][[2]][[1]] - #avoid false just because of layer name - names(ras1a) <- names(ras1b) - names(ras2a) <- names(ras1a) + #avoid false just because of layer name + names(ras1a) <- names(ras1b) + names(ras2a) <- names(ras1a) - #check same var diff normal period - expect_false(isTRUE(terra::all.equal(ras1a, ras1b))) - #check diff var same normal period - expect_false(isTRUE(terra::all.equal(ras1a, ras2a))) - } + #check same var diff normal period + expect_false(isTRUE(terra::all.equal(ras1a, ras1b))) + #check diff var same normal period + expect_false(isTRUE(terra::all.equal(ras1a, ras2a))) + } ## now test with studyArea and rasterTaMatch skip_if_not_installed("SpaDES.tools") @@ -219,15 +225,17 @@ test_that("prepClimateLayers properly handles unordered tileIDs", { }) -## Layers cached before maskInvalidPPT() (or before the postProcessTo smoothing fix) kept coming back, -## because the prepClimateLayers() cache key did not change when the builder functions did. +## Layers cached before the zero-PPT mask (or before the postProcessTo smoothing fix) kept coming +## back, because the prepClimateLayers() cache key did not change when the builder functions did. test_that("the prepClimateLayers cache key changes when a layer-building function changes", { env <- new.env() - for (nm in .climateBuilders) assign(nm, function(x) x, envir = env) + for (nm in .climateBuilders) { + assign(nm, function(x) x, envir = env) + } d1 <- climateBuilderDigest(env) expect_identical(d1, climateBuilderDigest(env)) - assign("maskInvalidPPT", function(x) x + 1, envir = env) + assign("calcAsIs", function(x) x + 1, envir = env) expect_false(identical(d1, climateBuilderDigest(env))) ## the real functions are covered diff --git a/tests/testthat/test-sqliteConcurrency.R b/tests/testthat/test-sqliteConcurrency.R index 87c6635..81b2935 100644 --- a/tests/testthat/test-sqliteConcurrency.R +++ b/tests/testthat/test-sqliteConcurrency.R @@ -12,15 +12,21 @@ test_that("parallel latestHistoricalYear() calls on one database do not fail", { ## R CMD check caps forked workers at 2 (_R_CHECK_LIMIT_CORES_) nWorkers <- if (nzchar(Sys.getenv("_R_CHECK_LIMIT_CORES_"))) 2L else 8L - res <- parallel::mclapply(seq_len(nWorkers), function(i) { - t0 <- Sys.time() - out <- character() - while (difftime(Sys.time(), t0, units = "secs") < 10) { - r <- tryCatch(identical(latestHistoricalYear(), expected), error = function(e) conditionMessage(e)) - if (!isTRUE(r)) out <- c(out, as.character(r)) - } - out - }, mc.cores = nWorkers) + res <- parallel::mclapply( + seq_len(nWorkers), + function(i) { + t0 <- Sys.time() + out <- character() + while (difftime(Sys.time(), t0, units = "secs") < 10) { + r <- tryCatch(identical(latestHistoricalYear(), expected), error = function(e) { + conditionMessage(e) + }) + if (!isTRUE(r)) out <- c(out, as.character(r)) + } + out + }, + mc.cores = nWorkers + ) errs <- unlist(res) expect_identical(unique(errs), character(0), info = paste(head(errs, 3), collapse = "; ")) @@ -44,6 +50,24 @@ test_that("a read-only lookup neither writes nor creates tables", { expect_false(DBI::dbExistsTable(con, "future_normals")) }) +test_that("a lookup that fails closes its connection", { + f <- dbCopy() + on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) + con <- DBI::dbConnect(RSQLite::SQLite(), f) + DBI::dbExecute(con, "DROP TABLE future_normals") + DBI::dbDisconnect(con) + + realConnect <- sqlite_connect_db + opened <- NULL + testthat::local_mocked_bindings(sqlite_connect_db = function(...) { + opened <<- realConnect(...) + opened + }) + on.exit(if (!is.null(opened) && DBI::dbIsValid(opened)) DBI::dbDisconnect(opened), add = TRUE) + expect_error(ClimateNA_sql(f, "future_normals", readonly = TRUE)) + expect_false(DBI::dbIsValid(opened)) +}) + test_that("writing connections wait for each other's lock; an immutable read does not", { f <- dbCopy() on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) diff --git a/tests/testthat/test-sqliteReadOnlyNoWrites.R b/tests/testthat/test-sqliteReadOnlyNoWrites.R index 43bdae7..5023d23 100644 --- a/tests/testthat/test-sqliteReadOnlyNoWrites.R +++ b/tests/testthat/test-sqliteReadOnlyNoWrites.R @@ -6,10 +6,11 @@ dbState <- function(f) { size = file.size(f), mtime = file.mtime(f), md5 = unname(tools::md5sum(f))) } +## ordered by `id`, the tile tables' key (the pipeline's index has no `rowid` column) lookup <- function() { dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical", readonly = TRUE) on.exit(DBI::dbDisconnect(dbdf[["db"]]), add = TRUE) - dplyr::collect(dplyr::arrange(dplyr::filter(dbdf[["df"]], tileid <= 20L), rowid)) + dplyr::collect(dplyr::arrange(dplyr::filter(dbdf[["df"]], tileid <= 20L), id)) } test_that("the shipped tile index is not in WAL mode", { diff --git a/vignettes/climateData.Rmd b/vignettes/climateData.Rmd new file mode 100644 index 0000000..b7c3b38 --- /dev/null +++ b/vignettes/climateData.Rmd @@ -0,0 +1,144 @@ +--- +title: "Getting climate data for a study area" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Getting climate data for a study area} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r, include = FALSE} +knitr::opts_chunk$set(collapse = TRUE, comment = "#>") +``` + +climateData gives you [ClimateNA](https://climatena.ca/) climate rasters for a study area in Canada. It covers: +- historical years from 1901 to 2025; +- future years from 2011 to 2100, for several climate models (GCMs) and emissions scenarios (SSPs); +- 30-year climate normals, historical and future. + +The data are prepared in advance as tiles and stored on Google Drive. climateData downloads only the tiles that cover your study area, then gives you rasters cropped, projected and resampled to match a raster of your own. + +The `canClimateData` SpaDES module uses the same functions, so what follows also explains the `climateVariables` it takes. + +## Before you start + +The archives are downloaded with the googledrive package, so you need a Google account: + +```{r, eval = FALSE} +install.packages("climateData", repos = c("https://predictiveecology.r-universe.dev", getOption("repos"))) +googledrive::drive_auth() # once per session (or cache a token) +``` + +## What is available + +```{r} +library(climateData) + +range(available("historical")$years) +available("historical_normals")$periods +available("future")[c("gcms", "ssps")] +available("future_normals")$periods + +## the data release behind this version of the package +climateDataRelease()$release_id +``` + +## Naming climate variables + +Each variable is named `_`, adding `_normal` for a 30-year normal: + +| You want | Example | Notes | +|---|---|---| +| an annual variable | `historical_CMD`, `future_MAT` | | +| a seasonal variable | `historical_CMD_sm` | `_wt` winter, `_sp` spring, `_sm` summer, `_at` autumn | +| a monthly variable | `historical_PPT07`, `future_Tmax04` | months `01` to `12` | +| a normal | `historical_MAT_normal`, `future_CMI_normal` | annual variables only | + +The variables are ClimateNA's; see its [variable list](https://climatena.ca/Help2) for definitions and units. Solar radiation follows ClimateNA v7.60 and later: `rsds`, `rsds_sm`, `rsds07`, and so on (formerly `MAR`, `Rad_sm`, `Rad07`). Asking for an old name stops with a message naming the new one. + +## Describing what you want + +`prepClimateLayers()` takes a named list. Each element is one output layer: +- **`vars`:** the ClimateNA variables it is computed from; +- **`fun`:** a quoted function that computes it; +- **`.dots`:** which years (`historical_years`, `future_years`) or normals periods (`historical_period`, `future_period`) to use. + +```{r, eval = FALSE} +climateVariables <- list( + ## an annual variable, as is + historical_CMI = list( + vars = "historical_CMI", + fun = quote(calcAsIs), + .dots = list(historical_years = 1991:2025) + ), + ## a historical normal + historical_CMI_normal = list( + vars = "historical_CMI_normal", + fun = quote(calcAsIs), + .dots = list(historical_period = "1991_2020") + ), + ## a derived variable: Monthly Drought Code from April-September precipitation and Tmax + future_MDC = list( + vars = c(sprintf("future_PPT%02d", 4:9), sprintf("future_Tmax%02d", 4:9)), + fun = quote(calcMDC), + .dots = list(future_years = 2011:2100) + ), + ## a future normal + future_MAT_normal = list( + vars = "future_MAT_normal", + fun = quote(calcAsIs), + .dots = list(future_period = c("2011_2040", "2041_2070")) + ) +) +``` + +The functions provided are: +- `calcAsIs()`, the variable as it comes; +- `calcMDC()`, a Monthly Drought Code; +- `calcCumMDC()`, a cumulative Monthly Drought Code carried from month to month and year to year. + +`climateLayers()` builds this list for common cases. For example, `climateLayers(c("CMD_sm", "cumMDC"))` covers both historical and projected years. + +## Getting the rasters + +Give a study area (an `sf` or `SpatVector` polygon) and a raster to match. climateData works out which tiles cover the study area, using `whereAmI()`. + +```{r, eval = FALSE} +studyArea <- sf::st_read("my_study_area.gpkg") +rasterToMatch <- terra::rast("my_raster_to_match.tif") + +climateRasters <- prepClimateLayers( + climateVarsList = climateVariables, + srcdir = "climate/inputs", # downloaded archives and extracted files + dstdir = "climate/outputs", # mosaics and the final rasters + gcm = "CanESM5", # for future_ variables + ssp = 370, + studyArea = studyArea, + studyAreaName = "my_study_area", + rasterToMatch = rasterToMatch +) + +names(climateRasters) # one element per entry of climateVariables +climateRasters$historical_CMI # one layer per year +``` + +Instead of a study area and a raster to match, you can pass `tile =` with one or more tile IDs. That gives you whole tiles, unprojected. + +## 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`). + +`filledCells()` lists these cells as points, with where ClimateNA was run for each, so you can map them or leave them out: + +```{r, eval = FALSE} +fc <- filledCells(studyArea = studyArea) +table(fc$class, fc$filled) # class: "historical" or "future" archives +``` + +## Downloads and caching + +- **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. +- **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 new file mode 100644 index 0000000..e385684 --- /dev/null +++ b/vignettes/maintaining-climate-data.Rmd @@ -0,0 +1,218 @@ +--- +title: "Maintaining the climate data" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Maintaining the climate data} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r, include = FALSE} +knitr::opts_chunk$set(collapse = TRUE, comment = "#>", eval = FALSE) +``` + +This vignette is for the package's maintainers and developers. It explains how the climate data that climateData serves are built and published, and how to add a year or a climate scenario. + +## What a data release is + +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 on Google Drive: 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 a Drive file ID. + +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. + +A [targets](https://docs.ropensci.org/targets/) pipeline in `data-raw/pipeline/` builds a release: + +1. it runs ClimateNA for every tile and year or period, in a Docker container, and checks each output folder; +2. it cuts the four subset zips for each tile and decade from the `MSY` output, and checks each zip; +3. it uploads the zips to Drive, MD5-verified, reusing the previous release's file for any zip that hasn't changed; +4. it writes the tile index for the release and a report of anything that failed. + +targets records what has been built, so a rerun does only what is missing, failed or changed. + +## What you need + +- A Linux compute node with Docker, where your account can run `docker` without `sudo`. +- R with targets, tarchetypes, crew, yaml, devtools, googledrive, digest, DBI and RSQLite, and a checkout of this package. Run the pipeline from the package root: every R process loads the package from there with `devtools::load_all()`. +- The `zip` program, which writes the archives so that a rebuilt zip of unchanged outputs is byte-identical (and so keeps matching the previous release's file). +- ClimateNA, unpacked onto a shared directory (see below). +- The DEM tiles, `can_dem_.asc`, with Windows line endings (`makeClimateDEM()`, `rewrite_asc()`). +- Write access to the Drive folder that holds the archives, for real uploads. + +## The ClimateNA image + +ClimateNA is a 32-bit Windows program. The pipeline runs it under Wine in a Docker image that GitHub Actions builds from `docker/climatena/` and publishes as `ghcr.io/predictiveecology/climatena-wine`. Pull it on every node that will run ClimateNA: + +```sh +docker pull ghcr.io/predictiveecology/climatena-wine:latest +``` + +or build it locally: + +```sh +docker build -t climatena-wine docker/climatena +``` + +The image's Wine prefix belongs to uid/gid 1000, and containers must run as that user (`uid` and `gid` in `_local.R`). If your uid differs, build with `--build-arg UID=... --build-arg GID=...`. A container run as another user stops with exit code 64. + +ClimateNA itself is not in the image, because its download requires registration. Each run mounts an unpacked ClimateNA directory read-only. `docker/climatena/README.md` shows how to run a single job by hand, which is useful for testing a new ClimateNA version. + +## Unpacking ClimateNA + +Download each ClimateNA release from [climatena.ca](https://climatena.ca/) and unzip it once into its own directory on a filesystem every node can read, for example `/path/to/ClimateNA_v7.70/`. The directory holds the executable (`ClimateNA_v7.70.exe`) and its data folders (`GCMdat`, `Perioddat`, `prismdat`, ...). Keep old versions: the compatibility check below compares a new version with the outputs of the old one. + +## Settings: `release.yml` and `_local.R` + +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 Drive folder (`drive_parent`). +- `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 Drive account (`drive_email`), `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. + +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. + +The DEM tiles have no elevation for some cells (`nan`), and ClimateNA writes values there anyway, computed at the wrong elevation. When the zips are cut, those cells are set to NODATA unless their centre lies in Canada (GADM 4.1, level 0, holes filled, downloaded once to `/boundary/`). The stored raw outputs keep ClimateNA's values, and a masked file keeps its modification time, so a zip rebuilt from the same outputs is byte-identical. The masking code is in the package (`R/pipelineMask.R`), which targets does not track: after changing it, rerun the zips with `targets::tar_invalidate(tidyselect::starts_with("zips_"))`. + +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 Drive files. + +## Where it runs + +`workers` in `_local.R` sets how many ClimateNA runs go at once on the main node. Each run is a single-threaded container limited to 1 CPU and 1 GB. The pipeline uses at most half of each node's cores: on the main node, `workers` is lowered (with a message) to half the cores less the upload workers and the main process. + +```r +workers = 60L +``` + +Across several machines, use [crew.ssh](https://github.com/FOR-CAST/crew.ssh) instead; each node's count is lowered to half its cores. Don't list the main node there: its uploads and main process are not counted. + +```r +ssh_nodes = c(node1 = 60L, node2 = 90L), # host name = workers on that host +projdir = "/path/to/climateData" # the package checkout, at the same path on every node +``` + +The older `controller` setting is no longer read: the pipeline stops and asks for `workers`. + +With several nodes, the package checkout, ClimateNA, the DEM tiles and `out_root` must be at the same paths on every node (a shared filesystem), and every node needs Docker and the image. + +Uploads always run on the main node, where the Drive token is: in parallel on a separate set of local workers (`upload_workers`, 8 by default), after the main process has created the release's Drive folders. The index is built in the main process. + +## Running the pipeline + +Start with a dry run (`dry_run = TRUE`, the default): it builds everything except the uploads, and writes an index whose Drive IDs are missing (or are the previous release's, for unchanged zips). A dry run on one tile (`tiles = 39L`) is a quick check of a new setup. + +From the package root on the main node, start the run as its own systemd unit, so it survives the end of your session and is easy to stop: + +```sh +systemd-run --user --unit=cna-release --same-dir \ + -p StandardOutput=file:/path/to/out_root/tar_make.log -p StandardError=inherit \ + Rscript -e 'targets::tar_make(script = "data-raw/pipeline/_targets.R", + store = "/path/to/out_root/_targets", reporter = "timestamp")' +``` + +(Your account needs lingering enabled for the unit to outlive your login: `loginctl show-user $USER -p Linger`.) Follow it with `tail -f /path/to/out_root/tar_make.log`, or in R: + +```r +targets::tar_progress_summary(store = "/path/to/out_root/_targets") +``` + +To stop it, run `systemctl --user stop cna-release`. Containers belong to the Docker daemon rather than the unit, so check for any left running afterwards with `docker ps --filter name=cna-`: the pipeline names its containers `cna--`. + +ClimateNA takes about 45 seconds per tile and year at 3 arcmin, so a decade batch takes about 8 minutes, and a full 3 arcmin release about 1,000 CPU-hours. + +## Checking a run + +When a run ends, read `report.csv` in `out_root`. It is empty when everything was built and uploaded. Otherwise it lists: + +- every error and warning that targets recorded, with the target that raised it; +- every zip that is missing from the release, because its batch, zip or upload failed. + +The same errors are in the targets metadata: + +```r +m <- targets::tar_meta(fields = c(error, warnings), store = "/path/to/out_root/_targets") +m[!is.na(m$error) | !is.na(m$warnings), ] +``` + +Common errors: + +- `ClimateNA failed or wrote incomplete output for : `: the run crashed, timed out (`run_timeout`), or left files missing. The container log is in `out_root/logs/.log`. That batch's zips are not cut. +- `ClimateNA changes outputs`: see "Adding a year" below. +- `MD5 mismatch after uploading ...`: the upload was corrupted; rerunning uploads the zip again. + +Fix the cause and run `tar_make()` again. Only what failed reruns. Every run also re-checks each batch's output folders, so a deleted or damaged folder is found and rerun. + +## Adding a year + +Each new year of data comes with a new ClimateNA release. + +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. +3. In `R/available.R`, extend the historical years in `available()`. +4. Run the pipeline as above (dry run first). + +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: + +- **compatible** (the same files, at most 1 in 100,000 cells differ, and none by more than 1): the stored outputs are kept, only the new year runs, and only the zips for the decade that gained the year are cut and uploaded. Every other zip reuses the previous release's Drive file. +- **changed**: the pipeline stops with a message naming the type. If the differences are real, regenerate that type: set its `min_version` to the new version in `release.yml` and run again. Every period of that type is then rerun with the new ClimateNA, and all its zips are uploaded as new files. + +## 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. + +## Uploading + +Set `dry_run = FALSE` in `_local.R` for the real run. Uploads use your Google account's OAuth token: authenticate once, interactively, on the main node with `googledrive::drive_auth()`, and set `drive_email = "you@example.org"` in `_local.R` so the pipeline finds the cached token. + +Each zip is, in order of preference: + +- **reused**: the previous release's index (`previous_index`; by default the index shipped in the package checkout) has the identical zip (same path and MD5), and its Drive file still exists; +- **found**: the release folder already has the file, from an interrupted run; +- **updated**: the release folder has a file of that name with another MD5, because the zip was rebuilt (as for the mask in #40). Only with `replace_changed = TRUE` in `_local.R`: the file's content is replaced in place and MD5-checked, and its Drive ID stays the same, so the index still points to it. Without it, the upload stops with an error naming the zip; +- **uploaded** as a new file and MD5-checked. + +The pipeline never deletes a file on Drive, and it replaces one only in the release's own folder and only when you set `replace_changed`, so the indexes of older package versions keep working. Set it for the one run that needs it, then back to `FALSE`. Drive keeps a replaced file's previous content as an older revision for a while. + +## The release folder on Drive + +New files go into a folder for the release inside the archive folder (`drive_parent`): + +``` +//[/_ssp]// +``` + +for example `cna-v7.70-3arcmin/future/CanESM5_ssp245/MSY/39_CanESM5_245_MSY_2050.zip`. The index's `zipfile` column holds the path below the release folder. A release folder holds only the zips that release uploaded; reused zips stay in the folder of the release that first uploaded them. Don't delete an old release's folder while any shipped index still points into it. + +## Shipping a release + +1. Audit the release (below). +2. Copy the index into the package: + + ```r + file.copy("/path/to/out_root/ClimateNA_tiles.sqlite", "inst/extdata/ClimateNA_tiles.sqlite", + overwrite = TRUE) + climateDataRelease() # after devtools::load_all(): shows the new release_id + ``` + +3. Update `available()` if you haven't, add a `NEWS.md` entry, and bump the version. +4. Run `devtools::test()` and `devtools::check()` on a compute node, then open a pull request into `development`. +5. Once it is released, update the modules that depend on the data (e.g. canClimateData's version requirement). + +The copied index becomes the next release's `previous_index`. + +## Auditing a release + +`data-raw/04-audit_archives.R` checks the published archives independently of the pipeline. For every zip in an index, it checks that the file on Drive holds every year or period folder the index claims, with every variable file present and non-empty, downloading the Drive copy when the local zip differs from it. It writes its findings (`zips.csv`, `report.csv`, `summary.md`) and changes nothing. Audit a release's index before copying it into the package. From the package root, on the main node: + +```r +googledrive::drive_auth(email = "you@example.org") +auditIndex <- "/path/to/out_root/ClimateNA_tiles.sqlite" +auditZipRoot <- "/path/to/out_root/zips" +auditDriveFolders <- list(release = "") +auditDir <- file.path("/path/to/out_root/_audit", format(Sys.Date())) +auditTypes <- c("historical", "historical_normals", "future", "future_normals") +source("data-raw/04-audit_archives.R") +``` + +Zips that the release reused from an earlier release are outside its folder; the script looks those up by their Drive IDs. Every zip should come out complete; any that doesn't is classed `rerun_pipeline`.