---
title: 'Intro to r5r: Rapid Realistic Routing with R5 in R'
author: "Rafael H. M. Pereira, Marcus Saraiva, Daniel Herszenhut, Carlos Kaue Braga"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
abstract: "`{r5r}` is an R package for rapid realistic routing on multimodal transport networks (walk, bike, public transport and car) using R<sup>5</sup>. The package allows users to generate detailed routing analysis or calculate travel time matrices using seamless parallel computing on top of the R<sup>5</sup> Java machine <https://github.com/conveyal/r5>"
urlcolor: blue
vignette: >
  %\VignetteIndexEntry{Intro to r5r: Rapid Realistic Routing with R5 in R} 
  %\VignetteEngine{knitr::rmarkdown} 
  \usepackage[utf8]{inputenc}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = identical(tolower(Sys.getenv("NOT_CRAN")), "true"),
  out.width = "100%"
)

## removes files previously created by 'build_network()'
#data_path <- system.file("extdata/poa", package = "r5r")
#existing_files <- list.files(data_path)
#files_to_keep <- c(
#  "poa_hexgrid.csv",
#  "poa_osm.pbf",
#  "poa_points_of_interest.csv",
#  "poa_eptc.zip",
#  "poa_trensurb.zip",
#  'fares'
#  )
#files_to_remove <- existing_files[! existing_files %in% files_to_keep]
#invisible(file.remove(file.path(data_path, files_to_remove)))
```

# 1. Introduction 

**r5r** is an [R package for rapid realistic routing on multimodal transport networks](https://github.com/ipea/r5r) (walk, bike, public transport and car). It provides a simple and friendly interface to R<sup>5</sup>, a really fast and open source Java-based routing engine developed separately by [Conveyal](https://www.conveyal.com/). R<sup>5</sup> stands for [Rapid Realistic Routing on Real-world and Reimagined networks](https://github.com/conveyal/r5). More details about **r5r** can be found on the [package webpage](https://ipea.github.io/r5r/index.html) or on this [paper](
https://doi.org/10.32866/001c.21262).

# 2. Installation

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

```{r, eval = FALSE}
# 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:

- [Adoptium/Eclipse Temurin](https://adoptium.net/) (our preferred option)
- [Amazon Corretto](https://aws.amazon.com/corretto/)
- [Oracle OpenJDK](https://jdk.java.net/21/). 

The easiest way to install JDK 21 is with the [{rJavaEnv}](https://www.ekotov.pro/rJavaEnv/) package in R:

```{r, eval = FALSE}
# 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 {#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.

```{r, message = FALSE}
old_options <- 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:

```{r, message = FALSE, warning = FALSE}
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](https://ipea.github.io/r5r/articles/fare_structure.html)).

**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:

- OpenStreetMap
  - [osmextract](https://docs.ropensci.org/osmextract/) R package
  - [geofabrik](https://download.geofabrik.de/) website
  - [hot export tool](https://export.hotosm.org/) website
  - [BBBike.org](https://extract.bbbike.org/) website

- GTFS
  - [tidytransit](https://r-transit.github.io/tidytransit/) R package
  - [transitland](https://www.transit.land/) website
  - [Mobility Database](https://mobilitydatabase.org/) website

- Elevation
  - [elevatr](https://github.com/USEPA/elevatr) R package
  - Nasa's SRTMGL1 website


# 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.


```{r}
data_path <- system.file("extdata/poa", package = "r5r")
list.files(data_path)
```

Points of interest, used below as origins and destinations:

```{r}
poi <- fread(file.path(data_path, "poa_points_of_interest.csv"))
head(poi)
```

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

```{r}
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 R<sup>5</sup> JAR (on first use or when the R<sup>5</sup> 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.

```{r, message = FALSE}
# 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](https://ipea.github.io/r5r/articles/accessibility.html)).

```{r, message = FALSE, warning = FALSE}
# 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](https://ipea.github.io/r5r/articles/time_window.html)). 


```{r, message = FALSE}
# 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)
```

```{r ttm head, echo=FALSE, message=FALSE, out.width='100%', eval = FALSE}
knitr::include_graphics("https://github.com/ipea/r5r/blob/master/r-package/inst/img/vig_output_ttm.png?raw=true")
```


### 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.


```{r, message = FALSE}
# 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:

```{r, message = FALSE}
# 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)
```
```{r detailed head, echo = FALSE, out.width='100%', message = FALSE, eval = FALSE}
knitr::include_graphics("https://github.com/ipea/r5r/blob/master/r-package/inst/img/vig_output_detailed.png?raw=true")
```

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:

```{r, message = FALSE}
# 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()

```

```{r ggplot2 output, echo = FALSE, out.width='100%', message = FALSE, eval = FALSE}
knitr::include_graphics("https://github.com/ipea/r5r/blob/master/r-package/inst/img/vig_detailed_ggplot.png?raw=true")
```


### Cleaning up after usage

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

```{r, message = FALSE}
r5r::stop_r5(r5r_network)
rJava::.jgc(R.gc = TRUE)
options(old_options)
```

If you have any suggestions or want to report an error, please visit [the package GitHub page](https://github.com/ipea/r5r).


