Flooding results from tidal events can limit local residents’ outdoor trips not only by the storm events, but also by disturbing the street network because the flash flood can cause standing water on the street, which, if cannot be drained properly, it won’t be safe for people to get on the “watered”, slippery roads.

Our project want to study how the street network was disrupted by the tidal event in Charleston city in South Carolina. We investigated robustness of the street network linking each census tract to the local restaurants by assuming that restaurants are very common destinations of driving trips, and restaurants are places for people hanging out and enjoying their lives together. Therefore, any disturbance on this network will have very noticeable impacts on people’s daily lives.

We chose the tidal event happening on March 20th - 21st, 2023 in Charleston county. The flood map is generated using the remote sensing Sentinel-1 from google earth engine:

https://code.earthengine.google.com/d5d42b688e52609c898429ba0639f1a2

It is a flood extent mapping by calculating the difference of the surface reflection before and after the flood event.

The code template was referenced from the tutorial:

“Step-by-Step: Recommended Practice: Flood Mapping and Damage Assessment Using Sentinel-1 SAR Data in Google Earth Engine.” United Nations. https://un-spider.org/advisory-support/recommended-practices/recommended-practice-google-earth-engine-flood-mapping/step-by-step#Step%2013:%20Affected%20urban%20areas

A snapshot of the flood mapping generated from google earth engine
A snapshot of the flood mapping generated from google earth engine

Then by taking this flood extent mapping as a vector layer. We used it to clipped the “un-disrupted” street network.

We downloaded and processed the street networks from open street map. Then we got our “shortest-path-to-restaurant network” (the network linking each census tract in Charleston city to all the local restaurants) by getting the shortest paths from each census tract’s centroid to all the restaurants.

After that, we cut the network into disconnected pieces, which demonstrated that the street network was substantially disrupted after the tidal floods.

However, since it is hard to calculate “after-flooding” network with disconnected network pieces, alternatively, we weighted the “flooded streets” (the street lines overlapping with the polygons of the flooded areas) to 0.5 by assuming that people could still get onto these streets if they drove with extra carefulness but they are not the preferred roads. Then we calculated all the shortest paths again using the weighted network (weight = 0.5 if flooded, weight = 1 if not flooded).

By overlaying the shortest paths before the tidal event and the shortest paths after the event, some crucial segments were identified: the streets appeared in the shortest paths before the tidal event but did not in the paths after the event.

This finding can suggest which part of the roads / part of the city areas need extra caring. Maybe a better drainage system is needed, maybe a better stormwater management practice is needed such as a more pervious surfaces, more green spaces/green roofs, etc.

Also, a layer downloaded from census tract was stacked on the map as well (the median household income) so that we can have some ideas about which communities (rich communities or poor communities) have most of the “disrupted roads” and are impacted by the tidal events very much.

First of all, load the packages:

library(tidyverse)
library(tmap)
library(ggplot2)
library(units)
library(sf)
library(leaflet)
library(tidycensus)
library(leafsync)
library(dbscan)
library(sfnetworks)
library(tigris)
library(tidygraph)
library(plotly)
library(osmdata)
library(here)
library(tidytransit)
library(units)
library(leaflet)
library(tidycensus)
library(leafsync)

epsg <- 4326

Download census tract data for API request

census_api_key(Sys.getenv("census_api"))
## To install your API key for use in future sessions, run this function with `install = TRUE`.
### Tract polygons for the Yelp query
tract <- suppressMessages(
  get_acs(geography = "tract", # or "block group", "county", "state" etc.
          state = "SC",
          county = c("charleston"),
          variables = c(hhincome = 'B19019_001',
                        race.tot = "B02001_001",
                        race.white = "B02001_002",
                        race.black = 'B02001_003'
                        ),
          year = 2021,
          survey = "acs5", # American Community Survey 5-year estimate
          geometry = TRUE, # returns sf objects
          output = "wide") # wide vs. long
)
# Save downloaded census data to a file
saveRDS(tract, "charleston_tract.rds")
tract_char <- read_rds("charleston_tract.rds")

Get the boundary for Charleston city

charleston <- places('SC') %>%
  filter(NAME == 'Charleston')

Intersect the county level census tracts with the city boundary because the city is the area of scope that we are interested in:

