| Title: | Bioclimatic Variables from Monthly Climate Data |
|---|---|
| Description: | Computes the 19 standard bioclimatic variables (BIO01-BIO19) from monthly climate data. The variable set was originally proposed by Nix (1986, ISBN:978-0-644-04887-3) for the BIOCLIM modelling system and is also distributed with the CHELSA climatologies (Karger et al., 2017 <doi:10.1038/sdata.2017.122>). Provides both individual variable functions and a unified interface to compute all 19 variables at once. Designed as an R implementation of the 'xbioclim' C++ library (Robles Fernandez, 2026 <https://github.com/alrobles/xbioclimcpp>). Supports single-pixel vectors and block-based raster processing via 'terra' for memory-efficient handling of large spatial datasets. Includes helpers to transform ERA5-Land hourly reanalysis data (Muñoz-Sabater et al., 2021 <doi:10.5194/essd-13-4349-2021>) into monthly climate inputs. |
| Authors: | Angel Luis Robles Fernandez [aut, cre] |
| Maintainer: | Angel Luis Robles Fernandez <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.3 |
| Built: | 2026-10-07 09:18:13 UTC |
| Source: | https://github.com/alrobles/xbioclim |
Computes the 19 standard bioclimatic variables (BIO01-BIO19) from monthly climate data following the WorldClim specification. This is an R implementation of the xbioclim C++ library, with a compiled C++ back-end exposed through Rcpp Modules.
No return value; package-level documentation.
In addition to the BIO01–BIO19 computation, xbioclim provides helpers to
aggregate ERA5-Land hourly t2m/tp into the CHELSA-compatible monthly
variables (tas, tasmax, tasmin, pr) used by the bioclim functions:
era5_to_monthly() – single-pass hourly → monthly aggregation.
era5_t2m_to_monthly() / era5_tp_to_monthly() – variable-specific helpers.
era5_bioclim() / era5_bioclim_years() – end-to-end ERA5-Land → BIO pipeline.
xbioclim mirrors the SpatMessages pattern used by the terra package.
C++ routines record errors and warnings into an internal message store
rather than throwing directly. R-side wrappers around C++ calls should
invoke check_messages() after each call to convert any stored messages
into native R conditions. Users can also inspect the store
programmatically:
bioclim_errors() / bioclim_warnings() – retrieve stored messages.
has_error() / has_warning() – test whether messages exist.
clear_messages() – reset the store.
Maintainer: Angel Luis Robles Fernandez [email protected]
Authors:
Angel Luis Robles Fernandez [email protected]
Useful links:
Report bugs at https://github.com/alrobles/xbioclim/issues
Reads input_path and mask_path tile-by-tile (one row at a
time) and writes the result to output_path. Pixels where the mask
equals 0 are replaced with NaN in the output; all other
pixels retain their original values (with any GDAL scale/offset applied).
apply_mask_cpp(input_path, mask_path, output_path)apply_mask_cpp(input_path, mask_path, output_path)
input_path |
Character string: path to a GDAL-readable raster (any number of bands). |
mask_path |
Character string: path to a single-band |
output_path |
Character string: file path where the output
|
This function is the low-level C++ entry point. Most users should call
the higher-level create_mask wrapper instead.
Stops with an informative error if the package was built without GDAL support or if the mask and input dimensions differ.
Invisibly returns NULL. The side effect is the creation
of the masked raster at output_path.
create_mask, rasterize_mask_cpp
if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") mask <- tempfile(fileext = ".tif") output <- tempfile(fileext = ".tif") writeLines( '{"type":"FeatureCollection","features":[{"type":"Feature", "geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}, "properties":{}}]}', poly) rasterize_mask_cpp(poly, ref, mask) apply_mask_cpp(ref, mask, output) }if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") mask <- tempfile(fileext = ".tif") output <- tempfile(fileext = ".tif") writeLines( '{"type":"FeatureCollection","features":[{"type":"Feature", "geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}, "properties":{}}]}', poly) rasterize_mask_cpp(poly, ref, mask) apply_mask_cpp(ref, mask, output) }
A convenience wrapper around the C++ ClimateBlock class exposed by
the bioclim_mod Rcpp module. Accepts the same four monthly climate
vectors as bioclim but delegates the computation to the
compiled C++ back-end via Rcpp.
bioclim_block(tas, tasmax, tasmin, pr)bioclim_block(tas, tasmax, tasmin, pr)
tas |
Numeric vector of length 12: monthly mean temperature. |
tasmax |
Numeric vector of length 12: monthly maximum temperature. |
tasmin |
Numeric vector of length 12: monthly minimum temperature. |
pr |
Numeric vector of length 12: monthly precipitation. |
A named numeric vector of length 19 (bio01 through
bio19), identical in meaning to the output of
bioclim.
tas <- c(5, 7, 10, 14, 18, 22, 25, 24, 20, 15, 10, 6) tasmax <- c(8, 10, 14, 18, 23, 28, 32, 31, 26, 19, 13, 9) tasmin <- c(1, 3, 6, 10, 13, 17, 20, 19, 15, 10, 6, 2) pr <- c(60, 55, 50, 40, 30, 15, 5, 10, 25, 45, 55, 65) bioclim_block(tas, tasmax, tasmin, pr)tas <- c(5, 7, 10, 14, 18, 22, 25, 24, 20, 15, 10, 6) tasmax <- c(8, 10, 14, 18, 23, 28, 32, 31, 26, 19, 13, 9) tasmin <- c(1, 3, 6, 10, 13, 17, 20, 19, 15, 10, 6, 2) pr <- c(60, 55, 50, 40, 30, 15, 5, 10, 25, 45, 55, 65) bioclim_block(tas, tasmax, tasmin, pr)
High-level R interface to the BioclimEngine C++ tiled computation
pipeline. Reads four sets of monthly climate rasters (mean temperature,
maximum temperature, minimum temperature, and precipitation) from disk,
computes the requested bioclimatic variables, and writes all 19 variables
to a single multi-band GeoTIFF named bio.tif inside the output
directory — one tile at a time so that peak memory is proportional to
tile_size, not the full raster extent.
bioclim_engine( tas, tasmax, tasmin, pr, output = tempfile("bioclim_"), variables = 1:19, mask = NULL, threads = 1L, tile_size = 256L, overwrite = FALSE, device = c("auto", "cpu", "gpu"), dtype = c("Float64", "Float32"), use_pipeline = FALSE )bioclim_engine( tas, tasmax, tasmin, pr, output = tempfile("bioclim_"), variables = 1:19, mask = NULL, threads = 1L, tile_size = 256L, overwrite = FALSE, device = c("auto", "cpu", "gpu"), dtype = c("Float64", "Float32"), use_pipeline = FALSE )
tas |
Character vector of length 1 (12-band file) or 12 (one file per
month), or a |
tasmax |
Like |
tasmin |
Like |
pr |
Like |
output |
Character string: path to the output directory where the
multi-band GeoTIFF |
variables |
Integer vector of variable numbers to compute, with
values in |
mask |
Optional mask: a character file path, an |
threads |
Positive integer: number of OpenMP threads to use. Default
is |
tile_size |
Positive integer: tile dimension (pixels) for tiled I/O.
Default is |
overwrite |
Logical: whether to overwrite an existing |
device |
Character scalar: compute device to use. One of
|
dtype |
Character scalar: output data type, one of |
use_pipeline |
Logical scalar: if |
GDAL requirement. This function requires the package to have been
compiled with GDAL support (see has_gdal). If GDAL is not
available an informative error is raised immediately.
Variable selection. By default all 19 standard bioclimatic variables
(BIO01–BIO19) are returned. Pass variables as an integer vector
(e.g. c(1, 12, 15)) to restrict the returned
terra::SpatRaster to a subset. The engine always computes all 19
internally and writes a full 19-band bio.tif; the subsetting is
applied when constructing the returned object.
Single multi-band output. The output directory contains one file,
bio.tif, with 19 bands (BIO01–BIO19). This reduces GDAL I/O call
overhead compared with the previous one-file-per-variable layout.
Tiled processing. The engine reads and writes rasters in square tiles of
tile_size × tile_size pixels. Choosing a large tile improves
I/O efficiency; a small tile reduces peak RAM. The default (256) is a
good balance for most use cases.
Multi-band vs. single-band inputs. Each climate variable can be
supplied either as twelve single-band files (one per calendar month) or as
one multi-band file with exactly 12 bands. A terra::SpatRaster with
12 layers is also accepted; its on-disk source paths are extracted
automatically via terra::sources().
Mask support. An optional raster or vector mask can be used to restrict
computation to a specific region. Pixels outside the mask are written as
NaN. Accepted formats:
character — path to any GDAL-readable raster or OGR vector.
sf object — written to a temporary GeoJSON and rasterized.
terra::SpatRaster — written to a temporary GeoTIFF.
Output data type. Use dtype = "Float32" to halve the output file
size. Values are rounded from double-precision internal arithmetic to
single precision on write; numerical differences are typically below
1e-5.
Output. If terra is installed the function returns a
terra::SpatRaster whose layers correspond to the selected variables.
Otherwise it returns the path to the output bio.tif file.
If terra is installed, a terra::SpatRaster with one
layer per selected variable (named bio01 … bio19).
Otherwise a character scalar: the path to bio.tif.
bioclim_raster for the in-memory R/terra path,
has_gdal to check GDAL availability,
engine_create for the low-level XPtr interface.
if (has_gdal() && requireNamespace("terra", quietly = TRUE)) { library(terra) # Create tiny synthetic climate rasters (10x10 pixels, 12 layers each) make_rast <- function(vals, file) { r <- rast(nrows = 10, ncols = 10, nlyrs = 12, xmin = 0, xmax = 1, ymin = 0, ymax = 1, crs = "EPSG:4326") for (m in seq_len(12)) values(r[[m]]) <- vals[m] writeRaster(r, file, overwrite = TRUE) file } tmp <- tempdir() tas_file <- make_rast(c(5,7,10,14,18,22,25,24,20,15,10,6), file.path(tmp, "tas.tif")) tasmax_file <- make_rast(c(8,10,14,18,23,28,32,31,26,19,13,9), file.path(tmp, "tasmax.tif")) tasmin_file <- make_rast(c(1,3,6,10,13,17,20,19,15,10,6,2), file.path(tmp, "tasmin.tif")) pr_file <- make_rast(c(60,55,48,35,28,22,18,20,35,55,65,68), file.path(tmp, "pr.tif")) # Compute all 19 variables (single multi-band output file) out_dir <- file.path(tmp, "bioclim_out") result <- bioclim_engine(tas_file, tasmax_file, tasmin_file, pr_file, output = out_dir, overwrite = TRUE) nlyr(result) # 19 list.files(out_dir, pattern = "[.]tif$") # Compute only BIO01 and BIO12 out_dir2 <- file.path(tmp, "bioclim_subset") result2 <- bioclim_engine(tas_file, tasmax_file, tasmin_file, pr_file, output = out_dir2, variables = c(1L, 12L), overwrite = TRUE) nlyr(result2) # 2 names(result2) # "bio01" "bio12" }if (has_gdal() && requireNamespace("terra", quietly = TRUE)) { library(terra) # Create tiny synthetic climate rasters (10x10 pixels, 12 layers each) make_rast <- function(vals, file) { r <- rast(nrows = 10, ncols = 10, nlyrs = 12, xmin = 0, xmax = 1, ymin = 0, ymax = 1, crs = "EPSG:4326") for (m in seq_len(12)) values(r[[m]]) <- vals[m] writeRaster(r, file, overwrite = TRUE) file } tmp <- tempdir() tas_file <- make_rast(c(5,7,10,14,18,22,25,24,20,15,10,6), file.path(tmp, "tas.tif")) tasmax_file <- make_rast(c(8,10,14,18,23,28,32,31,26,19,13,9), file.path(tmp, "tasmax.tif")) tasmin_file <- make_rast(c(1,3,6,10,13,17,20,19,15,10,6,2), file.path(tmp, "tasmin.tif")) pr_file <- make_rast(c(60,55,48,35,28,22,18,20,35,55,65,68), file.path(tmp, "pr.tif")) # Compute all 19 variables (single multi-band output file) out_dir <- file.path(tmp, "bioclim_out") result <- bioclim_engine(tas_file, tasmax_file, tasmin_file, pr_file, output = out_dir, overwrite = TRUE) nlyr(result) # 19 list.files(out_dir, pattern = "[.]tif$") # Compute only BIO01 and BIO12 out_dir2 <- file.path(tmp, "bioclim_subset") result2 <- bioclim_engine(tas_file, tasmax_file, tasmin_file, pr_file, output = out_dir2, variables = c(1L, 12L), overwrite = TRUE) nlyr(result2) # 2 names(result2) # "bio01" "bio12" }
Returns the character vector of error messages currently held in the
xbioclim message store. Under normal usage the store is automatically
flushed by check_messages() after every C++ call, but you can inspect it
manually before that point if needed.
bioclim_errors()bioclim_errors()
A character vector (possibly empty).
bioclim_warnings(), has_error(), clear_messages()
clear_messages() bioclim_errors() # character(0)clear_messages() bioclim_errors() # character(0)
Computes the 19 standard bioclimatic variables (BIO01-BIO19) from monthly climate raster data (SpatRaster objects with 12 layers, one per month) using terra's block-loop architecture for memory-efficient processing.
bioclim_raster( tas, tasmax, tasmin, pr, filename = "", n_blocks = NULL, ncores = 1L, overwrite = FALSE, ... )bioclim_raster( tas, tasmax, tasmin, pr, filename = "", n_blocks = NULL, ncores = 1L, overwrite = FALSE, ... )
tas |
SpatRaster with 12 layers: monthly mean temperature. |
tasmax |
SpatRaster with 12 layers: monthly maximum temperature. |
tasmin |
SpatRaster with 12 layers: monthly minimum temperature. |
pr |
SpatRaster with 12 layers: monthly precipitation. |
filename |
Character string: output file path. Pass |
n_blocks |
Integer: target number of row blocks. If |
ncores |
Integer: number of CPU cores for within-block parallel
processing via OpenMP. Default is |
overwrite |
Logical: whether to overwrite an existing output file.
Default is |
... |
Additional arguments passed to |
This function follows terra's block-loop pattern: the input rasters are read
one horizontal block at a time (using terra::readStart(),
terra::readValues(), and terra::readStop()), keeping peak memory use
proportional to the block size rather than the full raster extent. Results
are written to the output raster block by block (using
terra::writeStart(), terra::writeValues(), and terra::writeStop()).
When ncores > 1, pixels within each block are processed in parallel using
OpenMP threads via bioclim_cpp(). Only one block is held in memory at a
time regardless of the number of threads.
A SpatRaster with 19 layers named bio01 through
bio19, sharing the spatial extent, resolution and CRS of tas.
bioclim() for single-pixel (vector) computation.
library(terra) # Create small test rasters: 4 rows x 3 cols, 12 monthly layers make_rast <- function(vals) { r <- rast(nrows = 4, ncols = 3, nlyr = 12) values(r) <- vals r } n <- 4 * 3 # number of cells tas <- make_rast(matrix(rep(1:12, each = n), nrow = n, ncol = 12)) tasmax <- make_rast(matrix(rep(2:13, each = n), nrow = n, ncol = 12)) tasmin <- make_rast(matrix(rep(0:11, each = n), nrow = n, ncol = 12)) pr <- make_rast(matrix(rep(1:12, each = n), nrow = n, ncol = 12)) # Compute all 19 bioclimatic variables in a single pass result <- bioclim_raster(tas, tasmax, tasmin, pr) nlyr(result) # 19library(terra) # Create small test rasters: 4 rows x 3 cols, 12 monthly layers make_rast <- function(vals) { r <- rast(nrows = 4, ncols = 3, nlyr = 12) values(r) <- vals r } n <- 4 * 3 # number of cells tas <- make_rast(matrix(rep(1:12, each = n), nrow = n, ncol = 12)) tasmax <- make_rast(matrix(rep(2:13, each = n), nrow = n, ncol = 12)) tasmin <- make_rast(matrix(rep(0:11, each = n), nrow = n, ncol = 12)) pr <- make_rast(matrix(rep(1:12, each = n), nrow = n, ncol = 12)) # Compute all 19 bioclimatic variables in a single pass result <- bioclim_raster(tas, tasmax, tasmin, pr) nlyr(result) # 19
Computes the 19 bioclimatic variables using a rolling window of arbitrary
length over the full 12 months. The base variables (bio01..bio07,
bio12..bio15) are annual, while the rolling variables
(bio08..bio11, bio16..bio19) use the best window-month period.
With window = 3 this is equivalent to the standard BIO08-BIO19.
bioclim_rolling(tas, tasmax, tasmin, pr, window = 3L, na.rm = FALSE, ...)bioclim_rolling(tas, tasmax, tasmin, pr, window = 3L, na.rm = FALSE, ...)
tas |
Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData. |
tasmax |
Same form as |
tasmin |
Same form as |
pr |
Same form as |
window |
Integer: length of the rolling window in months (2-11). Default is 3. |
na.rm |
Logical. If |
... |
Not currently used. |
Named vector (length 19), matrix (pixels x 19), or 19-layer SpatRaster.
Returns the character vector of warning messages currently held in the
xbioclim message store. Under normal usage the store is automatically
flushed by check_messages() after every C++ call, but you can inspect it
manually before that point if needed.
bioclim_warnings()bioclim_warnings()
A character vector (possibly empty).
bioclim_errors(), has_warning(), clear_messages()
clear_messages() bioclim_warnings() # character(0)clear_messages() bioclim_warnings() # character(0)
Computes the 19 standard bioclimatic variables over a user-defined subset of months. This is useful when a species' relevant season does not coincide with fixed quarters (e.g. eBird Status & Trends breeding windows).
bioclim_window( tas, tasmax, tasmin, pr, months = NULL, start = NULL, end = NULL, window = 3L, na.rm = FALSE, ... )bioclim_window( tas, tasmax, tasmin, pr, months = NULL, start = NULL, end = NULL, window = 3L, na.rm = FALSE, ... )
tas |
Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData. |
tasmax |
Same form as |
tasmin |
Same form as |
pr |
Same form as |
months |
Integer vector of 1-based months in the window, e.g.
|
start, end
|
Optional character strings in |
window |
Integer: length of the internal rolling sub-window used
to compute |
na.rm |
Logical. If |
... |
Not currently used. |
The base variables (bio01..bio07, bio12..bio15) are computed
directly over the selected months. The rolling variables
(bio08..bio11, bio16..bio19) are computed over the best
contiguous window-month period that is fully contained in months.
If length(months) < window or no such contiguous period exists,
those columns are NA.
Vector input: a named numeric vector of length 19 (bio01..bio19).
Matrix / BioclimData input: a numeric matrix (pixels x 19).
SpatRaster input: a 19-layer SpatRaster.
bioclim_rolling() for rolling optimal windows over the full
year with a free window length.
Functions for computing bioclimatic variables from monthly climate rasters (SpatRaster objects) using terra's block-loop architecture for memory-efficient processing of large rasters.
No return value; this is an overview page. bioclim_raster()
returns a SpatRaster with 19 layers named bio01 through
bio19.
Computes the 19 standard bioclimatic variables (BIO01-BIO19) from monthly climate data following the WorldClim specification. This is an R implementation of the xbioclim C++ library.
bio01(tas, ...) bio02(tasmax, tasmin, ...) bio03(tasmax, tasmin, ...) bio04(tas, ...) bio05(tasmax, ...) bio06(tasmin, ...) bio07(tasmax, tasmin, ...) bio08(tas, pr, ...) bio09(tas, pr, ...) bio10(tas, ...) bio11(tas, ...) bio12(pr, ...) bio13(pr, ...) bio14(pr, ...) bio15(pr, ...) bio16(pr, ...) bio17(pr, ...) bio18(tas, pr, ...) bio19(tas, pr, ...) bioclim(tas, tasmax, tasmin, pr, ...)bio01(tas, ...) bio02(tasmax, tasmin, ...) bio03(tasmax, tasmin, ...) bio04(tas, ...) bio05(tasmax, ...) bio06(tasmin, ...) bio07(tasmax, tasmin, ...) bio08(tas, pr, ...) bio09(tas, pr, ...) bio10(tas, ...) bio11(tas, ...) bio12(pr, ...) bio13(pr, ...) bio14(pr, ...) bio15(pr, ...) bio16(pr, ...) bio17(pr, ...) bio18(tas, pr, ...) bio19(tas, pr, ...) bioclim(tas, tasmax, tasmin, pr, ...)
tas |
Numeric vector of length 12 or BioclimData: monthly mean temperature. |
... |
Additional arguments. For BioclimData inputs the
argument |
tasmax |
Numeric vector of length 12: monthly maximum temperature. |
tasmin |
Numeric vector of length 12: monthly minimum temperature. |
pr |
Numeric vector of length 12: monthly precipitation. |
The 19 bioclimatic variables are:
BIO01: Mean Annual Temperature
BIO02: Mean Diurnal Range (mean of monthly (tasmax - tasmin))
BIO03: Isothermality (100 * BIO02 / BIO07)
BIO04: Temperature Seasonality (100 * population SD of monthly tas)
BIO05: Max Temperature of Warmest Month
BIO06: Min Temperature of Coldest Month
BIO07: Temperature Annual Range (BIO05 - BIO06)
BIO08: Mean Temperature of Wettest Quarter
BIO09: Mean Temperature of Driest Quarter
BIO10: Mean Temperature of Warmest Quarter
BIO11: Mean Temperature of Coldest Quarter
BIO12: Annual Precipitation
BIO13: Precipitation of Wettest Month
BIO14: Precipitation of Driest Month
BIO15: Precipitation Seasonality (CV)
BIO16: Precipitation of Wettest Quarter
BIO17: Precipitation of Driest Quarter
BIO18: Precipitation of Warmest Quarter
BIO19: Precipitation of Coldest Quarter
All functions accept either plain numeric vectors of length 12 (single pixel) or a BioclimData object holding a raster block (multiple pixels). When a BioclimData object is supplied, computation is delegated to the compiled C++ backend (xbioclim) and a numeric vector (one value per pixel) is returned.
For bio01–bio19 with plain numeric-vector inputs: a single numeric
value.
For bioclim() with plain numeric-vector inputs: a named numeric vector
of length 19 (names bio01–bio19).
For BioclimData inputs to bio01–bio19: a numeric vector with
one value per pixel.
For BioclimData inputs to bioclim(): a numeric matrix with one
row per pixel and 19 named columns (bio01–bio19).
Constructs a BioclimData object from monthly climate data. Plain numeric vectors of length 12 are automatically coerced to 1-row matrices so that single-pixel and raster-block inputs are handled uniformly.
BioclimData(tas, tasmax, tasmin, pr)BioclimData(tas, tasmax, tasmin, pr)
tas |
Numeric vector (length 12) or matrix (pixels × 12): monthly mean temperature. |
tasmax |
Numeric vector (length 12) or matrix (pixels × 12): monthly maximum temperature. |
tasmin |
Numeric vector (length 12) or matrix (pixels × 12): monthly minimum temperature. |
pr |
Numeric vector (length 12) or matrix (pixels × 12): monthly precipitation. |
A BioclimData object.
tas <- 1:12 tasmax <- 2:13 tasmin <- 0:11 pr <- 1:12 bd <- BioclimData(tas, tasmax, tasmin, pr) bdtas <- 1:12 tasmax <- 2:13 tasmin <- 0:11 pr <- 1:12 bd <- BioclimData(tas, tasmax, tasmin, pr) bd
Holds monthly climate data for one or more pixels (a raster block) and exposes S4 methods for computing each of the 19 standard bioclimatic variables as well as the full batch computation. Each slot is a numeric matrix with 12 columns (one per calendar month) and one row per pixel; single-pixel inputs (plain numeric vectors of length 12) are automatically promoted to 1-row matrices by the constructor.
The S4 methods delegate to the compiled C++ routines exported by the
package (e.g. bio01_cpp, bioclim_cpp), mirroring the xbioclim
convention for all 19 variables.
An S4 object of class BioclimData holding four numeric matrices
(tas, tasmax, tasmin, pr), each with 12 columns (one per calendar
month) and one row per pixel.
tasNumeric matrix (pixels × 12): monthly mean temperature.
tasmaxNumeric matrix (pixels × 12): monthly maximum temperature.
tasminNumeric matrix (pixels × 12): monthly minimum temperature.
prNumeric matrix (pixels × 12): monthly precipitation.
Constructs a BioclimModel-class S4 object backed by a C++
BioclimModel instance. The four monthly climate arrays are validated
and passed to the C++ object; all bioclimatic variable computations delegate
to that object via Rcpp.
BioclimModel(tas, tasmax, tasmin, pr)BioclimModel(tas, tasmax, tasmin, pr)
tas |
Numeric vector of length 12: monthly mean temperature. |
tasmax |
Numeric vector of length 12: monthly maximum temperature. |
tasmin |
Numeric vector of length 12: monthly minimum temperature. |
pr |
Numeric vector of length 12: monthly precipitation. |
A BioclimModel-class object.
tas <- 1:12 tasmax <- 2:13 tasmin <- 0:11 pr <- 1:12 m <- BioclimModel(tas, tasmax, tasmin, pr) bio01(m) bioclim(m)tas <- 1:12 tasmax <- 2:13 tasmin <- 0:11 pr <- 1:12 m <- BioclimModel(tas, tasmax, tasmin, pr) bio01(m) bioclim(m)
An S4 class that wraps a C++ BioclimModel object via an opaque
external pointer handle, following the terra package pattern for C++ object
handles. All 19 bioclimatic variable computations are delegated to the
underlying C++ object via Rcpp.
An S4 object of class BioclimModel wrapping a C++
BioclimModel instance via an externalptr handle in slot
pntr.
pntrAn externalptr to the underlying C++ BioclimModel
object.
S4 method implementations for all 19 bioclimatic variable functions and
bioclim that dispatch to the underlying C++ object via Rcpp when
the first argument is a BioclimModel-class instance.
For bio01–bio19: a single numeric value with the
corresponding bioclimatic variable computed from the monthly climate
data stored in the object. For bioclim: a named numeric vector of
length 19 (bio01 through bio19).
Discards all error and warning messages currently held in the xbioclim
message store. This is called automatically by check_messages() after
propagating messages to R conditions, but you can call it manually to reset
state between operations.
clear_messages()clear_messages()
Invisible NULL.
bioclim_errors(), bioclim_warnings()
clear_messages() has_error() # FALSE has_warning() # FALSEclear_messages() has_error() # FALSE has_warning() # FALSE
An Rcpp module class exposing the C++ ClimateBlock implementation of
the xbioclim library. Accepts four n_pixels x 12 matrices of monthly
climate data and computes all 19 bioclimatic variables for each pixel via a
compiled C++ back-end.
ClimateBlock is loaded into the package namespace when the package
is attached (via loadModule in .onLoad).
new(ClimateBlock, tas, tasmax, tasmin, pr) returns an Rcpp
module object of class ClimateBlock. Its $n_pixels() method
returns a single integer and its $compute() method returns an
n_pixels x 19 numeric matrix with columns named bio01
through bio19.
new(ClimateBlock, tas, tasmax, tasmin, pr)
tasNumeric matrix of dimensions n_pixels x 12:
monthly mean temperature for each pixel.
tasmaxNumeric matrix of dimensions n_pixels x 12:
monthly maximum temperature for each pixel.
tasminNumeric matrix of dimensions n_pixels x 12:
monthly minimum temperature for each pixel.
prNumeric matrix of dimensions n_pixels x 12:
monthly precipitation for each pixel.
All four matrices must have exactly 12 columns and the same number of rows.
n_pixels()Returns the number of pixels (integer).
compute()Computes the 19 bioclimatic variables for all
pixels and returns an n_pixels x 19 numeric matrix with columns
named bio01 through bio19.
tas <- matrix(rep(1:12, 3), nrow = 3, byrow = TRUE) tasmax <- tas + 1 tasmin <- tas - 1 pr <- matrix(rep(1:12, 3), nrow = 3, byrow = TRUE) block <- new(ClimateBlock, tas, tasmax, tasmin, pr) block$n_pixels() # 3 result <- block$compute() # 3 x 19 matrixtas <- matrix(rep(1:12, 3), nrow = 3, byrow = TRUE) tasmax <- tas + 1 tasmin <- tas - 1 pr <- matrix(rep(1:12, 3), nrow = 3, byrow = TRUE) block <- new(ClimateBlock, tas, tasmax, tasmin, pr) block$n_pixels() # 3 result <- block$compute() # 3 x 19 matrix
Converts a polygon source to a binary raster mask aligned to a reference
raster, and optionally applies that mask to an input raster (replacing
pixels outside all polygons with NA).
create_mask( polygon, reference_raster = NULL, output = tempfile(fileext = ".tif"), apply_to = NULL, apply_output = tempfile(fileext = ".tif") )create_mask( polygon, reference_raster = NULL, output = tempfile(fileext = ".tif"), apply_to = NULL, apply_output = tempfile(fileext = ".tif") )
polygon |
Polygon source: an |
reference_raster |
Character string: path to a GDAL-readable raster
used to set the spatial reference (extent, resolution, CRS) of the
output mask. Ignored when |
output |
Character string: file path for the output mask GeoTIFF. Defaults to a temporary file. |
apply_to |
Character string or |
apply_output |
Character string: file path for the masked output
raster. Used only when |
The function accepts three types of polygon input:
sf objectWritten to a temporary GeoJSON file via
sf::st_write() and then rasterized.
Requires the sf package.
Passed directly to the C++ rasterizer. Any OGR-readable format is supported (shapefile, GeoJSON, GeoPackage, etc.).
SpatRaster objectUsed directly as a pre-made mask raster.
Must already be binary (0/1) and aligned to reference_raster.
Requires the terra package.
All GDAL-dependent operations skip gracefully (returning NULL invisibly
with a message) when the package was built without GDAL support.
When apply_to is NULL, returns the path to the binary mask
GeoTIFF invisibly. When apply_to is provided, returns the path to the
masked output raster invisibly.
rasterize_mask_cpp(), apply_mask_cpp()
if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") writeLines( paste0( '{"type":"FeatureCollection","features":[{"type":"Feature",', '"geometry":{"type":"Polygon",', '"coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]},', '"properties":{}}]}' ), poly ) mask_path <- create_mask(poly, ref) }if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") writeLines( paste0( '{"type":"FeatureCollection","features":[{"type":"Feature",', '"geometry":{"type":"Polygon",', '"coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]},', '"properties":{}}]}' ), poly ) mask_path <- create_mask(poly, ref) }
Returns the number of CUDA-capable GPUs available on this machine.
Returns 0 when the package was built without CUDA support or when
no CUDA-capable device is found.
cuda_device_count()cuda_device_count()
Non-negative integer: number of CUDA devices detected.
Returns a named list with hardware information about the first CUDA-capable GPU. Returns an empty list when no CUDA device is available or when the package was built without CUDA.
cuda_device_info()cuda_device_info()
Named list with:
Character: GPU model name.
Numeric: total global memory in gigabytes.
Character: e.g. "8.0" for A100.
An empty list when no CUDA device is detected.
Returns hardware information about the first CUDA-capable GPU detected on this machine.
cuda_info()cuda_info()
A named list with name (character GPU model name),
memory_gb (numeric total memory in GB), and
compute_capability (character, e.g. "8.0" for A100).
Returns an empty list when no CUDA device is available.
cuda_info()cuda_info()
Reads all monthly climate input rasters tile by tile, computes the
bioclimatic variables for every pixel, and writes all 19 variables to a
single multi-band GeoTIFF named bio.tif inside the output
directory. Peak memory is proportional to the tile size, not the full
raster size.
engine_compute(xptr)engine_compute(xptr)
xptr |
External pointer returned by |
Requires GDAL support. Stops with an informative error when the package was built without GDAL.
Character scalar: the output directory path (same as the value
passed to engine_set_output).
engine_create, engine_set_output,
has_gdal
Allocates a new BioclimEngine C++ object and returns an opaque
external pointer to it. Use the companion engine_*() functions to
configure and run the engine.
engine_create()engine_create()
An externalptr to a new BioclimEngine object.
Associates four sets of raster file paths with the engine. Each vector must contain either one multi-band file (12 bands) or twelve single-band files (one per calendar month).
engine_open(xptr, tas_files, tasmax_files, tasmin_files, pr_files)engine_open(xptr, tas_files, tasmax_files, tasmin_files, pr_files)
xptr |
External pointer returned by |
tas_files |
Character vector (length 1 or 12): mean temperature. |
tasmax_files |
Character vector (length 1 or 12): maximum temperature. |
tasmin_files |
Character vector (length 1 or 12): minimum temperature. |
pr_files |
Character vector (length 1 or 12): precipitation. |
NULL invisibly.
Controls whether the computation runs on a CUDA GPU or the CPU.
When "auto" is selected the engine uses the GPU if at least one
CUDA device is present, otherwise it falls back to the CPU. GPU
requests on systems without a CUDA device silently fall back to the CPU.
engine_set_device(xptr, device)engine_set_device(xptr, device)
xptr |
External pointer returned by |
device |
Character scalar: one of |
NULL invisibly.
engine_create, has_cuda,
bioclim_engine
Pixels where the mask band equals 0 or NaN receive NaN
(no-data) in every output band. Pass an empty string to disable masking.
engine_set_mask(xptr, mask_path)engine_set_mask(xptr, mask_path)
xptr |
External pointer returned by |
mask_path |
Character scalar: mask raster path, or |
NULL invisibly.
The engine will create (or overwrite) a multi-band GeoTIFF named
bio.tif inside this directory when engine_compute is
called.
engine_set_output(xptr, path)engine_set_output(xptr, path)
xptr |
External pointer returned by |
path |
Character scalar: output directory path. |
NULL invisibly.
Controls the number of threads used in the per-pixel inner loop inside each tile. Values less than 1 are clamped to 1.
engine_set_threads(xptr, n)engine_set_threads(xptr, n)
xptr |
External pointer returned by |
n |
Integer scalar: number of threads. |
NULL invisibly.
Restricts the output to a subset of the 19 standard bioclimatic variables.
The engine always computes all 19 internally (they share intermediate
values). With the multi-band output file, all 19 bands are written and
the bioclim_engine R wrapper subsets the returned
SpatRaster.
engine_set_variables(xptr, variables)engine_set_variables(xptr, variables)
xptr |
External pointer returned by |
variables |
Integer vector with elements in 1..19. |
NULL invisibly.
End-to-end pipeline that reads ERA5-Land hourly GRIB/NetCDF files, aggregates them to CHELSA-compatible monthly climate variables, and computes the 19 standard bioclimatic variables (BIO01–BIO19).
era5_bioclim( t2m_files, tp_files, year, output = tempdir(), to_celsius = TRUE, variables = 1:19, ncores = 1L, save_monthly = FALSE )era5_bioclim( t2m_files, tp_files, year, output = tempdir(), to_celsius = TRUE, variables = 1:19, ncores = 1L, save_monthly = FALSE )
t2m_files |
Character vector of 12 file paths to monthly ERA5-Land hourly 2-m temperature files (one per calendar month, January–December). Each file may be GRIB or NetCDF. |
tp_files |
Character vector of 12 file paths to monthly ERA5-Land
hourly total precipitation files (same order as |
year |
Integer: the calendar year (used to determine days per month). |
output |
Character path to an output directory for GeoTIFF files. Defaults to a temporary directory. |
to_celsius |
Logical: convert temperatures to Celsius?
Default |
variables |
Integer vector of bioclimatic variables to compute
(1–19).
Default |
ncores |
Integer: OpenMP threads for aggregation. Default |
save_monthly |
Logical: write intermediate monthly GeoTIFFs?
Default |
The pipeline proceeds in three stages:
Monthly aggregation: For each of the 12 calendar months,
hourly t2m is aggregated to tas, tasmax, and
tasmin; hourly tp is summed to pr.
Stack: The 12 monthly layers are assembled into
terra::SpatRaster objects with 12 bands each.
Bioclim: bioclim_raster computes BIO01–BIO19.
A terra::SpatRaster with one layer per bioclimatic variable.
era5_t2m_to_monthly, era5_tp_to_monthly,
bioclim_raster
## Not run: # Paths to ERA5-Land GRIB files on the HPC cluster t2m_files <- sprintf("era5land_t2m_hourly_2020_%02d.grib", 1:12) tp_files <- sprintf("era5land_tp_hourly_2020_%02d.grib", 1:12) bio <- era5_bioclim(t2m_files, tp_files, year = 2020L, ncores = 4L) terra::plot(bio[[1]]) # BIO01 ## End(Not run)## Not run: # Paths to ERA5-Land GRIB files on the HPC cluster t2m_files <- sprintf("era5land_t2m_hourly_2020_%02d.grib", 1:12) tp_files <- sprintf("era5land_tp_hourly_2020_%02d.grib", 1:12) bio <- era5_bioclim(t2m_files, tp_files, year = 2020L, ncores = 4L) terra::plot(bio[[1]]) # BIO01 ## End(Not run)
Batch-processes multiple years of ERA5-Land data through the
era5_bioclim pipeline.
era5_bioclim_years( base_dir, years, output_dir, t2m_pattern = "era5land_t2m_hourly_%d_%02d.grib", tp_pattern = "era5land_tp_hourly_%d_%02d.grib", ... )era5_bioclim_years( base_dir, years, output_dir, t2m_pattern = "era5land_t2m_hourly_%d_%02d.grib", tp_pattern = "era5land_tp_hourly_%d_%02d.grib", ... )
base_dir |
Character: base directory containing ERA5-Land raw data.
Expected structure: |
years |
Integer vector of years to process. |
output_dir |
Character: output directory. |
t2m_pattern |
Character: filename pattern for t2m files.
Must contain |
tp_pattern |
Character: filename pattern for tp files.
Default: |
... |
Additional arguments passed to |
A named list of terra::SpatRaster objects, one per year.
## Not run: bio_all <- era5_bioclim_years( base_dir = "/scratch/era5-land/raw", years = 1980:2020, output_dir = "/scratch/era5-land/bioclim", ncores = 8L ) ## End(Not run)## Not run: bio_all <- era5_bioclim_years( base_dir = "/scratch/era5-land/raw", years = 1980:2020, output_dir = "/scratch/era5-land/bioclim", ncores = 8L ) ## End(Not run)
A lightweight diagnostic that tries to open the specified path via GDAL
and returns TRUE if successful, FALSE if GDAL cannot open
it. Stops with an informative error if the package was built without
GDAL support.
gdal_can_open(path)gdal_can_open(path)
path |
Character string: path to the raster file. |
Logical TRUE if GDAL can open the file, FALSE
otherwise.
if (has_gdal()) { gdal_can_open(system.file("extdata", "tiny.tif", package = "xbioclim")) }if (has_gdal()) { gdal_can_open(system.file("extdata", "tiny.tif", package = "xbioclim")) }
Opens the raster at path and returns a named list with dimensions,
geotransform, coordinate reference system, and per-band scale/offset
values.
gdal_info(path)gdal_info(path)
path |
Character string: path to the raster file. |
Data values are always returned as double (float64) in
memory. If the raster bands carry GDAL scale/offset metadata (e.g. packed
integers), those are reported here and applied automatically by
GdalReader::read_window().
Stops with an informative error if the package was built without GDAL support.
Named list with the following elements:
pathCharacter: the path as supplied.
nrowsInteger: number of rows (Y pixels).
ncolsInteger: number of columns (X pixels).
nbandsInteger: number of raster bands.
geotransformNumeric vector of length 6 (GDAL
convention): [x_origin, pixel_width, rotation_x,
y_origin, rotation_y, pixel_height].
crsCharacter: WKT coordinate reference system string, or an empty string if not defined.
scaleNumeric vector (one per band): GDAL scale factor
(1.0 if not set).
offsetNumeric vector (one per band): GDAL offset
(0.0 if not set).
if (has_gdal()) { info <- gdal_info( system.file("extdata", "tiny.tif", package = "xbioclim") ) str(info) }if (has_gdal()) { info <- gdal_info( system.file("extdata", "tiny.tif", package = "xbioclim") ) str(info) }
Returns TRUE when at least one CUDA-capable GPU is detected at
runtime. Returns FALSE when the package was built without CUDA
support or when no CUDA-capable device is present.
has_cuda()has_cuda()
Logical scalar: TRUE if at least one CUDA GPU is available.
has_cuda()has_cuda()
Check whether any errors are stored
has_error()has_error()
TRUE if the message store contains at least one error, FALSE
otherwise.
bioclim_errors(), has_warning()
clear_messages() has_error() # FALSEclear_messages() has_error() # FALSE
Returns TRUE when xbioclim was compiled with GDAL and the native
BioclimEngine tiled pipeline is available, FALSE otherwise.
has_gdal()has_gdal()
Internally the function calls gdal_can_open with a dummy path
and inspects whether the resulting error message indicates an absent GDAL
build.
Logical scalar: TRUE if GDAL is available, FALSE
otherwise.
has_gdal()has_gdal()
Check whether any warnings are stored
has_warning()has_warning()
TRUE if the message store contains at least one warning, FALSE
otherwise.
bioclim_warnings(), has_error()
clear_messages() has_warning() # FALSEclear_messages() has_warning() # FALSE
Convenience wrapper around quarterly_variables() for the four standard
fixed quarters.
quarterly_fixed( tas, tasmax, tasmin, pr, quarter, type = c("meteorological", "calendar"), na.rm = FALSE, ... )quarterly_fixed( tas, tasmax, tasmin, pr, quarter, type = c("meteorological", "calendar"), na.rm = FALSE, ... )
tas |
Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData. |
tasmax |
Same form as |
tasmin |
Same form as |
pr |
Same form as |
quarter |
Integer 1-4. |
type |
Character: |
na.rm |
Logical. If |
... |
Not currently used. |
Same structure as quarterly_variables(): a named numeric vector
of length 6 for vector input, a numeric matrix (pixels x 6) for matrix or
BioclimData input, or a 6-layer SpatRaster for
SpatRaster input, with variables tmean_s, tmax_max, tmin_min,
trange, pr_tot, pr_cv.
Convenience wrapper around quarterly_variables() for a rolling 3-month
quarter starting at start.
quarterly_rolling(tas, tasmax, tasmin, pr, start, na.rm = FALSE, ...)quarterly_rolling(tas, tasmax, tasmin, pr, start, na.rm = FALSE, ...)
tas |
Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData. |
tasmax |
Same form as |
tasmin |
Same form as |
pr |
Same form as |
start |
Integer 1-12: starting month. |
na.rm |
Logical. If |
... |
Not currently used. |
Same structure as quarterly_variables(): a named numeric vector
of length 6 for vector input, a numeric matrix (pixels x 6) for matrix or
BioclimData input, or a 6-layer SpatRaster for
SpatRaster input, with variables tmean_s, tmax_max, tmin_min,
trange, pr_tot, pr_cv.
Computes six quarterly/seasonal variables for an arbitrary set of months.
quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...) ## Default S3 method: quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...)quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...) ## Default S3 method: quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...)
tas |
Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData. |
tasmax |
Same form as |
tasmin |
Same form as |
pr |
Same form as |
months |
Integer vector of 1-based month indices to include (e.g.
|
na.rm |
Logical. If |
... |
Not currently used. |
The output variables are:
tmean_s — mean tas over the selected months.
tmax_max — maximum monthly tasmax among the selected months.
tmin_min — minimum monthly tasmin among the selected months.
trange — tmax_max - tmin_min.
pr_tot — total pr over the selected months.
pr_cv — coefficient of variation of monthly pr
(100 * sd_pop / mean), matching the BIO15 scaling.
Use quarterly_fixed() for the four standard fixed quarters and
quarterly_rolling() for rolling 3-month windows.
Vector input: a named numeric vector of length 6.
Matrix / BioclimData input: a numeric matrix (pixels x 6) with
columns tmean_s, tmax_max, tmin_min, trange, pr_tot, pr_cv.
SpatRaster input: a 6-layer SpatRaster with the same geometry and the same names.
Burns all polygon features from a vector source into a new single-band
GeoTIFF raster that is spatially aligned to a reference raster. Pixels
that fall inside at least one polygon are set to 1; all other
pixels are set to 0.
rasterize_mask_cpp(vector_path, ref_raster_path, output_mask_path)rasterize_mask_cpp(vector_path, ref_raster_path, output_mask_path)
vector_path |
Character string: path to any OGR-readable vector source (shapefile, GeoJSON, GeoPackage, etc.). |
ref_raster_path |
Character string: path to a GDAL-readable raster used as the spatial reference (extent, resolution, CRS). |
output_mask_path |
Character string: file path where the output
|
This function is the low-level C++ entry point. Most users should call
the higher-level create_mask wrapper instead.
Stops with an informative error if the package was built without GDAL support.
Invisibly returns NULL. The side effect is the creation
of the output mask raster at output_mask_path.
if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") mask <- tempfile(fileext = ".tif") writeLines( '{"type":"FeatureCollection","features":[{"type":"Feature", "geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}, "properties":{}}]}', poly) rasterize_mask_cpp(poly, ref, mask) }if (has_gdal()) { # Requires GDAL support at build time. ref <- system.file("extdata", "tiny.tif", package = "xbioclim") poly <- tempfile(fileext = ".geojson") mask <- tempfile(fileext = ".tif") writeLines( '{"type":"FeatureCollection","features":[{"type":"Feature", "geometry":{"type":"Polygon","coordinates":[[[0,0],[1,0],[1,1],[0,1],[0,0]]]}, "properties":{}}]}', poly) rasterize_mask_cpp(poly, ref, mask) }
xbioclim mirrors the SpatMessages pattern from the terra package to
provide a clean mechanism for propagating error and warning messages across
the C++/R boundary.
How the cross-boundary workflow works:
A C++ routine performs its computation and, instead of throwing directly, records any error or warning strings into a session-level message store.
After every .Call() invocation, the R-side wrapper calls
check_messages() to inspect the store and re-raise any messages as
native R conditions (stop() for errors, warning() for warnings).
Users can also inspect the store directly with bioclim_errors() and
bioclim_warnings() before R conditions are raised, or clear it with
clear_messages().
Functions available to users:
bioclim_errors() – retrieve stored error messages.
bioclim_warnings() – retrieve stored warning messages.
has_error() – TRUE if at least one error is stored.
has_warning() – TRUE if at least one warning is stored.
clear_messages() – discard all stored messages.
Functions used internally (and by future C++ glue code):
push_error() – store an error message.
push_warning() – store a warning message.
check_messages() – raise stored messages as R conditions and clear them.
No return value; this page documents the internal message store.
bioclim_errors() and bioclim_warnings() return character vectors,
has_error() and has_warning() return logicals, and
clear_messages() returns NULL invisibly.