Package 'metaweave'

Title: Spatial Ecological Network Inference
Description: A model-agnostic framework for reconstructing and analysing spatially explicit ecological networks from species distributions and ecological inference models. Supports arbitrary ecological groups and includes stochastic block and maximum-entropy inference backends, simulation helpers, network summaries, and spatial mapping utilities.
Authors: Gabriel Munoz [aut, cre]
Maintainer: Gabriel Munoz <[email protected]>
License: MIT + file LICENSE
Version: 0.4.0
Built: 2026-10-07 11:21:55 UTC
Source: https://github.com/fgabriel1891/metaweave

Help Index


Add standard metrics to network collection

Description

Add standard metrics to network collection

Usage

add_network_metrics(x, threshold = NULL)

Arguments

x

Network collection.

threshold

Optional probability threshold.


Assemble local communities from aligned distribution rasters

Description

Assemble local communities from aligned distribution rasters

Usage

assemble_communities(distributions, min_species = 1L)

Arguments

distributions

Named list of SpatRaster or distribution_collection objects.

min_species

Minimum species per group.


Construct a generic stochastic block model backend

Description

Construct a generic stochastic block model backend

Usage

block_model(
  row_lookup,
  column_lookup,
  theta,
  row_group,
  column_group,
  species_col = "species",
  guild_col = "guild"
)

Arguments

row_lookup

Data frame mapping species in the matrix rows to blocks.

column_lookup

Data frame mapping species in the matrix columns to blocks.

theta

Guild-by-guild probability matrix.

row_group

Name of the assemblage group placed in matrix rows.

column_group

Name of the assemblage group placed in matrix columns.

species_col

Species column in lookup tables.

guild_col

Guild column in lookup tables.


Build a species range stack

Description

Build a species range stack

Usage

build_range_stack(
  source,
  template,
  species_col = NULL,
  species_keep = NULL,
  region = NULL,
  touches = TRUE
)

Arguments

source

Directory, vector file, sf, or SpatVector.

template

Raster template.

species_col

Species column for multi-species data.

species_keep

Optional species subset.

region

Optional crop region.

touches

Count all touched cells.


Create a standard raster grid

Description

Create a standard raster grid

Usage

create_standard_grid(
  extent = c(-180, 180, -90, 90),
  resolution = 1,
  crs = "EPSG:4326"
)

Arguments

extent

Numeric vector c(xmin, xmax, ymin, ymax).

resolution

Cell resolution.

crs

Coordinate reference system.


Crop a stack and remove species absent from the region

Description

Crop a stack and remove species absent from the region

Usage

crop_filter_stack(stack, region, return_cropped = TRUE)

Arguments

stack

Species raster stack.

region

Crop region.

return_cropped

Return cropped rather than original layers.


Compatibility wrapper for spatial network downscaling

Description

Compatibility wrapper for spatial network downscaling

Usage

downscale_networks(
  palm_stack,
  mammal_stack,
  palm_lookup,
  mammal_lookup,
  theta,
  species_col = "species",
  guild_col = "guild",
  min_palms = 1L,
  min_mammals = 1L
)

Arguments

palm_stack, mammal_stack

Aligned species distribution rasters.

palm_lookup, mammal_lookup

Species-to-guild lookup tables.

theta

Guild-by-guild probability matrix.

species_col

Species column in lookup tables.

guild_col

Guild column in lookup tables.

min_palms, min_mammals

Minimum local richness in each group.


Infer a network for one assemblage

Description

Infer a network for one assemblage

Usage

infer_network(assemblage, model)

Arguments

assemblage

An assemblage.

model

An inference model.


Infer networks for many assemblages

Description

Infer networks for many assemblages

Usage

infer_networks(assemblages, model, template = NULL)

Arguments

assemblages

List of assemblages.

model

Inference model.

template

Optional spatial template.


Convert an interaction table to a matrix

Description

Convert an interaction table to a matrix

Usage

interaction_table_to_matrix(data, row_col, column_col, value_col, fill = 0)

