Incomplete set of shortest paths from gdistance

45 Views Asked by At

When least cost paths between two spatial points on a raster are calculated with gdistance, the resulting set of least cost paths seems to be incomplete. Specifically, not all ties are systematically included among the spatial lines that compose the output. The minimum working example hereby illustrates the issue.

To be clear, any alternative code that could still compute LCPs while properly correcting for distance on the transition layer would still be fine. But for the time being, I have focused on the only approach I can come up with, which still relies on gdistance and raster.

# Packages
library(gdistance)
library(raster)
library(sp)
library(terra)

# Cost matrix
nr <- 3
nc <- 3
cost.m <- matrix(
  data = c( 1, 1, 1,
            1, 3, 1,
            1, 1, 1),
  nrow = nr,
  ncol = nc,
  byrow = T)

# Cost raster
cost.r <- rast(
  cost.m,
  crs = "EPSG:3003"
)

# Conductance raster
conductance.r <- rast(
  1/cost.m, 
  crs = "EPSG:3003")

# Transition layer
conductance.tr <- gdistance::transition(
  raster(conductance.r),
  transitionFunction = mean,
  directions = 8,
  symm = T
)
conductance.tr <- gdistance::geoCorrection(conductance.tr,
                                           type = "c",
                                           multpl = F)

# Polygons from raster cells
pgn <- as.polygons(conductance.r,
                   aggregate = F,
                   na.rm = T,
                   na.all = T)
crs(pgn) <- crs(conductance.r)

# Endpoints as cell centroids
endpts <- centroids(pgn) %>% 
  as("Spatial")

# Least cost paths
lcp <- gdistance::shortestPath(conductance.tr, 
                               endpts[2,], 
                               endpts[8,], 
                               output = "SpatialLines")
# Plot
plot(conductance.r, axes=F)
plot(pgn,border="white",add=T)
plot(lcp,lwd=2,col="black",add=T)
plot(endpts[c(2,8),],pch=16,col="black",add=T)

enter image description here

I have also entertained related discussions with the maintainer of the package leastcostpath. In particular, this question shows how the problem was first noted, while this other question and related comments clarify why I still need to use gdistance in order to have proper distance correction in the computation of least cost paths.

0

There are 0 best solutions below