Package 'terralink'

Title: Connectivity Corridor Optimization for Raster and Vector Data
Description: Standalone R implementation of habitat connectivity corridor optimization for raster and vector workflows. Supports scenario-based planning with budget-constrained optimization, optional impassable areas, packaged parity fixtures, and comparative before-and-after connectivity metrics. The package exposes structural, movement-oriented, and species-oriented strategies in a reproducible workflow aligned with a companion GIS plugin while avoiding a desktop GIS dependency.
Authors: Benjamin Bishop [aut, cre], SORUS Consulting LLC [fnd, cph]
Maintainer: Benjamin Bishop <[email protected]>
License: MIT + file LICENSE
Version: 1.8.0
Built: 2026-05-12 21:39:45 UTC
Source: https://github.com/cran/terralink

Help Index


Build contiguous network raster (patches + corridors)

Description

Build contiguous network raster (patches + corridors)

Usage

build_contiguous_raster(habitat_mask, corridor_raster, connectivity = 8)

Arguments

habitat_mask

SpatRaster of habitat.

corridor_raster

SpatRaster of corridors.

connectivity

Connectivity for patches (4 or 8).

Value

SpatRaster with component sizes.


Create corridor raster from selected edges

Description

Create corridor raster from selected edges

Usage

build_corridor_raster(
  labels,
  patch_df,
  corridors,
  min_corridor_width_px = 1,
  assignment_mode = "sum_total_network_area"
)

Arguments

labels

SpatRaster labels.

patch_df

Patch summary data frame.

corridors

Data frame with patch1, patch2, and optional line geometry.

min_corridor_width_px

Width (pixels) for buffering corridors.

assignment_mode

Corridor cell assignment mode.

Value

SpatRaster with corridor cells set by assignment mode.


Build an igraph graph from patch ids and corridor edges

Description

Build an igraph graph from patch ids and corridor edges

Usage

build_graph_from_corridors(patches, corridors, distance_col = "distance_m")

Arguments

patches

Patch ids (vector) or data frame with column id.

corridors

Data frame with patch1, patch2, and optional distance column.

distance_col

Column name to use for edge distance/weight.

Value

An igraph graph.


Build candidate edges between patches (centroid distance)

Description

Build candidate edges between patches (centroid distance)

Usage

build_patch_candidates(patch_df, max_search_distance, raster_ref)

Arguments

patch_df

Patch summary data frame.

max_search_distance

Maximum distance in pixels.

raster_ref

Raster reference for pixel size.

Value

Data frame with patch1, patch2, cost, distance_map, id.


Build raster candidates using shortest paths

Description

Build raster candidates using shortest paths

Usage

build_raster_candidates(
  labels,
  patch_df,
  passable_mask,
  max_search_distance_px,
  raster_ref,
  min_corridor_width_px = 1,
  pair_index = NULL,
  patch_connectivity = 4,
  habitat_mask = NULL,
  obstacle_mask = NULL
)

Arguments

labels

SpatRaster of filtered patch labels.

patch_df

Patch summary data frame.

passable_mask

SpatRaster with 1 for passable cells.

max_search_distance_px

Max search distance in pixels.

raster_ref

Raster reference for CRS/resolution.

min_corridor_width_px

Corridor width in pixels (used for area-based candidate cost).

pair_index

Optional two-column matrix of patch index pairs to evaluate.

patch_connectivity

Patch connectivity (4 or 8).

habitat_mask

SpatRaster of habitat (pre-filter), optional.

obstacle_mask

SpatRaster of blocked pixels, optional.

Value

Data frame of candidates with geometry.


Calculate disturbance penalty (diameter normalized)

Description

Calculate disturbance penalty (diameter normalized)

Usage

calculate_disturbance_penalty(graph)

Arguments

graph

igraph graph.

Value

Numeric penalty.


Estimate failure probability via edge removal

Description

Estimate failure probability via edge removal

Usage

calculate_failure_probability(graph, k_failures = 1, iterations = 100)

Arguments

graph

igraph graph.

k_failures

Number of edges removed each trial.

iterations

Number of Monte Carlo iterations.

