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    "# vrp_drop_nodes"
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/vrp_drop_nodes.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/vrp_drop_nodes.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    "\"\"\"Capacited Vehicles Routing Problem (CVRP).\"\"\"\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    "        [\n",
105    "            0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,\n",
106    "            468, 776, 662\n",
107    "        ],\n",
108    "        [\n",
109    "            548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480, 674,\n",
110    "            1016, 868, 1210\n",
111    "        ],\n",
112    "        [\n",
113    "            776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,\n",
114    "            1130, 788, 1552, 754\n",
115    "        ],\n",
116    "        [\n",
117    "            696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628, 822,\n",
118    "            1164, 560, 1358\n",
119    "        ],\n",
120    "        [\n",
121    "            582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514, 708,\n",
122    "            1050, 674, 1244\n",
123    "        ],\n",
124    "        [\n",
125    "            274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,\n",
126    "            514, 1050, 708\n",
127    "        ],\n",
128    "        [\n",
129    "            502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890, 856,\n",
130    "            514, 1278, 480\n",
131    "        ],\n",
132    "        [\n",
133    "            194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,\n",
134    "            662, 742, 856\n",
135    "        ],\n",
136    "        [\n",
137    "            308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,\n",
138    "            320, 1084, 514\n",
139    "        ],\n",
140    "        [\n",
141    "            194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,\n",
142    "            274, 810, 468\n",
143    "        ],\n",
144    "        [\n",
145    "            536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,\n",
146    "            730, 388, 1152, 354\n",
147    "        ],\n",
148    "        [\n",
149    "            502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,\n",
150    "            308, 650, 274, 844\n",
151    "        ],\n",
152    "        [\n",
153    "            388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0, 194,\n",
154    "            536, 388, 730\n",
155    "        ],\n",
156    "        [\n",
157    "            354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194, 0,\n",
158    "            342, 422, 536\n",
159    "        ],\n",
160    "        [\n",
161    "            468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,\n",
162    "            342, 0, 764, 194\n",
163    "        ],\n",
164    "        [\n",
165    "            776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,\n",
166    "            388, 422, 764, 0, 798\n",
167    "        ],\n",
168    "        [\n",
169    "            662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,\n",
170    "            536, 194, 798, 0\n",
171    "        ],\n",
172    "    ]\n",
173    "    # [START demands_capacities]\n",
174    "    data['demands'] = [0, 1, 1, 3, 6, 3, 6, 8, 8, 1, 2, 1, 2, 6, 6, 8, 8]\n",
175    "    data['vehicle_capacities'] = [15, 15, 15, 15]\n",
176    "    # [END demands_capacities]\n",
177    "    data['num_vehicles'] = 4\n",
178    "    data['depot'] = 0\n",
179    "    return data\n",
180    "    # [END data_model]\n",
181    "\n",
182    "\n",
183    "# [START solution_printer]\n",
184    "def print_solution(data, manager, routing, assignment):\n",
185    "    \"\"\"Prints assignment on console.\"\"\"\n",
186    "    print(f'Objective: {assignment.ObjectiveValue()}')\n",
187    "    # Display dropped nodes.\n",
188    "    dropped_nodes = 'Dropped nodes:'\n",
189    "    for node in range(routing.Size()):\n",
190    "        if routing.IsStart(node) or routing.IsEnd(node):\n",
191    "            continue\n",
192    "        if assignment.Value(routing.NextVar(node)) == node:\n",
193    "            dropped_nodes += ' {}'.format(manager.IndexToNode(node))\n",
194    "    print(dropped_nodes)\n",
195    "    # Display routes\n",
196    "    total_distance = 0\n",
197    "    total_load = 0\n",
198    "    for vehicle_id in range(data['num_vehicles']):\n",
199    "        index = routing.Start(vehicle_id)\n",
200    "        plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\n",
201    "        route_distance = 0\n",
202    "        route_load = 0\n",
203    "        while not routing.IsEnd(index):\n",
204    "            node_index = manager.IndexToNode(index)\n",
205    "            route_load += data['demands'][node_index]\n",
206    "            plan_output += ' {0} Load({1}) -> '.format(node_index, route_load)\n",
207    "            previous_index = index\n",
208    "            index = assignment.Value(routing.NextVar(index))\n",
209    "            route_distance += routing.GetArcCostForVehicle(\n",
210    "                previous_index, index, vehicle_id)\n",
211    "        plan_output += ' {0} Load({1})\\n'.format(manager.IndexToNode(index),\n",
212    "                                                 route_load)\n",
213    "        plan_output += 'Distance of the route: {}m\\n'.format(route_distance)\n",
214    "        plan_output += 'Load of the route: {}\\n'.format(route_load)\n",
215    "        print(plan_output)\n",
216    "        total_distance += route_distance\n",
217    "        total_load += route_load\n",
218    "    print('Total Distance of all routes: {}m'.format(total_distance))\n",
219    "    print('Total Load of all routes: {}'.format(total_load))\n",
220    "    # [END solution_printer]\n",
221    "\n",
222    "\n",
223    "\"\"\"Solve the CVRP problem.\"\"\"\n",
224    "# Instantiate the data problem.\n",
225    "# [START data]\n",
226    "data = create_data_model()\n",
227    "# [END data]\n",
228    "\n",
229    "# Create the routing index manager.\n",
230    "# [START index_manager]\n",
231    "manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),\n",
232    "                                       data['num_vehicles'], data['depot'])\n",
233    "# [END index_manager]\n",
234    "\n",
235    "# Create Routing Model.\n",
236    "# [START routing_model]\n",
237    "routing = pywrapcp.RoutingModel(manager)\n",
238    "\n",
239    "# [END routing_model]\n",
240    "\n",
241    "# Create and register a transit callback.\n",
242    "# [START transit_callback]\n",
243    "def distance_callback(from_index, to_index):\n",
244    "    \"\"\"Returns the distance between the two nodes.\"\"\"\n",
245    "    # Convert from routing variable Index to distance matrix NodeIndex.\n",
246    "    from_node = manager.IndexToNode(from_index)\n",
247    "    to_node = manager.IndexToNode(to_index)\n",
248    "    return data['distance_matrix'][from_node][to_node]\n",
249    "\n",
250    "transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
251    "# [END transit_callback]\n",
252    "\n",
253    "# Define cost of each arc.\n",
254    "# [START arc_cost]\n",
255    "routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
256    "\n",
257    "# [END arc_cost]\n",
258    "\n",
259    "# Add Capacity constraint.\n",
260    "# [START capacity_constraint]\n",
261    "def demand_callback(from_index):\n",
262    "    \"\"\"Returns the demand of the node.\"\"\"\n",
263    "    # Convert from routing variable Index to demands NodeIndex.\n",
264    "    from_node = manager.IndexToNode(from_index)\n",
265    "    return data['demands'][from_node]\n",
266    "\n",
267    "demand_callback_index = routing.RegisterUnaryTransitCallback(\n",
268    "    demand_callback)\n",
269    "routing.AddDimensionWithVehicleCapacity(\n",
270    "    demand_callback_index,\n",
271    "    0,  # null capacity slack\n",
272    "    data['vehicle_capacities'],  # vehicle maximum capacities\n",
273    "    True,  # start cumul to zero\n",
274    "    'Capacity')\n",
275    "# Allow to drop nodes.\n",
276    "penalty = 1000\n",
277    "for node in range(1, len(data['distance_matrix'])):\n",
278    "    routing.AddDisjunction([manager.NodeToIndex(node)], penalty)\n",
279    "# [END capacity_constraint]\n",
280    "\n",
281    "# Setting first solution heuristic.\n",
282    "# [START parameters]\n",
283    "search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
284    "search_parameters.first_solution_strategy = (\n",
285    "    routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
286    "search_parameters.local_search_metaheuristic = (\n",
287    "    routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)\n",
288    "search_parameters.time_limit.FromSeconds(1)\n",
289    "# [END parameters]\n",
290    "\n",
291    "# Solve the problem.\n",
292    "# [START solve]\n",
293    "assignment = routing.SolveWithParameters(search_parameters)\n",
294    "# [END solve]\n",
295    "\n",
296    "# Print solution on console.\n",
297    "# [START print_solution]\n",
298    "if assignment:\n",
299    "    print_solution(data, manager, routing, assignment)\n",
300    "# [END print_solution]\n",
301    "\n"
302   ]
303  }
304 ],
305 "metadata": {},
306 "nbformat": 4,
307 "nbformat_minor": 5
308}
309