| Title: | Distances on Directed Graphs |
| Version: | 0.4.3 |
| Description: | Distances on dual-weighted directed graphs using priority-queue shortest paths (Padgham (2019) <doi:10.32866/6945>). Weighted directed graphs have weights from A to B which may differ from those from B to A. Dual-weighted directed graphs have two sets of such weights. A canonical example is a street network to be used for routing in which routes are calculated by weighting distances according to the type of way and mode of transport, yet lengths of routes must be calculated from direct distances. |
| License: | GPL-3 |
| URL: | https://UrbanAnalyst.github.io/dodgr/,https://github.com/UrbanAnalyst/dodgr |
| BugReports: | https://github.com/UrbanAnalyst/dodgr/issues |
| Depends: | R (≥ 3.5.0) |
| Imports: | callr, digest, fs, geodist (≥ 0.1.0), magrittr, memoise,methods, osmdata, Rcpp (≥ 0.12.6), RcppParallel |
| Suggests: | bench, dplyr, ggplot2, igraph, igraphdata, jsonlite, knitr,markdown, rmarkdown, sf, testthat (≥ 3.1.6), tidygraph |
| LinkingTo: | Rcpp, RcppParallel, RcppThread |
| VignetteBuilder: | knitr |
| Encoding: | UTF-8 |
| LazyData: | true |
| NeedsCompilation: | yes |
| RoxygenNote: | 7.3.2 |
| SystemRequirements: | GNU make |
| Packaged: | 2025-09-01 11:38:06 UTC; smexus |
| Author: | Mark Padgham [aut, cre], Andreas Petutschnig [aut], David Cooley [aut], Robin Lovelace [ctb], Andrew Smith [ctb], Malcolm Morgan [ctb], Andrea Gilardi |
| Maintainer: | Mark Padgham <mark.padgham@email.com> |
| Repository: | CRAN |
| Date/Publication: | 2025-09-01 14:20:02 UTC |
Distances On Directed GRaphs ("dodgr")
Description
Distances on dual-weighted directed graphs using priority-queue shortestpaths. Weighted directed graphs have weights from A to B which may differfrom those from B to A. Dual-weighted directed graphs have two sets of suchweights. A canonical example is a street network to be used for routing inwhich routes are calculated by weighting distances according to the type ofway and mode of transport, yet lengths of routes must be calculated fromdirect distances.
The Main Function
dodgr_dists(): Calculate pair-wise distances betweenspecified pairs of points in a graph.
Functions to Obtain Graphs
dodgr_streetnet(): Extract a street network in SimpleFeatures (sf) form.weight_streetnet(): Convert ansf-formatted streetnetwork to adodgrgraph through applying specified weights to alledges.
Functions to Modify Graphs
dodgr_components(): Number all graph edges according totheir presence in distinct connected components.dodgr_contract_graph(): Contract a graph by removingredundant edges.
Miscellaneous Functions
dodgr_sample(): Randomly sample a graph, returning a singleconnected component of a defined number of vertices.dodgr_vertices(): Extract all vertices of a graph.compare_heaps(): Compare the performance of differentpriority queue heap structures for a given type of graph.
Author(s)
Maintainer: Mark Padghammark.padgham@email.com
Authors:
Andreas Petutschnig
David Cooley
Other contributors:
Robin Lovelace [contributor]
Andrew Smith [contributor]
Malcolm Morgan [contributor]
Andrea Gilardi (ORCID) [contributor]
Eduardo Leoni (ORCID) [contributor]
Shane Saunders (Original author of included code for priority heaps) [copyright holder]
Stanislaw Adaszewski (author of include concaveman-cpp code) [copyright holder]
See Also
Useful links:
Report bugs athttps://github.com/UrbanAnalyst/dodgr/issues
Pipe operator
Description
Pipe operator
Usage
lhs %>% rhsInsert new nodes into a graph, breaking edges at point of nearestintersection.
Description
Note that this routine presumes graphs to bedodgr_streetnet object, withgeographical coordinates.
Usage
add_nodes_to_graph(graph, xy, dist_tol = 0.000001, intersections_only = FALSE)Arguments
graph | A |
xy | coordinates of points to be matched to the vertices, either asmatrix orsf-formatted |
dist_tol | Only insert new nodes if they are further from existing nodesthan this distance, expressed in units of the distance column of |
intersections_only | If |
Details
This inserts new nodes by extending lines from each input point to the edgewith the closest point of perpendicular intersection. That edge is then splitat that point of intersection, creating two new edges (or four for directededges). Ifintersections_only = FALSE (default), then additional edges areinserted from those intersection points to the input points. Ifintersections_only = TRUE, then nodes are added by splitting graph edges atpoints of nearest perpendicular intersection, without adding additional edgesout to the actual input points.
In the former case, the properties of those new edges, such as distance andtime weightings, are inherited from the edges which are intersected, and mayneed to be manually modified after calling this function.
Value
A modified version ofgraph, with additional edges formed bybreaking previous edges at nearest perpendicular intersections with thepoints,xy.
See Also
Other match:match_points_to_graph(),match_points_to_verts(),match_pts_to_graph(),match_pts_to_verts()
Examples
graph <- weight_streetnet (hampi, wt_profile = "foot")dim (graph)verts <- dodgr_vertices (graph)set.seed (2)npts <- 10xy <- data.frame ( x = min (verts$x) + runif (npts) * diff (range (verts$x)), y = min (verts$y) + runif (npts) * diff (range (verts$y)))graph <- add_nodes_to_graph (graph, xy)dim (graph) # more edges than originalRemove cached versions ofdodgr graphs.
Description
This function should generallynot be needed, except if graphstructure has been directly modified other than throughdodgr functions;for example by modifying edge weights or distances. Graphs are cached basedon the vector of edge IDs, so manual changes to any other attributes will notnecessarily be translated into changes indodgr output unless the cachedversions are cleared using this function. Seehttps://github.com/UrbanAnalyst/dodgr/wiki/Caching-of-streetnets-and-contracted-graphsfor details of caching process.
Usage
clear_dodgr_cache()Value
Nothing; the function silently clears any cached objects
See Also
Other cache:dodgr_cache_off(),dodgr_cache_on(),dodgr_load_streetnet(),dodgr_save_streetnet()
Examples
clear_dodgr_cache ()# Then call dodgr functions as usual:graph <- weight_streetnet (hampi, wt_profile = "foot")Compare timings of different sort heaps for a given input graph.
Description
Perform timing comparison between different kinds of heaps as well as withequivalent routines from theigraph package. To do this, a randomsub-graph containing a defined number of vertices is first selected.Alternatively, this random sub-graph can be pre-generated with thedodgr_sample function and passed directly.
Usage
compare_heaps(graph, nverts = 100, replications = 2)Arguments
graph |
|
nverts | Number of vertices used to generate random sub-graph. If anon-numeric value is given, the whole graph will be used. |
replications | Number of replications to be used in comparison |
Value
Result ofbench::mark comparison.
See Also
Other misc:dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)## Not run: compare_heaps (graph, nverts = 1000, replications = 1)## End(Not run)Turn off all dodgr caching in current session.
Description
This function is useful is speed is paramount, and if graph contraction isnot needed. Caching can be switched back on withdodgr_cache_on.
Usage
dodgr_cache_off()Value
Nothing; the function invisibly returnsTRUE if successful.
See Also
Other cache:clear_dodgr_cache(),dodgr_cache_on(),dodgr_load_streetnet(),dodgr_save_streetnet()
Examples
dodgr_cache_off ()# Then call dodgr functions as usual:graph <- weight_streetnet (hampi, wt_profile = "foot")Turn on all dodgr caching in current session.
Description
This will only have an effect after caching has been turned off withdodgr_cache_off.
Usage
dodgr_cache_on()Value
Nothing; the function invisibly returnsTRUE if successful.
See Also
Other cache:clear_dodgr_cache(),dodgr_cache_off(),dodgr_load_streetnet(),dodgr_save_streetnet()
Examples
dodgr_cache_on ()# Then call dodgr functions as usual:graph <- weight_streetnet (hampi, wt_profile = "foot")Calculate betweenness centrality for a 'dodgr' network.
Description
Centrality can be calculated in either vertex- or edge-based form.
Usage
dodgr_centrality( graph, contract = TRUE, edges = TRUE, column = "d_weighted", vert_wts = NULL, dist_threshold = NULL, heap = "BHeap", check_graph = TRUE)Arguments
graph | 'data.frame' or equivalent object representing the networkgraph (see Details) |
contract | If 'TRUE', centrality is calculated on contracted graphbefore mapping back on to the original full graph. Note that for streetnetworks, in particular those obtained from theosmdata package, vertexplacement is effectively arbitrary except at junctions; centrality for suchgraphs should only be calculated between the latter points, and thus'contract' should always be 'TRUE'. |
edges | If 'TRUE', centrality is calculated for graph edges, returningthe input 'graph' with an additional 'centrality' column; otherwisecentrality is calculated for vertices, returning the equivalent of'dodgr_vertices(graph)', with an additional vertex-based 'centrality' column. |
column | Column of graph defining the edge properties used to calculatecentrality (see Note). |
vert_wts | Optional vector of length equal to number of vertices( |
dist_threshold | If not 'NULL', only calculate centrality for each pointout to specified threshold. Setting values for this will result inapproximate estimates for centrality, yet with considerable gains incomputational efficiency. For sufficiently large values, approximations willbe accurate to within some constant multiplier. Appropriate values can beestablished via theestimate_centrality_threshold function. |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; 'FHeap'), Binary Heap ('BHeap'),Trinomial Heap ('TriHeap'), Extended Trinomial Heap('TriHeapExt', and 2-3 Heap ('Heap23'). |
check_graph | If |
Value
Modified version of graph with additional 'centrality' column added.
Note
Thecolumn parameter is by defaultd_weighted, meaning centralityis calculated by routing according to weighted distances. Other possiblevalues for this parameter are
dfor unweighted distancestimefor unweighted time-based routingtime_weightedfor weighted time-based routing
Centrality is calculated by default using parallel computation with themaximal number of available cores or threads. This number can be reduced byspecifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
See Also
Other centrality:estimate_centrality_threshold(),estimate_centrality_time()
Examples
## Not run: graph_full <- weight_streetnet (hampi)graph <- dodgr_contract_graph (graph_full)graph <- dodgr_centrality (graph)# 'graph' is then the contracted graph with an additional 'centrality' column# Same calculation via 'igraph':igr <- dodgr_to_igraph (graph)library (igraph)cent <- edge_betweenness (igr)identical (cent, graph$centrality) # TRUE# Values of centrality between all junctions in the contracted graph can then# be mapped back onto the original full network by "uncontracting":graph_full <- dodgr_uncontract_graph (graph)# For visualisation, it is generally necessary to merge the directed edges to# form an equivalent undirected graph. Conversion to 'sf' format via# 'dodgr_to_sf()' is also useful for many visualisation routines.graph_sf <- merge_directed_graph (graph_full) %>% dodgr_to_sf ()## End(Not run)## Not run: library (mapview)centrality <- graph_sf$centrality / max (graph_sf$centrality)ncols <- 30cols <- c ("lawngreen", "red")cols <- colorRampPalette (cols) (ncols) [ceiling (ncols * centrality)]mapview (graph_sf, color = cols, lwd = 10 * centrality)## End(Not run)# An example of flow aggregation across a generic (non-OSM) highway,# represented as the 'routes_fast' object of the \pkg{stplanr} package,# which is a SpatialLinesDataFrame containing commuter densities along# components of a street network.## Not run: library (stplanr)# merge all of the 'routes_fast' lines into a single networkr <- overline (routes_fast, attrib = "length", buff_dist = 1)r <- sf::st_as_sf (r)# Convert to a 'dodgr' network, for which we need to specify both a 'type'# and 'id' column.r$type <- 1r$id <- seq (nrow (r))graph_full <- weight_streetnet ( r, type_col = "type", id_col = "id", wt_profile = 1)# convert to contracted form, retaining junction vertices only, and append# 'centrality' columngraph <- dodgr_contract_graph (graph_full) %>% dodgr_centrality ()#' expand back to full graph; merge directed flows; and convert result to# 'sf'-format for plottinggraph_sf <- dodgr_uncontract_graph (graph) %>% merge_directed_graph () %>% dodgr_to_sf ()plot (graph_sf ["centrality"])## End(Not run)Identify connected components of graph.
Description
Identify connected components of graph and add correspondingcomponentcolumn todata.frame.
Usage
dodgr_components(graph)Arguments
graph | A |
Value
Equivalent graph with additionalcomponent column,sequentially numbered from 1 = largest component.
See Also
Other modification:dodgr_contract_graph(),dodgr_uncontract_graph()
Examples
graph <- weight_streetnet (hampi)graph <- dodgr_components (graph)Contract graph to junction vertices only.
Description
Removes redundant (straight-line) vertices from graph, leaving only junctionvertices.
Usage
dodgr_contract_graph(graph, verts = NULL, nocache = FALSE)Arguments
graph | A flat table of graph edges. Must contain columns labelled |
verts | Optional list of vertices to be retained as routing points.These must match the |
nocache | If |
Value
A contracted version of the originalgraph, containing the samenumber of columns, but with each row representing an edge between twojunction vertices (or between the submittedverts, which may or may not bejunctions).
See Also
Other modification:dodgr_components(),dodgr_uncontract_graph()
Examples
graph <- weight_streetnet (hampi)nrow (graph) # 5,973graph <- dodgr_contract_graph (graph)nrow (graph) # 662Deduplicate edges in a graph
Description
Graph may have duplicated edges, particularly when extracted asdodgr_streetnet objects. This function de-duplicates any repeatededges, reducing weighted distances and times to the minimal values from allduplicates.
Usage
dodgr_deduplicate_graph(graph)Arguments
graph | Any 'dodgr' graph or network. |
Value
A potentially modified version of graph, with any formerly duplicatededges reduces to single rows containing minimal weighted distances and times.
See Also
Other conversion:dodgr_to_igraph(),dodgr_to_sf(),dodgr_to_sfc(),dodgr_to_tidygraph(),igraph_to_dodgr()
Examples
net0 <- weight_streetnet (hampi, wt_profile = "foot")nrow (net0)# Duplicate part of input data:h2 <- rbind (hampi, hampi [1, ])net1 <- weight_streetnet (h2, wt_profile = "foot")nrow (net1) # network then has more edgesnet2 <- dodgr_deduplicate_graph (net1)nrow (net2)stopifnot (identical (nrow (net0), nrow (net2)))Calculate matrix of pair-wise distances between points.
Description
Alias fordodgr_dists
Usage
dodgr_distances( graph, from = NULL, to = NULL, shortest = TRUE, pairwise = FALSE, heap = "BHeap", parallel = TRUE, quiet = TRUE)Arguments
graph |
The Note that longitude and latitude values are always interpreted in 'dodgr' tobe in EPSG:4326 / WSG84 coordinates. Any other kinds of coordinates shouldfirst be reprojected to EPSG:4326 before submitting to any 'dodgr' routines. See further information in Details. |
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
shortest | If |
pairwise | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
parallel | If |
quiet | If |
Value
square matrix of distances between nodes
See Also
Other distances:dodgr_dists(),dodgr_dists_categorical(),dodgr_dists_nearest(),dodgr_paths(),dodgr_times()
Examples
# A simple graphgraph <- data.frame ( from = c ("A", "B", "B", "B", "C", "C", "D", "D"), to = c ("B", "A", "C", "D", "B", "D", "C", "A"), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph)# Example of "from" and "to" as integer-ish values, in which case they are# interpreted to index into "dodgr_vertices()":graph <- data.frame ( from = c (1, 3, 2, 2, 3, 3, 4, 4), to = c (2, 1, 3, 4, 2, 4, 3, 1), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph, from = 1, to = 2)# That then gives distance from "1" to "3" because the vertices are built# sequentially along "graph$from":dodgr_vertices (graph)# And vertex$id [2] is "3"# A larger example from the included [hampi()] data.graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)to <- sample (graph$to_id, size = 50)d <- dodgr_dists (graph, from = from, to = to)# d is a 100-by-50 matrix of distances between `from` and `to`## Not run: # a more complex street network example, thanks to @chrijo; see# https://github.com/UrbanAnalyst/dodgr/issues/47xy <- rbind ( c (7.005994, 51.45774), # limbeckerplatz 1 essen germany c (7.012874, 51.45041)) # hauptbahnhof essen germanyxy <- data.frame (lon = xy [, 1], lat = xy [, 2])essen <- dodgr_streetnet (pts = xy, expand = 0.2, quiet = FALSE)graph <- weight_streetnet (essen, wt_profile = "foot")d <- dodgr_dists (graph, from = xy, to = xy)# First reason why this does not work is because the graph has multiple,# disconnected components.table (graph$component)# reduce to largest connected component, which is always number 1graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)# should work, but even then note thattable (essen$level)# There are parts of the network on different building levels (because of# shopping malls and the like). These may or may not be connected, so it may# be necessary to filter out particular levelsindex <- which (!(essen$level == "-1" | essen$level == "1")) # for examplelibrary (sf) # needed for following sub-select operationessen <- essen [index, ]graph <- weight_streetnet (essen, wt_profile = "foot")graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)## End(Not run)Calculate matrix of pair-wise distances between points.
Description
Calculates distances from inputdata.frame objects (graph),which must minimally contain three columns offrom,to, andd ordist. If an additional column namedweight orwt is present, shortestpaths are calculated according to values specified in that column, whiledistances returned are calculated from thed ordist column. That is,paths between any pair of points will be calculated according to the minimaltotal sum ofweight values (if present), while reported distances will betotal sums ofdist values.
Graphs derived from Open Street Map street networks, via theweight_streetnet function, have columns labelledd,d_weighted,time, andtime_weighted. For these inputs, paths between origin anddestination points are always routed usingd_weighted (ort_weighted fortimes), while final distances are sums of values ofd (ort for times)-that is, of un-weighted distances or times - along those paths.
The function is parallelized for efficient computation of distances betweenmultiple origin and destination points, as described in thefrom parameterbelow.
Usage
dodgr_dists( graph, from = NULL, to = NULL, shortest = TRUE, pairwise = FALSE, heap = "BHeap", parallel = TRUE, quiet = TRUE)Arguments
graph |
The Note that longitude and latitude values are always interpreted in 'dodgr' tobe in EPSG:4326 / WSG84 coordinates. Any other kinds of coordinates shouldfirst be reprojected to EPSG:4326 before submitting to any 'dodgr' routines. See further information in Details. |
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
shortest | If |
pairwise | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
parallel | If |
quiet | If |
Value
square matrix of distances between nodes
See Also
Other distances:dodgr_distances(),dodgr_dists_categorical(),dodgr_dists_nearest(),dodgr_paths(),dodgr_times()
Examples
# A simple graphgraph <- data.frame ( from = c ("A", "B", "B", "B", "C", "C", "D", "D"), to = c ("B", "A", "C", "D", "B", "D", "C", "A"), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph)# Example of "from" and "to" as integer-ish values, in which case they are# interpreted to index into "dodgr_vertices()":graph <- data.frame ( from = c (1, 3, 2, 2, 3, 3, 4, 4), to = c (2, 1, 3, 4, 2, 4, 3, 1), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph, from = 1, to = 2)# That then gives distance from "1" to "3" because the vertices are built# sequentially along "graph$from":dodgr_vertices (graph)# And vertex$id [2] is "3"# A larger example from the included [hampi()] data.graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)to <- sample (graph$to_id, size = 50)d <- dodgr_dists (graph, from = from, to = to)# d is a 100-by-50 matrix of distances between `from` and `to`## Not run: # a more complex street network example, thanks to @chrijo; see# https://github.com/UrbanAnalyst/dodgr/issues/47xy <- rbind ( c (7.005994, 51.45774), # limbeckerplatz 1 essen germany c (7.012874, 51.45041)) # hauptbahnhof essen germanyxy <- data.frame (lon = xy [, 1], lat = xy [, 2])essen <- dodgr_streetnet (pts = xy, expand = 0.2, quiet = FALSE)graph <- weight_streetnet (essen, wt_profile = "foot")d <- dodgr_dists (graph, from = xy, to = xy)# First reason why this does not work is because the graph has multiple,# disconnected components.table (graph$component)# reduce to largest connected component, which is always number 1graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)# should work, but even then note thattable (essen$level)# There are parts of the network on different building levels (because of# shopping malls and the like). These may or may not be connected, so it may# be necessary to filter out particular levelsindex <- which (!(essen$level == "-1" | essen$level == "1")) # for examplelibrary (sf) # needed for following sub-select operationessen <- essen [index, ]graph <- weight_streetnet (essen, wt_profile = "foot")graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)## End(Not run)Cumulative distances along different edge categories
Description
The maindodgr_distances function calculates distancesbetween input sets of origin and destination points, and returns a singlematrix of numeric distances. This function aggregates distances alongcategories of edges or segments, and returns an overall distance matrix(identical to the result ofdodgr_distances), along with oneadditional matrix for each edge category.
Edges types must be specified in a column of the input graph named"edge_type". If this has two types of values (for example, "a"and "b"), then the function will return two additional distance matrices,one of total lengths of distances between all pairs of points traversedalong edges of the first type, "a", and one of aggregated distances alongedges of type "b".
See the description ofdodgr_distances for details on the expectedformat of input graphs.
Usage
dodgr_dists_categorical( graph, from = NULL, to = NULL, proportions_only = FALSE, pairwise = FALSE, dlimit = NULL, heap = "BHeap", quiet = TRUE)Arguments
graph |
|
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
proportions_only | If |
pairwise | If |
dlimit | If no value to |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
quiet | If |
Value
Ifto is specified, a list of distance matrices of equal dimensions(length(from), length(to)), the first of which ("distance") holds the finaldistances, while the rest are one matrix for each unique value of"edge_type", holding the distances traversed along those types of edges only.Otherwise, a single matrix of total distances along all ways from each pointout to the specified value ofdlimit, along with distances along each ofthe different kinds of ways specified in the "edge_type" column of the inputgraph.
Note
The "edge_type" column in the graph can contain any kind of discrete orcategorical values, although integer values of 0 are not permissible.NAvalues are ignored. The function requires one full distancematrix to be stored for each category of "edge_type" (unlessproportions_only = TRUE). It is wise to keep numbers of discrete types aslow as possible, especially for large distance matrices.
Setting theproportions_only flag toTRUE may be advantageous forlarge jobs, because this avoids construction of the full matrices. This mayspeed up calculations, but perhaps more importantly it may make possiblecalculations which would otherwise require distance matrices too large to bedirectly stored.
Calculations are not able to be interrupted (for example, byCtrl-C),and can only be stopped by killing the R process.
See Also
Other distances:dodgr_distances(),dodgr_dists(),dodgr_dists_nearest(),dodgr_paths(),dodgr_times()
Examples
# Prepare a graph for categorical routing by including an "edge_type" columngraph <- weight_streetnet (hampi, wt_profile = "foot")graph <- graph [graph$component == 1, ]graph$edge_type <- graph$highway# Define start and end points for categorical distances; using all vertices# here.length (unique (graph$edge_type)) # Number of categoriesv <- dodgr_vertices (graph)from <- to <- v$id [1:100]d <- dodgr_dists_categorical (graph, from, to)# Internal 'summary' method to summarise results:summary (d)class (d)length (d)sapply (d, dim)# 9 distance matrices, all of same dimensions, first of which is standard# distance matrixs <- summary (d) # print summary as proportions along each "edge_type"# or directly calculate proportions onlydodgr_dists_categorical (graph, from, to, proportions_only = TRUE)# Pairwise distances return single matrix with number of rows equal to 'from'# / 'to', and number of columns equal to number of edge types plus one for# total distances.d <- dodgr_dists_categorical (graph, from, to, pairwise = TRUE)class (d)dim (d)# The 'dlimit' parameter can be used to calculate total distances along each# category of edges from a set of points out to specified threshold:dlimit <- 2000 # in metresd <- dodgr_dists_categorical (graph, from, dlimit = dlimit)dim (d) # length(from), length(unique(edge_type)) + 1Calculate vector of shortest distances from a series of 'from' points tonearest one of series of 'to' points.
Description
Calculate vector of shortest distances from a series of 'from' points tonearest one of series of 'to' points.
Usage
dodgr_dists_nearest( graph, from = NULL, to = NULL, shortest = TRUE, heap = "BHeap", quiet = TRUE)Arguments
graph |
The Note that longitude and latitude values are always interpreted in 'dodgr' tobe in EPSG:4326 / WSG84 coordinates. Any other kinds of coordinates shouldfirst be reprojected to EPSG:4326 before submitting to any 'dodgr' routines. See further information in Details. |
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
shortest | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
quiet | If |
Value
Vector of distances, one element for each 'from' point giving thedistance to the nearest 'to' point.
Note
graph must minimally contain three columns offrom,to,dist. If an additional column namedweight orwt is present, shortest paths are calculated according to valuesspecified in that column; otherwise according todist values. Eitherway, final distances betweenfrom andto points are calculatedby default according to values ofdist. That is, paths between any pair ofpoints will be calculated according to the minimal total sum ofweightvalues (if present), while reported distances will be total sums ofdistvalues.
For street networks produced withweight_streetnet, distances may alsobe calculated along thefastest routes with theshortest = FALSEoption. Graphs must in this case have columns oftime andtime_weighted.Note that the fastest routes will only be approximate when derived fromsf-format data generated with theosmdata functionosmdata_sf(), and will be much more accurate when derived fromsc-formatdata generated withosmdata_sc(). Seeweight_streetnet for details.
Thefrom andto columns ofgraph may be either singlecolumns of numeric or character values specifying the numbers or names ofgraph vertices, or combinations to two columns specifying geographical(longitude and latitude) coordinates. In the latter case, almost any sensiblecombination of names will be accepted (for example,fromx, fromy,from_x, from_y, orfr_lat, fr_lon.)
from andto values can be either two-column matrices orequivalent of longitude and latitude coordinates, or else single columnsprecisely matching node numbers or names given ingraph$from orgraph$to. Ifto isNULL, pairwise distances are calculated from allfrom points to all other nodes ingraph. If bothfrom andto areNULL, pairwise distances are calculated between all nodes ingraph.
Calculations are always calculated in parallel, using multiple threads.
See Also
Other distances:dodgr_distances(),dodgr_dists(),dodgr_dists_categorical(),dodgr_paths(),dodgr_times()
Examples
# A simple graphgraph <- data.frame ( from = c ("A", "B", "B", "B", "C", "C", "D", "D"), to = c ("B", "A", "C", "D", "B", "D", "C", "A"), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph)# A larger example from the included [hampi()] data.graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)to <- sample (graph$to_id, size = 50)d <- dodgr_dists (graph, from = from, to = to)# d is a 100-by-50 matrix of distances between `from` and `to`## Not run: # a more complex street network example, thanks to @chrijo; see# https://github.com/UrbanAnalyst/dodgr/issues/47xy <- rbind ( c (7.005994, 51.45774), # limbeckerplatz 1 essen germany c (7.012874, 51.45041)) # hauptbahnhof essen germanyxy <- data.frame (lon = xy [, 1], lat = xy [, 2])essen <- dodgr_streetnet (pts = xy, expand = 0.2, quiet = FALSE)graph <- weight_streetnet (essen, wt_profile = "foot")d <- dodgr_dists (graph, from = xy, to = xy)# First reason why this does not work is because the graph has multiple,# disconnected components.table (graph$component)# reduce to largest connected component, which is always number 1graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)# should work, but even then note thattable (essen$level)# There are parts of the network on different building levels (because of# shopping malls and the like). These may or may not be connected, so it may# be necessary to filter out particular levelsindex <- which (!(essen$level == "-1" | essen$level == "1")) # for examplelibrary (sf) # needed for following sub-select operationessen <- essen [index, ]graph <- weight_streetnet (essen, wt_profile = "foot")graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)## End(Not run)Create a map ofdodgr flows.
Description
Create a map of the output ofdodgr_flows_aggregate ordodgr_flows_disperse
Usage
dodgr_flowmap(net, bbox = NULL, linescale = 1)Arguments
net | A street network with a |
bbox | If given, scale the map to this bbox, otherwise use entire extendof |
linescale | Maximal thickness of plotted lines |
Value
Nothing; called for side-effect of producing plot.
Note
net should be first passed throughmerge_directed_graphprior to plotting, otherwise lines for different directions will be overlaid.
See Also
Other misc:compare_heaps(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 10)to <- sample (graph$to_id, size = 5)to <- to [!to %in% from]flows <- matrix ( 10 * runif (length (from) * length (to)), nrow = length (from))graph <- dodgr_flows_aggregate (graph, from = from, to = to, flows = flows)# graph then has an additonal 'flows` column of aggregate flows along all# edges. These flows are directed, and can be aggregated to equivalent# undirected flows on an equivalent undirected graph with:graph_undir <- merge_directed_graph (graph)## Not run: dodgr_flowmap (graph_undir)## End(Not run)Aggregate flows throughout a network.
Description
Aggregate flows throughout a network based on an input matrixof flows between all pairs offrom andto points. Flows are calculatedby default on contracted graphs, via thecontract = TRUE parameter. (Theseare derived by reducing the input graph down to junction vertices only, byjoining all intermediate edges between each junction.) If changes to theinput graph do not prompt changes to resultant flows, and the defaultcontract = TRUE is used, it may be that calculations are using previouslycached versions of the contracted graph. If so, please use eitherclear_dodgr_cache to remove the cached version, ordodgr_cache_off prior to initial graph construction to switch thecache off completely.
Usage
dodgr_flows_aggregate( graph, from, to, flows, pairwise = FALSE, contract = TRUE, heap = "BHeap", tol = 0.000000000001, norm_sums = TRUE, quiet = TRUE)Arguments
graph |
|
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
flows | Matrix of flows with |
pairwise | If |
contract | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
tol | Relative tolerance below which flows towards |
norm_sums | Standardise sums from all origin points, so sum of flowsthroughout entire network equals sum of densities from all origins (seeNote). |
quiet | If |
Value
Modified version of graph with additionalflow column added.
Note
Thenorm_sums parameter should be used whenever densities at originsand destinations are absolute values, and ensures that the sum of resultantflow values throughout the entire network equals the sum of densities at allorigins. For example, withnorm_sums = TRUE (the default), a flow from asingle origin with density one to a single destination along two edges willallocate flows of one half to each of those edges, such that the sum of flowsacross the network will equal one, or the sum of densities from all origins.Thenorm_sums = TRUE option is appropriate where densities are relativevalues, and ensures that each edge maintains relative proportions. In theabove example, flows along each of two edges would equal one, for a networksum of two, or greater than the sum of densities.
Flows are calculated by default using parallel computation with the maximalnumber of available cores or threads. This number can be reduced byspecifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
See Also
Other flows:dodgr_flows_disperse(),dodgr_flows_si()
Examples
graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 10)to <- sample (graph$to_id, size = 5)to <- to [!to %in% from]flows <- matrix (10 * runif (length (from) * length (to)), nrow = length (from))graph <- dodgr_flows_aggregate (graph, from = from, to = to, flows = flows)# graph then has an additonal 'flows' column of aggregate flows along all# edges. These flows are directed, and can be aggregated to equivalent# undirected flows on an equivalent undirected graph with:graph_undir <- merge_directed_graph (graph)# This graph will only include those edges having non-zero flows, and so:nrow (graph)nrow (graph_undir) # the latter is much smaller# The following code can be used to convert the resultant graph to an `sf`# object suitable for plotting## Not run: gsf <- dodgr_to_sf (graph_undir)# example of plotting with the 'mapview' packagelibrary (mapview)flow <- gsf$flow / max (gsf$flow)ncols <- 30cols <- c ("lawngreen", "red")colranmp <- colorRampPalette (cols) (ncols) [ceiling (ncols * flow)]mapview (gsf, color = colranmp, lwd = 10 * flow)## End(Not run)# An example of flow aggregation across a generic (non-OSM) highway,# represented as the `routes_fast` object of the \pkg{stplanr} package,# which is a SpatialLinesDataFrame containing commuter densities along# components of a street network.## Not run: library (stplanr)# merge all of the 'routes_fast' lines into a single networkr <- overline (routes_fast, attrib = "length", buff_dist = 1)r <- sf::st_as_sf (r)# then extract the start and end points of each of the original 'routes_fast'# lines and use these for routing with `dodgr`l <- lapply (routes_fast@lines, function (i) { c ( sp::coordinates (i) [[1]] [1, ], tail (sp::coordinates (i) [[1]], 1) )})l <- do.call (rbind, l)xy_start <- l [, 1:2]xy_end <- l [, 3:4]# Then just specify a generic OD matrix with uniform values of 1:flows <- matrix (1, nrow = nrow (l), ncol = nrow (l))# We need to specify both a `type` and `id` column for the# \link{weight_streetnet} function.r$type <- 1r$id <- seq (nrow (r))graph <- weight_streetnet ( r, type_col = "type", id_col = "id", wt_profile = 1)f <- dodgr_flows_aggregate ( graph, from = xy_start, to = xy_end, flows = flows)# Then merge directed flows and convert to \pkg{sf} for plotting as before:f <- merge_directed_graph (f)geoms <- dodgr_to_sfc (f)gc <- dodgr_contract_graph (f)gsf <- sf::st_sf (geoms)gsf$flow <- gc$flow# sf plot:plot (gsf ["flow"])## End(Not run)Aggregate flows dispersed from each point in a network.
Description
Disperse flows throughout a network based on a input vectors oforigin points and associated densities. Dispersal is implemented as anexponential decay, controlled by a parameter,k, so that flows decay withexp(-d / k), whered is distance. The algorithm allows for efficientfitting of multiple dispersal models for different coefficients to be fittedwith a single call. Values of the dispersal coefficients,k, may take oneof the following forms:
A single numeric value (> 0), with dispersal along all pathscalculated with that single value. Return object (see below) will then havea single additional column named "flow".
A vector of length equal to the number of
frompoints, withdispersal from each point then calculated using the corresponding value ofk. Return object has single additional "flow" column.A vector of any other length (that is, > 1 yet different to number of
frompoints), in which case different dispersal models will be fitted foreach of thenspecified values, and the resultant return object will havean additional 'n' columns, named 'flow1', 'flow2', ... up to 'n'. Thesecolumns must be subsequently matched by the user back on to thecorresponding 'k' values.A matrix with number of rows equal to the number of
frompoints, andany number of columns. Each column will then specify a distinct dispersalmodel, with different values from each row applied to the correspondingfrompoints. The return value will then be the same as the previousversion, with an additionalncolumns, "flow1" to "flown".
Flows are calculated by default on contracted graphs, via thecontract = TRUE parameter. (These are derived by reducing the input graph down tojunction vertices only, by joining all intermediate edges between eachjunction.) If changes to the input graph do not prompt changes to resultantflows, and the defaultcontract = TRUE is used, it may be thatcalculations are using previously cached versions of the contracted graph.If so, please use eitherclear_dodgr_cache to remove the cachedversion, ordodgr_cache_off prior to initial graph construction toswitch the cache off completely.
Usage
dodgr_flows_disperse( graph, from, dens, k = 500, contract = TRUE, heap = "BHeap", tol = 0.000000000001, quiet = TRUE)Arguments
graph |
|
from | Vector or matrix of pointsfrom which aggregate dispersedflows are to be calculated (see Details) |
dens | Vectors of densities corresponding to the |
k | Width coefficient of exponential diffusion function defined as |
contract | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
tol | Relative tolerance below which dispersal is considered to havefinished. This parameter can generally be ignored; if in doubt, its effectcan be removed by setting |
quiet | If |
Value
Modified version of graph with additionalflow column added.
See Also
Other flows:dodgr_flows_aggregate(),dodgr_flows_si()
Examples
# This is generally needed to explore different values of `k` on same graph:dodgr_cache_off ()graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 10)dens <- rep (1, length (from)) # Uniform densitiesgraph <- dodgr_flows_disperse (graph, from = from, dens = dens)# graph then has an additonal 'flows` column of aggregate flows along all# edges. These flows are directed, and can be aggregated to equivalent# undirected flows on an equivalent undirected graph with:graph_undir <- merge_directed_graph (graph)# Remove `flow` column to avoid warning about over-writing values:graph$flow <- NULL# One dispersal coefficient for each origin point:k <- runif (length (from))graph <- dodgr_flows_disperse (graph, from = from, dens = dens, k = k)grep ("^flow", names (graph), value = TRUE)# single dispersal model; single "flow" column# Multiple models, muliple dispersal coefficients:k <- 1:5graph$flow <- NULLgraph <- dodgr_flows_disperse (graph, from = from, dens = dens, k = k)grep ("^flow", names (graph), value = TRUE)# Rm all flow columns:graph [grep ("^flow", names (graph), value = TRUE)] <- NULL# Multiple models with unique coefficient at each origin point:k <- matrix (runif (length (from) * 5), ncol = 5)dim (k)graph <- dodgr_flows_disperse (graph, from = from, dens = dens, k = k)grep ("^flow", names (graph), value = TRUE)# 5 "flow" columns again, but this time different dispersal coefficients each# each origin point.Aggregate flows throughout a network using a spatial interaction model.
Description
Aggregate flows throughout a network using an exponentialSpatial Interaction (SI) model between a specified set of origin anddestination points, and associated vectors of densities. Spatialinteractions are implemented using an exponential decay, controlled by aparameter,k, so that interactions decay withexp(-d / k), whered isdistance. The algorithm allows for efficient fitting of multiple interactionmodels for different coefficients to be fitted with a single call. Values ofthe interaction coefficients,k, may take one of the following forms:
A single numeric value (> 0), with interactions along all pathscalculated with that single value. Return object (see below) will then havea single additional column named "flow".
A vector of length equal to the number of
frompoints, withinteractions from each point then calculated using the corresponding valueofk. Return object has single additional "flow" column.A vector of any other length (that is, > 1 yet different to number of
frompoints), in which case different interaction models will be fittedfor each of thenspecified values, and the resultant return object willhave an additional 'n' columns, named 'flow1', 'flow2', ... up to 'n'. Thesecolumns must be subsequently matched by the user back on to thecorresponding 'k' values.A matrix with number of rows equal to the number of
frompoints, andany number of columns. Each column will then specify a distinct interactionmodel, with different values from each row applied to the correspondingfrompoints. The return value will then be the same as the previousversion, with an additionalncolumns, "flow1" to "flown".
Flows are calculated by default on contracted graphs, via thecontract = TRUE parameter. (These are derived by reducing the input graph down tojunction vertices only, by joining all intermediate edges between eachjunction.) If changes to the input graph do not prompt changes to resultantflows, and the defaultcontract = TRUE is used, it may be thatcalculations are using previously cached versions of the contracted graph.If so, please use eitherclear_dodgr_cache to remove the cachedversion, ordodgr_cache_off prior to initial graph construction toswitch the cache off completely.
Usage
dodgr_flows_si( graph, from, to, k = 500, dens_from = NULL, dens_to = NULL, contract = TRUE, norm_sums = TRUE, heap = "BHeap", tol = 0.000000000001, quiet = TRUE)Arguments
graph |
|
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
k | Width of exponential spatial interaction function (exp (-d / k)),in units of 'd', specified in one of 3 forms: (i) a single value; (ii) avector of independent values for each origin point (with same length as'from' points); or (iii) an equivalent matrix with each column holding valuesfor each 'from' point, so 'nrow(k)==length(from)'. See Note. |
dens_from | Vector of densities at origin ('from') points |
dens_to | Vector of densities at destination ('to') points |
contract | If |
norm_sums | Standardise sums from all origin points, so sum of flowsthroughout entire network equals sum of densities from all origins (seeNote). |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
tol | Relative tolerance below which flows towards |
quiet | If |
Value
Modified version of graph with additionalflow column added.
Note
Thenorm_sums parameter should be used whenever densities at originsand destinations are absolute values, and ensures that the sum of resultantflow values throughout the entire network equals the sum of densities at allorigins. For example, withnorm_sums = TRUE (the default), a flow from asingle origin with density one to a single destination along two edges willallocate flows of one half to each of those edges, such that the sum of flowsacross the network will equal one, or the sum of densities from all origins.Thenorm_sums = TRUE option is appropriate where densities are relativevalues, and ensures that each edge maintains relative proportions. In theabove example, flows along each of two edges would equal one, for a networksum of two, or greater than the sum of densities.
Withnorm_sums = TRUE, the sum of network flows (sum(output$flow)) shouldequal the sum of origin densities (sum(dens_from)). This may neverthelessnot always be the case, because origin points may simply be too far from anydestination (to) points for an exponential model to yield non-zero valuesanywhere in a network within machine tolerance. Such cases may result in sumsof output flows being less than sums of input densities.
See Also
Other flows:dodgr_flows_aggregate(),dodgr_flows_disperse()
Examples
# This is generally needed to explore different values of `k` on same graph:dodgr_cache_off ()graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 10)to <- sample (graph$from_id, size = 20)dens_from <- runif (length (from))dens_to <- runif (length (to))graph <- dodgr_flows_si ( graph, from = from, to = to, dens_from = dens_from, dens_to = dens_to)# graph then has an additonal 'flows' column of aggregate flows along all# edges. These flows are directed, and can be aggregated to equivalent# undirected flows on an equivalent undirected graph with:graph_undir <- merge_directed_graph (graph)# This graph will only include those edges having non-zero flows, and so:nrow (graph)nrow (graph_undir) # the latter is much smaller# ----- One dispersal coefficient for each origin point:# Remove `flow` column to avoid warning about over-writing values:graph$flow <- NULLk <- runif (length (from))graph <- dodgr_flows_si ( graph, from = from, to = to, dens_from = dens_from, dens_to = dens_to, k = k)grep ("^flow", names (graph), value = TRUE)# single dispersal model; single "flow" column# ----- Multiple models, muliple dispersal coefficients:k <- 1:5graph$flow <- NULLgraph <- dodgr_flows_si ( graph, from = from, to = to, dens_from = dens_from, dens_to = dens_to, k = k)grep ("^flow", names (graph), value = TRUE)# Rm all flow columns:graph [grep ("^flow", names (graph), value = TRUE)] <- NULL# Multiple models with unique coefficient at each origin point:k <- matrix (runif (length (from) * 5), ncol = 5)dim (k)graph <- dodgr_flows_si ( graph, from = from, to = to, dens_from = dens_from, dens_to = dens_to, k = k)grep ("^flow", names (graph), value = TRUE)# 5 "flow" columns again, but this time different dispersal coefficients each# each origin point.Calculate fundamental cycles on a FULL (that is, non-contracted) graph.
Description
Calculate fundamental cycles on a FULL (that is, non-contracted) graph.
Usage
dodgr_full_cycles(graph, graph_max_size = 10000, expand = 0.05)Arguments
graph |
|
graph_max_size | Maximum size submitted to the internal C++ routines asa single chunk. Warning: Increasing this may lead to computer meltdown! |
expand | For large graphs which must be broken into chunks, this factordetermines the relative overlap between chunks to ensure all cycles arecaptured. (This value should only need to be modified in special cases.) |
Value
List of cycle paths, in terms of vertex IDs ingraph and, forspatial graphs, the corresponding coordinates.
Note
This function converts thegraph to its contracted form, calculatesthe fundamental cycles on that version, and then expands these cycles backonto the original graph. This is far more computationally efficient thancalculating fundamental cycles on a full (non-contracted) graph.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
## Not run: net <- weight_streetnet (hampi)graph <- dodgr_contract_graph (net)cyc1 <- dodgr_fundamental_cycles (graph)cyc2 <- dodgr_full_cycles (net)## End(Not run)# cyc2 has same number of cycles, but each one is generally longer, through# including all points intermediate to junctions; cyc1 has cycles composed of# junction points only.Calculate fundamental cycles in a graph.
Description
Calculate fundamental cycles in a graph.
Usage
dodgr_fundamental_cycles( graph, vertices = NULL, graph_max_size = 10000, expand = 0.05)Arguments
graph |
|
vertices |
|
graph_max_size | Maximum size submitted to the internal C++ routines asa single chunk. Warning: Increasing this may lead to computer meltdown! |
expand | For large graphs which must be broken into chunks, this factordetermines the relative overlap between chunks to ensure all cycles arecaptured. (This value should only need to be modified in special cases.) |
Value
List of cycle paths, in terms of vertex IDs ingraph and, forspatial graphs, the corresponding coordinates.
Note
Calculation of fundamental cycles is VERY computationally demanding,and this function should only be executed on CONTRACTED graphs (that is,graphs returned fromdodgr_contract_graph), and even than may take along time to execute. Results for full graphs can be obtained with thefunctiondodgr_full_cycles. The computational complexity can also notbe calculated in advance, and so the parametergraph_max_size will lead tographs larger than that (measured in numbers of edges) being cut into smallerparts. (Note that that is only possible for spatial graphs, meaning that itis not at all possible to apply this function to large, non-spatial graphs.)Each of these smaller parts will be expanded by the specified amount(expand), and cycles found within. The final result is obtained byaggregating all of these cycles and removing any repeated ones arising due tooverlap in the expanded portions. Finally, note that this procedure ofcutting graphs into smaller, computationally manageable sub-graphs providesonly an approximation and may not yield all fundamental cycles.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
net <- weight_streetnet (hampi)graph <- dodgr_contract_graph (net)verts <- dodgr_vertices (graph)cyc <- dodgr_fundamental_cycles (graph, verts)Insert a new node or vertex into a network
Description
Insert a new node or vertex into a network
Usage
dodgr_insert_vertex(graph, v1, v2, x = NULL, y = NULL)Arguments
graph | A flat table of graph edges. Must contain columns labelled |
v1 | Vertex defining start of graph edge along which new vertex is to beinserted |
v2 | Vertex defining end of graph edge along which new vertex is to beinserted (order of |
x | The |
y | The |
Value
A modified graph with specified edge between defined start and endvertices split into two edges either side of new vertex.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)e1 <- sample (nrow (graph), 1)v1 <- graph$from_id [e1]v2 <- graph$to_id [e1]# insert new vertex in the middle of that randomly-selected edge:graph2 <- dodgr_insert_vertex (graph, v1, v2)nrow (graph)nrow (graph2) # new edges added to graph2Calculate isochrone contours from specified points.
Description
Calculates isochrones from inputdata.frame objects(graph), which must minimally contain three columns offrom,to, andt ortime. If an additional column namedt_weight ort_wt ispresent, fastest paths are calculated according to values specified in thatcolumn, while resultant isochrones are calculated from thet ortimecolumn. That is, the paths tracing isochrones from any point will becalculated according to the minimal total sum oft_weight values (ifpresent), while reported isochrones will be total sums oftime values.
Graphs derived from Open Street Map street networks, via theweight_streetnet function, have columns labelledd,d_weighted,time, andtime_weighted. For these inputs, isochrones are always routedusingt_weighted, while final isochrones are sums of values oft - thatis, of un-weighted distances or times - along those paths.
Function is fully vectorized to calculate accept vectors of central pointsand vectors defining multiple isochrones. Calculations use by defaultparallel computation with the maximal number of available cores or threads.This number can be reduced by specifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
Usage
dodgr_isochrones( graph, from = NULL, tlim = NULL, concavity = 0, length_threshold = 0, heap = "BHeap")Arguments
graph |
|
from | Vector or matrix of pointsfrom which isochrones are tobe calculated. |
tlim | Vector of desired limits of isochrones in seconds |
concavity | A value between 0 and 1, with 0 giving (generally smootherbut less detailed) convex iso-contours and 1 giving highly concave (andgenerally more detailed) contours. |
length_threshold | The minimal length of a segment of the iso-contourto be made more convex according to the 'concavity' parameter.. Low valueswill produce highly detailed hulls which may cause problems; if in doubt, orif odd results appear, increase this value. |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
Value
A singledata.frame of isochrones as points sorted anticlockwisearound each origin (from) point, with columns denoting thefrom pointsandtlim value(s). The isochrones are given asid values and associatedcoordinates of the series of points from eachfrom point at the specifiedisochrone times.
Isochrones are calculated by default using parallel computation with themaximal number of available cores or threads. This number can be reduced byspecifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
See Also
Other iso:dodgr_isodists(),dodgr_isoverts()
Examples
## Not run: # Use osmdata package to extract 'SC'-format data:library (osmdata)dat <- opq ("hampi india") %>% add_osm_feature (key = "highway") %>% osmdata_sc ()graph <- weight_streetnet (dat)from <- sample (graph$.vx0, size = 100)tlim <- c (5, 10, 20, 30, 60) * 60 # times in secondsx <- dodgr_isochrones (graph, from = from, tlim)## End(Not run)Calculate isodistance contours from specified points.
Description
Calculates isodistances from inputdata.frame objects(graph), which must minimally contain three columns offrom,to, andd ordist. If an additional column namedweight orwt is present,shortest paths are calculated according to values specified in that column,while resultant isodistances are calculated from thed ordist column.That is, the paths tracing isodistances from any point will be calculatedaccording to the minimal total sum ofweight values (if present), whilereported isodistances will be total sums ofdist values.
Graphs derived from Open Street Map street networks, via theweight_streetnet function, have columns labelledd,d_weighted,time, andtime_weighted. For these inputs, isodistances are alwaysrouted usingd_weighted (ort_weighted for times), while finalisodistances are sums of values ofd (ort for times)- that is, ofun-weighted distances or times - along those paths.
Function is fully vectorized to calculate accept vectors of central pointsand vectors defining multiple isodistances. Calculations use by defaultparallel computation with the maximal number of available cores or threads.This number can be reduced by specifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
Usage
dodgr_isodists( graph, from = NULL, dlim = NULL, concavity = 0, length_threshold = 0, contract = TRUE, heap = "BHeap")Arguments
graph |
|
from | Vector or matrix of pointsfrom which isodistances are tobe calculated. |
dlim | Vector of desired limits of isodistances in metres. |
concavity | A value between 0 and 1, with 0 giving (generally smootherbut less detailed) convex iso-contours and 1 giving highly concave (andgenerally more detailed) contours. |
length_threshold | The minimal length of a segment of the iso-contourto be made more convex according to the 'concavity' parameter.. Low valueswill produce highly detailed hulls which may cause problems; if in doubt, orif odd results appear, increase this value. |
contract | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
Value
A singledata.frame of isodistances as points sorted anticlockwisearound each origin (from) point, with columns denoting thefrom pointsanddlim value(s). The isodistance contours are given asid values andassociated coordinates of the series of points from eachfrom point at thespecified isodistances.
See Also
Other iso:dodgr_isochrones(),dodgr_isoverts()
Examples
graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)dlim <- c (1, 2, 5, 10, 20) * 100d <- dodgr_isodists (graph, from = from, dlim)Calculate isodistance or isochrone vertices from specified points.
Description
Returns lists of all network vertices contained withinisodistance or isochrone contours. Input objects must bedata.frameobjects (graph), which must minimally contain three columns offrom,to, andd ordist. If an additional column namedweight orwt ispresent, iso contours are evaluate via shortest paths calculated accordingto values specified in that column, while resultant values of iso contoursare calculated from thed ordist column. That is, the paths tracing isocontours from any point will be calculated according to the minimal totalsum ofweight values (if present), while reported iso contours will betotal sums ofdist values.
Graphs derived from Open Street Map street networks, via theweight_streetnet function, have columns labelledd,d_weighted,time, andtime_weighted. For these inputs, iso contours are alwaysrouted usingd_weighted (ort_weighted for times), while final isocontours reflect sums of values ofd (ort for times) - that is, ofun-weighted distances or times - along those paths.
Function is fully vectorized to accept vectors of central points and vectorsdefining multiple isochrone or isodistance thresholds. Provide one or moredlim values for isodistances, or one or moretlim values for isochrones.Calculations use by default parallel computation with the maximal number ofavailable cores or threads. This number can be reduced by specifying a valueviaRcppParallel::setThreadOptions (numThreads = <desired_number>).
Usage
dodgr_isoverts(graph, from = NULL, dlim = NULL, tlim = NULL, heap = "BHeap")Arguments
graph |
|
from | Vector or matrix of pointsfrom which isodistances orisochrones are to be calculated. |
dlim | Vector of desired limits of isodistances in metres. |
tlim | Vector of desired limits of isochrones in seconds |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
Value
A singledata.frame of vertex IDs, with columns denoting thefrompoints andtlim value(s). The isochrones are given asid values andassociated coordinates of the series of points from eachfrom point at thespecified isochrone times.
Isoverts are calculated by default using parallel computation with themaximal number of available cores or threads. This number can be reduced byspecifying a value viaRcppParallel::setThreadOptions (numThreads = <desired_number>).
See Also
Other iso:dodgr_isochrones(),dodgr_isodists()
Examples
## Not run: # Use osmdata package to extract 'SC'-format data:library (osmdata)dat <- opq ("hampi india") %>% add_osm_feature (key = "highway") %>% osmdata_sc ()graph <- weight_streetnet (dat)from <- sample (graph$.vx0, size = 100)tlim <- c (5, 10, 20, 30, 60) * 60 # times in secondsx <- dodgr_isoverts (graph, from = from, tlim)## End(Not run)Load a street network previously saved withdodgr_save_streetnet.
Description
This always returns the full, non-contracted graph. The contracted graph canbe generated by passing the result tododgr_contract_graph.
Usage
dodgr_load_streetnet(filename)Arguments
filename | Name (with optional full path) of file to be loaded. |
Value
The loaded street network.
See Also
Other cache:clear_dodgr_cache(),dodgr_cache_off(),dodgr_cache_on(),dodgr_save_streetnet()
Examples
net <- weight_streetnet (hampi)f <- file.path (tempdir (), "streetnet.Rds")dodgr_save_streetnet (net, f)clear_dodgr_cache () # rm cached objects from tempdir# at some later time, or in a new R session:net <- dodgr_load_streetnet (f)Calculate lists of pair-wise shortest paths between points.
Description
Calculate lists of pair-wise shortest paths between points.
Usage
dodgr_paths( graph, from, to, vertices = TRUE, pairwise = FALSE, heap = "BHeap", quiet = TRUE)Arguments
graph |
|
from | Vector or matrix of pointsfrom which route paths are tobe calculated (see Details) |
to | Vector or matrix of pointsto which route paths are to becalculated (see Details) |
vertices | If |
pairwise | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
quiet | If |
Value
List of list of paths tracing all connections between nodes such thatifx <- dodgr_paths (graph, from, to), then the path betweenfrom[i] andto[j] isx [[i]] [[j]]. Each individual path is then avector of integers indexing into the rows ofgraph ifvertices = FALSE,or into the rows ofdodgr_vertices (graph) ifvertices = TRUE.
Note
graph must minimally contain four columns offrom,to,dist. If an additional column namedweight orwt is present, shortest paths are calculated according to valuesspecified in that column; otherwise according todist values. Eitherway, final distances betweenfrom andto points are calculatedaccording to values ofdist. That is, paths between any pair of pointswill be calculated according to the minimal total sum ofweightvalues (if present), while reported distances will be total sums ofdist values.
Thefrom andto columns ofgraph may be either singlecolumns of numeric or character values specifying the numbers or names ofgraph vertices, or combinations to two columns specifying geographical(longitude and latitude) coordinates. In the latter case, almost any sensiblecombination of names will be accepted (for example,fromx, fromy,from_x, from_y, orfr_lat, fr_lon.)
from andto values can be either two-column matrices ofequivalent of longitude and latitude coordinates, or else single columnsprecisely matching node numbers or names given ingraph$from orgraph$to. Ifto is missing, pairwise distances are calculatedbetween all points specified infrom. If neitherfrom norto are specified, pairwise distances are calculated between all nodesingraph.
See Also
Other distances:dodgr_distances(),dodgr_dists(),dodgr_dists_categorical(),dodgr_dists_nearest(),dodgr_times()
Examples
graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)to <- sample (graph$to_id, size = 50)dp <- dodgr_paths (graph, from = from, to = to)# dp is a list with 100 items, and each of those 100 items has 30 items, each# of which is a single path listing all vertiex IDs as taken from `graph`.# it is also possible to calculate paths between pairwise start and end# pointsfrom <- sample (graph$from_id, size = 5)to <- sample (graph$to_id, size = 5)dp <- dodgr_paths (graph, from = from, to = to, pairwise = TRUE)# dp is a list of 5 items, each of which just has a single path between each# pairwise from and to point.Sample a random but connected sub-component of a graph
Description
Sample a random but connected sub-component of a graph
Usage
dodgr_sample(graph, nverts = 1000)Arguments
graph | A flat table of graph edges. Must contain columns labelled |
nverts | Number of vertices to sample |
Value
A connected sub-component ofgraph
Note
Graphs may occasionally havenverts + 1 vertices, rather thanthe requestednverts.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)nrow (graph) # 5,742graph <- dodgr_sample (graph, nverts = 200)nrow (graph) # generally around 400 edgesnrow (dodgr_vertices (graph)) # 200Save a weighted streetnet to a local file
Description
Theweight_streetnet function returns a singledata.frame object,the processing of which also relies on a couple of cached lookup-tables tomatch edges in thedata.frame to objects in the original input data. Itautomatically calculates and caches a contracted version of the same graph,to enable rapid conversion between contracted and uncontracted forms. Thisfunction saves all of these items in a single.Rds file, so that a theresult of aweight_streetnet call can be rapidly loaded into aworkspace in subsequent sessions, rather than re-calculating the entireweighted network.
Usage
dodgr_save_streetnet(net, filename = NULL)Arguments
net |
|
filename | Name with optional full path of file in which to save theinput |
Value
Nothing; function called for side-effect of saving network.
Note
This may take some time ifdodgr_cache_off has been called.The contracted version of the graph is also saved, and so must be calculatedif it has not previously been automatically cached.
See Also
Other cache:clear_dodgr_cache(),dodgr_cache_off(),dodgr_cache_on(),dodgr_load_streetnet()
Examples
net <- weight_streetnet (hampi)f <- file.path (tempdir (), "streetnet.Rds")dodgr_save_streetnet (net, f)clear_dodgr_cache () # rm cached objects from tempdir# at some later time, or in a new R session:net <- dodgr_load_streetnet (f)ConvertsfLINESTRING objects toPOLYGON objects representing allfundamental cycles within theLINESTRING objects.
Description
ConvertsfLINESTRING objects toPOLYGON objects representing allfundamental cycles within theLINESTRING objects.
Usage
dodgr_sflines_to_poly(sflines, graph_max_size = 10000, expand = 0.05)Arguments
sflines | Ansf |
graph_max_size | Maximum size submitted to the internal C++ routines asa single chunk. Warning: Increasing this may lead to computer meltdown! |
expand | For large graphs which must be broken into chunks, this factordetermines the relative overlap between chunks to ensure all cycles arecaptured. (This value should only need to be modified in special cases.) |
Value
Ansf::sfc collection ofPOLYGON objects.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
## Not run: p <- dodgr_sflines_to_poly (hampi)## End(Not run)Extract a street network insf-format for a given location.
Description
Use theosmdata package to extract the street network for a givenlocation. For routing between a given set of points (passed aspts),thebbox argument may be omitted, in which case a bounding box willbe constructed by expanding the range ofpts by the relative amount ofexpand.
Usage
dodgr_streetnet(bbox, pts = NULL, expand = 0.05, quiet = TRUE)Arguments
bbox | Bounding box as vector or matrix of coordinates, or locationname. Passed to |
pts | List of points presumably containing spatial coordinates |
expand | Relative factor by which street network should extend beyondlimits defined by pts (only if |
quiet | If |
Value
A Simple Features (sf) object with coordinates of all lines inthe street network.
Note
Calls to this function may return "General overpass server error" witha note that "Query timed out." The overpass served used to access the datahas a sophisticated queueing system which prioritises requests that arelikely to require little time. These timeout errors can thus generallynotbe circumvented by changing "timeout" options on the HTTP requests, andshould rather be interpreted to indicate that a request is too large, and mayneed to be refined, or somehow broken up into smaller queries.
See Also
Other extraction:dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway(),weight_streetnet()
Examples
## Not run: streetnet <- dodgr_streetnet ("hampi india", expand = 0)# convert to form needed for `dodgr` functions:graph <- weight_streetnet (streetnet)nrow (graph) # around 5,900 edges# Alternative ways of extracting street networks by using a small selection# of graph vertices to define bounding box:verts <- dodgr_vertices (graph)verts <- verts [sample (nrow (verts), size = 200), ]streetnet <- dodgr_streetnet (pts = verts, expand = 0)graph <- weight_streetnet (streetnet)nrow (graph)# This will generally have many more rows because most street networks# include streets that extend considerably beyond the specified bounding box.# bbox can also be a polygon:bb <- osmdata::getbb ("gent belgium") # rectangular bboxnrow (dodgr_streetnet (bbox = bb)) # around 30,000bb <- osmdata::getbb ("gent belgium", format_out = "polygon")nrow (dodgr_streetnet (bbox = bb)) # around 17,000# The latter has fewer rows because only edges within polygon are returned# Example with access restrictionsbbox <- c (-122.2935, 47.62663, -122.28, 47.63289)x <- dodgr_streetnet_sc (bbox)net <- weight_streetnet (x, keep_cols = "access", turn_penalty = TRUE)# has many streets with "access" = "private"; these can be removed like this:net2 <- net [which (!net$access != "private"), ]# or modified in some other way such as strongly penalizing use of those# streets:index <- which (net$access == "private")net$time_weighted [index] <- net$time_weighted [index] * 100## End(Not run)Forceweight_streetnet to use geodesic distances.
Description
Distances by default are Mapbox "cheap" distances if maximal networkdistances are < 100km, otherwise Haversine distances. Calling this functionforces all calls toweight_streetnet from that point on to usegeodesic distances. These are more computationally expensive to calculate,and weighting networks will likely take more time.
Usage
dodgr_streetnet_geodesic(unset = FALSE)Arguments
unset | Calling this function with |
Value
Nothing; the function is called for its side-effect only of settingdistance calculations to geodesic.
See Also
Other extraction:dodgr_streetnet(),dodgr_streetnet_sc(),weight_railway(),weight_streetnet()
Examples
net0 <- weight_streetnet (hampi) # Default "cheap" methoddodgr_streetnet_geodesic ()net1 <- weight_streetnet (hampi)cor (net0$d, net1$d) # Strongly correlated, but not perfectmax (abs (net0$d - net1$d)) # in metresExtract a street network insilicate-format for a given location.
Description
Use theosmdata package to extract the street network for a givenlocation and return it inSC-format. For routing between a given set ofpoints (passed aspts), thebbox argument may be omitted, in which case abounding box will be constructed by expanding the range ofpts by therelative amount ofexpand.
Usage
dodgr_streetnet_sc(bbox, pts = NULL, expand = 0.05, quiet = TRUE)Arguments
bbox | Bounding box as vector or matrix of coordinates, or locationname. Passed to |
pts | List of points presumably containing spatial coordinates |
expand | Relative factor by which street network should extend beyondlimits defined by pts (only if |
quiet | If |
Value
A Simple Features (sf) object with coordinates of all lines inthe street network.
Note
Calls to this function may return "General overpass server error" witha note that "Query timed out." The overpass served used to access the datahas a sophisticated queueing system which prioritises requests that arelikely to require little time. These timeout errors can thus generallynotbe circumvented by changing "timeout" options on the HTTP requests, andshould rather be interpreted to indicate that a request is too large, and mayneed to be refined, or somehow broken up into smaller queries.
See Also
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),weight_railway(),weight_streetnet()
Examples
## Not run: streetnet <- dodgr_streetnet ("hampi india", expand = 0)# convert to form needed for `dodgr` functions:graph <- weight_streetnet (streetnet)nrow (graph) # around 5,900 edges# Alternative ways of extracting street networks by using a small selection# of graph vertices to define bounding box:verts <- dodgr_vertices (graph)verts <- verts [sample (nrow (verts), size = 200), ]streetnet <- dodgr_streetnet (pts = verts, expand = 0)graph <- weight_streetnet (streetnet)nrow (graph)# This will generally have many more rows because most street networks# include streets that extend considerably beyond the specified bounding box.# bbox can also be a polygon:bb <- osmdata::getbb ("gent belgium") # rectangular bboxnrow (dodgr_streetnet (bbox = bb)) # around 30,000bb <- osmdata::getbb ("gent belgium", format_out = "polygon")nrow (dodgr_streetnet (bbox = bb)) # around 17,000# The latter has fewer rows because only edges within polygon are returned# Example with access restrictionsbbox <- c (-122.2935, 47.62663, -122.28, 47.63289)x <- dodgr_streetnet_sc (bbox)net <- weight_streetnet (x, keep_cols = "access", turn_penalty = TRUE)# has many streets with "access" = "private"; these can be removed like this:net2 <- net [which (!net$access != "private"), ]# or modified in some other way such as strongly penalizing use of those# streets:index <- which (net$access == "private")net$time_weighted [index] <- net$time_weighted [index] * 100## End(Not run)Calculate matrix of pair-wise travel times between points.
Description
Calculates distances from inputdata.frame objects (graph),which must minimally contain three columns offrom,to, andd ordist. If an additional column namedweight orwt is present, shortestpaths are calculated according to values specified in that column, whiledistances returned are calculated from thed ordist column. That is,paths between any pair of points will be calculated according to the minimaltotal sum ofweight values (if present), while reported distances will betotal sums ofdist values.
Graphs derived from Open Street Map street networks, via theweight_streetnet function, have columns labelledd,d_weighted,time, andtime_weighted. For these inputs, paths between origin anddestination points are always routed usingd_weighted (ort_weighted fortimes), while final distances are sums of values ofd (ort for times)-that is, of un-weighted distances or times - along those paths.
The function is parallelized for efficient computation of distances betweenmultiple origin and destination points, as described in thefrom parameterbelow.
Usage
dodgr_times(graph, from = NULL, to = NULL, shortest = FALSE, heap = "BHeap")Arguments
graph |
The Note that longitude and latitude values are always interpreted in 'dodgr' tobe in EPSG:4326 / WSG84 coordinates. Any other kinds of coordinates shouldfirst be reprojected to EPSG:4326 before submitting to any 'dodgr' routines. See further information in Details. |
from | Vector or matrix of pointsfrom which route distances are tobe calculated, specified as one of the following:
|
to | Vector or matrix of pointsto which route distances are to becalculated. If |
shortest | If |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; |
Value
square matrix of distances between nodes
See Also
Other distances:dodgr_distances(),dodgr_dists(),dodgr_dists_categorical(),dodgr_dists_nearest(),dodgr_paths()
Examples
# A simple graphgraph <- data.frame ( from = c ("A", "B", "B", "B", "C", "C", "D", "D"), to = c ("B", "A", "C", "D", "B", "D", "C", "A"), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph)# Example of "from" and "to" as integer-ish values, in which case they are# interpreted to index into "dodgr_vertices()":graph <- data.frame ( from = c (1, 3, 2, 2, 3, 3, 4, 4), to = c (2, 1, 3, 4, 2, 4, 3, 1), d = c (1, 2, 1, 3, 2, 1, 2, 1))dodgr_dists (graph, from = 1, to = 2)# That then gives distance from "1" to "3" because the vertices are built# sequentially along "graph$from":dodgr_vertices (graph)# And vertex$id [2] is "3"# A larger example from the included [hampi()] data.graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 100)to <- sample (graph$to_id, size = 50)d <- dodgr_dists (graph, from = from, to = to)# d is a 100-by-50 matrix of distances between `from` and `to`## Not run: # a more complex street network example, thanks to @chrijo; see# https://github.com/UrbanAnalyst/dodgr/issues/47xy <- rbind ( c (7.005994, 51.45774), # limbeckerplatz 1 essen germany c (7.012874, 51.45041)) # hauptbahnhof essen germanyxy <- data.frame (lon = xy [, 1], lat = xy [, 2])essen <- dodgr_streetnet (pts = xy, expand = 0.2, quiet = FALSE)graph <- weight_streetnet (essen, wt_profile = "foot")d <- dodgr_dists (graph, from = xy, to = xy)# First reason why this does not work is because the graph has multiple,# disconnected components.table (graph$component)# reduce to largest connected component, which is always number 1graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)# should work, but even then note thattable (essen$level)# There are parts of the network on different building levels (because of# shopping malls and the like). These may or may not be connected, so it may# be necessary to filter out particular levelsindex <- which (!(essen$level == "-1" | essen$level == "1")) # for examplelibrary (sf) # needed for following sub-select operationessen <- essen [index, ]graph <- weight_streetnet (essen, wt_profile = "foot")graph <- graph [which (graph$component == 1), ]d <- dodgr_dists (graph, from = xy, to = xy)## End(Not run)Convert adodgr graph to anigraph.
Description
Convert adodgr graph to anigraph.
Usage
dodgr_to_igraph(graph, weight_column = "d")Arguments
graph | A |
weight_column | The column of the |
Value
Theigraph equivalent of the input. Note that this willnotbe a dual-weighted graph.
See Also
Other conversion:dodgr_deduplicate_graph(),dodgr_to_sf(),dodgr_to_sfc(),dodgr_to_tidygraph(),igraph_to_dodgr()
Examples
graph <- weight_streetnet (hampi)graphi <- dodgr_to_igraph (graph)Convert adodgr graph into an equivalentsf object.
Description
Works by aggregating edges intoLINESTRING objects representing longestsequences between all junction nodes. The resultant objects will generallycontain moreLINESTRING objects than the originalsf object, becausethe former will be bisected at every junction point.
Usage
dodgr_to_sf(graph)Arguments
graph | A |
Value
Equivalent object of classsf.
Note
Requires thesf package to be installed.
See Also
Other conversion:dodgr_deduplicate_graph(),dodgr_to_igraph(),dodgr_to_sfc(),dodgr_to_tidygraph(),igraph_to_dodgr()
Examples
hw <- weight_streetnet (hampi)nrow (hw) # 5,729 edgesxy <- dodgr_to_sf (hw)dim (xy) # 764 edges; 14 attributesConvert adodgr graph into an equivalentsf::sfc object.
Description
Convert adodgr graph into alist composed oftwo objects:dat, adata.frame; andgeometry, ansfc object from the (sf) package.Works by aggregating edges intoLINESTRINGobjects representing longest sequences between all junction nodes. Theresultant objects will generally contain moreLINESTRING objects thanthe originalsf object, because the former will be bisected at everyjunction point.
Usage
dodgr_to_sfc(graph)Arguments
graph | A |
Value
A list containing (1) Adata.frame of data associated with thesf geometries; and (ii) A Simple Features Collection (sfc) list ofLINESTRING objects.
Note
The output of this function corresponds to the edges obtained fromdodgr_contract_graph. This function does not require thesf packageto be installed; the corresponding function that creates a fullsfobject -dodgr_to_sf does requiressf to be installed.
See Also
Other conversion:dodgr_deduplicate_graph(),dodgr_to_igraph(),dodgr_to_sf(),dodgr_to_tidygraph(),igraph_to_dodgr()
Examples
hw <- weight_streetnet (hampi)nrow (hw)xy <- dodgr_to_sfc (hw)dim (hw) # 5.845 edgeslength (xy$geometry) # more linestrings aggregated from those edgesnrow (hampi) # than the 191 linestrings in original sf objectdim (xy$dat) # same number of rows as there are geometries# The dodgr_to_sf function then just implements this final conversion:# sf::st_sf (xy$dat, geometry = xy$geometry, crs = 4326)Convert adodgr graph to antidygraph.
Description
Convert adodgr graph to antidygraph.
Usage
dodgr_to_tidygraph(graph)Arguments
graph | A |
Value
Thetidygraph equivalent of the input
See Also
Other conversion:dodgr_deduplicate_graph(),dodgr_to_igraph(),dodgr_to_sf(),dodgr_to_sfc(),igraph_to_dodgr()
Examples
graph <- weight_streetnet (hampi)grapht <- dodgr_to_tidygraph (graph)Re-expand a contracted graph.
Description
Revert a contracted graph created withdodgr_contract_graph back toa full, uncontracted version. This function is mostly used for the sideeffect of mapping any new columns inserted on to the contracted graph backon to the original graph, as demonstrated in the example.
Usage
dodgr_uncontract_graph(graph)Arguments
graph | A contracted graph created fromdodgr_contract_graph. |
Details
Note that this function will generallynot recover original graphssubmitted tododgr_contract_graph. Specifically, the sequencedodgr_contract_graph(graph) |> dodgr_uncontract_graph() will generallyproduce a graph with fewer edges than the original. This is because graphsmay have multiple paths between a given pair of points. Contraction willreduce these to the single path with the shortest weighted distance (ortime), and uncontraction will restore only that single edge with shortestweighted distance, and not any original edges which may have had longerweighted distances.
Value
A singledata.frame representing the equivalent original,uncontracted graph.
See Also
Other modification:dodgr_components(),dodgr_contract_graph()
Examples
graph0 <- weight_streetnet (hampi)nrow (graph0) # 6,813graph1 <- dodgr_contract_graph (graph0)nrow (graph1) # 760graph2 <- dodgr_uncontract_graph (graph1)nrow (graph2) # 6,813# Insert new data on to the contracted graph and uncontract it:graph1$new_col <- runif (nrow (graph1))graph3 <- dodgr_uncontract_graph (graph1)# graph3 is then the uncontracted graph which includes "new_col" as welldim (graph0)dim (graph3)Extract vertices of graph, including spatial coordinates if included.
Description
Extract vertices of graph, including spatial coordinates if included.
Usage
dodgr_vertices(graph)Arguments
graph | A flat table of graph edges. Must contain columns labelled |
Value
Adata.frame of vertices with unique numbers (n).
Note
Values ofn are 0-indexed
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),merge_directed_graph(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)v <- dodgr_vertices (graph)Estimate a value for the 'dist_threshold' parameter of thedodgr_centrality function.
Description
Providing distance thresholds to thisfunction generally provides considerably speed gains, and results inapproximations of centrality. This function enables the determination ofvalues of 'dist_threshold' corresponding to specific degrees of accuracy.
Usage
estimate_centrality_threshold(graph, tolerance = 0.001)Arguments
graph | 'data.frame' or equivalent object representing the networkgraph (see Details) |
tolerance | Desired maximal degree of inaccuracy in centrality estimates
|
Value
A single value for 'dist_threshold' giving the required tolerance.
Note
This function may take some time to execute. While running, it displaysongoing information on screen of estimated values of 'dist_threshold' andassociated errors. Thresholds are progressively increased until the error isreduced below the specified tolerance.
See Also
Other centrality:dodgr_centrality(),estimate_centrality_time()
Examples
# No threshold estimation possible on this small example graph:graph <- weight_streetnet (hampi, wt_profile = "foot")estimate_centrality_threshold (graph)Estimate time required for a planned centrality calculation.
Description
The 'dodgr' centrality functions are designed to be applied to potentiallyvery large graphs, and may take considerable time to execute. This helperfunction estimates how long a centrality function may take for a given graphand given value of 'dist_threshold' estimated via theestimate_centrality_threshold function.
Usage
estimate_centrality_time( graph, contract = TRUE, edges = TRUE, dist_threshold = NULL, heap = "BHeap")Arguments
graph | 'data.frame' or equivalent object representing the networkgraph (see Details) |
contract | If 'TRUE', centrality is calculated on contracted graphbefore mapping back on to the original full graph. Note that for streetnetworks, in particular those obtained from theosmdata package, vertexplacement is effectively arbitrary except at junctions; centrality for suchgraphs should only be calculated between the latter points, and thus'contract' should always be 'TRUE'. |
edges | If 'TRUE', centrality is calculated for graph edges, returningthe input 'graph' with an additional 'centrality' column; otherwisecentrality is calculated for vertices, returning the equivalent of'dodgr_vertices(graph)', with an additional vertex-based 'centrality' column. |
dist_threshold | If not 'NULL', only calculate centrality for each pointout to specified threshold. Setting values for this will result inapproximate estimates for centrality, yet with considerable gains incomputational efficiency. For sufficiently large values, approximations willbe accurate to within some constant multiplier. Appropriate values can beestablished via theestimate_centrality_threshold function. |
heap | Type of heap to use in priority queue. Options includeFibonacci Heap (default; 'FHeap'), Binary Heap ('BHeap'),Trinomial Heap ('TriHeap'), Extended Trinomial Heap('TriHeapExt', and 2-3 Heap ('Heap23'). |
Value
An estimated calculation time for calculating centrality for thegiven value of 'dist_threshold'
Note
This function may take some time to execute. While running, it displaysongoing information on screen of estimated values of 'dist_threshold' andassociated errors. Thresholds are progressively increased until the error isreduced below the specified tolerance.
See Also
Other centrality:dodgr_centrality(),estimate_centrality_threshold()
Examples
graph <- weight_streetnet (hampi, wt_profile = "foot")estimate_centrality_time (graph)Sample street network from Hampi, India.
Description
A sample street network from the township of Hampi, Karnataka, India.
Format
A Simple Featuressfdata.frame containing the streetnetwork of Hampi.
Note
Can be re-created with the following command, which also removesextraneous columns to reduce size:
See Also
Other data:os_roads_bristol,weighting_profiles
Examples
## Not run: hampi <- dodgr_streetnet ("hampi india")cols <- c ("osm_id", "highway", "oneway", "geometry")hampi <- hampi [, which (names (hampi) %in% cols)]## End(Not run)# this 'sf data.frame' can be converted to a 'dodgr' network withnet <- weight_streetnet (hampi, wt_profile = "foot")Convert aigraph network to an equivalentdodgr representation.
Description
Convert aigraph network to an equivalentdodgr representation.
Usage
igraph_to_dodgr(graph)Arguments
graph | Anigraph network |
Value
Thedodgr equivalent of the input.
See Also
Other conversion:dodgr_deduplicate_graph(),dodgr_to_igraph(),dodgr_to_sf(),dodgr_to_sfc(),dodgr_to_tidygraph()
Examples
graph <- weight_streetnet (hampi)graphi <- dodgr_to_igraph (graph)graph2 <- igraph_to_dodgr (graphi)identical (graph2, graph) # FALSEAlias formatch_pts_to_graph
Description
Match spatial points to the edges of a spatial graph, through finding theedge with the closest perpendicular intersection. NOTE: Intersections arecalculated geometrically, and presume planar geometry. It is up to users ofprojected geometrical data, such as those within adodgr_streetnet object,to ensure that either: (i) Data span an sufficiently small area that errorsfrom presuming planar geometry may be ignored; or (ii) Data are re-projectedto an equivalent planar geometry prior to calling this routine.
Usage
match_points_to_graph(graph, xy, connected = FALSE, distances = FALSE)Arguments
graph | A |
xy | coordinates of points to be matched to the vertices, either asmatrix orsf-formatted |
connected | Should points be matched to the same (largest) connectedcomponent of graph? If |
distances | If |
Value
Fordistances = FALSE (default), a vector index matching thexycoordinates to nearest edges. For bi-directional edges, only one match isreturned, and it is up to the user to identify and suitably process matchingedge pairs. For 'distances = TRUE', a 'data.frame' of four columns:
"index" The index of closest edges in "graph", as described above.
"d_signed" The perpendicular distance from ech point to the nearestedge, with negative distances denoting points to the left of edges, andpositive distances denoting points to the right. Distances of zero denotepoints lying precisely on the line of an edge (potentially including caseswhere nearest point of bisection lies beyond the actual edge).
"x" The x-coordinate of the point of intersection.
"y" The y-coordinate of the point of intersection.
See Also
Other match:add_nodes_to_graph(),match_points_to_verts(),match_pts_to_graph(),match_pts_to_verts()
Examples
graph <- weight_streetnet (hampi, wt_profile = "foot")# Then generate some random points to match to graphverts <- dodgr_vertices (graph)npts <- 10xy <- data.frame ( x = min (verts$x) + runif (npts) * diff (range (verts$x)), y = min (verts$y) + runif (npts) * diff (range (verts$y)))edges <- match_pts_to_graph (graph, xy)graph [edges, ] # The edges of the graph closest to `xy`Alias formatch_pts_to_verts
Description
Thematch_pts_to_graph function matches points to the nearest edgebased on geometric intersections; this function only matches to the nearestvertex based on point-to-point distances.
Usage
match_points_to_verts(verts, xy, connected = FALSE)Arguments
verts | A |
xy | coordinates of points to be matched to the vertices, either asmatrix orsf-formatted |
connected | Should points be matched to the same (largest) connectedcomponent of graph? If |
Value
A vector index into verts
See Also
Other match:add_nodes_to_graph(),match_points_to_graph(),match_pts_to_graph(),match_pts_to_verts()
Examples
net <- weight_streetnet (hampi, wt_profile = "foot")verts <- dodgr_vertices (net)# Then generate some random points to match to graphnpts <- 10xy <- data.frame ( x = min (verts$x) + runif (npts) * diff (range (verts$x)), y = min (verts$y) + runif (npts) * diff (range (verts$y)))pts <- match_pts_to_verts (verts, xy)pts # an index into vertspts <- verts$id [pts]pts # names of those verticesMatch spatial points to the edges of a spatial graph.
Description
Match spatial points to the edges of a spatial graph, through finding theedge with the closest perpendicular intersection. NOTE: Intersections arecalculated geometrically, and presume planar geometry. It is up to users ofprojected geometrical data, such as those within adodgr_streetnet object,to ensure that either: (i) Data span an sufficiently small area that errorsfrom presuming planar geometry may be ignored; or (ii) Data are re-projectedto an equivalent planar geometry prior to calling this routine.
Usage
match_pts_to_graph(graph, xy, connected = FALSE, distances = FALSE)Arguments
graph | A |
xy | coordinates of points to be matched to the vertices, either asmatrix orsf-formatted |
connected | Should points be matched to the same (largest) connectedcomponent of graph? If |
distances | If |
Value
Fordistances = FALSE (default), a vector index matching thexycoordinates to nearest edges. For bi-directional edges, only one match isreturned, and it is up to the user to identify and suitably process matchingedge pairs. For 'distances = TRUE', a 'data.frame' of four columns:
"index" The index of closest edges in "graph", as described above.
"d_signed" The perpendicular distance from ech point to the nearestedge, with negative distances denoting points to the left of edges, andpositive distances denoting points to the right. Distances of zero denotepoints lying precisely on the line of an edge (potentially including caseswhere nearest point of bisection lies beyond the actual edge).
"x" The x-coordinate of the point of intersection.
"y" The y-coordinate of the point of intersection.
See Also
Other match:add_nodes_to_graph(),match_points_to_graph(),match_points_to_verts(),match_pts_to_verts()
Examples
graph <- weight_streetnet (hampi, wt_profile = "foot")# Then generate some random points to match to graphverts <- dodgr_vertices (graph)npts <- 10xy <- data.frame ( x = min (verts$x) + runif (npts) * diff (range (verts$x)), y = min (verts$y) + runif (npts) * diff (range (verts$y)))edges <- match_pts_to_graph (graph, xy)graph [edges, ] # The edges of the graph closest to `xy`Match spatial points to the vertices of a spatial graph.
Description
Thematch_pts_to_graph function matches points to the nearest edgebased on geometric intersections; this function only matches to the nearestvertex based on point-to-point distances.
Usage
match_pts_to_verts(verts, xy, connected = FALSE)Arguments
verts | A |
xy | coordinates of points to be matched to the vertices, either asmatrix orsf-formatted |
connected | Should points be matched to the same (largest) connectedcomponent of graph? If |
Value
A vector index into verts
See Also
Other match:add_nodes_to_graph(),match_points_to_graph(),match_points_to_verts(),match_pts_to_graph()
Examples
net <- weight_streetnet (hampi, wt_profile = "foot")verts <- dodgr_vertices (net)# Then generate some random points to match to graphnpts <- 10xy <- data.frame ( x = min (verts$x) + runif (npts) * diff (range (verts$x)), y = min (verts$y) + runif (npts) * diff (range (verts$y)))pts <- match_pts_to_verts (verts, xy)pts # an index into vertspts <- verts$id [pts]pts # names of those verticesMerge directed edges into equivalent undirected edges.
Description
Merge directed edges into equivalent undirected values by aggregating acrossdirections. This function is primarily intended to aid visualisation ofdirected graphs, particularly visualising the results of thedodgr_flows_aggregate anddodgr_flows_disperse functions, whichreturn columns of aggregated flows directed along each edge of a graph.
Usage
merge_directed_graph(graph, col_names = c("flow"))Arguments
graph | A undirected graph in which directed edges of the input graphhave been merged through aggregation to yield a single, undirected edgebetween each pair of vertices. |
col_names | Names of columns to be merged through aggregation. Valuesfor these columns in resultant undirected graph will be aggregated fromdirected values. |
Value
An equivalent graph in which all directed edges have been reduced tosingle, undirected edges, and all values of the specified column(s) have beenaggregated across directions to undirected values.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),summary.dodgr_dists_categorical(),write_dodgr_wt_profile()
Examples
graph <- weight_streetnet (hampi)from <- sample (graph$from_id, size = 10)to <- sample (graph$to_id, size = 5)to <- to [!to %in% from]flows <- matrix (10 * runif (length (from) * length (to)), nrow = length (from))graph <- dodgr_flows_aggregate (graph, from = from, to = to, flows = flows)# graph then has an additonal 'flows` column of aggregate flows along all# edges. These flows are directed, and can be aggregated to equivalent# undirected flows on an equivalent undirected graph with:graph_undir <- merge_directed_graph (graph)# This graph will only include those edges having non-zero flows, and so:nrow (graph)nrow (graph_undir) # the latter is much smallerSample street network from Bristol, U.K.
Description
A sample street network for Bristol, U.K., from the Ordnance Survey.
Format
A Simple Featuressfdata.frame representingmotorways in Bristol, UK.
Note
Input data downloaded fromhttps://osdatahub.os.uk/downloads/open,To download the data from that page click on the tick box next to'OS Open Roads', scroll to the bottom, click 'Continue' and completethe form on the subsequent page.This dataset is open access and can be used underthese licensingconditions,and must be cited as follows:Contains OS data © Crown copyright and database right (2017)
See Also
Other data:hampi,weighting_profiles
Examples
## Not run: library (sf)library (dplyr)# data must be unzipped here# os_roads <- sf::read_sf("~/data/ST_RoadLink.shp")# u <- paste0 (# "https://opendata.arcgis.com/datasets/",# "686603e943f948acaa13fb5d2b0f1275_4.kml"# )# lads <- sf::read_sf(u)# mapview::mapview(lads)# bristol_pol <- dplyr::filter(lads, grepl("Bristol", lad16nm))# os_roads <- st_transform(os_roads, st_crs(lads)# os_roads_bristol <- os_roads[bristol_pol, ] %>%# dplyr::filter(class == "Motorway" &# roadNumber != "M32") %>%# st_zm(drop = TRUE)# mapview::mapview(os_roads_bristol)## End(Not run)# Converting this 'sf data.frame' to a 'dodgr' network requires manual# specification of weighting profile:colnm <- "formOfWay" # name of column used to determine weightswts <- data.frame ( name = "custom", way = unique (os_roads_bristol [[colnm]]), value = c (0.1, 0.2, 0.8, 1))net <- weight_streetnet ( os_roads_bristol, wt_profile = wts, type_col = colnm, id_col = "identifier")# 'id_col' tells the function which column to use to attribute IDs of waysTransform a result fromdodgr_dists_categorical to summary statistics
Description
Transform a result fromdodgr_dists_categorical to summary statistics
Usage
## S3 method for class 'dodgr_dists_categorical'summary(object, ...)Arguments
object | A 'dodgr_dists_categorical' object |
... | Extra parameters currently not used |
Value
The summary statistics (invisibly)
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),write_dodgr_wt_profile()
Examples
# Prepare a graph for categorical routing by including an "edge_type" columngraph <- weight_streetnet (hampi, wt_profile = "foot")graph <- graph [graph$component == 1, ]graph$edge_type <- graph$highway# Define start and end points for categorical distances; using all vertices# here.length (unique (graph$edge_type)) # Number of categoriesv <- dodgr_vertices (graph)from <- to <- v$id [1:100]d <- dodgr_dists_categorical (graph, from, to)# Internal 'summary' method to summarise results:summary (d)Weight a network for routing along railways.
Description
Weight (or re-weight) ansf-formatted OSM street network for routingalong railways.
Usage
weight_railway( x, type_col = "railway", id_col = "osm_id", keep_cols = c("maxspeed"), excluded = c("abandoned", "disused", "proposed", "razed"))Arguments
x | A street network represented either as |
type_col | Specify column of the |
id_col | Specify column of thesf |
keep_cols | Vectors of columns from |
excluded | Types of railways to exclude from routing. |
Value
Adata.frame of edges representing the rail network, alongwith a column of graph component numbers.
Note
Default railway weighting is by distance. Other weighting schemes, suchas by maximum speed, can be implemented simply by modifying thed_weighted column returned by this function accordingly.
See Also
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_streetnet()
Examples
## Not run: # sample railway extraction with the 'osmdata' packagelibrary (osmdata)dat <- opq ("shinjuku") %>% add_osm_feature (key = "railway") %>% osmdata_sf (quiet = FALSE)graph <- weight_railway (dat$osm_lines)## End(Not run)Weight a street network according to a specified weighting profile.
Description
Weight (or re-weight) ansf orsilicate ("SC") formatted OSMstreet network according to a specified weighting profile. Standardweighting profiles may be specified by name, as one of:
foot
horse
wheelchair
bicycle
moped
motorcycle
motorcar
goods
hgv
psv
Custom weighting profiles are also possible, as explained in the Note below.
Usage
weight_streetnet( x, wt_profile = "bicycle", wt_profile_file = NULL, turn_penalty = FALSE, type_col = "highway", id_col = "osm_id", keep_cols = NULL, left_side = FALSE)## Default S3 method:weight_streetnet( x, wt_profile = "bicycle", wt_profile_file = NULL, turn_penalty = FALSE, type_col = "highway", id_col = "osm_id", keep_cols = NULL, left_side = FALSE)## S3 method for class 'sf'weight_streetnet( x, wt_profile = "bicycle", wt_profile_file = NULL, turn_penalty = FALSE, type_col = "highway", id_col = "osm_id", keep_cols = NULL, left_side = FALSE)## S3 method for class 'sc'weight_streetnet( x, wt_profile = "bicycle", wt_profile_file = NULL, turn_penalty = FALSE, type_col = "highway", id_col = "osm_id", keep_cols = NULL, left_side = FALSE)## S3 method for class 'SC'weight_streetnet( x, wt_profile = "bicycle", wt_profile_file = NULL, turn_penalty = FALSE, type_col = "highway", id_col = "osm_id", keep_cols = NULL, left_side = FALSE)Arguments
x | A street network represented either as |
wt_profile | Name of weighting profile, or |
wt_profile_file | Name of locally-stored, |
turn_penalty | Including time penalty on edges for turning acrossoncoming traffic at intersections (see Note). |
type_col | Specify column of the |
id_col | For |
keep_cols | Vectors of columns from |
left_side | Does traffic travel on the left side of the road ( |
Details
Distances along each edge are calculated using thegeodist package,defaulting to the Mapbox "cheap" metric if maximal network distances are <100km, otherwise using Haversine distances. Thedodgr_streetnet_geodesic function can be called to force edgedistances to be calculated using more accurate yet slower geodesicdistances.
The structure of networks generated by this function is dependenton many aspects of the input network, and in particular on specifickey-value pairs defined in the underlying OpenStreetMap (OSM) data.
Many key-value pairs influence the resultant network through being used inspecified weighting profiles. Keys used in weighting profiles are alwayskept in the weighted networks, and are specified inweighting_profiles by the "way" column in the "weighting_profiles"item. These include:
"bridleway"
"cycleway"
"ferry"
"footway"
"living_street"
"motorway"
"motorway_link
"path"
"pedestrian"
"primary"
"primary_link"
"residential"
"secondary"
"secondary_link
"service"
"steps"
"tertiary"
"tertiary_link"
"track"
"trunk"
"trunk_link
"unclassified"
Some of these are only optionally kept, dependent on the weighting profilechosen. For example, "cycleway" keys are only kept for bicycle weighting.Most of the specified keys also include all possible variations on thosekeys. For the example of "cycleway" again, key-value pairs are also kept for"cycleway:left" and "cycleway:right".
The following additional keys are also automatically retained in weightednetworks:
"highway"
"junction"
"lanes"
"maxspeed"
"oneway", including with all alternative forms such as "oneway.bicycle"
"surface"
Realistic routing including factors such as access restrictions, turnpenalties, and effects of incline, can only be implemented when the objectspassed toweight_streetnet are ofsc ("silicate") format, generatedwithdodgr_streetnet_sc (and possibly enhanced through applying theosmdata functionosm_elevation()). Restrictions applied to ways (inOSM terminology) may be controlled by ensuring specific columns are retainedin thedodgr network with thekeep_cols argument. For example,restrictions on access are generally specified by specifying a value for thekey of "access". Include "access" inkeep_cols will ensure these valuesare retained in thedodgr version, from which ways with specified valuescan easily be removed or modified, as demonstrated in the examples.
Restrictions and time-penalties on turns can be implemented by settingturn_penalty = TRUE, which will then honour turn restrictions specified inOSM (unless the "penalties" table ofweighting_profiles hasrestrictions = FALSE for a specifiedwt_profile). Resultant graphs arefundamentally different from the default for distance-based routing. Thesegraphs may be used directly in most 'dodgr' functions, but generally only ifthey have been created by calling this function in the same session, or ifthey have been saved and loaded with thedodgr_save_streetnet anddodgr_load_streetnet functions. (This is because the weightedstreetnets also have accompanying data stored in a local temporary cachedirectory; attempting to pass a weighted street network without theseaccompanying cache files will generally error.)
Some key-value pairs may also directly influence not just the value of thegraph produced by this function, but also its size. Among these are "oneway"flags. Without these flags, each edge will be represented indirected form,and so as two rows of the graph: one for A -> B, and one for B -> A. If away is tagged in OSM as "oneway" = "yes", and if oneway flags are respectedfor a chosen weighting profile (which, for example, they are generally notfor pedestrian or "foot" weighting), then only one edge will be returnedrepresenting travel in the direction permitted within the OSM data. Thusweighting a network which includes "oneway" flags, and using a weightingprofile which respects these, will generate a graph with fewer rows than agraph produced by ignoring those "oneway" flags.
Value
Adata.frame of edges representing the street network, withdistances in metres and times in seconds, along with a column of graphcomponent numbers. Times forsf-formatted street networks are onlyapproximate, and do not take into account traffic lights, turn angles, orelevation changes. Times forsc-formatted street networks take intoaccount all of these factors, with elevation changes automatically taken intoaccount for networks generated with theosmdata functionosm_elevation().
Note
Names for thewt_profile parameter are taken fromweighting_profiles, which is a list including adata.frame alsocalledweighting_profiles of weights for different modes of transport.Values forwt_profile are taken from current modes included there, whichare "bicycle", "foot", "goods", "hgv", "horse", "moped", "motorcar","motorcycle", "psv", and "wheelchair". Railway routing can be implementedwith the separate functionweight_railway. Alternatively, the entireweighting_profile structures can be written to a local.json-formattedfile withwrite_dodgr_wt_profile, the values edited as desired, andthe name of this file passed as thewt_profile_file parameter.
The resultant graph includes only those edges for which the givenweighting profile specifies finite edge weights. Any edges of types notpresent in a given weighting profile are automatically removed from theweighted streetnet.
If the resultant graph is to be contracted viadodgr_contract_graph,and if the columns of the graph have been,or will be, modified, then automatic caching must be switched off withdodgr_cache_off. If not, thedodgr_contract_graph function willreturn the automatically cached version, which is the contracted version ofthe full graph prior to any modification of columns.
See Also
write_dodgr_wt_profile,dodgr_times
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway()
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway()
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway()
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway()
Other extraction:dodgr_streetnet(),dodgr_streetnet_geodesic(),dodgr_streetnet_sc(),weight_railway()
Examples
# hampi is included with package as an 'osmdata' sf-formatted street networknet <- weight_streetnet (hampi)class (net) # data.framedim (net) # 6096 11; 6096 streets# os_roads_bristol is also included as an sf data.frame, but in a different# format requiring identification of columns and specification of custom# weighting scheme.colnm <- "formOfWay"wts <- data.frame ( name = "custom", way = unique (os_roads_bristol [[colnm]]), value = c (0.1, 0.2, 0.8, 1))net <- weight_streetnet ( os_roads_bristol, wt_profile = wts, type_col = colnm, id_col = "identifier")dim (net) # 406 11; 406 streets# An example for a generic (non-OSM) highway, represented as the# `routes_fast` object of the \pkg{stplanr} package, which is a# SpatialLinesDataFrame.## Not run: library (stplanr)# merge all of the 'routes_fast' lines into a single networkr <- overline (routes_fast, attrib = "length", buff_dist = 1)r <- sf::st_as_sf (r, crs = 4326)# We need to specify both a `type` and `id` column for the# \link{weight_streetnet} function.r$type <- 1r$id <- seq (nrow (r))graph <- weight_streetnet ( r, type_col = "type", id_col = "id", wt_profile = 1)## End(Not run)Weighting profiles used to route different modes of transport.
Description
Collection of weighting profiles used to adjust the routing process todifferent means of transport. Modified from data taken from the Routinoproject, with additional tables for average speeds, dependence of speed ontype of surface, and waiting times in seconds at traffic lights. The lattertable (called "penalties") includes waiting times at traffic lights (inseconds), additional time penalties for turning across oncoming traffic("turn"), and a binary flag indicating whether turn restrictions should beobeyed or not.
Format
List ofdata.frame objects with profile names, means of transportand weights.
References
https://www.routino.org/xml/routino-profiles.xml
See Also
Other data:hampi,os_roads_bristol
Writedodgr weighting profiles to local file.
Description
Write thedodgr street network weighting profiles to a local.json-formatted file for manual editing and subsequent re-reading.
Usage
write_dodgr_wt_profile(file = NULL)Arguments
file | Full name (including path) of file to which to write. The |
Value
TRUE if writing successful.
See Also
Other misc:compare_heaps(),dodgr_flowmap(),dodgr_full_cycles(),dodgr_fundamental_cycles(),dodgr_insert_vertex(),dodgr_sample(),dodgr_sflines_to_poly(),dodgr_vertices(),merge_directed_graph(),summary.dodgr_dists_categorical()
Examples
f <- tempfile (fileext = ".json")write_dodgr_wt_profile (file = f)wt_profiles <- jsonlite::read_json (f, simplify = TRUE)