| Title: | Workflow for Environmental Risk Assessment: Habitat, Food Web, Dispersal, Exposure and Risk |
|---|---|
| Description: | A set of tools dedicated to modeling food web transfer based on an initial ground raster. It provides a directed acyclic graph structure for a set of rasters representing the flow of elements (e.g., food, energy, contaminants). It also includes tools for working with dispersal algorithms, enabling the combination of flux data with population movement. |
| Authors: | Virgile Baudrot [aut, cre], Léa Bariod [ctb], Clémentine Fritsch [ctb], Renaud Scheifler [ctb] |
| Maintainer: | Virgile Baudrot <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.1.3 |
| Built: | 2026-05-22 07:34:41 UTC |
| Source: | https://github.com/cran/spacemodR |
Ensures that any subsetting or modification preserves the validity of the trophic table.
## S3 method for class 'trophic_tbl' x[...]## S3 method for class 'trophic_tbl' x[...]
x |
A trophic_tbl object. |
... |
Additional arguments passed to the base method. |
A validated trophic_tbl object.
Add habitat zones to a Habitat object
add_habitat(hab, sf_data, weight = 1, ...)add_habitat(hab, sf_data, weight = 1, ...)
hab |
A Habitat object |
sf_data |
An sf object containing geometries to add |
weight |
A weight to apply on the habitat feature. Can then be used as resistance for dispersal functions for instance. |
... |
Additional arguments |
A Habitat object with new geometries added as habitat
Adds one or several directed links to a trophic_tbl object.
add_link(tbl, from, to, weight = 1)add_link(tbl, from, to, weight = 1)
tbl |
A |
from |
A single character string indicating the source node. |
to |
A character vector indicating target nodes. |
weight |
A numeric vector of weights associated with each link.
If a single value is provided, it is recycled to match the length of |
The function performs several checks:
from must be a scalar character string
to must be a character vector
Links must be unique
Self-loops (from == to) are forbidden
The resulting graph must remain acyclic
A validated trophic_tbl object with the new links added.
net <- trophic() |> add_link("a", "b", weight = 1)net <- trophic() |> add_link("a", "b", weight = 1)
Add non-habitat zones to a Habitat object
add_nohabitat(hab, sf_data, ...)add_nohabitat(hab, sf_data, ...)
hab |
A Habitat object |
sf_data |
An sf object containing geometries to add |
... |
Additional arguments |
A Habitat object with new geometries added as non-habitat
Low-level function to apply spatial processing (Convolution or External algorithms) to a raster. It handles NA masking and method dispatch to Julia if necessary.
compute_dispersal(x, method = "convolution", options = list(), mask = NULL)compute_dispersal(x, method = "convolution", options = list(), mask = NULL)
x |
SpatRaster. Source layer to disperse. |
method |
Character. "convolution" or "omniscape" (placeholder). |
options |
List. Parameters (e.g., 'kernel' for convolution). |
mask |
SpatRaster (optional). A mask to apply after dispersion (e.g., maintain original NA structure). |
A SpatRaster object containing the dispersed values.
Create a 2D Gaussian motion kernel as a SpatRaster
compute_kernel(radius, GSD, size_std = 1.5)compute_kernel(radius, GSD, size_std = 1.5)
radius |
Numeric, std of the distribution in meters |
GSD |
Numeric, ground sampling distance in meters per pixel |
size_std |
Numeric, how many std to extend kernel on each side |
A matrix defining the kernel
Applies a dispersal mechanism to a specific layer of the 'spacemodel' object.
This function acts as a wrapper around compute_dispersal to handle
the 'spacemodel' class structure.
dispersal( spacemodel, layer = 1, method = "convolution", method_option = list() )dispersal( spacemodel, layer = 1, method = "convolution", method_option = list() )
spacemodel |
A |
layer |
Character or Integer. The name or index of the layer to disperse (e.g., "Fox", 1). |
method |
Character. The dispersal method to use. Options are:
|
method_option |
A list of parameters specific to the chosen method:
|
The spacemodel object with the specified layer updated with dispersed values.
## Not run: # 1. Convolution example my_kernel <- matrix(1, nrow=3, ncol=3) sm_updated <- dispersal(sm, layer = "Predator", method = "convolution", method_option = list(kernel = my_kernel)) # 2. Omniscape example (requires Julia) sm_updated <- dispersal(sm, layer = "Predator", method = "omniscape", method_option = list(resistance = res_map, radius = 10)) ## End(Not run)## Not run: # 1. Convolution example my_kernel <- matrix(1, nrow=3, ncol=3) sm_updated <- dispersal(sm, layer = "Predator", method = "convolution", method_option = list(kernel = my_kernel)) # 2. Omniscape example (requires Julia) sm_updated <- dispersal(sm, layer = "Predator", method = "omniscape", method_option = list(resistance = res_map, radius = 10)) ## End(Not run)
Computes the contribution of a resource raster to a consumer layer using the normalized weight and a flux function stored in the trophic table.
flux(raster, intakes, from, to)flux(raster, intakes, from, to)
raster |
A |
intakes |
A |
from |
Character string, name of the source node. |
to |
Character string, name of the target node. |
The function extracts the link corresponding to from -> to from the
trophic table and applies:
the associated flux function to the raster values
the normalized weight of the link
An error is thrown if no such link exists.
A raster object with transformed values.
This function takes a region of interest (ROI) as an 'sf' or 'sfc' object and returns the codes of departments intersecting this region.
get_departements_for_roi(roi)get_departements_for_roi(roi)
roi |
A spatial object of type 'sf' or 'sfc' representing the region of interest. Use only the first geometry (polygon). |
A character vector containing the codes of departments intersecting the region of interest.
library(sf) roi <- sf::st_as_sfc(sf::st_bbox( c(xmin = 600000, ymin = 6600000, xmax = 650000, ymax = 6650000), crs = 2154) ) departments <- get_departements_for_roi(roi)library(sf) roi <- sf::st_as_sfc(sf::st_bbox( c(xmin = 600000, ymin = 6600000, xmax = 650000, ymax = 6650000), crs = 2154) ) departments <- get_departements_for_roi(roi)
This function retrieves OCS GE (Land Cover) data for a specific Region of Interest (ROI) directly from a remote FlatGeobuf (.fgb) file hosted on a server (e.g., S3).
It leverages GDAL's virtual file system ('/vsicurl/') and the spatial indexing capabilities of FlatGeobuf to download only the data chunks intersecting the bounding box of the ROI, making it highly efficient for large datasets.
get_ocsge_data_fgb(roi, fgb_url)get_ocsge_data_fgb(roi, fgb_url)
roi |
An |
fgb_url |
Character string. The public URL to the remote '.fgb' file. |
The function performs the following steps:
Transforms the roi to Lambert-93 (EPSG:2154).
calculates the bounding box of the roi.
Uses sf::st_read with a WKT filter to fetch only relevant features from the remote file.
Applies a precise geometric intersection ('st_intersection') to clip the data to the exact shape of the roi.
An sf object containing the OCS GE polygons intersected by the ROI,
projected in Lambert-93 (EPSG:2154).
This function requires a working internet connection and GDAL support for the FlatGeobuf driver and network capabilities (vsicurl).
## Not run: library(sf) # 1. Define a Region of Interest (ROI) # Example: A small bounding box in France my_roi <- st_as_sf(data.frame( lon = c(2.3, 2.4, 2.4, 2.3, 2.3), lat = c(48.8, 48.8, 48.9, 48.9, 48.8) ), coords = c("lon", "lat"), crs = 4326) # 2. URL to the remote FlatGeobuf file # (Replace with the actual URL of your OCS GE bucket) url_fgb <- "https://example.com/data/ocsge_grand_est.fgb" # 3. Fetch data ocsge_data <- get_ocsge_data_fgb(roi = my_roi, fgb_url = url_fgb) # 4. Check result print(ocsge_data) plot(st_geometry(ocsge_data)) ## End(Not run)## Not run: library(sf) # 1. Define a Region of Interest (ROI) # Example: A small bounding box in France my_roi <- st_as_sf(data.frame( lon = c(2.3, 2.4, 2.4, 2.3, 2.3), lat = c(48.8, 48.8, 48.9, 48.9, 48.8) ), coords = c("lon", "lat"), crs = 4326) # 2. URL to the remote FlatGeobuf file # (Replace with the actual URL of your OCS GE bucket) url_fgb <- "https://example.com/data/ocsge_grand_est.fgb" # 3. Fetch data ocsge_data <- get_ocsge_data_fgb(roi = my_roi, fgb_url = url_fgb) # 4. Check result print(ocsge_data) plot(st_geometry(ocsge_data)) ## End(Not run)
Create a spatial Habitat object based on an optional sf data.frame.
If no geometry is provided, creates an empty Habitat object.
The object has columns:
habitat: logical, TRUE/FALSE
weight: numeric
geometry: sfc geometry
habitat(geometry = NULL, habitat = NULL, weight = NULL)habitat(geometry = NULL, habitat = NULL, weight = NULL)
geometry |
An object of class |
habitat |
Logical vector indicating habitat presence. Default is logical(0). |
weight |
Numeric vector of weights. Default is numeric(0). |
An object of class habitat, inheriting from sf and data.frame.
library(sf) # Empty habitat h <- habitat() h # Habitat with geometries geom <- st_sfc( st_point(c(0, 0)), st_point(c(1, 1)), crs = 4326 ) hab <- habitat( geometry = geom, habitat = c(TRUE, FALSE), weight = c(0.8, 0) ) hablibrary(sf) # Empty habitat h <- habitat() h # Habitat with geometries geom <- st_sfc( st_point(c(0, 0)), st_point(c(1, 1)), crs = 4326 ) hab <- habitat( geometry = geom, habitat = c(TRUE, FALSE), weight = c(0.8, 0) ) hab
Create a raster from a habitat object
habitat_raster(ground_raster, habitat)habitat_raster(ground_raster, habitat)
ground_raster |
SpatRaster (reference grid). |
habitat |
habitat object inherited from |
SpatRaster (weight and NA in nogo)
Creates and configures the trophic flux table with a simplified syntax.
intake(x, ..., default = NULL, normalize = TRUE)intake(x, ..., default = NULL, normalize = TRUE)
x |
A 'spacemodel' object or a 'trophic_tbl'. |
... |
Flux definitions. - Key '"Target"' (e.g., '"Fox" = 0.5'): applies to all links pointing to Fox. - Key '"Source -> Target"' (e.g., '"Soil -> Worm" = 0.8'): targets a specific link. Values can be numeric (linear coefficient), formulas, or functions. |
default |
The default function for unspecified links (default is identity). |
normalize |
Logical. Whether to normalize diet weights (default TRUE). |
A 'trophic_tbl' with a configured 'flux' column.
Implements Kahn's algorithm to detect cycles in a directed graph.
is_cyclic(df)is_cyclic(df)
df |
A data.frame with columns |
Logical. TRUE if the graph contains at least one cycle.
df <- data.frame(from=c("A","B"), to=c("B","A")) is_cyclic(df)df <- data.frame(from=c("A","B"), to=c("B","A")) is_cyclic(df)
A raster of the (example).
load_raster_extdata(path_name)load_raster_extdata(path_name)
path_name |
Path of the raster (.tiff) file to download. |
An object 'SpatRaster' (package terra).
A SpatRaster object
Internal data package.
Returns the upstream neighbors (prey/resources) of a given layer in a trophic graph.
lower_neighbors(trophic_tbl, layer)lower_neighbors(trophic_tbl, layer)
trophic_tbl |
A |
layer |
Name of the layer (string) in the spacemodel. |
A character vector of names of layers that are resources for layer.
Adds a new column normalized_weight to a trophic_tbl object so that,
for each target node (to), the sum of incoming weights equals 1.
normalize_weights(tbl)normalize_weights(tbl)
tbl |
A |
For every unique value in the to elements of the link column,
the function divides each corresponding weight by the total weight of all links
pointing to that same node.
Nodes with no incoming links are left unchanged.
A trophic_tbl object with an additional column
normalized_weight.
net <- trophic() |> add_link("a", "b", weight = 2) |> add_link("c", "b", weight = 3) net_norm <- normalize_weights(net)net <- trophic() |> add_link("a", "b", weight = 2) |> add_link("c", "b", weight = 3) net_norm <- normalize_weights(net)
Simple feature collection with 9 features and 11 fields. Projected CRS: RGF93 v1 / Lambert-93.
data(ocsge_metaleurop)data(ocsge_metaleurop)
An object of class sf (inherits from data.frame) with 9 rows and 12 columns.
data(ocsge_metaleurop)data(ocsge_metaleurop)
Valued weight between OCSGE layer and species
data(ocsge_species_dict)data(ocsge_species_dict)
An object of class data.frame with 13090 rows and 6 columns.
data(ocsge_species_dict)data(ocsge_species_dict)
Creates a simple graphical representation of a trophic network using ggplot2.
## S3 method for class 'trophic_tbl' plot(x, shift = TRUE, ...)## S3 method for class 'trophic_tbl' plot(x, shift = TRUE, ...)
x |
A |
shift |
To shift x_axis between trophic level and avoid the potential overlapping of arrows. |
... |
Additional arguments (not used, for S3 consistency). |
Nodes are positioned according to their trophic level:
The y-axis represents trophic levels
Nodes of the same level are placed on the same horizontal line
The x-axis positions are assigned sequentially (0, 1, 2, ...)
Directed links are drawn from lower to higher trophic levels using arrows.
A ggplot object.
net <- trophic() |> add_link("a", "b") |> add_link("b", "c") plot(net)net <- trophic() |> add_link("a", "b") |> add_link("b", "c") plot(net)
This function creates a 'SpatRaster' stack from a list of rasters and assigns unique names to each layer.
raster_stack(raster_list, names = NULL)raster_stack(raster_list, names = NULL)
raster_list |
A list of 'SpatRaster' objects or file paths to raster files. |
names |
A character vector of unique names for each raster layer in the stack. |
The function checks that the length of 'raster_list' matches the length of 'names', and that all names are unique. If not, it stops with an error.
A SpatRaster object with named layers.
# Example with terra rasters library(terra) r1 <- rast(nrows=10, ncols=10, vals=1:100) r2 <- rast(nrows=10, ncols=10, vals=101:200) raster_stack(list(r1, r2), c("layer1", "layer2"))# Example with terra rasters library(terra) r1 <- rast(nrows=10, ncols=10, vals=1:100) r2 <- rast(nrows=10, ncols=10, vals=101:200) raster_stack(list(r1, r2), c("layer1", "layer2"))
Nomenclature of OCS-GE soil cover
data(ref_ocsge)data(ref_ocsge)
An object of class data.frame with 14 rows and 4 columns.
data(ref_ocsge)data(ref_ocsge)
Simple feature collection with 1 feature and 1 field. Geodetic CRS: WGS 84.
data(roi_metaleurop)data(roi_metaleurop)
An object of class sf (inherits from data.frame) with 1 rows and 2 columns.
data(roi_metaleurop)data(roi_metaleurop)
DataBase of collected MicroMammals species
data(sf_micromammals)data(sf_micromammals)
An object of class sf (inherits from tbl_df, tbl, data.frame) with 1426 rows and 27 columns.
data(sf_micromammals)data(sf_micromammals)
Constructor for the 'spacemodel' class. This function combines spatial data (a raster stack) and ecological data (a trophic table) into a single object used for modelling.
spacemodel(raster_stack, trophic_tbl)spacemodel(raster_stack, trophic_tbl)
raster_stack |
A |
trophic_tbl |
An object of class |
The function performs several checks to ensure data consistency:
Verifies that raster_stack is a SpatRaster.
Verifies that trophic_tbl is a trophic_tbl object.
Ensures the number of raster layers matches the number of levels in the trophic table.
Ensures that the names of the raster layers match the names in the trophic table.
A SpatRaster object with the following additional attributes:
trophic_tbl: The trophic_tbl object passed as input.
spacemodel: A logical flag set to TRUE, indicating this raster
is part of a spacemodel.
rast, trophic_tbl
Computes the transfer through a trophic network from lower to higher trophic levels using spatial spreading and intake functions.
transfer( spacemodel, kernels, intakes = NULL, exposure_weighting = "local", verbose = FALSE )transfer( spacemodel, kernels, intakes = NULL, exposure_weighting = "local", verbose = FALSE )
spacemodel |
A named list of spatial layers (e.g. |
kernels |
A list of kernel parameters for each layer. |
intakes |
A |
exposure_weighting |
Character. Defines how the realized exposure is calculated based on the predator's presence. Options are:
|
verbose |
Logical. If |
The function processes layers in ascending trophic order, as defined
by the level attribute of the trophic table.
For each layer:
Resources (lower neighbors) are identified.
Concentration from each resource is spatially spread using spread().
Intake is computed using intake().
Contributions from all resources are summed.
The function assumes that intake weights are already normalized so that, for each consumer, the sum of contributions from all resources equals 1.
A named 'spacemodel' object as a list of spatial layers representing values after transfer.
Creates a data.frame of class trophic_tbl designed to store trophic links.
Can be initialized empty or from an existing data.frame.
trophic(data = NULL, from = NULL, to = NULL, weight = NULL)trophic(data = NULL, from = NULL, to = NULL, weight = NULL)
data |
(Optional) A data.frame containing link information. |
from |
(Optional) Character string. Name of the column in |
to |
(Optional) Character string. Name of the column in |
weight |
(Optional) Character string. Name of the column in |
An object of class trophic_tbl.
# 1. Empty initialization (pipe style) net <- trophic() |> add_link("sol", "sp1") # 2. Initialization from data.frame df_raw <- data.frame(src = c("A", "A"), target = c("B", "C"), w = c(2, 5)) net_from_df <- trophic(df_raw, from = "src", to = "target", weight = "w")# 1. Empty initialization (pipe style) net <- trophic() |> add_link("sol", "sp1") # 2. Initialization from data.frame df_raw <- data.frame(src = c("A", "A"), target = c("B", "C"), w = c(2, 5)) net_from_df <- trophic(df_raw, from = "src", to = "target", weight = "w")