Arguments

data

Data frame.

row_col, column_col, value_col

Column names.

fill

Missing-pair value.


List ESRI shapefiles

Description

List ESRI shapefiles

Usage

list_shapefiles(path, recursive = FALSE)

Arguments

path

Directory.

recursive

Search recursively.


Build one local generic block-model network directly

Description

Build one local generic block-model network directly

Usage

local_block_network(
  rows,
  columns,
  row_lookup,
  column_lookup,
  theta,
  row_group = "rows",
  column_group = "columns",
  species_col = "species",
  guild_col = "guild",
  cell_id = NA_integer_
)

Arguments

rows, columns

Species names in each network group.

row_lookup

Data frame mapping species in the matrix rows to blocks.

column_lookup

Data frame mapping species in the matrix columns to blocks.

theta

Guild-by-guild probability matrix.

row_group

Name of the assemblage group placed in matrix rows.

column_group

Name of the assemblage group placed in matrix columns.

species_col

Species column in lookup tables.

guild_col

Guild column in lookup tables.

cell_id

Optional raster cell identifier.


Build one local palm-mammal probability network directly

Description

Compatibility wrapper around local_block_network().

Usage

local_probability_network(
  palms,
  mammals,
  palm_lookup,
  mammal_lookup,
  theta,
  species_col = "species",
  guild_col = "guild",
  cell_id = NA_integer_
)

Arguments

palms, mammals

Species names in each network group.

palm_lookup, mammal_lookup

Species-to-guild lookup tables.

theta

Guild-by-guild probability matrix.

species_col

Species column in lookup tables.

guild_col

Guild column in lookup tables.

cell_id

Optional raster cell identifier.


Create a bounding-box polygon

Description

Create a bounding-box polygon

Usage

make_bbox(extent, crs = "EPSG:4326")

Arguments

extent

Numeric vector c(xmin, xmax, ymin, ymax).

crs

Coordinate reference system.


Map cell metrics back to rasters

Description

Map cell metrics back to rasters

Usage

map_metrics(x, metrics = NULL)

Arguments

x

Network collection with metrics in its index.

metrics

Metric columns; inferred when omitted.


Maximum-entropy ecological network model

Description

Constructs a directed network inference backend that generates binary adjacency matrices under hard structural constraints and returns their marginal species-pair probabilities. Rows are consumers, columns are resources, and matrix[i, j] = 1 means consumer i uses resource j.

Usage

maxent_model(
  row_group,
  column_group = row_group,
  constraint = c("connectance", "links", "degree_sequence"),
  connectance = NULL,
  links = NULL,
  out_degree = NULL,
  in_degree = NULL,
  ensemble_size = 100L,
  self_links = FALSE,
  seed = 1L,
  burn_in = 1000L,
  thin = 100L,
  keep_ensemble = FALSE
)

Arguments

row_group

Assemblage group represented by matrix rows (consumers).

column_group

Assemblage group represented by matrix columns (resources). May equal row_group for a directed unipartite food web.

constraint

One of "connectance", "links", or "degree_sequence".

connectance

Desired connectance in ⁠[0, 1]⁠. Converted to an exact local link count with round(connectance * allowed_dyads).

links

Exact number of interactions in every local ensemble member.

out_degree

Row sums (numbers of resources per consumer).

in_degree

Column sums (numbers of consumers per resource). Degree constraints may be named numeric vectors or functions accepting the locally present species names and returning a numeric vector.

ensemble_size

Number of adjacency matrices used for marginal probabilities.

self_links

Whether a species may interact with itself when its name appears in both groups.

seed

Integer seed. A cell identifier is added to this seed so spatial cells receive distinct reproducible ensembles. The previous global random state is restored after inference. Use NULL to use normal R RNG behavior.

burn_in

Number of degree-preserving swap proposals before recording a degree-constrained ensemble.

thin

Number of swap proposals between recorded matrices.

keep_ensemble

Store binary ensemble members in network metadata.

Details

