I am currently developing the ompr package to model mixed integer linear programs. In order to debug the package I try to implement various optimization models and see how the package behaves.

Boris Johnson said in an interview that “it would really take me too long to engage in a fully global itinerary of apology to all concerned” [reuters]. Indy100 compiled a map of all countries he has offended so far.

So it seems like this would be a fun example to test a larger TSP model and compute the distance minimal roundtrip visiting all capital cities. I hope nobody feels offended by this :)

Get the data

First step is to get a list of countries and their capitals that Boris Johnson offended.

library(dplyr)
library(maps)
countries <- c("Canada", "USA", "Guyana", "Belize",
               "Ireland", "UK", "France", "Germany", "Netherlands", "Russia",
               "Sierra Leone", "Ghana", "Nigeria", "Cameroon", "Congo Democratic Republic",
               "Uganda", "Rwanda", "Kenya", "Tanzania", "Zambia",
               "Malawi", "Mozambique", "Zimbabwe", "Botswana", "Namibia", "Swaziland",
               "Lesotho", "South Africa",
               "Turkey", "Syria", "Iran", "Pakistan", "India", "China", "Japan", "Bangladesh",
               "Malaysia", "Papua New Guinea",
               "Australia", "New Zealand")
capitals <- world.cities %>% 
  filter(country.etc %in% countries, capital == 1) %>% 
  arrange(country.etc) %>% 
  mutate(id = row_number())

Second step is to construct a distance matrix for all capitals. The geosphere package has a handy method. It uses the Haversine distance in meters for all pairs of points.

distance <- geosphere::distm(as.matrix(dplyr::select(capitals, long, lat))) %>% 
  round

Build the model

Instead of the MTZ model we use a model with flow constraints as suggested on OR-exchange. Suprisingly this yields a better LP lower bound and it enables us to solve a TSP of 40 cities without using the classic sub-tour elimination constraints through callbacks (which ompr does not support yet).

library(ompr)
n <- nrow(capitals)
# Model based on the answer by Alan Erera at http://www.or-exchange.com/questions/11784/solving-tsp-using-solvers/11943
model <- MIPModel() %>%
  
  # we create a variable that is 1 iff we travel from city i to j
  add_variable(y[i, j], i = 1:n, j = 1:n, type = "binary") %>%
  
  # flow from i to j
  add_variable(x[i, j], i = 1:n, j = 1:n, lb = 0, ub = n - 1) %>%
  
  # minimize travel distance
  set_objective(sum_exp(distance[i, j] * y[i, j], i = 1:n, j = 1:n), "min") %>%
  
  # you cannot go to the same city
  add_constraint(y[i, i], "==", 0, i = 1:n) %>%
  
  # leave each city
  add_constraint(sum_exp(y[i, j], j = 1:n), "==", 1, i = 1:n) %>%
  
  # visit each city
  add_constraint(sum_exp(y[i, j], i = 1:n), "==", 1, j = 1:n) %>%
  
  # ensure the flow
  add_constraint(x[i, j], "<=", (n - 1) * y[i, j], i = 1:n, j = 1:n) %>%
  
  # each node consumes -1
  add_constraint(sum_exp(x[j, i], j = 1:n) , "==", sum_exp(x[i, j], j = 1:n) + 1, i = 2:n) %>% 
  
  # source supply
  add_constraint(sum_exp(x[1, j], j = 1:n), "==", n - 1)
  
model
## Mixed linear integer optimization problem
## Variables:
##   Continuous: 1600 
##   Integer: 0 
##   Binary: 1600 
## Search direction: minimize 
## Constraints: 1760

Solve it

We solve the model using Symphony as it seems to be generally faster than GLPK. ompr.roi is a solver interface to the ROI package that offers a common interface to various popular solvers.

library(ompr.roi)
library(ROI.plugin.symphony)
# I saved the result in a rds file as it takes a long time to compute the optimal solution. Comment out the following line to start the computation.
#result <- solve_model(model, with_ROI(solver = "symphony", verbose = TRUE))
# saveRDS(result, "opt_result.rds")
result <- readRDS("opt_result.rds")

Plot it

The following code extracts the results of the y variable from the solution.

solution <- get_solution(result, y[i, j]) %>% 
  filter(value > 0)
head(solution)
##   variable  i j value
## 1        y 27 1     1
## 2        y 13 2     1
## 3        y 12 3     1
## 4        y 31 4     1
## 5        y  8 5     1
## 6        y 38 6     1

Now we link the result to the capitals and convert it to a format that ggplot2’s geom_path can handle.

paths <- select(solution, i, j) %>% 
  rename(from = i, to = j) %>% 
  mutate(trip_id = row_number()) %>% 
  tidyr::gather(property, idx_val, from:to) %>% 
  mutate(idx_val = as.integer(idx_val)) %>% 
  inner_join(capitals, by = c("idx_val" = "id")) %>% 
  arrange(trip_id)
head(paths)
##   trip_id property idx_val         name      country.etc     pop    lat
## 1       1     from      27 Port Moresby Papua New Guinea  289861  -9.48
## 2       1       to       1     Canberra        Australia  324736 -35.31
## 3       2     from      13     Ni Dilli            India  321883  28.60
## 4       2       to       2        Dhaka       Bangladesh 6724976  23.70
## 5       3     from      12   Georgetown           Guyana  236878   6.79
## 6       3       to       3     Belmopan           Belize   14590  17.25
##     long capital
## 1 147.18       1
## 2 149.13       1
## 3  77.22       1
## 4  90.39       1
## 5 -58.16       1
## 6 -88.79       1

Finally the map.

library(ggplot2)
library(ggalt)
library(ggthemes)
library(ggmap)
world <- map_data("world") %>% filter(region != "Antarctica")
ggplot(data = paths, aes(long, lat)) + 
  geom_map(data = world, map = world, aes(long, lat, map_id = region), 
           fill = "white", color = "darkgray", alpha = 0.8, size = 0.2) + 
  geom_path(aes(group = trip_id), color = "#E41A1C") + 
  geom_point(data = capitals, color = "#E41A1C", size = 0.8) + 
  theme_map() + 
  coord_proj("+proj=robin +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs") + 
  ggtitle("Shortest fully global itinerary of apology", 
          subtitle = paste0(format(round(result@objective_value/ 1000), big.mark = ","), " km"))

# projection code from 
# http://gis.stackexchange.com/a/186712 by hrbrmstr (https://gis.stackexchange.com/users/29544/hrbrmstr)

License

This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.

In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org/