1{
2 "cells": [
3  {
4   "cell_type": "markdown",
5   "id": "google",
6   "metadata": {},
7   "source": [
8    "##### Copyright 2021 Google LLC."
9   ]
10  },
11  {
12   "cell_type": "markdown",
13   "id": "apache",
14   "metadata": {},
15   "source": [
16    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
17    "you may not use this file except in compliance with the License.\n",
18    "You may obtain a copy of the License at\n",
19    "\n",
20    "    http://www.apache.org/licenses/LICENSE-2.0\n",
21    "\n",
22    "Unless required by applicable law or agreed to in writing, software\n",
23    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
24    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
25    "See the License for the specific language governing permissions and\n",
26    "limitations under the License.\n"
27   ]
28  },
29  {
30   "cell_type": "markdown",
31   "id": "basename",
32   "metadata": {},
33   "source": [
34    "# tsp_cities"
35   ]
36  },
37  {
38   "cell_type": "markdown",
39   "id": "link",
40   "metadata": {},
41   "source": [
42    "<table align=\"left\">\n",
43    "<td>\n",
44    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/master/examples/notebook/constraint_solver/tsp_cities.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
45    "</td>\n",
46    "<td>\n",
47    "<a href=\"https://github.com/google/or-tools/blob/master/ortools/constraint_solver/samples/tsp_cities.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/github_32px.png\"/>View source on GitHub</a>\n",
48    "</td>\n",
49    "</table>"
50   ]
51  },
52  {
53   "cell_type": "markdown",
54   "id": "doc",
55   "metadata": {},
56   "source": [
57    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
58   ]
59  },
60  {
61   "cell_type": "code",
62   "execution_count": null,
63   "id": "install",
64   "metadata": {},
65   "outputs": [],
66   "source": [
67    "!pip install ortools"
68   ]
69  },
70  {
71   "cell_type": "code",
72   "execution_count": null,
73   "id": "code",
74   "metadata": {},
75   "outputs": [],
76   "source": [
77    "#!/usr/bin/env python3\n",
78    "# Copyright 2010-2021 Google LLC\n",
79    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
80    "# you may not use this file except in compliance with the License.\n",
81    "# You may obtain a copy of the License at\n",
82    "#\n",
83    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
84    "#\n",
85    "# Unless required by applicable law or agreed to in writing, software\n",
86    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
87    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
88    "# See the License for the specific language governing permissions and\n",
89    "# limitations under the License.\n",
90    "# [START program]\n",
91    "\"\"\"Simple Travelling Salesperson Problem (TSP) between cities.\"\"\"\n",
92    "\n",
93    "# [START import]\n",
94    "from ortools.constraint_solver import routing_enums_pb2\n",
95    "from ortools.constraint_solver import pywrapcp\n",
96    "# [END import]\n",
97    "\n",
98    "\n",
99    "# [START data_model]\n",
100    "def create_data_model():\n",
101    "    \"\"\"Stores the data for the problem.\"\"\"\n",
102    "    data = {}\n",
103    "    data['distance_matrix'] = [\n",
104    "        [0, 2451, 713, 1018, 1631, 1374, 2408, 213, 2571, 875, 1420, 2145, 1972],\n",
105    "        [2451, 0, 1745, 1524, 831, 1240, 959, 2596, 403, 1589, 1374, 357, 579],\n",
106    "        [713, 1745, 0, 355, 920, 803, 1737, 851, 1858, 262, 940, 1453, 1260],\n",
107    "        [1018, 1524, 355, 0, 700, 862, 1395, 1123, 1584, 466, 1056, 1280, 987],\n",
108    "        [1631, 831, 920, 700, 0, 663, 1021, 1769, 949, 796, 879, 586, 371],\n",
109    "        [1374, 1240, 803, 862, 663, 0, 1681, 1551, 1765, 547, 225, 887, 999],\n",
110    "        [2408, 959, 1737, 1395, 1021, 1681, 0, 2493, 678, 1724, 1891, 1114, 701],\n",
111    "        [213, 2596, 851, 1123, 1769, 1551, 2493, 0, 2699, 1038, 1605, 2300, 2099],\n",
112    "        [2571, 403, 1858, 1584, 949, 1765, 678, 2699, 0, 1744, 1645, 653, 600],\n",
113    "        [875, 1589, 262, 466, 796, 547, 1724, 1038, 1744, 0, 679, 1272, 1162],\n",
114    "        [1420, 1374, 940, 1056, 879, 225, 1891, 1605, 1645, 679, 0, 1017, 1200],\n",
115    "        [2145, 357, 1453, 1280, 586, 887, 1114, 2300, 653, 1272, 1017, 0, 504],\n",
116    "        [1972, 579, 1260, 987, 371, 999, 701, 2099, 600, 1162, 1200, 504, 0],\n",
117    "    ]  # yapf: disable\n",
118    "    data['num_vehicles'] = 1\n",
119    "    data['depot'] = 0\n",
120    "    return data\n",
121    "    # [END data_model]\n",
122    "\n",
123    "\n",
124    "# [START solution_printer]\n",
125    "def print_solution(manager, routing, solution):\n",
126    "    \"\"\"Prints solution on console.\"\"\"\n",
127    "    print('Objective: {} miles'.format(solution.ObjectiveValue()))\n",
128    "    index = routing.Start(0)\n",
129    "    plan_output = 'Route for vehicle 0:\\n'\n",
130    "    route_distance = 0\n",
131    "    while not routing.IsEnd(index):\n",
132    "        plan_output += ' {} ->'.format(manager.IndexToNode(index))\n",
133    "        previous_index = index\n",
134    "        index = solution.Value(routing.NextVar(index))\n",
135    "        route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)\n",
136    "    plan_output += ' {}\\n'.format(manager.IndexToNode(index))\n",
137    "    print(plan_output)\n",
138    "    plan_output += 'Route distance: {}miles\\n'.format(route_distance)\n",
139    "    # [END solution_printer]\n",
140    "\n",
141    "\n",
142    "\"\"\"Entry point of the program.\"\"\"\n",
143    "# Instantiate the data problem.\n",
144    "# [START data]\n",
145    "data = create_data_model()\n",
146    "# [END data]\n",
147    "\n",
148    "# Create the routing index manager.\n",
149    "# [START index_manager]\n",
150    "manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),\n",
151    "                                       data['num_vehicles'], data['depot'])\n",
152    "# [END index_manager]\n",
153    "\n",
154    "# Create Routing Model.\n",
155    "# [START routing_model]\n",
156    "routing = pywrapcp.RoutingModel(manager)\n",
157    "\n",
158    "# [END routing_model]\n",
159    "\n",
160    "# [START transit_callback]\n",
161    "def distance_callback(from_index, to_index):\n",
162    "    \"\"\"Returns the distance between the two nodes.\"\"\"\n",
163    "    # Convert from routing variable Index to distance matrix NodeIndex.\n",
164    "    from_node = manager.IndexToNode(from_index)\n",
165    "    to_node = manager.IndexToNode(to_index)\n",
166    "    return data['distance_matrix'][from_node][to_node]\n",
167    "\n",
168    "transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
169    "# [END transit_callback]\n",
170    "\n",
171    "# Define cost of each arc.\n",
172    "# [START arc_cost]\n",
173    "routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
174    "# [END arc_cost]\n",
175    "\n",
176    "# Setting first solution heuristic.\n",
177    "# [START parameters]\n",
178    "search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
179    "search_parameters.first_solution_strategy = (\n",
180    "    routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
181    "# [END parameters]\n",
182    "\n",
183    "# Solve the problem.\n",
184    "# [START solve]\n",
185    "solution = routing.SolveWithParameters(search_parameters)\n",
186    "# [END solve]\n",
187    "\n",
188    "# Print solution on console.\n",
189    "# [START print_solution]\n",
190    "if solution:\n",
191    "    print_solution(manager, routing, solution)\n",
192    "# [END print_solution]\n",
193    "\n"
194   ]
195  }
196 ],
197 "metadata": {},
198 "nbformat": 4,
199 "nbformat_minor": 5
200}
201