Intro to r5r: Rapid Realistic Routing with R5 in R

1. Introduction

r5r is an R package for rapid realistic routing on multimodal transport networks (walk, bike, public transport and car). It provides a simple and friendly interface to R5, a really fast and open source Java-based routing engine developed separately by Conveyal. R5 stands for Rapid Realistic Routing on Real-world and Reimagined networks. More details about r5r can be found on the package webpage or on this paper.

2. Installation

You can install {r5r} from CRAN, or the development version from github.

# from CRAN
install.packages('r5r')

# dev version with latest features
devtools::install_github("ipea/r5r", subdir = "r-package")

{r5r} requires the Java Development Kit (JDK) 21. Any free, open-source JDK works, for example:

The easiest way to install JDK 21 is with the {rJavaEnv} package in R:

# install {rJavaEnv} from CRAN
install.packages("rJavaEnv")

# check version of Java currently installed (if any) 
rJavaEnv::java_check_version_rjava()

## if this is the first time you use {rJavaEnv}, you might need to run this code
## below to consent the installation of Java.
# rJavaEnv::rje_consent(provided = TRUE)

# install Java 21
rJavaEnv::java_quick_install(version = 21)

# check if Java was successfully installed
rJavaEnv::java_check_version_rjava()

3. Usage

First, set the memory available to Java with the java.parameters option (2 GB is enough for the sample data). Do this before loading {r5r} or any other Java-based package: rJava starts the Java Virtual Machine only once per R session, so later changes only take effect after restarting R.

options(java.parameters = "-Xmx2G")

# By default, {r5r} uses all CPU cores available. If you want to limit the 
# number of CPUs to 4, for example, you can run:  
options(java.parameters = c("-Xmx2G", "-XX:ActiveProcessorCount=4"))

Then we can load the packages used in this vignette:

library(r5r)
library(sf)
library(data.table)
library(ggplot2)

{r5r} has eight fundamental functions:

Function Returns
build_network() A routable multimodal transport network
accessibility() Access to opportunities from each origin, given a decay function
travel_time_matrix() Travel times between origin/destination pairs for a departure time
arrival_travel_time_matrix() Travel times for an arrival time, with routes used (and a time breakdown with breakdown = TRUE)
expanded_travel_time_matrix() Travel times per departure minute, with routes used (and a time breakdown with breakdown = TRUE)
detailed_itineraries() One or more alternative routes per origin/destination pair, detailed by trip segment
pareto_frontier() The trade-off between travel time and monetary cost of route alternatives
isochrone() Areas reachable from an origin within given travel times

Most of them can also account for monetary travel costs (fare structure vignette).

Support functions:

Function Returns
street_network_to_sf() The OpenStreetMap street network of a network.dat file, as sf
transit_network_to_sf() The public transport network of a network.dat file, as sf
find_snap() Where input points snap to the street network
r5r_sitrep() A situation report to help debug errors

3.1 Data requirements:

To use {r5r}, you will need:

  • A road network data set from OpenStreetMap in .pbf format (mandatory)
  • A public transport feed in GTFS.zip format (optional)
  • A raster file of Digital Elevation Model data in .tif format (optional)

Here are a few places from where you can download these data sets:

4. Demonstration on sample data

Data

{r5r} includes sample data for Porto Alegre (Brazil):

  • An OpenStreetMap network: poa_osm.pbf
  • Two public transport feeds: poa_eptc.zip and poa_trensurb.zip
  • A raster elevation data: poa_elevation.tif
  • A poa_hexgrid.csv file with spatial coordinates of a regular hexagonal grid covering the sample area, which can be used as origin/destination pairs in a travel time matrix calculation.
  • A poa_points_of_interest.csv file containing the names and spatial coordinates of 15 places within Porto Alegre
  • A fares_poa.zip file with the fare rules of the city’s public transport system.
data_path <- system.file("extdata/poa", package = "r5r")
list.files(data_path)

Points of interest, used below as origins and destinations:

poi <- fread(file.path(data_path, "poa_points_of_interest.csv"))
head(poi)

Hexagonal grid points; we use a random sample of 200:

points <- fread(file.path(data_path, "poa_hexgrid.csv"))

# sample points
sampled_rows <- sample(1:nrow(points), 200, replace = FALSE)
points <- points[ sampled_rows, ]
head(points)