Value

Failure probability.


Calculate movement entropy for a graph

Description

Calculate movement entropy for a graph

Usage

calculate_movement_entropy(graph, alpha = 0.002)

Arguments

graph

igraph graph.

alpha

Dispersal kernel parameter.

Value

Numeric entropy value.


Calculate topology penalty (cycle count)

Description

Calculate topology penalty (cycle count)

Usage

calculate_topology_penalty(graph)

Arguments

graph

igraph graph.

Value

Numeric penalty.


Calculate total entropy summary

Description

Calculate total entropy summary

Usage

calculate_total_entropy(graph, lambda_c = 1, lambda_f = 1, lambda_d = 1)

Arguments

graph

igraph graph.

lambda_c

Connectivity penalty multiplier.

lambda_f

Topology penalty multiplier.

lambda_d

Disturbance penalty multiplier.

Value

Named list of entropy components.


Calculate the fraction of node pairs with two edge-disjoint paths

Description

Calculate the fraction of node pairs with two edge-disjoint paths

Usage

calculate_two_edge_connectivity(graph)

Arguments

graph

igraph graph.

Value

Numeric ratio.


Label contiguous habitat patches

Description

Label contiguous habitat patches

Usage

label_patches(mask, connectivity = 8)

Arguments

mask

Logical SpatRaster mask.

connectivity

4 or 8.

Value

SpatRaster of patch labels.


Network optimizer for corridor selection

Description

Implements a two-phase optimizer: MST backbone, then optional loop additions.

Methods

initialize

Create a new optimizer with nodes.

add_candidate

Add a candidate edge.

solve

Run optimization.

Public fields

nodes

Node weights.

edges

Candidate edge list.

uf

UnionFind instance.

Methods

Public methods


Method new()

Usage
NetworkOptimizer$new(nodes)
Arguments
nodes

Named numeric vector of node weights.

nodes

Named numeric vector of node weights.


Method add_candidate()

Usage
NetworkOptimizer$add_candidate(u, v, cand_id, cost)
Arguments
u

Candidate edge start node.

u

Candidate edge start node.

v

Candidate edge end node.

v

Candidate edge end node.

cand_id

Candidate edge id.

cand_id

Candidate edge id.

cost

Candidate edge cost.

cost

Candidate edge cost.


Method solve()

Usage
NetworkOptimizer$solve(budget, loop_fraction = 0.05, max_redundancy = 2)
Arguments
budget

Numeric budget for corridor costs.

budget

Numeric budget for corridor costs.

loop_fraction

Fraction of budget reserved for loops.

loop_fraction

Fraction of budget reserved for loops.

max_redundancy

Max redundant edges per component.

max_redundancy

Max redundant edges per component.


Method clone()

The objects of this class are cloneable with this method.

Usage
NetworkOptimizer$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.


Create a candidate corridor descriptor

Description

Create a candidate corridor descriptor

Usage

new_candidate(patch_ids, cost, weight = NULL, geometry = NULL)

Arguments

patch_ids

Integer vector of patch ids.

cost

Numeric cost of the corridor.

weight

Numeric benefit or ROI.

geometry

Optional geometry object.

Value

A candidate list with class 'terralink_candidate'.


Create a patch descriptor

Description

Create a patch descriptor

Usage

new_patch(id, weight, geometry = NULL)

Arguments

id

Patch identifier.

weight

Numeric patch weight (area, quality).

geometry

Optional geometry object.

Value

A patch list with class 'terralink_patch'.


Optimize for largest connected network (MST backbone + loops)

Description

Optimize for largest connected network (MST backbone + loops)

Usage

optimize_largest_network(
  nodes,
  edges,
  budget,
  loop_fraction = 0.05,
  max_redundancy = 2
)

Arguments

nodes

Named numeric vector of patch sizes.

edges

Data frame with u, v, id, cost columns.

budget

Numeric budget for corridor cost.

loop_fraction

Fraction of budget reserved for loops.

max_redundancy

Max redundant edges per component.

Value

List with selected ids and summary.


Optimize a network given nodes and candidate edges

Description

