Repository: toddwschneider/shiny-salesman Branch: master Commit: 229b5bcc41a1 Files: 11 Total size: 15.8 KB Directory structure: gitextract_crelo5c4/ ├── .gitignore ├── LICENSE ├── README.md ├── data/ │ ├── cities.rds │ ├── distance_matrix.rds │ ├── great_circles.rds │ └── usa_cities.rds ├── helpers.R ├── server.R ├── ui.R └── www/ └── custom_styles.css ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .Rapp.history shinyapps ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. ================================================ FILE: README.md ================================================ A Shiny app to solve the traveling salesman problem with simulated annealing. Check out the full post here: https://toddwschneider.com/posts/traveling-salesman-with-simulated-annealing-r-and-shiny/ To run on your local machine, paste the following into your R console: ```R install.packages(c("shiny", "maps", "geosphere"), repos="http://cran.rstudio.com/") library(shiny) runGitHub("shiny-salesman", "toddwschneider") ``` ![](http://images.rapgenius.com/0e1ca854cbc30f33abc46108f2ba38f2.640x640x42.gif) ================================================ FILE: helpers.R ================================================ miles_per_meter = 100 / 2.54 / 12 / 5280 if (!exists("all_cities")) all_cities = readRDS("data/cities.rds") if (!exists("usa_cities")) usa_cities = readRDS("data/usa_cities.rds") generate_random_cities = function(n = 10, min_dist = 250, usa_only=FALSE) { if (usa_only) { candidates = usa_cities } else { candidates = all_cities } cities = candidates[sample(nrow(candidates), 1),] candidates = subset(candidates, !(full.name %in% cities$full.name)) i = 0 while (nrow(cities) < n & i < nrow(all_cities)) { candidate = candidates[sample(nrow(candidates), 1),] candidate_dist_matrix = distm(rbind(cities, candidate)[, c("long", "lat")]) * miles_per_meter if (min(candidate_dist_matrix[candidate_dist_matrix > 0]) > min_dist) { cities = rbind(cities, candidate) candidates = subset(candidates, !(candidates$full.name %in% cities$full.name)) } i = i + 1 } cities = cities[order(cities$full.name),] cities$n = 1:nrow(cities) return(cities) } plot_base_map = function(map_name="world") { margins = c(3.5, 0, 3.5, 0) if (map_name == "world") { map("world", col="#f3f3f3", fill=TRUE, lwd=0.2, mar=margins) } else if (map_name == "usa") { map("usa", col="#f3f3f3", border=FALSE, fill=TRUE, mar=margins) #, projection="albers", parameters=c(29.5, 45.5)) map("state", add=TRUE, col="#999999", fill=FALSE) #, projection="albers", parameters=c(29.5, 45.5)) } } plot_city_map = function(cities, map_name="world", label_cities=TRUE) { plot_base_map(map_name) # TODO: maptools pointLabel() for better label placement map.cities(cities, pch=19, cex=1.1, label=label_cities) } plot_tour = function(cities, tour, great_circles, map_name="world", label_cities=TRUE) { plot_city_map(cities, map_name, label_cities=label_cities) if (length(tour) > 1) { closed_tour = c(tour, tour[1]) keys = apply(embed(closed_tour, 2), 1, function(row) paste(sort(row), collapse="_")) invisible(sapply(great_circles[keys], lines, lwd=0.8)) } } calculate_great_circles = function(cities) { great_circles = list() if (nrow(cities) == 0) return(great_circles) pairs = combn(cities$n, 2) for(i in 1:ncol(pairs)) { key = paste(sort(pairs[,i]), collapse="_") pair = subset(cities, n %in% pairs[,i]) pts = gcIntermediate(c(pair$long[1], pair$lat[1]), c(pair$long[2], pair$lat[2]), n=25, addStartEnd=TRUE, breakAtDateLine=TRUE, sp=TRUE) great_circles[[key]] = pts } return(great_circles) } calculate_tour_distance = function(tour, distance_matrix) { sum(distance_matrix[embed(c(tour, tour[1]), 2)]) } current_temperature = function(iter, s_curve_amplitude, s_curve_center, s_curve_width) { s_curve_amplitude * s_curve(iter, s_curve_center, s_curve_width) } s_curve = function(x, center, width) { 1 / (1 + exp((x - center) / width)) } run_intermediate_annealing_process = function(cities, distance_matrix, tour, tour_distance, best_tour, best_distance, starting_iteration, number_of_iterations, s_curve_amplitude, s_curve_center, s_curve_width) { n_cities = nrow(cities) for(i in 1:number_of_iterations) { iter = starting_iteration + i temp = current_temperature(iter, s_curve_amplitude, s_curve_center, s_curve_width) candidate_tour = tour swap = sample(n_cities, 2) candidate_tour[swap[1]:swap[2]] = rev(candidate_tour[swap[1]:swap[2]]) candidate_dist = calculate_tour_distance(candidate_tour, distance_matrix) if (temp > 0) { ratio = exp((tour_distance - candidate_dist) / temp) } else { ratio = as.numeric(candidate_dist < tour_distance) } if (runif(1) < ratio) { tour = candidate_tour tour_distance = candidate_dist if (tour_distance < best_distance) { best_tour = tour best_distance = tour_distance } } } return(list(tour=tour, tour_distance=tour_distance, best_tour=best_tour, best_distance=best_distance)) } ensure_between = function(num, min_allowed, max_allowed) { max(min(num, max_allowed), min_allowed) } seed_cities = c( "Buenos Aires, Argentina", "Sydney, Australia", "Rio de Janeiro, Brazil", "Montreal, Canada", "Beijing, China", "Moroni, Comoros", "Cairo, Egypt", "Paris, France", "Athens, Greece", "Budapest, Hungary", "Reykjavik, Iceland", "Delhi, India", "Baghdad, Iraq", "Rome, Italy", "Tokyo, Japan", "Bamako, Mali", "Mexico City, Mexico", "Kathmandu, Nepal", "Oslo, Norway", "Port Moresby, Papua New Guinea", "Lima, Peru", "Kigali, Rwanda", "San Marino, San Marino", "Singapore, Singapore", "Moscow, Russia", "Colombo, Sri Lanka", "Bangkok, Thailand", "Istanbul, Turkey", "London, UK", "New York, USA" ) ================================================ FILE: server.R ================================================ library(shiny) library(maps) library(geosphere) source("helpers.R") shinyServer(function(input, output, session) { vals = reactiveValues() map_name = reactive({ tolower(input$map_name) }) set_random_cities = reactive({ input$set_random_cities + input$set_random_cities_2 }) city_choices = reactive({ if (map_name() == "world") { return(all_cities) } else if (map_name() == "usa") { return(usa_cities) } }) update_allowed_cities = observe({ if (isolate(input$go_button) == 0 & isolate(set_random_cities()) == 0 & map_name() == "world") return() updateSelectizeInput(session, "cities", choices=city_choices()$full.name) }, priority=500) one_time_initialization = observe({ isolate({ cty = subset(city_choices(), full.name %in% seed_cities) cty$n = 1:nrow(cty) updateSelectizeInput(session, "cities", selected=cty$full.name) vals$cities = cty vals$distance_matrix = readRDS("data/distance_matrix.rds") vals$great_circles = readRDS("data/great_circles.rds") }) }, priority=1000) set_cities_randomly = observe({ if (set_random_cities() == 0 & map_name() == "world") return() run_annealing_process$suspend() isolate({ if (map_name() == "world") { cty = generate_random_cities(n=20, min_dist=500) } else if (map_name() == "usa") { cty = generate_random_cities(n=20, min_dist=50, usa_only=TRUE) } cty$n = 1:nrow(cty) updateSelectizeInput(session, "cities", selected=cty$full.name) vals$cities = cty }) }, priority=100) set_cities_from_selected = observe({ if (input$go_button == 0) return() run_annealing_process$suspend() isolate({ cty = subset(city_choices(), full.name %in% input$cities) if (nrow(cty) == 0 | identical(sort(cty$full.name), sort(vals$cities$full.name))) return() cty$n = 1:nrow(cty) vals$cities = cty }) }, priority=50) set_dist_matrix_and_great_circles = observe({ if (input$go_button == 0 & set_random_cities() == 0 & map_name() == "world") return() isolate({ if (nrow(vals$cities) < 2) return() if (identical(sort(vals$cities$name), sort(colnames(vals$distance_matrix)))) return() dist_mat = distm(vals$cities[,c("long", "lat")]) * miles_per_meter dimnames(dist_mat) = list(vals$cities$name, vals$cities$name) vals$distance_matrix = dist_mat vals$great_circles = calculate_great_circles(vals$cities) }) }, priority=40) setup_to_run_annealing_process = observe({ input$go_button set_random_cities() map_name() isolate({ vals$tour = sample(nrow(vals$cities)) vals$tour_distance = calculate_tour_distance(vals$tour, vals$distance_matrix) vals$best_tour = c() vals$best_distance = Inf vals$s_curve_amplitude = ensure_between(input$s_curve_amplitude, 0, 1000000) vals$s_curve_center = ensure_between(input$s_curve_center, -1000000, 1000000) vals$s_curve_width = ensure_between(input$s_curve_width, 1, 1000000) vals$total_iterations = ensure_between(input$total_iterations, 1, 1000000) vals$plot_every_iterations = ensure_between(input$plot_every_iterations, 1, 1000000) vals$number_of_loops = ceiling(vals$total_iterations / vals$plot_every_iterations) vals$distances = rep(NA, vals$number_of_loops) vals$iter = 0 }) run_annealing_process$resume() }, priority=20) run_annealing_process = observe({ qry = parseQueryString(session$clientData$url_search) if (input$go_button == 0 & is.null(qry$auto)) return() if (nrow(isolate(vals$cities)) < 2) return() isolate({ intermediate_results = run_intermediate_annealing_process( cities = vals$cities, distance_matrix = vals$distance_matrix, tour = vals$tour, tour_distance = vals$tour_distance, best_tour = vals$best_tour, best_distance = vals$best_distance, starting_iteration = vals$iter, number_of_iterations = vals$plot_every_iterations, s_curve_amplitude = vals$s_curve_amplitude, s_curve_center = vals$s_curve_center, s_curve_width = vals$s_curve_width ) vals$tour = intermediate_results$tour vals$tour_distance = intermediate_results$tour_distance vals$best_tour = intermediate_results$best_tour vals$best_distance = intermediate_results$best_distance vals$iter = vals$iter + vals$plot_every_iterations vals$distances[ceiling(vals$iter / vals$plot_every_iterations)] = intermediate_results$tour_distance }) if (isolate(vals$iter) < isolate(vals$total_iterations)) { invalidateLater(0, session) } else { isolate({ vals$tour = vals$best_tour vals$tour_distance = vals$best_distance }) } }, priority=10) output$map = renderPlot({ plot_tour(vals$cities, vals$tour, vals$great_circles, map_name=tolower(input$map_name), label_cities=input$label_cities) if (length(vals$tour) > 1) { pretty_dist = prettyNum(vals$tour_distance, big.mark=",", digits=0, scientific=FALSE) pretty_iter = prettyNum(vals$iter, big.mark=",", digits=0, scientific=FALSE) pretty_temp = prettyNum(current_temperature(vals$iter, vals$s_curve_amplitude, vals$s_curve_center, vals$s_curve_width), big.mark=",", digits=0, scientific=FALSE) plot_title = paste0("Distance: ", pretty_dist, " miles\n", "Iterations: ", pretty_iter, "\n", "Temperature: ", pretty_temp) title(plot_title) } }, height=550) output$annealing_schedule = renderPlot({ xvals = seq(from=0, to=vals$total_iterations, length.out=100) yvals = current_temperature(xvals, vals$s_curve_amplitude, vals$s_curve_center, vals$s_curve_width) plot(xvals, yvals, type='l', xlab="iterations", ylab="temperature", main="Annealing Schedule") points(vals$iter, current_temperature(vals$iter, vals$s_curve_amplitude, vals$s_curve_center, vals$s_curve_width), pch=19, col='red') }, height=260) output$distance_results = renderPlot({ if (all(is.na(vals$distances))) return() xvals = vals$plot_every_iterations * (1:vals$number_of_loops) plot(xvals, vals$distances, type='o', pch=19, cex=0.7, ylim=c(0, max(vals$distances, na.rm=TRUE)), xlab="iterations", ylab="current tour distance", main="Evolution of Current Tour Distance") }, height=260) session$onSessionEnded(function() { run_annealing_process$suspend() set_cities_randomly$suspend() }) }) ================================================ FILE: ui.R ================================================ library(shiny) if (!exists("all_cities")) all_cities = readRDS("data/cities.rds") if (!exists("usa_cities")) usa_cities = readRDS("data/usa_cities.rds") shinyUI(fluidPage( tags$head( tags$link(rel="stylesheet", type="text/css", href="custom_styles.css") ), title = "Traveling Salesman with Simulated Annealing, Shiny, and R", tags$h2(tags$a(href="/traveling-salesman", "Traveling Salesman", target="_blank")), plotOutput("map", height="550px"), fluidRow( column(5, tags$ol( tags$li("Customize the list of cities, based on the world or US map"), tags$li("Adjust simulated annealing parameters to taste"), tags$li("Click the 'solve' button!") ) ), column(3, tags$button("SOLVE", id="go_button", class="btn btn-info btn-large action-button shiny-bound-input") ), column(3, HTML("") ), class="aaa" ), hr(), fluidRow( column(5, h4("Choose a map and which cities to tour"), selectInput("map_name", NA, c("World", "USA"), "World", width="100px"), p("Type below to select individual cities, or", actionButton("set_random_cities", "set randomly", icon=icon("refresh"))), selectizeInput("cities", NA, all_cities$full.name, multiple=TRUE, width="100%", options = list(maxItems=30, maxOptions=100, placeholder="Start typing to select some cities...", selectOnTab=TRUE, openOnFocus=FALSE, hideSelected=TRUE)), checkboxInput("label_cities", "Label cities on map?", FALSE) ), column(2, h4("Simulated Annealing Parameters"), inputPanel( numericInput("s_curve_amplitude", "S-curve Amplitude", 4000, min=0, max=10000000), numericInput("s_curve_center", "S-curve Center", 0, min=-1000000, max=1000000), numericInput("s_curve_width", "S-curve Width", 3000, min=1, max=1000000), numericInput("total_iterations", "Number of Iterations to Run", 25000, min=0, max=1000000), numericInput("plot_every_iterations", "Draw Map Every N Iterations", 1000, min=1, max=1000000) ), class="numeric-inputs" ), column(5, plotOutput("annealing_schedule", height="260px"), plotOutput("distance_results", height="260px") ) ) )) ================================================ FILE: www/custom_styles.css ================================================ .recalculating { opacity: 1 !important; } .numeric-inputs input { width: 75px; } #go_button, #set_random_cities_2 { width: 100%; margin-bottom: 10px; } hr { margin: 8px 0; }