Files
ortools-clone/examples/notebook/constraint_solver/tsp.ipynb
Corentin Le Molgat 27121a1068 Update examples/notebook
generated using ./tools/gen_all_notebook.sh
2020-03-04 14:34:33 +01:00

156 lines
6.1 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Copyright 2010-2018 Google LLC\n",
"# 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",
"# [START program]\n",
"\"\"\"Simple Travelling Salesman Problem.\n",
"\n",
"A description of the problem can be found here:\n",
"http://en.wikipedia.org/wiki/Travelling_salesman_problem.\n",
"\"\"\"\n",
"\n",
"# [START import]\n",
"from __future__ import print_function\n",
"from ortools.constraint_solver import routing_enums_pb2\n",
"from ortools.constraint_solver import pywrapcp\n",
"# [END import]\n",
"\n",
"\n",
"# [START data_model]\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",
" # [END data_model]\n",
"\n",
"\n",
"# [START distance_callback]\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",
" # [END distance_callback]\n",
"\n",
"\n",
"# [START solution_printer]\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",
" # [END solution_printer]\n",
"\n",
"\n",
"\"\"\"Entry point of the program.\"\"\"\n",
"# Instantiate the data problem.\n",
"# [START data]\n",
"data = create_data_model()\n",
"# [END data]\n",
"\n",
"# Create the routing index manager.\n",
"# [START index_manager]\n",
"manager = pywrapcp.RoutingIndexManager(len(data['locations']),\n",
" data['num_vehicles'], data['depot'])\n",
"# [END index_manager]\n",
"\n",
"# Create Routing Model.\n",
"# [START routing_model]\n",
"routing = pywrapcp.RoutingModel(manager)\n",
"# [END routing_model]\n",
"\n",
"# Create and register a transit callback.\n",
"# [START transit_callback]\n",
"distance_callback = create_distance_callback(data, manager)\n",
"transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
"# [END transit_callback]\n",
"\n",
"# Define cost of each arc.\n",
"# [START arc_cost]\n",
"routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
"# [END arc_cost]\n",
"\n",
"# Setting first solution heuristic.\n",
"# [START parameters]\n",
"search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
"search_parameters.first_solution_strategy = (\n",
" routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
"# [END parameters]\n",
"\n",
"# Solve the problem.\n",
"# [START solve]\n",
"assignment = routing.SolveWithParameters(search_parameters)\n",
"# [END solve]\n",
"\n",
"# Print solution on console.\n",
"# [START print_solution]\n",
"if assignment:\n",
" print_solution(manager, routing, assignment)\n",
"# [END print_solution]\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 4
}