4.1 Building routable transport network with build_network()

build_network() (1) downloads the R5 JAR (on first use or when the R5 version changes) and caches it locally; and (2) combines the .pbf, GTFS .zip and optional elevation .tif files in data_path into a routable network.

# Indicate the path where OSM and GTFS data are stored
r5r_network <- build_network(data_path = data_path)

4.2 Accessibility analysis

accessibility() is the fastest way to estimate accessibility. Here we count the schools and healthcare facilities reachable in less than 60 minutes by public transport and walking (accessibility vignette).

# set departure datetime input
departure_datetime <- as.POSIXct("13-05-2019 14:00:00",
                                 format = "%d-%m-%Y %H:%M:%S")

# calculate accessibility
access <- accessibility(
  r5r_network,
  origins = points,
  destinations = points,
  opportunities_colnames = c("schools", "healthcare"),
  mode = c("WALK", "TRANSIT"),
  departure_datetime = departure_datetime,
  decay_function = "step",
  cutoffs = 60
  )

head(access)

4.3 Routing analysis

For fast routing analysis, r5r currently has three core functions: travel_time_matrix(), expanded_travel_time_matrix() and detailed_itineraries().

Fast many to many travel time matrix

travel_time_matrix() computes travel times between origin/destination pairs. Origins and destinations can be an sf POINT object or a data.frame with columns id, lon and lat. max_walk_time and max_trip_duration are in minutes, as are the resulting travel times.

It can also capture travel time variation across departures within a time window (time window vignette).

# set inputs
mode <- c("WALK", "TRANSIT")
max_walk_time <- 30 # minutes
max_trip_duration <- 120 # minutes
departure_datetime <- as.POSIXct("13-05-2019 14:00:00",
                                 format = "%d-%m-%Y %H:%M:%S")

# calculate a travel time matrix
ttm <- travel_time_matrix(
  r5r_network,
  origins = poi,
  destinations = poi,
  mode = mode,
  departure_datetime = departure_datetime,
  max_walk_time = max_walk_time,
  max_trip_duration = max_trip_duration
  )

head(ttm)

Expanded travel time matrix with minute-by-minute estimates

expanded_travel_time_matrix() works like travel_time_matrix() but also returns, for each origin/destination pair, the routes used and (with breakdown = TRUE) the access, waiting, in-vehicle and transfer times. It can be very memory intensive for large data sets.

# calculate a travel time matrix
ettm <- expanded_travel_time_matrix(
  r5r_network,
  origins = poi,
  destinations = poi,
  mode = mode,
  departure_datetime = departure_datetime,
  breakdown = TRUE,
  max_walk_time = max_walk_time,
  max_trip_duration = max_trip_duration
  )

head(ettm)

Detailed itineraries

Most routing packages return only the fastest route. detailed_itineraries() can also return alternative routes between origin/destination pairs, detailed by trip segment: transport mode, waiting time, travel time and distance.

Below, alternative routes for a single origin/destination pair:

# set inputs
origins <- poi[10,]
destinations <- poi[12,]
mode <- c("WALK", "TRANSIT")
max_walk_time <- 60 # minutes
departure_datetime <- as.POSIXct("13-05-2019 14:00:00",
                                 format = "%d-%m-%Y %H:%M:%S")

# calculate detailed itineraries
det <- detailed_itineraries(
  r5r_network,
  origins = origins,
  destinations = destinations,
  mode = mode,
  departure_datetime = departure_datetime,
  max_walk_time = max_walk_time,
  shortest_path = FALSE
  )

head(det)

The output is an sf data.frame, ready to map.

Visualize results

street_network_to_sf() extracts the OSM street network used in routing, to give the map geographic context:

# extract OSM network
street_net <- r5r::street_network_to_sf(r5r_network)

# extract public transport network
transit_net <- r5r::transit_network_to_sf(r5r_network)

# plot
ggplot() +
  geom_sf(data = street_net$edges, color='gray85') +
  geom_sf(data = det, aes(color=mode)) +
  facet_wrap(.~option) + 
  theme_void()

Cleaning up after usage

Stop the network and run Java’s garbage collector to free the memory it used:

r5r::stop_r5(r5r_network)
rJava::.jgc(R.gc = TRUE)

If you have any suggestions or want to report an error, please visit the package GitHub page.