For constraint = "connectance" or "links", networks are sampled uniformly from all allowed adjacency matrices with exactly the requested number of links. This is the maximum-entropy distribution under a hard link count. For constraint = "degree_sequence", a feasible matrix is found by maximum flow and randomized with degree-preserving checkerboard swaps. This is an approximate uniform MCMC ensemble conditional on the supplied margins.

The implementation follows the constrained, minimally biased ensemble rationale of Banville, Gravel & Poisot (2023), but does not yet implement their SVD-entropy objective or simulated-annealing optimizer.

Value

An inference_model compatible with infer_network() and infer_networks().

References

Banville F, Gravel D, Poisot T (2023). What constrains food webs? A maximum entropy framework for predicting their structure with minimal biases. PLOS Computational Biology 19: e1011458. doi:10.1371/journal.pcbi.1011458

Examples

assemblage <- new_assemblage(list(food_web = c("a", "b", "c")))
model <- maxent_model(
  row_group = "food_web",
  constraint = "connectance",
  connectance = 0.25,
  ensemble_size = 50,
  self_links = FALSE,
  seed = 42
)
network <- infer_network(assemblage, model)
network$matrix

Compatibility alias returning metric rasters

Description

Compatibility alias returning metric rasters

Usage

network_metrics_raster(x, metrics = NULL)

Arguments

x

Network collection with metrics in its index.

metrics

Metric columns; inferred when omitted.


Construct a local assemblage

Description

Construct a local assemblage

Usage

new_assemblage(species, cell_id = NA_integer_, coordinates = NULL)

Arguments

species

Named list of character vectors, one per ecological group.

cell_id

Optional raster cell identifier.

coordinates

Optional named numeric vector containing x and y.


Construct a distribution collection

Description

Construct a distribution collection

Usage

new_distribution_collection(data, guild = NULL, metadata = NULL)

Arguments

data

A named terra::SpatRaster whose layers represent species.

guild

Optional guild label for the collection.

metadata

Optional species metadata data frame.


Construct an ecological network

Description

Construct an ecological network

Usage

new_ecological_network(
  matrix,
  type = c("probability", "binary", "weighted", "observed"),
  metadata = list(),
  row_group = "rows",
  column_group = "columns",
  directed = FALSE,
  self_links = NA
)

Arguments

matrix

Numeric interaction matrix.

type

One of probability, binary, weighted, or observed.

metadata

Optional metadata.

row_group, column_group

Ecological groups represented by rows and columns.

directed

Whether matrix orientation represents directed interactions.

self_links

Whether self-links are permitted; NA when not applicable.


Construct a pluggable inference model

Description

Construct a pluggable inference model

Usage

new_inference_model(
  predict,
  name = "custom",
  parameters = list(),
  subclass = NULL
)

Arguments

predict

A function accepting ⁠(model, assemblage)⁠ and returning an ecological network.

name

Model name.

parameters

Model-specific parameters.

subclass

Optional additional class name.


Construct a collection of spatial ecological networks

Description

Construct a collection of spatial ecological networks

Usage

new_network_collection(networks, index, template = NULL, settings = list())

Arguments

networks

List of ecological networks.

index

Cell-level data frame.

template

Spatial raster template.

settings

Optional workflow settings.


Construct a spatial result

Description

Construct a spatial result

Usage

new_spatial_result(data, metrics = names(data))

Arguments

data

A spatial object.

metrics

Names of mapped metrics.


Prepare palm and mammal range stacks

Description

Prepare palm and mammal range stacks

Usage

prepare_range_stacks(
  palm_source,
  mammal_source,
  mammal_species_col,
  mammal_species_keep = NULL,
  template = create_standard_grid(),
  region = NULL,
  output_dir = NULL,
  touches = TRUE
)

Arguments

palm_source, mammal_source

Range sources accepted by build_range_stack().

mammal_species_col

Species-name column in the mammal source.

mammal_species_keep

Optional mammal species subset.

template

Raster template.

region

Optional crop region.

