getCosts: Get cost of travel

View source: R/getCosts.R

getCostsR Documentation

Get cost of travel

Description

A function that calculates the cost to travel between two sets of points. This can be between two circumscribed sets of points, or one circumscribed one ('nodes') and all other points on the landscape.

Usage

getCosts(
  region,
  from,
  to = NULL,
  id = "ID",
  dir = tempdir(),
  x = "x",
  y = "y",
  destination = "pairs",
  polygons = "centroid",
  costs = c("dt", "dW_l", "dE_l"),
  direction = "both",
  output = "object",
  outname = deparse(substitute(from)),
  overwrite = FALSE,
  ...
)

Arguments

region

A SpatVector, Spatial* or Raster* representing the area of maximum movement

from

One of data.frame, data.table, SpatVector, SpatialPointsDataFrame, or SpatialPolygonsDataFrame representing the origin locations. If to = NULL and destination = 'pairs', this will also be used as the to parameter. If it is a polygon, the location will be controlled by the polygons parameter.

to

One of data.frame, data.table, SpatVector SpatialPointsDataFrame, or SpatialPolygonsDataFrame representing the origin locations. Optional if destination = 'pairs', ignored if destination = 'all'.

id

Character string representing the column containing the unique IDs for for each location in the from (and to) objects.

dir

A filepath to the directory being used as the workspace. Default is tempdir() but unless the analyses will only be performed a few times it is highly recommended to define a permanent workspace.

x

A character vector representing the column containing the 'x' coordinates. Required if data is not Spatial*.

y

A character vector representing the column containing the 'y' coordinates. Required if data is not Spatial*.

destination

One of 'pairs' or 'all'. If 'pairs', a distance matrix will be generated between every pair of locations in from, or every pair of locations between from and to. If 'all', rasters will be generated for each node representing the cost to travel to every cell in the given world.

polygons

One of c('polygon','centroid','center'). Ignored unless from and/or to are polygons. If polygons = 'centroid' (the default), the destinations are calculated to the centroid of the polygon whether or not it lies within the polygon itself. If polygons = 'center', distances are calculated to the point within the polygon closest to the centroid. If polygons = 'polygons', distances are calculated to any point within the polygon—in essence, the polygon acts as a giant node permitting costless movement within its bounds. This is generally not consistent with real-world scenarios and for that reason is not the default.

costs

A character vector containing any combination of the strings of differential values present in the environment (see calculateCosts function; default is costs = c("dt","dW_l","dE_l") anticipating the use of calculateCosts(costFUN = energyCosts).

direction

A character vector containing one or both of c("in","out") or the singular string 'both'. This determines whether costs to or from the nodes are calculated. Ignored for destination = 'pairs'.

output

A character vector containing one or both of c("object","file"). If "object" is included, then a list of RasterStacks will be returned. If "file" is included, then the appropriate cost rasters will be saved to the workspace directory dir. Ignored if destination = 'pairs'.

outname

A character vector describing the name of the set of input nodes for raster analysis. Ignored unless 'file' %in% output, in which case the files will be stored in a file named as such. Default is the name of the from input, which can lead to files being overwritten if vector sources are arbitrarily changed.

overwrite

Should any output files with the same outname be overwritten? Default is overwrite = FALSE.

...

Additional arguments to pass to importWorld.

Details

There are four possible workflows:

(1) If you simply desire the distance between two sets of points, provide entries for from and to (or just from if the interest is in all distances between locations in that object). Output is a distance matrix. The computational time for this operation is comparable to generating a raster for the distance to all cells in the world (unless all of the locations in the object are close to each other). So unless the operation is to be done multiple times, it is highly recommended to generate the rasters as below and extract values

(2) If you wish to generate a RasterStack of costs from and/or to all nodes in the from object, set the output = 'object' and destination = 'all'.

(3) You may also save the rasters as a series of .tif files in the same workspace directory as the transition .gz tensor files and the cropped/downloaded DEMs. This allows us to use getCosts within a loop for large numbers of origin nodes without running into random access memory limitations. Do this by setting output = 'file' and destination = 'all'.

(4) You may perform (2) and (3) simultaneously by setting output == c('file','object') and destination = 'all'.

Value

A list, with entries for each combination of selected costs and directions. The object class of the list entries depends on the destination and output parameters:

(1) If destination = 'pairs', entries are distance matrices. (2) If destination = 'all' and 'object' %in% output, entries are RasterStacks with each Raster* representing the cost to/from each node. (3) If destination = 'all' and output == 'file', no list is output.

Moreover, if file %in% output, then the cost rasters are saved in the workspace directory.

Examples

#### Example 1:
n <- 5
dem <- expand.grid(list(x = 1:(n * 100),
                        y = 1:(n * 100))) / 100
dem <- as.data.table(dem)
dem[, z := 250 * exp(-(x - n/2)^2) + 
      250 * exp(-(y - n/2)^2)]
dem <- rast(dem)
ext(dem) <- c(10000, 20000, 30000, 40000)
crs(dem) <- "+proj=lcc +lat_1=48 +lat_2=33 +lon_0=-100 +datum=WGS84"

# Export it so it doesn't just exist on the memory
dir <- tempdir()
writeRaster(dem, paste0(dir,"/DEM.tif"),overwrite=TRUE)


# Import raster, get the grid
dem <- rast(paste0(dir,"/DEM.tif"))
grid <- makeGrid(dem = dem, nx = n, ny = n, sources = TRUE)

# Select all tiles that exist between x = (12000,16000) and y = (32000,36000)
tiles <- ext(c(12000,16000,32000,36000))
tiles <- as.polygons(tiles)
crs(tiles) <- crs(grid)
tiles <- whichTiles(region = tiles, polys = grid)

region <- grid[8,]
# Generate five random points that fall within the region
points <- data.table(ID = 1:5,
                     x = runif(5, ext(region)[1], ext(region)[2]),
                     y = runif(5, ext(region)[3], ext(region)[4]))
                     
# Make a world but limit it to the DEM grid size
defineWorld(source = grid, cut_slope = 0.5, 
            res = res(dem), dir = dir, overwrite=TRUE)
            
# Get time and work costs between points
costMatrix <- getCosts(grid[8,], from = points, dir = dir, 
                       costs = c('dt','dW_l'), costFUN = energyCosts,
                       m = 70, v_max = 1.5, BMR = 76, k = 3.5, s = 0.05, l_s = 1,
                       L = 0.8)
                   
#### Example 2:
# Calculate the cost rasters to travel to ad from the center of a polygon
costRasters <- getCosts(grid[8,], from = grid[8,], dir = dir, destination = 'all',
                       polygons = 'center',
                       costs = c('dt','dW_l'), costFUN = energyCosts,
                       m = 70, v_max = 1.5, BMR = 76, k = 3.5, s = 0.05, l_s = 1,
                       L = 0.8)


andresgmejiar/lbmech documentation built on Feb. 2, 2025, 12:37 a.m.