From 59b51e7d6663333ea7f00d60dd204a9b8a447c4f Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Tue, 29 Sep 2026 09:46:50 -0700 Subject: [PATCH 1/9] feat(createSSURGO): add MUKEY rasterization with multi-grid alignment and COG output docs(createSSURGO): document named raster grids chore: exclude local planning artifacts fix(createSSURGO): preserve raster grid through output refactor(createSSURGO): centralize raster helpers test(createSSURGO): cover named raster grids docs(createSSURGO): describe raster NoData encoding fix(createSSURGO): accept default grid choices fix(createSSURGO): keep raster options scoped fix(createSSURGO): apply selected raster resolutions feat(createSSURGO): warn on coarse SSURGO MUKEY grids refactor(createSSURGO): centralize grid alignment choices refactor(createSSURGO): reuse grid origin helper fix(createSSURGO): detect fiscal year from sacatlog export feat(createSSURGO): separate raster resolution from alignment Delete TODO.md --- NEWS.md | 5 +- R/createSSURGO.R | 846 ++++++++++++++++++++++++++++- man/createSSURGO.Rd | 50 ++ tests/testthat/test-createSSURGO.R | 813 ++++++++++++++++++++++++++- 4 files changed, 1706 insertions(+), 8 deletions(-) diff --git a/NEWS.md b/NEWS.md index db59e67a..6e62e21b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,6 +1,9 @@ # soilDB 2.9.4 (2026-11-12) - SoilWeb Web Coverage Service specifications for `mukey.wcs()`, `issr800.wcs()`, and `soilColor.wcs()` now are available as JSON rather than hard-coded - + - `createSSURGO()` can optionally create MUKEY GeoTIFF rasters with `include_raster = TRUE`. `resolution_m` accepts any cell size (10 m by default); `template` can supply a custom `SpatRaster` grid; and `grid_alignment` accepts `"gssurgo"` (default), `"target_aligned"`, or `"nlcd"` when no template is supplied. + - `touches` controls whether rasterization includes every cell touched by polygon boundaries or only cells whose centers fall within polygons. + - `fiscal_year` labels the raster cache (otherwise inferred from the SSURGO catalog), `areasymbols` limits processing to selected survey areas, and `LAPPLY.FUN`/`LAPPLY.FUN.ARGS` customize iteration for rasterization. + # soilDB 2.9.3 (2026-09-17) - `createSSURGO()` fix bug in logical column handling (introduced in 2.9.2) due to metadata column type enforcement (#483) - Fix `structure()` usage of special argument names (.Label, .Names) in test fixtures for R-devel (#484) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index 58d2d965..300cc1c1 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -252,6 +252,17 @@ downloadSSURGO <- function(WHERE = NULL, #' you encounter issues using specific DBI connection types, please report in the soilDB issue #' tracker. #' +#' When `include_raster=TRUE`, common resolutions include 10m, 30m, 300m, and 900m; any positive +#' resolution can be requested. Custom `SpatRaster` templates can be supplied for arbitrary grids. +#' The alignment modes are +#' intentional: `gssurgo` matches official USDA-NRCS products, `target_aligned` follows +#' zero-origin GDAL-style alignment, and `nlcd` uses the canonical WGS84 Albers origin. These +#' choices support interoperability with federal raster products including NLCD, CDL, USGS 3DEP, +#' and gNATSGO. Raster output uses `NAflag = 0`; MUKEY zero is reserved as NoData. +#' +#' A single SSURGO MUKEY per cell may be misleading at resolutions greater than 90 meters. +#' A warning is issued for recognized SSURGO area symbols when the output grid exceeds this resolution. +#' #' @param filename _character_. Output file name (e.g. `'db.sqlite'` or `'db.gpkg'`). Only used when #' `con` is not specified by the user. #' @param exdir _character_. Path containing input SSURGO spatial (.shp) and tabular @@ -271,6 +282,17 @@ downloadSSURGO <- function(WHERE = NULL, #' "muaggatt")` writes only the `mapunit` and `muaggatt` tables. Note that special feature #' descriptions are stored in table `"featdesc"` and metadata for each soil survey area are stored #' in `"soil_metadata"` tables. +#' @param include_raster _logical_. Generate MUKEY GeoTIFF rasters for each SSA? +#' Default: `FALSE` does not create raster outputs. Set to `TRUE` to create georeferenced rasters cached in +#' `soilDB_user_dir("cache", "WSS", ...)` and output a combined/copied raster matching `filename`. +#' Requires `terra` package. +#' @param LAPPLY.FUN _function_. `lapply()`-like function to use for iteration during rasterization +#' phase. Only used if `include_raster=TRUE`. This allows for the rasterization operations to be run +#' in parallel instead of sequential, custom progress reporting, or similar. +#' @param LAPPLY.FUN.ARGS _list_. Optional list of additional arguments to pass to `LAPPLY.FUN`. +#' @param fiscal_year _character_. Optional fiscal year label for cache organization (e.g., `'FY2024'`, +#' `'FY26'`). If `NULL`, auto-detect from sacatalog saverest date. Allows organizing rasters by official +#' release year or custom labels. Only used if `include_raster=TRUE`. #' @param dissolve_field _character_. Dissolve geometries to create MULTIPOLYGON features? Column #' name specified is the grouping variable. Default: `NULL` does no aggregation, giving 1 #' `POLYGON` feature per delineation. `"mukey"` aggregates all related delineations within a soil @@ -283,6 +305,18 @@ downloadSSURGO <- function(WHERE = NULL, #' @param sep _character_. Passed to `data.table::fread()`. Default: `"|"` #' @param na.strings _character_. Passed to `data.table::fread()`. Default: `c("", "NA")` #' @param quote _character_. Passed to `data.table::fread()`. Default: `""` +#' @param template Optional `SpatRaster` template to align with. If `NULL` (default), creates a standard +#' grid at `resolution_m` in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, +#' EPSG:32161 for PR/VI, EPSG:4326 for Pacific Islands) with bounds snapped according to `grid_alignment`. +#' @param touches _logical_. If `TRUE`, all cells touched by polygon boundaries are rasterized. Default +#' `FALSE` rasterizes only cells whose centroids fall within polygons. +#' @param grid_alignment _character_. Grid alignment mode when `template = NULL`. Use +#' `"gssurgo"` (default), `"target_aligned"`, or `"nlcd"`. The GSSURGO mode uses a +#' half-cell origin matching official USDA-NRCS products; +#' target-aligned uses a zero origin; and NLCD uses the canonical WGS84 Albers +#' origin anchor `(-2415585, 3314805)`. A supplied `template` takes precedence. +#' @param resolution_m _numeric_. Finite positive raster cell size in meters when `template = NULL` +#' (default: `10`). #' @param quiet _logical_. Suppress messages and other output from database read/write operations? #' @param areasymbols _character_. Optional character vector of soil survey area symbols (e.g. `c("CA067", "CA077")`) used to subset the folders/files within `exdir` to process. Default `NULL` processes all SSURGO exports found in `exdir`. #' @param ... Additional arguments passed to `sf::write_sf()` for writing spatial layers. @@ -303,6 +337,9 @@ createSSURGO <- function(filename = NULL, pattern = NULL, include_spatial = TRUE, include_tabular = TRUE, + include_raster = FALSE, + LAPPLY.FUN = lapply, + LAPPLY.FUN.ARGS = NULL, dissolve_field = NULL, maxruledepth = 0, overwrite = FALSE, @@ -311,10 +348,22 @@ createSSURGO <- function(filename = NULL, sep = "|", na.strings = c("", "NA"), quote = "", + fiscal_year = NULL, + template = NULL, + touches = FALSE, + grid_alignment = c("gssurgo", "target_aligned", "nlcd"), + resolution_m = 10, quiet = TRUE, areasymbols = NULL, ...) { + grid_alignment <- .normalize_grid_alignment(grid_alignment) + if (!is.numeric(resolution_m) || is.complex(resolution_m) || + length(resolution_m) != 1L || is.na(resolution_m) || + !is.finite(resolution_m) || resolution_m <= 0) { + stop("`resolution_m` must be a single finite positive number.", call. = FALSE) + } + if ((missing(filename) || length(filename) == 0) && missing(conn)) { stop("`filename` should be a path to a .gpkg or .sqlite file to create or append to, or a DBIConnection should be provided via `conn`.") } @@ -367,6 +416,14 @@ createSSURGO <- function(filename = NULL, ) } + # Validate terra package availability for rasterization + if (isTRUE(include_raster)) { + if (!requireNamespace("terra", quietly = TRUE)) { + stop("package 'terra' is required for include_raster=TRUE. ", + "Install it with: install.packages('terra')", + call. = FALSE) + } + } if (missing(conn) || is.null(conn)) { # delete existing file if overwrite=TRUE; does _not_ apply to DBIConnection if (file.exists(filename)) { @@ -384,7 +441,7 @@ createSSURGO <- function(filename = NULL, if (inherits(conn, 'DBIConnection')) { filename <- DBI::dbGetInfo(conn)$dbname } - + # DuckDB has special spatial format, so it gets custom handling for IS_DUCKDB <- inherits(conn, "duckdb_connection") @@ -395,8 +452,11 @@ createSSURGO <- function(filename = NULL, } } - if (!IS_DUCKDB && !requireNamespace("sf")) { - stop("package `sf` is required to write spatial datasets to DBI data sources", call. = FALSE) + if ((!IS_DUCKDB && isTRUE(include_spatial)) || + isTRUE(include_raster)) { + if (!requireNamespace("sf", quietly = TRUE)) { + stop("package `sf` is required for spatial output or rasterization", call. = FALSE) + } } layer_names <- .get_spatial_layer_names() @@ -431,13 +491,14 @@ createSSURGO <- function(filename = NULL, " Tabular: ", paste0(include_tabular, collapse = ", ") ) } - + f_inventory <- f[fdx] # initialize timing records for this run (collected locally and attached to result) write_timings <- list() + raster_paths <- list() zero_time <- Sys.time() - + inv <- .inventory_ssurgo_files( files = f_inventory, layer_names = layer_names, @@ -578,6 +639,128 @@ createSSURGO <- function(filename = NULL, } } + # Derive fiscal year from sacatalog if not provided by user + derived_fiscal_year <- fiscal_year + if (isTRUE(include_raster) && is.null(fiscal_year)) { + # Try to extract fiscal year from sacatalog table in extracted SSURGO files + derived_fiscal_year <- .derive_fiscal_year_from_sacatalog(inv$f.txt.grp, exdir, sep, quote, na.strings, header) + + # If derivation failed, error and inform user + if (is.na(derived_fiscal_year)) { + stop("Could not auto-detect fiscal_year from sacatalog. ", + "Please specify fiscal_year explicitly (e.g., fiscal_year='FY2024')", + call. = FALSE) + } + } + + # Rasterize mupolygon to MUKEY raster (parallelized by SSA if include_raster=TRUE) + if (isTRUE(include_raster) && !is.null(inv$shp.grp) && nrow(inv$shp.grp) >= 1) { + + # Extract unique SSA directories from mupolygon shapefiles + mu_idx <- which(inv$shp.grp[, 1] == "mu" & inv$shp.grp[, 2] == "a") + + if (length(mu_idx) > 0) { + # Get mupolygon shapefiles (feature "mu", geometry "a") directly from inventory + mu_files <- inv$f.shp[mu_idx] + + # Extract unique SSA directories and areasymbols + ssa_dirs <- unique(dirname(mu_files)) + ssa_list <- lapply(ssa_dirs, function(d) { + # Extract areasymbol from directory or filename + mu_file <- mu_files[dirname(mu_files) == d][1] + areasymbol <- .areasymbol_from_mupolygon_file(mu_file) + list(ssa_dir = d, areasymbol = areasymbol, fiscal_year = derived_fiscal_year) + }) + + warning_resolution_m <- .ssurgo_raster_resolution_m(template, resolution_m) + .warn_if_coarse_ssurgo_raster( + vapply(ssa_list, `[[`, character(1), "areasymbol"), + warning_resolution_m + ) + + # Define rasterization worker function for namespace isolation + # Captures ssa_list and quiet from enclosing scope + .RASTERIZE.FUN <- function(ssa_index) { + if (ssa_index > length(ssa_list)) { + return(list()) + } + + ssa_info <- ssa_list[[ssa_index]] + ssa_dir <- ssa_info$ssa_dir + areasymbol <- ssa_info$areasymbol + fiscal_year_arg <- ssa_info$fiscal_year + + # Explicitly fetch internal functions from namespace for worker isolation + .rasterize_fn <- get(".rasterize_ssurgo_ssa", envir = asNamespace("soilDB")) + .write_raster_fn <- get(".write_raster_with_cache", envir = asNamespace("soilDB")) + + # Call rasterization helper + mukey_raster <- .rasterize_fn( + ssa_dir = ssa_dir, + areasymbol = areasymbol, + template = template, + touches = touches, + grid_alignment = grid_alignment, + quiet = quiet, + resolution_m = resolution_m + ) + + # Write raster to cache if rasterization succeeded + if (!is.null(mukey_raster)) { + raster_path <- .write_raster_fn( + raster_obj = mukey_raster, + areasymbol = areasymbol, + fiscal_year = fiscal_year_arg, + cache_root = NULL, + resolution_m = resolution_m, + quiet = quiet + ) + + if (!is.na(raster_path)) { + return(list(list( + areasymbol = areasymbol, + path = raster_path + ))) + } + } + list() + } + + # Compute the unified vector extent before rasterization so final output + # is cropped to the same snapped geometry bounds as the SSA templates. + target_bbox <- .compute_ssa_vector_bbox( + mu_files = mu_files, + ssa_list = ssa_list, + template = template, + grid_alignment = grid_alignment, + resolution_m = resolution_m + ) + + # Execute rasterization in parallel or sequential mode + raster_results <- do.call(LAPPLY.FUN, c(list(seq_along(ssa_list), .RASTERIZE.FUN), LAPPLY.FUN.ARGS)) + + # Accumulate results into raster_paths (vectorized: filter empty lists and unlist one level) + raster_paths <- c(raster_paths, unlist(Filter(length, raster_results), recursive = FALSE)) + + # If filename or conn was provided, write/merge final output raster + final_raster_path <- .create_final_raster_output( + raster_paths = raster_paths, + filename = filename, + conn = conn, + exdir = exdir, + target_bbox = target_bbox, + template = template, + grid_alignment = grid_alignment, + resolution_m = resolution_m, + overwrite = overwrite, + quiet = quiet + ) + if (!is.null(final_raster_path) && !is.na(final_raster_path)) { + attr(raster_paths, "output_raster") <- final_raster_path + } + } + } + if (IS_GPKG) { if (!requireNamespace("RSQLite")) { @@ -791,6 +974,20 @@ createSSURGO <- function(filename = NULL, attr(res, 'write_timings') <- timings_df } + # attach raster cache paths as attribute for programmatic access + if (length(raster_paths) > 0) { + raster_paths_df <- do.call(rbind, lapply(raster_paths, function(r) + data.frame( + areasymbol = r$areasymbol, + path = r$path, + stringsAsFactors = FALSE + ))) + if (!is.null(attr(raster_paths, "output_raster"))) { + attr(raster_paths_df, "output_raster") <- attr(raster_paths, "output_raster") + } + attr(res, 'raster_paths') <- raster_paths_df + } + invisible(res) } @@ -810,7 +1007,7 @@ createSSURGO <- function(filename = NULL, f.shp <- files[grepl(".*\\.shp$", files)] shp.grp <- do.call('rbind', strsplit( gsub( - ".*soil([musfa]{2})_([apl])_([a-z]{2}\\d{3}|[a-z]{2})\\.shp", + ".*soil([musfa]{2})_([apl])_([a-z]{2}\\d{3}|mxnl\\d{3}|[a-z]{2})\\.shp", "\\1;\\2;\\3", f.shp ), @@ -1279,3 +1476,640 @@ createSSURGO <- function(filename = NULL, RSQLite::dbExecute(con, q) } else return(1) } + +#' @noRd +#' @keywords internal +.grid_alignment_choices <- function() { + c("gssurgo", "target_aligned", "nlcd") +} + +.normalize_grid_alignment <- function(grid_alignment) { + match.arg(grid_alignment[1], .grid_alignment_choices()) +} + +.grid_origin <- function(grid_alignment, resolution_m) { + if (grid_alignment == "nlcd") { + c(-2415585, 3314805) + } else if (grid_alignment == "gssurgo") { + c(resolution_m / 2, resolution_m / 2) + } else { + c(0, 0) + } +} + +.write_cog_raster <- function(raster_obj, filename) { + terra::writeRaster( + raster_obj, + filename, + overwrite = TRUE, + datatype = "INT4U", + NAflag = 0, + filetype = "COG", + gdal = c("COMPRESS=DEFLATE", "TILED=YES", "BIGTIFF=IF_SAFER") + ) +} +#' Resolve Standard CRS for Soil Survey Area +#' +#' @param areasymbol Soil survey area symbol or state code (e.g. "CA067", "AK650", "HI") +#' @param grid_alignment Grid alignment mode (e.g. "gssurgo", "nlcd") +#' @return Character CRS identifier (e.g. "EPSG:5070", "EPSG:3338", or PROJ string) +#' @noRd +#' @keywords internal +.resolve_ssa_crs <- function(areasymbol = NULL, grid_alignment = "gssurgo") { + if (identical(grid_alignment, "nlcd")) { + return("+proj=aea +lat_0=23 +lon_0=-96 +lat_1=29.5 +lat_2=45.5 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") + } + + if (!is.null(areasymbol) && length(areasymbol) > 0 && nchar(areasymbol[1]) >= 2) { + prefix <- toupper(substr(areasymbol[1], 1, 2)) + if (prefix == "AK") { + return("EPSG:3338") + } else if (prefix == "HI") { + return("EPSG:6628") + } else if (prefix %in% c("PR", "VI")) { + return("EPSG:32161") + } else if (prefix %in% c("AS", "GU", "MP", "PW", "FM", "MH")) { + return("EPSG:4326") + } + } + "EPSG:5070" +} + +#' @noRd +#' @keywords internal +.compute_ssa_vector_bbox <- function(mu_files, ssa_list, + template = NULL, + grid_alignment = c("gssurgo", "target_aligned", "nlcd"), + resolution_m = 10) { + stopifnot(requireNamespace("sf", quietly = TRUE)) + + grid_alignment <- .normalize_grid_alignment(grid_alignment) + + if (length(mu_files) == 0 || length(ssa_list) == 0) { + return(NULL) + } + + first_crs <- if (inherits(template, "SpatRaster")) { + terra::crs(template) + } else { + .resolve_ssa_crs(ssa_list[[1]]$areasymbol, grid_alignment = grid_alignment) + } + bounds <- lapply(seq_along(mu_files), function(i) { + mu <- sf::read_sf(mu_files[[i]], quiet = TRUE) + if (nrow(mu) == 0) { + return(NULL) + } + mu <- sf::st_transform(mu, first_crs) + sf::st_bbox(mu) + }) + bounds <- Filter(Negate(is.null), bounds) + if (length(bounds) == 0) { + return(NULL) + } + + xmin <- min(vapply(bounds, function(x) x[["xmin"]], numeric(1))) + xmax <- max(vapply(bounds, function(x) x[["xmax"]], numeric(1))) + ymin <- min(vapply(bounds, function(x) x[["ymin"]], numeric(1))) + ymax <- max(vapply(bounds, function(x) x[["ymax"]], numeric(1))) + + origin <- if (inherits(template, "SpatRaster")) { + terra::origin(template) + } else { + .grid_origin(grid_alignment, resolution_m) + } + + .snap_extent_to_grid( + xmin, xmax, ymin, ymax, + origin = origin, + resolution = c(resolution_m, resolution_m) + ) +} + +#' @noRd +#' @keywords internal +.snap_extent_to_grid <- function(xmin, xmax, ymin, ymax, + origin = c(0, 0), + resolution = c(1, 1)) { + c( + xmin = as.numeric(origin[1] + floor((xmin - origin[1]) / resolution[1]) * resolution[1]), + xmax = as.numeric(origin[1] + ceiling((xmax - origin[1]) / resolution[1]) * resolution[1]), + ymin = as.numeric(origin[2] + floor((ymin - origin[2]) / resolution[2]) * resolution[2]), + ymax = as.numeric(origin[2] + ceiling((ymax - origin[2]) / resolution[2]) * resolution[2]) + ) +} + +#' Create SpatRaster Template for Soil Survey Area +#' +#' @param mu_shp sf object containing map unit polygons +#' @param template Optional SpatRaster template to align with +#' @param areasymbol Soil survey area symbol (e.g. "CA067") +#' @param resolution_m Resolution in meters (default: 10) +#' @param buffer_m Buffer in meters added around bbox before snapping (default: 0) +#' @param grid_alignment Grid alignment mode: `"gssurgo"` (default), `"target_aligned"`, or `"nlcd"` +#' @return SpatRaster template covering the SSA extent snapped to grid +#' @noRd +#' @keywords internal +.create_ssa_raster_template <- function(mu_shp, template = NULL, areasymbol = NULL, + resolution_m = 10, buffer_m = 0, + grid_alignment = c("gssurgo", "target_aligned", "nlcd")) { + stopifnot(requireNamespace("sf", quietly = TRUE)) + stopifnot(requireNamespace("terra", quietly = TRUE)) + + grid_alignment <- .normalize_grid_alignment(grid_alignment) + + if (inherits(template, "SpatRaster")) { + target_crs <- terra::crs(template) + mu_proj <- sf::st_transform(mu_shp, target_crs) + extent_bbox <- sf::st_bbox(mu_proj) + + xmin <- extent_bbox[["xmin"]] - buffer_m + xmax <- extent_bbox[["xmax"]] + buffer_m + ymin <- extent_bbox[["ymin"]] - buffer_m + ymax <- extent_bbox[["ymax"]] + buffer_m + + t_res <- terra::res(template) + t_origin <- terra::origin(template) + + snapped <- .snap_extent_to_grid(xmin, xmax, ymin, ymax, origin = t_origin, resolution = t_res) + xmin_snap <- snapped[["xmin"]] + xmax_snap <- snapped[["xmax"]] + ymin_snap <- snapped[["ymin"]] + ymax_snap <- snapped[["ymax"]] + + terra::rast( + xmin = xmin_snap, + xmax = xmax_snap, + ymin = ymin_snap, + ymax = ymax_snap, + resolution = t_res, + crs = target_crs + ) + } else { + target_crs <- .resolve_ssa_crs(areasymbol, grid_alignment = grid_alignment) + mu_proj <- sf::st_transform(mu_shp, target_crs) + extent_bbox <- sf::st_bbox(mu_proj) + + xmin <- extent_bbox[["xmin"]] - buffer_m + xmax <- extent_bbox[["xmax"]] + buffer_m + ymin <- extent_bbox[["ymin"]] - buffer_m + ymax <- extent_bbox[["ymax"]] + buffer_m + + origin <- .grid_origin(grid_alignment, resolution_m) + + snapped <- .snap_extent_to_grid( + xmin, xmax, ymin, ymax, + origin = origin, + resolution = c(resolution_m, resolution_m) + ) + xmin_snap <- snapped[["xmin"]] + xmax_snap <- snapped[["xmax"]] + ymin_snap <- snapped[["ymin"]] + ymax_snap <- snapped[["ymax"]] + + terra::rast( + xmin = xmin_snap, + xmax = xmax_snap, + ymin = ymin_snap, + ymax = ymax_snap, + resolution = resolution_m, + crs = target_crs + ) + } +} + + +#' Rasterize SSURGO MUKEY to Standard Grid +#' +#' @description `.rasterize_ssurgo_ssa()`: Generate in-memory SpatRaster from MUKEY polygons +#' for a single soil survey area (SSA). +#' +#' @details +#' Workflow: +#' 1. Extract MUKEY from SSURGO mapunit polygon shapefile from SSA directory +#' 2. Create standard or custom grid template via `.create_ssa_raster_template()` +#' 3. Project polygon features to template target CRS and convert MUKEY to numeric +#' 4. Rasterize polygon features to grid using MUKEY as cell values +#' 5. Return in-memory SpatRaster object for caller to handle writing +#' +#' @param ssa_dir _character_. Path to SSA extraction directory +#' containing SSURGO spatial (.shp) files. +#' @param areasymbol _character_. Soil survey area symbol (e.g., "CA067") for logging. +#' @param template Optional SpatRaster template to align with. +#' @param touches _logical_. If TRUE, all cells touched by polygons are rasterized. Default FALSE. +#' @param grid_alignment Grid alignment mode: `"gssurgo"` (default), `"target_aligned"`, or `"nlcd"`. +#' @param quiet _logical_. Suppress rasterization messages if TRUE. +#' +#' @return SpatRaster object (in-memory), or NULL if rasterization fails or mupolygon not found. +#' @noRd +#' @keywords internal +.rasterize_ssurgo_ssa <- function(ssa_dir, areasymbol, template = NULL, touches = FALSE, + grid_alignment = c("gssurgo", "target_aligned", "nlcd"), + resolution_m = 10, + quiet = FALSE) { + + grid_alignment <- .normalize_grid_alignment(grid_alignment) + + # Locate mupolygon shapefile in ssa_dir + mu_shp_pattern <- list.files(ssa_dir, pattern = "^soilmu_a_.*\\.shp$", full.names = TRUE) + + if (length(mu_shp_pattern) == 0) { + if (!isTRUE(quiet)) { + warning("No mupolygon shapefile found for ", areasymbol, "; skipping rasterization", + call. = FALSE) + } + return(NULL) + } + + mu_shp_file <- mu_shp_pattern[1] + + tryCatch({ + # Read mupolygon shapefile + mu_shp <- sf::read_sf(mu_shp_file) + + # Validate shapefile has data + if (nrow(mu_shp) == 0) { + if (!isTRUE(quiet)) { + warning("Mupolygon shapefile for ", areasymbol, " has no features; skipping rasterization", + call. = FALSE) + } + return(NULL) + } + + # Lowercase column names for consistency + colnames(mu_shp) <- tolower(colnames(mu_shp)) + + # Check for MUKEY field + if (!("mukey" %in% colnames(mu_shp))) { + if (!isTRUE(quiet)) { + warning("MUKEY field not found in mupolygon shapefile for ", areasymbol, + "; skipping rasterization", call. = FALSE) + } + return(NULL) + } + + # Create SpatRaster template snapped to grid + rast_template <- .create_ssa_raster_template( + mu_shp, + template = template, + areasymbol = areasymbol, + resolution_m = resolution_m, + grid_alignment = grid_alignment + ) + + # Project polygons into template target CRS + target_crs <- terra::crs(rast_template) + mu_proj <- sf::st_transform(mu_shp, target_crs) + + # Convert mukey values to numeric for clean integer cell values + mu_proj$mukey <- as.numeric(mu_proj$mukey) + + # Convert sf object to SpatVector for terra::rasterize + mu_vec <- terra::vect(mu_proj) + + # Rasterize MUKEY field to template grid + mukey_raster <- terra::rasterize( + mu_vec, + rast_template, + field = "mukey", + touches = touches + ) + + if (!isTRUE(quiet)) { + message("Rasterizing MUKEY for ", areasymbol, "...") + } + + return(mukey_raster) + + }, error = function(e) { + if (!isTRUE(quiet)) { + warning("Rasterization failed for ", areasymbol, ": ", conditionMessage(e), + call. = FALSE) + } + return(NULL) + }) +} + +.areasymbol_from_mupolygon_file <- function(mu_file) { + gsub( + ".*soil[musfa]{2}_[apl]_([a-z]{2}\\d{3}|mxnl\\d{3}|[a-z]{2})\\.shp.*", + "\\1", + mu_file, + ignore.case = TRUE + ) +} + +.is_ssurgo_areasymbol <- function(areasymbol) { + grepl("^([A-Z]{2}[0-9]{3}|MXNL[0-9]{3})$", toupper(areasymbol)) +} + +.ssurgo_raster_resolution_m <- function(template, resolution_m) { + if (!inherits(template, "SpatRaster")) { + return(resolution_m) + } + + units_gdal <- sf::st_crs(terra::crs(template))$units_gdal + if (length(units_gdal) != 1L || is.na(units_gdal) || + !tolower(units_gdal) %in% c("metre", "meter")) { + return(NA_real_) + } + + max(terra::res(template)) +} + +.warn_if_coarse_ssurgo_raster <- function(areasymbols, resolution_m) { + if (isTRUE(length(resolution_m) == 1L && is.finite(resolution_m) && + resolution_m > 90) && + any(.is_ssurgo_areasymbol(areasymbols), na.rm = TRUE)) { + warning( + "A single SSURGO MUKEY per cell may be misleading at resolutions greater than 90 meters.", + call. = FALSE + ) + } +} + +#' Derive Fiscal Year from SSURGO Metadata +#' +#' @description Extract saverest date from sacatalog table in extracted SSURGO files +#' and derive fiscal year (Oct-Sep) as "FY{YY}" format. +#' +#' @param f.txt.grp _list_. Named list of tabular text file groups from inventory. +#' @param exdir _character_. Extraction directory containing SSURGO files. +#' @param sep _character_. Field separator for reading delimited files. +#' @param quote _character_. Quote character for reading delimited files. +#' @param na.strings _character_. NA string representation. +#' @param header _logical_. Whether files have headers. +#' +#' @return _character_. Fiscal year in "FY{YY}" format (e.g., "FY24"), or NA if not found. +#' @noRd +#' @keywords internal +.derive_fiscal_year_from_sacatalog <- function(f.txt.grp, exdir, sep = "|", quote = "", na.strings = c("", "NA"), header = FALSE) { + + # WSS exports have also been observed with the filename typo "sacatlog.txt". + sacatalog_files <- c(f.txt.grp[["sacatalog"]], f.txt.grp[["sacatlog"]]) + if (length(sacatalog_files) > 0L) { + sacatalog_files <- sacatalog_files[file.exists(sacatalog_files)] + } + if (length(sacatalog_files) == 0L) { + return(NA_character_) + } + sacatalog_file <- sacatalog_files[1] + + tryCatch({ + # Read sacatalog table + sacatalog <- suppressWarnings(data.table::fread( + sacatalog_file, + sep = sep, + header = header, + na.strings = na.strings, + showProgress = FALSE, + data.table = FALSE + )) + + if (is.null(sacatalog) || nrow(sacatalog) == 0) { + return(NA_character_) + } + + saverest <- as.Date(NA_character_) + for (col_name in intersect(c("saverest", "V3", "V4"), colnames(sacatalog))) { + saverest_str <- as.character(sacatalog[[col_name]][1]) + if (is.na(saverest_str) || + !grepl( + "^([0-9]{1,2}/[0-9]{1,2}/[0-9]{4}([[:space:]]+[0-9]{1,2}:[0-9]{2}(:[0-9]{2})?)?|[0-9]{4}-[0-9]{2}-[0-9]{2})$", + saverest_str + )) { + next + } + + # Some exports have a non-date in V3 and the saverest date in V4. + parsed_date <- suppressWarnings(as.Date(saverest_str, format = "%m/%d/%Y %H:%M:%S")) + if (is.na(parsed_date)) { + parsed_date <- suppressWarnings(as.Date(saverest_str, format = "%m/%d/%Y %H:%M")) + } + if (is.na(parsed_date)) { + parsed_date <- suppressWarnings(as.Date(saverest_str, format = "%m/%d/%Y")) + } + if (is.na(parsed_date)) { + parsed_date <- suppressWarnings(as.Date(saverest_str, format = "%Y-%m-%d")) + } + if (!is.na(parsed_date)) { + saverest <- parsed_date + break + } + } + + if (is.na(saverest)) { + return(NA_character_) + } + + # Derive fiscal year using existing WSS function + fiscal_year <- .wss_fiscal_year(saverest) + return(fiscal_year) + + }, error = function(e) { + return(NA_character_) + }) +} + +#' Write SpatRaster to Cache with terra Fallback +#' +#' @description `.write_raster_with_cache()`: Write in-memory SpatRaster to disk cache +#' using soilDB user directory pattern. Falls back to terra::tmpdir() if primary +#' cache write fails. +#' +#' @param raster_obj _SpatRaster_. In-memory raster object to persist. +#' @param areasymbol _character_. Soil survey area symbol (e.g., "CA067") for filename. +#' @param resolution_m _numeric_. Grid resolution in meters, used in the cache filename. +#' @param cache_root _character_. Cache root directory. If NULL, defaults to +#' soilDB_user_dir("cache", "raster", create=TRUE). +#' @param fiscal_year _character_. Optional fiscal year label for cache path organization +#' (e.g., `"FY2024"`, `"FY26"`). If provided, raster is written to +#' `soilDB_user_dir("cache", "WSS", {fiscal_year}, "raster")`. If `NULL`, uses legacy cache path. +#' @param quiet _logical_. Suppress write messages if TRUE. +#' +#' @return _character_. Normalized path to written GeoTIFF, or NA_character_ if write failed. +#' @noRd +#' @keywords internal +.write_raster_with_cache <- function(raster_obj, areasymbol, fiscal_year = NULL, cache_root = NULL, + resolution_m = 10, quiet = FALSE) { + + # Determine cache root directory + if (is.null(cache_root)) { + if (!is.null(fiscal_year)) { + # Nested cache structure: soilDB_user_dir("cache", "WSS", fiscal_year, "raster") + wss_cache_root <- .wss_cache_root(create = TRUE) + cache_root <- file.path(wss_cache_root, fiscal_year, "raster") + } else { + # Legacy flat cache structure: soilDB_user_dir("cache", "raster") + cache_root <- soilDB_user_dir("cache", "raster", create = TRUE) + } + } + dir.create(cache_root, recursive = TRUE, showWarnings = FALSE) + + # Construct filename + filename <- paste0("MUKEY_", resolution_m, "m_", toupper(areasymbol), ".tif") + cache_path <- file.path(cache_root, filename) + + tryCatch({ + # Ensure raster values are compatible with unsigned integer representation + if (inherits(raster_obj, "SpatRaster")) { + raster_obj <- terra::as.int(raster_obj) + } + + # Write raster to primary cache location + .write_cog_raster(raster_obj, cache_path) + + if (!isTRUE(quiet)) { + message("Wrote raster to cache: ", cache_path) + } + + # Return normalized path + normalizePath(cache_path, winslash = .Platform$file.sep, mustWork = FALSE) + + }, error = function(e) { + # Fallback: write to temporary directory + tmpdir <- terra::tmpdir() + tmppath <- file.path(tmpdir, filename) + + tryCatch({ + .write_cog_raster(raster_obj, tmppath) + + warning("Cache directory unavailable; raster written to temporary directory: ", + tmppath, call. = FALSE) + + normalizePath(tmppath, winslash = .Platform$file.sep, mustWork = FALSE) + + }, error = function(e2) { + warning("Failed to write raster for ", areasymbol, ": ", conditionMessage(e2), + call. = FALSE) + return(NA_character_) + }) + }) +} + +#' Create Final Output Raster from SSA Rasters +#' +#' Copies single SSA raster or merges/mosaics multiple SSA rasters into a final output GeoTIFF. +#' If vector bounding box / shapefile extents are available, trims/crops to the exact snapped vector extent. +#' +#' @param raster_paths List of list(areasymbol, path) objects. +#' @param filename Database filename (e.g. "path/to/test.gpkg"). +#' @param conn DBIConnection (used to infer dbname if filename is NULL). +#' @param exdir Directory containing SSURGO files. +#' @param target_bbox Optional numeric bounding box or SpatExtent to crop the final output to. +#' @param template Optional SpatRaster template defining the target grid. +#' @param grid_alignment Grid alignment mode: `"gssurgo"` (default), `"target_aligned"`, or `"nlcd"`. +#' @param resolution_m Target raster resolution in meters (default: 10). +#' @param overwrite Overwrite existing output raster? +#' @param quiet Suppress messages if TRUE. +#' +#' @return Normalized path to final output raster, or NULL. +#' @noRd +#' @keywords internal +.create_final_raster_output <- function(raster_paths, + filename = NULL, + conn = NULL, + exdir = NULL, + target_bbox = NULL, + template = NULL, + grid_alignment = c("gssurgo", "target_aligned", "nlcd"), + resolution_m = 10, + overwrite = FALSE, + quiet = FALSE) { + if (is.null(raster_paths) || length(raster_paths) == 0) { + return(NULL) + } + + grid_alignment <- .normalize_grid_alignment(grid_alignment) + + paths <- unlist(lapply(raster_paths, function(x) x$path), use.names = FALSE) + paths <- paths[!is.na(paths) & file.exists(paths)] + + if (length(paths) == 0) { + return(NULL) + } + + # Determine target output raster directory and base name + target_file <- NULL + if (!is.null(filename) && is.character(filename) && length(filename) > 0 && nzchar(filename[1])) { + target_file <- sub("\\.[^.]+$", ".tif", filename[1]) + if (!grepl("\\.tif$", target_file, ignore.case = TRUE)) { + target_file <- paste0(target_file, ".tif") + } + } else if (!is.null(conn) && inherits(conn, "DBIConnection")) { + dbname <- tryCatch(conn@dbname, error = function(e) NULL) + if (!is.null(dbname) && is.character(dbname) && length(dbname) > 0 && nzchar(dbname[1])) { + target_file <- sub("\\.[^.]+$", ".tif", dbname[1]) + if (!grepl("\\.tif$", target_file, ignore.case = TRUE)) { + target_file <- paste0(target_file, ".tif") + } + } + } + + if (is.null(target_file) && !is.null(exdir)) { + target_file <- file.path(exdir, "mukey.tif") + } + + if (is.null(target_file)) { + return(NULL) + } + + dir.create(dirname(target_file), recursive = TRUE, showWarnings = FALSE) + + if (file.exists(target_file) && !isTRUE(overwrite)) { + if (!isTRUE(quiet)) { + message("Output raster already exists; skipping overwrite: ", target_file) + } + return(normalizePath(target_file, winslash = .Platform$file.sep, mustWork = FALSE)) + } + + tryCatch({ + # Determine target SpatRaster (single source or mosaic) + if (length(paths) == 1) { + out_r <- terra::rast(paths[1]) + } else { + sprc <- terra::sprc(paths) + out_r <- terra::mosaic(sprc) + } + + # If target_bbox is provided, crop output raster to exact snapped bounds + if (!is.null(target_bbox)) { + if (inherits(target_bbox, c("bbox", "numeric", "integer")) && length(target_bbox) >= 4) { + tb_names <- names(target_bbox) + xmin_val <- if ("xmin" %in% tb_names) target_bbox[["xmin"]] else target_bbox[1] + ymin_val <- if ("ymin" %in% tb_names) target_bbox[["ymin"]] else target_bbox[2] + xmax_val <- if ("xmax" %in% tb_names) target_bbox[["xmax"]] else target_bbox[3] + ymax_val <- if ("ymax" %in% tb_names) target_bbox[["ymax"]] else target_bbox[4] + + if (inherits(template, "SpatRaster")) { + snapped <- c(xmin = xmin_val, xmax = xmax_val, ymin = ymin_val, ymax = ymax_val) + } else { + origin <- .grid_origin(grid_alignment, resolution_m) + + snapped <- .snap_extent_to_grid( + xmin_val, xmax_val, ymin_val, ymax_val, + origin = origin, + resolution = c(resolution_m, resolution_m) + ) + } + crop_ext <- terra::ext(snapped[["xmin"]], snapped[["xmax"]], snapped[["ymin"]], snapped[["ymax"]]) + out_r <- terra::crop(out_r, crop_ext) + } else if (inherits(target_bbox, "SpatExtent")) { + out_r <- terra::crop(out_r, target_bbox) + } + } + + # Write final raster output as COG GeoTIFF + .write_cog_raster(out_r, target_file) + + if (!isTRUE(quiet)) { + message("Created final raster output: ", target_file) + } + + normalizePath(target_file, winslash = .Platform$file.sep, mustWork = FALSE) + }, error = function(e) { + if (!isTRUE(quiet)) { + warning("Failed to create final output raster: ", conditionMessage(e), call. = FALSE) + } + NULL + }) +} diff --git a/man/createSSURGO.Rd b/man/createSSURGO.Rd index 780c6962..32770edc 100644 --- a/man/createSSURGO.Rd +++ b/man/createSSURGO.Rd @@ -11,6 +11,9 @@ createSSURGO( pattern = NULL, include_spatial = TRUE, include_tabular = TRUE, + include_raster = FALSE, + LAPPLY.FUN = lapply, + LAPPLY.FUN.ARGS = NULL, dissolve_field = NULL, maxruledepth = 0, overwrite = FALSE, @@ -19,6 +22,11 @@ createSSURGO( sep = "|", na.strings = c("", "NA"), quote = "", + fiscal_year = NULL, + template = NULL, + touches = FALSE, + grid_alignment = c("gssurgo", "target_aligned", "nlcd"), + resolution_m = 10, quiet = TRUE, areasymbols = NULL, ... @@ -48,6 +56,17 @@ containing table names, only that set are written to file. e.g. \code{include_ta descriptions are stored in table \code{"featdesc"} and metadata for each soil survey area are stored in \code{"soil_metadata"} tables.} +\item{include_raster}{\emph{logical}. Generate MUKEY GeoTIFF rasters for each SSA? +Default: \code{FALSE} does not create raster outputs. Set to \code{TRUE} to create georeferenced rasters cached in +\code{soilDB_user_dir("cache", "WSS", ...)} and output a combined/copied raster matching \code{filename}. +Requires \code{terra} package.} + +\item{LAPPLY.FUN}{\emph{function}. \code{lapply()}-like function to use for iteration during rasterization +phase. Only used if \code{include_raster=TRUE}. This allows for the rasterization operations to be run +in parallel instead of sequential, custom progress reporting, or similar.} + +\item{LAPPLY.FUN.ARGS}{\emph{list}. Optional list of additional arguments to pass to \code{LAPPLY.FUN}.} + \item{dissolve_field}{\emph{character}. Dissolve geometries to create MULTIPOLYGON features? Column name specified is the grouping variable. Default: \code{NULL} does no aggregation, giving 1 \code{POLYGON} feature per delineation. \code{"mukey"} aggregates all related delineations within a soil @@ -68,6 +87,26 @@ only shallowest ratings for smaller database size.} \item{quote}{\emph{character}. Passed to \code{data.table::fread()}. Default: \code{""}} +\item{fiscal_year}{\emph{character}. Optional fiscal year label for cache organization (e.g., \code{'FY2024'}, +\code{'FY26'}). If \code{NULL}, auto-detect from sacatalog saverest date. Allows organizing rasters by official +release year or custom labels. Only used if \code{include_raster=TRUE}.} + +\item{template}{Optional \code{SpatRaster} template to align with. If \code{NULL} (default), creates a standard +grid at \code{resolution_m} in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, +EPSG:32161 for PR/VI, EPSG:4326 for Pacific Islands) with bounds snapped according to \code{grid_alignment}.} + +\item{touches}{\emph{logical}. If \code{TRUE}, all cells touched by polygon boundaries are rasterized. Default +\code{FALSE} rasterizes only cells whose centroids fall within polygons.} + +\item{grid_alignment}{\emph{character}. Grid alignment mode when \code{template = NULL}. Use +\code{"gssurgo"} (default), \code{"target_aligned"}, or \code{"nlcd"}. The GSSURGO mode uses a +half-cell origin matching official USDA-NRCS products; +target-aligned uses a zero origin; and NLCD uses the canonical WGS84 Albers +origin anchor \verb{(-2415585, 3314805)}. A supplied \code{template} takes precedence.} + +\item{resolution_m}{\emph{numeric}. Finite positive raster cell size in meters when \code{template = NULL} +(default: \code{10}).} + \item{quiet}{\emph{logical}. Suppress messages and other output from database read/write operations?} \item{areasymbols}{\emph{character}. Optional character vector of soil survey area symbols (e.g. \code{c("CA067", "CA077")}) used to subset the folders/files within \code{exdir} to process. Default \code{NULL} processes all SSURGO exports found in \code{exdir}.} @@ -89,6 +128,17 @@ The following database types are tested and fully supported: In theory any other DBI-compatible data source can be used for output. See \code{conn} argument. If you encounter issues using specific DBI connection types, please report in the soilDB issue tracker. + +When \code{include_raster=TRUE}, common resolutions include 10m, 30m, 300m, and 900m; any positive +resolution can be requested. Custom \code{SpatRaster} templates can be supplied for arbitrary grids. +The alignment modes are +intentional: \code{gssurgo} matches official USDA-NRCS products, \code{target_aligned} follows +zero-origin GDAL-style alignment, and \code{nlcd} uses the canonical WGS84 Albers origin. These +choices support interoperability with federal raster products including NLCD, CDL, USGS 3DEP, +and gNATSGO. Raster output uses \code{NAflag = 0}; MUKEY zero is reserved as NoData. + +A single SSURGO MUKEY per cell may be misleading at resolutions greater than 90 meters. +A warning is issued for recognized SSURGO area symbols when the output grid exceeds this resolution. } \examples{ \dontrun{ diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index c77acaa1..22249f0b 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -161,5 +161,816 @@ test_that("createSSURGO does not append after failed table initialization", { expect_identical(write_call_n, 2L) expect_identical(append_calls, c(FALSE, FALSE)) - expect_false(append_calls[2]) +}) + +# createSSURGO accepts raster-related parameters +test_that("createSSURGO accepts raster-related parameters", { + skip_on_cran() + skip_if_not_installed("RSQLite") + skip_if_not_installed("DBI") + skip_if_not_installed("terra") + + exdir <- tempfile("soilDB-test-parameter-exdir-") + dir.create(exdir) + on.exit(unlink(exdir, recursive = TRUE, force = TRUE), add = TRUE) + + expect_error( + createSSURGO( + filename = tempfile(fileext = ".sqlite"), + exdir = exdir, + include_raster = TRUE, + fiscal_year = "FY2024", + LAPPLY.FUN = lapply, + quiet = TRUE + ), + "appears to be empty" + ) +}) + +# .write_raster_with_cache uses fiscal_year in path +test_that(".write_raster_with_cache constructs correct cache path with fiscal_year", { + skip_on_cran() + skip_if_not_installed("terra") + + # Create a minimal raster for testing + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 10, ymin = 0, ymax = 10) + terra::values(r) <- 1:100 + + temp_cache_base <- tempfile("soilDB-test-cache-") + on.exit({ + try(unlink(temp_cache_base, recursive = TRUE), silent = TRUE) + }, add = TRUE) + + # Test with fiscal_year specified + result <- .write_raster_with_cache( + raster_obj = r, + areasymbol = "CA067", + fiscal_year = "FY2024", + cache_root = NULL, + quiet = TRUE + ) + + # Result should contain the fiscal year in path + expect_true(grepl("FY2024", result, ignore.case = TRUE)) + # Result should contain "raster" subdirectory + expect_true(grepl("raster", result, ignore.case = TRUE)) + # Result should contain the area symbol in filename + expect_true(grepl("CA067", result, ignore.case = TRUE)) +}) + +# .write_raster_with_cache creates nested directory structure +test_that(".write_raster_with_cache creates nested WSS cache structure", { + skip_on_cran() + skip_if_not_installed("terra") + + # Create a minimal raster for testing + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 10, ymin = 0, ymax = 10) + terra::values(r) <- 1:100 + + temp_cache <- tempfile("soilDB-test-wss-cache-") + on.exit({ + try(unlink(temp_cache, recursive = TRUE), silent = TRUE) + }, add = TRUE) + + # Write with custom cache_root and fiscal_year + raster_path <- .write_raster_with_cache( + raster_obj = r, + areasymbol = "CA067", + fiscal_year = "FY2024", + cache_root = file.path(temp_cache, "WSS", "FY2024", "raster"), + quiet = TRUE + ) + + # Verify file was created + expect_true(file.exists(raster_path)) + # Verify path contains the expected structure + expect_true(grepl("FY2024.*raster", raster_path)) +}) + +# .resolve_ssa_crs resolves standard CRS correctly for various SSA regions +test_that(".resolve_ssa_crs resolves CRS correctly by region prefix and grid_alignment", { + # CONUS + expect_equal(.resolve_ssa_crs("CA067"), "EPSG:5070") + expect_equal(.resolve_ssa_crs("TX001"), "EPSG:5070") + + # Alaska + expect_equal(.resolve_ssa_crs("AK650"), "EPSG:3338") + + # Hawaii + expect_equal(.resolve_ssa_crs("HI701"), "EPSG:6628") + + # Puerto Rico / Virgin Islands + expect_equal(.resolve_ssa_crs("PR687"), "EPSG:32161") + expect_equal(.resolve_ssa_crs("VI010"), "EPSG:32161") + + # Pacific Islands + expect_equal(.resolve_ssa_crs("GU600"), "EPSG:4326") + expect_equal(.resolve_ssa_crs("AS010"), "EPSG:4326") + expect_equal(.resolve_ssa_crs("MP001"), "EPSG:4326") + expect_equal(.resolve_ssa_crs("PW001"), "EPSG:4326") + expect_equal(.resolve_ssa_crs("FM001"), "EPSG:4326") + expect_equal(.resolve_ssa_crs("MH001"), "EPSG:4326") + + # Fallbacks / Default + expect_equal(.resolve_ssa_crs("US"), "EPSG:5070") + expect_equal(.resolve_ssa_crs(NULL), "EPSG:5070") + expect_equal(.resolve_ssa_crs(character(0)), "EPSG:5070") + + # NLCD alignment canonical PROJ string + nlcd_crs <- .resolve_ssa_crs("CA067", grid_alignment = "nlcd") + expect_equal(nlcd_crs, "+proj=aea +lat_0=23 +lon_0=-96 +lat_1=29.5 +lat_2=45.5 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") +}) + +test_that("grid alignment names are independent of raster resolution", { + for (alignment in c("gssurgo", "target_aligned", "nlcd")) { + expect_identical(.normalize_grid_alignment(alignment), alignment) + } + + for (resolution_m in c(10, 30, 300, 900, 17.5)) { + expect_equal(.grid_origin("gssurgo", resolution_m), c(resolution_m / 2, resolution_m / 2)) + } + + expect_error(.normalize_grid_alignment("legacy_gssurgo")) + expect_error(.normalize_grid_alignment("gssurgo_900m")) + expect_error(.normalize_grid_alignment("not_a_grid")) + expect_identical(formals(createSSURGO)$resolution_m, 10) + expect_error( + createSSURGO(filename = tempfile(fileext = ".sqlite"), resolution_m = 0), + "`resolution_m` must be a single finite positive number" + ) +}) + +test_that("fiscal-year detection accepts both catalog filenames and date columns", { + temp_root <- tempfile("soilDB-test-sacatalog-") + dir.create(temp_root, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + canonical_file <- file.path(temp_root, "sacatalog.txt") + writeLines("CA630|Central Sierra Foothills|09/01/2026 15:15:13|11|", canonical_file) + expect_equal( + .derive_fiscal_year_from_sacatalog(list(sacatalog = canonical_file), temp_root), + "FY27" + ) + + misspelled_file <- file.path(temp_root, "sacatlog.txt") + writeLines("CA630|Central Sierra Foothills|11|09/01/2026 15:15:13|11|", misspelled_file) + expect_equal( + .derive_fiscal_year_from_sacatalog(list(sacatlog = misspelled_file), temp_root), + "FY27" + ) + + writeLines("CA630|Central Sierra Foothills|11|not-a-date|11|", misspelled_file) + expect_identical( + .derive_fiscal_year_from_sacatalog(list(sacatlog = misspelled_file), temp_root), + NA_character_ + ) + expect_identical( + .derive_fiscal_year_from_sacatalog(list(), temp_root), + NA_character_ + ) +}) + +test_that("SSURGO area symbols are distinguished from STATSGO symbols", { + expect_equal( + .areasymbol_from_mupolygon_file("spatial/soilmu_a_ca067.shp"), + "ca067" + ) + expect_equal( + .areasymbol_from_mupolygon_file("spatial/soilmu_a_mxnl001.shp"), + "mxnl001" + ) + expect_equal(.is_ssurgo_areasymbol(c("CA067", "MXNL001")), c(TRUE, TRUE)) + expect_equal(.is_ssurgo_areasymbol(c("US", "WY")), c(FALSE, FALSE)) +}) + +test_that("coarse-grid warning applies only to SSURGO grids larger than 90m", { + expect_warning( + .warn_if_coarse_ssurgo_raster(c("CA067"), 300), + "greater than 90" + ) + expect_warning( + .warn_if_coarse_ssurgo_raster(c("MXNL001"), 300), + "greater than 90" + ) + expect_no_warning(.warn_if_coarse_ssurgo_raster(c("US", "WY"), 300)) + expect_no_warning(.warn_if_coarse_ssurgo_raster(c("CA067"), 90)) + + template_90m <- terra::rast( + xmin = 0, xmax = 9000, ymin = 0, ymax = 9000, + resolution = 90, crs = "EPSG:5070" + ) + template_91m <- terra::rast( + xmin = 0, xmax = 9100, ymin = 0, ymax = 9100, + resolution = 91, crs = "EPSG:5070" + ) + expect_no_warning(.warn_if_coarse_ssurgo_raster( + "CA067", .ssurgo_raster_resolution_m(template_90m, 300) + )) + expect_warning(.warn_if_coarse_ssurgo_raster( + "CA067", .ssurgo_raster_resolution_m(template_91m, 10) + ), "greater than 90") +}) + +# .create_ssa_raster_template with template = NULL and default gssurgo alignment +test_that(".create_ssa_raster_template with default gssurgo aligns to Peaslee 10k+5 grid and expands outward", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + # Create synthetic sf polygon in EPSG:4269 (NAD83) + poly <- sf::st_polygon(list(matrix( + c(-121.55, 38.55, + -121.45, 38.55, + -121.45, 38.65, + -121.55, 38.65, + -121.55, 38.55), + ncol = 2, byrow = TRUE + ))) + poly_sf <- sf::st_sf(geometry = sf::st_sfc(poly, crs = 4269)) + + tmpl_legacy <- .create_ssa_raster_template( + mu_shp = poly_sf, + template = NULL, + areasymbol = "CA067", + resolution_m = 10, + buffer_m = 10, + grid_alignment = "gssurgo" + ) + + expect_s4_class(tmpl_legacy, "SpatRaster") + expect_equal(terra::crs(tmpl_legacy, describe = TRUE)$code, "5070") + expect_equal(terra::res(tmpl_legacy), c(10, 10)) + + ext_legacy <- terra::ext(tmpl_legacy) + # Legacy gSSURGO Peaslee grid coordinates satisfy (coord - 5) %% 10 == 0 + expect_equal(unname((ext_legacy$xmin - 5) %% 10), 0) + expect_equal(unname((ext_legacy$xmax - 5) %% 10), 0) + expect_equal(unname((ext_legacy$ymin - 5) %% 10), 0) + expect_equal(unname((ext_legacy$ymax - 5) %% 10), 0) + + # Outward expansion check against original transformed polygon bounding box + poly_5070 <- sf::st_transform(poly_sf, "EPSG:5070") + raw_bbox <- sf::st_bbox(poly_5070) + expect_lte(ext_legacy$xmin, raw_bbox[["xmin"]] - 10) + expect_gte(ext_legacy$xmax, raw_bbox[["xmax"]] + 10) + expect_lte(ext_legacy$ymin, raw_bbox[["ymin"]] - 10) + expect_gte(ext_legacy$ymax, raw_bbox[["ymax"]] + 10) +}) + +# Test 11b: .create_ssa_raster_template with target_aligned alignment +test_that(".create_ssa_raster_template with target_aligned aligns to 10k grid", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + poly <- sf::st_polygon(list(matrix( + c(-121.55, 38.55, + -121.45, 38.55, + -121.45, 38.65, + -121.55, 38.65, + -121.55, 38.55), + ncol = 2, byrow = TRUE + ))) + poly_sf <- sf::st_sf(geometry = sf::st_sfc(poly, crs = 4269)) + + tmpl_target <- .create_ssa_raster_template( + mu_shp = poly_sf, + template = NULL, + areasymbol = "CA067", + resolution_m = 10, + buffer_m = 10, + grid_alignment = "target_aligned" + ) + + expect_s4_class(tmpl_target, "SpatRaster") + expect_equal(terra::crs(tmpl_target, describe = TRUE)$code, "5070") + expect_equal(terra::res(tmpl_target), c(10, 10)) + + ext_target <- terra::ext(tmpl_target) + # Target aligned grid coordinates satisfy coord %% 10 == 0 + expect_equal(unname(ext_target$xmin %% 10), 0) + expect_equal(unname(ext_target$xmax %% 10), 0) + expect_equal(unname(ext_target$ymin %% 10), 0) + expect_equal(unname(ext_target$ymax %% 10), 0) + + poly_5070 <- sf::st_transform(poly_sf, "EPSG:5070") + raw_bbox <- sf::st_bbox(poly_5070) + expect_lte(ext_target$xmin, raw_bbox[["xmin"]] - 10) + expect_gte(ext_target$xmax, raw_bbox[["xmax"]] + 10) + expect_lte(ext_target$ymin, raw_bbox[["ymin"]] - 10) + expect_gte(ext_target$ymax, raw_bbox[["ymax"]] + 10) +}) + +# Test 11c: .create_ssa_raster_template with nlcd alignment +test_that(".create_ssa_raster_template with nlcd aligns to NLCD CONUS origin (-2415585, 3314805)", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + poly <- sf::st_polygon(list(matrix( + c(-121.55, 38.55, + -121.45, 38.55, + -121.45, 38.65, + -121.55, 38.65, + -121.55, 38.55), + ncol = 2, byrow = TRUE + ))) + poly_sf <- sf::st_sf(geometry = sf::st_sfc(poly, crs = 4269)) + + tmpl_nlcd <- .create_ssa_raster_template( + mu_shp = poly_sf, + template = NULL, + areasymbol = "CA067", + resolution_m = 30, + buffer_m = 30, + grid_alignment = "nlcd" + ) + + expect_s4_class(tmpl_nlcd, "SpatRaster") + expect_equal(terra::res(tmpl_nlcd), c(30, 30)) + + ext_nlcd <- terra::ext(tmpl_nlcd) + # Snapped coordinates locked to (-2415585, 3314805) + expect_equal(unname((ext_nlcd$xmin - (-2415585)) %% 30), 0) + expect_equal(unname((ext_nlcd$xmax - (-2415585)) %% 30), 0) + expect_equal(unname((ext_nlcd$ymin - 3314805) %% 30), 0) + expect_equal(unname((ext_nlcd$ymax - 3314805) %% 30), 0) + + # Check outward expansion in NLCD target CRS + nlcd_crs <- "+proj=aea +lat_0=23 +lon_0=-96 +lat_1=29.5 +lat_2=45.5 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" + poly_nlcd <- sf::st_transform(poly_sf, nlcd_crs) + raw_bbox <- sf::st_bbox(poly_nlcd) + expect_lte(ext_nlcd$xmin, raw_bbox[["xmin"]] - 30) + expect_gte(ext_nlcd$xmax, raw_bbox[["xmax"]] + 30) + expect_lte(ext_nlcd$ymin, raw_bbox[["ymin"]] - 30) + expect_gte(ext_nlcd$ymax, raw_bbox[["ymax"]] + 30) +}) + +# Grid phase matching between adjacent SSAs +test_that("grid phase matching produces aligned templates between adjacent SSAs", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + # Adjacent polygon 1 + poly1 <- sf::st_polygon(list(matrix( + c(-121.50, 38.50, + -121.40, 38.50, + -121.40, 38.60, + -121.50, 38.60, + -121.50, 38.50), + ncol = 2, byrow = TRUE + ))) + sf1 <- sf::st_sf(geometry = sf::st_sfc(poly1, crs = 4269)) + + # Adjacent polygon 2 (shares east edge with polygon 1) + poly2 <- sf::st_polygon(list(matrix( + c(-121.40, 38.50, + -121.30, 38.50, + -121.30, 38.60, + -121.40, 38.60, + -121.40, 38.50), + ncol = 2, byrow = TRUE + ))) + sf2 <- sf::st_sf(geometry = sf::st_sfc(poly2, crs = 4269)) + + # Test default gssurgo + tmpl1_leg <- .create_ssa_raster_template(sf1, template = NULL, areasymbol = "CA067", resolution_m = 10, grid_alignment = "gssurgo") + tmpl2_leg <- .create_ssa_raster_template(sf2, template = NULL, areasymbol = "CA067", resolution_m = 10, grid_alignment = "gssurgo") + + orig1_leg <- terra::origin(tmpl1_leg) + orig2_leg <- terra::origin(tmpl2_leg) + expect_equal(orig1_leg, orig2_leg) + expect_equal(terra::res(tmpl1_leg), terra::res(tmpl2_leg)) + + # Test target_aligned + tmpl1_tgt <- .create_ssa_raster_template(sf1, template = NULL, areasymbol = "CA067", resolution_m = 10, grid_alignment = "target_aligned") + tmpl2_tgt <- .create_ssa_raster_template(sf2, template = NULL, areasymbol = "CA067", resolution_m = 10, grid_alignment = "target_aligned") + + orig1_tgt <- terra::origin(tmpl1_tgt) + orig2_tgt <- terra::origin(tmpl2_tgt) + expect_equal(orig1_tgt, orig2_tgt) + expect_equal(terra::res(tmpl1_tgt), terra::res(tmpl2_tgt)) + + # Test nlcd + tmpl1_nlcd <- .create_ssa_raster_template(sf1, template = NULL, areasymbol = "CA067", resolution_m = 30, grid_alignment = "nlcd") + tmpl2_nlcd <- .create_ssa_raster_template(sf2, template = NULL, areasymbol = "CA067", resolution_m = 30, grid_alignment = "nlcd") + + orig1_nlcd <- terra::origin(tmpl1_nlcd) + orig2_nlcd <- terra::origin(tmpl2_nlcd) + expect_equal(orig1_nlcd, orig2_nlcd) + expect_equal(terra::res(tmpl1_nlcd), terra::res(tmpl2_nlcd)) +}) + +# .create_ssa_raster_template with custom template preserves resolution, CRS, origin +test_that(".create_ssa_raster_template with custom template preserves resolution, CRS, and origin", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + # Custom template with 30m resolution and offset origin + custom_tmpl <- terra::rast( + xmin = -2000005, + xmax = -1900005, + ymin = 2000005, + ymax = 2100005, + resolution = c(30, 30), + crs = "EPSG:5070" + ) + + poly <- sf::st_polygon(list(matrix( + c(-1950000, 2050000, + -1940000, 2050000, + -1940000, 2060000, + -1950000, 2060000, + -1950000, 2050000), + ncol = 2, byrow = TRUE + ))) + poly_sf <- sf::st_sf(geometry = sf::st_sfc(poly, crs = 5070)) + + res_tmpl <- .create_ssa_raster_template( + mu_shp = poly_sf, + template = custom_tmpl, + areasymbol = "CA067", + resolution_m = 10 + ) + + expect_equal(terra::res(res_tmpl), c(30, 30)) + expect_equal(terra::crs(res_tmpl), terra::crs(custom_tmpl)) + expect_equal(terra::origin(res_tmpl), terra::origin(custom_tmpl)) +}) + +# .write_raster_with_cache COG format and datatype +test_that(".write_raster_with_cache writes INT4U datatype and COG format", { + skip_on_cran() + skip_if_not_installed("terra") + + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 100, ymin = 0, ymax = 100, crs = "EPSG:5070") + terra::values(r) <- c(rep(1001:1050, each = 1), rep(NA, 50)) + + temp_dir <- tempfile("soilDB-test-cog-") + on.exit(try(unlink(temp_dir, recursive = TRUE), silent = TRUE), add = TRUE) + + file_path <- .write_raster_with_cache( + raster_obj = r, + areasymbol = "CA067", + cache_root = temp_dir, + resolution_m = 30, + quiet = TRUE + ) + + expect_true(file.exists(file_path)) + expect_match(basename(file_path), "^MUKEY_30m_CA067\\.tif$") + + read_r <- terra::rast(file_path) + expect_equal(terra::datatype(read_r), "INT4U") + + desc <- terra::describe(file_path) + expect_true(any(grepl("LAYOUT=COG", desc))) + expect_true(any(grepl("COMPRESSION=DEFLATE", desc))) + expect_true(any(grepl("Block=", desc))) + expect_true(any(grepl("NoData Value=0", desc))) +}) + +# .rasterize_ssurgo_ssa with mock shapefile (touches = FALSE and TRUE) +test_that(".rasterize_ssurgo_ssa rasterizes mock shapefile with touches = FALSE and TRUE", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + temp_ssa <- tempfile("soilDB-test-ssa-") + dir.create(temp_ssa, recursive = TRUE) + on.exit(try(unlink(temp_ssa, recursive = TRUE), silent = TRUE), add = TRUE) + + # Create mock polygons with mukey + poly1 <- sf::st_polygon(list(matrix( + c(-121.50, 38.50, + -121.45, 38.50, + -121.45, 38.55, + -121.50, 38.55, + -121.50, 38.50), + ncol = 2, byrow = TRUE + ))) + poly2 <- sf::st_polygon(list(matrix( + c(-121.45, 38.50, + -121.40, 38.50, + -121.40, 38.55, + -121.45, 38.55, + -121.45, 38.50), + ncol = 2, byrow = TRUE + ))) + + mock_sf <- sf::st_sf( + mukey = c("12345", "67890"), + geometry = sf::st_sfc(poly1, poly2, crs = 4269) + ) + + sf::st_write(mock_sf, file.path(temp_ssa, "soilmu_a_test.shp"), quiet = TRUE) + + # Rasterize with touches = FALSE + r_untouched <- .rasterize_ssurgo_ssa(temp_ssa, areasymbol = "CA067", touches = FALSE, quiet = TRUE) + expect_s4_class(r_untouched, "SpatRaster") + vals_untouched <- stats::na.omit(terra::values(r_untouched)) + expect_true(all(vals_untouched %in% c(12345, 67890))) + + # Rasterize with touches = TRUE + r_touched <- .rasterize_ssurgo_ssa(temp_ssa, areasymbol = "CA067", touches = TRUE, quiet = TRUE) + expect_s4_class(r_touched, "SpatRaster") + vals_touched <- stats::na.omit(terra::values(r_touched)) + expect_true(all(vals_touched %in% c(12345, 67890))) + expect_gte(length(vals_touched), length(vals_untouched)) +}) + +test_that(".rasterize_ssurgo_ssa applies the requested resolution unless a template is supplied", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + + temp_ssa <- tempfile("soilDB-test-resolution-") + dir.create(temp_ssa, recursive = TRUE) + on.exit(try(unlink(temp_ssa, recursive = TRUE), silent = TRUE), add = TRUE) + + poly <- sf::st_polygon(list(matrix( + c(-121.50, 38.50, + -121.45, 38.50, + -121.45, 38.55, + -121.50, 38.55, + -121.50, 38.50), + ncol = 2, byrow = TRUE + ))) + mock_sf <- sf::st_sf( + mukey = "12345", + geometry = sf::st_sfc(poly, crs = 4269) + ) + sf::st_write(mock_sf, file.path(temp_ssa, "soilmu_a_test.shp"), quiet = TRUE) + + for (resolution_m in c(10, 30, 300, 900, 17.5)) { + raster <- .rasterize_ssurgo_ssa( + temp_ssa, + areasymbol = "CA067", + resolution_m = resolution_m, + quiet = TRUE + ) + expect_equal(terra::res(raster), c(resolution_m, resolution_m)) + } + + custom_template <- terra::rast( + xmin = -2000005, + xmax = -1900005, + ymin = 2000005, + ymax = 2100005, + resolution = 30, + crs = "EPSG:5070" + ) + custom_raster <- .rasterize_ssurgo_ssa( + temp_ssa, + areasymbol = "CA067", + template = custom_template, + resolution_m = 900, + quiet = TRUE + ) + expect_equal(terra::res(custom_raster), terra::res(custom_template)) +}) + +# createSSURGO works with include_spatial = FALSE and include_raster = TRUE +test_that("createSSURGO handles include_spatial = FALSE and include_raster = TRUE without error", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + skip_if_not_installed("RSQLite") + + temp_root <- tempfile("soilDB-test-spatial-false-") + ssa_dir <- file.path(temp_root, "spatial") + dir.create(ssa_dir, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + # Create mock polygons + poly1 <- sf::st_polygon(list(matrix( + c(-121.50, 38.50, + -121.45, 38.50, + -121.45, 38.55, + -121.50, 38.55, + -121.50, 38.50), + ncol = 2, byrow = TRUE + ))) + mock_sf <- sf::st_sf( + mukey = c("12345"), + geometry = sf::st_sfc(poly1, crs = 4269) + ) + sf::st_write(mock_sf, file.path(ssa_dir, "soilmu_a_ca067.shp"), quiet = TRUE) + + db_file <- file.path(temp_root, "test.sqlite") + res <- expect_no_error( + createSSURGO( + filename = db_file, + exdir = temp_root, + include_spatial = FALSE, + include_tabular = FALSE, + include_raster = TRUE, + fiscal_year = "FY2026", + quiet = TRUE + ) + ) + + # Check final output raster was created next to test.sqlite + expected_tif <- file.path(temp_root, "test.tif") + expect_true(file.exists(expected_tif)) + rp <- attr(res, "raster_paths") + expect_true(!is.null(rp)) + expect_equal(attr(rp, "output_raster"), normalizePath(expected_tif, winslash = "/")) +}) + +test_that("createSSURGO warns for coarse Mexico SSURGO grids", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + skip_if_not_installed("RSQLite") + + temp_root <- tempfile("soilDB-test-coarse-ssurgo-") + ssa_dir <- file.path(temp_root, "ssa") + dir.create(ssa_dir, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + old_opt <- options(soilDB.WSS.cache_dir = file.path(temp_root, "cache")) + on.exit(options(old_opt), add = TRUE) + + poly <- sf::st_polygon(list(matrix( + c(-121.50, 38.50, + -121.45, 38.50, + -121.45, 38.55, + -121.50, 38.55, + -121.50, 38.50), + ncol = 2, byrow = TRUE + ))) + sf::st_write( + sf::st_sf( + mukey = "12345", + geometry = sf::st_sfc(poly, crs = 4269) + ), + file.path(ssa_dir, "soilmu_a_mxnl001.shp"), + quiet = TRUE + ) + + expect_warning( + createSSURGO( + filename = file.path(temp_root, "coarse.sqlite"), + exdir = temp_root, + include_spatial = FALSE, + include_tabular = FALSE, + include_raster = TRUE, + fiscal_year = "FY2026", + grid_alignment = "gssurgo", + resolution_m = 300, + overwrite = TRUE, + quiet = TRUE + ), + "greater than 90" + ) +}) + +# createSSURGO crops a multi-SSA raster to the snapped vector union +test_that("createSSURGO uses the snapped union extent for multiple SSAs", { + skip_on_cran() + skip_if_not_installed("sf") + skip_if_not_installed("terra") + skip_if_not_installed("RSQLite") + + for (alignment in c("gssurgo", "target_aligned", "nlcd")) { + temp_root <- tempfile(paste0("soilDB-test-multi-ssa-", alignment, "-")) + dir.create(temp_root, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + for (spec in list( + list(dir = "ssa1", file = "soilmu_a_ca067.shp", x = -121.50), + list(dir = "ssa2", file = "soilmu_a_ca077.shp", x = -121.40) + )) { + ssa_dir <- file.path(temp_root, spec$dir) + dir.create(ssa_dir, recursive = TRUE) + poly <- sf::st_polygon(list(matrix( + c(spec$x, 38.50, spec$x + 0.02, 38.50, + spec$x + 0.02, 38.52, spec$x, 38.52, spec$x, 38.50), + ncol = 2, byrow = TRUE + ))) + sf::st_write( + sf::st_sf(mukey = 12345, geometry = sf::st_sfc(poly, crs = 4269)), + file.path(ssa_dir, spec$file), quiet = TRUE + ) + } + + db_file <- file.path(temp_root, "multi.sqlite") + result <- createSSURGO( + filename = db_file, + exdir = temp_root, + include_spatial = FALSE, + include_tabular = FALSE, + include_raster = TRUE, + fiscal_year = "FY2026", + grid_alignment = alignment, + quiet = TRUE + ) + + output <- attr(attr(result, "raster_paths"), "output_raster") + expect_true(file.exists(output)) + actual <- terra::ext(terra::rast(output)) + expected <- .compute_ssa_vector_bbox( + mu_files = c( + file.path(temp_root, "ssa1", "soilmu_a_ca067.shp"), + file.path(temp_root, "ssa2", "soilmu_a_ca077.shp") + ), + ssa_list = list(list(areasymbol = "ca067"), list(areasymbol = "ca077")), + grid_alignment = alignment, + resolution_m = 10 + ) + expect_equal(unname(as.vector(actual)), unname(expected[c("xmin", "xmax", "ymin", "ymax")])) + + origin <- switch( + alignment, + gssurgo = c(5, 5), + target_aligned = c(0, 0), + nlcd = c(-2415585, 3314805) + ) + expect_equal( + as.numeric((expected[c("xmin", "xmax")] - origin[1]) %% 10), + c(0, 0) + ) + expect_equal( + as.numeric((expected[c("ymin", "ymax")] - origin[2]) %% 10), + c(0, 0) + ) + + custom_template <- terra::rast( + xmin = -2000005, xmax = -1990005, + ymin = 2000007, ymax = 2010007, + resolution = 10, crs = "EPSG:5070" + ) + template_origin <- terra::origin(custom_template) + template_bbox <- .compute_ssa_vector_bbox( + mu_files = c( + file.path(temp_root, "ssa1", "soilmu_a_ca067.shp"), + file.path(temp_root, "ssa2", "soilmu_a_ca077.shp") + ), + ssa_list = list(list(areasymbol = "ca067"), list(areasymbol = "ca077")), + template = custom_template, + grid_alignment = alignment, + resolution_m = 10 + ) + expect_equal( + as.numeric((template_bbox[c("xmin", "xmax")] - template_origin[1]) %% 10), + c(0, 0) + ) + expect_equal( + as.numeric((template_bbox[c("ymin", "ymax")] - template_origin[2]) %% 10), + c(0, 0) + ) + } +}) +# .create_final_raster_output crops to snapped target_bbox +test_that(".create_final_raster_output crops output raster to snapped target_bbox without padding", { + skip_on_cran() + skip_if_not_installed("terra") + + temp_root <- tempfile("soilDB-test-final-crop-") + dir.create(temp_root, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + # Create a mock raster covering [0, 100] x [0, 100] in EPSG:5070 with 5m offset alignment + mock_r <- terra::rast( + xmin = -5, xmax = 105, ymin = -5, ymax = 105, + resolution = 10, + crs = "EPSG:5070" + ) + terra::values(mock_r) <- 1001 + mock_tif <- file.path(temp_root, "mock_ssa.tif") + terra::writeRaster(mock_r, mock_tif, overwrite = TRUE) + + raster_paths <- list(list(areasymbol = "CA067", path = mock_tif)) + target_file <- file.path(temp_root, "final.tif") + + # Target bbox [12, 12, 48, 48] in gssurgo snapping should snap to [5, 5, 55, 55] + target_bbox <- c(xmin = 12, ymin = 12, xmax = 48, ymax = 48) + + res_path <- .create_final_raster_output( + raster_paths = raster_paths, + filename = target_file, + target_bbox = target_bbox, + grid_alignment = "gssurgo", + resolution_m = 10, + overwrite = TRUE, + quiet = TRUE + ) + + expect_true(!is.null(res_path)) + expect_true(file.exists(res_path)) + + cropped_r <- terra::rast(res_path) + ext <- terra::ext(cropped_r) + expect_equal(unname(ext$xmin), 5) + expect_equal(unname(ext$ymin), 5) + expect_equal(unname(ext$xmax), 55) + expect_equal(unname(ext$ymax), 55) + expect_equal(terra::datatype(cropped_r), "INT4U") + desc <- terra::describe(res_path) + expect_true(any(grepl("LAYOUT=COG", desc))) + expect_true(any(grepl("COMPRESSION=DEFLATE", desc))) + expect_true(any(grepl("NoData Value=0", desc))) }) From 1993226112fa7ea042e0493ceb9baef21c02980e Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Thu, 12 Nov 2026 15:23:51 -0800 Subject: [PATCH 2/9] fix(raster): preserve MU inventory and validate target CRS --- R/createSSURGO.R | 228 +++++++++++++++++------------ man/createSSURGO.Rd | 14 +- tests/testthat/test-createSSURGO.R | 57 ++++++++ 3 files changed, 201 insertions(+), 98 deletions(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index 300cc1c1..4244abc0 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -258,7 +258,10 @@ downloadSSURGO <- function(WHERE = NULL, #' intentional: `gssurgo` matches official USDA-NRCS products, `target_aligned` follows #' zero-origin GDAL-style alignment, and `nlcd` uses the canonical WGS84 Albers origin. These #' choices support interoperability with federal raster products including NLCD, CDL, USGS 3DEP, -#' and gNATSGO. Raster output uses `NAflag = 0`; MUKEY zero is reserved as NoData. +#' and gNATSGO. A supplied template defines a common CRS and grid for all selected SSAs. Without +#' a template, selected SSAs must share a regional CRS. The Pacific Island default CRS (EPSG:4326) +#' is geographic, so meter-based rasterization there requires an explicit template. Raster output +#' uses `NAflag = 0`; MUKEY zero is reserved as NoData. #' #' A single SSURGO MUKEY per cell may be misleading at resolutions greater than 90 meters. #' A warning is issued for recognized SSURGO area symbols when the output grid exceeds this resolution. @@ -305,8 +308,10 @@ downloadSSURGO <- function(WHERE = NULL, #' @param sep _character_. Passed to `data.table::fread()`. Default: `"|"` #' @param na.strings _character_. Passed to `data.table::fread()`. Default: `c("", "NA")` #' @param quote _character_. Passed to `data.table::fread()`. Default: `""` -#' @param template Optional `SpatRaster` template to align with. If `NULL` (default), creates a standard -#' grid at `resolution_m` in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, +#' @param template Optional `SpatRaster` template defining a common target CRS and grid, including +#' cell size, for all selected SSAs. Use a template when the selection spans regional CRSs or +#' when a geographic CRS is needed. If `NULL` (default), creates a standard grid at `resolution_m` +#' in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, #' EPSG:32161 for PR/VI, EPSG:4326 for Pacific Islands) with bounds snapped according to `grid_alignment`. #' @param touches _logical_. If `TRUE`, all cells touched by polygon boundaries are rasterized. Default #' `FALSE` rasterizes only cells whose centroids fall within polygons. @@ -316,7 +321,8 @@ downloadSSURGO <- function(WHERE = NULL, #' target-aligned uses a zero origin; and NLCD uses the canonical WGS84 Albers #' origin anchor `(-2415585, 3314805)`. A supplied `template` takes precedence. #' @param resolution_m _numeric_. Finite positive raster cell size in meters when `template = NULL` -#' (default: `10`). +#' and the regional CRS is projected (default: `10`). Meter-based rasterization with a geographic +#' regional CRS requires an explicit `template`. #' @param quiet _logical_. Suppress messages and other output from database read/write operations? #' @param areasymbols _character_. Optional character vector of soil survey area symbols (e.g. `c("CA067", "CA077")`) used to subset the folders/files within `exdir` to process. Default `NULL` processes all SSURGO exports found in `exdir`. #' @param ... Additional arguments passed to `sf::write_sf()` for writing spatial layers. @@ -654,110 +660,106 @@ createSSURGO <- function(filename = NULL, } # Rasterize mupolygon to MUKEY raster (parallelized by SSA if include_raster=TRUE) - if (isTRUE(include_raster) && !is.null(inv$shp.grp) && nrow(inv$shp.grp) >= 1) { - - # Extract unique SSA directories from mupolygon shapefiles - mu_idx <- which(inv$shp.grp[, 1] == "mu" & inv$shp.grp[, 2] == "a") - - if (length(mu_idx) > 0) { - # Get mupolygon shapefiles (feature "mu", geometry "a") directly from inventory - mu_files <- inv$f.shp[mu_idx] - - # Extract unique SSA directories and areasymbols - ssa_dirs <- unique(dirname(mu_files)) - ssa_list <- lapply(ssa_dirs, function(d) { - # Extract areasymbol from directory or filename - mu_file <- mu_files[dirname(mu_files) == d][1] - areasymbol <- .areasymbol_from_mupolygon_file(mu_file) - list(ssa_dir = d, areasymbol = areasymbol, fiscal_year = derived_fiscal_year) - }) - - warning_resolution_m <- .ssurgo_raster_resolution_m(template, resolution_m) - .warn_if_coarse_ssurgo_raster( - vapply(ssa_list, `[[`, character(1), "areasymbol"), - warning_resolution_m - ) + if (isTRUE(include_raster) && length(inv$f.mupolygon) > 0) { + # Get mupolygon shapefiles directly from the unfiltered raster inventory + mu_files <- inv$f.mupolygon + + # Extract unique SSA directories and areasymbols + ssa_dirs <- unique(dirname(mu_files)) + ssa_list <- lapply(ssa_dirs, function(d) { + # Extract areasymbol from directory or filename + mu_file <- mu_files[dirname(mu_files) == d][1] + areasymbol <- .areasymbol_from_mupolygon_file(mu_file) + list(ssa_dir = d, areasymbol = areasymbol, fiscal_year = derived_fiscal_year) + }) - # Define rasterization worker function for namespace isolation - # Captures ssa_list and quiet from enclosing scope - .RASTERIZE.FUN <- function(ssa_index) { - if (ssa_index > length(ssa_list)) { - return(list()) - } + .validate_ssa_raster_crs(ssa_list, template, grid_alignment) + + warning_resolution_m <- .ssurgo_raster_resolution_m(template, resolution_m) + .warn_if_coarse_ssurgo_raster( + vapply(ssa_list, `[[`, character(1), "areasymbol"), + warning_resolution_m + ) + + # Define rasterization worker function for namespace isolation + # Captures ssa_list and quiet from enclosing scope + .RASTERIZE.FUN <- function(ssa_index) { + if (ssa_index > length(ssa_list)) { + return(list()) + } - ssa_info <- ssa_list[[ssa_index]] - ssa_dir <- ssa_info$ssa_dir - areasymbol <- ssa_info$areasymbol - fiscal_year_arg <- ssa_info$fiscal_year + ssa_info <- ssa_list[[ssa_index]] + ssa_dir <- ssa_info$ssa_dir + areasymbol <- ssa_info$areasymbol + fiscal_year_arg <- ssa_info$fiscal_year - # Explicitly fetch internal functions from namespace for worker isolation - .rasterize_fn <- get(".rasterize_ssurgo_ssa", envir = asNamespace("soilDB")) - .write_raster_fn <- get(".write_raster_with_cache", envir = asNamespace("soilDB")) + # Explicitly fetch internal functions from namespace for worker isolation + .rasterize_fn <- get(".rasterize_ssurgo_ssa", envir = asNamespace("soilDB")) + .write_raster_fn <- get(".write_raster_with_cache", envir = asNamespace("soilDB")) - # Call rasterization helper - mukey_raster <- .rasterize_fn( - ssa_dir = ssa_dir, + # Call rasterization helper + mukey_raster <- .rasterize_fn( + ssa_dir = ssa_dir, + areasymbol = areasymbol, + template = template, + touches = touches, + grid_alignment = grid_alignment, + quiet = quiet, + resolution_m = resolution_m + ) + + # Write raster to cache if rasterization succeeded + if (!is.null(mukey_raster)) { + raster_path <- .write_raster_fn( + raster_obj = mukey_raster, areasymbol = areasymbol, - template = template, - touches = touches, - grid_alignment = grid_alignment, - quiet = quiet, - resolution_m = resolution_m + fiscal_year = fiscal_year_arg, + cache_root = NULL, + resolution_m = resolution_m, + quiet = quiet ) - # Write raster to cache if rasterization succeeded - if (!is.null(mukey_raster)) { - raster_path <- .write_raster_fn( - raster_obj = mukey_raster, + if (!is.na(raster_path)) { + return(list(list( areasymbol = areasymbol, - fiscal_year = fiscal_year_arg, - cache_root = NULL, - resolution_m = resolution_m, - quiet = quiet - ) - - if (!is.na(raster_path)) { - return(list(list( - areasymbol = areasymbol, - path = raster_path - ))) - } + path = raster_path + ))) } - list() } + list() + } - # Compute the unified vector extent before rasterization so final output - # is cropped to the same snapped geometry bounds as the SSA templates. - target_bbox <- .compute_ssa_vector_bbox( - mu_files = mu_files, - ssa_list = ssa_list, - template = template, - grid_alignment = grid_alignment, - resolution_m = resolution_m - ) + # Compute the unified vector extent before rasterization so final output + # is cropped to the same snapped geometry bounds as the SSA templates. + target_bbox <- .compute_ssa_vector_bbox( + mu_files = mu_files, + ssa_list = ssa_list, + template = template, + grid_alignment = grid_alignment, + resolution_m = resolution_m + ) - # Execute rasterization in parallel or sequential mode - raster_results <- do.call(LAPPLY.FUN, c(list(seq_along(ssa_list), .RASTERIZE.FUN), LAPPLY.FUN.ARGS)) + # Execute rasterization in parallel or sequential mode + raster_results <- do.call(LAPPLY.FUN, c(list(seq_along(ssa_list), .RASTERIZE.FUN), LAPPLY.FUN.ARGS)) - # Accumulate results into raster_paths (vectorized: filter empty lists and unlist one level) - raster_paths <- c(raster_paths, unlist(Filter(length, raster_results), recursive = FALSE)) + # Accumulate results into raster_paths (vectorized: filter empty lists and unlist one level) + raster_paths <- c(raster_paths, unlist(Filter(length, raster_results), recursive = FALSE)) - # If filename or conn was provided, write/merge final output raster - final_raster_path <- .create_final_raster_output( - raster_paths = raster_paths, - filename = filename, - conn = conn, - exdir = exdir, - target_bbox = target_bbox, - template = template, - grid_alignment = grid_alignment, - resolution_m = resolution_m, - overwrite = overwrite, - quiet = quiet - ) - if (!is.null(final_raster_path) && !is.na(final_raster_path)) { - attr(raster_paths, "output_raster") <- final_raster_path - } + # If filename or conn was provided, write/merge final output raster + final_raster_path <- .create_final_raster_output( + raster_paths = raster_paths, + filename = filename, + conn = conn, + exdir = exdir, + target_bbox = target_bbox, + template = template, + grid_alignment = grid_alignment, + resolution_m = resolution_m, + overwrite = overwrite, + quiet = quiet + ) + if (!is.null(final_raster_path) && !is.na(final_raster_path)) { + attr(raster_paths, "output_raster") <- final_raster_path } } @@ -1014,6 +1016,11 @@ createSSURGO <- function(filename = NULL, ";", fixed = TRUE )) + f.mupolygon <- if (!is.null(shp.grp) && nrow(shp.grp) > 0) { + f.shp[shp.grp[, 1] == "mu" & shp.grp[, 2] == "a"] + } else { + character(0) + } f.shp.sc <- character(0) if (is.character(include_spatial)) { @@ -1073,6 +1080,7 @@ createSSURGO <- function(filename = NULL, list( f.shp = f.shp, shp.grp = shp.grp, + f.mupolygon = f.mupolygon, f.shp.sc = f.shp.sc, include_spatial = include_spatial, f.txt.grp = f.txt.grp, @@ -1535,6 +1543,38 @@ createSSURGO <- function(filename = NULL, "EPSG:5070" } +.validate_ssa_raster_crs <- function(ssa_list, template = NULL, + grid_alignment = "gssurgo") { + if (inherits(template, "SpatRaster") || length(ssa_list) == 0L) { + return(invisible(NULL)) + } + + grid_alignment <- .normalize_grid_alignment(grid_alignment) + crs <- vapply( + ssa_list, + function(ssa) .resolve_ssa_crs(ssa$areasymbol, grid_alignment = grid_alignment), + character(1) + ) + + if (length(unique(crs)) > 1L) { + stop( + "Selected SSAs use different regional CRSs; supply a common `template` to rasterize them together.", + call. = FALSE + ) + } + + units_gdal <- sf::st_crs(crs[1])$units_gdal + if (length(units_gdal) != 1L || is.na(units_gdal) || + !tolower(units_gdal) %in% c("metre", "meter")) { + stop( + "The default CRS for the selected SSA is geographic, but `resolution_m` is in meters; supply a `template` defining the target grid.", + call. = FALSE + ) + } + + invisible(NULL) +} + #' @noRd #' @keywords internal .compute_ssa_vector_bbox <- function(mu_files, ssa_list, diff --git a/man/createSSURGO.Rd b/man/createSSURGO.Rd index 32770edc..d19f10a9 100644 --- a/man/createSSURGO.Rd +++ b/man/createSSURGO.Rd @@ -91,8 +91,10 @@ only shallowest ratings for smaller database size.} \code{'FY26'}). If \code{NULL}, auto-detect from sacatalog saverest date. Allows organizing rasters by official release year or custom labels. Only used if \code{include_raster=TRUE}.} -\item{template}{Optional \code{SpatRaster} template to align with. If \code{NULL} (default), creates a standard -grid at \code{resolution_m} in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, +\item{template}{Optional \code{SpatRaster} template defining a common target CRS and grid, including +cell size, for all selected SSAs. Use a template when the selection spans regional CRSs or +when a geographic CRS is needed. If \code{NULL} (default), creates a standard grid at \code{resolution_m} +in the regional standard CRS (EPSG:5070 for CONUS, EPSG:3338 for AK, EPSG:6628 for HI, EPSG:32161 for PR/VI, EPSG:4326 for Pacific Islands) with bounds snapped according to \code{grid_alignment}.} \item{touches}{\emph{logical}. If \code{TRUE}, all cells touched by polygon boundaries are rasterized. Default @@ -105,7 +107,8 @@ target-aligned uses a zero origin; and NLCD uses the canonical WGS84 Albers origin anchor \verb{(-2415585, 3314805)}. A supplied \code{template} takes precedence.} \item{resolution_m}{\emph{numeric}. Finite positive raster cell size in meters when \code{template = NULL} -(default: \code{10}).} +and the regional CRS is projected (default: \code{10}). Meter-based rasterization with a geographic +regional CRS requires an explicit \code{template}.} \item{quiet}{\emph{logical}. Suppress messages and other output from database read/write operations?} @@ -135,7 +138,10 @@ The alignment modes are intentional: \code{gssurgo} matches official USDA-NRCS products, \code{target_aligned} follows zero-origin GDAL-style alignment, and \code{nlcd} uses the canonical WGS84 Albers origin. These choices support interoperability with federal raster products including NLCD, CDL, USGS 3DEP, -and gNATSGO. Raster output uses \code{NAflag = 0}; MUKEY zero is reserved as NoData. +and gNATSGO. A supplied template defines a common CRS and grid for all selected SSAs. Without +a template, selected SSAs must share a regional CRS. The Pacific Island default CRS (EPSG:4326) +is geographic, so meter-based rasterization there requires an explicit template. Raster output +uses \code{NAflag = 0}; MUKEY zero is reserved as NoData. A single SSURGO MUKEY per cell may be misleading at resolutions greater than 90 meters. A warning is issued for recognized SSURGO area symbols when the output grid exceeds this resolution. diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 22249f0b..34cdfd50 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -300,6 +300,39 @@ test_that("grid alignment names are independent of raster resolution", { ) }) +test_that("rasterization rejects mixed or geographic default CRSs", { + mixed_ssas <- list( + list(areasymbol = "CA067"), + list(areasymbol = "AK650") + ) + + expect_error( + .validate_ssa_raster_crs(mixed_ssas), + "different regional CRSs.*template" + ) + expect_error( + .validate_ssa_raster_crs(list(list(areasymbol = "GU600"))), + "geographic.*resolution_m.*template" + ) +}) + +test_that("a raster template allows mixed regional CRSs to share one grid", { + skip_if_not_installed("terra") + + template <- terra::rast( + xmin = 0, xmax = 300, + ymin = 0, ymax = 300, + resolution = 30, + crs = "EPSG:5070" + ) + expect_no_error( + .validate_ssa_raster_crs( + list(list(areasymbol = "CA067"), list(areasymbol = "AK650")), + template = template + ) + ) +}) + test_that("fiscal-year detection accepts both catalog filenames and date columns", { temp_root <- tempfile("soilDB-test-sacatalog-") dir.create(temp_root, recursive = TRUE) @@ -758,6 +791,11 @@ test_that("createSSURGO handles include_spatial = FALSE and include_raster = TRU geometry = sf::st_sfc(poly1, crs = 4269) ) sf::st_write(mock_sf, file.path(ssa_dir, "soilmu_a_ca067.shp"), quiet = TRUE) + sf::st_write( + sf::st_sf(areasymbol = "CA067", geometry = sf::st_sfc(poly1, crs = 4269)), + file.path(ssa_dir, "soilsa_a_ca067.shp"), + quiet = TRUE + ) db_file <- file.path(temp_root, "test.sqlite") res <- expect_no_error( @@ -778,6 +816,25 @@ test_that("createSSURGO handles include_spatial = FALSE and include_raster = TRU rp <- attr(res, "raster_paths") expect_true(!is.null(rp)) expect_equal(attr(rp, "output_raster"), normalizePath(expected_tif, winslash = "/")) + + selected_db <- file.path(temp_root, "selected.gpkg") + selected_res <- expect_no_error( + createSSURGO( + filename = selected_db, + exdir = temp_root, + include_spatial = "sapolygon", + include_tabular = FALSE, + include_raster = TRUE, + fiscal_year = "FY2026", + quiet = TRUE + ) + ) + selected_tif <- file.path(temp_root, "selected.tif") + expect_true(file.exists(selected_tif)) + expect_equal( + attr(attr(selected_res, "raster_paths"), "output_raster"), + normalizePath(selected_tif, winslash = "/") + ) }) test_that("createSSURGO warns for coarse Mexico SSURGO grids", { From f442e2fad318769946b6ac6823684a77eb837d5f Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Thu, 12 Nov 2026 22:29:35 -0800 Subject: [PATCH 3/9] fix(raster): honor template resolution for snapping and cache --- R/createSSURGO.R | 24 ++++++++++++++++++++---- tests/testthat/test-createSSURGO.R | 16 ++++++++-------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index 4244abc0..e639680c 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -1617,11 +1617,16 @@ createSSURGO <- function(filename = NULL, } else { .grid_origin(grid_alignment, resolution_m) } + resolution <- if (inherits(template, "SpatRaster")) { + terra::res(template) + } else { + c(resolution_m, resolution_m) + } .snap_extent_to_grid( xmin, xmax, ymin, ymax, origin = origin, - resolution = c(resolution_m, resolution_m) + resolution = resolution ) } @@ -1958,7 +1963,8 @@ createSSURGO <- function(filename = NULL, #' #' @param raster_obj _SpatRaster_. In-memory raster object to persist. #' @param areasymbol _character_. Soil survey area symbol (e.g., "CA067") for filename. -#' @param resolution_m _numeric_. Grid resolution in meters, used in the cache filename. +#' @param resolution_m _numeric_. Fallback grid resolution for the cache filename when the +#' raster's resolution is unavailable. #' @param cache_root _character_. Cache root directory. If NULL, defaults to #' soilDB_user_dir("cache", "raster", create=TRUE). #' @param fiscal_year _character_. Optional fiscal year label for cache path organization @@ -1985,8 +1991,18 @@ createSSURGO <- function(filename = NULL, } dir.create(cache_root, recursive = TRUE, showWarnings = FALSE) - # Construct filename - filename <- paste0("MUKEY_", resolution_m, "m_", toupper(areasymbol), ".tif") + raster_resolution <- if (inherits(raster_obj, "SpatRaster")) { + terra::res(raster_obj) + } else { + resolution_m + } + resolution_label <- if (length(raster_resolution) > 1L && + raster_resolution[1] != raster_resolution[2]) { + paste(format(raster_resolution, trim = TRUE, scientific = FALSE), collapse = "x") + } else { + format(raster_resolution[1], trim = TRUE, scientific = FALSE) + } + filename <- paste0("MUKEY_", resolution_label, "m_", toupper(areasymbol), ".tif") cache_path <- file.path(cache_root, filename) tryCatch({ diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 34cdfd50..309c7324 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -634,11 +634,11 @@ test_that(".create_ssa_raster_template with custom template preserves resolution }) # .write_raster_with_cache COG format and datatype -test_that(".write_raster_with_cache writes INT4U datatype and COG format", { +test_that(".write_raster_with_cache names output from actual resolution", { skip_on_cran() skip_if_not_installed("terra") - r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 100, ymin = 0, ymax = 100, crs = "EPSG:5070") + r <- terra::rast(nrows = 10, ncols = 10, xmin = 0, xmax = 300, ymin = 0, ymax = 300, crs = "EPSG:5070") terra::values(r) <- c(rep(1001:1050, each = 1), rep(NA, 50)) temp_dir <- tempfile("soilDB-test-cog-") @@ -648,7 +648,7 @@ test_that(".write_raster_with_cache writes INT4U datatype and COG format", { raster_obj = r, areasymbol = "CA067", cache_root = temp_dir, - resolution_m = 30, + resolution_m = 10, quiet = TRUE ) @@ -956,9 +956,9 @@ test_that("createSSURGO uses the snapped union extent for multiple SSAs", { ) custom_template <- terra::rast( - xmin = -2000005, xmax = -1990005, - ymin = 2000007, ymax = 2010007, - resolution = 10, crs = "EPSG:5070" + xmin = -2000005, xmax = -1990015, + ymin = 2000007, ymax = 2009997, + resolution = 30, crs = "EPSG:5070" ) template_origin <- terra::origin(custom_template) template_bbox <- .compute_ssa_vector_bbox( @@ -972,11 +972,11 @@ test_that("createSSURGO uses the snapped union extent for multiple SSAs", { resolution_m = 10 ) expect_equal( - as.numeric((template_bbox[c("xmin", "xmax")] - template_origin[1]) %% 10), + as.numeric((template_bbox[c("xmin", "xmax")] - template_origin[1]) %% 30), c(0, 0) ) expect_equal( - as.numeric((template_bbox[c("ymin", "ymax")] - template_origin[2]) %% 10), + as.numeric((template_bbox[c("ymin", "ymax")] - template_origin[2]) %% 30), c(0, 0) ) } From abd1d9a5f22351ccf02647785d8b18ab56a4d264 Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Thu, 12 Nov 2026 22:29:52 -0800 Subject: [PATCH 4/9] fix(raster): merge categorical tiles using first-source values --- R/createSSURGO.R | 2 +- tests/testthat/test-createSSURGO.R | 34 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index e639680c..f8e50806 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -2124,7 +2124,7 @@ createSSURGO <- function(filename = NULL, out_r <- terra::rast(paths[1]) } else { sprc <- terra::sprc(paths) - out_r <- terra::mosaic(sprc) + out_r <- terra::merge(sprc) } # If target_bbox is provided, crop output raster to exact snapped bounds diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 309c7324..22839606 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -1031,3 +1031,37 @@ test_that(".create_final_raster_output crops output raster to snapped target_bbo expect_true(any(grepl("COMPRESSION=DEFLATE", desc))) expect_true(any(grepl("NoData Value=0", desc))) }) + +test_that(".create_final_raster_output merges categorical values using the first source", { + skip_on_cran() + skip_if_not_installed("terra") + + temp_root <- tempfile("soilDB-test-modal-mosaic-") + dir.create(temp_root, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + source_values <- c(1001, 1003, 1003, 1003) + raster_paths <- lapply(seq_along(source_values), function(i) { + r <- terra::rast( + nrows = 2, ncols = 2, + xmin = 0, xmax = 20, ymin = 0, ymax = 20, + crs = "EPSG:5070" + ) + terra::values(r) <- source_values[i] + path <- file.path(temp_root, paste0("ssa", i, ".tif")) + terra::writeRaster(r, path, overwrite = TRUE) + list(areasymbol = paste0("CA00", i), path = path) + }) + + output_path <- .create_final_raster_output( + raster_paths = raster_paths, + filename = file.path(temp_root, "mosaic.tif"), + overwrite = TRUE, + quiet = TRUE + ) + + expect_true(file.exists(output_path)) + output_values <- terra::values(terra::rast(output_path)) + expect_equal(unique(as.vector(output_values)), 1001) + expect_true(all(as.vector(output_values) %in% source_values)) +}) From fe66bd5731d89bbb0ac3011f796aab5790365b78 Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Thu, 12 Nov 2026 22:30:14 -0800 Subject: [PATCH 5/9] test(raster): isolate cache state and guard optional terra --- tests/testthat/test-createSSURGO.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 22839606..4f576d9c 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -206,7 +206,7 @@ test_that(".write_raster_with_cache constructs correct cache path with fiscal_ye raster_obj = r, areasymbol = "CA067", fiscal_year = "FY2024", - cache_root = NULL, + cache_root = file.path(temp_cache_base, "WSS", "FY2024", "raster"), quiet = TRUE ) @@ -377,6 +377,8 @@ test_that("SSURGO area symbols are distinguished from STATSGO symbols", { }) test_that("coarse-grid warning applies only to SSURGO grids larger than 90m", { + skip_if_not_installed("terra") + expect_warning( .warn_if_coarse_ssurgo_raster(c("CA067"), 300), "greater than 90" From 920e2db7fcc604bf4ebcdbae55c12f2fa89b453e Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Thu, 12 Nov 2026 22:30:33 -0800 Subject: [PATCH 6/9] fix(raster): use terra configured tempdir for fallback --- R/createSSURGO.R | 7 +++--- tests/testthat/test-createSSURGO.R | 36 ++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index f8e50806..d373e6ba 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -1958,8 +1958,8 @@ createSSURGO <- function(filename = NULL, #' Write SpatRaster to Cache with terra Fallback #' #' @description `.write_raster_with_cache()`: Write in-memory SpatRaster to disk cache -#' using soilDB user directory pattern. Falls back to terra::tmpdir() if primary -#' cache write fails. +#' using soilDB user directory pattern. Falls back to the directory configured by +#' `terra::terraOptions()` if the primary cache write fails. #' #' @param raster_obj _SpatRaster_. In-memory raster object to persist. #' @param areasymbol _character_. Soil survey area symbol (e.g., "CA067") for filename. @@ -2023,7 +2023,8 @@ createSSURGO <- function(filename = NULL, }, error = function(e) { # Fallback: write to temporary directory - tmpdir <- terra::tmpdir() + tmpdir <- terra::terraOptions(print = FALSE)$tempdir + dir.create(tmpdir, recursive = TRUE, showWarnings = FALSE) tmppath <- file.path(tmpdir, filename) tryCatch({ diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 4f576d9c..3a625fae 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -247,6 +247,42 @@ test_that(".write_raster_with_cache creates nested WSS cache structure", { expect_true(grepl("FY2024.*raster", raster_path)) }) +test_that(".write_raster_with_cache falls back to terra's configured tempdir", { + skip_on_cran() + skip_if_not_installed("terra") + + temp_root <- tempfile("soilDB-test-raster-fallback-") + dir.create(temp_root, recursive = TRUE) + on.exit(try(unlink(temp_root, recursive = TRUE), silent = TRUE), add = TRUE) + + old_tempdir <- terra::terraOptions(print = FALSE)$tempdir + on.exit(terra::terraOptions(tempdir = old_tempdir, print = FALSE), add = TRUE) + fallback_dir <- file.path(temp_root, "terra-temp") + dir.create(fallback_dir) + terra::terraOptions(tempdir = fallback_dir, print = FALSE) + + r <- terra::rast(nrows = 2, ncols = 2, xmin = 0, xmax = 20, ymin = 0, ymax = 20) + terra::values(r) <- 1001 + blocked_cache <- file.path(temp_root, "cache-file") + writeLines("", blocked_cache) + + fallback_path <- expect_warning( + .write_raster_with_cache( + raster_obj = r, + areasymbol = "CA067", + cache_root = blocked_cache, + quiet = TRUE + ), + "Cache directory unavailable" + ) + + expect_true(file.exists(fallback_path)) + expect_equal( + normalizePath(dirname(fallback_path)), + normalizePath(fallback_dir) + ) +}) + # .resolve_ssa_crs resolves standard CRS correctly for various SSA regions test_that(".resolve_ssa_crs resolves CRS correctly by region prefix and grid_alignment", { # CONUS From 28d45d5ecc27c2eb9be599d37eb5f63a2d3c0834 Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Fri, 13 Nov 2026 10:22:24 -0800 Subject: [PATCH 7/9] fix(raster): drop unsupported COG tiling option --- R/createSSURGO.R | 2 +- tests/testthat/test-createSSURGO.R | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index d373e6ba..1ba0b9d5 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -1513,7 +1513,7 @@ createSSURGO <- function(filename = NULL, datatype = "INT4U", NAflag = 0, filetype = "COG", - gdal = c("COMPRESS=DEFLATE", "TILED=YES", "BIGTIFF=IF_SAFER") + gdal = c("COMPRESS=DEFLATE", "BIGTIFF=IF_SAFER") ) } #' Resolve Standard CRS for Soil Survey Area diff --git a/tests/testthat/test-createSSURGO.R b/tests/testthat/test-createSSURGO.R index 3a625fae..7985e112 100644 --- a/tests/testthat/test-createSSURGO.R +++ b/tests/testthat/test-createSSURGO.R @@ -202,12 +202,14 @@ test_that(".write_raster_with_cache constructs correct cache path with fiscal_ye }, add = TRUE) # Test with fiscal_year specified - result <- .write_raster_with_cache( - raster_obj = r, - areasymbol = "CA067", - fiscal_year = "FY2024", - cache_root = file.path(temp_cache_base, "WSS", "FY2024", "raster"), - quiet = TRUE + result <- expect_no_warning( + .write_raster_with_cache( + raster_obj = r, + areasymbol = "CA067", + fiscal_year = "FY2024", + cache_root = file.path(temp_cache_base, "WSS", "FY2024", "raster"), + quiet = TRUE + ) ) # Result should contain the fiscal year in path From eb428bab7590b0b6a35128fab11faa1d82880380 Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Fri, 13 Nov 2026 10:25:18 -0800 Subject: [PATCH 8/9] fix(raster): avoid MEM driver COG option warnings --- R/createSSURGO.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index 1ba0b9d5..4d6d26a9 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -1513,7 +1513,9 @@ createSSURGO <- function(filename = NULL, datatype = "INT4U", NAflag = 0, filetype = "COG", - gdal = c("COMPRESS=DEFLATE", "BIGTIFF=IF_SAFER") + gdal = c("COMPRESS=DEFLATE", "BIGTIFF=IF_SAFER"), + # Avoid passing COG creation options to Terra's in-memory MEM staging driver. + todisk = TRUE ) } #' Resolve Standard CRS for Soil Survey Area From 9490d7a0e4501cef9f63f9585575f1855fd08a02 Mon Sep 17 00:00:00 2001 From: Andrew Gene Brown Date: Wed, 18 Nov 2026 07:44:32 -0800 Subject: [PATCH 9/9] fix(createSSURGO): tabular overwrite logic --- R/createSSURGO.R | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/R/createSSURGO.R b/R/createSSURGO.R index 4d6d26a9..421fd876 100644 --- a/R/createSSURGO.R +++ b/R/createSSURGO.R @@ -870,18 +870,14 @@ createSSURGO <- function(filename = NULL, append_arg <- FALSE overwrite_arg <- overwrite - if (!table_exists || !isTRUE(table_initialized)) { - append_arg <- FALSE - overwrite_arg <- table_exists || overwrite - } else if (isTRUE(append)) { + if (table_exists && (isTRUE(append) || isTRUE(table_initialized))) { + # append to existing data, including tables already written for an earlier SSA in this run append_arg <- TRUE overwrite_arg <- FALSE - } else if (isTRUE(overwrite)) { - append_arg <- FALSE - overwrite_arg <- TRUE } else { - append_arg <- TRUE - overwrite_arg <- FALSE + # first write of this table in this run: create (replacing if overwrite is set) + append_arg <- FALSE + overwrite_arg <- table_exists || overwrite } rec <- .write_table_with_log(