Package {xbioclim}


Type: Package
Title: Bioclimatic Variables from Monthly Climate Data
Version: 1.0.3
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.
License: MIT + file LICENSE
NeedsCompilation: yes
SystemRequirements: GNU make, C++17; optionally GDAL (>= 2.0.1) with gdal-config, CUDA toolkit (>= 11.0) with nvcc for GPU acceleration
Encoding: UTF-8
Language: en-US
Imports: methods, Rcpp (≥ 1.0.0)
LinkingTo: Rcpp
Suggests: parallel, sf, terra, testthat (≥ 3.0.0), knitr, rmarkdown
Config/testthat/edition: 3
URL: https://alrobles.github.io/xbioclim/, https://github.com/alrobles/xbioclim
BugReports: https://github.com/alrobles/xbioclim/issues
Collate: 'RcppExports.R' 'primitives.R' 'bioclim.R' 'BioclimData.R' 'quarterly.R' 'bioclim_window.R' 'bioclim_module.R' 'bioclimmodel.R' 'bioclim_raster.R' 'era5_monthly.R' 'era5_bioclim.R' 'bioclim_engine.R' 'engine.R' 'mask.R' 'messages.R' 'xbioclim-package.R'
Config/roxygen2/version: 8.0.0
Packaged: 2026-09-24 14:30:45 UTC; alrobles
Author: Angel Luis Robles Fernandez [aut, cre]
Maintainer: Angel Luis Robles Fernandez <a.l.robles.fernandez@gmail.com>
Repository: CRAN
Date/Publication: 2026-10-05 16:40:02 UTC

xbioclim: Bioclimatic Variables from Monthly Climate Data

Description

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.

Value

No return value; package-level documentation.

ERA5-Land monthly aggregation

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:

Error and warning propagation

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:

Author(s)

Maintainer: Angel Luis Robles Fernandez a.l.robles.fernandez@gmail.com

Authors:

See Also

Useful links:


Compute Bioclimatic Variables for a Block of Cells

Description

Processes a matrix of monthly climate values (one row per cell, 12 columns per month) and returns a matrix of 19 bioclimatic variable values. Cells with any NA input values are returned as all-NA rows.

Usage

.compute_bioclim_block(v_tas, v_tasmax, v_tasmin, v_pr, ncores = 1L)

Arguments

v_tas

Numeric matrix (n_cells x 12): monthly mean temperature.

v_tasmax

Numeric matrix (n_cells x 12): monthly max temperature.

v_tasmin

Numeric matrix (n_cells x 12): monthly min temperature.

v_pr

Numeric matrix (n_cells x 12): monthly precipitation.

ncores

Integer: number of OpenMP threads (default 1).

Value

A numeric matrix (n_cells x 19) of bioclimatic variable values.


Resolve a climate input to a character vector of file paths

Description

Accepts a character vector (length 1 or 12) or a terra::SpatRaster (12 layers). Returns a character vector of length 1 or 12 and validates that all files exist.

Usage

.resolve_climate_input(x, name)

Arguments

x

The input to resolve.

name

Variable name for error messages.

Value

Character vector of length 1 or 12.


Resolve a mask argument to a file path

Description

Accepts a character string, an sf object, or a terra::SpatRaster. Returns a list with path (character) and tmp (path to clean up, or NULL).

Usage

.resolve_engine_mask(mask)

Arguments

mask

The mask argument passed by the user.

Value

Named list with path and tmp.


Create a BioclimData Object

Description

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.

Usage

BioclimData(tas, tasmax, tasmin, pr)

Arguments

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.

Value

A BioclimData object.

Examples

tas    <- 1:12
tasmax <- 2:13
tasmin <- 0:11
pr     <- 1:12
bd <- BioclimData(tas, tasmax, tasmin, pr)
bd

S4 Class for Bioclimatic Input Data

Description

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.

Value

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.

Slots

tas

Numeric matrix (pixels × 12): monthly mean temperature.

tasmax

Numeric matrix (pixels × 12): monthly maximum temperature.

tasmin

Numeric matrix (pixels × 12): monthly minimum temperature.

pr

Numeric matrix (pixels × 12): monthly precipitation.


Create a BioclimModel Object

Description

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.

Usage

BioclimModel(tas, tasmax, tasmin, pr)

Arguments

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.

Value

A BioclimModel-class object.

Examples

tas    <- 1:12
tasmax <- 2:13
tasmin <- 0:11
pr     <- 1:12
m <- BioclimModel(tas, tasmax, tasmin, pr)
bio01(m)
bioclim(m)

BioclimModel S4 Class

Description

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.

Value

An S4 object of class BioclimModel wrapping a C++ BioclimModel instance via an externalptr handle in slot pntr.

Slots

pntr

An externalptr to the underlying C++ BioclimModel object.


S4 Methods for BioclimModel Objects

Description

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.

Value

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).


C++ ClimateBlock class for batch bioclim computation

Description

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.

Details

ClimateBlock is loaded into the package namespace when the package is attached (via loadModule in .onLoad).

Value

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.

Constructor

new(ClimateBlock, tas, tasmax, tasmin, pr)

tas

Numeric matrix of dimensions n_pixels x 12: monthly mean temperature for each pixel.

tasmax

Numeric matrix of dimensions n_pixels x 12: monthly maximum temperature for each pixel.

tasmin

Numeric matrix of dimensions n_pixels x 12: monthly minimum temperature for each pixel.

pr

Numeric 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.

Methods

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.

Examples

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 matrix

Apply a binary mask raster to an input raster

Description

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).

Usage

apply_mask_cpp(input_path, mask_path, output_path)

Arguments

input_path

Character string: path to a GDAL-readable raster (any number of bands).

mask_path

Character string: path to a single-band GDT_Byte mask raster (e.g., produced by rasterize_mask_cpp).

