Files
ortools-clone/examples/notebook/constraint_solver/vrpgs.ipynb
2022-04-14 14:31:02 +02:00

248 lines
8.8 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": [
"# vrpgs"
]
},
{
"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/master/examples/notebook/constraint_solver/vrpgs.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/master/ortools/constraint_solver/samples/vrpgs.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/master/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": [
"Simple Vehicles Routing Problem (VRP).\n",
"\n",
" This is a sample using the routing library python wrapper to solve a VRP\n",
" problem.\n",
" A description of the problem can be found here:\n",
" http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
"\n",
" Distances are in meters.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"import functools\n",
"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 unit\n",
" locations_ = [\n",
" (4, 4), # depot\n",
" (2, 0),\n",
" (8, 0), # locations to visit\n",
" (0, 1),\n",
" (1, 1),\n",
" (5, 2),\n",
" (7, 2),\n",
" (3, 3),\n",
" (6, 3),\n",
" (5, 5),\n",
" (8, 5),\n",
" (1, 6),\n",
" (2, 6),\n",
" (3, 7),\n",
" (6, 7),\n",
" (0, 8),\n",
" (7, 8),\n",
" ]\n",
" # Compute locations in meters using the block dimension defined as follow\n",
" # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
" # here we use: 114m x 80m city block\n",
" # src: https://nyti.ms/2GDoRIe 'NY Times: Know Your distance'\n",
" data['locations'] = [(l[0] * 114, l[1] * 80) for l in locations_]\n",
" data['num_locations'] = len(data['locations'])\n",
" data['num_vehicles'] = 4\n",
" data['depot'] = 0\n",
" return data\n",
"\n",
"\n",
"\n",
"def print_solution(data, manager, routing, assignment):\n",
" \"\"\"Prints solution on console.\"\"\"\n",
" print(f'Objective: {assignment.ObjectiveValue()}')\n",
" total_distance = 0\n",
" for vehicle_id in range(data['num_vehicles']):\n",
" index = routing.Start(vehicle_id)\n",
" plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\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(\n",
" previous_index, index, vehicle_id)\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",
" total_distance += route_distance\n",
" print('Total Distance of all routes: {}m'.format(total_distance))\n",
"\n",
"\n",
"\n",
"#######################\n",
"# Problem Constraints #\n",
"#######################\n",
"def manhattan_distance(position_1, position_2):\n",
" \"\"\"Computes the Manhattan distance between two points.\"\"\"\n",
" return (abs(position_1[0] - position_2[0]) +\n",
" abs(position_1[1] - position_2[1]))\n",
"\n",
"\n",
"def create_distance_evaluator(data):\n",
" \"\"\"Creates callback to return distance between points.\"\"\"\n",
" distances_ = {}\n",
" # precompute distance between location to have distance callback in O(1)\n",
" for from_node in range(data['num_locations']):\n",
" distances_[from_node] = {}\n",
" for to_node in range(data['num_locations']):\n",
" if from_node == to_node:\n",
" distances_[from_node][to_node] = 0\n",
" else:\n",
" distances_[from_node][to_node] = (manhattan_distance(\n",
" data['locations'][from_node], data['locations'][to_node]))\n",
"\n",
" def distance_evaluator(manager, 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 = manager.IndexToNode(from_index)\n",
" to_node = manager.IndexToNode(to_index)\n",
" return distances_[from_node][to_node]\n",
"\n",
" return distance_evaluator\n",
"\n",
"\n",
"def add_distance_dimension(routing, distance_evaluator_index):\n",
" \"\"\"Add Global Span constraint.\"\"\"\n",
" distance = 'Distance'\n",
" routing.AddDimension(\n",
" distance_evaluator_index,\n",
" 0, # null slack\n",
" 3000, # maximum distance per vehicle\n",
" True, # start cumul to zero\n",
" distance)\n",
" distance_dimension = routing.GetDimensionOrDie(distance)\n",
" # Try to minimize the max distance among vehicles.\n",
" # /!\\ It doesn't mean the standard deviation is minimized\n",
" distance_dimension.SetGlobalSpanCostCoefficient(100)\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(data['num_locations'],\n",
" data['num_vehicles'], data['depot'])\n",
"\n",
" # Create Routing Model.\n",
" routing = pywrapcp.RoutingModel(manager)\n",
"\n",
" # Define weight of each edge\n",
" distance_evaluator_index = routing.RegisterTransitCallback(\n",
" functools.partial(create_distance_evaluator(data), manager))\n",
"\n",
" # Define cost of each arc.\n",
" routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\n",
"\n",
" # Add Distance constraint.\n",
" add_distance_dimension(routing, distance_evaluator_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",
" solution = routing.SolveWithParameters(search_parameters)\n",
"\n",
" # Print solution on console.\n",
" if solution:\n",
" print_solution(data, manager, routing, solution)\n",
" else:\n",
" print('No solution found !')\n",
"\n",
"\n",
"main()\n",
"\n"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}