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    "# vrpgs"
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/vrpgs.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/vrpgs.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    "# Copyright 2015 Tin Arm Engineering AB\n",
80    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
81    "# you may not use this file except in compliance with the License.\n",
82    "# You may obtain a copy of the License at\n",
83    "#\n",
84    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
85    "#\n",
86    "# Unless required by applicable law or agreed to in writing, software\n",
87    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
88    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
89    "# See the License for the specific language governing permissions and\n",
90    "# limitations under the License.\n",
91    "# [START program]\n",
92    "\"\"\"Simple Vehicles Routing Problem (VRP).\n",
93    "\n",
94    "   This is a sample using the routing library python wrapper to solve a VRP\n",
95    "   problem.\n",
96    "   A description of the problem can be found here:\n",
97    "   http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
98    "\n",
99    "   Distances are in meters.\n",
100    "\"\"\"\n",
101    "\n",
102    "# [START import]\n",
103    "import functools\n",
104    "from ortools.constraint_solver import routing_enums_pb2\n",
105    "from ortools.constraint_solver import pywrapcp\n",
106    "# [END import]\n",
107    "\n",
108    "\n",
109    "# [START data_model]\n",
110    "def create_data_model():\n",
111    "    \"\"\"Stores the data for the problem.\"\"\"\n",
112    "    data = {}\n",
113    "    # Locations in block unit\n",
114    "    locations_ = [\n",
115    "        (4, 4),  # depot\n",
116    "        (2, 0),\n",
117    "        (8, 0),  # locations to visit\n",
118    "        (0, 1),\n",
119    "        (1, 1),\n",
120    "        (5, 2),\n",
121    "        (7, 2),\n",
122    "        (3, 3),\n",
123    "        (6, 3),\n",
124    "        (5, 5),\n",
125    "        (8, 5),\n",
126    "        (1, 6),\n",
127    "        (2, 6),\n",
128    "        (3, 7),\n",
129    "        (6, 7),\n",
130    "        (0, 8),\n",
131    "        (7, 8),\n",
132    "    ]\n",
133    "    # Compute locations in meters using the block dimension defined as follow\n",
134    "    # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
135    "    # here we use: 114m x 80m city block\n",
136    "    # src: https://nyti.ms/2GDoRIe 'NY Times: Know Your distance'\n",
137    "    data['locations'] = [(l[0] * 114, l[1] * 80) for l in locations_]\n",
138    "    data['num_locations'] = len(data['locations'])\n",
139    "    data['num_vehicles'] = 4\n",
140    "    data['depot'] = 0\n",
141    "    return data\n",
142    "\n",
143    "# [END data_model]\n",
144    "\n",
145    "\n",
146    "# [START solution_printer]\n",
147    "def print_solution(data, manager, routing, assignment):\n",
148    "    \"\"\"Prints solution on console.\"\"\"\n",
149    "    print(f'Objective: {assignment.ObjectiveValue()}')\n",
150    "    total_distance = 0\n",
151    "    for vehicle_id in range(data['num_vehicles']):\n",
152    "        index = routing.Start(vehicle_id)\n",
153    "        plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\n",
154    "        route_distance = 0\n",
155    "        while not routing.IsEnd(index):\n",
156    "            plan_output += ' {} ->'.format(manager.IndexToNode(index))\n",
157    "            previous_index = index\n",
158    "            index = assignment.Value(routing.NextVar(index))\n",
159    "            route_distance += routing.GetArcCostForVehicle(\n",
160    "                previous_index, index, vehicle_id)\n",
161    "        plan_output += ' {}\\n'.format(manager.IndexToNode(index))\n",
162    "        plan_output += 'Distance of the route: {}m\\n'.format(route_distance)\n",
163    "        print(plan_output)\n",
164    "        total_distance += route_distance\n",
165    "    print('Total Distance of all routes: {}m'.format(total_distance))\n",
166    "\n",
167    "# [END solution_printer]\n",
168    "\n",
169    "\n",
170    "#######################\n",
171    "# Problem Constraints #\n",
172    "#######################\n",
173    "def manhattan_distance(position_1, position_2):\n",
174    "    \"\"\"Computes the Manhattan distance between two points.\"\"\"\n",
175    "    return (abs(position_1[0] - position_2[0]) +\n",
176    "            abs(position_1[1] - position_2[1]))\n",
177    "\n",
178    "\n",
179    "def create_distance_evaluator(data):\n",
180    "    \"\"\"Creates callback to return distance between points.\"\"\"\n",
181    "    distances_ = {}\n",
182    "    # precompute distance between location to have distance callback in O(1)\n",
183    "    for from_node in range(data['num_locations']):\n",
184    "        distances_[from_node] = {}\n",
185    "        for to_node in range(data['num_locations']):\n",
186    "            if from_node == to_node:\n",
187    "                distances_[from_node][to_node] = 0\n",
188    "            else:\n",
189    "                distances_[from_node][to_node] = (manhattan_distance(\n",
190    "                    data['locations'][from_node], data['locations'][to_node]))\n",
191    "\n",
192    "    def distance_evaluator(manager, from_index, to_index):\n",
193    "        \"\"\"Returns the manhattan distance between the two nodes.\"\"\"\n",
194    "        # Convert from routing variable Index to distance matrix NodeIndex.\n",
195    "        from_node = manager.IndexToNode(from_index)\n",
196    "        to_node = manager.IndexToNode(to_index)\n",
197    "        return distances_[from_node][to_node]\n",
198    "\n",
199    "    return distance_evaluator\n",
200    "\n",
201    "\n",
202    "def add_distance_dimension(routing, distance_evaluator_index):\n",
203    "    \"\"\"Add Global Span constraint.\"\"\"\n",
204    "    distance = 'Distance'\n",
205    "    routing.AddDimension(\n",
206    "        distance_evaluator_index,\n",
207    "        0,  # null slack\n",
208    "        3000,  # maximum distance per vehicle\n",
209    "        True,  # start cumul to zero\n",
210    "        distance)\n",
211    "    distance_dimension = routing.GetDimensionOrDie(distance)\n",
212    "    # Try to minimize the max distance among vehicles.\n",
213    "    # /!\\ It doesn't mean the standard deviation is minimized\n",
214    "    distance_dimension.SetGlobalSpanCostCoefficient(100)\n",
215    "\n",
216    "\n",
217    "\"\"\"Entry point of the program.\"\"\"\n",
218    "# Instantiate the data problem.\n",
219    "# [START data]\n",
220    "data = create_data_model()\n",
221    "# [END data]\n",
222    "\n",
223    "# Create the routing index manager.\n",
224    "# [START index_manager]\n",
225    "manager = pywrapcp.RoutingIndexManager(data['num_locations'],\n",
226    "                                       data['num_vehicles'], data['depot'])\n",
227    "# [END index_manager]\n",
228    "\n",
229    "# Create Routing Model.\n",
230    "# [START routing_model]\n",
231    "routing = pywrapcp.RoutingModel(manager)\n",
232    "# [END routing_model]\n",
233    "\n",
234    "# Define weight of each edge\n",
235    "# [START transit_callback]\n",
236    "distance_evaluator_index = routing.RegisterTransitCallback(\n",
237    "    functools.partial(create_distance_evaluator(data), manager))\n",
238    "# [END transit_callback]\n",
239    "\n",
240    "# Define cost of each arc.\n",
241    "# [START arc_cost]\n",
242    "routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\n",
243    "# [END arc_cost]\n",
244    "\n",
245    "# Add Distance constraint.\n",
246    "# [START distance_constraint]\n",
247    "add_distance_dimension(routing, distance_evaluator_index)\n",
248    "# [END distance_constraint]\n",
249    "\n",
250    "# Setting first solution heuristic.\n",
251    "# [START parameters]\n",
252    "search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
253    "search_parameters.first_solution_strategy = (\n",
254    "    routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
255    "# [END parameters]\n",
256    "\n",
257    "# Solve the problem.\n",
258    "# [START solve]\n",
259    "solution = routing.SolveWithParameters(search_parameters)\n",
260    "# [END solve]\n",
261    "\n",
262    "# Print solution on console.\n",
263    "# [START print_solution]\n",
264    "if solution:\n",
265    "    print_solution(data, manager, routing, solution)\n",
266    "else:\n",
267    "    print('No solution found !')\n",
268    "# [END print_solution]\n",
269    "\n"
270   ]
271  }
272 ],
273 "metadata": {},
274 "nbformat": 4,
275 "nbformat_minor": 5
276}
277