char_city <- tract_char[charleston,]
# Save Charleston city census data to a file
saveRDS(char_city, "charlestoncity_tract.rds")
charcity_tract <- read_rds("charlestoncity_tract.rds")
#View the geographic boundary
charcity_tract <- charcity_tract %>% 
  select(GEOID, 
         hhincome = hhincomeE, # New name = old name
         race.tot = race.totE,
         race.white = race.whiteE,
         race.black = race.blackE) %>% 
  mutate(area=st_area(geometry) %>% 
           set_units(., km^2)) %>% 
  mutate(pop.dense = race.tot/area)

View of the area in our study:

tmap_mode("view")
## tmap mode set to interactive viewing
tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'darkred')

Create centroids in each census tract to:

  1. use them as the “origins” of the trips to all the restaurants

  2. use them to request yelp data of restaurants in Charleston city

# Repeat exercise in mini assignment 1 to request yelp data
library(httr)
library(jsonlite)
library(reshape2)
library(yelpr)
library(knitr)
# Data would be written into .rds file after requesting and, 
# the code chunks for yelp API request would be commented out
# Function: Get tract-wise radius
get_r <- function(poly, epsg_id){
  #---------------------
  # Takes: a single POLYGON or LINESTRTING
  # Outputs: distance between the centroid of the boundingbox and a corner of the bounding box
  #---------------------

  # Get bounding box of a given polygon
  bb <- st_bbox(poly)
  # Get lat & long coordinates of any one corner of the bounding box.
  bb_corner <- st_point(c(bb[1], bb[2])) %>% st_sfc(crs = epsg_id)
  # Get centroid of the bb
  bb_center_x <- (bb[3]+bb[1])/2
  bb_center_y <- (bb[4]+bb[2])/2
  bb_center <- st_point(c(bb_center_x, bb_center_y)) %>% st_sfc(crs = epsg_id) %>% st_sf()

  # Get the distance between bb_p and c
  r <- st_distance(bb_corner, bb_center)
  # Multiply 1.1 to make the circle a bit larger than the Census Tract.
  # See the Yelp explanation of their radius parameter to see why we do this.
  bb_center$radius <- r*1.2
  return(bb_center)
}
r4all_apply <- charcity_tract %>%
  st_geometry() %>%
  st_transform(crs = epsg) %>%
  lapply(., function(x) get_r(x, epsg_id = epsg))

r4all_apply <- bind_rows(r4all_apply)
ready_4_yelp <- r4all_apply %>%
  mutate(x = st_coordinates(.)[,1],
         y = st_coordinates(.)[,2])

Use the function we learned from Module 1 to request yelp data:

# FUNCTION
get_yelp <- function(tract, category){
  # ----------------------------------
  # Gets one row of tract information (1,) and category name (str),
  # Outputs a list of business data.frame
  Sys.sleep(1)
  n <- 1
  # First request --------------------------------------------------------------
  resp <- business_search(api_key = Sys.getenv("yelpr_api"),
                          categories = category,
                          latitude = tract$y,
                          longitude = tract$x,
                          offset = (n - 1) * 50, # = 0 when n = 1
                          radius = round(tract$radius),
                          limit = 50)
  # Calculate how many requests are needed in total
  required_n <- ceiling(resp$total/50)

  # out is where the results will be appended to.
  out <- vector("list", required_n)

  # Store the business information to nth slot in out
  out[[n]] <- resp$businesses

  # Change the name of the elements to the total required_n
  # This is to know if there are more than 1000 businesses,
  # we know how many.
  names(out)[n] <- required_n

  # Throw error if more than 1000
  if (resp$total >= 1000)
  {
    # glue formats string by inserting {n} with what's currently stored in object n.
    print(glue::glue("{n}th row has >= 1000 businesses."))
    # Stop before going into the loop because we need to
    # break down Census Tract to something smaller.
    return(out)
  }
  else
  {
    # add 1 to n
    n <- n + 1

    # Now we know required_n -----------------------------------------------------
    # Starting a loop
    while(n <= required_n){
      resp <- business_search(api_key = Sys.getenv("yelpr_api"),
                              categories = category,
                              latitude = tract$y,
                              longitude = tract$x,
                              offset = (n - 1) * 50,
                              radius = round(tract$radius),
                              limit = 50)

      out[[n]] <- resp$businesses

      n <- n + 1
    } #<< end of while loop

    # Merge all elements in the list into a single data frame
    out <- out %>% bind_rows()

    return(out)
  }
}
# Prepare a collector
yelp_all_list <- vector("list", nrow(ready_4_yelp))

