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_baseline.py 20 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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
  1. import argparse
  2. import os
  3. import numpy as np
  4. from utils import run_all_in_pool
  5. from utils.data_utils import check_extension, load_dataset, save_dataset
  6. from subprocess import check_call, check_output
  7. import re
  8. import time
  9. from datetime import timedelta
  10. import random
  11. from scipy.spatial import distance_matrix
  12. from .salesman.pctsp.model.pctsp import Pctsp
  13. from .salesman.pctsp.algo.ilocal_search import ilocal_search
  14. from .salesman.pctsp.model import solution
  15. MAX_LENGTH_TOL = 1e-5
  16. def get_pctsp_executable():
  17. path = os.path.join("pctsp", "PCTSP", "PCPTSP")
  18. sourcefile = os.path.join(path, "main.cpp")
  19. execfile = os.path.join(path, "main.out")
  20. if not os.path.isfile(execfile):
  21. print ("Compiling...")
  22. check_call(["g++", "-g", "-Wall", sourcefile, "-std=c++11", "-o", execfile])
  23. print ("Done!")
  24. assert os.path.isfile(execfile), "{} does not exist! Compilation failed?".format(execfile)
  25. return os.path.abspath(execfile)
  26. def solve_pctsp_log(executable, directory, name, depot, loc, penalty, deterministic_prize, stochastic_prize, runs=10):
  27. problem_filename = os.path.join(directory, "{}.pctsp{}.pctsp".format(name, runs))
  28. output_filename = os.path.join(directory, "{}.pctsp{}.pkl".format(name, runs))
  29. log_filename = os.path.join(directory, "{}.pctsp{}.log".format(name, runs))
  30. try:
  31. # May have already been run
  32. if not os.path.isfile(output_filename):
  33. write_pctsp(problem_filename, depot, loc, penalty, deterministic_prize, name=name)
  34. with open(log_filename, 'w') as f:
  35. start = time.time()
  36. output = check_output(
  37. # exe, filename, min_total_prize (=1), num_runs
  38. [executable, problem_filename, float_to_scaled_int_str(1.), str(runs)],
  39. stderr=f
  40. ).decode('utf-8')
  41. duration = time.time() - start
  42. f.write(output)
  43. save_dataset((output, duration), output_filename)
  44. else:
  45. output, duration = load_dataset(output_filename)
  46. # Now parse output
  47. tour = None
  48. for line in output.splitlines():
  49. heading = "Best Result Route: "
  50. if line[:len(heading)] == heading:
  51. tour = np.array(line[len(heading):].split(" ")).astype(int)
  52. break
  53. assert tour is not None, "Could not find tour in output!"
  54. assert tour[0] == 0, "Tour should start with depot"
  55. assert tour[-1] == 0, "Tour should end with depot"
  56. tour = tour[1:-1] # Strip off depot
  57. return calc_pctsp_cost(depot, loc, penalty, deterministic_prize, tour), tour.tolist(), duration
  58. except Exception as e:
  59. print("Exception occured")
  60. print(e)
  61. return None
  62. def solve_stochastic_pctsp_log(
  63. executable, directory, name, depot, loc, penalty, deterministic_prize, stochastic_prize, runs=10, append='all'):
  64. try:
  65. problem_filename = os.path.join(directory, "{}.stochpctsp{}{}.pctsp".format(name, append, runs))
  66. output_filename = os.path.join(directory, "{}.stochpctsp{}{}.pkl".format(name, append, runs))
  67. log_filename = os.path.join(directory, "{}.stochpctsp{}{}.log".format(name, append, runs))
  68. # May have already been run
  69. if not os.path.isfile(output_filename):
  70. total_start = time.time()
  71. outputs = []
  72. durations = []
  73. final_tour = []
  74. coord = [depot] + loc
  75. mask = np.zeros(len(coord), dtype=bool)
  76. dist = distance_matrix(coord, coord)
  77. penalty = np.array(penalty)
  78. deterministic_prize = np.array(deterministic_prize)
  79. it = 0
  80. total_collected_prize = 0.
  81. # As long as we have not visited all nodes we repeat
  82. # even though we have already satisfied the total prize collected constraint
  83. # since the algorithm may decide to include more nodes to avoid further penalties
  84. while len(final_tour) < len(stochastic_prize):
  85. # Mask all nodes already visited (not the depot)
  86. mask[final_tour] = True
  87. # The distance from the 'start' or 'depot' is the distance from the 'current node'
  88. # this way we mimic as if we have a separate start and end by the assymetric distance matrix
  89. # Note: this violates the triangle inequality and the distance from 'depot to depot' becomes nonzero
  90. # but the program seems to deal with this well
  91. if len(final_tour) > 0: # in the first iteration we are at depot and distance matrix is ok
  92. dist[0, :] = dist[final_tour[-1], :]
  93. remaining_deterministic_prize = deterministic_prize[~mask[1:]]
  94. write_pctsp_dist(problem_filename,
  95. dist[np.ix_(~mask, ~mask)], penalty[~mask[1:]], remaining_deterministic_prize)
  96. # If the remaining deterministic prize is less than the prize we should still collect
  97. # set this lower value as constraint since otherwise problem is infeasible
  98. # compute total remaining deterministic prize after converting to ints
  99. # otherwise we may still have problems with rounding
  100. # Note we need to clip 1 - total_collected_prize between 0 (constraint can already be satisfied)
  101. # and the maximum achievable with the remaining_deterministic_prize
  102. min_prize_int = max(0, min(
  103. float_to_scaled_int(1. - total_collected_prize),
  104. sum([float_to_scaled_int(v) for v in remaining_deterministic_prize])
  105. ))
  106. with open(log_filename, 'a') as f:
  107. start = time.time()
  108. output = check_output(
  109. # exe, filename, min_total_prize (=1), num_runs
  110. [executable, problem_filename, str(min_prize_int), str(runs)],
  111. stderr=f
  112. ).decode('utf-8')
  113. durations.append(time.time() - start)
  114. outputs.append(output)
  115. # Now parse output
  116. tour = None
  117. for line in output.splitlines():
  118. heading = "Best Result Route: "
  119. if line[:len(heading)] == heading:
  120. tour = np.array(line[len(heading):].split(" ")).astype(int)
  121. break
  122. assert tour is not None, "Could not find tour in output!"
  123. assert tour[0] == 0, "Tour should start with depot"
  124. assert tour[-1] == 0, "Tour should end with depot"
  125. tour = tour[1:-1] # Strip off depot
  126. # Now find to which nodes these correspond
  127. tour_node_ids = np.arange(len(coord), dtype=int)[~mask][tour]
  128. if len(tour_node_ids) == 0:
  129. # The inner algorithm can decide to stop, but does not have to
  130. assert total_collected_prize > 1 - 1e-5, "Collected prize should be one"
  131. break
  132. if append == 'first':
  133. final_tour.append(tour_node_ids[0])
  134. elif append == 'half':
  135. final_tour.extend(tour_node_ids[:max(len(tour_node_ids) // 2, 1)])
  136. else:
  137. assert append == 'all'
  138. final_tour.extend(tour_node_ids)
  139. total_collected_prize = calc_pctsp_total(stochastic_prize, final_tour)
  140. it = it + 1
  141. os.remove(problem_filename)
  142. final_cost = calc_pctsp_cost(depot, loc, penalty, stochastic_prize, final_tour)
  143. total_duration = time.time() - total_start
  144. save_dataset((final_cost, final_tour, total_duration, outputs, durations), output_filename)
  145. else:
  146. final_cost, final_tour, total_duration, outputs, durations = load_dataset(output_filename)
  147. return final_cost, final_tour, total_duration
  148. except Exception as e:
  149. print("Exception occured")
  150. print(e)
  151. return None
  152. def solve_salesman(directory, name, depot, loc, penalty, deterministic_prize, stochastic_prize, runs=10):
  153. problem_filename = os.path.join(directory, "{}.salesman{}.pctsp".format(name, runs))
  154. output_filename = os.path.join(directory, "{}.salesman{}.pkl".format(name, runs))
  155. try:
  156. # May have already been run
  157. if not os.path.isfile(output_filename):
  158. write_pctsp(problem_filename, depot, loc, penalty, deterministic_prize, name=name)
  159. start = time.time()
  160. random.seed(1234)
  161. pctsp = Pctsp()
  162. pctsp.load(problem_filename, float_to_scaled_int(1.))
  163. s = solution.random(pctsp, start_size=int(len(pctsp.prize) * 0.7))
  164. s = ilocal_search(s, n_runs=runs)
  165. output = (s.route[:s.size], s.quality)
  166. duration = time.time() - start
  167. save_dataset((output, duration), output_filename)
  168. else:
  169. output, duration = load_dataset(output_filename)
  170. # Now parse output
  171. tour = output[0][:]
  172. assert tour[0] == 0, "Tour should start with depot"
  173. assert tour[-1] != 0, "Tour should not end with depot"
  174. tour = tour[1:] # Strip off depot
  175. total_cost = calc_pctsp_cost(depot, loc, penalty, deterministic_prize, tour)
  176. assert (float_to_scaled_int(total_cost) - output[1]) / float(output[1]) < 1e-5
  177. return total_cost, tour, duration
  178. except Exception as e:
  179. print("Exception occured")
  180. print(e)
  181. return None
  182. def solve_gurobi(directory, name, depot, loc, penalty, deterministic_prize, stochastic_prize,
  183. disable_cache=False, timeout=None, gap=None):
  184. # Lazy import so we do not need to have gurobi installed to run this script
  185. from .pctsp_gurobi import solve_euclidian_pctsp as solve_euclidian_pctsp_gurobi
  186. try:
  187. problem_filename = os.path.join(directory, "{}.gurobi{}{}.pkl".format(
  188. name, "" if timeout is None else "t{}".format(timeout), "" if gap is None else "gap{}".format(gap)))
  189. if os.path.isfile(problem_filename) and not disable_cache:
  190. (cost, tour, duration) = load_dataset(problem_filename)
  191. else:
  192. # 0 = start, 1 = end so add depot twice
  193. start = time.time()
  194. # Must collect 1 or the sum of the prices if it is less then 1.
  195. cost, tour = solve_euclidian_pctsp_gurobi(
  196. depot, loc, penalty, deterministic_prize, min(sum(deterministic_prize), 1.),
  197. threads=1, timeout=timeout, gap=gap
  198. )
  199. duration = time.time() - start # Measure clock time
  200. save_dataset((cost, tour, duration), problem_filename)
  201. # First and last node are depot(s), so first node is 2 but should be 1 (as depot is 0) so subtract 1
  202. assert tour[0] == 0
  203. tour = tour[1:]
  204. total_cost = calc_pctsp_cost(depot, loc, penalty, deterministic_prize, tour)
  205. assert abs(total_cost - cost) <= 1e-5, "Cost is incorrect"
  206. return total_cost, tour, duration
  207. except Exception as e:
  208. # For some stupid reason, sometimes OR tools cannot find a feasible solution?
  209. # By letting it fail we do not get total results, but we can retry by the caching mechanism
  210. print("Exception occured")
  211. print(e)
  212. return None
  213. def solve_ortools(directory, name, depot, loc, penalty, deterministic_prize, stochastic_prize,
  214. sec_local_search=0, disable_cache=False):
  215. # Lazy import so we do not require ortools by default
  216. from .pctsp_ortools import solve_pctsp_ortools
  217. try:
  218. problem_filename = os.path.join(directory, "{}.ortools{}.pkl".format(name, sec_local_search))
  219. if os.path.isfile(problem_filename) and not disable_cache:
  220. objval, tour, duration = load_dataset(problem_filename)
  221. else:
  222. # 0 = start, 1 = end so add depot twice
  223. start = time.time()
  224. objval, tour = solve_pctsp_ortools(depot, loc, deterministic_prize, penalty,
  225. min(sum(deterministic_prize), 1.), sec_local_search=sec_local_search)
  226. duration = time.time() - start
  227. save_dataset((objval, tour, duration), problem_filename)
  228. assert tour[0] == 0, "Tour must start with depot"
  229. tour = tour[1:]
  230. total_cost = calc_pctsp_cost(depot, loc, penalty, deterministic_prize, tour)
  231. assert abs(total_cost - objval) <= 1e-5, "Cost is incorrect"
  232. return total_cost, tour, duration
  233. except Exception as e:
  234. # For some stupid reason, sometimes OR tools cannot find a feasible solution?
  235. # By letting it fail we do not get total results, but we dcan retry by the caching mechanism
  236. print("Exception occured")
  237. print(e)
  238. return None
  239. def calc_pctsp_total(vals, tour):
  240. # Subtract 1 since vals index start with 0 while tour indexing starts with 1 as depot is 0
  241. assert (np.array(tour) > 0).all(), "Depot cannot be in tour"
  242. return np.array(vals)[np.array(tour) - 1].sum()
  243. def calc_pctsp_length(depot, loc, tour):
  244. loc_with_depot = np.vstack((np.array(depot)[None, :], np.array(loc)))
  245. sorted_locs = loc_with_depot[np.concatenate(([0], tour, [0]))]
  246. return np.linalg.norm(sorted_locs[1:] - sorted_locs[:-1], axis=-1).sum()
  247. def calc_pctsp_cost(depot, loc, penalty, prize, tour):
  248. # With some tolerance we should satisfy minimum prize
  249. assert len(np.unique(tour)) == len(tour), "Tour cannot contain duplicates"
  250. assert calc_pctsp_total(prize, tour) >= 1 - 1e-5 or len(tour) == len(prize), \
  251. "Tour should collect at least 1 as total prize or visit all nodes"
  252. # Penalty is only incurred for locations not visited, so charge total penalty minus penalty of locations visited
  253. return calc_pctsp_length(depot, loc, tour) + np.sum(penalty) - calc_pctsp_total(penalty, tour)
  254. def write_pctsp(filename, depot, loc, penalty, prize, name="problem"):
  255. coord = [depot] + loc
  256. return write_pctsp_dist(filename, distance_matrix(coord, coord), penalty, prize)
  257. def float_to_scaled_int_str(v): # Program only accepts ints so scale everything by 10^7
  258. return str(float_to_scaled_int(v))
  259. def float_to_scaled_int(v):
  260. return int(v * 10000000 + 0.5)
  261. def write_pctsp_dist(filename, dist, penalty, prize):
  262. with open(filename, 'w') as f:
  263. f.write("\n".join([
  264. "",
  265. " ".join([float_to_scaled_int_str(p) for p in [0] + list(prize)]),
  266. "",
  267. "",
  268. " ".join([float_to_scaled_int_str(p) for p in [0] + list(penalty)]),
  269. "",
  270. "",
  271. *(
  272. " ".join(float_to_scaled_int_str(d) for d in d_row)
  273. for d_row in dist
  274. )
  275. ]))
  276. if __name__ == "__main__":
  277. parser = argparse.ArgumentParser()
  278. parser.add_argument("method",
  279. help="Name of the method to evaluate, 'pctsp', 'salesman' or 'stochpctsp(first|half|all)'")
  280. parser.add_argument("datasets", nargs='+', help="Filename of the dataset(s) to evaluate")
  281. parser.add_argument("-f", action='store_true', help="Set true to overwrite")
  282. parser.add_argument("-o", default=None, help="Name of the results file to write")
  283. parser.add_argument("--cpus", type=int, help="Number of CPUs to use, defaults to all cores")
  284. parser.add_argument('--disable_cache', action='store_true', help='Disable caching')
  285. parser.add_argument('--progress_bar_mininterval', type=float, default=0.1, help='Minimum interval')
  286. parser.add_argument('-n', type=int, help="Number of instances to process")
  287. parser.add_argument('--offset', type=int, help="Offset where to start processing")
  288. parser.add_argument('--results_dir', default='results', help="Name of results directory")
  289. opts = parser.parse_args()
  290. assert opts.o is None or len(opts.datasets) == 1, "Cannot specify result filename with more than one dataset"
  291. for dataset_path in opts.datasets:
  292. assert os.path.isfile(check_extension(dataset_path)), "File does not exist!"
  293. dataset_basename, ext = os.path.splitext(os.path.split(dataset_path)[-1])
  294. if opts.o is None:
  295. results_dir = os.path.join(opts.results_dir, "pctsp", dataset_basename)
  296. os.makedirs(results_dir, exist_ok=True)
  297. out_file = os.path.join(results_dir, "{}{}{}-{}{}".format(
  298. dataset_basename,
  299. "offs{}".format(opts.offset) if opts.offset is not None else "",
  300. "n{}".format(opts.n) if opts.n is not None else "",
  301. opts.method, ext
  302. ))
  303. else:
  304. out_file = opts.o
  305. assert opts.f or not os.path.isfile(
  306. out_file), "File already exists! Try running with -f option to overwrite."
  307. match = re.match(r'^([a-z]+)(\d*)$', opts.method)
  308. assert match
  309. method = match[1]
  310. runs = 1 if match[2] == '' else int(match[2])
  311. if method in ("pctsp", "salesman", "gurobi", "gurobigap", "gurobit", "ortools") or method[:10] == "stochpctsp":
  312. target_dir = os.path.join(results_dir, "{}-{}".format(
  313. dataset_basename,
  314. opts.method
  315. ))
  316. assert opts.f or not os.path.isdir(target_dir), \
  317. "Target dir already exists! Try running with -f option to overwrite."
  318. if not os.path.isdir(target_dir):
  319. os.makedirs(target_dir)
  320. dataset = load_dataset(dataset_path)
  321. if method[:6] == "gurobi":
  322. use_multiprocessing = True # We run one thread per instance
  323. def run_func(args):
  324. return solve_gurobi(*args, disable_cache=opts.disable_cache,
  325. timeout=runs if method[6:] == "t" else None,
  326. gap=float(runs) if method[6:] == "gap" else None)
  327. elif method == "pctsp":
  328. executable = get_pctsp_executable()
  329. use_multiprocessing = False
  330. def run_func(args):
  331. return solve_pctsp_log(executable, *args, runs=runs)
  332. elif method == "salesman":
  333. use_multiprocessing = True
  334. def run_func(args):
  335. return solve_salesman(*args, runs=runs)
  336. elif method == "ortools":
  337. use_multiprocessing = True
  338. def run_func(args):
  339. return solve_ortools(*args, sec_local_search=runs, disable_cache=opts.disable_cache)
  340. else:
  341. assert method[:10] == "stochpctsp"
  342. append = method[10:]
  343. assert append in ('first', 'half', 'all')
  344. use_multiprocessing = True
  345. def run_func(args):
  346. return solve_stochastic_pctsp_log(executable, *args, runs=runs, append=append)
  347. results, parallelism = run_all_in_pool(
  348. run_func,
  349. target_dir, dataset, opts, use_multiprocessing=use_multiprocessing
  350. )
  351. else:
  352. assert False, "Unknown method: {}".format(opts.method)
  353. costs, tours, durations = zip(*results) # Not really costs since they should be negative
  354. print("Average cost: {} +- {}".format(np.mean(costs), 2 * np.std(costs) / np.sqrt(len(costs))))
  355. print("Average serial duration: {} +- {}".format(
  356. np.mean(durations), 2 * np.std(durations) / np.sqrt(len(durations))))
  357. print("Average parallel duration: {}".format(np.mean(durations) / parallelism))
  358. print("Calculated total duration: {}".format(timedelta(seconds=int(np.sum(durations) / parallelism))))
  359. save_dataset((results, parallelism), out_file)
Tip!

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

Comments

Loading...