output_path

Character string: file path where the output Float64 GeoTIFF will be written (created or overwritten).

Details

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.

Value

Invisibly returns NULL. The side effect is the creation of the masked raster at output_path.

See Also

create_mask, rasterize_mask_cpp

Examples


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)
}


Compute BIO01 (Mean Annual Temperature) for a raster block

Description

Compute BIO01 (Mean Annual Temperature) for a raster block

Usage

bio01_cpp(tas)

Arguments

tas

Numeric matrix with 12 columns (one per month); rows are pixels.

Value

Numeric vector with one value per pixel.


Compute BIO02 (Mean Diurnal Range) for a raster block

Description

Compute BIO02 (Mean Diurnal Range) for a raster block

Usage

bio02_cpp(tasmax, tasmin)

Arguments

tasmax

Numeric matrix (pixels x 12): monthly max temperature.

tasmin

Numeric matrix (pixels x 12): monthly min temperature.

Value

Numeric vector with one value per pixel.


Compute BIO03 (Isothermality) for a raster block

Description

Compute BIO03 (Isothermality) for a raster block

Usage

bio03_cpp(tasmax, tasmin)

Arguments

tasmax

Numeric matrix (pixels x 12): monthly max temperature.

tasmin

Numeric matrix (pixels x 12): monthly min temperature.

Value

Numeric vector with one value per pixel (NaN where BIO07 == 0).


Compute BIO04 (Temperature Seasonality) for a raster block

Description

Compute BIO04 (Temperature Seasonality) for a raster block

Usage

bio04_cpp(tas)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

Value

Numeric vector with one value per pixel.


Compute BIO05 (Max Temperature of Warmest Month) for a raster block

Description

Compute BIO05 (Max Temperature of Warmest Month) for a raster block

Usage

bio05_cpp(tasmax)

Arguments

tasmax

Numeric matrix (pixels x 12): monthly max temperature.

Value

Numeric vector with one value per pixel.


Compute BIO06 (Min Temperature of Coldest Month) for a raster block

Description

Compute BIO06 (Min Temperature of Coldest Month) for a raster block

Usage

bio06_cpp(tasmin)

Arguments

tasmin

Numeric matrix (pixels x 12): monthly min temperature.

Value

Numeric vector with one value per pixel.


Compute BIO07 (Temperature Annual Range) for a raster block

Description

Compute BIO07 (Temperature Annual Range) for a raster block

Usage

bio07_cpp(tasmax, tasmin)

Arguments

tasmax

Numeric matrix (pixels x 12): monthly max temperature.

tasmin

Numeric matrix (pixels x 12): monthly min temperature.

Value

Numeric vector with one value per pixel.


Compute BIO08 (Mean Temperature of Wettest Quarter) for a raster block

Description

Compute BIO08 (Mean Temperature of Wettest Quarter) for a raster block

Usage

bio08_cpp(tas, pr)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO09 (Mean Temperature of Driest Quarter) for a raster block

Description

Compute BIO09 (Mean Temperature of Driest Quarter) for a raster block

Usage

bio09_cpp(tas, pr)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO10 (Mean Temperature of Warmest Quarter) for a raster block

Description

Compute BIO10 (Mean Temperature of Warmest Quarter) for a raster block

Usage

bio10_cpp(tas)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

Value

Numeric vector with one value per pixel.


Compute BIO11 (Mean Temperature of Coldest Quarter) for a raster block

Description

Compute BIO11 (Mean Temperature of Coldest Quarter) for a raster block

Usage

bio11_cpp(tas)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

Value

Numeric vector with one value per pixel.


Compute BIO12 (Annual Precipitation) for a raster block

Description

Compute BIO12 (Annual Precipitation) for a raster block

Usage

bio12_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO13 (Precipitation of Wettest Month) for a raster block

Description

Compute BIO13 (Precipitation of Wettest Month) for a raster block

Usage

bio13_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO14 (Precipitation of Driest Month) for a raster block

Description

Compute BIO14 (Precipitation of Driest Month) for a raster block

Usage

bio14_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO15 (Precipitation Seasonality) for a raster block

Description

Compute BIO15 (Precipitation Seasonality) for a raster block

Usage

bio15_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel (NaN where mean precip == 0).


Compute BIO16 (Precipitation of Wettest Quarter) for a raster block

Description

Compute BIO16 (Precipitation of Wettest Quarter) for a raster block

Usage

bio16_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO17 (Precipitation of Driest Quarter) for a raster block

Description

Compute BIO17 (Precipitation of Driest Quarter) for a raster block

Usage

bio17_cpp(pr)

Arguments

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO18 (Precipitation of Warmest Quarter) for a raster block

Description

Compute BIO18 (Precipitation of Warmest Quarter) for a raster block

Usage

bio18_cpp(tas, pr)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Compute BIO19 (Precipitation of Coldest Quarter) for a raster block

Description

Compute BIO19 (Precipitation of Coldest Quarter) for a raster block

Usage

bio19_cpp(tas, pr)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

Value

Numeric vector with one value per pixel.


Block-Based Raster Processing for Bioclimatic Variables

Description

Functions for computing bioclimatic variables from monthly climate rasters (SpatRaster objects) using terra's block-loop architecture for memory-efficient processing of large rasters.

Value

No return value; this is an overview page. bioclim_raster() returns a SpatRaster with 19 layers named bio01 through bio19.


Compute Bioclimatic Variables from Monthly Climate Data

Description

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.

Usage

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, ...)

Arguments

tas

Numeric vector of length 12 or BioclimData: monthly mean temperature.

...

Additional arguments. For BioclimData inputs the argument na.rm is accepted: if TRUE, missing months are omitted and each BIO is computed from the available months (a quarter needs at least one valid month). The default na.rm = FALSE makes a pixel all-NA if any input month is NA.

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.