# Looping through all Census Tracts
for (row in 1:nrow(ready_4_yelp)){
  yelp_all_list[[row]] <- suppressMessages(get_yelp(ready_4_yelp[row,], "restaurants"))
  if (row %% 10 == 0){
    print(paste0("Current row: ", row))
  }
}

# Collapsing the list into a data.frame
eatinchar_yelp <- yelp_all_list %>% bind_rows() %>% as_tibble()

# print
eatinchar_yelp %>% print(width=1000)
# Save before-tidied eatinchar_yelp to a file
saveRDS(eatinchar_yelp, "eatinchar_yelp_raw.rds")
eatinchar_yelp_raw <- read_rds("eatinchar_yelp_raw.rds")

Clean the yelp data we requested so it can be ready for our analysis:

# Flatten

# Custom function that takes the data frame in "categories" column in Yelp data
# and returns a character vector
concate_list <- function(x){
  # x is a data frame with columns "alias" and "title" from Yelp$categories
  # returns a character vector containing category concatenated titles 
  titles <- x[["title"]] %>% str_c(collapse = ", ")
  return(titles)
}
eatinchar_yelp_clean <- eatinchar_yelp_raw %>% 
  distinct(id, .keep_all=T) %>% 
  jsonlite::flatten() %>% 
  # 2. Handling list-columns
  mutate(transactions = transactions %>% 
           map_chr(., function(x) str_c(x, collapse=", ")),
         location.display_address = location.display_address %>% 
           map_chr(., function(x) str_c(x, collapse=", ")),
         categories = categories %>% map_chr(concate_list))
# Check missing values
eatinchar_yelp_clean %>% 
  map_dbl(., function(x) sum(is.na(x))) %>% 
  # map_dbl is a variant of map() which outputs 
  # numeric vector rather than a list.
  sapply(., function(x) x != 0) %>% 
  which()
##             price location.address1 location.address2 location.address3 
##                11                17                18                19

No missing data in our analysis of interest was found (coordinates, reviews and rating).

eatinchar_yelp_sf <- eatinchar_yelp_clean %>% 
  st_as_sf(coords=c("coordinates.longitude", "coordinates.latitude"), 
           crs = 4326)

View our requested yelp data. Since there are several hundreds of restaurants, we will only show the “popular and good ones” on the map

(We set threshold as review counts > 500 and rating > 3)

tm_shape(eatinchar_yelp_sf %>% filter(review_count>500 & rating>3)) +
  tm_symbols(col = "review_count",
             size="rating",
             style = "quantile",
             sizes.legend=c(.5, 1,3)*1e6, 
             scale=1, 
             legend.shape.show = FALSE, 
             legend.size.is.portrait = TRUE, 
             shapes.legend = 22,
             group = "cat",
             id = "name",
             popup.vars = c("Rating"="rating",
                            "No.of Reviews"="review_count",
                            "Offer"="categories")) + 
  tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.

There are some data points outside of our study area for some reason, so we need to get the data points further cleaned by intersecting the Charleston city boundary and the yelp data points:

st_crs(charleston) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that
eatwithinchar_yelp_sf <- eatinchar_yelp_sf[charleston, ,op = st_intersects]
tm_shape(eatwithinchar_yelp_sf %>% filter(review_count>500 & rating>3)) +
  tm_symbols(col = "review_count",
             size="rating",
             style = "quantile",
             sizes.legend=c(.5, 1,3)*1e6, 
             scale=1, 
             legend.shape.show = FALSE, 
             legend.size.is.portrait = TRUE, 
             shapes.legend = 22,
             group = "cat",
             id = "name",
             popup.vars = c("Rating"="rating",
                            "No.of Reviews"="review_count",
                            "Offer"="categories")) + 
  tm_shape(charcity_tract) + tm_borders() + tm_shape(charleston) + tm_borders(col = 'skyblue')