Optimize a network given nodes and candidate edges

Usage

optimize_network(
  nodes,
  edges,
  budget,
  loop_fraction = 0.05,
  max_redundancy = 2
)

Arguments

nodes

Named numeric vector of node weights.

edges

Data frame with columns u, v, id, cost.

budget

Numeric budget for corridor costs.

loop_fraction

Fraction of budget reserved for loops.

max_redundancy

Max redundant edges per component.

Value

List with selected edge ids, component sizes/counts, and total cost.


Choose optimization strategy

Description

Choose optimization strategy

Usage

optimize_strategy(strategy, nodes, edges, candidates, budget, ...)

Arguments

strategy

Strategy name.

nodes

Named numeric vector of patch sizes.

edges

Data frame with u, v, id, cost.

candidates

Candidate list (for circuit utility).

budget

Numeric budget.

...

Additional args forwarded to circuit utility selector.

Value

List with selected ids and stats.


Summarize patch labels into a data frame

Description

Summarize patch labels into a data frame

Usage

patch_summary_from_labels(labels)

Arguments

labels

SpatRaster of patch labels.

Value

Data frame with patch_id, cell_count, area, x, y.


Create a logical mask from raster values

Description

Create a logical mask from raster values

Usage

raster_mask_from_values(raster, values)

Arguments

raster

SpatRaster.

values

Numeric values to keep.

Value

Logical SpatRaster mask.


Run TerraLink raster workflow

Description

Run TerraLink raster workflow

Usage

run_raster_analysis(
  raster,
  patch_values,
  budget = NULL,
  budget_pixels = NULL,
  strategy = "most_connected_networks",
  min_patch_size = 10,
  min_corridor_width = 3,
  corridor_cell_assignment = "sum_total_network_area",
  max_search_distance = 100,
  obstacle_values = NULL,
  obstacle_ranges = NULL,
  allow_bottlenecks = FALSE,
  patch_connectivity = 4,
  units = "pixels",
  patch_ranges = NULL,
  allow_large = FALSE,
  max_pair_checks = 2e+06,
  max_candidates = 2e+05,
  verbose = 0,
  progress = FALSE,
  obstacle_strategy = c("error", "straight_line", "disable_obstacles"),
  pc_alpha = NULL,
  pc_cutoff = NULL,
  species_dispersal_distance = NULL,
  species_dispersal_kernel = HABITAT_AVAILABILITY_DEFAULT_KERNEL,
  min_patch_area_for_species = 0,
  patch_area_scaling = HABITAT_AVAILABILITY_DEFAULT_SCALING,
  mobility_detour_cap = 8,
  redundancy_method = "ime",
  keep_candidates = FALSE
)

Arguments

raster

SpatRaster or path to raster.

patch_values

Numeric values representing habitat.

budget

Total corridor budget (units defined by units).

budget_pixels

Back-compat alias for budget (pixels).

strategy

Strategy name. Canonical values are "most_connected_networks", "most_connected_networks_2", "largest_single_network", and "landscape_fluidity".

min_patch_size

Minimum patch size (units defined by units).

min_corridor_width

Minimum corridor width (units defined by units).

corridor_cell_assignment

Corridor cell assignment mode.

max_search_distance

Maximum search distance (units defined by units).

obstacle_values

Optional impassable raster values.

obstacle_ranges

Optional list of impassable ranges.

allow_bottlenecks

Whether to allow corridors to squeeze through gaps.

patch_connectivity

Connectivity for patch labeling (4 or 8).

units

Unit system: "pixels", "metric", or "imperial".

patch_ranges

Optional list of value ranges defining habitat.

allow_large

Allow processing very large rasters.

max_pair_checks

Limit for candidate pair checks (prevents O(n^2) blowups).

max_candidates

Limit for candidate corridors.

verbose

Verbosity level (0-2).

progress

Show progress bars.

obstacle_strategy

Behavior when gdistance is unavailable and obstacles are provided.

pc_alpha

Optional dispersal alpha used by Probability of Connectivity metrics.

pc_cutoff

Optional cutoff distance used by Probability of Connectivity metrics.

