Files
ortools-clone/examples/notebook/constraint_solver/tsp.ipynb
2022-06-27 15:42:26 +02:00

197 lines
6.9 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2022 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# tsp"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/tsp.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/tsp.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"!pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"\n",
"Simple Travelling Salesman Problem.\n",
"\n",
"A description of the problem can be found here:\n",
"http://en.wikipedia.org/wiki/Travelling_salesperson_problem.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"from ortools.constraint_solver import routing_enums_pb2\n",
"from ortools.constraint_solver import pywrapcp\n",
"\n",
"\n",
"def create_data_model():\n",
" \"\"\"Stores the data for the problem.\"\"\"\n",
" data = {}\n",
" # Locations in block units\n",
" locations = \\\n",
" [(4, 4), # depot\n",
" (2, 0), (8, 0), # locations to visit\n",
" (0, 1), (1, 1),\n",
" (5, 2), (7, 2),\n",
" (3, 3), (6, 3),\n",
" (5, 5), (8, 5),\n",
" (1, 6), (2, 6),\n",
" (3, 7), (6, 7),\n",
" (0, 8), (7, 8),]\n",
" # Convert locations in meters using a city block dimension of 114m x 80m.\n",
" data['locations'] = [(l[0] * 114, l[1] * 80) for l in locations]\n",
" data['num_vehicles'] = 1\n",
" data['depot'] = 0\n",
" return data\n",
"\n",
"\n",
"def create_distance_callback(data, manager):\n",
" \"\"\"Creates callback to return distance between points.\"\"\"\n",
" distances_ = {}\n",
" index_manager_ = manager\n",
" # precompute distance between location to have distance callback in O(1)\n",
" for from_counter, from_node in enumerate(data['locations']):\n",
" distances_[from_counter] = {}\n",
" for to_counter, to_node in enumerate(data['locations']):\n",
" if from_counter == to_counter:\n",
" distances_[from_counter][to_counter] = 0\n",
" else:\n",
" distances_[from_counter][to_counter] = (\n",
" abs(from_node[0] - to_node[0]) +\n",
" abs(from_node[1] - to_node[1]))\n",
"\n",
" def distance_callback(from_index, to_index):\n",
" \"\"\"Returns the manhattan distance between the two nodes.\"\"\"\n",
" # Convert from routing variable Index to distance matrix NodeIndex.\n",
" from_node = index_manager_.IndexToNode(from_index)\n",
" to_node = index_manager_.IndexToNode(to_index)\n",
" return distances_[from_node][to_node]\n",
"\n",
" return distance_callback\n",
"\n",
"\n",
"def print_solution(manager, routing, assignment):\n",
" \"\"\"Prints assignment on console.\"\"\"\n",
" print('Objective: {}'.format(assignment.ObjectiveValue()))\n",
" index = routing.Start(0)\n",
" plan_output = 'Route for vehicle 0:\\n'\n",
" route_distance = 0\n",
" while not routing.IsEnd(index):\n",
" plan_output += ' {} ->'.format(manager.IndexToNode(index))\n",
" previous_index = index\n",
" index = assignment.Value(routing.NextVar(index))\n",
" route_distance += routing.GetArcCostForVehicle(previous_index, index, 0)\n",
" plan_output += ' {}\\n'.format(manager.IndexToNode(index))\n",
" plan_output += 'Distance of the route: {}m\\n'.format(route_distance)\n",
" print(plan_output)\n",
"\n",
"\n",
"def main():\n",
" \"\"\"Entry point of the program.\"\"\"\n",
" # Instantiate the data problem.\n",
" data = create_data_model()\n",
"\n",
" # Create the routing index manager.\n",
" manager = pywrapcp.RoutingIndexManager(len(data['locations']),\n",
" data['num_vehicles'], data['depot'])\n",
"\n",
" # Create Routing Model.\n",
" routing = pywrapcp.RoutingModel(manager)\n",
"\n",
" # Create and register a transit callback.\n",
" distance_callback = create_distance_callback(data, manager)\n",
" transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
"\n",
" # Define cost of each arc.\n",
" routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
"\n",
" # Setting first solution heuristic.\n",
" search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
" search_parameters.first_solution_strategy = (\n",
" routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
"\n",
" # Solve the problem.\n",
" assignment = routing.SolveWithParameters(search_parameters)\n",
"\n",
" # Print solution on console.\n",
" if assignment:\n",
" print_solution(manager, routing, assignment)\n",
"\n",
"\n",
"main()\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}