## Legend for symbol sizes not available in view mode.

Now only the data points lying within / at the boundary are retained. The yelp data points are ready for use as destinations of the trips.

Download Required data from OSM; then create a street network from the downloaded polylines:

osm_road <- opq(bbox = st_bbox(charleston)) %>%
  add_osm_feature(key = 'highway', 
                  value = c("motorway", "trunk", "primary", "secondary", "tertiary", 
                            "residential", "motorway_link", "trunk_link", "primary_link", 
                            "secondary_link", "tertiary_link", "residential_link", 
                            "unclassified")) %>%
  osmdata_sf() %>% 
  osm_poly2line()

names(osm_road)
## [1] "bbox"              "overpass_call"     "meta"             
## [4] "osm_points"        "osm_lines"         "osm_polygons"     
## [7] "osm_multilines"    "osm_multipolygons"
osm <- osm_road$osm_line %>%
  select(osm_id, highway) %>% 
  sfnetworks::as_sfnetwork(directed = FALSE) %>% 
  activate("edges") %>%
  filter(!edge_is_multiple()) %>%
  filter(!edge_is_loop()) %>% 
  convert(., sfnetworks::to_spatial_subdivision) %>%
  # rename_all(~gsub(":", "_", .)) %>% 
  convert(., sfnetworks::to_spatial_smooth) 
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
# Add a new column named 'length' to the edges part of the object `osm`.
osm <- osm %>% mutate(length = edge_length())

Before calculating the shortest paths between the controids of census tracts and the local restaurants, viewing the un-disrupted street network:

# Plot 
osm_before_map <- leaflet() %>%
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  addPolylines(data = osm %>% st_as_sf('edges'), col = "grey", weight = 3, opacity = 0.9) %>%
  addCircles(data = osm %>% st_as_sf('nodes'), fillColor = "orange", stroke = F, radius = 20, fillOpacity = 0.7) 
# %>% addLegend(position = "bottomright", pal = pal, values = before_net %>% st_as_sf("nodes") %>% pull(is.new))

osm_before_map

Calculate the betweenness centrality so we can know the important street segments that are falling on the “shortest” paths to all the possible destinations.

# Calculate centrality measures
betweenness_char <- osm %>% 
  activate("edges") %>%
  mutate(weight = edge_length()) %>% 
  mutate(edge_bc = centrality_edge_betweenness(weights = weight, directed = F)) %>%
  activate("nodes") %>% 
  mutate(node_bc = centrality_betweenness(weights = weight, directed = F))
# Save Charleston city census data to a file
saveRDS(betweenness_char, "betweenness_char.rds")
betweenness_char <- read_rds("betweenness_char.rds")
# Edge betweenness
bet_pal_edge <- colorNumeric(palette = "Reds", domain = betweenness_char %>% activate("edges") %>% pull(edge_bc), n = 6)

# Node betweenness
bet_pal_node <- colorNumeric(palette = "Reds", domain = betweenness_char %>% activate("nodes") %>% pull(node_bc), n = 6)


# Map
leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  setView( -79.940918, 32.784618, zoom = 14) %>% # zooming in to show more details
  addPolylines(data = betweenness_char %>% st_as_sf("edges"), 
               color = ~bet_pal_edge(betweenness_char %>% st_as_sf('edges') %>% pull(edge_bc)), weight = 3, opacity = 0.7) %>% 
  addCircles(data = betweenness_char %>% st_as_sf("nodes"), 
               fillColor = ~bet_pal_node(betweenness_char %>% st_as_sf('nodes') %>% pull(node_bc)), stroke = F, fillOpacity = 0.7, 
             radius = betweenness_char %>% st_as_sf("nodes") %>% with(.$node_bc/(max(.$node_bc)/100))) # denominator is selected to make the max value roughly equal to 100
snapshot of my betweenness map because I could not render this file with many heavy leaflet maps
snapshot of my betweenness map because I could not render this file with many heavy leaflet maps

The map is showing the hierarchy of the importance of the street segments. The more red the segment is, the more frequent it lies in part of the shortest paths to “somewhere” in the city.

And we can use this hierarchy to set priority when assessing which flooded segments are more critical.

Try the simulation from just one census tract to one restaurant as a pilot test.