Details

The 19 bioclimatic variables are:

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.

Value


Create a C++ ClimateBlock and compute bioclimatic variables

Description

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.

Usage

bioclim_block(tas, tasmax, tasmin, pr)

Arguments

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.

Value

A named numeric vector of length 19 (bio01 through bio19), identical in meaning to the output of bioclim.

Examples

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)

Compute all 19 bioclimatic variables for a raster block

Description

Compute all 19 bioclimatic variables for a raster block

Usage

bioclim_cpp(tas, tasmax, tasmin, pr, ncores = 1L, na_rm = FALSE)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

tasmax

Numeric matrix (pixels x 12): monthly max temperature.

tasmin

Numeric matrix (pixels x 12): monthly min temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

ncores

Integer: number of OpenMP threads (default 1).

na_rm

Logical: if TRUE, treat NA as missing and compute each BIO from the available months (quarters need >=1 valid month). If FALSE, a single NA in any input for a pixel gives an all-NA row (default).

Value

Numeric matrix (pixels x 19) with one column per variable (bio01..bio19), named accordingly.


Compute Bioclimatic Variables via the Native GDAL-Tiled Engine

Description

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.

Usage

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
)

Arguments

tas

Character vector of length 1 (12-band file) or 12 (one file per month), or a terra::SpatRaster with 12 layers: monthly mean temperature.

tasmax

Like tas but for monthly maximum temperature.

tasmin

Like tas but for monthly minimum temperature.

pr

Like tas but for monthly precipitation.

output

Character string: path to the output directory where the multi-band GeoTIFF bio.tif will be written. The directory is created automatically if it does not exist. Defaults to a temporary directory.

variables

Integer vector of variable numbers to compute, with values in 1:19. Default is 1:19 (all 19 variables). For example, c(1, 12) returns only BIO01 and BIO12 from the 19-band output.

mask

Optional mask: a character file path, an sf object (polygon), or a terra::SpatRaster. NULL (default) means no masking.

threads

Positive integer: number of OpenMP threads to use. Default is 1L.

tile_size

Positive integer: tile dimension (pixels) for tiled I/O. Default is 256L.

overwrite

Logical: whether to overwrite an existing bio.tif inside output. Default is FALSE.

device

Character scalar: compute device to use. One of "auto" (default), "cpu", or "gpu". "auto" selects the GPU when a CUDA device is available, otherwise falls back to the CPU. "gpu" on a system without CUDA emits a warning and falls back to the CPU. When device = "gpu" and tile_size is left at its default, the tile size is automatically scaled to match the detected GPU memory (4096 for high-memory GPUs such as the A100, 1024 otherwise).

dtype

Character scalar: output data type, one of "Float64" (default) or "Float32".

use_pipeline

Logical scalar: if TRUE, use the experimental overlapped read/compute/write pipeline with parallel 12-reader I/O. Default is FALSE, which keeps the original serial tiled loop.

Details

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:

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.

Value

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.

See Also

bioclim_raster for the in-memory R/terra path, has_gdal to check GDAL availability, engine_create for the low-level XPtr interface.

Examples


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"
}


Retrieve stored error messages

Description

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.

Usage

bioclim_errors()

Value

A character vector (possibly empty).

See Also

bioclim_warnings(), has_error(), clear_messages()

Examples

clear_messages()
bioclim_errors()   # character(0)

Compute all 19 bioclimatic variables from the C++ object

Description

Compute all 19 bioclimatic variables from the C++ object

Usage

bioclim_model_compute(ptr)

Arguments

ptr

An external pointer to a BioclimModel C++ object.

Value

Named numeric vector of length 19.


Test whether the C++ pointer is null

Description

Test whether the C++ pointer is null

Usage

bioclim_model_is_null(ptr)

Arguments

ptr

An external pointer.

Value

Logical scalar.


Create a new C++ BioclimModel and return an external pointer

Description

Create a new C++ BioclimModel and return an external pointer

Usage

bioclim_model_new(tas, tasmax, tasmin, pr)

Arguments

tas

Numeric vector of length 12.

tasmax

Numeric vector of length 12.

tasmin

Numeric vector of length 12.

pr

Numeric vector of length 12.

Value

An external pointer wrapping a BioclimModel C++ object.


Compute Bioclimatic Variables from Monthly Climate Rasters

Description

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.

Usage

bioclim_raster(
  tas,
  tasmax,
  tasmin,
  pr,
  filename = "",
  n_blocks = NULL,
  ncores = 1L,
  overwrite = FALSE,
  ...
)

Arguments

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 "" (default) to keep the result in memory.

n_blocks

Integer: target number of row blocks. If NULL (default), terra selects an appropriate number based on available memory.

ncores

Integer: number of CPU cores for within-block parallel processing via OpenMP. Default is 1 (sequential).

overwrite

Logical: whether to overwrite an existing output file. Default is FALSE.

...

Additional arguments passed to terra::writeStart().

Details

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.

Value

A SpatRaster with 19 layers named bio01 through bio19, sharing the spatial extent, resolution and CRS of tas.

See Also

bioclim() for single-pixel (vector) computation.

Examples


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)  # 19


Rolling optimal-window bioclimatic variables

Description

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.

Usage

bioclim_rolling(tas, tasmax, tasmin, pr, window = 3L, na.rm = FALSE, ...)

Arguments

tas

Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData.

tasmax

Same form as tas: monthly maximum temperature.

tasmin

Same form as tas: monthly minimum temperature.

pr

Same form as tas: monthly precipitation.

window

Integer: length of the rolling window in months (2-11). Default is 3.

na.rm

Logical. If FALSE (default), a single NA makes all outputs NA for that pixel. If TRUE, missing months are skipped.

...

