{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The Traveling Salesperson Problem\n",
    "\n",
    "Consider the [*Traveling Salesperson Problem*](http://en.wikipedia.org/wiki/Traveling_salesman_problem) (or TSP): \n",
    "\n",
    "> *Given a set of cities and the distance between each pair of cities, what is the shortest possible tour that visits each city exactly once, and returns to the starting city?*\n",
    "\n",
    "In this notebook we will develop some solutions to the problem, and more generally show *how to think about* solving  problems. The algorithms developed here are used in [serious applications](https://research.googleblog.com/2016/09/the-280-year-old-algorithm-inside.html) that millions of people rely on every day.\n",
    "\n",
    "|![](http://support.sas.com/documentation/cdl/en/ornoaug/66084/HTML/default/images/map002g.png)|\n",
    "|---|\n",
    "|[An example tour](http://www.math.uwaterloo.ca/tsp/history/pictorial/dfj.html)|\n",
    "\n",
    "Do we understand the problem statement well enough to program a solution? Let's check:\n",
    "\n",
    "- ***Given a set of cities***\n",
    "<br>A Python `set` could represent a set of cities. An individual city might be just an integer index, or it might be (x, y) coordinates.\n",
    "- ... ***and the distance between each pair of cities***: \n",
    "<br>We could use either a function, `distance(A, B),` or a table, `distance[A, B]`.\n",
    "- ... ***what is the shortest possible tour***\n",
    "<br>A tour is a sequential order in which to visit the cities; a function `shortest_tour(tours)` should find the one that minimizes `tour_length(tour)`, which is the sum of the distances between adjacent cities in the tour. \n",
    "- ... ***that visits each city once and returns to the starting city***\n",
    "<br>Make sure a tour doesn't re-visit a city (except returning to the start). \n",
    "\n",
    "\n",
    "\n",
    "I don't yet have all the answers, but I'm ready to attack the problem. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Imports used in this notebook. This is Python 3 on Jupyter with matplotlib.\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import random\n",
    "from time        import clock \n",
    "from itertools   import permutations, combinations\n",
    "from functools   import lru_cache as cache\n",
    "from collections import Counter\n",
    "from statistics  import mean, median"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exhaustive Search Algorithm: `exhaustive_tsp`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's start with an algorithm that is *guaranteed* to solve the problem, although inefficiently:\n",
    "\n",
    "> **Exhaustive Search Algorithm**: *Generate all possible tours of the cities, and choose the shortest tour (the one with minimum tour length).*\n",
    "\n",
    "My design philosophy is to first write an English description of the algorithm (as above), then write Python code that closely mirrors the English description. This will probably require some auxilliary functions and data structures; just assume they exist; put them on a TO DO list, and eventually define them with the same design philosophy:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def exhaustive_tsp(cities):\n",
    "    \"Generate all possible tours of the cities and choose the shortest tour.\"\n",
    "    return shortest_tour(alltours(cities))\n",
    "\n",
    "def shortest_tour(tours): return min(tours, key=tour_length)\n",
    "\n",
    "# TO DO: Data types: City, Cities, Tour; Functions: alltours, tour_length"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This gives us a good start; the Python code closely matches the English description.  Now for the TO DO list.\n",
    "\n",
    "**Tours:** A tour that starts in city `1`, moves to `2`, then `3`, then back to `1` will be represented by  `(1, 2, 3)`. Any valid tour of a set of cities will be a *permutation* of the cities. That means we can implement `alltours` with the built-in `permutations` function (from the `itertools` module). \n",
    "The length of a tour is the sum of the distances between adjacent cities in the tour&mdash;the sum of the lengths of the **links** between cities in the tour. \n",
    "\n",
    "**Cities:** the only thing we need to know about a city is its distance to other cities. We don't need to know the city's name, population, best restaurants, or anything else.  We'll assume the distance between two cities is the [Euclidean distance](http://en.wikipedia.org/wiki/Euclidean_distance), the straight-line distance between points in a two-dimensional plane. So I want `City(300, 100)` to be the city with x-coordinate 300 and y coordinate 100. At first glance it seems like Python does not have a builtin type for a point in the two-dimensional plane, but actually there is one: complex numbers. I'll implement `City` with `complex`, which means the distance between two cities, `distance(A, B)`, is the absolute value of the vector difference between them. \n",
    "I'll also define `Cities(n)` to make a set of `n` random cities. I want `Cities(n)` to be reproducible (to return the same result when called with the same arguments), so I provide an optional argument that sets `random.seed`. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "alltours = permutations \n",
    "\n",
    "def tour_length(tour):\n",
    "    \"\"\"The total of distances between each pair of consecutive cities in the tour.\n",
    "    This includes the last-to-first, distance(tour[-1], tour[0])\"\"\"\n",
    "    return sum(distance(tour[i - 1], tour[i]) \n",
    "               for i in range(len(tour)))\n",
    "\n",
    "City = complex\n",
    "\n",
    "def distance(A, B): return abs(A - B)\n",
    "\n",
    "def Cities(n, seed=123, width=999, height=666):\n",
    "    \"Make a set of n cities, sampled uniformly from a (width x height) rectangle.\"\n",
    "    random.seed((n, seed))\n",
    "    return frozenset(City(random.randint(1, width), random.randint(1, height))\n",
    "                     for c in range(n))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A solution!\n",
    "\n",
    "Now we're ready: `exhaustive_tsp` can find a tour for a set of cities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((158+421j),\n",
       " (297+397j),\n",
       " (832+102j),\n",
       " (872+207j),\n",
       " (817+315j),\n",
       " (939+600j),\n",
       " (620+498j),\n",
       " (163+639j),\n",
       " (31+501j))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exhaustive_tsp(Cities(9))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Quick, is that the shortest tour?  I can't tell. But this should help:\n",
    "\n",
    "## Visualizing results: `plot_tour` and `do`\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def plot_tour(tour, style='bo-'): \n",
    "    \"Plot every city and link in the tour, and highlight start city.\"\n",
    "    if len(tour) > 1000: plt.figure(figsize=(15, 10))\n",
    "    start = tour[0:1]\n",
    "    plot_segment(tour + start, style)\n",
    "    plot_segment(start, 'rD') # start city is red Diamond.\n",
    "    \n",
    "def plot_segment(segment, style='bo-'):\n",
    "    \"Plot every city and link in the segment.\"\n",
    "    plt.plot([X(c) for c in segment], [Y(c) for c in segment], style, clip_on=False)\n",
    "    plt.axis('scaled')\n",
    "    plt.axis('off')\n",
    "    \n",
    "def X(city): \"X coordinate.\"; return city.real\n",
    "def Y(city): \"Y coordinate.\"; return city.imag"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 10460 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x112964400>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_tour(exhaustive_tsp(Cities(9)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That looks much better!  It certainly looks like the shortest possible tour, although I can't prove it. \n",
    "\n",
    "*Vocabulary note:* A **segment** is a portion of a tour that does not loop back to the start. The **segment** `(1, 2, 3)` has only two links, 1-2 and 2-3, whereas the **tour** `(1, 2, 3)` has three links, because it includes the link back to the start, 3-1.\n",
    "\n",
    "One more convenience: the function `do` runs a TSP algorithm on a set of cities, plots the tour, asserts it is valid, and prints summary information. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def do(algorithm, cities):\n",
    "    \"Apply a TSP algorithm to cities, plot the result, and print info.\"\n",
    "    t0   = clock()\n",
    "    tour = algorithm(cities)\n",
    "    t1   = clock()\n",
    "    assert Counter(tour) == Counter(cities) # Every city appears exactly once in tour\n",
    "    plot_tour(tour)\n",
    "    print(\"{}: {} cities ⇒ tour length {:.0f} (in {:.3f} sec)\".format(\n",
    "          name(algorithm), len(tour), tour_length(tour), t1 - t0))\n",
    "    \n",
    "def name(algorithm): return algorithm.__name__.replace('_tsp', '')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "exhaustive: 9 cities ⇒ tour length 2450 (in 1.049 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 10460 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114cc1dd8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(exhaustive_tsp, Cities(9))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimization: non-redundant  `alltours`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We said there are *n*! tours of *n* cities, and thus 6 tours of 3 cities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(alltours({1, 2, 3}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "But this is redundant: `(1, 2, 3)`, `(2, 3, 1)`, and `(3, 1, 2)` are three ways of describing the same tour. So let's arbitrarily say that a tour must start with the first city in the set of cities.  While we're redefining `alltours`, we'll take the opportunity to define a tour as a *list* rather than a *tuple*. It doesn't matter now, but I anticipate wanting to represent *partial* tours, to which we will append cities one by one; appending can be done to lists, but not tuples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def alltours(cities):\n",
    "    \"Return a list of non-redundant tours (permutations of cities).\"\n",
    "    start, *others = cities\n",
    "    return [[start] + Tour(perm) for perm in permutations(others)]\n",
    "    \n",
    "Tour = list  # A Tour is a list of cities"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can verify that for 3 cities there are now only 2 tours, and that `exhaustive_tsp` can now do 10 cities in about the time it took to do 9 before:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 2, 3], [1, 3, 2]]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "alltours({1, 2, 3})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "exhaustive: 10 cities ⇒ tour length 2720 (in 1.466 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 9120 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114d33cf8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(exhaustive_tsp, Cities(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# General Strategies\n",
    "\n",
    "It takes Exhaustive Search 1 or 2 seconds to solve a 10-city problem. Since it looks at all permutations, an 11-city problem would take about 11 times longer, and a 15-city problem would take days.\n",
    "There must be a better way ... \n",
    "\n",
    "To get inspired, here are some general  strategies for algorithm design: \n",
    "\n",
    "* **Brute Force Strategy**: The strategy used for `exhaustive_tsp`; as [Ken Thompson](https://en.wikipedia.org/wiki/Ken_Thompson) [says](https://www.brainyquote.com/quotes/ken_thompson_185574?src=t_brute_force), *\"when in doubt, use brute force.\"*\n",
    "* **Approximation Strategy**: If it is too hard to find a precise, optimal solution, consider finding an approximate, suboptimal solution.\n",
    "* **Greeedy Strategy**: To complete a multiple step problem, first do the step that has the best gain. Repeat. \n",
    "* **Iterative Improvement Strategy**: Use an existing algorithm to create a solution, then have another algorithm improve the solution.\n",
    "* **Ensemble Strategy**: Apply a set of algorithms to the problem, and pick the best solution. \n",
    "* **Divide and Conquer Strategy**: Split the problem in half, solve each half, and combine the two partial solutions.\n",
    "* **Stand on the Shoulders of Giants Strategy**: Find out what other people have done, and copy (or modify).\n",
    "\n",
    "Let's apply these strategies to develop some TSP algorithms.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Nearest Neighbor Algorithm: `nn_tsp`\n",
    "\n",
    "> **Nearest Neighbor Algorithm:** *Start at some city; at each step extend the tour by moving from the previous city to its nearest neighbor that has not yet been visited.*\n",
    "\n",
    "This is an instance of both the **approximation strategy** and the **greedy strategy**, where we are being greedy about choosing the shortest link to a neighbor. So now, instead of considering all *n*! tours, we incrementally build a single tour. \n",
    "In  more detail:\n",
    "\n",
    "* ***Start at some city***  (pass the start city as an argument, or if `None`, use the first city in the set)\n",
    "* ***... at each step extend the tour*** (using `tour.append`)\n",
    "* ***... by moving from the previous city*** (`C`)\n",
    "* ***...to its nearest neighbor*** (as given by the function `nearest_neighbor`)\n",
    "* ***...that has not yet been visited*** (I will maintain a set of `unvisited` cities)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def nn_tsp(cities, start=None):\n",
    "    \"\"\"Start the tour at the given start city (default: first city); \n",
    "    at each step extend the tour by moving from the previous city \n",
    "    to its nearest neighbor that has not yet been visited.\"\"\"\n",
    "    C = start or first(cities)\n",
    "    tour = [C]\n",
    "    unvisited = set(cities - {C})\n",
    "    while unvisited:\n",
    "        C = nearest_neighbor(C, unvisited)\n",
    "        tour.append(C)\n",
    "        unvisited.remove(C)\n",
    "    return tour\n",
    "\n",
    "def first(collection): return next(iter(collection))\n",
    "\n",
    "def nearest_neighbor(A, cities):\n",
    "    \"Find the city in cities that is nearest to city A.\"\n",
    "    return min(cities, key=lambda C: distance(C, A))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "While `exhaustive_tsp` was limited to about a dozen cities, this algorithm can do thousands of cities in less than a second:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nn: 1998 cities ⇒ tour length 33688 (in 0.510 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 198972 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114cdf710>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(nn_tsp, Cities(2000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "(Note: I asked for 2000 cities but only got 1998 distinct ones&mdash;sometimes the random number generator produces the exact same city.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nn: 10 cities ⇒ tour length 2792 (in 0.000 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 9128 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114d5f2b0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(nn_tsp, Cities(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On `Cities(10)`, `nn_tsp` took almost no time, but the tour is not optimal: it is 3% longer than optimal. But that will vary, depending on the set of cities, and also depending on the starting city. So that gives me an idea: Just as with buying lottery tickets, we can improve our chance of winning by trying more often.\n",
    "\n",
    "## Repetitive Nearest Neighbor Algorithm: `rep_nn_tsp`\n",
    "\n",
    "> **Repetitive Nearest Neighbor Algorithm:** *Run the nearest neighbor algorithm repeatedly, each time with a different start city, and pick the resulting tour with the shortest total distance.*\n",
    "\n",
    "This is an instance of the **ensemble strategy**, because providing a different paramater to the function each time is like using a different algorithm each time. Which starting cities should we pick? I'll define a function to randomly `sample` the cities (and for reproducibility I'll give it a `seed` argument, as I did with `Cities`). The parameter *k* says how many cities to sample."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rep_nn_tsp(cities, k=25):\n",
    "    \"Repeat nn_tsp starting from k different cities; pick the shortest tour.\"\n",
    "    return shortest_tour(nn_tsp(cities, start) for start in sample(cities, k))\n",
    "\n",
    "def sample(population, k, seed=42):\n",
    "    \"Return a list of k elements sampled from population. Set random.seed.\"\n",
    "    if k >= len(population): \n",
    "        return population\n",
    "    else:\n",
    "        random.seed((k, seed))\n",
    "        return random.sample(population, k)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rep_nn: 10 cities ⇒ tour length 2720 (in 0.000 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 9140 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x115604518>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(rep_nn_tsp, Cities(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rep_nn: 1998 cities ⇒ tour length 32382 (in 12.480 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 195612 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x111bdf0b8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(rep_nn_tsp, Cities(2000))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's encouraging; it found the optimal tour for `Cities(10)` and it improved the `Cities(2000)` tour by 4%, although it does take *k* times longer to run. \n",
    "\n",
    "# Real Cities"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Random cities are boring to look at; I thought it would be fun to work on some *real* cities. I found a web page (now 404, but a copy is [here](https://raw.githubusercontent.com/norvig/pytudes/master/data/latlong.htm)) that lists coordinates of over 10,000 cities in the USA, in this format:\n",
    "\n",
    "    [TCL]  33.23   87.62  Tuscaloosa,AL\n",
    "    [FLG]  35.13  111.67  Flagstaff,AZ\n",
    "    [PHX]  33.43  112.02  Phoenix,AZ\n",
    "\n",
    "I define the function `parse_cities` to take an iterable of lines and build a `City` out of each line that matches the format (excluding Alaska and Hawaii)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "def continental_USA(line): \n",
    "    \"Is this a line of the form '[TLA]  long lat City,ST'?\"\n",
    "    return line.startswith('[') and ',AK' not in line and ',HI' not in line\n",
    "    \n",
    "def parse_cities(lines, keep=continental_USA, long_scale=-48, lat_scale=69):\n",
    "    \"\"\"Make a set of Cities from lines of text.\"\"\"\n",
    "    return frozenset(City(long_scale * ncol(line, 2), lat_scale  * ncol(line, 1))\n",
    "                     for line in lines if keep(line))\n",
    "\n",
    "def ncol(line, n): \"The number in the nth column\"; return float(line.split()[n])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You might be wondering about the `long_scale=-48, lat_scale=69` part. The issue is that we have latitude and longitude for cities, and we want to compute the distance between cities. To do that accurately requires [complicated trigonometry](http://en.wikipedia.org/wiki/Haversine_formula).  But we can get an approximation by assuming that latitude and longitude are on a flat rectangular grid. (This is a bad approximation if you're talking about distances of 10,000 miles, but close enough for distances of 100 miles, as long as you're not too near the poles.)  I took the latitude of the center of the USA (Wichita, KS: latitude 37.65) and plugged it into a [Length Of A Degree Of Latitude\n",
    "And Longitude Calculator](http://www.csgnetwork.com/degreelenllavcalc.html) to find that, in Wichita, one degree of latitude is 69 miles, and one degree of longitude is 48 miles.  (It is -48 rather than +48 because the USA is west of the prime meridian.) \n",
    "\n",
    "I also found a [blog post](http://www.randalolson.com/2015/03/08/computing-the-optimal-road-trip-across-the-u-s/) by Randal S. Olson, who chose 50 landmarks across the USA and found a tour based on actual road-travel distances, not straight-line distance; I would need a new `distance` function to handle that. William Cook provides an\n",
    "analysis, and a [tour that is shorter](http://www.math.uwaterloo.ca/tsp/usa50/index.html) than Randal's.\n",
    "\n",
    "Now let's fetch the file (with a shell command); parse it; and find a baseline nearest neighbor tour:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "! [ -e latlong.htm ] || curl -O https://raw.githubusercontent.com/norvig/pytudes/master/data/latlong.htm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nn: 1089 cities ⇒ tour length 52879 (in 0.158 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 131048 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1152f96d8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "USA = parse_cities(open('latlong.htm'))\n",
    "\n",
    "do(nn_tsp, USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Improving Bad Links\n",
    "\n",
    "There are some obviously bad (long) links in this tour. \n",
    "To understand the problem and how we might fix it, consider this simpler tour:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "nn: 10 cities ⇒ tour length 17 (in 0.000 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAABLCAYAAABgOHyfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAACKVJREFUeJzt3VuIVecZxvH/azQmM5npaJuqMx52MulBHMSEKmko3rS2hkINBloh04seqCl4YwmBkhQCHQo9QW5KjL3ITUJjL0rBi6ZFCkpJaRJoirGGxrNTHRMPURzjofHtxVqDe+/Z3ziHtde31prnBx+jo+79KM7jO6/fzJi7IyIi5TcndgAREcmGCl1EpCJU6CIiFaFCFxGpCBW6iEh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M7a7v5l/6myo0KVUzLprMDAEq9bAgkWwY637pWOxczW7lXNJL5w+Be88q5zTl1XOdLpv3t3Xn27gGK1XORNO90X4s5yb55OJzETyBrNpD+zoT27EjQKn95h1f6VIJdQ655MPK+f0ZJkznb6H07Nv/HO1nO43pN+umfEhLVc526/Dpldi/1mq0KVEBoZuvcFA8nJHP9z7N7Mifbj/9x+En/YpZ1ai57xJ8oFrR4AlJF94/JHGn9IDDDE+4+EhYDCHjIAKXUplSe+tN5gxncDFc8DOCIECLg5BZ1/j65Rz+sqQ88QQdK5ufF0nsLg3zxQqdCmR06eSd2XrS30UOLjfnd2RQo1jdvBbMLpaObNRhpzhjCOncg3i7jo6pTjQVYPBQ3DZwT15OXgIumqxsynn7M5ZlIy65SKlcusmweLeZPop+q0M5cxCGXIWIaMKXUSkIubEDiAiItlQoYuIVIQKXUSkIlToIiIVoUIXEakIFbqISEWo0EVEKkKFLiJSESp0EZGKUKGLiFSECl1EpCJU6CIiFaFCFxGpCBW6iEhFqNBFRCpChS4iUhH/B8lVHxulj8D5AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1152974a8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "cities10 = {City(x, 1) for x in range(0, 5)} | {City(x - 1.49, 0) for x in range(5, 10)}\n",
    "\n",
    "do(nn_tsp, cities10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Starting at the upper left, the tour goes to the right, picking up the 5 cities in a line, jogs downward, and continues to the right, picking up the remaining 5 cities. But then it has a long diagonal link back to the start. Once you've seen this type of configuration a few times it becomes clear: *any time a tour has an \"X\" where two links cross, we can shorten the tour by uncrossing the \"X\".* \n",
    "\n",
    "You can think of uncrossing the X as deleting two links and adding two new ones. Or you can think of it as **reversing a segment**: this tour visits the bottom 5 cities in left-to-right order; let's reverse that segment and visit them in right-to-left order:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "15.299342436137655"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAABLCAYAAABgOHyfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAACNtJREFUeJzt3VuMVeUZxvH/y0HqbGc6UKowgI4GiShHLWitNaBQhyubtKmm5aZpUtP2oqnxohf2oilJL1p6W23StElrondtbMqAAqJIOdTggYMtVHGUYaAK5TBUrPD2Yq2db61hBoZh7/3tvdbzS1YIM4T9hKzvzcPe6/vG3B0REWl942IHEBGR2tBAFxEpCA10EZGC0EAXESkIDXQRkYLQQBcRKQgNdBGRgmjYQDezznlmz5lZZ6NeU0SkTBoy0M0qPUtpG3gevrGUtgGzSk8jXvdKmXV0m937R7OvbUp+7eiOnWk4yllbrZJT5LLcva4XtPUsYcqF4+AOfhx8CVMuQFtPvV/7ynK2d8Pqg3DGk6hnPPl9e3fsbMqpnLp0jeYy9/pt/TezzqW0DfRydtLkzNdPAA/Rfn4X+56CmefqFuCKfG8V/HIuVDJfGwSe2A+/Xhcr1cWUs7ZGyrnyGfdtq2OlEhmLCfX8y++Ap58dMswBJgPPcXr8Mr77zT7++hTwUT1zjI5NzC9qSH8/EehvfJ6RKGdtjZRz0T1mzAf2uKMDj6Ql1HWg74XHHqXt4eEa+iNc92kfv9sO/ADYB6xLr9fcuVDPXMMxe30xDM6+uKm9scOdtY3OMxLlrK2Rc3Ie+DNwjRm9JPfmi+6cjBBTZHTq/Z7O5d5DB58EvgJ8Lfg+8GPgfwD/FvjURr331CrvpSpn43KCG/gc8B+C94KfBt8C/mPwheAWO78uXdmrru+hVyVPufCnZzk76VHazu2Er7oP9g7/Z7kJ6AFWAcuBtwnt/e/unK9fzo5umLcGpnXBQD/sedL91KF6vd5YKWdtjTanGW3AMpJ7cxVwLeTa+38al1rkYg0Z6JB8QHoH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plotlib.figure.Figure at 0x1153833c8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "tour = nn_tsp(cities10)\n",
    "\n",
    "tour[5:10] = reversed(tour[5:10])\n",
    "\n",
    "plot_tour(tour)\n",
    "tour_length(tour)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's an improvement! \n",
    "\n",
    "Below is a diagram to explain why uncrossing the X is *always* an improvement. Below the crossed lines that we will remove are dotted blue; the lines we will add are dashed red. We can see that two red-and-blue triangles are formed, and by the [triangle inequality](https://en.wikipedia.org/wiki/Triangle_inequality) each red line is shorter than the two parts of the blue lines that make up the rest of the triangle."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 5104 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1153a0f60>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_tour([tour[4], tour[5]], 'r--');  plot_tour([tour[5], tour[0]], 'b:')\n",
    "plot_tour([tour[0], tour[9]], 'r--');  plot_tour([tour[9], tour[4]], 'b:')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is difficult to get nearest neighbors to avoid  mistakes (like crossing an X), because in the middle of the tour, when the algorithm is forced to make a choice, it doesn't know where the rest of the tour will end up. So, rather than tackling the difficult task of *avoiding* the mistakes, the **iterative improvement strategy** says to go ahead and make mistakes, finish the tour, and then do the much easier task of *fixing* the mistakes. Why is it easier to fix the mistakes? Because we can see the whole tour, so we can propose a change and get a definitive answer: either the change makes the whole tour shorter or it doesn't. The strategy is called *iterative* because we do multiple improvements, if possible.\n",
    "\n",
    "The changes we propose will all consist of reversing segments; here is how we can check if reversing an arbitrary segment would be an improvement, and if it is, go ahead and do the reversal:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "def reverse_segment_if_improvement(tour, i, j):\n",
    "    \"If reversing tour[i:j] would make the tour shorter, then do it.\" \n",
    "    # Given tour [...A,B...C,D...], consider reversing B...C to get [...A,C...B,D...]\n",
    "    A, B, C, D = tour[i-1], tour[i], tour[j-1], tour[j % len(tour)]\n",
    "    # Are old links (AB + CD) longer than new ones (AC + BD)? If so, reverse segment.\n",
    "    if distance(A, B) + distance(C, D) > distance(A, C) + distance(B, D):\n",
    "        tour[i:j] = reversed(tour[i:j])\n",
    "        return True"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now I'll define `improve_tour` to consider various segments, and reverse the ones that improve the tour. What segments should we consider? I don't know how to be clever about that, but I do know how to use **brute force**: try every subsegment. (I have an intuition (from experience with [simulated annealing](https://en.wikipedia.org/wiki/Simulated_annealing)) that trying longer subsegments first would be better, so I'll write `subsegments` that way.) After I've tried all segments, if one of them did improve the tour that might open up new possibilities, so I'll repeat the process until there are no improvements, then return the improved tour:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "def improve_tour(tour):\n",
    "    \"Try to alter tour for the better by reversing segments.\"\n",
    "    while True:\n",
    "        improvements = {reverse_segment_if_improvement(tour, i, j)\n",
    "                        for (i, j) in subsegments(len(tour))}\n",
    "        if improvements == {None}:\n",
    "            return tour\n",
    "\n",
    "@cache()\n",
    "def subsegments(N):\n",
    "    \"Return (i, j) pairs denoting tour[i:j] subsegments of a tour of length N.\"\n",
    "    return [(i, i + length)\n",
    "            for length in reversed(range(2, N))\n",
    "            for i in reversed(range(N - length + 1))]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here are all the subsegments of a 5 city tour:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 5), (0, 4), (2, 5), (1, 4), (0, 3), (3, 5), (2, 4), (1, 3), (0, 2)]"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "subsegments(5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Improved Nearest Neighbor Algorithms\n",
    "\n",
    "Here are two ways of improving nearest neighbor algorithms&mdash;either improve the single nearest neighbor algorithm, or improve each candidate tour from the repetitive nearest neighbor algorithm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "def improve_nn_tsp(cities): \n",
    "    \"Improve the tour produced by nn_tsp.\"\n",
    "    return improve_tour(nn_tsp(cities))\n",
    "\n",
    "def rep_improve_nn_tsp(cities, k=5):\n",
    "    \"Run nn_tsp from k different starts, improve each tour; keep the best.\"\n",
    "    return shortest_tour(improve_tour(nn_tsp(cities, start)) \n",
    "                         for start in sample(cities, k))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "improve_nn: 10 cities ⇒ tour length 15 (in 0.000 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAABLCAYAAABgOHyfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAACNtJREFUeJzt3VuMVeUZxvH/y0HqbGc6UKowgI4GiShHLWitNaBQhyubtKmm5aZpUtP2oqnxohf2oilJL1p6W23StElrondtbMqAAqJIOdTggYMtVHGUYaAK5TBUrPD2Yq2db61hBoZh7/3tvdbzS1YIM4T9hKzvzcPe6/vG3B0REWl942IHEBGR2tBAFxEpCA10EZGC0EAXESkIDXQRkYLQQBcRKQgNdBGRgmjYQDezznlmz5lZZ6NeU0SkTBoy0M0qPUtpG3gevrGUtgGzSk8jXvdKmXV0m937R7OvbUp+7eiOnWk4yllbrZJT5LLcva4XtPUsYcqF4+AOfhx8CVMuQFtPvV/7ynK2d8Pqg3DGk6hnPPl9e3fs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rADfw28B+BbwA/Db4Ztv4cvt0HZxzck19XH4T27tiZ8/nbu5NcylnEnOCd4F8H/y14P/hBeO338J3+2BnV0KXpmVEBlsP318Iv5kAl891B4CeH4Ve7I8UbxuOL4WczlLNWmjqnAQvgp7PgCS7OuPIZ922rGxVmQqNeSGSsPNmo9Bezo49DZU7+uxXg5EfAbyJEG8HJNVCZkf+aco5dK+TsWwOVBfmvVYBpXY1MoYEuLeRIf9J6hrag/W+583ykUBcx2/8IDC5QztpohZwjZxxo7M9Tjf3+mC5do72a7b1U5VTOZsuo99ClpYQnCaZ1Je2n2Z/KUM5aaIWczZBRA11EpCDGxQ4gIiK1oYEuIlIQGugiIgWhgS4iUhAa6CIiBaGBLiJSEBroIiIFoYEuIlIQGugiIgWhgS4iUhAa6CIiBaGBLiJSEBroIiIFoYEuIlIQGugiIgWhgS4iUhD/B9l356pXaE21AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1153e0da0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(improve_nn_tsp, cities10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "improve_nn: 1089 cities ⇒ tour length 45489 (in 2.571 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 121712 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x111bd5fd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(improve_nn_tsp, USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not bad! A single call to `improve_tour` fixes the `cities10` problem, and on the USA map, uncrosses every X and saves over 7000 miles of travel! Let's try repetitions:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rep_improve_nn: 1089 cities ⇒ tour length 44500 (in 15.181 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 120488 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11524dfd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(rep_improve_nn_tsp, USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Even better! Could we do better still by trying more repetitions? Maybe, but there's a problem: `do` doesn't accept extra arguments, so I have no place to  change `rep_improve_nn_tsp`'s optional *k* parameter from the default value of 5. I could modify `do`, but instead I'll define a [higher-order function](https://en.wikipedia.org/wiki/Higher-order_function), `bind`, so that `bind(rep_improve_nn_tsp, 5)`  creates a new function, that, when called with the argument `cities`, calls `rep_improve_nn_tsp(cities, 5)`. (My `bind` does the same job as `functools.partial`, but also sets the function name of the newly created function.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache()\n",
    "def bind(fn, *extra):\n",
    "    \"Bind extra arguments; also assign .__name__\"\n",
    "    newfn = lambda *args: fn(*args, *extra)\n",
    "    newfn.__name__ = fn.__name__  + ''.join(', ' + str(x) for x in extra)\n",
    "    return newfn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "rep_improve_nn, 10: 1089 cities ⇒ tour length 44418 (in 32.362 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 120744 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1152d8c88>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(bind(rep_improve_nn_tsp, 10), USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We got a slight improvement, but we may be at the point of diminishing returns. Let's try something new.\n",
    "\n",
    "# Greedy Algorithm: `greedy_tsp`\n",
    "\n",
    "Let's return to the **greedy strategy**. We've already covered the Nearest Neighbor Algorithm, which follows the greedy strategy in always choosing the neighbor that is nearest to the last city in the tour. But one problem is that when you get near the end of the tour, you may be left with some very long links. Another way to be greedy is to always grab the shortest possible link, from among all the links between cities. That means we will no longer be building up a single tour, city by city; rather we will be maintaining a set of segments, and joining segments together by greedily choosing the shortest link:\n",
    "\n",
    "> **Greedy Algorithm:** *Maintain a set of segments; intially each city defines its own 1-city segment. Find the shortest possible link that connects two endpoints of two different segments, and join those segments with that link. Repeat until we form a single segment that tours all the cities.*\n",
    "\n",
    "On each step of the algorithm, we want to *\"find the shortest possible link that connects two endpoints.\"* That seems like an expensive operation to do on each step. So we will add in some data structures  to speed up the computation:  \n",
    "\n",
    "1. Pre-compute a list of links, sorted by shortest link first. A link is a pair of cities: `(A, B)`.\n",
    "2. Maintain a dict that maps **endpoints** to **segments**, e.g. `{A: [A, B, C], C: [A, B, C], D: [D]}` means that `A` and `C` are the endpoints of segment `[A, B, C]` and `D` is a 1-city segment. \n",
    "3. Go through the links in shortest-first order. Suppose `(B, D)` is the next shortest link. We can't use it, because `B` is already attached to `A` and `C`. But if `(A, D)` is the next shortest, that works: `A` and `D` are endpoints of different segments, so we can join the two segments together.  Update the endpoints dict to reflect this new segment: `{A: [D, A, B, C], D: [D, A, B, C]}`.\n",
    "4. Stop when the newly created segment contains all the cities.\n",
    "\n",
    "Here is the code:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [],
   "source": [
    "def greedy_tsp(cities):\n",
    "    \"\"\"Go through links, shortest first. Use a link to join segments if possible.\"\"\"\n",
    "    endpoints = {C: [C] for C in cities} # A dict of {endpoint: segment}\n",
    "    for (A, B) in shortest_links_first(cities):\n",
    "        if A in endpoints and B in endpoints and endpoints[A] != endpoints[B]:\n",
    "            new_segment = join_endpoints(endpoints, A, B)\n",
    "            if len(new_segment) == len(cities):\n",
    "                return new_segment\n",
    "            \n",
    "def improve_greedy_tsp(cities): return improve_tour(greedy_tsp(cities))\n",
    "            \n",
    "def shortest_links_first(cities):\n",
    "    \"Return all links between cities, sorted shortest first.\"\n",
    "    return sorted(combinations(cities, 2), key=lambda link: distance(*link))\n",
    "            \n",
    "# TO DO: join_endpoints"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** The `endpoints` dict is serving two purposes. First, the keys of the dict are all the cities that are endpoints of some segment, making it possible to ask \"`A in endpoints`\" to see if city `A` is an endpoint. Second, the value of `endpoints[A]` is the segment that `A` is an endpoint of, making it possible to ask \"`endpoints[A] != endpoints[B]`\" to make sure that the two cities are endpoints of different segments, not of the same segment.\n",
    "\n",
    "For the `join_endpoints` function, I first make sure that A is the last element of one segment and B is the first element of the other, by reversing segments if necessary.  Then I add the B segment on to the end of the A segment. Finally, I update the `endpoints` dict by deleting `A` and `B` and then adding the two endpoints of the new segment: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [],
   "source": [
    "def join_endpoints(endpoints, A, B):\n",
    "    \"Join segments [...,A] + [B,...] into one segment. Maintain `endpoints`.\"\n",
    "    Aseg, Bseg = endpoints[A], endpoints[B]\n",
    "    if Aseg[-1] is not A: Aseg.reverse()\n",
    "    if Bseg[0]  is not B: Bseg.reverse()\n",
    "    Aseg += Bseg\n",
    "    del endpoints[A], endpoints[B] \n",
    "    endpoints[Aseg[0]] = endpoints[Aseg[-1]] = Aseg\n",
    "    return Aseg"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's try out the `greedy_tsp` algorithm, with and without improvement, on the USA map:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "greedy: 1089 cities ⇒ tour length 46982 (in 0.561 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 122524 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1160c00b8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(greedy_tsp, USA)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "improve_greedy: 1089 cities ⇒ tour length 43844 (in 2.855 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 118872 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x10d040b38>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(improve_greedy_tsp, USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's the best result yet,  and it only took 3 seconds!\n",
    "\n",
    "What about a repetitive greedy algorithm?  That might be a good idea, but there is no obvious way to do it, because the greedy algorithm as it stands doesn't have a parameter that can be varied on each repeated run.\n",
    "\n",
    "## Visualizing the Greedy Algorithm\n",
    "\n",
    "I would like to visualize how the process of joining segments unfolds.  Although I dislike copy-and-paste (because it violates the *[Don't Repeat Yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself)* principle), I'll copy  `greedy_tsp` and make a new version called `visualize_improve_greedy_tsp` which adds a line to plot the segments several times as the algorithm is running, and a few lines at the end to improve and plot the final tour."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [],
   "source": [
    "def visualize_improve_greedy_tsp(cities, plot_sizes):\n",
    "    \"\"\"Go through links, shortest first. Use link to join segments if possible.\n",
    "    Plot segments at specified plot_sizes.\"\"\"\n",
    "    endpoints = {c: [c] for c in cities} # A dict of {endpoint: segment}\n",
    "    for (A, B) in shortest_links_first(cities):\n",
    "        if A in endpoints and B in endpoints and endpoints[A] != endpoints[B]:\n",
    "            new_segment = join_endpoints(endpoints, A, B)\n",
    "            plot_segments(endpoints, plot_sizes)\n",
    "            if len(new_segment) == len(cities):\n",
    "                plot_tour(new_segment)\n",
    "                plt.show()\n",
    "                do(improve_greedy_tsp, cities)\n",
    "                return \n",
    "    \n",
    "def plot_segments(endpoints, plot_sizes):\n",
    "    \"If the number of distinct segments is one of plot_sizes, then plot segments.\"\n",
    "    segments = set(map(tuple, endpoints.values()))\n",
    "    if len(segments) in plot_sizes:\n",
    "        for s in segments:\n",
    "            plot_segment(s)\n",
    "        plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 9936 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x10d040780>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 12540 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11556c358>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 14352 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11acc7470>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 15888 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x115372198>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "image/png": "[encoded data, 18684 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1153f7940>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "improve_greedy: 110 cities ⇒ tour length 14999 (in 0.030 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 17880 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1154f1978>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "visualize_improve_greedy_tsp(sample(USA, 110), {40, 20, 10, 5});"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Divide and Conquer Strategy\n",
    "\n",
    "The next general strategy to consider is **divide and conquer**.  Suppose we have an algorithm, like `exhaustive_tsp`, that we can't feasibly apply to a large set of cities, because it is inefficient. We could divide the problem into smaller pieces, and then combine those pieces:\n",
    "\n",
    "1. Split the set of cities in half.\n",
    "2. Find a tour for each half.\n",
    "3. Join those two tours into one.\n",
    "\n",
    "When *n* is small, then step 2 can be done directly by the inefficient algorithm.  But when *n* is large, step 2 is done with a recursive call, breaking each half into two smaller pieces.\n",
    "Here's an example with six cities. We split them into two halves of 3 cities each, for which we can easily create tours:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7156 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11c0346a0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "d, a, b, e, c, f = Cities(6)\n",
    "\n",
    "half1, half2 = [c, a, b], [d, e, f]\n",
    "\n",
    "plot_tour(half1, 'bo-')\n",
    "plot_tour(half2, 'gs-')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now to join the two halves together, the first thing I do is delete a link from each half. There are 3 &times; 3 ways to do that; here's one:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 4464 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11c02ecf8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_segment(half1, 'bo-')\n",
    "plot_segment(half2, 'gs-')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now I connect the two halves back together. There are two ways to do that; this is the better way:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 7736 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11a290c50>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plot_tour(half1 + half2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have a feel for what we have to do.  I'll call the divide and conquer algorithm `divide_tsp`.  If the size of the set of cities is *n* or less, then find the shortest tour using `exhaustive_tsp`. If there are more than *n* cities, then split the cities in half (with `split_cities`), find a tour for each half (using `divide_tsp` recursively), and join the two tours together (with `join_tours`): "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [],
   "source": [
    "def divide_tsp(cities, n=6):\n",
    "    \"\"\"Find a tour by divide and conquer: if number of cities is n or less, use exhaustive search.\n",
    "    Otherwise, split the cities in half, solve each half recursively, \n",
    "    then join those two tours together.\"\"\"\n",
    "    if len(cities) <= n:\n",
    "        return exhaustive_tsp(cities)\n",
    "    else:\n",
    "        half1, half2 = split_cities(cities)\n",
    "        return join_tours(divide_tsp(half1), divide_tsp(half2))\n",
    "    \n",
    "# TO DO: functions: split_cities, join_tours"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "How do we split a set of cities?  My approach is to imagine drawing an axis-aligned rectangle that is just big enough to contain all the cities. If the rectangle  is wider than it is tall, then order all the cities by *x* coordinate and split that ordered list in half.  If the rectangle is taller than it is wide, order and split the cities by *y* coordinate. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [],
   "source": [
    "def split_cities(cities):\n",
    "    \"Split cities vertically if map is wider; horizontally if map is taller.\"\n",
    "    width  = extent(list(map(X, cities)))\n",
    "    height = extent(list(map(Y, cities)))\n",
    "    cities = sorted(cities, key=(X if (width > height) else Y))\n",
    "    middle = len(cities) // 2\n",
    "    return cities[:middle], cities[middle:]\n",
    "\n",
    "def extent(numbers): return max(numbers) - min(numbers)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now for the tricky part: joining two tours together. First we consider all ways of deleting one link from each of the two tours.  If we delete a link from a tour we get a segment.  We are representing segments as lists of cities, the same surface representation as tours.  But there is a difference in their interpretation.  The tour `[c, a, b]` is a triangle of three links, but the segment `[c, a, b]` consists of only two links, from `c` to `a` and from `a` to `b`. The segments that result from deleting a link from the tour `[c, a, b]` are:\n",
    "\n",
    "     [c, a, b],  [a, b, c],  [b, c, a]\n",
    "\n",
    "You may recognize these as the *rotations* of the segment `[c, a, b]`. So any candidate combined tour consists of taking a rotation of the first tour, and appending to it a rotation of the second tour, with one caveat: when we go to append the two segments, there are two ways of doing it: either keep the second segment as is, or reverse the second segment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [],
   "source": [
    "def join_tours(tour1, tour2):\n",
    "    \"Consider all ways of joining the two tours together, and pick the shortest.\"\n",
    "    segments1, segments2 = rotations(tour1), rotations(tour2)\n",
    "    return shortest_tour(s1 + s2\n",
    "                         for s1 in segments1\n",
    "                         for s  in segments2\n",
    "                         for s2 in (s, s[::-1]))\n",
    "\n",
    "def rotations(sequence):\n",
    "    \"All possible rotations of a sequence.\"\n",
    "    # A rotation is some suffix of the sequence followed by the rest of the sequence.\n",
    "    return [sequence[i:] + sequence[:i] for i in range(len(sequence))]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As usual, we can define an **improved** version:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "def improve_divide_tsp(cities): return improve_tour(divide_tsp(cities))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's divide and conquer! First the 6 cities, then 100 USA cities:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "divide, 3: 6 cities ⇒ tour length 1922 (in 0.000 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 7716 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11b54dd30>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(bind(divide_tsp, 3), Cities(6))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "improve_divide: 110 cities ⇒ tour length 14749 (in 0.247 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 17344 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x115396470>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(improve_divide_tsp, sample(USA, 110))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's slightly better than `improve_greedy_tsp` (although it took 10 times longer).\n",
    "\n",
    "# Shoulders of Giants: Minimum Spanning Tree Algorithm\n",
    "\n",
    "\n",
    "| ![Joseph Kruskal (Wikipedia)](http://people.inf.elte.hu/hytruongson/Kruskal/J.Kruskal.jpg) |\n",
    "|----|\n",
    "| [Joseph Kruskal (Wikipedia)](https://en.wikipedia.org/wiki/Joseph_Kruskal) |\n",
    "\n",
    "\n",
    "\n",
    "I hope you now believe that you could have come up with some ideas for solving the TSP, using the set of **strategies**. But even if you can't come up with something all on your own, you can follow the **Stand on the Shoulders of Giants Strategy**, also known as the **[Just Google it Strategy](http://bit.ly/XNGt2y)**, in which case you'll no doubt find a giant of a mathematician, [Joseph Kruskal](http://en.wikipedia.org/wiki/Joseph_Kruskal), who, in 1956, published [a paper](http://www.cmat.edu.uy/~marclan/TAG/Sellanes/Kruskal.pdf) that led to an algorithm that\n",
    "most people would not have thought of on their own (I know I wouldn't have):\n",
    "> **Minimum Spanning Tree Traversal Algorithm:** *Construct a Minimum Spanning Tree, then do a pre-order traversal.  That will give you a tour that is guaranteed to be no more than twice as long as the minimal tour.* \n",
    "\n",
    "What does all this jargon mean? It is part of *[graph theory](https://en.wikipedia.org/wiki/Graph_theory)*, the study of vertexes and links.  Here is a glossary of terms:\n",
    "\n",
    "* A **graph** is a collection of vertexes and links.\n",
    "* A **vertex** is a point (such as a city).\n",
    "* A **link** is an edge between two vertexes. Links have lengths.\n",
    "\n",
    "* A **directed graph** is a graph where the links have a direction.  We say that the link goes from the **parent** vertex to the **child** vertex.\n",
    "\n",
    "* A **tree** is a directed graph in which there is one distinguished vertex called the **root** that has no parent; every other vertex has exactly one parent. \n",
    "\n",
    "* A **spanning tree** (of a set of vertexes) is a tree that contains all the vertexes.    \n",
    "\n",
    "* A **minimum spanning tree** is a spanning tree with the smallest possible sum of link lengths.\n",
    "\n",
    "* A **traversal** of a tree is a way of visiting all the vertexes in some order.\n",
    "\n",
    "* A **pre-order traversal** means that you visit the root first, then do a pre-order traversal of each of the children.\n",
    "\n",
    "* A **guarantee** means that, no matter what set of cities you consider, the tour found by the minimum spanning tree traversal algorithm will never be more than twice as long as the shortest possible tour. None of the other algorithms has any guarantee at all (except for `exhaustive_tsp`, which is guaranteed to find the optimal algorithm, if it has enough time to complete).\n",
    "\n",
    "We will implement a directed graph as a dict of `{parent: [child, ...]}`. Now our plan is:\n",
    "\n",
    "1. Implement an algorithm to create a minimum spanning tree.\n",
    "2. Implement a tree traversal; that will give us our `mst_tsp` algorithm.\n",
    "3. Understand the guarantee.\n",
    "\n",
    "# Creating a Minimum Spanning Tree (`mst`)\n",
    "\n",
    "\n",
    "Now let's see how to create a minimum spanning tree (or MST).  Kruskal has a very nice algorithm to find MSTs, but with what we have done so far, it will be a bit easier to implement [another Giant](https://en.wikipedia.org/wiki/Robert_C._Prim)'s algorithm:\n",
    "\n",
    "> **[Prim's algorithm for creating a MST](http://en.wikipedia.org/wiki/Prim%27s_algorithm):** *List all the links and sort them, shortest first.  Initialize a tree to be a single root city (we'll arbitrarily choose the first city). Now repeat the following until the tree contains all the cities: find the shortest link that links a city (A) that is in the tree to a city (B) that is not yet in the tree, and add B to the list of A's children in the tree.*\n",
    "\n",
    "Here's the code. One tricky bit: In the first line inside the `while` loop, we assign `(A, B)` to be a link in which exactly one of `A` or `B` is in the tree, using the exclusive-or operator, `^`.  Then in the next line, we make sure that `A` is the one that is in the tree and B is not, by swapping if necessary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mst(vertexes):\n",
    "    \"\"\"Given a set of vertexes, build a minimum spanning tree: a dict of the form \n",
    "    {parent: [child...]}, spanning all vertexes.\"\"\"\n",
    "    tree  = {first(vertexes): []} # the first city is the root of the tree.\n",
    "    links = shortest_links_first(vertexes)\n",
    "    while len(tree) < len(vertexes):\n",
    "        (A, B) = first((A, B) for (A, B) in links if (A in tree) ^ (B in tree))\n",
    "        if A not in tree: (A, B) = (B, A)\n",
    "        tree[A].append(B)\n",
    "        tree[B] = []\n",
    "    return tree"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's see what a minimum spanning tree looks like:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1089 node Graph of total length: 37868.3\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 89956 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11a907358>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def plot_graph(graph):\n",
    "    \"Given a graph of the form {parent: [child...]}, plot vertexes and links.\"\n",
    "    vertexes = {v for parent in graph for v in graph[parent]} | set(graph)\n",
    "    links    = [(parent, child) for parent in graph for child in graph[parent]]\n",
    "    total    = sum(distance(p, c) for (p, c) in links)\n",
    "    print('{} node Graph of total length: {:.1f}'.format(len(vertexes), total))\n",
    "    if len(graph) > 1000: plt.figure(figsize=(15, 7.5))\n",
    "    for link in links:\n",
    "        plot_segment(link, 'b.-')\n",
    "\n",
    "    \n",
    "plot_graph(mst(USA))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This certainly looks like a spanning tree.  But can we prove it is a minimum spanning tree?  \n",
    "\n",
    "1. The output is a **tree** because (1) every city is connected by a path from the root, and (2) every city only gets one parent (we only add a B that is not in tree), so there can be no loops. \n",
    "2. The output is a **spanning tree** because it contains all the cities.\n",
    "3. The output is a **minimum spanning tree** because each city was added with the shortest possible link.  Suppose this algorithm produces the tree T. For another putative spanning tree to be shorter, it would have to contain at least one city C whose link from its parent was shorter than the link in T. But that is not possible, because the algorithm always chooses the shortest possible link from C's parent to C.\n",
    "\n",
    "\n",
    "# Turning a Minimum Spanning Tree into a Tour (`mst_tsp`)\n",
    "\n",
    "\n",
    "Given a minimum spanning tree, we can generate a tour by doing a pre-order traversal, which means the tour starts at the root, then visits all the cities in the pre-order traversal of the first child of the root, followed by the pre-order traversals of any other children."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "def mst_tsp(cities):\n",
    "    \"Create a minimum spanning tree and walk it in pre-order, omitting duplicates.\"\n",
    "    return Tour(preorder_traversal(mst(cities), first(cities)))\n",
    "\n",
    "def preorder_traversal(tree, root):\n",
    "    \"Traverse tree in pre-order, starting at root of tree.\"\n",
    "    yield root\n",
    "    for child in tree.get(root, ()):\n",
    "        yield from preorder_traversal(tree, child)\n",
    "        \n",
    "def improve_mst_tsp(cities): return improve_tour(mst_tsp(cities))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can think of this as starting at the root of the tree and going around the outside of the tree, as if you were walking with your hand always touching a link, but skipping cities you have already been to.\n",
    "\n",
    "Let's see what `mst_tsp` can do on the USA map:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mst: 1089 cities ⇒ tour length 58059 (in 0.879 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 134512 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11a8f6940>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(mst_tsp, USA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's 5,000 miles worse than `nn_tsp`. Why would anyone want to use the minimum spanning tree algorithm, when the nearest neighbor algorithm is simpler to describe and implement, runs faster, and produces shorter tours? \n",
    "\n",
    "# Guaranteed Tour Length!\n",
    "\n",
    "The \"giant\" thing about the minimum spanning tree algorithm is that it comes with a *guarantee*, which none of the other algorithms offer. The algorithm  guarantees that the tour length will be no worse than twice as long as the optimal tour.  (And, with a bit more [complication](https://en.wikipedia.org/wiki/Christofides_algorithm), you can modify it to give a guarantee of 1.5 times longer.)  The guarantee works like this:\n",
    "\n",
    "1. The minimum spanning tree, by definition, connects all the cities with the shortest possible total link length.\n",
    "2. So if you could follow each link in the spanning tree just once, and that formed a legal tour, then that would be guaranteed to be\n",
    "a minimal tour.  \n",
    "3. But you can't do that in general; in general there will be places where you skip to the next city without following the spanning tree.  Any such skip, however, is a straight line, and thus will be less than you would take if you went to the next city by following along the spanning tree.\n",
    "4. If you did follow along the spanning tree, you would follow some links twice, and some links once.  Hence the total length of the tour would be at most twice the spanning tree, and thus at most twice the minimal tour.\n",
    "\n",
    "A guarantee is great from a theoretical point of view, but in practice the greedy or nearest neighbor algorithms do better than the minimum spanning tree, and the improved versions of those algorithms do significantly better, on the maps that we actually see. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Shoulders of Giants: Held-Karp Algorithm: `held_karp_tsp`\n",
    "\n",
    "\n",
    "| ![](http://archive.computerhistory.org/resources/still-image/IBM/IBM_People/IBM.3_mathematicians_Held_Shareshian_Karp.ca1964.102650390.lg.jpg) |\n",
    "|----|\n",
    "| [Held, Shareshian, Karp (Computer History Museum)](http://www.computerhistory.org/collections/catalog/102650390) |\n",
    "\n",
    "| ![](http://imgs.xkcd.com/comics/travelling_salesman_problem.png) |\n",
    "|----|\n",
    "| [xkcd 399](http://xkcd.com/399/) |\n",
    "\n",
    "\n",
    "Another algorithm that shows up with a literature search is the [Held-Karp Dynamic Programming Algorithm](http://en.wikipedia.org/wiki/Held%E2%80%93Karp_algorithm), named after giants [Michael Held](http://www.computerhistory.org/collections/catalog/102650390) and [Richard Karp](http://en.wikipedia.org/wiki/Richard_M._Karp). It is an algorithm for finding optimal tours, not approximate ones, so it is not appropriate for large *n*.  But even in its simplest form, without any programming tricks, it can go quite a bit further than `exhaustive_tsp`.  That is because `exhaustive_tsp` is O(*n*!), while the Held-Karp algorithm is only O(*n*<sup>2</sup> 2<sup>*n*</sup>).  How did Held and Karp achieve this speedup?  They noticed that `exhaustive_tsp` wastes a lot of time with permutations that can't possibly be optimal tours.  Here's the key idea:\n",
    "\n",
    "\n",
    ">*Given a start city A, an end city C, and a set of middle cities Bs, then out of all the possible segments that start in A, end in C, and go through all and only the cities in Bs, only the shortest of those segments could ever be part of an optimal tour.*\n",
    "\n",
    "Of course, we don't know that the optimal tour goes through exactly those Bs cities before hitting C.  But if it does, then we need only consider the permutation of Bs that leads to the shortest segment.  Why is that such a big deal? Suppose we are considering segments of the form:\n",
    "\n",
    "     [A, {B1, ... B10}, C, {D1, ... D10}, E]\n",
    "     \n",
    "That is, segments that start with A, then have have 10 B<sub>i</sub> cities in some order, then C, then 10 D<sub>j</sub> cities in some order, then E. With the Exhaustive Search algorithm, we have to consider all orderings of B<sub>i</sub> and all orderings of D<sub>j</sub>, so overall there would be (10!)<sup>2</sup> &approx; 13 trillion orderings of this form. But with Held-Karp, we consider the B<sub>i</sub> and D<sub>j</sub> separately, and chose the best segment from each, giving us only 2 &times; 10! &approx; 7 million orderings to consider. (Actually it is even better than that, because we use Held-Karp recursively to split the B<sub>i</sub> and D<sub>j</sub> into pieces.) \n",
    "\n",
    "So far we have only been talking about segments.  We know that the TSP is defined for tours, not segments. So even if we find the shortest possible segment, it might not be the shortest possible tour.  But here's something we do know: a tour has to end somewhere.  So just find the shortest segment from the start city, `A`, to each possible end city, `C`.   Out of those segments, choose the one that is the shortest tour. That gives us our algorithm:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [],
   "source": [
    "def held_karp_tsp(cities):\n",
    "    \"\"\"The Held-Karp shortest tour of this set of cities.\n",
    "    For each end city C, find the shortest segment from A (the start) to C.\n",
    "    Out of all these shortest segments, pick the one that is the shortest tour.\"\"\"\n",
    "    A = first(cities)\n",
    "    shortest_segment.cache_clear() # Start a new problem\n",
    "    return shortest_tour(shortest_segment(A, cities - {A, C}, C)\n",
    "                         for C in cities - {A})\n",
    "\n",
    "# TO DO: function: shortest_segment(A, Bs, C)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now for `shortest_segment(A, Bs, C)`, the shortest segment that starts in city `A`, ends in `C`, and visits some permutation of `Bs` cities in the middle.  If there are no `Bs` cities, then of course the shortest segment is to go directly from `A` to `C`.  If there are `Bs` cities, then one of them has to be the last `B` city visited (just before visiting `C`). So for each `B`, find the shortest segment that first goes from `A`, through all the other `Bs` cities, then to `B`, and finally to `C`.  Out of all these candidate segments, return the one with the minimum segment length.\n",
    "\n",
    "**Note:** the decorator `@cache` makes this a **dynamic programming** algorithm, which is a fancy name meaning that we cache the results of sub-computations because we will re-use them multiple times. In the function `held_karp_tsp` we clear the cache at the start of each new problem."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache(None)\n",
    "def shortest_segment(A, Bs, C):\n",
    "    \"The shortest segment starting at A, going through all Bs, and ending at C.\"\n",
    "    if not Bs:\n",
    "        return [A, C]\n",
    "    else:\n",
    "        return min((shortest_segment(A, Bs - {B}, B) + [C] for B in Bs),\n",
    "                   key=segment_length)\n",
    "            \n",
    "def segment_length(segment):\n",
    "    \"The total of distances between each pair of consecutive cities in the segment.\"\n",
    "    # Same as tour_length, but without distance(tour[0], tour[-1])\n",
    "    return sum(distance(segment[i], segment[i-1]) \n",
    "               for i in range(1, len(segment)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's all there is to it.  Let's compare `exhaustive_tsp` with `held_karp_tsp` on 10 city tours:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "exhaustive: 10 cities ⇒ tour length 2720 (in 1.611 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 9120 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11acb9fd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(exhaustive_tsp, Cities(10))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "held_karp: 10 cities ⇒ tour length 2720 (in 0.032 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 9120 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x114d2e898>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(held_karp_tsp, Cities(10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that `held_karp_tsp` is a lot faster.  We can extend into uncharted territory  beyond the reach of  `exhaustive_tsp`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "held_karp: 18 cities ⇒ tour length 2771 (in 42.475 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 11348 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x116d54b38>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(held_karp_tsp, Cities(18))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not bad! To see how much time we save using `held_karp_tsp` over `exhaustive_tsp`, we can extrapolate from the timings we've done, using the fact that Held-Karp is *O*(*n*<sup>2</sup> 2<sup>*n*</sup>) while Exhaustive Search is *O*(*n*!), to get this table:\n",
    "\n",
    "\n",
    "|*n*|Exhaustive Search|Held Karp|\n",
    "|---|---|---|\n",
    "|10| 2 secs                | 0.04 secs |\n",
    "|12|&approx; 4 mins   | 0.25 secs|\n",
    "|15|&approx; 8 days |3 secs|\n",
    "|18|&approx; 112 years| 43 secs|\n",
    "|25|&approx; <a href=\"https://www.google.com/search?q=2+seconds*25!+%2F+10!+in+years\">270 billion years</a>|&approx; 3 hours|\n",
    "|50|&approx; 10<sup>50</sup> years</a>|&approx; 45,000 years|\n",
    "\n",
    "\n",
    "So if we had the patience to wait 3 hours, `held_karp_tsp` could give us an answer that saves 270 billion years of computing with `exhaustive_tsp`.  The original Held-Karp algorithm had refinements that allowed it to handle 50-city sets in hours, not milleniums, and could do so even with 1970s-era computing power! See **Branch and Cut** below.\n",
    "\n",
    "We have one more trick to try:\n",
    "\n",
    "# Ensemble Strategy: `ensemble_tsp`\n",
    "\n",
    "When we have several optimization algorithms and we're not sure which is best, we can always try them all and take the best result:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "ensemble = {rep_improve_nn_tsp, improve_greedy_tsp, improve_mst_tsp, improve_divide_tsp}\n",
    "\n",
    "def ensemble_tsp(cities, algorithms=None): \n",
    "    \"Apply an ensemble of algorithms to cities and take the shortest resulting tour.\"\n",
    "    return shortest_tour(tsp(cities) for tsp in (algorithms or ensemble))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ensemble: 110 cities ⇒ tour length 14727 (in 0.388 sec)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 17552 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x116d54278>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "do(ensemble_tsp, set(sample(USA, 110)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Review\n",
    "\n",
    "Here are the algorithms we developed, sorted by strategy:\n",
    "\n",
    "- **Brute Force Strategy**: `exhaustive_tsp`\n",
    "- **Greedy Strategy**: `nn_tsp`, `greedy_tsp`\n",
    "- **Divide and Conquer Strategy**: `divide_tsp`\n",
    "- **Ensemble Strategy**: `rep_nn_tsp`, `ensemble_tsp`\n",
    "- **Giant Shoulders Strategy**: `mst_tsp`, `held_karp_tsp`\n",
    "- **Iterative Improvement Strategy**: `improve_nn_tsp`, `improve_greedy_tsp`, `improve_divide_tsp`,  `rep_improve_nn_tsp`, `improve_mst_tsp`\n",
    "\n",
    "\n",
    "# Benchmark Experiments on Algorithms\n",
    "\n",
    "Which algorithm is best? I can't tell by trying them on only one or two problems. What I need to do is **benchmark** each algorithm on a standard **test suite** of problems. If the test suite is large enough, the results will have statistical significance. First we'll define `TestSuite`. It passes a different `seed` to `sample` each time, so we get a different set of cities each time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [],
   "source": [
    "def TestSuite(n, k, cities=USA):\n",
    "    \"Return n different samples from cities, each consisting of k cities.\"\n",
    "    return tuple(frozenset(sample(cities, k, seed=(n, k, i)))\n",
    "                 for i in range(n))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(frozenset({(-3804+2908.35j), (-3847.2000000000003+1798.83j)}),\n",
       " frozenset({(-3512.6400000000003+2915.94j), (-3623.04+2611.65j)}),\n",
       " frozenset({(-4736.64+3237.48j), (-4761.6+2439.15j)}),\n",
       " frozenset({(-3435.84+2840.73j), (-4353.6+2925.6j)}))"
      ]
     },
     "execution_count": 61,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A tiny test of sets of 2 cities each:\n",
    "TestSuite(4, 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, the function `benchmark` takes as input a TSP function and a test suite, runs the function on each city set in the suite, and returns two values: the list of tour lengths that the function produced, and the average run time of the function. (Note that I *cache* the results, so that if you call benchmark a second time, and it has already done the computation, it just looks up the result rather than tediously re-running it. Note also that I round the tour lengths at 4 digits past the decimal place, because I don't want a round-off error to proclaim one tour better than another when they actually have the same length.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [],
   "source": [
    "@cache(None)\n",
    "def benchmark(algorithm, tests):\n",
    "    \"Benchmark one TSP algorithm on a test suite; return ([tour_lengths], average_time)\"\n",
    "    t0      = clock()\n",
    "    lengths = [round(tour_length(algorithm(cities)), 4) for cities in tests] \n",
    "    t1      = clock()\n",
    "    return lengths, (t1 - t0) / len(tests)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Boxplots\n",
    "\n",
    "A **boxplot** is a standard statistical visualization tool. I'll plot first,  explain later. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [],
   "source": [
    "def boxplots(algorithms, tests):\n",
    "    \"Draw a boxplot for each of the functions executing the tests.\"\n",
    "    lengthlists, times = unzip(benchmark(tsp, tests) for tsp in algorithms)\n",
    "    best   = min(map(median, lengthlists))\n",
    "    labels = [boxplot_label(A, L, T, best) \n",
    "              for (A, L, T) in zip(algorithms, lengthlists, times)]\n",
    "    plt.figure(figsize=(15, 7.5))\n",
    "    plt.grid(axis='y')\n",
    "    plt.tick_params(axis='x', which='major', labelsize=12)\n",
    "    plt.boxplot(lengthlists, labels=labels, showmeans=True, whis=(10, 90), sym='o', notch=True)\n",
    "    plt.title(\"Comparison  on {} sets of Cities({})\"\n",
    "              .format(len(tests), len(tests[0])), fontsize=14)\n",
    "\n",
    "def boxplot_label(tsp, lengths, T, best):\n",
    "    return '{}\\n{:.0f} ms\\n{:.0f} mean len\\n{:.0f} med len\\n{:.3f} med ratio'.format(\n",
    "           name(tsp), T * 1000, mean(lengths), median(lengths), median(lengths) / best)\n",
    "\n",
    "def unzip(sequences): return zip(*sequences)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 44888 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11556c668>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# boxplots for the 5 basic approximate algorithms:\n",
    "basic5 = [greedy_tsp, rep_nn_tsp, divide_tsp, nn_tsp, mst_tsp]\n",
    "\n",
    "boxplots(basic5, TestSuite(50, 200))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each column represents a data set (in this case, the 50 tour lengths for one algorithm) with a box covering the first to third quartiles of the data; inside the box is a horizontal line indicating the median and a marker indicating the mean. The 10% and 90%  intervals are the \"whiskers\" coming out of the top and bottom of the box, and individual points outside that range are shown as dots. The \"notches\" in the sides of a boxes represent the 95% confidence interval on the median: if two boxes' notches do not overlap, that is strong evidence that the true medians of the algorithms differ. The **label** at the bottom of each column gives the name of the algorithm, the average run time in milliseconds, the mean and median tour length, and the ratio of the median tour length of this algorithm to the median tour length of the best algorithm in this boxplot.\n",
    "\n",
    "This plot says that the first three algorithms all did about the same in tour length; their notches overlap, so we can't be confident that one is better than the others. (Although we can be confident that the greedy algorithm is much faster.) The minimum spanning tree algorithm produces by far the longest tours. Nearest neighbor is fastest, while divide and conquer is slowest.\n",
    "\n",
    "# Rankings\n",
    "\n",
    "I'd also like to know for how many different problems each algorithm was best, or second best, etc. I will define a function called `rankings` to do that. I'll also define  `compare` to call both `boxplots` and `rankings`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [],
   "source": [
    "def rankings(algorithms, tests):\n",
    "    \"Print a table of how often each algorithm had each rank: you get a #1 if you were shortest.\"\n",
    "    N = len(algorithms)\n",
    "    lengthlists = [benchmark(tsp, tests)[0] for tsp in algorithms]\n",
    "    # ordered[i] is all tour lengths (for all algorithms) for the i-th problem, sorted\n",
    "    ordered = [sorted(L) for L in zip(*lengthlists)]\n",
    "    fmt = ('{:>4}' * len(algorithms) + ' | {}').format\n",
    "    print(fmt(*['#' + str(i + 1) for i in range(N)], 'Algorithm'))\n",
    "    print(' ---' * N + ' | ---------')\n",
    "    for alg, lengths in zip(algorithms, lengthlists):\n",
    "        ranks = Counter(ordered[i].index(lengths[i]) for i in range(len(tests)))\n",
    "        print(fmt(*[ranks[i] for i in range(N)], name(alg)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3  #4  #5 | Algorithm\n",
      " --- --- --- --- --- | ---------\n",
      "  14  17  14   5   0 | greedy\n",
      "  16  15  16   3   0 | rep_nn\n",
      "  20  14  12   4   0 | divide\n",
      "   0   4   8  22  16 | nn\n",
      "   0   0   0  16  34 | mst\n"
     ]
    }
   ],
   "source": [
    "rankings(basic5, TestSuite(50, 200))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The top line of the rankings says the greedy algorithm was #1 (had the shortest tour) for 14 out of the 50 problems, came in second  for 17 problems,  third 14 times, and fourth 5 times. The `rep_nn_tsp` algorithm was similar, coming in first 16 times; divide and conquer had the most first-place finishes with 20, and the MST algorithm was terrible, coming in last 34 times."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Comparsion of Improved Algorithms\n",
    "\n",
    "Now let's compare the **improved** versions of these algorithms (using `compare` to do boxplots and rankings):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [],
   "source": [
    "def compare(algorithms, tests=TestSuite(50, 200)):\n",
    "    \"Compare TSP algorithms on a test suite.\"\n",
    "    boxplots(algorithms, tests)\n",
    "    plt.show()\n",
    "    rankings(algorithms, tests)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 46012 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11524dfd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3  #4  #5 | Algorithm\n",
      " --- --- --- --- --- | ---------\n",
      "  17  16   8   8   1 | improve_greedy\n",
      "  26  16   6   2   0 | rep_improve_nn\n",
      "   0   2   4   6  38 | improve_divide\n",
      "   3  10  15  19   3 | improve_nn\n",
      "   4   6  17  15   8 | improve_mst\n"
     ]
    }
   ],
   "source": [
    "improved = [improve_greedy_tsp, rep_improve_nn_tsp, improve_divide_tsp, improve_nn_tsp, improve_mst_tsp]\n",
    "\n",
    "compare(improved)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `improve_greedy_tsp` and `rep_improve_nn_tsp` algorithms give the shortest tours. One surprising result is that the divide and conquer algorithm was not improved much; perhaps the re-assembly steps of divide and conquer are already doing similar things to what `improve_tour` does. The minimum spanning tree algorithm is no longer terrible.\n",
    "\n",
    "\n",
    "# Comparison of *k* Values for `rep_improve_nn_tsp`\n",
    "\n",
    "What's a good value for the *k* parameter for the repetitive improved nearest neighbor algorithm?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 48836 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11561f4a8>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3  #4  #5  #6 | Algorithm\n",
      " --- --- --- --- --- --- | ---------\n",
      "  10   4   1  11  12  12 | improve_greedy\n",
      "  17  17  10   6   0   0 | rep_improve_nn, 15\n",
      "  15   9  17   5   2   2 | rep_improve_nn, 10\n",
      "   8   8   8  12   9   5 | rep_improve_nn, 5\n",
      "   5   5   7  10  12  11 | rep_improve_nn, 3\n",
      "   1   4   8   4  13  20 | rep_improve_nn, 1\n"
     ]
    }
   ],
   "source": [
    "compare([improve_greedy_tsp] + [bind(rep_improve_nn_tsp, k) for k in (15, 10, 5, 3, 1)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We do get shorter tours as we increase the reptitions, but of course we pay a penalty in run time. With *k*=3,\n",
    "`rep_improve_nn_tsp` is roughly comparable to `improve_greedy_tsp` (although the later is twice as fast). With *k*=15 the tours are 2.5% shorter than with *k*=1, but the run time is 15 times longer. \n",
    "\n",
    "# Comparison of Ensemble Strategy\n",
    "\n",
    "Since no one algorithm always dominates the others, maybe it is time for the **ensemble strategy**:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 41208 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x11525f828>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3  #4 | Algorithm\n",
      " --- --- --- --- | ---------\n",
      "  50   0   0   0 | ensemble\n",
      "  28   0  19   3 | rep_improve_nn\n",
      "  18   0  20  12 | improve_greedy\n",
      "   4   0  11  35 | improve_mst\n"
     ]
    }
   ],
   "source": [
    "ensemble = (rep_improve_nn_tsp, improve_greedy_tsp, improve_mst_tsp)\n",
    "\n",
    "compare((ensemble_tsp, *ensemble))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `ensemble_tsp` algorithm produces the shortest tours yet, because it gets contributions from both `rep_improve_nn_tsp` and `improve_greedy_tsp` (and, for just 4 out of 50 problems, from `improve_mst_tsp`). Note that in the rankings, for every problem there is a two way tie for first between the `ensemble_tsp` algorithm and whichever member of the ensemble contributed that tour. That's why there are 100 (not 50) entries in the \"#1\" column, and 0 in the \"#2\" column. \n",
    "\n",
    "Let's see if the results are different for different-sized city sets:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 71,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 41172 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x1153d5080>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3  #4 | Algorithm\n",
      " --- --- --- --- | ---------\n",
      "  30   0   0   0 | ensemble\n",
      "  14   0  15   1 | rep_improve_nn\n",
      "  14   0  12   4 | improve_greedy\n",
      "   2   0   3  25 | improve_mst\n"
     ]
    }
   ],
   "source": [
    "compare((ensemble_tsp, *ensemble), TestSuite(30, 300))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A similar picture.\n",
    "\n",
    "# Comparing Precise Algorithms\n",
    "\n",
    "Here I compare the two precise algorithms, Exhaustive Search and Held-Karp, to the (approximate) ensemble algorithm. I'll try both 9 and 10-city test suites:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30548 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x111bd5fd0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3 | Algorithm\n",
      " --- --- --- | ---------\n",
      " 200   0   0 | exhaustive\n",
      " 200   0   0 | held_karp\n",
      " 194   0   6 | ensemble\n"
     ]
    }
   ],
   "source": [
    "compare([exhaustive_tsp, held_karp_tsp, ensemble_tsp], TestSuite(200, 9))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 26748 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x10cfdc438>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "  #1  #2  #3 | Algorithm\n",
      " --- --- --- | ---------\n",
      "  20   0   0 | exhaustive\n",
      "  20   0   0 | held_karp\n",
      "  19   0   1 | ensemble\n"
     ]
    }
   ],
   "source": [
    "compare([exhaustive_tsp, held_karp_tsp, ensemble_tsp], TestSuite(20, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This says that while `ensemble_tsp` does not quite give a guarantee of an optimal tour, in practice on random city sets it performs almost exactly the same as the precise algorithms, only faster.\n",
    "\n",
    "\n",
    "# Further Explorations\n",
    "\n",
    "\n",
    "That's all I'm going to write for now.  But there are still plenty of open questions for you to explore:\n",
    "\n",
    "* **Branch and Cut**: this is a technique to cut off a search early, when a partial solution is obviously not optimal.  We saw how Held-Karp cuts off some permutations of cities when another permutation is better.  A refinement on that is to keep track of, say, the best total length of the segment going through all the Bs cities.  Then, any time you have a partial segment through some of the Bs cities that exceeds the best total, we can stop right there, before even finishing all the Bs.  With this technique, you can find optimal tours for around 50 cities.\n",
    "* **Linear programming**: Look up the topic \"linear programming\" and see how it applies to TSP.\n",
    "* **Heuristic Algorithms**: There are many approaches for using heurisitic estimates to find good (but not optimal) tours.  For example, *ant colony optimization algorithms* make random choices of which link to follow, and then the links that occur in the best tours get reinforced with some virtual pheromones, and other ants tend to follow those pheromones. *Simulated annealing* takes its inspiration from metallurgy.\n",
    "* The **[Lin-Kernighan heuristic](http://akira.ruc.dk/~keld/research/LKH/LKH-1.3/DOC/LKH_REPORT.pdf)** is a generalization of `improve_tour` that sometimes splits the tour into three pieces, not two, and considers all ways to put it back together. With this and other tricks, approximate algorithms  can handle hundreds of thousands of cities and come within 0.01% of the shortest possible tour.\n",
    "* The **[Christofides algorithm](https://en.wikipedia.org/wiki/Christofides_algorithm)** gives a guarantee of 3/2 the optimal tour length (improving on the minimum-spanning-tree guarantee of 2).\n",
    "* **improved** as a function: we defined a lot of one-line functions that just call another algorithm, and then call `improve_tour` on the result.  Can you write a function, `improved(algorithm)`, which takes a TSP algorithm as argument, and returns an improved TSP algorithm that does the original algorithm and then calls `improve_tour` on the result? Make sure it handles extra arguments, and has a readable function name.\n",
    "* Why does `mst_tsp` produce a guaranteed result, while `greedy_tsp` does not, even though the two algorithms have similar structure in the way they iterate over `shortest_links_first`?\n",
    "* The code in this notebook was designed for clarity, not efficiency.  Can you make the code faster?\n",
    "* **[William Cook](https://www.math.uwaterloo.ca/~bico/)** has a comprehensive \n",
    "[web page](http://www.math.uwaterloo.ca/tsp/) on the TSP, as well as a great \n",
    "[book](https://press.princeton.edu/titles/9531.html) and a\n",
    "[draft chapter](http://www.math.uwaterloo.ca/~bico/papers/comp_chapter1.pdf) on Discrete Optimization featuring TSP. Like my notebook here, Cook's chapter goes through a variety of algorithms for TSP, describing each one in prose and code. His coding style is different because he uses C (in an imperative style) while I used Python (in a functional style).  His code is much more efficient (but if it is 100 times faster, that might only mean two more cities). Cook  chooses a different set of algorithms to explore, with\n",
    "more emphasis on optimizing algorithms that find guaranteed shortest tours. I find his explanations and code\n",
    "are both beautiful and concise, and I think it is very interesting that\n",
    "there can be two quite different approaches, which (in my opinion) both turn out very well. \n",
    "* If you are heavily into math, there's a [taxonomy](http://cstheory.stackexchange.com/questions/9241/approximation-algorithms-for-metric-tsp) of solutions.\n",
    "* What else are you interested in?"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