home <- r4all_apply
# Extract the first row from `home` object and store it as `origin`
origin <- home[1,]

# Find a restaurant with the most review counts among all the ones having rating over or equal to 4.5 

pop_eat <- eatwithinchar_yelp_sf %>% 
  filter(rating>=4.5) %>% 
  filter(review_count==max(review_count))

# Find the shortest path from origin to station
# using st_network_paths() function.
# This "all_simple" function is taking too long
pop_path <- st_network_paths(osm, from = origin, to = pop_eat, type = "shortest")

# 1. From `osm` object, activate nodes part and
# 2. use `closest_index` to extract the selected path
pop_path <- osm %>%
  activate("nodes") %>% 
  slice(pop_path$node_paths[[1]])

Viewing the shortest path in the first trial:

# Visualize
leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>% 
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  # Base network in grey
  addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>% 
  
  # Chosen edges
  addPolylines(data = pop_path %>% st_as_sf("edges"), color = "red", weight = 10, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_path %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 50)

The trial shortest path was successfully calculated.

Read in the flood extent mapping as polygons:

flooded_char <- read_sf(here("floodedcharv2","flooded_char-v2.shp"))

View the flood extent mapping (a much larger area was exported from google earth engine to ensure that our study area will be covered)

flooded_char %>% 
  ggplot() +
  geom_sf()

Intersect the un-disrupted street network (all the streets, not the shortest paths yet) and the flood map to get the flooded road lines:

before_char <- osm_road$osm_lines
after_char <- before_char[flooded_char, ]

Clip out those flooded roads to get the “after flood” road network

(We have to do this 2-step approach instead of doing anti-join because the latter method took too long to process and eventually made the program crash.)

after_char_road <- before_char[!(before_char$osm_id %in% after_char$osm_id), ]
osm_after <- after_char_road %>%
  select(osm_id, highway) %>% 
  sfnetworks::as_sfnetwork(directed = FALSE) %>% 
  activate("edges") %>%
  filter(!edge_is_multiple()) %>%
  filter(!edge_is_loop()) %>% 
  convert(., sfnetworks::to_spatial_subdivision) %>%
  # rename_all(~gsub(":", "_", .)) %>% 
  convert(., sfnetworks::to_spatial_smooth) 
## Warning: to_spatial_subdivision assumes attributes are constant over geometries
# Add a new column named 'length' to the edges part of the object `osm`.
osm_after <- osm_after %>% mutate(length = edge_length())

View the street network after flood

# Plot 
osm_after_map <- leaflet() %>%
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  addPolylines(data = osm_after %>% st_as_sf('edges'), col = "grey", weight = 3, opacity = 0.9) %>%
  addCircles(data = osm_after %>% st_as_sf('nodes'), fillColor = "orange", stroke = F, radius = 20, fillOpacity = 0.7) 
# %>% addLegend(position = "bottomright", pal = pal, values = after_net %>% st_as_sf("nodes") %>% pull(is.new))

osm_after_map

Note that the roads are cut into disconnected pieces if we assume the flooded roads would not be accessible at all.

Recall that we did a shortest path trial using the un-disrupted street network. We were trying to find a path from same origin and same destination using this greatly segmented network. However, the destination is not reachable any more because of the disconnections within the network.

We figured something interesting to look at instead is to see how many restaurants, out of 646 in total are still reachable.

This analysis can give an idea about how the businesses are impacted by the floods. It is worth knowing because if those businesses owners could not have many customers, their income will be substantially impacted, at least during the period of the tidal events.

We did this analysis only using 1 origin, which is the same origin we used in our previous trial.

# Find the paths from origin to all reachable restaurants
# using st_network_paths() function.
paths_all_after <- st_network_paths(osm_after, from = origin, to = eatwithinchar_yelp_sf, type = "shortest")
## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.
lengthIs <- function(n) function(x) length(x)>n
# Filter(lengthIs(0), paths_all_after$edge_paths)
paths_exists_after <- paths_all_after %>%
  filter(edge_paths %in% Filter(lengthIs(0), paths_all_after$edge_paths))