Not currently used.

Value

Named vector (length 19), matrix (pixels x 19), or 19-layer SpatRaster.


Compute bioclimatic variables using a rolling window of arbitrary length

Description

Compute bioclimatic variables using a rolling window of arbitrary length

Usage

bioclim_rolling_cpp(tas, tasmax, tasmin, pr, window = 3L, na_rm = FALSE)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

tasmax

Numeric matrix (pixels x 12): monthly maximum temperature.

tasmin

Numeric matrix (pixels x 12): monthly minimum temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

window

Integer: length (months) of the rolling window (2-11).

na_rm

Logical: if TRUE, skip NA months.

Value

Numeric matrix (pixels x 19) with columns bio01..bio19. The base variables (bio01-bio07, bio12-bio15) are computed over the full 12 months; the rolling-window variables (bio08-bio11, bio16-bio19) are computed over the best window-month period.


Retrieve stored warning messages

Description

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.

Usage

bioclim_warnings()

Value

A character vector (possibly empty).

See Also

bioclim_errors(), has_warning(), clear_messages()

Examples

clear_messages()
bioclim_warnings()   # character(0)

Bioclimatic variables over an arbitrary window of months

Description

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).

Usage

bioclim_window(
  tas,
  tasmax,
  tasmin,
  pr,
  months = NULL,
  start = NULL,
  end = NULL,
  window = 3L,
  na.rm = FALSE,
  ...
)

Arguments

tas

Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData.

tasmax

Same form as tas: monthly maximum temperature.

tasmin

Same form as tas: monthly minimum temperature.

pr

Same form as tas: monthly precipitation.

months

Integer vector of 1-based months in the window, e.g. c(6, 7) for Jun-Jul or c(12, 1, 2) for DJF. If start and end are supplied, months is derived automatically.

start, end

Optional character strings in "MM-DD" format. When both are supplied, the months that overlap the day range are selected. Wrap-around across the year end is supported.

window

Integer: length of the internal rolling sub-window used to compute bio08..bio19. Defaults to 3 (quarterly). Must be ⁠<= length(months)⁠ for the rolling variables to be non-NA.

na.rm

Logical. If FALSE (default), a single NA among the selected months makes all outputs NA for that pixel. If TRUE, missing months are skipped.

...

Not currently used.

Details

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.

Value

See Also

bioclim_rolling() for rolling optimal windows over the full year with a free window length.


Compute bioclimatic variables over an arbitrary window of months

Description

Compute bioclimatic variables over an arbitrary window of months

Usage

bioclim_window_cpp(tas, tasmax, tasmin, pr, months, window = 3L, na_rm = FALSE)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

tasmax

Numeric matrix (pixels x 12): monthly maximum temperature.

tasmin

Numeric matrix (pixels x 12): monthly minimum temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

months

Integer vector of 1-based month indices in the window.

window

Integer: length (months) of the internal rolling sub-window used for the BIO08-BIO19 variables. Must be >= 3 and <= length(months) for those variables to be non-NA.

na_rm

Logical: if TRUE, skip NA months.

Value

Numeric matrix (pixels x 19) with columns bio01..bio19.


Compute all 19 bioclimatic variables (vectorized, zero-copy bridge)

Description

A faster alternative to bioclim_cpp() that uses whole-array vectorized operations and maps R matrix memory directly onto C++ pointers (zero-copy on both input and output).

Usage

bioclim_xt(tas, tasmax, tasmin, pr, ncores = 1L)

Arguments

tas

Numeric matrix (n_pixels x 12): monthly mean temperature.

tasmax

Numeric matrix (n_pixels x 12): monthly max temperature.

tasmin

Numeric matrix (n_pixels x 12): monthly min temperature.

pr

Numeric matrix (n_pixels x 12): monthly precipitation.

ncores

Integer: number of OpenMP threads (default 1).

Value

Numeric matrix (n_pixels x 19) with one column per variable (bio01..bio19), named accordingly. Rows with any NA input are returned as all-NA.


Propagate stored messages as R conditions

Description

Inspects the internal message store, issues any recorded warnings via base::warning(), clears them, then raises any recorded error via base::stop() and clears it. This function is called automatically by every R wrapper function immediately after invoking a C++ routine, matching the pattern used by the terra package.

Usage

check_messages()

Details

Calling this function when the store is empty is a no-op.

Value

Invisible NULL (unless an error is stored, in which case it throws).


Clear all stored messages

Description

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.

Usage

clear_messages()

Value

Invisible NULL.

See Also

bioclim_errors(), bioclim_warnings()

Examples

clear_messages()
has_error()    # FALSE
has_warning()  # FALSE

Create a binary mask raster from a polygon source

Description

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).

Usage

create_mask(
  polygon,
  reference_raster = NULL,
  output = tempfile(fileext = ".tif"),
  apply_to = NULL,
  apply_output = tempfile(fileext = ".tif")
)

Arguments

polygon

Polygon source: an sf object, a character file path to an OGR-readable vector source, or a terra::SpatRaster used directly as a binary mask.

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 polygon is a SpatRaster.

output

Character string: file path for the output mask GeoTIFF. Defaults to a temporary file.

apply_to

Character string or NULL: if supplied, path to a GDAL-readable raster to which the mask will be applied. Pixels outside all polygons are set to NA in the result.

apply_output

Character string: file path for the masked output raster. Used only when apply_to is not NULL. Defaults to a temporary file.

Details

The function accepts three types of polygon input:

sf object

Written to a temporary GeoJSON file via sf::st_write() and then rasterized. Requires the sf package.

Character file path

Passed directly to the C++ rasterizer. Any OGR-readable format is supported (shapefile, GeoJSON, GeoPackage, etc.).

SpatRaster object

Used 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.

Value

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.

See Also