species_dispersal_distance

Species movement distance used by habitat-availability reporting.

species_dispersal_kernel

Dispersal kernel for habitat availability.

min_patch_area_for_species

Minimum patch area eligible for species metrics.

patch_area_scaling

Patch-area scaling for habitat availability ("sqrt" or "log").

mobility_detour_cap

Cap used by graph-based mobility/fluidity metrics.

redundancy_method

Flow redundancy method ("ime" or "fri").

keep_candidates

Whether to keep candidate list in the output.

Details

Raster inputs are funneled through TerraLink's vector corridor pipeline after habitat and impassable classes are polygonized, matching the current QGIS plugin workflow.

Value

List with patches, corridors, rasters, and summary.


Run TerraLink vector workflow

Description

Run TerraLink vector workflow

Usage

run_vector_analysis(
  patches,
  budget,
  strategy = "most_connected_networks",
  min_patch_size = NULL,
  min_corridor_width = 100,
  max_search_distance = 5000,
  obstacle_layers = NULL,
  obstacle_resolution = NULL,
  units = "metric",
  max_pair_checks = 2e+06,
  max_candidates = 2e+05,
  verbose = 0,
  progress = FALSE,
  obstacle_strategy = c("error", "straight_line", "disable_obstacles"),
  return_crs = c("input", "utm"),
  pc_alpha = NULL,
  pc_cutoff = NULL,
  species_dispersal_distance = NULL,
  species_dispersal_kernel = HABITAT_AVAILABILITY_DEFAULT_KERNEL,
  min_patch_area_for_species = 0,
  patch_area_scaling = HABITAT_AVAILABILITY_DEFAULT_SCALING,
  patch_quality_field = NULL,
  mobility_detour_cap = 8,
  redundancy_method = "ime",
  keep_candidates = FALSE
)

Arguments

patches

sf polygons (one feature per patch) or file path.

budget

Corridor budget (ha/ac).

strategy

Strategy name. Canonical values are "most_connected_networks", "most_connected_networks_2", "largest_single_network", and "landscape_fluidity".

min_patch_size

Minimum patch size (ha/ac).

min_corridor_width

Minimum corridor width (m/ft).

max_search_distance

Maximum search distance (m/ft).

obstacle_layers

Optional obstacle layers (sf or file paths).

obstacle_resolution

Raster resolution for obstacle routing.

units

"metric" or "imperial".

max_pair_checks

Limit for candidate pair checks.

max_candidates

Limit for candidate corridors.

verbose

Verbosity level (0-2).

progress

Show progress bars.

obstacle_strategy

Behavior when gdistance is unavailable and obstacles are provided.

return_crs

CRS for outputs ("input" or "utm").

pc_alpha

Optional dispersal alpha used by Probability of Connectivity metrics.

pc_cutoff

Optional cutoff distance used by Probability of Connectivity metrics.

species_dispersal_distance

Species movement distance used by habitat-availability reporting.

species_dispersal_kernel

Dispersal kernel for habitat availability.

min_patch_area_for_species

Minimum patch area eligible for species metrics.

patch_area_scaling

Patch-area scaling for habitat availability ("sqrt" or "log").

patch_quality_field

Optional numeric field used to weight patch quality in vector mode.

mobility_detour_cap

Cap used by graph-based mobility/fluidity metrics.

redundancy_method

Flow redundancy method ("ime" or "fri").

keep_candidates

Keep candidate list in output.

Value

List with corridors, networks, and summary.


Score a loop edge for shortcut value

Description

Score a loop edge for shortcut value

Usage

score_edge_for_loops(graph, u, v, weight)

Arguments

graph

igraph graph.

u

First node id.

v

Second node id.

weight

Edge cost.

Value

Numeric score.


Select corridors for the "Most Connectivity" strategy

Description

Greedy ROI-based selector with dynamic rescoring, bridge seeding, and optional overlap checks.

Usage

