Code
# Load packages. Install if you need to.
library(terra)
library(raster)
library(sf)
library(gdistance)
library(mapview)
library(viridis)
library(tidyverse)Randomized shortest paths, circuit theory, and least cost corridors
Data for this lab.
Download Lab9.zip from the course data archive on Zenodo and unzip it into a folder called data/Lab9/ in your project directory.
Species move. Acknowledging this simple truth requires that conservation plans include objectives to maintain or restore the ability of species (and ecological processes) to traverse landscapes. As ecologists continue to learn about the movement of species and the importance of ecological flows (of water, fire, or genes), new tools have been developed to model landscape connectivity. These connectivity models have largely focused on predicting where species are moving - or could move - based on observation of their use of habitats and their dispersal among core areas. Some connectivity models are species-agnostic and assume that maintaining or restoring lands free of significant human modification will provide the best opportunities for the most species to disperse among protected or natural areas.
Migration routes of the Sublette pronghorn herd shown(Kauffman et al. 2022, USGS SIR 2022-5008, public domain.
Nearly all connectivity models require researchers to determine cores or nodes to be connected and a resistance surface that represent the ease or difficulty of traversing a landscape. Landscape resistance can reflect behavioral choices of individuals (e.g., animals might avoid heavily developed areas) or mortality risk (e.g., animals have a greater chance of being killed in heavily roaded areas). Most connectivity models are mapped predictions of hypotheses. Connectivity models are based on hypotheses that organisms moving from point A to point B will choose to follow a path or linkage zone with minimal resistance.
The choice of locating cores has a large effect on the outcomes of connectivity models, and decisions of which cores areas to connect should be carefully made and reflect specific research questions. Are you trying to connect core habitats that certain species are known to use or protected areas for establishing a connected network of conservation reserves?
The methods for determining landscape resistance also influence model outcomes. What observations or assumptions are you making that lead to specific predictions that certain features (e.g., roads, power lines, or water bodies) or land cover types (e.g., agriculture, forest, or grassland) impede or facilitate the movement or dispersal of organisms? We recommend varying some of the assumptions about which mapped features create what magnitude of resistance. Then, run several connectivity models to investigate alternative scenarios and evaluate the sensitivity of your model to various assumptions.
Once you’ve determined your cores and have developed resistance surfaces, there are various approaches to modeling connectivity. Two widely used approaches are least cost corridors (or least cost paths) and circuit theory. Least cost approaches calculate cost-weighted distances from each core area and identify the pixels that minimize cost between core areas. Cost-weighted distances are calculated as the accumulated cost from moving away from a core. The further an animal travels from a core area and the more resistance they encounter in each pixel, the higher the cost-weighted distance. You can visualize how least cost corridors are calculated by mapping the cost-weighted distances away from two cores (A and B), summing these values, and stretching the color ramp in a way that highlights the lowest values from the sum (see below). Least cost paths and corridors can represent priorities for maintaining connectivity under the assumption that species will have the easiest time moving along these corridors. This approach has been used to identify corridors linking protected areas.

Another widely used approach for modeling connectivity uses circuit theory, most commonly implemented in software such as Circuitscape or its derivative Omniscape. Unlike least-cost corridor models, which assume that species follow an optimal pathway of low resistance, circuit theory treats the landscape as an electrical circuit in which voltage is applied to source locations and current flows across the resistance surface. Circuit theory assumes that species usually prefer easier routes through the landscape but may wander or deviate from the most efficient path. Cumulative current flow (an important output from Circuitscape and Omniscape) represents pathways species may take between core areas. Current flow will typically be low in areas of high resistance. These areas are often descibed as having “impeded” flow. In contrast, current flow is typically very high in relatively natural regions surrounded by more developed lands. These areas of concentrated current flow have been described as “pinch points” that represent “channelized” flow in the model where few other good paths exist. In large landscapes free of human modification, current flow can also be moderately low, because there are many options for current to flow (i.e., currents are not channelized because of there are many options for moving though lands of low resistance). These lands have been described as having “diffuse” flow and typically represent large “wildlands”. See map below.
National Geographic map of output from Omniscape using human modification as the basis for connectivity model.
In R, the gdistance package includes a function called passage that allows you to model connectivity varying the assumptions of how much random deviation from optimal routes species may take. The amount of random deviation is controlled by a term the developers denote with θ (theta). This function allows users to conduct connectivity models that can resemble least cost corridors or circuit theory simply by varying θ. We are unsure how the performance and speed of passage compares to software optimized to run least cost corridors (e.g., Linkage Mapper in ArcGIS Pro) or circuit theory (e.g., Omniscape in the Julia language), especially with high resolution data of large landscape with many cores. We use the gdistance package here to demonstrate how you can create different resistance surfaces and make different assumptions about the randomness of animal movement to reflect alternative hypotheses in connectivity models.
For this lab, we will use four core areas and a map of landscape resistance that is based on transformations of the human modification data. The core areas are based on locations within large protected areas in the Northern Rockies (see map below). Specifically, we haphazardly identified locations in the Bob Marshall Wilderness, Frank Church-River of No Return Wilderness, Yellowstone National Park, and the Charles M. Russell Wildlife Refuge. These core protected areas also contain populations of species whose habitats conservation scientists seek to connect.

We will transform the human modification data into landscape resistance based on different hypotheses concerning how the composite human modification may affect the movement of species. We are going to assume that roads, altered land cover, mines, and other features included in human modification data will create resistance of movement by species. We will vary the relationship between human modification and landscape resistance based on assumptions that some species or individuals can tolerate low levels of modification before experiencing resistance to movement, while other species or individuals may experience a high degree of resistance even with low levels of human modification.
As usual, we will start by bringing in packages. Install them if you need to.
We will load the core areas and human modification data for the Northern Rockies, project the data to a common crs, and map the data using plot or mapview.
# Load the core areas, which are just points. These are the centroids of large protected areas.
cores <- terra::vect("data/Lab9/PAcentroids_NoRock.shp")
# Load the human modification data, which we will use as the basis of landscape
# resistance
hum_mod <- terra::rast("data/Lab9/human_modificationNoRock.tif")
# Project both to the same CRS
hum_mod <- terra::project(hum_mod, "EPSG:4326", method = "bilinear")
cores <- terra::project(cores, hum_mod)
# This will show a map of humanb modification for most of Montana, Idaho, and Wyoming with white circles representing the centroids of large protected areas.
plot(hum_mod, axes = F, box = F)
plot(cores, add = T, col = "white", cex = 2)
Now that we have human modification mapped, we need to decide how the degree of human modification influences landscape resistance. Researchers have used saturating exponential functions to transform human modification (or habitat suitability) into landscape resistance. These transformations can be easily changed by adjusting the term “c” in the formula below and can represent alternative hypotheses concerning how species respond to human modification (see curves in image below from this paper). The black line where c = 0.25 represents a relatively linear transformation of human modification into landscape resistance. This assumes that one unit change in human modification has a one unit change in landscape resistance. The red line represent species that may experience a high degree of resistance to movement at low levels of human modification (“human-sensitive species”), whereas the blue line represents species that may not experience landscape resistance except in the most human modified areas (“human-tolerant species”).
\[\text{Resistance} = 99 \times \frac{1 - e^{-c \times HM}}{1 - e^{-c}} + 1\]

Three approaches to converting human modification into landscape resistance: human-sensitive, linear, and human-tolerant scaling. From Belote, R.T., Barnett, K., Zeller, K. et al. (2022), “Examining local and regional ecological connectivity throughout North America,” Landscape Ecology 37, 2977-2990, https://doi.org/10.1007/s10980-022-01530-9. Licensed under CC BY 4.0.
We will start by using several different “c” terms to see how landscape resistance varies with human modification. Run this chunk of code for different values of “c”. I recommend starting with c = 0.25, which is roughly linear (i.e., one unit change in human modification represent one unit change in landscape resistance). Change “c” from -30 to +30 and anything in between.
# Let's set up our code where we can easily vary c and re-run the analysis
c <- 0.25
# HM, in this case, is scaled from 0 to 100, but we want it to be scaled
# from 0 to 1, so we will divide by 100
hm <- hum_mod / 100
# Apply the Keeley et al. (2016) and Belote et al. (2022) transformation
# This adds the resistance to the raster object with the human modification (hm)
# this automatically creates a raster stack with two layer (hm and resist)
hm$resist <- 99 * ((1 - exp(-c * hm)) / (1 - exp(-c))) + 1
# Rescale landscape resistance so that it ranges from 0 to 1.
# We do this by taking each value, subtrac the minimum value for the dataset,
# then divide by the range (max - min). This scales the data to 0 to 1.
# This isn't completely necessary.
hm$resist <- (hm$resist - minmax(hm$resist)[[1]]) / (minmax(hm$resist)[[2]] - minmax(hm$resist)[[1]])
# Rename the layers and use the c value from above as the name.
# This trick is nice so that the names of your layers will automatically change
# when you assign a new c value above
names(hm) <- c("human modification", paste0("resistance, c =", c))
# Turn the raster stack into a data frame and adjust the names
hm_resistDF <- hm %>% as.data.frame(xy = T)
names(hm_resistDF) <- c("x", "y", "hm", "resistance")
# Now, plot human modification and landscape resistance to see what changing c
# does to the shape of the relationship
hm_resistDF %>% ggplot(aes(x = hm, y = resistance)) + geom_line() +
xlab("Human modification") + ylab("Landscape resistance") +
ggtitle(paste0("c = ", c)) +
theme_bw()
How does changing “c” change the relationship between human modification and landscape resistance? What examples of species can you think of that might respond to human modification under these different hypotheses?
Let’s look at the maps of human modification and landscape resistance. This is easy, because we have resistance stacked with the human modification data.
Now we need to turn the terra raster objects into raster raster objects. This sounds confusing, but the package gdistance still uses the older form of raster data in R, which was managed in the package called raster. We can easily turn as terra SpatRaster object into a raster object using raster(). In the code above, we added the resistance surface into a raster stack so that resistance is the second layer in the stack called hm. We call landscape resistance as the second layer using hm[[2]]. We will convert that into a raster object.
We then need to create a transition matrix, which basically is needed to tell gdistance how to treat adjacent cells. We will use the inverse of the average resistance. This essentially turns our map of resistance to a map of conductance (1/resistance) and takes the average of resistance from neighboring cells. This tells R how to deal with adjacent pixels. We then need to perform a geographic correction so that R treats the geographic distance correctly.
# Turn landscape resistance (the second layer in the stack you made above) into a
# raster object.
hm_raster <- raster::raster(hm[[2]])
# Create the transition layer so that R knows how to treat adjacent pixels
# We convert resistance into conductance
tr <- gdistance::transition(hm_raster, function(x) 1 / mean(x), directions = 8)
# Then, perform that georgaphic correction
tr_corr <- gdistance::geoCorrection(tr, type = "c", scl = TRUE)passageWe’re going to run connectivity models between all pairs of core areas. Because gdistance has not been updated to work with vect objects from terra, we need to convert our cores to an sp object. Then, we will use combn to generate a matrix of all combinations of core areas.
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 2 2 3
[2,] 2 3 4 3 4 4
Now, we will loop through all pairwise combinations of core areas and run the randomized shortest path in passage. We will establish theta as an object so that we can easily modify this term and re-run the models. Run the model using theta = 2 at first, then chose any value from 10 to 0.0000001. I recommend trying the lower values.
The loop below first establishes an empty list that we will call rsp (randomized shortest paths). The loop goes through each pairwise combination of cores. We start the loop with for (i in 1:ncol(Pj_combn)) which tells R “for each combination of cores from the first combination of cores through the number of columns in Pj_comb object” do the work in the { } brackets. So the loop starts by subsetting two cores (loc1 and loc2) from the core_sp object based on the combinations created in Pj_combn. The loop then runs the randomized shortest path from passage using the two cores subset in the first two lines in the loop. Note that it is using the geographically corrected transition layer we created above, and we have the theta option pointing to the theta term we assigned at the top of the chunk below.
NOTE: I have commented out a line that uses cat(). You can un-comment this by deleting the #, and R will print each step of the loop. This can be useful when you are running a large number of cores, but is not necessary here.
# run passage model for each core pair
theta <- 2
rsp <- list()
for (i in 1:ncol(Pj_combn))
{
loc1 <- cores_sp[Pj_combn[1, i], ]
loc2 <- cores_sp[Pj_combn[2, i], ]
# cat(paste0("Running passage for pair ", i, " of ", ncol(Pj_combn), "\n"))
rsp[[i]] <- passage(tr_corr, origin = loc1, goal = loc2, theta = theta)
}Now we have a list of outputs called rsp from above. Each of these outputs contains a randomized shortest path connectivity model for each combination of cores. We often want one map that shows a full network of linkages or corridors among cores, so we will combine these results. We will start by stacking up these outputs using the raster package method, which conveniently is called stack(). We then, will take the average of the values. We will plot the average of the outputs, look at the map, and then classify the data into quantiles to stretch the colors in a way that can reveal more patterns in the data and map.
Note that I have added a main = option in the plot that uses paste0. This allows me to create text strings that include values of “c” and “theta” I have assigned above. The paste0 function can be really useful when you are conducting sensitivity analyses in models where you are varying different parameters and want to keep track of which values you used in each model run.

# Classify the output into 10 quantiles (i.e., deciles) for visualization
rsp_overlay$quantiles <- rsp_overlay %>% values() %>% ntile(10)
# plot the original map and the reclassified map to compare
# I have added a line where the choice of "c" value for
# transforming human modification into resistance is printed
# and where the theta in the randomized shortest path is printed
plot(rsp_overlay, col = viridis(50), axes = FALSE, box = FALSE, main = paste0("c = ", c, "\n theta = ", format(theta, scientific = FALSE)))
Finally, I recommend looking at the data in an interactive map with other cartographic features (mountain ranges, etc.). We first need to assign a coordinate reference system to the output and then we’ll use mapview with the ESRI National Geographic basemap.
# Assign the correct crs to the data
crs(rsp_overlay$quantiles) <- "EPSG:4326"
# Map the output.
# This will bring up an interactive map of the connectivity output.
if (knitr::is_html_output()) {
mapview(rsp_overlay$quantiles, alpha.regions = 0.6,
layer.name = "Connectivity",
map.types = "Esri.NatGeoWorldMap")
} else {
plot(rsp_overlay$quantiles, col = viridis(50), axes = FALSE, box = FALSE,
main = "Connectivity")
}Compare your output to cumulative current flow from Circuitscape and least cost corridors and least cost paths from Linkage Mapper.
Output from Circuitscape and Linkage Mapper. Output from Linkage Mapper includes least cost corridors and least cost paths (black lines in map on the right).
TASK 1.
Design a multifactorial modeling experiment crossing the transformation of human modification into landscape resistance by varying “c” with the randomness of the connectivity output varying “theta”. Use at least 3 “c” values and 3 “theta” values. You should have at least 9 outputs. This kind of exercise produces different maps representing different hypothesis while also allowing you to assess the sensitivity of outputs to different combinations of parameters.
Compare the maps with each other and consider their biological meaning (or lack of). How do the maps change with varying assumptions of landscape resistance (varying “c”) and randomness of potential movements (varying “theta”)? Which places (e.g., mountain ranges) are important for connectivity in which model runs? Which places are always important? Which places are only important for connectivity in certain model runs? Which models are relevant to which species and why?
Compare your 9 outputs to the results from Circuitscape and Linkage Mapper.
Present your maps with thorough figure captions. Please arrange your maps meaningfully as “small multiples” (hint, you can simply do this by storing your output as separate maps and plotting them using par(mfrow = c(3, 3) or an alternative. Write up an abstract for Landscape Ecology.
Human modification data can be downloaded here: https://zenodo.org/records/14502573
---
title: "Lab 9. Ecological Connectivity"
subtitle: "Randomized shortest paths, circuit theory, and least cost corridors"
---
::: {.callout-note appearance="minimal"}
**Data for this lab.**
Download `Lab9.zip` from the [course data archive on Zenodo](https://doi.org/10.5281/zenodo.22101926) and unzip it into a folder called `data/Lab9/` in your project directory.
:::
# Background
Species move. Acknowledging this simple truth requires that conservation plans include objectives to maintain or restore the ability of species (and ecological processes) to traverse landscapes. As ecologists continue to learn about the movement of species and the importance of ecological flows (of water, fire, or genes), new tools have been developed to model landscape connectivity. These connectivity models have largely focused on predicting where species are moving - or could move - based on observation of their use of habitats and their dispersal among core areas. Some connectivity models are species-agnostic and assume that maintaining or restoring lands free of significant human modification will provide the best opportunities for the most species to disperse among protected or natural areas.
*Migration routes of the Sublette pronghorn herd shown(Kauffman et al. 2022, USGS SIR 2022-5008, public domain*.
Nearly all connectivity models require researchers to determine cores or nodes to be connected and a resistance surface that represent the ease or difficulty of traversing a landscape. Landscape resistance can reflect behavioral choices of individuals (e.g., animals might avoid heavily developed areas) or mortality risk (e.g., animals have a greater chance of being killed in heavily roaded areas). Most connectivity models are mapped predictions of hypotheses. Connectivity models are based on hypotheses that organisms moving from point A to point B will choose to follow a path or linkage zone with minimal resistance.
The choice of locating cores has a large effect on the outcomes of connectivity models, and decisions of which cores areas to connect should be carefully made and reflect specific research questions. Are you trying to connect core habitats that certain species are known to use or protected areas for establishing a connected network of conservation reserves?
The methods for determining landscape resistance also influence model outcomes. What observations or assumptions are you making that lead to specific predictions that certain features (e.g., roads, power lines, or water bodies) or land cover types (e.g., agriculture, forest, or grassland) impede or facilitate the movement or dispersal of organisms? We recommend varying some of the assumptions about which mapped features create what magnitude of resistance. Then, run several connectivity models to investigate alternative scenarios and evaluate the sensitivity of your model to various assumptions.
Once you've determined your cores and have developed resistance surfaces, there are various approaches to modeling connectivity. Two widely used approaches are **least cost corridors** (or least cost paths) and **circuit theory**. Least cost approaches calculate cost-weighted distances from each core area and identify the pixels that minimize cost between core areas. Cost-weighted distances are calculated as the accumulated cost from moving away from a core. The further an animal travels from a core area and the more resistance they encounter in each pixel, the higher the cost-weighted distance. You can visualize how least cost corridors are calculated by mapping the cost-weighted distances away from two cores (A and B), summing these values, and stretching the color ramp in a way that highlights the lowest values from the sum (see below). Least cost paths and corridors can represent priorities for maintaining connectivity under the assumption that species will have the easiest time moving along these corridors. This approach has been used to identify [corridors linking protected areas](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0154223).

Another widely used approach for modeling connectivity uses circuit theory, most commonly implemented in software such as *Circuitscape* or its derivative *Omniscape*. Unlike least-cost corridor models, which assume that species follow an optimal pathway of low resistance, circuit theory treats the landscape as an electrical circuit in which voltage is applied to source locations and current flows across the resistance surface. Circuit theory assumes that species usually prefer easier routes through the landscape but may wander or deviate from the most efficient path. Cumulative current flow (an important output from *Circuitscape* and *Omniscape*) represents pathways species may take between core areas. Current flow will typically be low in areas of high resistance. These areas are often descibed as having "impeded" flow. In contrast, current flow is typically very high in *relatively* natural regions surrounded by more developed lands. These areas of concentrated current flow have been described as "pinch points" that represent "channelized" flow in the model where few other good paths exist. In large landscapes free of human modification, current flow can also be moderately low, because there are many options for current to flow (i.e., currents are not channelized because of there are many options for moving though lands of low resistance). These lands have been described as having "diffuse" flow and typically represent large "wildlands". See map below.
 *National Geographic map of output from Omniscape using human modification as the basis for connectivity model.*
In R, the `gdistance` package includes a function called `passage` that allows you to model connectivity varying the assumptions of how much random deviation from optimal routes species may take. The amount of random deviation is controlled by a term the developers denote with θ (theta). This function allows users to conduct connectivity models that can resemble least cost corridors or circuit theory simply by varying θ. We are unsure how the performance and speed of `passage` compares to software optimized to run least cost corridors (e.g., [Linkage Mapper](https://linkagemapper.org/) in ArcGIS Pro) or circuit theory (e.g., [Omniscape](https://docs.circuitscape.org/Omniscape.jl/latest/) in the Julia language), especially with high resolution data of large landscape with many cores. We use the `gdistance` package here to demonstrate how you can create different resistance surfaces and make different assumptions about the randomness of animal movement to reflect alternative hypotheses in connectivity models.
For this lab, we will use four core areas and a map of landscape resistance that is based on transformations of the human modification data. The core areas are based on locations within large protected areas in the Northern Rockies (see map below). Specifically, we haphazardly identified locations in the Bob Marshall Wilderness, Frank Church-River of No Return Wilderness, Yellowstone National Park, and the Charles M. Russell Wildlife Refuge. These core protected areas also contain populations of species whose habitats conservation scientists seek to connect.
{fig-align="center"}
We will transform the human modification data into landscape resistance based on different hypotheses concerning how the composite human modification may affect the movement of species. We are going to assume that roads, altered land cover, mines, and other features included in human modification data will create resistance of movement by species. We will vary the relationship between human modification and landscape resistance based on assumptions that some species or individuals can tolerate low levels of modification before experiencing resistance to movement, while other species or individuals may experience a high degree of resistance even with low levels of human modification.
As usual, we will start by bringing in packages. Install them if you need to.
```{r}
# Load packages. Install if you need to.
library(terra)
library(raster)
library(sf)
library(gdistance)
library(mapview)
library(viridis)
library(tidyverse)
```
We will load the core areas and human modification data for the Northern Rockies, project the data to a common `crs`, and map the data using `plot` or `mapview`.
```{r}
# Load the core areas, which are just points. These are the centroids of large protected areas.
cores <- terra::vect("data/Lab9/PAcentroids_NoRock.shp")
# Load the human modification data, which we will use as the basis of landscape
# resistance
hum_mod <- terra::rast("data/Lab9/human_modificationNoRock.tif")
# Project both to the same CRS
hum_mod <- terra::project(hum_mod, "EPSG:4326", method = "bilinear")
cores <- terra::project(cores, hum_mod)
# This will show a map of humanb modification for most of Montana, Idaho, and Wyoming with white circles representing the centroids of large protected areas.
plot(hum_mod, axes = F, box = F)
plot(cores, add = T, col = "white", cex = 2)
#mapview(hum_mod, layer.name = "Human modification") + mapview(cores, col.regions = "white", cex = 8)
```
## Transforming human modification into landscape resistance
Now that we have human modification mapped, we need to decide how the degree of human modification influences landscape resistance. Researchers have used saturating exponential functions to transform human modification (or habitat suitability) into landscape resistance. These transformations can be easily changed by adjusting the term "c" in the formula below and can represent alternative hypotheses concerning how species respond to human modification (see curves in image below from this [paper](https://link.springer.com/article/10.1007/s10980-022-01530-9)). The black line where c = 0.25 represents a relatively linear transformation of human modification into landscape resistance. This assumes that one unit change in human modification has a one unit change in landscape resistance. The red line represent species that may experience a high degree of resistance to movement at low levels of human modification ("human-sensitive species"), whereas the blue line represents species that may not experience landscape resistance except in the most human modified areas ("human-tolerant species").
$$\text{Resistance} = 99 \times \frac{1 - e^{-c \times HM}}{1 - e^{-c}} + 1$$

*Three approaches to converting human modification into landscape resistance: human-sensitive, linear, and human-tolerant scaling. From Belote, R.T., Barnett, K., Zeller, K. et al. (2022), "Examining local and regional ecological connectivity throughout North America," Landscape Ecology 37, 2977-2990, https://doi.org/10.1007/s10980-022-01530-9. Licensed under CC BY 4.0.*
We will start by using several different "c" terms to see how landscape resistance varies with human modification. Run this chunk of code for different values of "c". I recommend starting with c = 0.25, which is roughly linear (i.e., one unit change in human modification represent one unit change in landscape resistance). Change "c" from -30 to +30 and anything in between.
```{r}
# Let's set up our code where we can easily vary c and re-run the analysis
c <- 0.25
# HM, in this case, is scaled from 0 to 100, but we want it to be scaled
# from 0 to 1, so we will divide by 100
hm <- hum_mod / 100
# Apply the Keeley et al. (2016) and Belote et al. (2022) transformation
# This adds the resistance to the raster object with the human modification (hm)
# this automatically creates a raster stack with two layer (hm and resist)
hm$resist <- 99 * ((1 - exp(-c * hm)) / (1 - exp(-c))) + 1
# Rescale landscape resistance so that it ranges from 0 to 1.
# We do this by taking each value, subtrac the minimum value for the dataset,
# then divide by the range (max - min). This scales the data to 0 to 1.
# This isn't completely necessary.
hm$resist <- (hm$resist - minmax(hm$resist)[[1]]) / (minmax(hm$resist)[[2]] - minmax(hm$resist)[[1]])
# Rename the layers and use the c value from above as the name.
# This trick is nice so that the names of your layers will automatically change
# when you assign a new c value above
names(hm) <- c("human modification", paste0("resistance, c =", c))
# Turn the raster stack into a data frame and adjust the names
hm_resistDF <- hm %>% as.data.frame(xy = T)
names(hm_resistDF) <- c("x", "y", "hm", "resistance")
# Now, plot human modification and landscape resistance to see what changing c
# does to the shape of the relationship
hm_resistDF %>% ggplot(aes(x = hm, y = resistance)) + geom_line() +
xlab("Human modification") + ylab("Landscape resistance") +
ggtitle(paste0("c = ", c)) +
theme_bw()
```
How does changing "c" change the relationship between human modification and landscape resistance? What examples of species can you think of that might respond to human modification under these different hypotheses?
Let's look at the maps of human modification and landscape resistance. This is easy, because we have resistance stacked with the human modification data.
```{r}
# Map human modification and landscape resistance, side-by-side.
plot(hm, axes = F)
```
Now we need to turn the `terra` raster objects into `raster` raster objects. This sounds confusing, but the package `gdistance` still uses the older form of raster data in R, which was managed in the package called `raster`. We can easily turn as `terra` `SpatRaster` object into a `raster` object using `raster()`. In the code above, we added the resistance surface into a raster stack so that resistance is the second layer in the stack called `hm`. We call landscape resistance as the second layer using `hm[[2]]`. We will convert that into a `raster` object.
We then need to create a transition matrix, which basically is needed to tell `gdistance` how to treat adjacent cells. We will use the inverse of the average resistance. This essentially turns our map of resistance to a map of conductance (1/resistance) and takes the average of resistance from neighboring cells. This tells R how to deal with adjacent pixels. We then need to perform a geographic correction so that R treats the geographic distance correctly.
```{r}
# Turn landscape resistance (the second layer in the stack you made above) into a
# raster object.
hm_raster <- raster::raster(hm[[2]])
# Create the transition layer so that R knows how to treat adjacent pixels
# We convert resistance into conductance
tr <- gdistance::transition(hm_raster, function(x) 1 / mean(x), directions = 8)
# Then, perform that georgaphic correction
tr_corr <- gdistance::geoCorrection(tr, type = "c", scl = TRUE)
```
## Running the randomized shortest path connectivity models in `passage`
We're going to run connectivity models between all pairs of core areas. Because gdistance has not been updated to work with `vect` objects from `terra`, we need to convert our cores to an `sp` object. Then, we will use [`combn`](https://www.rdocumentation.org/packages/utils/versions/3.6.2/topics/combn) to generate a matrix of all combinations of core areas.
```{r}
# Convert our terra vector cores to sp object
cores_sp <- as(cores, "Spatial")
# Create a matrix of all pairwise combinations of cores taking 2 at a time
Pj_combn <- combn(1:length(cores_sp), 2)
# Look at the pairwise combinations
print(Pj_combn)
```
Now, we will loop through all pairwise combinations of core areas and run the randomized shortest path in `passage`. We will establish theta as an object so that we can easily modify this term and re-run the models. Run the model using theta = 2 at first, then chose any value from 10 to 0.0000001. I recommend trying the lower values.
The loop below first establishes an empty list that we will call rsp (randomized shortest paths). The loop goes through each pairwise combination of cores. We start the loop with `for (i in 1:ncol(Pj_combn))` which tells R "for each combination of cores from the first combination of cores through the number of columns in Pj_comb object" do the work in the `{ }` brackets. So the loop starts by subsetting two cores (loc1 and loc2) from the `core_sp` object based on the combinations created in `Pj_combn`. The loop then runs the randomized shortest path from `passage` using the two cores subset in the first two lines in the loop. Note that it is using the geographically corrected transition layer we created above, and we have the theta option pointing to the theta term we assigned at the top of the chunk below.
NOTE: I have commented out a line that uses `cat()`. You can un-comment this by deleting the `#,` and R will print each step of the loop. This can be useful when you are running a large number of cores, but is not necessary here.
```{r}
# run passage model for each core pair
theta <- 2
rsp <- list()
for (i in 1:ncol(Pj_combn))
{
loc1 <- cores_sp[Pj_combn[1, i], ]
loc2 <- cores_sp[Pj_combn[2, i], ]
# cat(paste0("Running passage for pair ", i, " of ", ncol(Pj_combn), "\n"))
rsp[[i]] <- passage(tr_corr, origin = loc1, goal = loc2, theta = theta)
}
```
Now we have a list of outputs called `rsp` from above. Each of these outputs contains a randomized shortest path connectivity model for each combination of cores. We often want one map that shows a full network of linkages or corridors among cores, so we will combine these results. We will start by stacking up these outputs using the `raster` package method, which conveniently is called `stack()`. We then, will take the average of the values. We will plot the average of the outputs, look at the map, and then classify the data into quantiles to stretch the colors in a way that can reveal more patterns in the data and map.
Note that I have added a `main =` option in the plot that uses `paste0`. This allows me to create text strings that include values of "c" and "theta" I have assigned above. The `paste0` function can be really useful when you are conducting sensitivity analyses in models where you are varying different parameters and want to keep track of which values you used in each model run.
```{r}
# Summarize and visualize results by first stacking up output
# from each pairwise combinations
rsp_stack <- stack(rsp)
# Take an average of the values with mean()
rsp_overlay <- mean(rsp_stack)
# Look at the map of the outputs
plot(rsp_overlay, col = viridis(50), axes = FALSE, box = FALSE)
# Classify the output into 10 quantiles (i.e., deciles) for visualization
rsp_overlay$quantiles <- rsp_overlay %>% values() %>% ntile(10)
# plot the original map and the reclassified map to compare
# I have added a line where the choice of "c" value for
# transforming human modification into resistance is printed
# and where the theta in the randomized shortest path is printed
plot(rsp_overlay, col = viridis(50), axes = FALSE, box = FALSE, main = paste0("c = ", c, "\n theta = ", format(theta, scientific = FALSE)))
```
Finally, I recommend looking at the data in an interactive map with other cartographic features (mountain ranges, etc.). We first need to assign a coordinate reference system to the output and then we'll use `mapview` with the ESRI National Geographic basemap.
```{r}
# Assign the correct crs to the data
crs(rsp_overlay$quantiles) <- "EPSG:4326"
# Map the output.
# This will bring up an interactive map of the connectivity output.
if (knitr::is_html_output()) {
mapview(rsp_overlay$quantiles, alpha.regions = 0.6,
layer.name = "Connectivity",
map.types = "Esri.NatGeoWorldMap")
} else {
plot(rsp_overlay$quantiles, col = viridis(50), axes = FALSE, box = FALSE,
main = "Connectivity")
}
```
Compare your output to cumulative current flow from Circuitscape and least cost corridors and least cost paths from Linkage Mapper.
 *Output from Circuitscape and Linkage Mapper. Output from Linkage Mapper includes least cost corridors and least cost paths (black lines in map on the right).*
::: {.callout-tip appearance="minimal"}
**TASK 1.**
Design a multifactorial modeling experiment crossing the transformation of human modification into landscape resistance by varying "c" with the randomness of the connectivity output varying "theta". Use at least 3 "c" values and 3 "theta" values. You should have at least 9 outputs. This kind of exercise produces different maps representing different hypothesis while also allowing you to assess the sensitivity of outputs to different combinations of parameters.
Compare the maps with each other and consider their biological meaning (or lack of). How do the maps change with varying assumptions of landscape resistance (varying "c") and randomness of potential movements (varying "theta")? Which places (e.g., mountain ranges) are important for connectivity in which model runs? Which places are always important? Which places are only important for connectivity in certain model runs? Which models are relevant to which species and why?
Compare your 9 outputs to the results from *Circuitscape* and *Linkage Mapper*.
Present your maps with thorough figure captions. Please arrange your maps meaningfully as "[small multiples](https://en.wikipedia.org/wiki/Small_multiple)" (hint, you can simply do this by storing your output as separate maps and plotting them using `par(mfrow = c(3, 3)` or an alternative. Write up an abstract for *Landscape Ecology*.
:::
# Data source(s)
Human modification data can be downloaded here: <https://zenodo.org/records/14502573>