rasterize_mask_cpp(), apply_mask_cpp()

Examples


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)
}


Count available CUDA GPU devices

Description

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.

Usage

cuda_device_count()

Value

Non-negative integer: number of CUDA devices detected.

See Also

has_cuda, cuda_device_info


Query properties of the first CUDA GPU device

Description

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.

Usage

cuda_device_info()

Value

Named list with:

name

Character: GPU model name.

memory_gb

Numeric: total global memory in gigabytes.

compute_capability

Character: e.g. "8.0" for A100.

An empty list when no CUDA device is detected.

See Also

has_cuda, cuda_device_count


Query CUDA GPU device information

Description

Returns hardware information about the first CUDA-capable GPU detected on this machine.

Usage

cuda_info()

Value

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.

See Also

has_cuda, bioclim_engine

Examples

cuda_info()

Number of days in a given month/year

Description

Number of days in a given month/year

Usage

days_in_month(year, month)

Arguments

year

Integer year.

month

Integer month (1–12).

Value

Integer number of days.


Run the bioclimatic-variable computation pipeline

Description

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.

Usage

engine_compute(xptr)

Arguments

xptr

External pointer returned by engine_create.

Details

Requires GDAL support. Stops with an informative error when the package was built without GDAL.

Value

Character scalar: the output directory path (same as the value passed to engine_set_output).

See Also

engine_create, engine_set_output, has_gdal


Create a new BioclimEngine instance

Description

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.

Usage

engine_create()

Value

An externalptr to a new BioclimEngine object.

See Also

engine_open, engine_compute


Configure monthly climate input files

Description

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).

Usage

engine_open(xptr, tas_files, tasmax_files, tasmin_files, pr_files)

Arguments

xptr

External pointer returned by engine_create.

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.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Set the compute device for a BioclimEngine instance

Description

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.

Usage

engine_set_device(xptr, device)

Arguments

xptr

External pointer returned by engine_create.

device

Character scalar: one of "auto", "cpu", or "gpu".

Value

NULL invisibly.

See Also

engine_create, has_cuda, bioclim_engine


Set the output data type

Description

Controls the on-disk data type of the output bio.tif file.

"Float64"

IEEE 754 double precision (default).

"Float32"

IEEE 754 single precision — half the file size with negligible loss for most climate data.

Usage

engine_set_dtype(xptr, dtype)

Arguments

xptr

External pointer returned by engine_create.

dtype

Character scalar: one of "Float64" or "Float32".

Value

NULL invisibly.

See Also

engine_create, engine_compute


Set an optional mask raster

Description

Pixels where the mask band equals 0 or NaN receive NaN (no-data) in every output band. Pass an empty string to disable masking.

Usage

engine_set_mask(xptr, mask_path)

Arguments

xptr

External pointer returned by engine_create.

mask_path

Character scalar: mask raster path, or "" for none.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Set the output raster path

Description

The engine will create (or overwrite) a multi-band GeoTIFF named bio.tif inside this directory when engine_compute is called.

Usage

engine_set_output(xptr, path)

Arguments

xptr

External pointer returned by engine_create.

path

Character scalar: output directory path.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Enable or disable the overlapped read/compute/write pipeline

Description

This is an internal, opt-in flag. When TRUE, the next call to engine_compute uses three background threads to overlap the GDAL read, BIOCLIM computation, and GDAL write stages for each tile. When FALSE (the default) the engine uses the original serial loop.

Usage

engine_set_pipeline(xptr, use_pipeline)

Arguments

xptr

External pointer returned by engine_create.

use_pipeline

Logical scalar: TRUE to enable the pipeline.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Set the number of OpenMP threads

Description

Controls the number of threads used in the per-pixel inner loop inside each tile. Values less than 1 are clamped to 1.

Usage

engine_set_threads(xptr, n)

Arguments

xptr

External pointer returned by engine_create.

n

Integer scalar: number of threads.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Set the tile size used during tiled processing

Description

Width and height of each processing tile in pixels. Default is 256. Mostly useful for testing with small rasters. Values less than 1 are clamped to 1.

Usage

engine_set_tile_size(xptr, tile_size)

Arguments

xptr

External pointer returned by engine_create.

tile_size

Integer scalar: tile width and height in pixels.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Select which bioclimatic variables to write

Description

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.

Usage

engine_set_variables(xptr, variables)

Arguments

xptr

External pointer returned by engine_create.

variables

Integer vector with elements in 1..19.

Value

NULL invisibly.

See Also

engine_create, engine_compute


Convert ERA5-Land Hourly Data to CHELSA-Compatible Monthly Variables

Description

Aggregates ERA5-Land hourly reanalysis data to CHELSA-compatible monthly climate variables. The four output variables (tas, tasmax, tasmin, pr) can be fed directly into bioclim or bioclim_raster to compute bioclimatic variables BIO01–BIO19.

Usage

era5_t2m_to_monthly_r(hourly_t2m, n_days, to_celsius = FALSE)

era5_tp_to_monthly_r(hourly_tp)

era5_to_monthly_r(hourly_t2m, hourly_tp, n_days, to_celsius = FALSE)

era5_t2m_to_monthly(hourly_t2m, n_days, to_celsius = FALSE, ncores = 1L)

era5_tp_to_monthly(hourly_tp, ncores = 1L)

era5_to_monthly(hourly_t2m, hourly_tp, n_days, to_celsius = FALSE, ncores = 1L)

Arguments

hourly_t2m

Numeric matrix (n_pixels × n_hours) of hourly 2-m temperatures (K), or a numeric vector for a single pixel.

n_days

Integer: number of days in the month.

to_celsius

Logical: convert temperatures from Kelvin to Celsius? Default FALSE.

hourly_tp

Numeric matrix (n_pixels × n_hours) of hourly total precipitation (m), or a numeric vector for a single pixel.