output_dir

Optional directory in which to save the range stacks.

touches

Count all touched cells.


Print a MetaWeave object

Description

Prints a compact summary of an assemblage, distribution collection, ecological network, inference model, or network collection. The object is returned invisibly. These methods are normally called through print().


Construct a species-level probability-matrix model

Description

Use this backend when an external model returns probabilities for named species pairs directly, including ensemble-averaged predictions for which no single coherent block partition exists.

Usage

probability_matrix_model(
  probability_matrix,
  row_group,
  column_group,
  name = "species probability matrix"
)

Arguments

probability_matrix

Numeric species-by-species probability matrix. Row and column names are required and must be unique.

row_group

Assemblage group corresponding to matrix rows.

column_group

Assemblage group corresponding to matrix columns.

name

Descriptive model name stored in outputs.


Placeholder adapter for rarefaction packages

Description

Simulates a standardized count matrix and evaluates a user-supplied metric function.

Usage

rarefied_network_metric(
  prob_mat,
  target_size = 100L,
  metric,
  n_per_level = 10L,
  seed = NULL
)

Arguments

prob_mat

Probability matrix.

target_size

Standardized number of interactions.

metric

A function accepting a count matrix.

n_per_level

Number of replicates.

seed

Optional seed.


Rasterize one range file

Description

Rasterize one range file

Usage

rasterize_range_file(shp_file, template, touches = TRUE)

Arguments

shp_file

Shapefile path.

template

Raster template.

touches

Count all touched cells.


Rasterize rows grouped by species

Description

Rasterize rows grouped by species

Usage

rasterize_range_rows(
  x,
  template,
  species_col,
  species_keep = NULL,
  touches = TRUE
)

Arguments

x

An sf or SpatVector object.

template

Raster template.

species_col

Species-name column.

species_keep

Optional species subset.

touches

Count all touched cells.


Reconstruct spatial networks from arbitrary distribution groups

Description

Reconstruct spatial networks from arbitrary distribution groups

Usage

reconstruct_networks(distributions, model, min_species = 1L)

Arguments

distributions

Named list of aligned distribution rasters or collections.

model

Inference model whose group names match distributions.

min_species

Minimum number of locally present species required in every group.


Complete compatibility workflow

Description

Complete compatibility workflow

Usage

run_network_downscaling(...)

Arguments

...

Arguments passed to downscale_networks().


Run generic spatial ecological-network inference

Description

Run generic spatial ecological-network inference

Usage

run_spatial_inference(distributions, model, min_species = 1L, threshold = NULL)

Arguments

distributions

Named distribution groups.

model

Inference model.

min_species

Minimum local richness in each group.

threshold

Optional probability threshold for network summaries.


Construct the original palm-mammal SBM backend

Description

Compatibility wrapper around block_model().

Usage

sbm_model(
  palm_lookup,
  mammal_lookup,
  theta,
  species_col = "species",
  guild_col = "guild"
)

Arguments

palm_lookup, mammal_lookup

Species-to-guild lookup tables.

theta

Guild-by-guild probability matrix.

species_col

Species column in lookup tables.

guild_col

Guild column in lookup tables.


Simulate an interaction-count matrix

Description

Simulate an interaction-count matrix

Usage

simulate_interaction_counts(network, size = 100L, seed = NULL)

Arguments

network

Ecological network or probability matrix.

size

Total number of interactions.

seed

Optional random seed.


Simulate a network

Description

Simulate a network

Usage

simulate_network(network, size = 100L, seed = NULL)

Arguments

network

Probability network.

size

Total interaction count.

seed

Optional seed.


Summarize one ecological network

Description

Summarize one ecological network

Usage

summarize_network(network, threshold = NULL)

Arguments

network

Ecological network or numeric matrix.

threshold

Optional threshold for realized links.


Summarize a collection of networks

Description

Summarize a collection of networks

Usage

summarize_networks(x, threshold = NULL)

Arguments

x

Network collection.

threshold

Optional probability threshold.