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_node_max"
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_node_max.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_node_max.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    "\"\"\"Vehicles Routing Problem (VRP).\n",
92    "\n",
93    "Each route as an associated objective cost equal to the max node value along the\n",
94    "road multiply by a constant factor (4200)\n",
95    "\"\"\"\n",
96    "\n",
97    "# [START import]\n",
98    "from ortools.constraint_solver import routing_enums_pb2\n",
99    "from ortools.constraint_solver import pywrapcp\n",
100    "# [END import]\n",
101    "\n",
102    "\n",
103    "# [START data_model]\n",
104    "def create_data_model():\n",
105    "    \"\"\"Stores the data for the problem.\"\"\"\n",
106    "    data = {}\n",
107    "    data['distance_matrix'] = [\n",
108    "        [\n",
109    "            0, 548, 776, 696, 582, 274, 502, 194, 308, 194, 536, 502, 388, 354,\n",
110    "            468, 776, 662\n",
111    "        ],\n",
112    "        [\n",
113    "            548, 0, 684, 308, 194, 502, 730, 354, 696, 742, 1084, 594, 480,\n",
114    "            674, 1016, 868, 1210\n",
115    "        ],\n",
116    "        [\n",
117    "            776, 684, 0, 992, 878, 502, 274, 810, 468, 742, 400, 1278, 1164,\n",
118    "            1130, 788, 1552, 754\n",
119    "        ],\n",
120    "        [\n",
121    "            696, 308, 992, 0, 114, 650, 878, 502, 844, 890, 1232, 514, 628,\n",
122    "            822, 1164, 560, 1358\n",
123    "        ],\n",
124    "        [\n",
125    "            582, 194, 878, 114, 0, 536, 764, 388, 730, 776, 1118, 400, 514,\n",
126    "            708, 1050, 674, 1244\n",
127    "        ],\n",
128    "        [\n",
129    "            274, 502, 502, 650, 536, 0, 228, 308, 194, 240, 582, 776, 662, 628,\n",
130    "            514, 1050, 708\n",
131    "        ],\n",
132    "        [\n",
133    "            502, 730, 274, 878, 764, 228, 0, 536, 194, 468, 354, 1004, 890,\n",
134    "            856, 514, 1278, 480\n",
135    "        ],\n",
136    "        [\n",
137    "            194, 354, 810, 502, 388, 308, 536, 0, 342, 388, 730, 468, 354, 320,\n",
138    "            662, 742, 856\n",
139    "        ],\n",
140    "        [\n",
141    "            308, 696, 468, 844, 730, 194, 194, 342, 0, 274, 388, 810, 696, 662,\n",
142    "            320, 1084, 514\n",
143    "        ],\n",
144    "        [\n",
145    "            194, 742, 742, 890, 776, 240, 468, 388, 274, 0, 342, 536, 422, 388,\n",
146    "            274, 810, 468\n",
147    "        ],\n",
148    "        [\n",
149    "            536, 1084, 400, 1232, 1118, 582, 354, 730, 388, 342, 0, 878, 764,\n",
150    "            730, 388, 1152, 354\n",
151    "        ],\n",
152    "        [\n",
153    "            502, 594, 1278, 514, 400, 776, 1004, 468, 810, 536, 878, 0, 114,\n",
154    "            308, 650, 274, 844\n",
155    "        ],\n",
156    "        [\n",
157    "            388, 480, 1164, 628, 514, 662, 890, 354, 696, 422, 764, 114, 0,\n",
158    "            194, 536, 388, 730\n",
159    "        ],\n",
160    "        [\n",
161    "            354, 674, 1130, 822, 708, 628, 856, 320, 662, 388, 730, 308, 194,\n",
162    "            0, 342, 422, 536\n",
163    "        ],\n",
164    "        [\n",
165    "            468, 1016, 788, 1164, 1050, 514, 514, 662, 320, 274, 388, 650, 536,\n",
166    "            342, 0, 764, 194\n",
167    "        ],\n",
168    "        [\n",
169    "            776, 868, 1552, 560, 674, 1050, 1278, 742, 1084, 810, 1152, 274,\n",
170    "            388, 422, 764, 0, 798\n",
171    "        ],\n",
172    "        [\n",
173    "            662, 1210, 754, 1358, 1244, 708, 480, 856, 514, 468, 354, 844, 730,\n",
174    "            536, 194, 798, 0\n",
175    "        ],\n",
176    "    ]\n",
177    "    data['value'] = [\n",
178    "        0,  # depot\n",
179    "        42,  # 1\n",
180    "        42,  # 2\n",
181    "        8,  # 3\n",
182    "        8,  # 4\n",
183    "        8,  # 5\n",
184    "        8,  # 6\n",
185    "        8,  # 7\n",
186    "        8,  # 8\n",
187    "        8,  # 9\n",
188    "        8,  # 10\n",
189    "        8,  # 11\n",
190    "        8,  # 12\n",
191    "        8,  # 13\n",
192    "        8,  # 14\n",
193    "        42,  # 15\n",
194    "        42,  # 16\n",
195    "    ]\n",
196    "    assert len(data['distance_matrix']) == len(data['value'])\n",
197    "    data['num_vehicles'] = 4\n",
198    "    data['depot'] = 0\n",
199    "    return data\n",
200    "# [END data_model]\n",
201    "\n",
202    "\n",
203    "# [START solution_printer]\n",
204    "def print_solution(data, manager, routing, solution):\n",
205    "    \"\"\"Prints solution on console.\"\"\"\n",
206    "    print(f'Objective: {solution.ObjectiveValue()}')\n",
207    "    max_route_distance = 0\n",
208    "    dim_one = routing.GetDimensionOrDie('One')\n",
209    "    dim_two = routing.GetDimensionOrDie('Two')\n",
210    "\n",
211    "    for vehicle_id in range(data['num_vehicles']):\n",
212    "        index = routing.Start(vehicle_id)\n",
213    "        plan_output = 'Route for vehicle {}:\\n'.format(vehicle_id)\n",
214    "        route_distance = 0\n",
215    "        while not routing.IsEnd(index):\n",
216    "            one_var = dim_one.CumulVar(index)\n",
217    "            one_slack_var = dim_one.SlackVar(index)\n",
218    "            two_var = dim_two.CumulVar(index)\n",
219    "            two_slack_var = dim_two.SlackVar(index)\n",
220    "            plan_output += ' N:{0} one:({1},{2}) two:({3},{4}) -> '.format(\n",
221    "                manager.IndexToNode(index), solution.Value(one_var),\n",
222    "                solution.Value(one_slack_var), solution.Value(two_var),\n",
223    "                solution.Value(two_slack_var))\n",
224    "            previous_index = index\n",
225    "            index = solution.Value(routing.NextVar(index))\n",
226    "            route_distance += routing.GetArcCostForVehicle(\n",
227    "                previous_index, index, vehicle_id)\n",
228    "        one_var = dim_one.CumulVar(index)\n",
229    "        two_var = dim_two.CumulVar(index)\n",
230    "        plan_output += 'N:{0} one:{1} two:{2}\\n'.format(\n",
231    "            manager.IndexToNode(index), solution.Value(one_var),\n",
232    "            solution.Value(two_var))\n",
233    "        plan_output += 'Distance of the route: {}m\\n'.format(route_distance)\n",
234    "        print(plan_output)\n",
235    "        max_route_distance = max(route_distance, max_route_distance)\n",
236    "    print('Maximum of the route distances: {}m'.format(max_route_distance))\n",
237    "# [END solution_printer]\n",
238    "\n",
239    "\n",
240    "\"\"\"Solve the CVRP problem.\"\"\"\n",
241    "# Instantiate the data problem.\n",
242    "# [START data]\n",
243    "data = create_data_model()\n",
244    "# [END data]\n",
245    "\n",
246    "# Create the routing index manager.\n",
247    "# [START index_manager]\n",
248    "manager = pywrapcp.RoutingIndexManager(\n",
249    "        len(data['distance_matrix']),\n",
250    "        data['num_vehicles'],\n",
251    "        data['depot'])\n",
252    "# [END index_manager]\n",
253    "\n",
254    "# Create Routing Model.\n",
255    "# [START routing_model]\n",
256    "routing = pywrapcp.RoutingModel(manager)\n",
257    "# [END routing_model]\n",
258    "\n",
259    "# Create and register a transit callback.\n",
260    "# [START transit_callback]\n",
261    "def distance_callback(from_index, to_index):\n",
262    "    \"\"\"Returns the distance between the two nodes.\"\"\"\n",
263    "    # Convert from routing variable Index to distance matrix NodeIndex.\n",
264    "    from_node = manager.IndexToNode(from_index)\n",
265    "    to_node = manager.IndexToNode(to_index)\n",
266    "    return data['distance_matrix'][from_node][to_node]\n",
267    "\n",
268    "transit_callback_index = routing.RegisterTransitCallback(distance_callback)\n",
269    "# [END transit_callback]\n",
270    "\n",
271    "# Define cost of each arc.\n",
272    "# [START arc_cost]\n",
273    "routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
274    "# [END arc_cost]\n",
275    "\n",
276    "# Add Distance constraint.\n",
277    "# [START distance_constraint]\n",
278    "dimension_name = 'Distance'\n",
279    "routing.AddDimension(\n",
280    "    transit_callback_index,\n",
281    "    0,  # no slack\n",
282    "    3_000,  # vehicle maximum travel distance\n",
283    "    True,  # start cumul to zero\n",
284    "    dimension_name)\n",
285    "distance_dimension = routing.GetDimensionOrDie(dimension_name)\n",
286    "distance_dimension.SetGlobalSpanCostCoefficient(10)\n",
287    "# [END distance_constraint]\n",
288    "\n",
289    "# Max Node value Constraint.\n",
290    "# Dimension One will be used to compute the max node value up to the node in\n",
291    "# the route and store the result in the SlackVar of the node.\n",
292    "routing.AddConstantDimensionWithSlack(\n",
293    "    0,  # transit 0\n",
294    "    42 * 16,  # capacity: be able to store PEAK*ROUTE_LENGTH in worst case\n",
295    "    42,  # slack_max: to be able to store peak in slack\n",
296    "    True,  #  Fix StartCumulToZero not really matter here\n",
297    "    'One')\n",
298    "dim_one = routing.GetDimensionOrDie('One')\n",
299    "\n",
300    "# Dimension Two will be used to store the max node value in the route end node\n",
301    "# CumulVar so we can use it as an objective cost.\n",
302    "routing.AddConstantDimensionWithSlack(\n",
303    "    0,  # transit 0\n",
304    "    42 * 16,  # capacity: be able to have PEAK value in CumulVar(End)\n",
305    "    42,  # slack_max: to be able to store peak in slack\n",
306    "    True,  #  Fix StartCumulToZero YES here\n",
307    "    'Two')\n",
308    "dim_two = routing.GetDimensionOrDie('Two')\n",
309    "\n",
310    "# force depot Slack to be value since we don't have any predecessor...\n",
311    "# Slack(Depot) = value(Depot)\n",
312    "for v in range(manager.GetNumberOfVehicles()):\n",
313    "    start = routing.Start(v)\n",
314    "    dim_one.SlackVar(start).SetValue(data['value'][0])\n",
315    "    routing.AddToAssignment(dim_one.SlackVar(start))\n",
316    "\n",
317    "    dim_two.SlackVar(start).SetValue(data['value'][0])\n",
318    "    routing.AddToAssignment(dim_two.SlackVar(start))\n",
319    "\n",
320    "# Step by step relation\n",
321    "# Slack(N) = max( Slack(N-1) , value(N) )\n",
322    "solver = routing.solver()\n",
323    "for node in range(1, 17):\n",
324    "    index = manager.NodeToIndex(node)\n",
325    "    routing.AddToAssignment(dim_one.SlackVar(index))\n",
326    "    routing.AddToAssignment(dim_two.SlackVar(index))\n",
327    "    test = []\n",
328    "    for v in range(manager.GetNumberOfVehicles()):\n",
329    "        previous_index = routing.Start(v)\n",
330    "        cond = routing.NextVar(previous_index) == index\n",
331    "        value = solver.Max(dim_one.SlackVar(previous_index),\n",
332    "                           data['value'][node])\n",
333    "        test.append((cond * value).Var())\n",
334    "    for previous in range(1, 17):\n",
335    "        previous_index = manager.NodeToIndex(previous)\n",
336    "        cond = routing.NextVar(previous_index) == index\n",
337    "        value = solver.Max(dim_one.SlackVar(previous_index),\n",
338    "                           data['value'][node])\n",
339    "        test.append((cond * value).Var())\n",
340    "    solver.Add(solver.Sum(test) == dim_one.SlackVar(index))\n",
341    "\n",
342    "# relation between dimensions, copy last node Slack from dim ONE to dim TWO\n",
343    "for node in range(1, 17):\n",
344    "    index = manager.NodeToIndex(node)\n",
345    "    values = []\n",
346    "    for v in range(manager.GetNumberOfVehicles()):\n",
347    "        next_index = routing.End(v)\n",
348    "        cond = routing.NextVar(index) == next_index\n",
349    "        value = dim_one.SlackVar(index)\n",
350    "        values.append((cond * value).Var())\n",
351    "    solver.Add(solver.Sum(values) == dim_two.SlackVar(index))\n",
352    "\n",
353    "# Should force all others dim_two slack var to zero...\n",
354    "for v in range(manager.GetNumberOfVehicles()):\n",
355    "    end = routing.End(v)\n",
356    "    dim_two.SetCumulVarSoftUpperBound(end, 0, 4200)\n",
357    "\n",
358    "# Setting first solution heuristic.\n",
359    "# [START parameters]\n",
360    "search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
361    "search_parameters.first_solution_strategy = (\n",
362    "    routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
363    "search_parameters.local_search_metaheuristic = (\n",
364    "    routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)\n",
365    "# search_parameters.log_search = True\n",
366    "search_parameters.time_limit.FromSeconds(5)\n",
367    "# [END parameters]\n",
368    "\n",
369    "# Solve the problem.\n",
370    "# [START solve]\n",
371    "solution = routing.SolveWithParameters(search_parameters)\n",
372    "# [END solve]\n",
373    "\n",
374    "# Print solution on console.\n",
375    "# [START print_solution]\n",
376    "if solution:\n",
377    "    print_solution(data, manager, routing, solution)\n",
378    "else:\n",
379    "    print('No solution found !')\n",
380    "# [END print_solution]\n",
381    "\n"
382   ]
383  }
384 ],
385 "metadata": {},
386 "nbformat": 4,
387 "nbformat_minor": 5
388}
389