ncores

Integer: OpenMP thread count. Default 1L.

Details

Temperature aggregation. ERA5-Land provides instantaneous 2-m temperature (t2m) at hourly resolution in Kelvin. The hourly values are first grouped into calendar days (24 hours each):

Precipitation aggregation. ERA5-Land provides total precipitation (tp) as hourly accumulations in metres of water equivalent. The hourly values are summed over the month and converted to \mathrm{kg\,m^{-2}\,month^{-1}} (= mm) by multiplying by 1000.

Unit conventions. By default, temperatures are returned in Kelvin to match the CHELSA convention. Set to_celsius = TRUE to obtain degrees Celsius instead (common for WorldClim-style bioclimatic variables).

Value

Named list: tas, tasmax, tasmin.

Numeric scalar: monthly precipitation in mm (kg m-2).

Named list: tas, tasmax, tasmin, pr.

Named list with tas, tasmax, tasmin — each a numeric vector of length n_pixels.

Numeric vector of length n_pixels: monthly precipitation in kg m-2 (mm).

Named list with tas, tasmax, tasmin, pr — each a numeric vector of length n_pixels (or scalar for single pixel).

Functions

Examples

# Single pixel: 3 days of hourly data (72 hours) at ~285 K
set.seed(42)
hourly <- 285 + cumsum(rnorm(72, 0, 0.5))
result <- era5_t2m_to_monthly(hourly, n_days = 3L)
result$tas     # monthly mean temperature (K)
result$tasmax  # monthly mean of daily maxima (K)
result$tasmin  # monthly mean of daily minima (K)

# Single pixel: 3 days of hourly precipitation (72 hours)
set.seed(42)
hourly_tp <- pmax(0, rnorm(72, 0.0001, 0.00005))
era5_tp_to_monthly(hourly_tp)  # total in mm

# Single pixel: 3 days of synthetic hourly data
n_days <- 3L
set.seed(42)
hourly_t2m <- 285 + 5 * sin(2 * pi * (seq(0, 71) - 4) / 24)
hourly_tp  <- pmax(0, rnorm(72, 0.0001, 0.00005))
result <- era5_to_monthly(hourly_t2m, hourly_tp, n_days)
result$tas     # monthly mean temperature (K)
result$tasmax  # monthly mean of daily maxima (K)
result$tasmin  # monthly mean of daily minima (K)
result$pr      # monthly precipitation (mm)


Compute Bioclimatic Variables from ERA5-Land Data

Description

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).

Usage

era5_bioclim(
  t2m_files,
  tp_files,
  year,
  output = tempdir(),
  to_celsius = TRUE,
  variables = 1:19,
  ncores = 1L,
  save_monthly = FALSE
)

Arguments

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 t2m_files).

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 TRUE for WorldClim-convention bioclimatic variables.

variables

Integer vector of bioclimatic variables to compute (1–19). Default 1:19 (all).

ncores

Integer: OpenMP threads for aggregation. Default 1L.

save_monthly

Logical: write intermediate monthly GeoTIFFs? Default FALSE.

Details

The pipeline proceeds in three stages:

  1. Monthly aggregation: For each of the 12 calendar months, hourly t2m is aggregated to tas, tasmax, and tasmin; hourly tp is summed to pr.

  2. Stack: The 12 monthly layers are assembled into terra::SpatRaster objects with 12 bands each.

  3. Bioclim: bioclim_raster computes BIO01–BIO19.

Value

A terra::SpatRaster with one layer per bioclimatic variable.

See Also

era5_t2m_to_monthly, era5_tp_to_monthly, bioclim_raster

Examples

## 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)


Generate Bioclimatic Variables for Multiple Years

Description

Batch-processes multiple years of ERA5-Land data through the era5_bioclim pipeline.

Usage

era5_bioclim_years(
  base_dir,
  years,
  output_dir,
  t2m_pattern = "era5land_t2m_hourly_%d_%02d.grib",
  tp_pattern = "era5land_tp_hourly_%d_%02d.grib",
  ...
)

Arguments

base_dir

Character: base directory containing ERA5-Land raw data. Expected structure: base_dir/t2m/YYYY/era5land_t2m_hourly_YYYY_MM.grib and base_dir/tp/YYYY/era5land_tp_hourly_YYYY_MM.grib.

years

Integer vector of years to process.

output_dir

Character: output directory.

t2m_pattern

Character: filename pattern for t2m files. Must contain %d for year and %02d for month. Default: "era5land_t2m_hourly_%d_%02d.grib".

tp_pattern

Character: filename pattern for tp files. Default: "era5land_tp_hourly_%d_%02d.grib".

...

Additional arguments passed to era5_bioclim.

Value

A named list of terra::SpatRaster objects, one per year.

Examples

## 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)


Aggregate ERA5-Land hourly 2-m temperature to monthly statistics

Description

Converts an hourly temperature matrix to monthly mean temperature (tas), monthly mean of daily maxima (tasmax), and monthly mean of daily minima (tasmin), following the CHELSA variable convention.

Usage

era5_t2m_to_monthly_cpp(hourly, n_days, to_celsius = FALSE, ncores = 1L)

Arguments

hourly

Numeric matrix (n_pixels x n_hours): hourly 2-m temperature. Column-major layout. n_hours must equal 24 * n_days.

n_days

Integer: number of days in the month.

to_celsius

Logical: if TRUE, convert Kelvin to Celsius (default FALSE, output in Kelvin matching CHELSA convention).

ncores

Integer: number of OpenMP threads (default 1).

Value

A named list with three numeric vectors of length n_pixels: tas, tasmax, tasmin.


Unified ERA5-Land hourly-to-monthly aggregation

Description

Converts hourly 2-m temperature and total precipitation to the four CHELSA-compatible monthly climate variables in a single parallel pass.

