Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

pctsp_ortools.py 8.2 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
  1. #!/usr/bin/env python
  2. # This Python file uses the following encoding: utf-8
  3. # Copyright 2015 Tin Arm Engineering AB
  4. # Copyright 2018 Google LLC
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Capacitated Vehicle Routing Problem (CVRP).
  17. This is a sample using the routing library python wrapper to solve a CVRP
  18. problem.
  19. A description of the problem can be found here:
  20. http://en.wikipedia.org/wiki/Vehicle_routing_problem.
  21. Distances are in meters.
  22. """
  23. from __future__ import print_function
  24. from collections import namedtuple
  25. from six.moves import xrange
  26. from ortools.constraint_solver import pywrapcp
  27. from ortools.constraint_solver import routing_enums_pb2
  28. import math
  29. ###########################
  30. # Problem Data Definition #
  31. ###########################
  32. # Vehicle declaration
  33. Vehicle = namedtuple('Vehicle', ['capacity'])
  34. def float_to_scaled_int(v):
  35. return int(v * 10000000 + 0.5)
  36. class DataProblem():
  37. """Stores the data for the problem"""
  38. def __init__(self, depot, loc, prize, penalty, min_prize):
  39. """Initializes the data for the problem"""
  40. # Locations in block unit
  41. self._locations = [(float_to_scaled_int(l[0]), float_to_scaled_int(l[1])) for l in [depot] + loc]
  42. self._prizes = [float_to_scaled_int(v) for v in prize]
  43. self._penalties = [float_to_scaled_int(v) for v in penalty]
  44. # Check that min_prize is feasible
  45. assert sum(prize) >= min_prize
  46. # After scaling and rounding, however, it can possible not be feasible so relax constraint
  47. self._min_prize = min(float_to_scaled_int(min_prize), sum(self.prizes))
  48. @property
  49. def vehicle(self):
  50. """Gets a vehicle"""
  51. return Vehicle()
  52. @property
  53. def num_vehicles(self):
  54. """Gets number of vehicles"""
  55. return 1
  56. @property
  57. def locations(self):
  58. """Gets locations"""
  59. return self._locations
  60. @property
  61. def num_locations(self):
  62. """Gets number of locations"""
  63. return len(self.locations)
  64. @property
  65. def depot(self):
  66. """Gets depot location index"""
  67. return 0
  68. @property
  69. def prizes(self):
  70. """Gets prizes at each location"""
  71. return self._prizes
  72. @property
  73. def penalties(self):
  74. """Gets penalties at each location"""
  75. return self._penalties
  76. @property
  77. def min_prize(self):
  78. """Gets penalties at each location"""
  79. return self._min_prize
  80. #######################
  81. # Problem Constraints #
  82. #######################
  83. def euclidian_distance(position_1, position_2):
  84. """Computes the Euclidian distance between two points"""
  85. return int(math.sqrt((position_1[0] - position_2[0]) ** 2 + (position_1[1] - position_2[1]) ** 2) + 0.5)
  86. class CreateDistanceEvaluator(object): # pylint: disable=too-few-public-methods
  87. """Creates callback to return distance between points."""
  88. def __init__(self, data):
  89. """Initializes the distance matrix."""
  90. self._distances = {}
  91. # precompute distance between location to have distance callback in O(1)
  92. for from_node in xrange(data.num_locations):
  93. self._distances[from_node] = {}
  94. for to_node in xrange(data.num_locations):
  95. if from_node == to_node:
  96. self._distances[from_node][to_node] = 0
  97. else:
  98. self._distances[from_node][to_node] = (
  99. euclidian_distance(data.locations[from_node],
  100. data.locations[to_node]))
  101. def distance_evaluator(self, from_node, to_node):
  102. """Returns the manhattan distance between the two nodes"""
  103. return self._distances[from_node][to_node]
  104. class CreatePrizeEvaluator(object): # pylint: disable=too-few-public-methods
  105. """Creates callback to get prizes at each location."""
  106. def __init__(self, data):
  107. """Initializes the prize array."""
  108. self._prizes = data.prizes
  109. def prize_evaluator(self, from_node, to_node):
  110. """Returns the prize of the current node"""
  111. del to_node
  112. return 0 if from_node == 0 else self._prizes[from_node - 1]
  113. def add_min_prize_constraints(routing, data, prize_evaluator, min_prize):
  114. """Adds capacity constraint"""
  115. prize = 'Prize'
  116. routing.AddDimension(
  117. prize_evaluator,
  118. 0, # null capacity slack
  119. sum(data.prizes), # No upper bound
  120. True, # start cumul to zero
  121. prize)
  122. capacity_dimension = routing.GetDimensionOrDie(prize)
  123. for vehicle in xrange(data.num_vehicles): # only single vehicle
  124. capacity_dimension.CumulVar(routing.End(vehicle)).RemoveInterval(0, min_prize)
  125. def add_distance_constraint(routing, distance_evaluator, maximum_distance):
  126. """Add Global Span constraint"""
  127. distance = "Distance"
  128. routing.AddDimension(
  129. distance_evaluator,
  130. 0, # null slack
  131. maximum_distance, # maximum distance per vehicle
  132. True, # start cumul to zero
  133. distance)
  134. ###########
  135. # Printer #
  136. ###########
  137. def print_solution(data, routing, assignment):
  138. """Prints assignment on console"""
  139. print('Objective: {}'.format(assignment.ObjectiveValue()))
  140. total_distance = 0
  141. total_load = 0
  142. capacity_dimension = routing.GetDimensionOrDie('Capacity')
  143. for vehicle_id in xrange(data.num_vehicles):
  144. index = routing.Start(vehicle_id)
  145. plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
  146. distance = 0
  147. while not routing.IsEnd(index):
  148. load_var = capacity_dimension.CumulVar(index)
  149. plan_output += ' {} Load({}) -> '.format(
  150. routing.IndexToNode(index), assignment.Value(load_var))
  151. previous_index = index
  152. index = assignment.Value(routing.NextVar(index))
  153. distance += routing.GetArcCostForVehicle(previous_index, index,
  154. vehicle_id)
  155. load_var = capacity_dimension.CumulVar(index)
  156. plan_output += ' {0} Load({1})\n'.format(
  157. routing.IndexToNode(index), assignment.Value(load_var))
  158. plan_output += 'Distance of the route: {}m\n'.format(distance)
  159. plan_output += 'Load of the route: {}\n'.format(assignment.Value(load_var))
  160. print(plan_output)
  161. total_distance += distance
  162. total_load += assignment.Value(load_var)
  163. print('Total Distance of all routes: {}m'.format(total_distance))
  164. print('Total Load of all routes: {}'.format(total_load))
  165. def solve_pctsp_ortools(depot, loc, prize, penalty, min_prize, sec_local_search=0):
  166. data = DataProblem(depot, loc, prize, penalty, min_prize)
  167. # Create Routing Model
  168. routing = pywrapcp.RoutingModel(data.num_locations, data.num_vehicles,
  169. data.depot)
  170. # Define weight of each edge
  171. distance_evaluator = CreateDistanceEvaluator(data).distance_evaluator
  172. routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator)
  173. # Add minimum total prize constraint
  174. prize_evaluator = CreatePrizeEvaluator(data).prize_evaluator
  175. add_min_prize_constraints(routing, data, prize_evaluator, data.min_prize)
  176. # Add penalties for missed nodes
  177. nodes = [routing.AddDisjunction([int(c + 1)], p) for c, p in enumerate(data.penalties)]
  178. # Setting first solution heuristic (cheapest addition).
  179. search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()
  180. search_parameters.first_solution_strategy = (
  181. routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
  182. if sec_local_search > 0:
  183. # Additionally do local search
  184. search_parameters.local_search_metaheuristic = (
  185. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  186. search_parameters.time_limit_ms = 1000 * sec_local_search
  187. # Solve the problem.
  188. assignment = routing.SolveWithParameters(search_parameters)
  189. assert assignment is not None, "ORTools was unable to find a feasible solution"
  190. index = routing.Start(0)
  191. route = []
  192. while not routing.IsEnd(index):
  193. node_index = routing.IndexToNode(index)
  194. route.append(node_index)
  195. index = assignment.Value(routing.NextVar(index))
  196. return assignment.ObjectiveValue() / 10000000., route
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...