cat("Number of reachable restaurants after flooding event:", nrow(paths_exists_after))
## Number of reachable restaurants after flooding event: 45
# 1. From `osm` object, activate nodes part and
# 2. use `closest_index` to extract the selected path
paths_left_after <- osm_after %>%
  activate("nodes") %>%
  slice(paths_exists_after$node_paths %>% unlist())

Only 45 out of 646 restaurants are reachable after the flooding event.

View the paths on the map:

# Visualize
leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>% 
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  # Base network in grey
  addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>% 
  
  # Chosen edges
  addPolylines(data = paths_left_after %>% st_as_sf("edges"), color = "orange", weight = 10, opacity = 0.5) %>% 
  addLegend(position = "bottomright", colors = c("orange"), labels = c("Routes to reachable restaurants after flooding"))

Since it is hard to compare the road networks before and after the flood if clipping the original intact network into disconnected segments. We wanted to find the after-flooding paths by putting different weights on flooded / not flooded roads by using the alternative assumption that people can still drive on the flooded roads, if and only if there is no other streets to drive.

Do a trial comparison using one origin and one destination:

path_after <- osm %>% 
  activate("edges") %>%
  mutate(weights = if_else(osm_id %in% after_char$osm_id, 0.5, 1) %>% 
           as.numeric()) %>% 
  st_network_paths(origin, pop_eat, weights = "weights")

# Calculate the length of edges in the shortest route to the popular restaurant selected
pop_path_after <- osm %>%
  activate("nodes") %>% 
  slice(path_after$node_paths[[1]])

View the before and after flood route on one map:

# Visualize
leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>% 
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  # Base network in grey
  addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>% 
  
  # Chosen edges
  addPolylines(data = pop_path %>% st_as_sf("edges"), color = "red", weight = 10, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_path %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 50) %>% 

  # Chosen edges
  addPolylines(data = pop_path_after %>% st_as_sf("edges"), color = "blue", weight = 10, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_path_after %>% st_as_sf("nodes"), stroke = F, fillColor = "blue", fillOpacity = 0.8, radius = 50) %>% 
  addLegend(position = "bottomright", colors = c("red","blue"), labels = c("Route before flooding", "Route after flooding"))

After the tidal event, people had to take a detour to go to that restaurant.

Now we wanted to add more restaurants as our destinations. We would still like to choose the popular and good ones instead of putting all the restaurants into destinations because:

  1. We assume that those restaurants are people’s go to places when eating outside, so the routes there would be taken by many people, which, if being disrupted by flood events, will have apparent impacts on peoples outdoor entertaining activities and outdoor trips.

  2. By limiting the number of paths to be calculated, we can have a cleaner map when showing them together on the map.

We set the threshold as:

Rating >= 4.5 and,

The 4th quantile of the distribution of “review count”

pop_eats <- eatwithinchar_yelp_sf %>% 
  filter(rating>=4.5) %>% 
  filter(review_count>quantile(review_count)[4])
# Define a function to get all the "popular" shortest paths before the tidal floods
get_pop_paths_before <- function(home, osm){
  origin <- home
  
  paths <- st_network_paths(osm, from = origin, to = pop_eats, type = "shortest")
  
  return(paths)
  }
# Prepare an empty vector to store the paths
pop_paths_before <- vector("list", nrow(home))

# Loop through all the origins to get the "popular" shortest paths before the tidal events
for (i in 1:nrow(home)){
  pop_paths_before[[i]] <- get_pop_paths_before(home[i,], osm)
}
## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.

## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.

## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.
pop_paths_before <- bind_rows(pop_paths_before)

It seems like there are still a few restaurants not reachable with the intact street network. We suspected that they could be the ones located on the edge of the city boundaries, to which some of the street segments were not included in the bounding box at the very beginning.

But we will ignore this warning message for now, since it won’t impact our analysis overall.

pop_nets_before <- osm %>%
  activate("nodes") %>%
  slice(pop_paths_before$node_paths %>% unlist())
# Define a function to get all the "popular" shortest paths after the tidal floods
get_pop_paths_after <- function(home, osm){
  origin <- home
  
  paths_after <- osm %>% 
  activate("edges") %>%
  mutate(weights = if_else(osm_id %in% after_char$osm_id, 0.5, 1) %>% 
           as.numeric()) %>% 
  st_network_paths(origin, pop_eats, weights = "weights")
  
  return(paths_after)
  }