Usage

era5_to_monthly_cpp(
  hourly_t2m,
  hourly_tp,
  n_days,
  to_celsius = FALSE,
  ncores = 1L
)

Arguments

hourly_t2m

Numeric matrix (n_pixels x n_hours_t2m): hourly 2-m temperature in Kelvin. n_hours_t2m must equal 24 * n_days.

hourly_tp

Numeric matrix (n_pixels x n_hours_tp): hourly total precipitation in metres. n_pixels must match hourly_t2m.

n_days

Integer: number of days in the month.

to_celsius

Logical: convert temperatures from Kelvin to Celsius? Default FALSE.

ncores

Integer: number of OpenMP threads (default 1).

Value

A named list with four numeric vectors of length n_pixels: tas, tasmax, tasmin, pr.


Aggregate ERA5-Land hourly total precipitation to monthly total

Description

Sums hourly precipitation accumulations and converts from metres of water to kg m-2 month-1 (equivalent to mm/month), matching the CHELSA pr variable convention.

Usage

era5_tp_to_monthly_cpp(hourly, ncores = 1L)

Arguments

hourly

Numeric matrix (n_pixels x n_hours): hourly total precipitation in metres.

ncores

Integer: number of OpenMP threads (default 1).

Value

Numeric vector of length n_pixels: monthly total precipitation in kg m-2 (mm).


Check whether GDAL can open a raster file

Description

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.

Usage

gdal_can_open(path)

Arguments

path

Character string: path to the raster file.

Value

Logical TRUE if GDAL can open the file, FALSE otherwise.

Examples


if (has_gdal()) {
  gdal_can_open(system.file("extdata", "tiny.tif", package = "xbioclim"))
}


Return metadata about a GDAL-readable raster

Description

Opens the raster at path and returns a named list with dimensions, geotransform, coordinate reference system, and per-band scale/offset values.

Usage

gdal_info(path)

Arguments

path

Character string: path to the raster file.

Details

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.

Value

Named list with the following elements:

path

Character: the path as supplied.

nrows

Integer: number of rows (Y pixels).

ncols

Integer: number of columns (X pixels).

nbands

Integer: number of raster bands.

geotransform

Numeric vector of length 6 (GDAL convention): [x_origin, pixel_width, rotation_x, y_origin, rotation_y, pixel_height].

crs

Character: WKT coordinate reference system string, or an empty string if not defined.

scale

Numeric vector (one per band): GDAL scale factor (1.0 if not set).

offset

Numeric vector (one per band): GDAL offset (0.0 if not set).

Examples


if (has_gdal()) {
  info <- gdal_info(
    system.file("extdata", "tiny.tif", package = "xbioclim")
  )
  str(info)
}


Check CUDA GPU availability

Description

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.

Usage

has_cuda()

Value

Logical scalar: TRUE if at least one CUDA GPU is available.

See Also

cuda_info, bioclim_engine

Examples

has_cuda()

Check whether any errors are stored

Description

Check whether any errors are stored

Usage

has_error()

Value

TRUE if the message store contains at least one error, FALSE otherwise.

See Also

bioclim_errors(), has_warning()

Examples

clear_messages()
has_error()   # FALSE

Check whether the package was built with GDAL support

Description

Returns TRUE when xbioclim was compiled with GDAL and the native BioclimEngine tiled pipeline is available, FALSE otherwise.

Usage

has_gdal()

Details

Internally the function calls gdal_can_open with a dummy path and inspects whether the resulting error message indicates an absent GDAL build.

Value

Logical scalar: TRUE if GDAL is available, FALSE otherwise.

Examples

has_gdal()

Check whether any warnings are stored

Description

Check whether any warnings are stored

Usage

has_warning()

Value

TRUE if the message store contains at least one warning, FALSE otherwise.

See Also

bioclim_warnings(), has_error()

Examples

clear_messages()
has_warning()   # FALSE

Primitive Helper Functions for Bioclimatic Variable Computation

Description

Internal helper functions used by the bioclimatic variable functions. These mirror the primitives in the xbioclim C++ library.

Value

No return value; this page only groups the internal helper functions. See the individual function pages for their return values.


Store an error message in the xbioclim message store

Description

This function is called by C++ routines (via .Call) or internal R helpers to record an error without immediately throwing an R condition. Call check_messages() afterwards to convert the stored message into a proper R error.

Usage

push_error(msg)

Arguments

msg

A single character string describing the error.

Value

Invisible NULL.


Store a warning message in the xbioclim message store

Description

This function is called by C++ routines (via .Call) or internal R helpers to record a warning without immediately issuing an R condition. Call check_messages() afterwards to convert the stored message into a proper R warning.

Usage

push_warning(msg)

Arguments

msg

A single character string describing the warning.

Value

Invisible NULL.


Find the starting month of the quarter with the maximum sum

Description

Find the starting month of the quarter with the maximum sum

Usage

quarter_argmax(x, na.rm = FALSE)

Arguments

x

A numeric vector of length 12 (monthly values).

na.rm

Logical. If TRUE, missing values are skipped; a quarter needs at least one non-missing value to be considered.

Value

An integer (1-12) indicating the starting month.


Find the starting month of the quarter with the minimum sum

Description

Find the starting month of the quarter with the minimum sum

Usage

quarter_argmin(x, na.rm = FALSE)

Arguments

x

A numeric vector of length 12 (monthly values).

na.rm

Logical. If TRUE, missing values are skipped; a quarter needs at least one non-missing value to be considered.

Value

An integer (1-12) indicating the starting month.


Get the 3-month values for a quarter starting at a given month

Description

Get the 3-month values for a quarter starting at a given month

Usage

quarter_values(x, start)

Arguments

x

A numeric vector of length 12 (monthly values).

