| 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 |
Standalone R implementation of habitat connectivity corridor optimization algorithms for raster and vector workflows, without desktop GIS dependencies.
Main user entry points:
terralink_raster() for raster inputs
terralink_vector() for polygon patch inputs
terralink_run() for a single generic wrapper
Raster inputs are funneled through TerraLink's vector corridor pipeline so the R package matches the current QGIS plugin workflow.
Maintainer: Benjamin Bishop [email protected]
Other contributors:
SORUS Consulting LLC [funder, copyright holder]
Report bugs at https://github.com/sorus-tools/terralink-r/issues
Build contiguous network raster (patches + corridors)
build_contiguous_raster(habitat_mask, corridor_raster, connectivity = 8)build_contiguous_raster(habitat_mask, corridor_raster, connectivity = 8)
habitat_mask |
SpatRaster of habitat. |
corridor_raster |
SpatRaster of corridors. |
connectivity |
Connectivity for patches (4 or 8). |
SpatRaster with component sizes.
Create corridor raster from selected edges
build_corridor_raster( labels, patch_df, corridors, min_corridor_width_px = 1, assignment_mode = "sum_total_network_area" )build_corridor_raster( labels, patch_df, corridors, min_corridor_width_px = 1, assignment_mode = "sum_total_network_area" )
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. |
SpatRaster with corridor cells set by assignment mode.
Build an igraph graph from patch ids and corridor edges
build_graph_from_corridors(patches, corridors, distance_col = "distance_m")build_graph_from_corridors(patches, corridors, distance_col = "distance_m")
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. |
An igraph graph.
Build candidate edges between patches (centroid distance)
build_patch_candidates(patch_df, max_search_distance, raster_ref)build_patch_candidates(patch_df, max_search_distance, raster_ref)
patch_df |
Patch summary data frame. |
max_search_distance |
Maximum distance in pixels. |
raster_ref |
Raster reference for pixel size. |
Data frame with patch1, patch2, cost, distance_map, id.
Build raster candidates using shortest paths
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 )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 )
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. |
Data frame of candidates with geometry.
Calculate disturbance penalty (diameter normalized)
calculate_disturbance_penalty(graph)calculate_disturbance_penalty(graph)
graph |
igraph graph. |
Numeric penalty.
Estimate failure probability via edge removal
calculate_failure_probability(graph, k_failures = 1, iterations = 100)calculate_failure_probability(graph, k_failures = 1, iterations = 100)
graph |
igraph graph. |
k_failures |
Number of edges removed each trial. |
iterations |
Number of Monte Carlo iterations. |
Failure probability.
Calculate movement entropy for a graph
calculate_movement_entropy(graph, alpha = 0.002)calculate_movement_entropy(graph, alpha = 0.002)
graph |
igraph graph. |
alpha |
Dispersal kernel parameter. |
Numeric entropy value.
Calculate topology penalty (cycle count)
calculate_topology_penalty(graph)calculate_topology_penalty(graph)
graph |
igraph graph. |
Numeric penalty.
Calculate total entropy summary
calculate_total_entropy(graph, lambda_c = 1, lambda_f = 1, lambda_d = 1)calculate_total_entropy(graph, lambda_c = 1, lambda_f = 1, lambda_d = 1)
graph |
igraph graph. |
lambda_c |
Connectivity penalty multiplier. |
lambda_f |
Topology penalty multiplier. |
lambda_d |
Disturbance penalty multiplier. |
Named list of entropy components.
Calculate the fraction of node pairs with two edge-disjoint paths
calculate_two_edge_connectivity(graph)calculate_two_edge_connectivity(graph)
graph |
igraph graph. |
Numeric ratio.
Label contiguous habitat patches
label_patches(mask, connectivity = 8)label_patches(mask, connectivity = 8)
mask |
Logical SpatRaster mask. |
connectivity |
4 or 8. |
SpatRaster of patch labels.
Implements a two-phase optimizer: MST backbone, then optional loop additions.
Create a new optimizer with nodes.
Add a candidate edge.
Run optimization.
nodesNode weights.
edgesCandidate edge list.
ufUnionFind instance.
new()
NetworkOptimizer$new(nodes)
nodesNamed numeric vector of node weights.
nodesNamed numeric vector of node weights.
add_candidate()
NetworkOptimizer$add_candidate(u, v, cand_id, cost)
uCandidate edge start node.
uCandidate edge start node.
vCandidate edge end node.
vCandidate edge end node.
cand_idCandidate edge id.
cand_idCandidate edge id.
costCandidate edge cost.
costCandidate edge cost.
solve()
NetworkOptimizer$solve(budget, loop_fraction = 0.05, max_redundancy = 2)
budgetNumeric budget for corridor costs.
budgetNumeric budget for corridor costs.
loop_fractionFraction of budget reserved for loops.
loop_fractionFraction of budget reserved for loops.
max_redundancyMax redundant edges per component.
max_redundancyMax redundant edges per component.
clone()
The objects of this class are cloneable with this method.
NetworkOptimizer$clone(deep = FALSE)
deepWhether to make a deep clone.
Create a candidate corridor descriptor
new_candidate(patch_ids, cost, weight = NULL, geometry = NULL)new_candidate(patch_ids, cost, weight = NULL, geometry = NULL)
patch_ids |
Integer vector of patch ids. |
cost |
Numeric cost of the corridor. |
weight |
Numeric benefit or ROI. |
geometry |
Optional geometry object. |
A candidate list with class 'terralink_candidate'.
Create a patch descriptor
new_patch(id, weight, geometry = NULL)new_patch(id, weight, geometry = NULL)
id |
Patch identifier. |
weight |
Numeric patch weight (area, quality). |
geometry |
Optional geometry object. |
A patch list with class 'terralink_patch'.
Optimize for largest connected network (MST backbone + loops)
optimize_largest_network( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )optimize_largest_network( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )
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. |
List with selected ids and summary.
Optimize a network given nodes and candidate edges
optimize_network( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )optimize_network( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )
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. |
List with selected edge ids, component sizes/counts, and total cost.
Choose optimization strategy
optimize_strategy(strategy, nodes, edges, candidates, budget, ...)optimize_strategy(strategy, nodes, edges, candidates, budget, ...)
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. |
List with selected ids and stats.
Summarize patch labels into a data frame
patch_summary_from_labels(labels)patch_summary_from_labels(labels)
labels |
SpatRaster of patch labels. |
Data frame with patch_id, cell_count, area, x, y.
Create a logical mask from raster values
raster_mask_from_values(raster, values)raster_mask_from_values(raster, values)
raster |
SpatRaster. |
values |
Numeric values to keep. |
Logical SpatRaster mask.
Run TerraLink raster workflow
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 )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 )
raster |
SpatRaster or path to raster. |
patch_values |
Numeric values representing habitat. |
budget |
Total corridor budget (units defined by |
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 |
min_corridor_width |
Minimum corridor width (units defined by |
corridor_cell_assignment |
Corridor cell assignment mode. |
max_search_distance |
Maximum search distance (units defined by |
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. |
Raster inputs are funneled through TerraLink's vector corridor pipeline after habitat and impassable classes are polygonized, matching the current QGIS plugin workflow.
List with patches, corridors, rasters, and summary.
Run TerraLink vector workflow
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 )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 )
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. |
List with corridors, networks, and summary.
Score a loop edge for shortcut value
score_edge_for_loops(graph, u, v, weight)score_edge_for_loops(graph, u, v, weight)
graph |
igraph graph. |
u |
First node id. |
v |
Second node id. |
weight |
Edge cost. |
Numeric score.
Greedy ROI-based selector with dynamic rescoring, bridge seeding, and optional overlap checks.
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 )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 )
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. |
List with picks, selected_ids, and summary stats.
Run TerraLink optimization on abstract nodes and edges
terralink_engine( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )terralink_engine( nodes, edges, budget, loop_fraction = 0.05, max_redundancy = 2 )
nodes |
Named numeric vector of patch weights. |
edges |
Data frame with columns u, v, id, cost. |
budget |
Numeric budget for corridor costs. |
loop_fraction |
Fraction of budget available for loops. |
max_redundancy |
Maximum redundant edges per component. |
List with selected edges and component summaries.
Locate packaged TerraLink example scripts
terralink_examples(type = c("all", "raster", "vector"))terralink_examples(type = c("all", "raster", "vector"))
type |
Which example scripts to return: |
Character vector of absolute file paths.
terralink_examples() terralink_examples("raster")terralink_examples() terralink_examples("raster")
Identifies habitat patches from a classified raster, builds candidate corridors between nearby patches, and selects an optimal corridor network under a budget constraint. Raster inputs are polygonized and routed through TerraLink's vector engine, matching the current QGIS plugin workflow.
terralink_raster( raster, patch_values = NULL, patch_ranges = NULL, 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 = 8, units = "pixels", 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", output_dir = NULL, output_prefix = NULL, output_paths = NULL, write_outputs = FALSE, keep_candidates = FALSE )terralink_raster( raster, patch_values = NULL, patch_ranges = NULL, 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 = 8, units = "pixels", 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", output_dir = NULL, output_prefix = NULL, output_paths = NULL, write_outputs = FALSE, keep_candidates = FALSE )
raster |
SpatRaster or file path to a single-band raster. |
patch_values |
Integer vector of cell values that represent habitat
(e.g., |
patch_ranges |
Optional list of length-2 numeric vectors giving
inclusive value ranges that define habitat (e.g., |
budget |
Total corridor budget. When |
budget_pixels |
Back-compat alias for |
strategy |
Character string selecting the optimization objective.
One of |
min_patch_size |
Numeric. Minimum patch size to include. In pixel
units when |
min_corridor_width |
Numeric. Minimum corridor width. In pixel units
when |
corridor_cell_assignment |
Character string controlling how corridor
cells are valued in the output raster. One of
|
max_search_distance |
Numeric. Maximum distance between patch edges
to consider a candidate corridor. Same unit system as
|
obstacle_values |
Optional integer vector of raster cell values that represent impassable barriers (e.g., roads, water bodies). |
obstacle_ranges |
Optional list of length-2 numeric vectors giving inclusive value ranges for obstacles. |
allow_bottlenecks |
Logical. If |
patch_connectivity |
Integer, 4 or 8. Pixel connectivity rule for grouping habitat cells into patches. 8 (default) includes diagonal neighbors; 4 uses only cardinal neighbors. |
units |
Character string specifying the unit system:
|
allow_large |
Logical. Set to |
max_pair_checks |
Integer. Upper limit on the number of patch pairs evaluated during candidate generation. Increase for landscapes with many patches; decrease if running out of memory. Default: 2,000,000. |
max_candidates |
Integer. Upper limit on total candidate corridors retained. Default: 200,000. |
verbose |
Integer verbosity level: 0 = silent, 1 = progress messages, 2 = detailed diagnostics. Default: 0. |
progress |
Logical. Show progress bars during long operations.
Default: |
obstacle_strategy |
Character string controlling behavior when obstacle
values are provided but the gdistance package is not installed.
One of |
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 |
Numeric. Typical movement distance for
the focal species, in the same distance units as the analysis (pixels /
meters / feet). Used by habitat-availability metrics. If |
species_dispersal_kernel |
Character string. Dispersal probability
kernel. Currently only |
min_patch_area_for_species |
Numeric. Minimum patch area (in analysis area units) for a patch to be included in species-level habitat availability calculations. Default: 0. |
patch_area_scaling |
Character string controlling how patch area is
transformed before weighting in habitat availability calculations.
|
mobility_detour_cap |
Numeric. Maximum detour ratio used by graph-based fluidity metrics. Controls how much longer an indirect route can be relative to the straight-line distance before it is considered non-functional. Default: 8. |
redundancy_method |
Character string selecting the flow redundancy
calculation method. |
output_dir |
Optional character path. Directory for writing output
files when |
output_prefix |
Optional character string prepended to output file names. |
output_paths |
Optional named list of explicit output file paths, overriding the default naming convention. |
write_outputs |
Logical. If |
keep_candidates |
Logical. If |
An object of class "terralink_result" (a list) with the
following elements:
corridors: Data frame or sf object of selected corridor
geometries with columns patch1, patch2,
corridor_area, corridor_length, connected_area,
and network_area.
patches: SpatRaster of labeled patch cells (raster mode).
patch_table: Data frame of patch attributes (id, area,
centroid coordinates).
networks: sf object of connected network polygons (one
feature per component of patches + corridors).
corridor_raster: SpatRaster where corridor cells are
assigned values according to corridor_cell_assignment.
contiguous_raster: SpatRaster labeling each contiguous
patch-corridor network.
strategy: The strategy key that was used.
summary: Named list with run overview including
budget_total, budget_used, corridors_used,
candidate_edges, patches, strategy,
units.
metrics: Named list of PRE/POST landscape metrics. Each
metric has a _pre (before corridors) and _post (after
corridors) value. Key metrics: total_connected_habitat_area,
largest_network_area, habitat_availability,
mean_effective_resistance (lower is better),
mesh_norm, lcc, pc, flow_redundancy,
strategic_mobility, landscape_fluidity,
composite_connectivity.
metrics_report: Character vector with a human-readable
PRE/POST metrics table. Print with
cat(result$metrics_report, sep = "\n").
strategy_stats: Named list of strategy-specific
optimization statistics (e.g., primary vs. redundant links).
mode: Character string "raster".
inputs: Named list echoing key input parameters.
run_stats: Named list with elapsed_s,
candidate_edges, candidate_pairs.
warnings: Character vector of any warnings raised during
the run.
diagnostics: List of diagnostic messages (e.g., why no
corridors were selected).
The object has print(), summary(), and plot()
methods.
budget: A practical starting point is often around 5–20 percent of total habitat area. Run several budget levels and compare PRE/POST metrics.
min_patch_size: Use this to exclude patches too small to function as habitat in your planning context. For raster mode, 5–20 pixels is a common starting range; for real landscapes, 1–10 ha can be a reasonable first pass.
min_corridor_width: Should reflect the minimum width for species movement. Depending on species and landscape context, 30–100 m is a common starting range for terrestrial mammals and 10–30 m for some birds.
max_search_distance: Should be at or above the maximum distance the focal species can cross non-habitat. 500–5000 m is a common starting range; increase if 0 corridors are generated.
species_dispersal_distance: Set to the focal species' typical natal or daily movement range. This directly affects the habitat-availability metrics.
r <- terra::rast( nrows = 6, ncols = 6, xmin = 0, xmax = 600, ymin = 0, ymax = 600, crs = "EPSG:3857" ) vals <- rep(0, terra::ncell(r)) vals[c(1, 2, 7, 8, 29, 30, 35, 36)] <- 1 terra::values(r) <- vals result <- terralink_raster( raster = r, patch_values = 1, budget = 15, min_patch_size = 2, min_corridor_width = 1, max_search_distance = 12, units = "pixels" ) result$summary # Access PRE/POST metrics result$metrics$largest_network_area_pre result$metrics$largest_network_area_postr <- terra::rast( nrows = 6, ncols = 6, xmin = 0, xmax = 600, ymin = 0, ymax = 600, crs = "EPSG:3857" ) vals <- rep(0, terra::ncell(r)) vals[c(1, 2, 7, 8, 29, 30, 35, 36)] <- 1 terra::values(r) <- vals result <- terralink_raster( raster = r, patch_values = 1, budget = 15, min_patch_size = 2, min_corridor_width = 1, max_search_distance = 12, units = "pixels" ) result$summary # Access PRE/POST metrics result$metrics$largest_network_area_pre result$metrics$largest_network_area_post
Run TerraLink with a single entry point
terralink_run(mode = c("raster", "vector"), input, ...)terralink_run(mode = c("raster", "vector"), input, ...)
mode |
"raster" or "vector". |
input |
Raster path/SpatRaster or sf/path. |
... |
Parameters forwarded to terralink_raster or terralink_vector. |
Result list.
Locate packaged TerraLink sample data files
terralink_sample_data( type = c("all", "raster", "vector", "obstacle", "synthetic_raster", "synthetic_vector", "synthetic_obstacle") )terralink_sample_data( type = c("all", "raster", "vector", "obstacle", "synthetic_raster", "synthetic_vector", "synthetic_obstacle") )
type |
Which sample data path to return: |
For "all", a named character vector of absolute file paths.
For other values, a single absolute file path (character scalar) or character(0)
when unavailable.
terralink_sample_data() terralink_sample_data("raster")terralink_sample_data() terralink_sample_data("raster")
Builds candidate corridors between polygon habitat patches and selects an optimal corridor network under a budget constraint. This is the native TerraLink workflow and is usually the better choice when planning inputs are already polygon features.
terralink_vector( 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", output_dir = NULL, output_prefix = NULL, output_paths = NULL, write_outputs = FALSE, keep_candidates = FALSE )terralink_vector( 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", output_dir = NULL, output_prefix = NULL, output_paths = NULL, write_outputs = FALSE, keep_candidates = FALSE )
patches |
sf object with polygon geometry (one row per patch), or a file path to a GeoPackage / Shapefile. The CRS should be projected (e.g., UTM) so that area and distance calculations are meaningful. |
budget |
Numeric. Total corridor area budget in hectares
( |
strategy |
Character string selecting the optimization objective.
One of |
min_patch_size |
Numeric. Minimum patch area in hectares
( |
min_corridor_width |
Numeric. Minimum corridor width in meters
( |
max_search_distance |
Numeric. Maximum edge-to-edge distance (meters or feet) between patches to consider a candidate corridor. Increase if few or no corridors are generated. Default: 5000. |
obstacle_layers |
Optional sf object or file path to polygon barriers (roads, water bodies). Requires the gdistance package for shortest-path routing around obstacles. |
obstacle_resolution |
Numeric. Raster cell size (in CRS units) used to rasterize obstacles for shortest-path routing. Smaller values give more accurate routing but increase computation time. |
units |
Character string: |
max_pair_checks |
Integer. Upper limit on patch pairs evaluated. Default: 2,000,000. |
max_candidates |
Integer. Upper limit on candidate corridors retained. Default: 200,000. |
verbose |
Integer verbosity level: 0 = silent, 1 = progress, 2 = detailed. Default: 0. |
progress |
Logical. Show progress bars. Default: |
obstacle_strategy |
Character string controlling behavior when
obstacles are provided but gdistance is not installed. One of
|
return_crs |
Character string controlling the output CRS.
|
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 |
Numeric. Typical movement distance for
the focal species in meters ( |
species_dispersal_kernel |
Character string. Dispersal probability
kernel. Currently only |
min_patch_area_for_species |
Numeric. Minimum patch area (in analysis area units) for inclusion in species-level metrics. Default: 0. |
patch_area_scaling |
Character string controlling how patch area is
transformed before weighting. |
patch_quality_field |
Optional character string naming a numeric
column in |
mobility_detour_cap |
Numeric. Maximum detour ratio for fluidity metrics. Controls how much longer an indirect route can be before it is considered non-functional. Default: 8. |
redundancy_method |
Character string selecting the flow redundancy
method. |
output_dir |
Optional output directory for |
output_prefix |
Optional name prefix for output files. |
output_paths |
Optional named list of explicit output file paths. |
write_outputs |
Logical. Write GeoPackage and CSV outputs to disk.
Default: |
keep_candidates |
Logical. Include full candidate table in result.
Default: |
An object of class "terralink_result" (a list) with the
following elements:
corridors: sf object of selected corridors with columns
patch1, patch2 (endpoint patch IDs),
corridor_area (ha or ac), corridor_length (m or ft),
connected_area, network_area, and geometry.
patches: sf object of patches used in the analysis, with
area and centroid attributes.
networks: sf object of connected network polygons (one
feature per component of patches + corridors).
summary: Named list including budget_total,
budget_used, corridors_used, candidate_edges,
patches, raw_patches, filtered_out,
primary_links, redundant_links, strategy,
units.
metrics: Named list of PRE/POST landscape connectivity
metrics. Every metric has a _pre and _post value.
Key metrics: total_connected_habitat_area,
largest_network_area, habitat_availability,
mean_effective_resistance (lower is better),
mesh_norm, lcc, pc, flow_redundancy,
strategic_mobility, landscape_fluidity,
composite_connectivity.
metrics_report: Character vector with a human-readable
PRE/POST table. Print with
cat(result$metrics_report, sep = "\n").
strategy_stats: Named list of strategy-specific
statistics.
mode: Character string "vector".
inputs: Named list echoing key input parameters.
run_stats: Named list with elapsed_s,
candidate_edges, candidate_pairs.
warnings: Character vector of warnings.
diagnostics: List of diagnostic messages.
The object has print(), summary(), and plot()
methods.
budget: A practical starting point is often around 5–20 percent of total patch area. Run multiple budgets and compare PRE/POST metrics to find the point of diminishing returns.
min_corridor_width: Depending on species and context, 30–100 m can be a useful starting range for mammals and 10–30 m for some small birds.
max_search_distance: 500–5000 m is a common starting range. Increase if 0 corridors are generated.
species_dispersal_distance: Set to the focal species' typical natal or daily movement range. Directly affects habitat-availability metrics.
p1 <- sf::st_polygon(list(rbind(c(0, 0), c(0, 10), c(10, 10), c(10, 0), c(0, 0)))) p2 <- sf::st_polygon(list(rbind(c(30, 0), c(30, 10), c(40, 10), c(40, 0), c(30, 0)))) patches <- sf::st_sf(id = 1:2, geometry = sf::st_sfc(p1, p2), crs = 32618) if (identical(Sys.getenv("NOT_CRAN"), "true")) { result <- terralink_vector( patches = patches, budget = 1, min_patch_size = 0.001, min_corridor_width = 5, max_search_distance = 200, units = "metric" ) result$summary # Access PRE/POST metrics result$metrics$largest_network_area_pre result$metrics$largest_network_area_post # Print the full metrics report cat(result$metrics_report, sep = "\n") }p1 <- sf::st_polygon(list(rbind(c(0, 0), c(0, 10), c(10, 10), c(10, 0), c(0, 0)))) p2 <- sf::st_polygon(list(rbind(c(30, 0), c(30, 10), c(40, 10), c(40, 0), c(30, 0)))) patches <- sf::st_sf(id = 1:2, geometry = sf::st_sfc(p1, p2), crs = 32618) if (identical(Sys.getenv("NOT_CRAN"), "true")) { result <- terralink_vector( patches = patches, budget = 1, min_patch_size = 0.001, min_corridor_width = 5, max_search_distance = 200, units = "metric" ) result$summary # Access PRE/POST metrics result$metrics$largest_network_area_pre result$metrics$largest_network_area_post # Print the full metrics report cat(result$metrics_report, sep = "\n") }
Union-Find data structure
Union-Find data structure
Create a new UnionFind.
Find root of a node with path compression.
Union two nodes; returns TRUE if merged.
Get component size for a node.
Get component count for a node.
parentEnvironment mapping nodes to parents.
sizeEnvironment mapping roots to component sizes.
countEnvironment mapping roots to component counts.
new()
UnionFind$new()
find()
UnionFind$find(x)
xNode id for lookup operations.
xNode id for lookup operations.
union()
UnionFind$union(a, b)
aNode id for union operations.
aNode id for union operations.
bNode id for union operations.
bNode id for union operations.
get_size()
UnionFind$get_size(x)
xNode id for lookup operations.
xNode id for lookup operations.
get_count()
UnionFind$get_count(x)
xNode id for lookup operations.
xNode id for lookup operations.
clone()
The objects of this class are cloneable with this method.
UnionFind$clone(deep = FALSE)
deepWhether to make a deep clone.
Write raster outputs to disk
write_terralink_raster_outputs( result, output_dir, prefix = NULL, overwrite = TRUE, output_paths = list() )write_terralink_raster_outputs( result, output_dir, prefix = NULL, overwrite = TRUE, output_paths = list() )
result |
Result list from terralink_raster. |
output_dir |
Directory to write outputs. |
prefix |
Optional name prefix for outputs. |
overwrite |
Whether to overwrite existing files. |
output_paths |
Named list of explicit file paths to override defaults. |
Named list of written file paths.
Write vector outputs to disk
write_terralink_vector_outputs( result, output_dir, prefix = NULL, overwrite = TRUE, output_paths = list() )write_terralink_vector_outputs( result, output_dir, prefix = NULL, overwrite = TRUE, output_paths = list() )
result |
Result list from terralink_vector. |
output_dir |
Directory to write outputs. |
prefix |
Optional name prefix for outputs. |
overwrite |
Whether to overwrite existing files. |
output_paths |
Named list of explicit file paths to override defaults. |
Named list of written file paths.