# Prepare an empty vector to store the paths
pop_paths_after <- vector("list", nrow(home))

# Loop through all the origins to get the "popular" shortest paths after the tidal events
for (i in 1:nrow(home)){
  pop_paths_after[[i]] <- get_pop_paths_after(home[i,], osm)
}
## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.

## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.

## Warning in shortest_paths(x, from, to, weights = weights, output = "both", : At
## core/paths/dijkstra.c:446 : Couldn't reach some vertices.
pop_paths_after <- bind_rows(pop_paths_after)

Again, ignore the warning messages because a few unreachable places won’t impact our analysis in general, because we want to find the streets that are more prone to the flood events rather than ensuring every popular and good restaurants are reachable

pop_nets_after <- osm %>%
  activate("nodes") %>%
  slice(pop_paths_after$node_paths %>% unlist())
st_crs(charcity_tract) <- 4326
## Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
## that

Overlay 3 components together:

  1. The shortest paths to “popular and good restaurants” before the tidal events

  2. The shortest paths to “popular and good restaurants” after the tidal events

  3. The median household income of each census tract

# Visualize
library(leaflegend)
pal_polygon <- colorQuantile("Greys", charcity_tract$hhincome, n=5)

# Label for mouseover & popup
hhinc_labels <- paste(
  "<strong>Median Household Income(1000$): </strong>",
  signif(((charcity_tract$hhincome)/1000), 3)) %>%
  lapply(htmltools::HTML)

leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>% 
  # addTiles() %>% 
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  # Base network in grey
  addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>% 
  # add polygons to show the median household income
  addPolygons(data = charcity_tract,
              stroke = F,
              color = "#444444", 
              weight = 1, 
              smoothFactor = 0.5,
              opacity = 1.0, 
              fillOpacity = 0.5,
              fillColor = ~pal_polygon(hhincome),
              highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
              popup=~hhinc_labels
              ) %>% 
  addLegendQuantile(pal = pal_polygon,
                    values = charcity_tract$hhincome,
                    position = 'bottomright',
                    title = "median household income",
                    numberFormat = NULL) %>% 
  # Chosen edges
  addPolylines(data = pop_nets_before %>% st_as_sf("edges"), color = "red", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_before %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 20) %>% 

  # Chosen edges
  addPolylines(data = pop_nets_after %>% st_as_sf("edges"), color = "blue", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_after %>% st_as_sf("nodes"), stroke = F, fillColor = "blue", fillOpacity = 0.8, radius = 20) %>% 
  addLegend(position = "bottomright", colors = c("red","blue"), labels = c("Routes before flooding", "Routes after flooding"))
snapshot of my street network map with median household income overlapped on it
snapshot of my street network map with median household income overlapped on it

(The legend is showing the percentile of the median household income distribution, from low to high)

I didn’t render the code chunk for this mapping because I had trouble rendering the document with many leaflet maps.

By overlaying the before-flood shortest paths and the after-flood shortest paths together. It can be seen that there are some road segments picked in the intact street network (the unweighted street network) but not picked in the disrupted street network. For these segments, it can be sure that they are prone to the tidal flood. And some further investigations about why these segments are more likely to be disrupted can start from here (For example, it may because they are located at lower elevations, or because the area are mostly impervious area so it is hard for water to be drained into the earth, or because some parts of the drainage system wasn’t performing well during that tidal event, etc.)

It seems like some of these street segments are lying in the lower income community. However, it is hard to tell if the dominant part of these segments are situated in rich communities or the others.

Since the neighborhood income didn’t give us a pattern to narrow down the weak street network to prioritize, we figured it could be a good idea to see if the population density could give us a focused area to prioritize. So we lai

# Visualize
library(leaflegend)
pal_polygon <- colorQuantile("Greys", charcity_tract$pop.dense, n=4)

# Label for mouseover & popup
hhinc_labels <- paste(
  "<strong>Population density (/km^2): </strong>",
  signif(charcity_tract$pop.dense,3)) %>%
  lapply(htmltools::HTML)

leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>% 
  # addTiles() %>% 
  setView( -79.940918, 32.784618, zoom = 14) %>% 
  # zooming in to show more details
  # Base network in grey
  addPolylines(data = osm %>% st_as_sf("edges"), color = 'grey', weight = 2, opacity = 0.7) %>% 
  # add polygons to show the median household income
  addPolygons(data = charcity_tract,
              stroke = F,
              color = "#444444", 
              weight = 1, 
              smoothFactor = 0.5,
              opacity = 1.0, 
              fillOpacity = 0.5,
              fillColor = ~pal_polygon(pop.dense),
              highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
              popup=~hhinc_labels
              ) %>% 
  addLegendQuantile(pal = pal_polygon,
                    values = charcity_tract$pop.dense,
                    position = 'bottomright',
                    title = "median household income",
                    numberFormat = NULL) %>% 
  # Chosen edges
  addPolylines(data = pop_nets_before %>% st_as_sf("edges"), color = "red", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_before %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 20) %>% 

  # Chosen edges
  addPolylines(data = pop_nets_after %>% st_as_sf("edges"), color = "blue", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_after %>% st_as_sf("nodes"), stroke = F, fillColor = "blue", fillOpacity = 0.8, radius = 20) %>% 
  addLegend(position = "bottomright", colors = c("red","blue"), labels = c("Routes before flooding", "Routes after flooding"))

(The legend is showing the percentile of the population density distribution, from low to high. You can click on the polygon to see the actual number)

The center of the Charleston city have a very high population density, in which each tract has over 1000 people each kilometer. So the improvement of the street network in this area should be prioritized not only because a very densed population will be impacted, but also because the network is highly probably located in a busy area with many businesses connected, as we can induced from the population density.

To further narrow down our priorities on improvements of street segments, we can over lay the anlysis with the betweenness centrality result, which is telling us which roads are most frequently lying on the “shortest paths” to all the possible destinations, not only restaurants.

# Edge betweenness
bet_pal_edge <- colorNumeric(palette = "PuRd", domain = betweenness_char %>% activate("edges") %>% pull(edge_bc), n = 6)

# Node betweenness
bet_pal_node <- colorNumeric(palette = "PuRd", domain = betweenness_char %>% activate("nodes") %>% pull(node_bc), n = 6)


# Map
leaflet() %>% 
  addProviderTiles(providers$CartoDB.DarkMatter) %>%
  setView( -79.940918, 32.784618, zoom = 14) %>% # zooming in to show more details
  addPolylines(data = betweenness_char %>% st_as_sf("edges"), 
               color = ~bet_pal_edge(betweenness_char %>% st_as_sf('edges') %>% pull(edge_bc)), weight = 6, opacity = 0.7) %>% 
  addCircles(data = betweenness_char %>% st_as_sf("nodes"), 
               fillColor = ~bet_pal_node(betweenness_char %>% st_as_sf('nodes') %>% pull(node_bc)), stroke = F, fillOpacity = 0.7, 
             radius = betweenness_char %>% st_as_sf("nodes") %>% with(.$node_bc/(max(.$node_bc)/100))) %>%  
# denominator is selected to make the max value roughly equal to 100

  # Chosen edges
  addPolylines(data = pop_nets_before %>% st_as_sf("edges"), color = "red", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_before %>% st_as_sf("nodes"), stroke = F, fillColor = "red", fillOpacity = 0.8, radius = 20) %>% 

  # Chosen edges
  addPolylines(data = pop_nets_after %>% st_as_sf("edges"), color = "blue", weight = 3, opacity = 0.5) %>% 
  # Chosen nodes
  addCircles(data = pop_nets_after %>% st_as_sf("nodes"), stroke = F, fillColor = "blue", fillOpacity = 0.8, radius = 20) %>% 
  addLegend(position = "bottomright", colors = c("red","blue"), labels = c("Routes before flooding", "Routes after flooding"))
snapshot of priority of the improvement of street network because I could not render this file with many heavy leaflet maps
snapshot of priority of the improvement of street network because I could not render this file with many heavy leaflet maps

So zoom the map into the city center (our prioritized area), we you see that the red segments, with the “fat” nodes are the main road segments we want to start our further investigation because:

  1. These segments are impacted by the flood and were left out in the “after-flooding” shortest paths selection.

  2. They are the segments that are critically important because they ought to be part of the shortest routes to all possible destination if the street network in intact, in other words, if the street network is not flooded.