select_circuit_utility(
  candidates,
  budget,
  get_patch_ids,
  get_pair_key,
  get_cost,
  get_base_roi,
  get_length,
  get_patch_size,
  overlap_ratio,
  global_overlap_ratio = NULL,
  overlap_obj,
  redundancy_distance_ok = NULL,
  overlap_reject_ratio = 0.3,
  global_overlap_reject_ratio = 0.6,
  max_prior_per_pair = 3,
  diminishing_base = 0.5,
  max_links_per_pair = Inf,
  enable_bridge_pairs = TRUE,
  bridge_max_per_patch = 25,
  distance_guard_for_primary = FALSE,
  global_overlap_for_primary = FALSE,
  parallel_dominance_ratio = 1.35,
  parallel_overlap_penalty_floor = 0.2,
  shortcut_ratio_high = 3,
  shortcut_ratio_mid = 1.5,
  shortcut_ratio_low = 1.5,
  shortcut_mult_high = 0.9,
  shortcut_mult_mid = 0.5,
  shortcut_mult_low = 0.1
)

Arguments

candidates

Iterable of candidate objects (data.frame rows or lists).

budget

Total corridor budget.

get_patch_ids

Function that returns patch ids for a candidate.

get_pair_key

Function that returns a sorted pair key for a candidate.

get_cost

Function that returns candidate cost.

get_base_roi

Function that returns candidate base ROI.

get_length

Function that returns candidate length for shortcut scoring.

get_patch_size

Function that returns patch size by id.

overlap_ratio

Function that returns overlap ratio vs prior objects.

global_overlap_ratio

Optional function that returns broader overlap ratio vs globally selected objects.

overlap_obj

Function that returns overlap object representation.

redundancy_distance_ok

Optional callback that can reject near-duplicate redundant corridors.

overlap_reject_ratio

Overlap ratio threshold for heavy redundancy penalty.

global_overlap_reject_ratio

Threshold for rejecting globally parallel candidates.

max_prior_per_pair

Maximum overlap objects retained per patch pair.

diminishing_base

Base for redundancy penalty when no shortcut context is available.

max_links_per_pair

Optional hard limit of selected corridors per patch pair.

enable_bridge_pairs

Whether to pre-seed bridge corridor pairs.

bridge_max_per_patch

Max candidates retained per bridge midpoint patch.

distance_guard_for_primary

Whether to apply distance guard to primary links.

global_overlap_for_primary

Whether to apply global-overlap reject to primary links.

parallel_dominance_ratio

Shortcut dominance threshold for parallel penalties.

parallel_overlap_penalty_floor

Floor multiplier for global-parallel penalties.

shortcut_ratio_high

High shortcut ratio threshold.

shortcut_ratio_mid

Mid shortcut ratio threshold.

shortcut_ratio_low

Low shortcut ratio threshold.

shortcut_mult_high

Multiplier when shortcut ratio is high.

shortcut_mult_mid

Multiplier when shortcut ratio is mid.

shortcut_mult_low

Multiplier when shortcut ratio is low.

Value

List with picks, selected_ids, and summary stats.


Union-Find data structure

Description

Union-Find data structure

Union-Find data structure

Methods

initialize

Create a new UnionFind.

find

Find root of a node with path compression.

union

Union two nodes; returns TRUE if merged.

get_size

Get component size for a node.

get_count

Get component count for a node.

Public fields

parent

Environment mapping nodes to parents.

size

Environment mapping roots to component sizes.

count

Environment mapping roots to component counts.

Methods

Public methods


Method new()

Usage
UnionFind$new()

Method find()

Usage
UnionFind$find(x)
Arguments
x

Node id for lookup operations.

x

Node id for lookup operations.


Method union()

Usage
UnionFind$union(a, b)
Arguments
a

Node id for union operations.

a

Node id for union operations.

b

Node id for union operations.

b

Node id for union operations.


Method get_size()

Usage
UnionFind$get_size(x)
Arguments
x

Node id for lookup operations.

x

Node id for lookup operations.


Method get_count()

Usage
UnionFind$get_count(x)
Arguments
x

Node id for lookup operations.

x

Node id for lookup operations.


Method clone()

The objects of this class are cloneable with this method.

Usage
UnionFind$clone(deep = FALSE)
Arguments
deep

Whether to make a deep clone.