start

The starting month (1-12).

Value

A numeric vector of length 3.


Fixed-quarter seasonal variables

Description

Convenience wrapper around quarterly_variables() for the four standard fixed quarters.

Usage

quarterly_fixed(
  tas,
  tasmax,
  tasmin,
  pr,
  quarter,
  type = c("meteorological", "calendar"),
  na.rm = FALSE,
  ...
)

Arguments

tas

Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData.

tasmax

Same form as tas: monthly maximum temperature.

tasmin

Same form as tas: monthly minimum temperature.

pr

Same form as tas: monthly precipitation.

quarter

Integer 1-4.

type

Character: "meteorological" (DJF, MAM, JJA, SON) or "calendar" (JFM, AMJ, JAS, OND).

na.rm

Logical. If FALSE (default), a single NA among the selected months makes all outputs NA for that pixel. If TRUE, missing months are skipped.

...

Not currently used.

Value

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.


Rolling-quarter seasonal variables

Description

Convenience wrapper around quarterly_variables() for a rolling 3-month quarter starting at start.

Usage

quarterly_rolling(tas, tasmax, tasmin, pr, start, na.rm = FALSE, ...)

Arguments

tas

Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData.

tasmax

Same form as tas: monthly maximum temperature.

tasmin

Same form as tas: monthly minimum temperature.

pr

Same form as tas: monthly precipitation.

start

Integer 1-12: starting month.

na.rm

Logical. If FALSE (default), a single NA among the selected months makes all outputs NA for that pixel. If TRUE, missing months are skipped.

...

Not currently used.

Value

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.


Quarterly / seasonal climate variables

Description

Computes six quarterly/seasonal variables for an arbitrary set of months.

Usage

quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...)

## Default S3 method:
quarterly_variables(tas, tasmax, tasmin, pr, months, na.rm = FALSE, ...)

Arguments

tas

Numeric vector (length 12), matrix (pixels x 12), SpatRaster with 12 layers, or BioclimData.

tasmax

Same form as tas: monthly maximum temperature.

tasmin

Same form as tas: monthly minimum temperature.

pr

Same form as tas: monthly precipitation.

months

Integer vector of 1-based month indices to include (e.g. c(1, 2, 3) for a fixed quarter, or c(12, 1, 2) for DJF).

na.rm

Logical. If FALSE (default), a single NA among the selected months makes all outputs NA for that pixel. If TRUE, missing months are skipped.

...

Not currently used.

Details

The output variables are:

Use quarterly_fixed() for the four standard fixed quarters and quarterly_rolling() for rolling 3-month windows.

Value


Compute quarterly/seasonal climate variables for a raster block

Description

Compute quarterly/seasonal climate variables for a raster block

Usage

quarterly_variables_cpp(tas, tasmax, tasmin, pr, months, na_rm = FALSE)

Arguments

tas

Numeric matrix (pixels x 12): monthly mean temperature.

tasmax

Numeric matrix (pixels x 12): monthly maximum temperature.

tasmin

Numeric matrix (pixels x 12): monthly minimum temperature.

pr

Numeric matrix (pixels x 12): monthly precipitation.

months

Integer vector of 1-based month indices to include.

na_rm

Logical: if TRUE, skip NA months.

Value

Numeric matrix (pixels x 6) with columns tmean_s, tmax_max, tmin_min, trange, pr_tot, pr_cv.


Rasterize a vector polygon layer to a binary mask raster

Description

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.

Usage

rasterize_mask_cpp(vector_path, ref_raster_path, output_mask_path)

Arguments

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 GDT_Byte GeoTIFF will be written (created or overwritten).

Details

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.

Value

Invisibly returns NULL. The side effect is the creation of the output mask raster at output_mask_path.

See Also

create_mask, apply_mask_cpp

Examples


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)
}


Compute rolling quarter means with circular wrapping

Description

For each starting month (1-12), computes the mean of 3 consecutive months with circular wrapping (month 13 = month 1, month 14 = month 2).

Usage

rolling_quarter_mean(x, na.rm = FALSE)

Arguments

x

A numeric vector of length 12 (monthly values).

na.rm

Logical. If TRUE, missing values are skipped.

Value

A numeric vector of length 12 with rolling quarter means.


Compute rolling quarter sums with circular wrapping

Description

For each starting month (1-12), computes the sum of 3 consecutive months with circular wrapping (month 13 = month 1, month 14 = month 2).

Usage

rolling_quarter_sum(x, na.rm = FALSE)

Arguments

x

A numeric vector of length 12 (monthly values).

na.rm

Logical. If TRUE, missing values are skipped.

Value

A numeric vector of length 12 with rolling quarter sums.


Population standard deviation

Description

Computes the population standard deviation (denominator N, not N-1) matching the xbioclim convention.

Usage

sd_pop(x, na.rm = FALSE)

Arguments

x

A numeric vector.

na.rm

Logical. If TRUE, missing values are skipped.

Value

A single numeric value.


Validate monthly climate input

Description

Checks that input is a numeric vector of length 12.

Usage

validate_monthly(x, name = "input")

Arguments

x

The input to validate.

name

Name of the variable for error messages.

Value

Invisible NULL. Throws an error if validation fails.


Validate SpatRaster Input

Description

Checks that input is a SpatRaster with 12 layers.

Usage

validate_spatraster(x, name = "input")

Arguments

x

The input to validate.

name

Name of the variable for error messages.

Value

Invisible NULL. Throws an error if validation fails.


Error and Warning Message Store

Description

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:

  1. A C++ routine performs its computation and, instead of throwing directly, records any error or warning strings into a session-level message store.

  2. 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).

  3. 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:

Functions used internally (and by future C++ glue code):

Value

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.

mirror server hosted at Truenetwork, Russian Federation.