-
Notifications
You must be signed in to change notification settings - Fork 33
/
tools.py
331 lines (273 loc) · 11.7 KB
/
tools.py
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import json
import os
import numpy as np
# https://stackoverflow.com/questions/26646362/numpy-array-is-not-json-serializable
class NumpyJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
def json_dumps_np(data):
return json.dumps(data, cls=NumpyJSONEncoder)
def json_loads_np(json_string):
return lists_to_np(json.loads(json_string))
def lists_to_np(obj):
"""Function will convert lists to numpy recursively."""
if isinstance(obj, dict):
return {k: lists_to_np(v) for k, v in obj.items()}
if isinstance(obj, list):
return np.array(obj)
return obj
def cleanup_tmp_dir(tmp_dir):
if not os.path.isdir(tmp_dir):
return
# Don't use shutil.rmtree for safety :)
for filename in os.listdir(tmp_dir):
filepath = os.path.join(tmp_dir, filename)
if 'problem.vrptw' in filename and os.path.isfile(filepath):
os.remove(filepath)
assert len(os.listdir(tmp_dir)) == 0, "Unexpected files in tmp_dir"
os.rmdir(tmp_dir)
def to_giant_tour(routes, with_depot=True):
# Converts a list of routes to a giant tour with depots
if len(routes) == 0:
return []
tour = list(routes[0])
for route in routes[1:]:
if with_depot:
tour.append(0)
tour.extend(list(route))
return tour
def compute_solution_driving_time(instance, solution):
return sum([
compute_route_driving_time(route, instance['duration_matrix'])
for route in solution
])
def validate_static_solution(instance, solution, allow_skipped_customers=False):
if not allow_skipped_customers:
validate_all_customers_visited(solution, len(instance['coords']) - 1)
for route in solution:
validate_route_capacity(route, instance['demands'], instance['capacity'])
validate_route_time_windows(route, instance['duration_matrix'], instance['time_windows'], instance['service_times'])
return compute_solution_driving_time(instance, solution)
def validate_dynamic_epoch_solution(epoch_instance, epoch_solution):
"""
Validates a solution for a VRPTW instance, raises assertion if not valid
Returns total driving time (excluding waiting time)
"""
# Renumber requests (and depot) to 0,1...n
request_idx = epoch_instance['request_idx']
assert request_idx[0] == 0
assert (request_idx[1:] > request_idx[:-1]).all()
# Look up positions of request idx
solution = [np.searchsorted(request_idx, route) for route in epoch_solution]
# Check that all 'must_dispatch' requests are dispatched
# if 'must_dispatch' in instance:
must_dispatch = epoch_instance['must_dispatch'].copy()
for route in solution:
must_dispatch[route] = False
assert not must_dispatch.any(), f"Some requests must be dispatched but were not: {request_idx[must_dispatch]}"
static_instance = {
k: v for k, v in epoch_instance.items()
if k not in ('request_idx', 'customer_idx', 'must_dispatch')
}
return validate_static_solution(static_instance, solution, allow_skipped_customers=True)
def compute_route_driving_time(route, duration_matrix):
"""Computes the route driving time excluding waiting time between stops"""
# From depot to first stop + first to last stop + last stop to depot
return duration_matrix[0, route[0]] + duration_matrix[route[:-1], route[1:]].sum() + duration_matrix[route[-1], 0]
def validate_all_customers_visited(solution, num_customers):
flat_solution = np.array([stop for route in solution for stop in route])
assert len(flat_solution) == num_customers, "Not all customers are visited"
visited = np.zeros(num_customers + 1) # Add padding for depot
visited[flat_solution] = True
assert visited[1:].all(), "Not all customers are visited"
def validate_route_capacity(route, demands, capacity):
assert sum(demands[route]) <= capacity, f"Capacity validated for route, {sum(demands[route])} > {capacity}"
def validate_route_time_windows(route, dist, timew, service_t, release_t=None):
depot = 0 # For readability, define variable
earliest_start_depot, latest_arrival_depot = timew[depot]
if release_t is not None:
earliest_start_depot = max(earliest_start_depot, release_t[route].max())
current_time = earliest_start_depot + service_t[depot]
prev_stop = depot
for stop in route:
earliest_arrival, latest_arrival = timew[stop]
arrival_time = current_time + dist[prev_stop, stop]
# Wait if we arrive before earliest_arrival
current_time = max(arrival_time, earliest_arrival)
assert current_time <= latest_arrival, f"Time window violated for stop {stop}: {current_time} not in ({earliest_arrival}, {latest_arrival})"
current_time += service_t[stop]
prev_stop = stop
current_time += dist[prev_stop, depot]
assert current_time <= latest_arrival_depot, f"Time window violated for depot: {current_time} not in ({earliest_start_depot}, {latest_arrival_depot})"
def readlines(filename):
try:
with open(filename, 'r') as f:
return f.readlines()
except:
with open(filename, 'rb') as f:
return [line.decode('utf-8', errors='ignore').strip() for line in f.readlines()]
def read_vrptw_solution(filename, return_extra=False):
"""Reads a VRPTW solution in VRPLib format (one route per row)"""
solution = []
extra = {}
for line in readlines(filename):
if line.startswith('Route'):
solution.append(np.array([int(node) for node in line.split(":")[-1].strip().split(" ")]))
else:
if len(line.strip().split(" ")) == 2:
key, val = line.strip().split(" ")
extra[key] = val
if return_extra:
return solution, extra
return solution
def read_vrplib(filename, rounded=True):
loc = []
demand = []
mode = ''
capacity = None
edge_weight_type = None
edge_weight_format = None
duration_matrix = []
service_t = []
timewi = []
with open(filename, 'r') as f:
for line in f:
line = line.strip(' \t\n')
if line == "":
continue
elif line.startswith('CAPACITY'):
capacity = int(line.split(" : ")[1])
elif line.startswith('EDGE_WEIGHT_TYPE'):
edge_weight_type = line.split(" : ")[1]
elif line.startswith('EDGE_WEIGHT_FORMAT'):
edge_weight_format = line.split(" : ")[1]
elif line == 'NODE_COORD_SECTION':
mode = 'coord'
elif line == 'DEMAND_SECTION':
mode = 'demand'
elif line == 'DEPOT_SECTION':
mode = 'depot'
elif line == "EDGE_WEIGHT_SECTION":
mode = 'edge_weights'
assert edge_weight_type == "EXPLICIT"
assert edge_weight_format == "FULL_MATRIX"
elif line == "TIME_WINDOW_SECTION":
mode = "time_windows"
elif line == "SERVICE_TIME_SECTION":
mode = "service_t"
elif line == "EOF":
break
elif mode == 'coord':
node, x, y = line.split() # Split by whitespace or \t, skip duplicate whitespace
node = int(node)
x, y = (int(x), int(y)) if rounded else (float(x), float(y))
if node == 1:
depot = (x, y)
else:
assert node == len(loc) + 2 # 1 is depot, 2 is 0th location
loc.append((x, y))
elif mode == 'demand':
node, d = [int(v) for v in line.split()]
if node == 1:
assert d == 0
demand.append(d)
elif mode == 'edge_weights':
duration_matrix.append(list(map(int if rounded else float, line.split())))
elif mode == 'service_t':
node, t = line.split()
node = int(node)
t = int(t) if rounded else float(t)
if node == 1:
assert t == 0
assert node == len(service_t) + 1
service_t.append(t)
elif mode == 'time_windows':
node, l, u = line.split()
node = int(node)
l, u = (int(l), int(u)) if rounded else (float(l), float(u))
assert node == len(timewi) + 1
timewi.append([l, u])
return {
'is_depot': np.array([1] + [0] * len(loc), dtype=bool),
'coords': np.array([depot] + loc),
'demands': np.array(demand),
'capacity': capacity,
'time_windows': np.array(timewi),
'service_times': np.array(service_t),
'duration_matrix': np.array(duration_matrix) if len(duration_matrix) > 0 else None
}
def write_vrplib(filename, instance, name="problem", euclidean=False, is_vrptw=True):
# LKH/VRP does not take floats (HGS seems to do)
coords = instance['coords']
demands = instance['demands']
is_depot = instance['is_depot']
duration_matrix = instance['duration_matrix']
capacity = instance['capacity']
assert (np.diag(duration_matrix) == 0).all()
assert (demands[~is_depot] > 0).all()
with open(filename, 'w') as f:
f.write("\n".join([
"{} : {}".format(k, v)
for k, v in [
("NAME", name),
("COMMENT", "ORTEC"), # For HGS we need an extra row...
("TYPE", "CVRP"),
("DIMENSION", len(coords)),
("EDGE_WEIGHT_TYPE", "EUC_2D" if euclidean else "EXPLICIT"),
] + ([] if euclidean else [
("EDGE_WEIGHT_FORMAT", "FULL_MATRIX")
]) + [("CAPACITY", capacity)]
]))
f.write("\n")
if not euclidean:
f.write("EDGE_WEIGHT_SECTION\n")
for row in duration_matrix:
f.write("\t".join(map(str, row)))
f.write("\n")
f.write("NODE_COORD_SECTION\n")
f.write("\n".join([
"{}\t{}\t{}".format(i + 1, x, y)
for i, (x, y) in enumerate(coords)
]))
f.write("\n")
f.write("DEMAND_SECTION\n")
f.write("\n".join([
"{}\t{}".format(i + 1, d)
for i, d in enumerate(demands)
]))
f.write("\n")
f.write("DEPOT_SECTION\n")
for i in np.flatnonzero(is_depot):
f.write(f"{i+1}\n")
f.write("-1\n")
if is_vrptw:
service_t = instance['service_times']
timewi = instance['time_windows']
# Following LKH convention
f.write("SERVICE_TIME_SECTION\n")
f.write("\n".join([
"{}\t{}".format(i + 1, s)
for i, s in enumerate(service_t)
]))
f.write("\n")
f.write("TIME_WINDOW_SECTION\n")
f.write("\n".join([
"{}\t{}\t{}".format(i + 1, l, u)
for i, (l, u) in enumerate(timewi)
]))
f.write("\n")
if 'release_times' in instance:
release_times = instance['release_times']
f.write("RELEASE_TIME_SECTION\n")
f.write("\n".join([
"{}\t{}".format(i + 1, s)
for i, s in enumerate(release_times)
]))
f.write("\n")
f.write("EOF\n")