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

tsp_baseline.py 17 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
  1. import argparse
  2. import numpy as np
  3. import os
  4. import time
  5. from datetime import timedelta
  6. from scipy.spatial import distance_matrix
  7. from utils import run_all_in_pool
  8. from utils.data_utils import check_extension, load_dataset, save_dataset
  9. from subprocess import check_call, check_output, CalledProcessError
  10. from problems.vrp.vrp_baseline import get_lkh_executable
  11. import torch
  12. from tqdm import tqdm
  13. import re
  14. def solve_gurobi(directory, name, loc, disable_cache=False, timeout=None, gap=None):
  15. # Lazy import so we do not need to have gurobi installed to run this script
  16. from problems.tsp.tsp_gurobi import solve_euclidian_tsp as solve_euclidian_tsp_gurobi
  17. try:
  18. problem_filename = os.path.join(directory, "{}.gurobi{}{}.pkl".format(
  19. name, "" if timeout is None else "t{}".format(timeout), "" if gap is None else "gap{}".format(gap)))
  20. if os.path.isfile(problem_filename) and not disable_cache:
  21. (cost, tour, duration) = load_dataset(problem_filename)
  22. else:
  23. # 0 = start, 1 = end so add depot twice
  24. start = time.time()
  25. cost, tour = solve_euclidian_tsp_gurobi(loc, threads=1, timeout=timeout, gap=gap)
  26. duration = time.time() - start # Measure clock time
  27. save_dataset((cost, tour, duration), problem_filename)
  28. # First and last node are depot(s), so first node is 2 but should be 1 (as depot is 0) so subtract 1
  29. total_cost = calc_tsp_length(loc, tour)
  30. assert abs(total_cost - cost) <= 1e-5, "Cost is incorrect"
  31. return total_cost, tour, duration
  32. except Exception as e:
  33. # For some stupid reason, sometimes OR tools cannot find a feasible solution?
  34. # By letting it fail we do not get total results, but we dcan retry by the caching mechanism
  35. print("Exception occured")
  36. print(e)
  37. return None
  38. def solve_concorde_log(executable, directory, name, loc, disable_cache=False):
  39. problem_filename = os.path.join(directory, "{}.tsp".format(name))
  40. tour_filename = os.path.join(directory, "{}.tour".format(name))
  41. output_filename = os.path.join(directory, "{}.concorde.pkl".format(name))
  42. log_filename = os.path.join(directory, "{}.log".format(name))
  43. # if True:
  44. try:
  45. # May have already been run
  46. if os.path.isfile(output_filename) and not disable_cache:
  47. tour, duration = load_dataset(output_filename)
  48. else:
  49. write_tsplib(problem_filename, loc, name=name)
  50. with open(log_filename, 'w') as f:
  51. start = time.time()
  52. try:
  53. # Concorde is weird, will leave traces of solution in current directory so call from target dir
  54. check_call([executable, '-s', '1234', '-x', '-o',
  55. os.path.abspath(tour_filename), os.path.abspath(problem_filename)],
  56. stdout=f, stderr=f, cwd=directory)
  57. except CalledProcessError as e:
  58. # Somehow Concorde returns 255
  59. assert e.returncode == 255
  60. duration = time.time() - start
  61. tour = read_concorde_tour(tour_filename)
  62. save_dataset((tour, duration), output_filename)
  63. return calc_tsp_length(loc, tour), tour, duration
  64. except Exception as e:
  65. print("Exception occured")
  66. print(e)
  67. return None
  68. def solve_lkh_log(executable, directory, name, loc, runs=1, disable_cache=False):
  69. problem_filename = os.path.join(directory, "{}.lkh{}.vrp".format(name, runs))
  70. tour_filename = os.path.join(directory, "{}.lkh{}.tour".format(name, runs))
  71. output_filename = os.path.join(directory, "{}.lkh{}.pkl".format(name, runs))
  72. param_filename = os.path.join(directory, "{}.lkh{}.par".format(name, runs))
  73. log_filename = os.path.join(directory, "{}.lkh{}.log".format(name, runs))
  74. try:
  75. # May have already been run
  76. if os.path.isfile(output_filename) and not disable_cache:
  77. tour, duration = load_dataset(output_filename)
  78. else:
  79. write_tsplib(problem_filename, loc, name=name)
  80. params = {"PROBLEM_FILE": problem_filename, "OUTPUT_TOUR_FILE": tour_filename, "RUNS": runs, "SEED": 1234}
  81. write_lkh_par(param_filename, params)
  82. with open(log_filename, 'w') as f:
  83. start = time.time()
  84. check_call([executable, param_filename], stdout=f, stderr=f)
  85. duration = time.time() - start
  86. tour = read_tsplib(tour_filename)
  87. save_dataset((tour, duration), output_filename)
  88. return calc_tsp_length(loc, tour), tour, duration
  89. except Exception as e:
  90. print("Exception occured")
  91. print(e)
  92. return None
  93. def write_lkh_par(filename, parameters):
  94. default_parameters = { # Use none to include as flag instead of kv
  95. "MAX_TRIALS": 10000,
  96. "RUNS": 10,
  97. "TRACE_LEVEL": 1,
  98. "SEED": 0
  99. }
  100. with open(filename, 'w') as f:
  101. for k, v in {**default_parameters, **parameters}.items():
  102. if v is None:
  103. f.write("{}\n".format(k))
  104. else:
  105. f.write("{} = {}\n".format(k, v))
  106. def write_tsplib(filename, loc, name="problem"):
  107. with open(filename, 'w') as f:
  108. f.write("\n".join([
  109. "{} : {}".format(k, v)
  110. for k, v in (
  111. ("NAME", name),
  112. ("TYPE", "TSP"),
  113. ("DIMENSION", len(loc)),
  114. ("EDGE_WEIGHT_TYPE", "EUC_2D"),
  115. )
  116. ]))
  117. f.write("\n")
  118. f.write("NODE_COORD_SECTION\n")
  119. f.write("\n".join([
  120. "{}\t{}\t{}".format(i + 1, int(x * 10000000 + 0.5), int(y * 10000000 + 0.5)) # tsplib does not take floats
  121. for i, (x, y) in enumerate(loc)
  122. ]))
  123. f.write("\n")
  124. f.write("EOF\n")
  125. def read_concorde_tour(filename):
  126. with open(filename, 'r') as f:
  127. n = None
  128. tour = []
  129. for line in f:
  130. if n is None:
  131. n = int(line)
  132. else:
  133. tour.extend([int(node) for node in line.rstrip().split(" ")])
  134. assert len(tour) == n, "Unexpected tour length"
  135. return tour
  136. def read_tsplib(filename):
  137. with open(filename, 'r') as f:
  138. tour = []
  139. dimension = 0
  140. started = False
  141. for line in f:
  142. if started:
  143. loc = int(line)
  144. if loc == -1:
  145. break
  146. tour.append(loc)
  147. if line.startswith("DIMENSION"):
  148. dimension = int(line.split(" ")[-1])
  149. if line.startswith("TOUR_SECTION"):
  150. started = True
  151. assert len(tour) == dimension
  152. tour = np.array(tour).astype(int) - 1 # Subtract 1 as depot is 1 and should be 0
  153. return tour.tolist()
  154. def calc_tsp_length(loc, tour):
  155. assert len(np.unique(tour)) == len(tour), "Tour cannot contain duplicates"
  156. assert len(tour) == len(loc)
  157. sorted_locs = np.array(loc)[np.concatenate((tour, [tour[0]]))]
  158. return np.linalg.norm(sorted_locs[1:] - sorted_locs[:-1], axis=-1).sum()
  159. def _calc_insert_cost(D, prv, nxt, ins):
  160. """
  161. Calculates insertion costs of inserting ins between prv and nxt
  162. :param D: distance matrix
  163. :param prv: node before inserted node, can be vector
  164. :param nxt: node after inserted node, can be vector
  165. :param ins: node to insert
  166. :return:
  167. """
  168. return (
  169. D[prv, ins]
  170. + D[ins, nxt]
  171. - D[prv, nxt]
  172. )
  173. def run_insertion(loc, method):
  174. n = len(loc)
  175. D = distance_matrix(loc, loc)
  176. mask = np.zeros(n, dtype=bool)
  177. tour = [] # np.empty((0, ), dtype=int)
  178. for i in range(n):
  179. feas = mask == 0
  180. feas_ind = np.flatnonzero(mask == 0)
  181. if method == 'random':
  182. # Order of instance is random so do in order for deterministic results
  183. a = i
  184. elif method == 'nearest':
  185. if i == 0:
  186. a = 0 # order does not matter so first is random
  187. else:
  188. a = feas_ind[D[np.ix_(feas, ~feas)].min(1).argmin()] # node nearest to any in tour
  189. elif method == 'cheapest':
  190. assert False, "Not yet implemented" # try all and find cheapest insertion cost
  191. elif method == 'farthest':
  192. if i == 0:
  193. a = D.max(1).argmax() # Node with farthest distance to any other node
  194. else:
  195. a = feas_ind[D[np.ix_(feas, ~feas)].min(1).argmax()] # node which has closest node in tour farthest
  196. mask[a] = True
  197. if len(tour) == 0:
  198. tour = [a]
  199. else:
  200. # Find index with least insert cost
  201. ind_insert = np.argmin(
  202. _calc_insert_cost(
  203. D,
  204. tour,
  205. np.roll(tour, -1),
  206. a
  207. )
  208. )
  209. tour.insert(ind_insert + 1, a)
  210. cost = D[tour, np.roll(tour, -1)].sum()
  211. return cost, tour
  212. def solve_insertion(directory, name, loc, method='random'):
  213. start = time.time()
  214. cost, tour = run_insertion(loc, method)
  215. duration = time.time() - start
  216. return cost, tour, duration
  217. def calc_batch_pdist(dataset):
  218. diff = (dataset[:, :, None, :] - dataset[:, None, :, :])
  219. return torch.matmul(diff[:, :, :, None, :], diff[:, :, :, :, None]).squeeze(-1).squeeze(-1).sqrt()
  220. def nearest_neighbour(dataset, start='first'):
  221. dist = calc_batch_pdist(dataset)
  222. batch_size, graph_size, _ = dataset.size()
  223. total_dist = dataset.new(batch_size).zero_()
  224. if not isinstance(start, torch.Tensor):
  225. if start == 'random':
  226. start = dataset.new().long().new(batch_size).zero_().random_(0, graph_size)
  227. elif start == 'first':
  228. start = dataset.new().long().new(batch_size).zero_()
  229. elif start == 'center':
  230. _, start = dist.mean(2).min(1) # Minimum total distance to others
  231. else:
  232. assert False, "Unknown start: {}".format(start)
  233. current = start
  234. dist_to_startnode = torch.gather(dist, 2, current.view(-1, 1, 1).expand(batch_size, graph_size, 1)).squeeze(2)
  235. tour = [current]
  236. for i in range(graph_size - 1):
  237. # Mark out current node as option
  238. dist.scatter_(2, current.view(-1, 1, 1).expand(batch_size, graph_size, 1), np.inf)
  239. nn_dist = torch.gather(dist, 1, current.view(-1, 1, 1).expand(batch_size, 1, graph_size)).squeeze(1)
  240. min_nn_dist, current = nn_dist.min(1)
  241. total_dist += min_nn_dist
  242. tour.append(current)
  243. total_dist += torch.gather(dist_to_startnode, 1, current.view(-1, 1)).squeeze(1)
  244. return total_dist, torch.stack(tour, dim=1)
  245. def solve_all_nn(dataset_path, eval_batch_size=1024, no_cuda=False, dataset_n=None, progress_bar_mininterval=0.1):
  246. import torch
  247. from torch.utils.data import DataLoader
  248. from problems import TSP
  249. from utils import move_to
  250. dataloader = DataLoader(
  251. TSP.make_dataset(filename=dataset_path, num_samples=dataset_n if dataset_n is not None else 1000000),
  252. batch_size=eval_batch_size
  253. )
  254. device = torch.device("cuda:0" if torch.cuda.is_available() and not no_cuda else "cpu")
  255. results = []
  256. for batch in tqdm(dataloader, mininterval=progress_bar_mininterval):
  257. start = time.time()
  258. batch = move_to(batch, device)
  259. lengths, tours = nearest_neighbour(batch)
  260. lengths_check, _ = TSP.get_costs(batch, tours)
  261. assert (torch.abs(lengths - lengths_check.data) < 1e-5).all()
  262. duration = time.time() - start
  263. results.extend(
  264. [(cost.item(), np.trim_zeros(pi.cpu().numpy(), 'b'), duration) for cost, pi in zip(lengths, tours)])
  265. return results, eval_batch_size
  266. if __name__ == "__main__":
  267. parser = argparse.ArgumentParser()
  268. parser.add_argument("method",
  269. help="Name of the method to evaluate, 'nn', 'gurobi' or '(nearest|random|farthest)_insertion'")
  270. parser.add_argument("datasets", nargs='+', help="Filename of the dataset(s) to evaluate")
  271. parser.add_argument("-f", action='store_true', help="Set true to overwrite")
  272. parser.add_argument("-o", default=None, help="Name of the results file to write")
  273. parser.add_argument("--cpus", type=int, help="Number of CPUs to use, defaults to all cores")
  274. parser.add_argument('--no_cuda', action='store_true', help='Disable CUDA (only for Tsiligirides)')
  275. parser.add_argument('--disable_cache', action='store_true', help='Disable caching')
  276. parser.add_argument('--max_calc_batch_size', type=int, default=1000, help='Size for subbatches')
  277. parser.add_argument('--progress_bar_mininterval', type=float, default=0.1, help='Minimum interval')
  278. parser.add_argument('-n', type=int, help="Number of instances to process")
  279. parser.add_argument('--offset', type=int, help="Offset where to start processing")
  280. parser.add_argument('--results_dir', default='results', help="Name of results directory")
  281. opts = parser.parse_args()
  282. assert opts.o is None or len(opts.datasets) == 1, "Cannot specify result filename with more than one dataset"
  283. for dataset_path in opts.datasets:
  284. assert os.path.isfile(check_extension(dataset_path)), "File does not exist!"
  285. dataset_basename, ext = os.path.splitext(os.path.split(dataset_path)[-1])
  286. if opts.o is None:
  287. results_dir = os.path.join(opts.results_dir, "tsp", dataset_basename)
  288. os.makedirs(results_dir, exist_ok=True)
  289. out_file = os.path.join(results_dir, "{}{}{}-{}{}".format(
  290. dataset_basename,
  291. "offs{}".format(opts.offset) if opts.offset is not None else "",
  292. "n{}".format(opts.n) if opts.n is not None else "",
  293. opts.method, ext
  294. ))
  295. else:
  296. out_file = opts.o
  297. assert opts.f or not os.path.isfile(
  298. out_file), "File already exists! Try running with -f option to overwrite."
  299. match = re.match(r'^([a-z_]+)(\d*)$', opts.method)
  300. assert match
  301. method = match[1]
  302. runs = 1 if match[2] == '' else int(match[2])
  303. if method == "nn":
  304. assert opts.offset is None, "Offset not supported for nearest neighbor"
  305. eval_batch_size = opts.max_calc_batch_size
  306. results, parallelism = solve_all_nn(
  307. dataset_path, eval_batch_size, opts.no_cuda, opts.n,
  308. opts.progress_bar_mininterval
  309. )
  310. elif method in ("gurobi", "gurobigap", "gurobit", "concorde", "lkh") or method[-9:] == 'insertion':
  311. target_dir = os.path.join(results_dir, "{}-{}".format(
  312. dataset_basename,
  313. opts.method
  314. ))
  315. assert opts.f or not os.path.isdir(target_dir), \
  316. "Target dir already exists! Try running with -f option to overwrite."
  317. if not os.path.isdir(target_dir):
  318. os.makedirs(target_dir)
  319. # TSP contains single loc array rather than tuple
  320. dataset = [(instance, ) for instance in load_dataset(dataset_path)]
  321. if method == "concorde":
  322. use_multiprocessing = False
  323. executable = os.path.abspath(os.path.join('problems', 'tsp', 'concorde', 'concorde', 'TSP', 'concorde'))
  324. def run_func(args):
  325. return solve_concorde_log(executable, *args, disable_cache=opts.disable_cache)
  326. elif method == "lkh":
  327. use_multiprocessing = False
  328. executable = get_lkh_executable()
  329. def run_func(args):
  330. return solve_lkh_log(executable, *args, runs=runs, disable_cache=opts.disable_cache)
  331. elif method[:6] == "gurobi":
  332. use_multiprocessing = True # We run one thread per instance
  333. def run_func(args):
  334. return solve_gurobi(*args, disable_cache=opts.disable_cache,
  335. timeout=runs if method[6:] == "t" else None,
  336. gap=float(runs) if method[6:] == "gap" else None)
  337. else:
  338. assert method[-9:] == "insertion"
  339. use_multiprocessing = True
  340. def run_func(args):
  341. return solve_insertion(*args, opts.method.split("_")[0])
  342. results, parallelism = run_all_in_pool(
  343. run_func,
  344. target_dir, dataset, opts, use_multiprocessing=use_multiprocessing
  345. )
  346. else:
  347. assert False, "Unknown method: {}".format(opts.method)
  348. costs, tours, durations = zip(*results) # Not really costs since they should be negative
  349. print("Average cost: {} +- {}".format(np.mean(costs), 2 * np.std(costs) / np.sqrt(len(costs))))
  350. print("Average serial duration: {} +- {}".format(
  351. np.mean(durations), 2 * np.std(durations) / np.sqrt(len(durations))))
  352. print("Average parallel duration: {}".format(np.mean(durations) / parallelism))
  353. print("Calculated total duration: {}".format(timedelta(seconds=int(np.sum(durations) / parallelism))))
  354. 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...