PyQrackIsing 9.17.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyqrackising/tsp.py ADDED
@@ -0,0 +1,2014 @@
1
+ from .maxcut_tfim_util import binary_search, opencl_context, to_scipy_sparse_upper_triangular
2
+ from .spin_glass_solver import spin_glass_solver
3
+ from concurrent.futures import ProcessPoolExecutor
4
+ import itertools
5
+ import networkx as nx
6
+ from numba import njit, prange
7
+ import numpy as np
8
+ import os
9
+ from scipy.sparse import lil_matrix
10
+
11
+
12
+ n_threads = os.cpu_count()
13
+ max_parallel_level = np.log2(n_threads)
14
+
15
+
16
+ # two_opt() and targeted_three_opt() written by Elara (OpenAI ChatGPT instance)
17
+ @njit(cache=True)
18
+ def path_length(path, G_m):
19
+ tot_len = 0.0
20
+ for i in range(len(path) - 1):
21
+ tot_len += G_m[path[i], path[i + 1]]
22
+
23
+ return tot_len
24
+
25
+
26
+ @njit(cache=True)
27
+ def one_way_two_opt(best_path, G):
28
+ improved = True
29
+ best_dist = path_length(best_path, G)
30
+ path_len = len(best_path)
31
+
32
+ while improved:
33
+ improved = False
34
+ for i in range(1, path_len - 1):
35
+ for j in range(i + 2, path_len):
36
+ new_path = best_path[:]
37
+ new_path[i:j] = best_path[j - 1 : i - 1 : -1]
38
+ new_dist = path_length(new_path, G)
39
+ if new_dist < best_dist:
40
+ best_path, best_dist = new_path, new_dist
41
+ improved = True
42
+
43
+ return best_path, best_dist
44
+
45
+
46
+ @njit(parallel=True, cache=True)
47
+ def one_way_two_opt_parallel(best_path, G):
48
+ improved = True
49
+ best_dist = path_length(best_path, G)
50
+ paths = [best_path] * n_threads
51
+ dists = [best_dist] * n_threads
52
+ path_len = len(best_path)
53
+
54
+ while improved:
55
+ improved = False
56
+ for i in range(1, path_len - 1):
57
+ for j in range(i + 2, path_len, n_threads):
58
+ max_k = min(n_threads, path_len - j)
59
+ for k in prange(max_k):
60
+ l = j + k
61
+ new_path = best_path[:]
62
+ new_path[i:l] = best_path[l - 1 : i - 1 : -1]
63
+ dists[k] = path_length(new_path, G)
64
+ paths[k] = new_path
65
+ for k in range(max_k):
66
+ if dists[k] < best_dist:
67
+ best_path, best_dist, improved = paths[k], dists[k], True
68
+
69
+ return best_path, best_dist
70
+
71
+
72
+ @njit(cache=True)
73
+ def anchored_two_opt(best_path, G):
74
+ improved = True
75
+ best_dist = path_length(best_path, G)
76
+ path_len = len(best_path)
77
+
78
+ while improved:
79
+ improved = False
80
+ for i in range(2, path_len - 1):
81
+ for j in range(i + 2, path_len):
82
+ new_path = best_path[:]
83
+ new_path[i:j] = best_path[j - 1 : i - 1 : -1]
84
+ new_dist = path_length(new_path, G)
85
+ if new_dist < best_dist:
86
+ best_path, best_dist = new_path, new_dist
87
+ improved = True
88
+
89
+ return best_path, best_dist
90
+
91
+
92
+ @njit(parallel=True, cache=True)
93
+ def anchored_two_opt_parallel(best_path, G):
94
+ improved = True
95
+ best_dist = path_length(best_path, G)
96
+ paths = [best_path] * n_threads
97
+ dists = [best_dist] * n_threads
98
+ path_len = len(best_path)
99
+
100
+ while improved:
101
+ improved = False
102
+ for i in range(2, path_len - 1):
103
+ for j in range(i + 2, path_len, n_threads):
104
+ max_k = min(n_threads, path_len - j)
105
+ for k in prange(max_k):
106
+ l = j + k
107
+ new_path = best_path[:]
108
+ new_path[i:l] = best_path[l - 1 : i - 1 : -1]
109
+ dists[k] = path_length(new_path, G)
110
+ paths[k] = new_path
111
+ for k in range(max_k):
112
+ if dists[k] < best_dist:
113
+ best_path, best_dist, improved = paths[k], dists[k], True
114
+
115
+ return best_path, best_dist
116
+
117
+
118
+ @njit(cache=True)
119
+ def two_opt(best_path, G):
120
+ improved = True
121
+ best_dist = path_length(best_path, G)
122
+ path_len = len(best_path)
123
+
124
+ while improved:
125
+ improved = False
126
+ for i in range(1, path_len - 2):
127
+ for j in range(i + 2, path_len - 1):
128
+ new_path = best_path[:]
129
+ new_path[i:j] = best_path[j - 1 : i - 1 : -1] # reverse segment
130
+ new_dist = path_length(new_path, G)
131
+ if new_dist < best_dist:
132
+ best_path, best_dist = new_path, new_dist
133
+ improved = True
134
+
135
+ return best_path, best_dist
136
+
137
+
138
+ @njit(parallel=True, cache=True)
139
+ def two_opt_parallel(best_path, G):
140
+ improved = True
141
+ best_dist = path_length(best_path, G)
142
+ paths = [best_path] * n_threads
143
+ dists = [best_dist] * n_threads
144
+ path_len = len(best_path)
145
+
146
+ while improved:
147
+ improved = False
148
+ for i in range(1, path_len - 2):
149
+ for j in range(i + 2, path_len - 1, n_threads):
150
+ max_k = min(n_threads, path_len - (j + 1))
151
+ for k in prange(max_k):
152
+ l = j + k
153
+ new_path = best_path[:]
154
+ new_path[i:l] = best_path[l - 1 : i - 1 : -1]
155
+ dists[k] = path_length(new_path, G)
156
+ paths[k] = new_path
157
+ for k in range(max_k):
158
+ if dists[k] < best_dist:
159
+ best_path, best_dist, improved = paths[k], dists[k], True
160
+
161
+ return best_path, best_dist
162
+
163
+
164
+ @njit(cache=True)
165
+ def targeted_three_opt(path, W, neighbor_lists, k_neighbors=20):
166
+ """
167
+ Lin-Kernighan style 3-opt heuristic for TSP improvement.
168
+
169
+ path: list of node indices (tour)
170
+ W: adjacency matrix (numpy array)
171
+ k_neighbors: restrict 3-opt to nearest neighbors for efficiency
172
+ """
173
+
174
+ n = len(path)
175
+ best_path = path[:]
176
+ best_dist = path_length(best_path, W)
177
+ improved = True
178
+
179
+ while improved:
180
+ improved = False
181
+ for i in range(n - 5):
182
+ for j in neighbor_lists[path[i]]:
183
+ if j <= i or j >= n - 3:
184
+ continue
185
+ for k in neighbor_lists[path[j]]:
186
+ if k <= j or k >= n - 1:
187
+ continue
188
+
189
+ # 7 unique cases (same as brute force, but restricted)
190
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
191
+ dist = path_length(new_path, W)
192
+ if dist < best_dist:
193
+ best_path, best_dist, improved = new_path, dist, True
194
+ break
195
+
196
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
197
+ dist = path_length(new_path, W)
198
+ if dist < best_dist:
199
+ best_path, best_dist, improved = new_path, dist, True
200
+ break
201
+
202
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
203
+ dist = path_length(new_path, W)
204
+ if dist < best_dist:
205
+ best_path, best_dist, improved = new_path, dist, True
206
+ break
207
+
208
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
209
+ dist = path_length(new_path, W)
210
+ if dist < best_dist:
211
+ best_path, best_dist, improved = new_path, dist, True
212
+ break
213
+
214
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
215
+ dist = path_length(new_path, W)
216
+ if dist < best_dist:
217
+ best_path, best_dist, improved = new_path, dist, True
218
+ break
219
+
220
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
221
+ dist = path_length(new_path, W)
222
+ if dist < best_dist:
223
+ best_path, best_dist, improved = new_path, dist, True
224
+ break
225
+
226
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
227
+ dist = path_length(new_path, W)
228
+ if dist < best_dist:
229
+ best_path, best_dist, improved = new_path, dist, True
230
+ break
231
+
232
+ if improved:
233
+ break
234
+
235
+ if improved:
236
+ break
237
+
238
+ path = best_path[:]
239
+
240
+ return best_path, best_dist
241
+
242
+
243
+ @njit(parallel=True, cache=True)
244
+ def targeted_three_opt_parallel(path, W, neighbor_lists, k_neighbors=20):
245
+ n = len(path)
246
+ best_path = path[:]
247
+ best_dist = path_length(best_path, W)
248
+ paths = [best_path] * 7
249
+ dists = [best_dist] * 7
250
+ improved = True
251
+
252
+ while improved:
253
+ improved = False
254
+ for i in range(n - 5):
255
+ for _j in range(k_neighbors):
256
+ j = neighbor_lists[path[i], _j]
257
+ if j <= i or j >= n - 3:
258
+ continue
259
+ for _k in range(k_neighbors):
260
+ k = neighbor_lists[path[j], _k]
261
+ if k <= j or k >= n - 1:
262
+ continue
263
+
264
+ # 7 unique cases (same as brute force, but restricted)
265
+ for l in prange(7):
266
+ match l:
267
+ case 0:
268
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
269
+ case 1:
270
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
271
+ case 2:
272
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
273
+ case 3:
274
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
275
+ case 4:
276
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
277
+ case 5:
278
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
279
+ case _:
280
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
281
+
282
+ dists[l] = path_length(new_path, W)
283
+ paths[l] = new_path
284
+
285
+ for l in range(7):
286
+ if dists[l] < best_dist:
287
+ best_path, best_dist, improved = paths[l], dists[l], True
288
+
289
+ if improved:
290
+ break
291
+
292
+ if improved:
293
+ break
294
+
295
+ if improved:
296
+ break
297
+
298
+ path = best_path[:]
299
+
300
+ return best_path, best_dist
301
+
302
+
303
+ @njit(cache=True)
304
+ def init_G_a_b(G_m, a, b):
305
+ n_a_nodes = len(a)
306
+ n_b_nodes = len(b)
307
+ G_a = np.zeros((n_a_nodes, n_a_nodes), dtype=np.float64)
308
+ G_b = np.zeros((n_b_nodes, n_b_nodes), dtype=np.float64)
309
+ for i in range(n_a_nodes):
310
+ for j in range(n_a_nodes):
311
+ if i == j:
312
+ continue
313
+ G_a[i, j] = G_m[a[i], a[j]]
314
+ for i in range(n_b_nodes):
315
+ for j in range(n_b_nodes):
316
+ if i == j:
317
+ continue
318
+ G_b[i, j] = G_m[b[i], b[j]]
319
+
320
+ return G_a, G_b
321
+
322
+
323
+ @njit(cache=True)
324
+ def stitch_singlet(G_m, singlet, bulk):
325
+ best_path = bulk.copy()
326
+ best_weight = G_m[singlet, bulk[0]]
327
+ weight = G_m[singlet, bulk[-1]]
328
+ if weight < best_weight:
329
+ best_weight = weight
330
+ best_path += [singlet]
331
+ else:
332
+ best_path = [singlet] + best_path
333
+
334
+ for i in range(1, len(bulk)):
335
+ weight = G_m[singlet, bulk[i - 1]] + G_m[singlet, bulk[i]] - G_m[bulk[i - 1], bulk[i]]
336
+ if weight < best_weight:
337
+ best_weight = weight
338
+ best_path = bulk.copy()
339
+ best_path.insert(i, singlet)
340
+
341
+ return best_path
342
+
343
+
344
+ @njit(cache=True)
345
+ def stitch_symmetric(G_m, path_a, path_b):
346
+ if len(path_a) == 1:
347
+ return stitch_singlet(G_m, path_a[0], path_b)
348
+
349
+ if len(path_b) == 1:
350
+ return stitch_singlet(G_m, path_b[0], path_a)
351
+
352
+ terminals_a = [path_a[0], path_a[-1]]
353
+ terminals_b = [path_b[0], path_b[-1]]
354
+
355
+ best_connect = G_m[terminals_a[1], terminals_b[0]]
356
+ best_path = path_b.copy()
357
+ weight = G_m[terminals_a[0], terminals_b[1]]
358
+ if weight < best_connect:
359
+ best_connect = weight
360
+ best_path += path_a
361
+ else:
362
+ best_path = path_a + best_path
363
+
364
+ for _ in range(2):
365
+ for _ in range(2):
366
+ for i in range(1, len(path_b)):
367
+ weight = G_m[terminals_a[0], path_b[i - 1]] + G_m[terminals_a[1], path_b[i]] - G_m[path_b[i - 1], path_b[i]]
368
+ if weight < best_connect:
369
+ best_connect = weight
370
+ best_path = path_b.copy()
371
+ best_path[i:i] = path_a
372
+ path_a.reverse()
373
+ terminals_a.reverse()
374
+ path_a, path_b = path_b, path_a
375
+ terminals_a, terminals_b = terminals_b, terminals_a
376
+
377
+ return best_path
378
+
379
+
380
+ @njit(cache=True)
381
+ def stitch_asymmetric(G_m, path_a, path_b):
382
+ if len(path_a) == 1:
383
+ return stitch_singlet(G_m, path_a[0], path_b)
384
+
385
+ if len(path_b) == 1:
386
+ return stitch_singlet(G_m, path_b[0], path_a)
387
+
388
+ terminals_a = [path_a[0], path_a[-1]]
389
+ terminals_b = [path_b[0], path_b[-1]]
390
+
391
+ best_connect = G_m[terminals_a[1], terminals_b[0]]
392
+ best_path = path_b.copy()
393
+ weight = G_m[terminals_a[0], terminals_b[1]]
394
+ if weight < best_connect:
395
+ best_connect = weight
396
+ best_path += path_a
397
+ else:
398
+ best_path = path_a + best_path
399
+
400
+ for _ in range(2):
401
+ for _ in range(2):
402
+ path_weight = path_length(path_a, G_m) + path_length(path_b, G_m)
403
+ best_weight = best_connect + path_weight
404
+ for i in range(1, len(path_b)):
405
+ weight = G_m[terminals_a[0], path_b[i - 1]] + G_m[terminals_a[1], path_b[i]] - G_m[path_b[i - 1], path_b[i]]
406
+ if (weight + path_weight) < best_weight:
407
+ best_weight = weight + path_weight
408
+ best_path = path_b.copy()
409
+ best_path[i:i] = path_a
410
+ path_a.reverse()
411
+ terminals_a.reverse()
412
+ path_a, path_b = path_b, path_a
413
+ terminals_a, terminals_b = terminals_b, terminals_a
414
+
415
+ return best_path
416
+
417
+
418
+ @njit(cache=True)
419
+ def restitch(G_m, path, is_sym):
420
+ l = len(path)
421
+ mid = ((l + 1) if (l & 1) and (np.random.random() < 0.5) else l) >> 1
422
+
423
+ if mid < 4:
424
+ return path
425
+
426
+ path_a = restitch(G_m, path[:mid], is_sym)
427
+ path_b = restitch(G_m, path[mid:], is_sym)
428
+
429
+ if is_sym:
430
+ return stitch_symmetric(G_m, path_a, path_b)
431
+
432
+ return stitch_asymmetric(G_m, path_a, path_b)
433
+
434
+
435
+ @njit(cache=True)
436
+ def monte_carlo_driver(n_nodes):
437
+ a, b = [], []
438
+ for i in range(n_nodes):
439
+ if np.random.random() < 0.5:
440
+ a.append(i)
441
+ else:
442
+ b.append(i)
443
+
444
+ return a, b
445
+
446
+
447
+ @njit(cache=True)
448
+ def monte_carlo_loop(n_nodes):
449
+ a, b = monte_carlo_driver(n_nodes)
450
+ while (len(a) == 0) or (len(b) == 0):
451
+ a, b = monte_carlo_driver(n_nodes)
452
+
453
+ return a, b
454
+
455
+
456
+ # Elara suggested replacing base-case handling with her brute-force solver
457
+ @njit(cache=True)
458
+ def tsp_bruteforce_cyclic(G_m, perms):
459
+ """
460
+ Brute-force TSP solver for small n.
461
+ G_m : numpy.ndarray (2D adjacency/weight matrix)
462
+ is_cyclic : bool (default=True) – whether to close the tour
463
+
464
+ Returns:
465
+ (best_path, best_weight)
466
+ """
467
+ n = len(G_m)
468
+ best_weight = float("inf")
469
+ best_path = None
470
+
471
+ # Must fix node 0 at start to remove rotational symmetry in cyclic case!
472
+
473
+ max_i = len(perms[0]) - 1
474
+
475
+ for perm in perms:
476
+ path = [0] + list(perm)
477
+ weight = 0.0
478
+ for i in range(max_i):
479
+ weight += G_m[path[i], path[i + 1]]
480
+ weight += G_m[path[-1], path[0]]
481
+
482
+ if weight < best_weight:
483
+ best_weight = weight
484
+ best_path = path
485
+
486
+ best_path = best_path + [best_path[0]]
487
+
488
+ return best_path, best_weight
489
+
490
+
491
+ @njit(cache=True)
492
+ def tsp_bruteforce_acyclic(G_m, perms):
493
+ """
494
+ Brute-force TSP solver for small n.
495
+ G_m : numpy.ndarray (2D adjacency/weight matrix)
496
+ is_cyclic : bool (default=True) – whether to close the tour
497
+
498
+ Returns:
499
+ (best_path, best_weight)
500
+ """
501
+ n = len(G_m)
502
+ best_weight = float("inf")
503
+ best_path = None
504
+
505
+ # Must fix node 0 at start to remove rotational symmetry in cyclic case!
506
+
507
+ max_i = len(perms[0]) - 1
508
+
509
+ for path in perms:
510
+ weight = 0.0
511
+ for i in range(max_i):
512
+ weight += G_m[path[i], path[i + 1]]
513
+
514
+ if weight < best_weight:
515
+ best_weight = weight
516
+ best_path = path
517
+
518
+ best_path = list(best_path)
519
+
520
+ return best_path, best_weight
521
+
522
+
523
+ @njit(cache=True)
524
+ def tsp_symmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic):
525
+ if n_nodes == 3:
526
+ if is_cyclic:
527
+ weight_0 = G_m[0, 1] + G_m[1, 2] + G_m[2, 0]
528
+ weight_1 = G_m[0, 2] + G_m[2, 1] + G_m[1, 0]
529
+
530
+ if weight_0 >= weight_1:
531
+ return (nodes + [nodes[0]], weight_0)
532
+
533
+ nodes.reverse()
534
+
535
+ return ([nodes[2]] + nodes, weight_1)
536
+
537
+ w_012 = G_m[0, 1] + G_m[1, 2]
538
+ w_021 = G_m[0, 1] + G_m[0, 2]
539
+ w_120 = G_m[0, 2] + G_m[1, 2]
540
+
541
+ if w_012 >= w_021 and w_012 >= w_120:
542
+ return (nodes, w_012)
543
+
544
+ if w_021 >= w_012 and w_021 >= w_120:
545
+ return ([nodes[1], nodes[0], nodes[2]], w_021)
546
+
547
+ return ([nodes[0], nodes[2], nodes[1]], w_120)
548
+
549
+ if n_nodes == 2:
550
+ if is_cyclic:
551
+ return (nodes + [nodes[0]], 2 * G_m[0, 1])
552
+
553
+ return (nodes, G_m[0, 1])
554
+
555
+ return (nodes, 0)
556
+
557
+
558
+ @njit(cache=True)
559
+ def tsp_symmetric_driver(
560
+ G_m,
561
+ is_cyclic,
562
+ is_top_level,
563
+ start_node,
564
+ end_node,
565
+ k_neighbors,
566
+ nodes,
567
+ sol_a,
568
+ sol_b,
569
+ a,
570
+ b,
571
+ c,
572
+ neighbor_lists,
573
+ is_parallel,
574
+ ):
575
+ path_a = [a[x] for x in sol_a[0]]
576
+ path_b = [b[x] for x in sol_b[0]]
577
+
578
+ if start_node is None:
579
+ best_path = stitch_symmetric(G_m, path_a, path_b)
580
+ else:
581
+ best_path = path_a + path_b
582
+ best_weight = G_m[path_a[0], path_b[0]]
583
+ weight = G_m[path_a[0], path_b[-1]]
584
+ if weight < best_weight:
585
+ path_b.reverse()
586
+ best_path = path_a + path_b
587
+ best_weight = weight
588
+
589
+ if not c is None:
590
+ best_path.append(c)
591
+
592
+ best_path = restitch(G_m, best_path, True)
593
+
594
+ if is_top_level:
595
+ if is_cyclic:
596
+ best_path += [best_path[0]]
597
+ if is_parallel:
598
+ best_path, _ = two_opt_parallel(best_path, G_m)
599
+ else:
600
+ best_path, _ = two_opt(best_path, G_m)
601
+ elif not end_node is None:
602
+ if is_parallel:
603
+ best_path, _ = two_opt_parallel(best_path, G_m)
604
+ else:
605
+ best_path, _ = two_opt(best_path, G_m)
606
+ elif not start_node is None:
607
+ if is_parallel:
608
+ best_path, _ = anchored_two_opt_parallel(best_path, G_m)
609
+ else:
610
+ best_path, _ = anchored_two_opt(best_path, G_m)
611
+ else:
612
+ if is_parallel:
613
+ best_path, _ = one_way_two_opt_parallel(best_path, G_m)
614
+ else:
615
+ best_path, _ = one_way_two_opt(best_path, G_m)
616
+
617
+ if k_neighbors > 0:
618
+ if is_parallel:
619
+ best_path, _ = targeted_three_opt_parallel(best_path, G_m, neighbor_lists, k_neighbors)
620
+ else:
621
+ best_path, _ = targeted_three_opt(best_path, G_m, neighbor_lists, k_neighbors)
622
+
623
+ best_weight = path_length(best_path, G_m)
624
+
625
+ return [nodes[x] for x in best_path], best_weight
626
+
627
+
628
+ def tsp_symmetric_header(
629
+ G_m,
630
+ nodes,
631
+ quality,
632
+ shots,
633
+ anneal_t,
634
+ anneal_h,
635
+ repulsion_base,
636
+ start_node,
637
+ end_node,
638
+ monte_carlo,
639
+ is_cyclic,
640
+ n_nodes,
641
+ multi_start,
642
+ ):
643
+ if is_cyclic:
644
+ start_node = None
645
+ end_node = None
646
+
647
+ if (start_node is None) and not (end_node is None):
648
+ start_node = end_node
649
+ end_node = None
650
+
651
+ a, b, c = [], [], []
652
+ if (start_node is None) and (end_node is None):
653
+ if monte_carlo:
654
+ a, b = monte_carlo_loop(n_nodes)
655
+ else:
656
+ best_cut = -float("inf")
657
+ for _ in range(multi_start):
658
+ bits = ([], [])
659
+ while (len(bits[0]) == 0) or (len(bits[1]) == 0):
660
+ _, cut_value, bits, _ = spin_glass_solver(
661
+ G_m,
662
+ is_spin_glass=False,
663
+ quality=quality,
664
+ shots=shots,
665
+ anneal_t=anneal_t,
666
+ anneal_h=anneal_h,
667
+ repulsion_base=repulsion_base,
668
+ )
669
+ if cut_value > best_cut:
670
+ best_cut = cut_value
671
+ a, b = bits
672
+ else:
673
+ is_cyclic = False
674
+ a.append(nodes.index(start_node))
675
+ b = list(range(n_nodes))
676
+ b.remove(a[0])
677
+ if end_node is not None:
678
+ c.append(nodes.index(end_node))
679
+ b.remove(c[0])
680
+
681
+ G_a, G_b = init_G_a_b(G_m, a, b)
682
+
683
+ return a, b, c, G_a, G_b, is_cyclic
684
+
685
+
686
+ def tsp_symmetric(
687
+ G,
688
+ start_node=None,
689
+ end_node=None,
690
+ quality=None,
691
+ shots=None,
692
+ anneal_t=None,
693
+ anneal_h=None,
694
+ repulsion_base=None,
695
+ monte_carlo=True,
696
+ k_neighbors=20,
697
+ is_cyclic=True,
698
+ multi_start=1,
699
+ is_top_level=True,
700
+ is_parallel=False,
701
+ parallel_level=0,
702
+ ):
703
+ dtype = opencl_context.dtype
704
+ nodes = None
705
+ n_nodes = 0
706
+ G_m = None
707
+ if isinstance(G, nx.Graph):
708
+ nodes = list(G.nodes())
709
+ n_nodes = len(nodes)
710
+ G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
711
+ else:
712
+ n_nodes = len(G)
713
+ nodes = list(range(n_nodes))
714
+ G_m = G
715
+
716
+ if n_nodes < 7:
717
+ if n_nodes > 3:
718
+ if is_cyclic:
719
+ best_path, best_weight = tsp_bruteforce_cyclic(G_m, list(itertools.permutations(list(range(1, n_nodes)))))
720
+ else:
721
+ best_path, best_weight = tsp_bruteforce_acyclic(G_m, list(itertools.permutations(list(range(n_nodes)))))
722
+
723
+ return [nodes[x] for x in best_path], best_weight
724
+
725
+ return tsp_symmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic)
726
+
727
+ a, b, c, G_a, G_b, is_cylic = tsp_symmetric_header(
728
+ G_m,
729
+ nodes,
730
+ quality,
731
+ shots,
732
+ anneal_t,
733
+ anneal_h,
734
+ repulsion_base,
735
+ start_node,
736
+ end_node,
737
+ monte_carlo,
738
+ is_cyclic,
739
+ n_nodes,
740
+ multi_start,
741
+ )
742
+
743
+ if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 3) and (len(b) > 3):
744
+ with ProcessPoolExecutor(max_workers=1) as executor:
745
+ f = executor.submit(
746
+ tsp_symmetric,
747
+ G_a,
748
+ None,
749
+ None,
750
+ quality,
751
+ shots,
752
+ anneal_t,
753
+ anneal_h,
754
+ repulsion_base,
755
+ True,
756
+ 0,
757
+ False,
758
+ multi_start,
759
+ False,
760
+ True,
761
+ parallel_level + 1,
762
+ )
763
+ sol_b = tsp_symmetric(
764
+ G_b,
765
+ None,
766
+ None,
767
+ quality,
768
+ shots,
769
+ anneal_t,
770
+ anneal_h,
771
+ repulsion_base,
772
+ True,
773
+ 0,
774
+ False,
775
+ multi_start,
776
+ False,
777
+ True,
778
+ parallel_level + 1,
779
+ )
780
+ sol_a = f.result()
781
+ else:
782
+ sol_a = tsp_symmetric(
783
+ G_a,
784
+ quality=quality,
785
+ shots=shots,
786
+ anneal_t=anneal_t,
787
+ anneal_h=anneal_h,
788
+ repulsion_base=repulsion_base,
789
+ monte_carlo=monte_carlo,
790
+ is_cyclic=False,
791
+ is_top_level=False,
792
+ k_neighbors=0,
793
+ multi_start=multi_start,
794
+ is_parallel=False,
795
+ )
796
+ sol_b = tsp_symmetric(
797
+ G_b,
798
+ quality=quality,
799
+ shots=shots,
800
+ anneal_t=anneal_t,
801
+ anneal_h=anneal_h,
802
+ repulsion_base=repulsion_base,
803
+ monte_carlo=monte_carlo,
804
+ is_cyclic=False,
805
+ is_top_level=False,
806
+ k_neighbors=0,
807
+ multi_start=multi_start,
808
+ is_parallel=False,
809
+ )
810
+
811
+ neighbor_lists = [[0]]
812
+ if k_neighbors > 0:
813
+ # Precompute nearest neighbors for each node
814
+ neighbor_lists = [([(float("inf"), 0)] * k_neighbors) for i in range(n_nodes)]
815
+
816
+ for i in range(n_nodes):
817
+ for j in range(n_nodes):
818
+ val = G_m[i, j]
819
+ if val < neighbor_lists[i][-1][0]:
820
+ neighbor_lists[i][-1] = (val, j)
821
+ neighbor_lists[i].sort(key=lambda x: x[0])
822
+
823
+ for i in range(len(neighbor_lists)):
824
+ neighbor_lists[i] = [x[1] for x in neighbor_lists[i]]
825
+
826
+ return tsp_symmetric_driver(
827
+ G_m,
828
+ is_cyclic,
829
+ is_top_level,
830
+ start_node,
831
+ end_node,
832
+ k_neighbors,
833
+ nodes,
834
+ sol_a,
835
+ sol_b,
836
+ a,
837
+ b,
838
+ c[0] if len(c) else None,
839
+ np.array(neighbor_lists),
840
+ is_parallel,
841
+ )
842
+
843
+
844
+ @njit(cache=True)
845
+ def tsp_asymmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic):
846
+ if n_nodes == 2:
847
+ weight = G_m[0, 1]
848
+ if G_m[1, 0] < weight:
849
+ weight = G_m[1, 0]
850
+ nodes.reverse()
851
+
852
+ if is_cyclic:
853
+ return (nodes + [nodes[0]], 2 * weight)
854
+
855
+ return (nodes, weight)
856
+
857
+ return (nodes, 0)
858
+
859
+
860
+ @njit(cache=True)
861
+ def tsp_asymmetric_driver(
862
+ G_m,
863
+ is_reversed,
864
+ is_cyclic,
865
+ is_top_level,
866
+ start_node,
867
+ end_node,
868
+ k_neighbors,
869
+ nodes,
870
+ sol_a,
871
+ sol_b,
872
+ a,
873
+ b,
874
+ c,
875
+ neighbor_lists,
876
+ is_parallel,
877
+ ):
878
+ path_a = [a[x] for x in sol_a[0]]
879
+ path_b = [b[x] for x in sol_b[0]]
880
+
881
+ if start_node is None:
882
+ best_path = stitch_asymmetric(G_m, path_a, path_b)
883
+ else:
884
+ best_path = path_a + path_b
885
+
886
+ if not c is None:
887
+ best_path.append(c)
888
+
889
+ best_path = restitch(G_m, best_path, False)
890
+
891
+ if is_top_level:
892
+ if is_cyclic:
893
+ best_path += [best_path[0]]
894
+ final_path, best_weight = two_opt_parallel(best_path.copy(), G_m) if is_parallel else two_opt(best_path.copy(), G_m)
895
+ best_path.reverse()
896
+ path, weight = two_opt_parallel(best_path, G_m) if is_parallel else two_opt(best_path, G_m)
897
+ if weight < best_weight:
898
+ final_path, best_weight = path, weight
899
+ elif not end_node is None:
900
+ final_path, best_weight = two_opt_parallel(best_path.copy(), G_m) if is_parallel else two_opt(best_path.copy(), G_m)
901
+ best_path.reverse()
902
+ path, weight = two_opt_parallel(best_path, G_m) if is_parallel else two_opt(best_path, G_m)
903
+ if weight < best_weight:
904
+ final_path, best_weight = path, weight
905
+ elif not start_node is None:
906
+ final_path, best_weight = anchored_two_opt_parallel(best_path.copy(), G_m) if is_parallel else anchored_two_opt(best_path.copy(), G_m)
907
+ best_path.reverse()
908
+ path, weight = two_opt_parallel(best_path, G_m) if is_parallel else two_opt(best_path, G_m)
909
+ if weight < best_weight:
910
+ final_path, best_weight = path, weight
911
+ else:
912
+ final_path, best_weight = one_way_two_opt_parallel(best_path.copy(), G_m) if is_parallel else one_way_two_opt(best_path.copy(), G_m)
913
+ best_path.reverse()
914
+ path, weight = one_way_two_opt_parallel(best_path, G_m) if is_parallel else one_way_two_opt(best_path, G_m)
915
+ if weight < best_weight:
916
+ final_path, best_weight = path, weight
917
+
918
+ if k_neighbors > 0:
919
+ best_path = final_path
920
+ final_path, best_weight = (
921
+ targeted_three_opt_parallel(best_path.copy(), G_m, neighbor_lists, k_neighbors)
922
+ if is_parallel
923
+ else targeted_three_opt(best_path.copy(), G_m, neighbor_lists, k_neighbors)
924
+ )
925
+ best_path.reverse()
926
+ path, weight = (
927
+ targeted_three_opt_parallel(best_path, G_m, neighbor_lists, k_neighbors)
928
+ if is_parallel
929
+ else targeted_three_opt(best_path, G_m, neighbor_lists, k_neighbors)
930
+ )
931
+ if weight < best_weight:
932
+ final_path, best_weight = path, weight
933
+ else:
934
+ final_path = best_path
935
+
936
+ best_weight = path_length(final_path, G_m)
937
+
938
+ if is_reversed:
939
+ final_path.reverse()
940
+
941
+ return [nodes[x] for x in final_path], best_weight
942
+
943
+
944
+ def tsp_asymmetric_header(
945
+ G_m,
946
+ nodes,
947
+ quality,
948
+ shots,
949
+ anneal_t,
950
+ anneal_h,
951
+ repulsion_base,
952
+ start_node,
953
+ end_node,
954
+ monte_carlo,
955
+ is_cyclic,
956
+ n_nodes,
957
+ multi_start,
958
+ ):
959
+ if is_cyclic:
960
+ start_node = None
961
+ end_node = None
962
+
963
+ is_reversed = False
964
+ if (start_node is None) and not (end_node is None):
965
+ is_reversed = True
966
+ start_node = end_node
967
+ end_node = None
968
+ G_m = G_m.T
969
+
970
+ a, b, c = [], [], []
971
+ if (start_node is None) and (end_node is None):
972
+ if monte_carlo:
973
+ a, b = monte_carlo_loop(n_nodes)
974
+ else:
975
+ best_cut = -float("inf")
976
+ for _ in range(multi_start):
977
+ bits = ([], [])
978
+ while (len(bits[0]) == 0) or (len(bits[1]) == 0):
979
+ _, cut_value, bits, _ = spin_glass_solver(
980
+ (G_m + G_m.T) / 2,
981
+ is_spin_glass=False,
982
+ quality=quality,
983
+ shots=shots,
984
+ anneal_t=anneal_t,
985
+ anneal_h=anneal_h,
986
+ repulsion_base=repulsion_base,
987
+ )
988
+ if cut_value > best_cut:
989
+ best_cut = cut_value
990
+ a, b = bits
991
+ else:
992
+ is_cyclic = False
993
+ a.append(nodes.index(start_node))
994
+ b = list(range(n_nodes))
995
+ b.remove(a[0])
996
+ if end_node is not None:
997
+ c.append(nodes.index(end_node))
998
+ b.remove(c[0])
999
+
1000
+ G_a, G_b = init_G_a_b(G_m, a, b)
1001
+
1002
+ return a, b, c, G_a, G_b, is_cyclic, is_reversed
1003
+
1004
+
1005
+ def tsp_asymmetric(
1006
+ G,
1007
+ start_node=None,
1008
+ end_node=None,
1009
+ quality=None,
1010
+ shots=None,
1011
+ anneal_t=None,
1012
+ anneal_h=None,
1013
+ repulsion_base=None,
1014
+ monte_carlo=True,
1015
+ k_neighbors=20,
1016
+ is_cyclic=True,
1017
+ multi_start=1,
1018
+ is_top_level=True,
1019
+ is_parallel=False,
1020
+ parallel_level=0,
1021
+ ):
1022
+ dtype = opencl_context.dtype
1023
+ nodes = None
1024
+ n_nodes = 0
1025
+ G_m = None
1026
+ if isinstance(G, nx.Graph):
1027
+ nodes = list(G.nodes())
1028
+ n_nodes = len(nodes)
1029
+ G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
1030
+ else:
1031
+ n_nodes = len(G)
1032
+ nodes = list(range(n_nodes))
1033
+ G_m = G
1034
+
1035
+ if n_nodes < 7:
1036
+ if n_nodes > 2:
1037
+ if is_cyclic:
1038
+ best_path, best_weight = tsp_bruteforce_cyclic(G_m, list(itertools.permutations(list(range(1, n_nodes)))))
1039
+ else:
1040
+ best_path, best_weight = tsp_bruteforce_acyclic(G_m, list(itertools.permutations(list(range(n_nodes)))))
1041
+
1042
+ return [nodes[x] for x in best_path], best_weight
1043
+
1044
+ return tsp_asymmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic)
1045
+
1046
+ a, b, c, G_a, G_b, is_cyclic, is_reversed = tsp_asymmetric_header(
1047
+ G_m,
1048
+ nodes,
1049
+ quality,
1050
+ shots,
1051
+ anneal_t,
1052
+ anneal_h,
1053
+ repulsion_base,
1054
+ start_node,
1055
+ end_node,
1056
+ monte_carlo,
1057
+ is_cyclic,
1058
+ n_nodes,
1059
+ multi_start,
1060
+ )
1061
+
1062
+ if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 2) and (len(b) > 2):
1063
+ with ProcessPoolExecutor(max_workers=1) as executor:
1064
+ f = executor.submit(
1065
+ tsp_asymmetric,
1066
+ G_a,
1067
+ None,
1068
+ None,
1069
+ quality,
1070
+ shots,
1071
+ anneal_t,
1072
+ anneal_h,
1073
+ repulsion_base,
1074
+ True,
1075
+ 0,
1076
+ False,
1077
+ multi_start,
1078
+ False,
1079
+ True,
1080
+ parallel_level + 1,
1081
+ )
1082
+ sol_b = tsp_asymmetric(
1083
+ G_b,
1084
+ None,
1085
+ None,
1086
+ quality,
1087
+ shots,
1088
+ anneal_t,
1089
+ anneal_h,
1090
+ repulsion_base,
1091
+ True,
1092
+ 0,
1093
+ False,
1094
+ multi_start,
1095
+ False,
1096
+ True,
1097
+ parallel_level + 1,
1098
+ )
1099
+ sol_a = f.result()
1100
+ else:
1101
+ sol_a = tsp_asymmetric(
1102
+ G_a,
1103
+ quality=quality,
1104
+ shots=shots,
1105
+ anneal_t=anneal_t,
1106
+ anneal_h=anneal_h,
1107
+ repulsion_base=repulsion_base,
1108
+ monte_carlo=monte_carlo,
1109
+ is_cyclic=False,
1110
+ is_top_level=False,
1111
+ k_neighbors=0,
1112
+ multi_start=multi_start,
1113
+ is_parallel=False,
1114
+ )
1115
+ sol_b = tsp_asymmetric(
1116
+ G_b,
1117
+ quality=quality,
1118
+ shots=shots,
1119
+ anneal_t=anneal_t,
1120
+ anneal_h=anneal_h,
1121
+ repulsion_base=repulsion_base,
1122
+ monte_carlo=monte_carlo,
1123
+ is_cyclic=False,
1124
+ is_top_level=False,
1125
+ k_neighbors=0,
1126
+ multi_start=multi_start,
1127
+ is_parallel=False,
1128
+ )
1129
+
1130
+ neighbor_lists = [[0]]
1131
+ if k_neighbors > 0:
1132
+ # Precompute nearest neighbors for each node
1133
+ neighbor_lists = [([(float("inf"), 0)] * k_neighbors) for i in range(n_nodes)]
1134
+
1135
+ for i in range(n_nodes):
1136
+ for j in range(n_nodes):
1137
+ val = G_m[i, j]
1138
+ if val < neighbor_lists[i][-1][0]:
1139
+ neighbor_lists[i][-1] = (val, j)
1140
+ neighbor_lists[i].sort(key=lambda x: x[0])
1141
+
1142
+ for i in range(len(neighbor_lists)):
1143
+ neighbor_lists[i] = [x[1] for x in neighbor_lists[i]]
1144
+
1145
+ return tsp_asymmetric_driver(
1146
+ G_m,
1147
+ is_reversed,
1148
+ is_cyclic,
1149
+ is_top_level,
1150
+ start_node,
1151
+ end_node,
1152
+ k_neighbors,
1153
+ nodes,
1154
+ sol_a,
1155
+ sol_b,
1156
+ a,
1157
+ b,
1158
+ c[0] if len(c) else None,
1159
+ np.array(neighbor_lists),
1160
+ is_parallel,
1161
+ )
1162
+
1163
+
1164
+ @njit(cache=True)
1165
+ def get_G_m(G_data, G_rows, G_cols, low, high):
1166
+ if high < low:
1167
+ low, high = high, low
1168
+
1169
+ start = G_rows[low]
1170
+ end = G_rows[low + 1]
1171
+
1172
+ i = binary_search(G_cols[start:end], high) + start
1173
+ if i < end:
1174
+ return G_data[i]
1175
+
1176
+ return 0.0
1177
+
1178
+
1179
+ @njit(cache=True)
1180
+ def path_length_sparse(path, G_data, G_rows, G_cols):
1181
+ tot_len = 0.0
1182
+ for i in range(len(path) - 1):
1183
+ low, high = path[i], path[i + 1]
1184
+ if high < low:
1185
+ low, high = high, low
1186
+
1187
+ start = G_rows[low]
1188
+ end = G_rows[low + 1]
1189
+
1190
+ i = binary_search(G_cols[start:end], high) + start
1191
+ if i < end:
1192
+ tot_len += G_data[i]
1193
+
1194
+ return tot_len
1195
+
1196
+
1197
+ @njit(cache=True)
1198
+ def one_way_two_opt_sparse(best_path, G_data, G_rows, G_cols):
1199
+ improved = True
1200
+ best_dist = path_length_sparse(best_path, G_data, G_rows, G_cols)
1201
+ path_len = len(best_path)
1202
+
1203
+ while improved:
1204
+ improved = False
1205
+ for i in range(1, path_len - 1):
1206
+ for j in range(i + 2, path_len):
1207
+ new_path = best_path[:]
1208
+ new_path[i:j] = best_path[j - 1 : i - 1 : -1]
1209
+ new_dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1210
+ if new_dist < best_dist:
1211
+ best_path, best_dist = new_path, new_dist
1212
+ improved = True
1213
+
1214
+ return best_path, best_dist
1215
+
1216
+
1217
+ @njit(parallel=True, cache=True)
1218
+ def one_way_two_opt_sparse_parallel(best_path, G_data, G_rows, G_cols):
1219
+ improved = True
1220
+ best_dist = path_length_sparse(best_path, G_data, G_rows, G_cols)
1221
+ paths = [best_path] * n_threads
1222
+ dists = [best_dist] * n_threads
1223
+ path_len = len(best_path)
1224
+
1225
+ while improved:
1226
+ improved = False
1227
+ for i in range(1, path_len - 1):
1228
+ for j in range(i + 2, path_len, n_threads):
1229
+ max_k = min(n_threads, path_len - j)
1230
+ for k in prange(max_k):
1231
+ l = j + k
1232
+ new_path = best_path[:]
1233
+ new_path[i:l] = best_path[l - 1 : i - 1 : -1]
1234
+ dists[k] = path_length_sparse(new_path, G_data, G_rows, G_cols)
1235
+ paths[k] = new_path
1236
+ for k in range(max_k):
1237
+ if dists[k] < best_dist:
1238
+ best_path, best_dist, improved = paths[k], dists[k], True
1239
+
1240
+ return best_path, best_dist
1241
+
1242
+
1243
+ @njit(cache=True)
1244
+ def targeted_three_opt_sparse(path, G_data, G_rows, G_cols, neighbor_lists, k_neighbors=20):
1245
+ n = len(path)
1246
+ best_path = path[:]
1247
+ best_dist = path_length_sparse(best_path, G_data, G_rows, G_cols)
1248
+ improved = True
1249
+
1250
+ while improved:
1251
+ improved = False
1252
+ for i in range(n - 5):
1253
+ for _j in range(k_neighbors):
1254
+ j = neighbor_lists[path[i], _j]
1255
+ if j <= i or j >= n - 3:
1256
+ continue
1257
+ for _k in range(k_neighbors):
1258
+ k = neighbor_lists[path[j], _k]
1259
+ if k <= j or k >= n - 1:
1260
+ continue
1261
+
1262
+ # 7 unique cases (same as brute force, but restricted)
1263
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
1264
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1265
+ if dist < best_dist:
1266
+ best_path, best_dist, improved = new_path, dist, True
1267
+ break
1268
+
1269
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1270
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1271
+ if dist < best_dist:
1272
+ best_path, best_dist, improved = new_path, dist, True
1273
+ break
1274
+
1275
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1276
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1277
+ if dist < best_dist:
1278
+ best_path, best_dist, improved = new_path, dist, True
1279
+ break
1280
+
1281
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1282
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1283
+ if dist < best_dist:
1284
+ best_path, best_dist, improved = new_path, dist, True
1285
+ break
1286
+
1287
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1288
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1289
+ if dist < best_dist:
1290
+ best_path, best_dist, improved = new_path, dist, True
1291
+ break
1292
+
1293
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1294
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1295
+ if dist < best_dist:
1296
+ best_path, best_dist, improved = new_path, dist, True
1297
+ break
1298
+
1299
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1300
+ dist = path_length_sparse(new_path, G_data, G_rows, G_cols)
1301
+ if dist < best_dist:
1302
+ best_path, best_dist, improved = new_path, dist, True
1303
+ break
1304
+
1305
+ if improved:
1306
+ break
1307
+
1308
+ if improved:
1309
+ break
1310
+
1311
+ path = best_path[:]
1312
+
1313
+ return best_path, best_dist
1314
+
1315
+
1316
+ @njit(parallel=True, cache=True)
1317
+ def targeted_three_opt_sparse_parallel(path, G_data, G_rows, G_cols, neighbor_lists, k_neighbors=20):
1318
+ n = len(path)
1319
+ best_path = path[:]
1320
+ best_dist = path_length_sparse(best_path, G_data, G_rows, G_cols)
1321
+ paths = [best_path] * 7
1322
+ dists = [best_dist] * 7
1323
+ improved = True
1324
+
1325
+ while improved:
1326
+ improved = False
1327
+ for i in range(n - 5):
1328
+ for _j in range(k_neighbors):
1329
+ j = neighbor_lists[path[i], _j]
1330
+ if j <= i or j >= n - 3:
1331
+ continue
1332
+ for _k in range(k_neighbors):
1333
+ k = neighbor_lists[path[j], _k]
1334
+ if k <= j or k >= n - 1:
1335
+ continue
1336
+
1337
+ # 7 unique cases (same as brute force, but restricted)
1338
+ for l in prange(7):
1339
+ match l:
1340
+ case 0:
1341
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
1342
+ case 1:
1343
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1344
+ case 2:
1345
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1346
+ case 3:
1347
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1348
+ case 4:
1349
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1350
+ case 5:
1351
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1352
+ case _:
1353
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1354
+
1355
+ dists[l] = path_length_sparse(new_path, G_data, G_rows, G_cols)
1356
+ paths[l] = new_path
1357
+
1358
+ for l in range(7):
1359
+ if dists[l] < best_dist:
1360
+ best_path, best_dist, improved = paths[l], dists[l], True
1361
+
1362
+ if improved:
1363
+ break
1364
+
1365
+ if improved:
1366
+ break
1367
+
1368
+ if improved:
1369
+ break
1370
+
1371
+ path = best_path[:]
1372
+
1373
+ return best_path, best_dist
1374
+
1375
+
1376
+ @njit(cache=True)
1377
+ def stitch_singlet_sparse(G_data, G_rows, G_cols, singlet, bulk):
1378
+ best_path = bulk.copy()
1379
+ best_weight = get_G_m(G_data, G_rows, G_cols, singlet, bulk[0])
1380
+ weight = get_G_m(G_data, G_rows, G_cols, singlet, bulk[-1])
1381
+ if weight < best_weight:
1382
+ best_weight = weight
1383
+ best_path += [singlet]
1384
+ else:
1385
+ best_path = [singlet] + best_path
1386
+
1387
+ for i in range(1, len(bulk)):
1388
+ weight = (
1389
+ get_G_m(G_data, G_rows, G_cols, singlet, bulk[i - 1])
1390
+ + get_G_m(G_data, G_rows, G_cols, singlet, bulk[i])
1391
+ - get_G_m(G_data, G_rows, G_cols, bulk[i - 1], bulk[i])
1392
+ )
1393
+ if weight < best_weight:
1394
+ best_weight = weight
1395
+ best_path = bulk.copy()
1396
+ best_path.insert(i, singlet)
1397
+
1398
+ return best_path
1399
+
1400
+
1401
+ @njit(cache=True)
1402
+ def stitch_sparse_symmetric(G_data, G_rows, G_cols, path_a, path_b):
1403
+ if len(path_a) == 1:
1404
+ return stitch_singlet_sparse(G_data, G_rows, G_cols, path_a[0], path_b)
1405
+
1406
+ if len(path_b) == 1:
1407
+ return stitch_singlet_sparse(G_data, G_rows, G_cols, path_b[0], path_a)
1408
+
1409
+ terminals_a = [path_a[0], path_a[-1]]
1410
+ terminals_b = [path_b[0], path_b[-1]]
1411
+
1412
+ best_connect = get_G_m(G_data, G_rows, G_cols, terminals_a[1], terminals_b[0])
1413
+ best_path = path_b.copy()
1414
+ weight = get_G_m(G_data, G_rows, G_cols, terminals_a[0], terminals_b[1])
1415
+ if weight < best_connect:
1416
+ best_connect = weight
1417
+ best_path += path_a
1418
+ else:
1419
+ best_path = path_a + best_path
1420
+
1421
+ for _ in range(2):
1422
+ for _ in range(2):
1423
+ for i in range(1, len(path_b)):
1424
+ weight = (
1425
+ get_G_m(G_data, G_rows, G_cols, terminals_a[0], path_b[i - 1])
1426
+ + get_G_m(G_data, G_rows, G_cols, terminals_a[1], path_b[i])
1427
+ - get_G_m(G_data, G_rows, G_cols, path_b[i - 1], path_b[i])
1428
+ )
1429
+ if weight < best_connect:
1430
+ best_connect = weight
1431
+ best_path = path_b.copy()
1432
+ best_path[i:i] = path_a
1433
+ path_a.reverse()
1434
+ terminals_a.reverse()
1435
+ path_a, path_b = path_b, path_a
1436
+ terminals_a, terminals_b = terminals_b, terminals_a
1437
+
1438
+ return best_path
1439
+
1440
+
1441
+ @njit(cache=True)
1442
+ def restitch_sparse(G_data, G_rows, G_cols, path):
1443
+ l = len(path)
1444
+ mid = ((l + 1) if (l & 1) and (np.random.random() < 0.5) else l) >> 1
1445
+
1446
+ if mid < 4:
1447
+ return path
1448
+
1449
+ path_a = restitch_sparse(G_data, G_rows, G_cols, path[:mid])
1450
+ path_b = restitch_sparse(G_data, G_rows, G_cols, path[mid:])
1451
+
1452
+ return stitch_sparse_symmetric(G_data, G_rows, G_cols, path_a, path_b)
1453
+
1454
+
1455
+ @njit(cache=True)
1456
+ def tsp_sparse_brute_force_driver(G_data, G_rows, G_cols, n_nodes, nodes):
1457
+ if n_nodes == 3:
1458
+ w_012 = get_G_m(G_data, G_rows, G_cols, 0, 1) + get_G_m(G_data, G_rows, G_cols, 1, 2)
1459
+ w_021 = get_G_m(G_data, G_rows, G_cols, 0, 1) + get_G_m(G_data, G_rows, G_cols, 0, 2)
1460
+ w_120 = get_G_m(G_data, G_rows, G_cols, 0, 2) + get_G_m(G_data, G_rows, G_cols, 1, 2)
1461
+
1462
+ if w_012 >= w_021 and w_012 >= w_120:
1463
+ return (nodes, w_012)
1464
+
1465
+ if w_021 >= w_012 and w_021 >= w_120:
1466
+ return ([nodes[1], nodes[0], nodes[2]], w_021)
1467
+
1468
+ return ([nodes[0], nodes[2], nodes[1]], w_120)
1469
+
1470
+ if n_nodes == 2:
1471
+ return (nodes, get_G_m(G_data, G_rows, G_cols, 0, 1))
1472
+
1473
+ return (nodes, 0)
1474
+
1475
+
1476
+ @njit(cache=True)
1477
+ def tsp_sparse_bruteforce(G_data, G_rows, G_cols, perms):
1478
+ n = len(G_rows) - 1
1479
+ best_weight = float("inf")
1480
+ best_path = None
1481
+
1482
+ # Must fix node 0 at start to remove rotational symmetry in cyclic case!
1483
+
1484
+ max_i = len(perms[0]) - 1
1485
+
1486
+ for path in perms:
1487
+ weight = 0.0
1488
+ for i in range(max_i):
1489
+ low, high = path[i], path[i + 1]
1490
+ if high < low:
1491
+ low, high = high, low
1492
+
1493
+ start = G_rows[low]
1494
+ end = G_rows[low + 1]
1495
+
1496
+ i = binary_search(G_cols[start:end], high) + start
1497
+ if i < end:
1498
+ weight += G_data[i]
1499
+
1500
+ if weight < best_weight:
1501
+ best_weight = weight
1502
+ best_path = path
1503
+
1504
+ best_path = list(best_path)
1505
+
1506
+ return best_path, best_weight
1507
+
1508
+
1509
+ def init_G_a_b_sparse(G_m, a, b, dtype):
1510
+ n_a_nodes = len(a)
1511
+ n_b_nodes = len(b)
1512
+ G_a = lil_matrix((n_a_nodes, n_a_nodes), dtype=opencl_context.dtype)
1513
+ G_b = lil_matrix((n_b_nodes, n_b_nodes), dtype=opencl_context.dtype)
1514
+ for i in range(n_a_nodes):
1515
+ for j in range(n_a_nodes):
1516
+ if i == j:
1517
+ continue
1518
+ weight = G_m[a[i], a[j]]
1519
+ if weight != 0.0:
1520
+ G_a[i, j] = weight
1521
+ for i in range(n_b_nodes):
1522
+ for j in range(n_b_nodes):
1523
+ if i == j:
1524
+ continue
1525
+ weight = G_m[b[i], b[j]]
1526
+ if weight != 0.0:
1527
+ G_b[i, j] = weight
1528
+
1529
+ return G_a.tocsr(), G_b.tocsr()
1530
+
1531
+
1532
+ @njit(cache=True)
1533
+ def tsp_symmetric_sparse_driver(
1534
+ G_data,
1535
+ G_rows,
1536
+ G_cols,
1537
+ is_top_level,
1538
+ k_neighbors,
1539
+ nodes,
1540
+ sol_a,
1541
+ sol_b,
1542
+ a,
1543
+ b,
1544
+ neighbor_lists,
1545
+ is_parallel,
1546
+ ):
1547
+ path_a = [a[x] for x in sol_a[0]]
1548
+ path_b = [b[x] for x in sol_b[0]]
1549
+
1550
+ best_path = stitch_sparse_symmetric(G_data, G_rows, G_cols, path_a, path_b)
1551
+
1552
+ if is_top_level:
1553
+ if is_parallel:
1554
+ best_path, _ = one_way_two_opt_sparse_parallel(best_path, G_data, G_rows, G_cols)
1555
+ else:
1556
+ best_path, _ = one_way_two_opt_sparse(best_path, G_data, G_rows, G_cols)
1557
+
1558
+ if k_neighbors > 0:
1559
+ if is_parallel:
1560
+ best_path, _ = targeted_three_opt_sparse_parallel(best_path, G_data, G_rows, G_cols, neighbor_lists, k_neighbors)
1561
+ else:
1562
+ best_path, _ = targeted_three_opt_sparse(best_path, G_data, G_rows, G_cols, neighbor_lists, k_neighbors)
1563
+
1564
+ best_path = restitch_sparse(G_data, G_rows, G_cols, best_path)
1565
+
1566
+ best_weight = path_length_sparse(best_path, G_data, G_rows, G_cols)
1567
+
1568
+ return [nodes[x] for x in best_path], best_weight
1569
+
1570
+
1571
+ def tsp_symmetric_sparse(G, k_neighbors=20, is_top_level=True, is_parallel=True, parallel_level=0):
1572
+ dtype = opencl_context.dtype
1573
+ nodes = None
1574
+ n_nodes = 0
1575
+ G_m = None
1576
+ if isinstance(G, nx.Graph):
1577
+ nodes = list(G.nodes())
1578
+ n_nodes = len(nodes)
1579
+ G_m = to_scipy_sparse_upper_triangular(G, nodes, n_nodes, dtype)
1580
+ else:
1581
+ n_nodes = G.shape[0]
1582
+ nodes = list(range(n_nodes))
1583
+ G_m = G
1584
+
1585
+ if n_nodes < 7:
1586
+ if n_nodes > 3:
1587
+ best_path, best_weight = tsp_sparse_bruteforce(
1588
+ G_m.data,
1589
+ G_m.indptr,
1590
+ G_m.indices,
1591
+ list(itertools.permutations(list(range(n_nodes)))),
1592
+ )
1593
+
1594
+ return [nodes[x] for x in best_path], best_weight
1595
+
1596
+ return tsp_sparse_brute_force_driver(G_m.data, G_m.indptr, G_m.indices, n_nodes, nodes)
1597
+
1598
+ a, b = monte_carlo_loop(n_nodes)
1599
+
1600
+ G_a, G_b = init_G_a_b_sparse(G_m, a, b, dtype)
1601
+
1602
+ if is_parallel and (parallel_level < max_parallel_level) and (len(a) > 3) and (len(b) > 3):
1603
+ with ProcessPoolExecutor(max_workers=1) as executor:
1604
+ f = executor.submit(tsp_symmetric_sparse, G_a, 0, False, True, parallel_level + 1)
1605
+ sol_b = tsp_symmetric_sparse(G_b, 0, False, True, parallel_level + 1)
1606
+ sol_a = f.result()
1607
+ else:
1608
+ sol_a = tsp_symmetric_sparse(G_a, is_top_level=False, k_neighbors=0, is_parallel=False)
1609
+ sol_b = tsp_symmetric_sparse(G_b, is_top_level=False, k_neighbors=0, is_parallel=False)
1610
+
1611
+ neighbor_lists = [[0]]
1612
+ if k_neighbors > 0:
1613
+ # Precompute nearest neighbors for each node
1614
+ neighbor_lists = [([(float("inf"), 0)] * k_neighbors) for i in range(n_nodes)]
1615
+
1616
+ for i in range(n_nodes):
1617
+ for j in range(n_nodes):
1618
+ val = G_m[i, j]
1619
+ if val < neighbor_lists[i][-1][0]:
1620
+ neighbor_lists[i][-1] = (val, j)
1621
+ neighbor_lists[i].sort(key=lambda x: x[0])
1622
+
1623
+ for i in range(len(neighbor_lists)):
1624
+ neighbor_lists[i] = [x[1] for x in neighbor_lists[i]]
1625
+
1626
+ return tsp_symmetric_sparse_driver(
1627
+ G_m.data,
1628
+ G_m.indptr,
1629
+ G_m.indices,
1630
+ is_top_level,
1631
+ k_neighbors,
1632
+ nodes,
1633
+ sol_a,
1634
+ sol_b,
1635
+ a,
1636
+ b,
1637
+ np.array(neighbor_lists),
1638
+ is_parallel,
1639
+ )
1640
+
1641
+
1642
+ @njit(cache=True)
1643
+ def path_length_streaming(path, G_func):
1644
+ tot_len = 0.0
1645
+ for i in range(len(path) - 1):
1646
+ tot_len += G_func(path[i], path[i + 1])
1647
+
1648
+ return tot_len
1649
+
1650
+
1651
+ @njit(cache=True)
1652
+ def one_way_two_opt_streaming(best_path, G_func):
1653
+ improved = True
1654
+ best_dist = path_length_streaming(best_path, G_func)
1655
+ path_len = len(best_path)
1656
+
1657
+ while improved:
1658
+ improved = False
1659
+ for i in range(1, path_len - 1):
1660
+ for j in range(i + 2, path_len):
1661
+ new_path = best_path[:]
1662
+ new_path[i:j] = best_path[j - 1 : i - 1 : -1]
1663
+ new_dist = path_length_streaming(new_path, G_func)
1664
+ if new_dist < best_dist:
1665
+ best_path, best_dist, improved = new_path, new_dist, True
1666
+
1667
+ return best_path, best_dist
1668
+
1669
+
1670
+ @njit(parallel=True, cache=True)
1671
+ def one_way_two_opt_streaming_parallel(best_path, G_func):
1672
+ improved = True
1673
+ best_dist = path_length_streaming(best_path, G_func)
1674
+ paths = [best_path] * n_threads
1675
+ dists = [best_dist] * n_threads
1676
+ path_len = len(best_path)
1677
+
1678
+ while improved:
1679
+ improved = False
1680
+ for i in range(1, path_len - 1):
1681
+ for j in range(i + 2, path_len, n_threads):
1682
+ max_k = min(n_threads, path_len - j)
1683
+ for k in prange(max_k):
1684
+ l = j + k
1685
+ new_path = best_path[:]
1686
+ new_path[i:l] = best_path[l - 1 : i - 1 : -1]
1687
+ dists[k] = path_length_streaming(new_path, G_func)
1688
+ paths[k] = new_path
1689
+ for k in range(max_k):
1690
+ if dists[k] < best_dist:
1691
+ best_path, best_dist, improved = paths[k], dists[k], True
1692
+
1693
+ return best_path, best_dist
1694
+
1695
+
1696
+ @njit(cache=True)
1697
+ def targeted_three_opt_streaming(path, G_func, neighbor_lists, k_neighbors=20):
1698
+ n = len(path)
1699
+ best_path = path[:]
1700
+ best_dist = path_length_streaming(best_path, G_func)
1701
+ improved = True
1702
+
1703
+ while improved:
1704
+ improved = False
1705
+ for i in range(n - 5):
1706
+ for _j in range(k_neighbors):
1707
+ j = neighbor_lists[path[i], _j]
1708
+ if j <= i or j >= n - 3:
1709
+ continue
1710
+ for _k in range(k_neighbors):
1711
+ k = neighbor_lists[path[j], _k]
1712
+ if k <= j or k >= n - 1:
1713
+ continue
1714
+
1715
+ # 7 unique cases (same as brute force, but restricted)
1716
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
1717
+ dist = path_length_streaming(new_path, G_func)
1718
+ if dist < best_dist:
1719
+ best_path, best_dist, improved = new_path, dist, True
1720
+ break
1721
+
1722
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1723
+ dist = path_length_streaming(new_path, G_func)
1724
+ if dist < best_dist:
1725
+ best_path, best_dist, improved = new_path, dist, True
1726
+ break
1727
+
1728
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1729
+ dist = path_length_streaming(new_path, G_func)
1730
+ if dist < best_dist:
1731
+ best_path, best_dist, improved = new_path, dist, True
1732
+ break
1733
+
1734
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1735
+ dist = path_length_streaming(new_path, G_func)
1736
+ if dist < best_dist:
1737
+ best_path, best_dist, improved = new_path, dist, True
1738
+ break
1739
+
1740
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1741
+ dist = path_length_streaming(new_path, G_func)
1742
+ if dist < best_dist:
1743
+ best_path, best_dist, improved = new_path, dist, True
1744
+ break
1745
+
1746
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1747
+ dist = path_length_streaming(new_path, G_func)
1748
+ if dist < best_dist:
1749
+ best_path, best_dist, improved = new_path, dist, True
1750
+ break
1751
+
1752
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1753
+ dist = path_length_streaming(new_path, G_func)
1754
+ if dist < best_dist:
1755
+ best_path, best_dist, improved = new_path, dist, True
1756
+ break
1757
+
1758
+ if improved:
1759
+ break
1760
+
1761
+ if improved:
1762
+ break
1763
+
1764
+ path = best_path[:]
1765
+
1766
+ return best_path, best_dist
1767
+
1768
+
1769
+ @njit(parallel=True, cache=True)
1770
+ def targeted_three_opt_streaming_parallel(path, G_func, neighbor_lists, k_neighbors=20):
1771
+ n = len(path)
1772
+ best_path = path[:]
1773
+ best_dist = path_length_streaming(best_path, G_func)
1774
+ paths = [best_path] * 7
1775
+ dists = [best_dist] * 7
1776
+ improved = True
1777
+
1778
+ while improved:
1779
+ improved = False
1780
+ for i in range(n - 5):
1781
+ for _j in range(k_neighbors):
1782
+ j = neighbor_lists[path[i], _j]
1783
+ if j <= i or j >= n - 3:
1784
+ continue
1785
+ for _k in range(k_neighbors):
1786
+ k = neighbor_lists[path[j], _k]
1787
+ if k <= j or k >= n - 1:
1788
+ continue
1789
+
1790
+ # 7 unique cases (same as brute force, but restricted)
1791
+ for l in prange(7):
1792
+ match l:
1793
+ case 0:
1794
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 :]
1795
+ case 1:
1796
+ new_path = best_path[: j + 1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1797
+ case 2:
1798
+ new_path = best_path[: i + 1] + best_path[i + 1 : j + 1][::-1] + best_path[j + 1 : k + 1][::-1] + best_path[k + 1 :]
1799
+ case 3:
1800
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1801
+ case 4:
1802
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1803
+ case 5:
1804
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1] + best_path[i + 1 : j + 1][::-1] + best_path[k + 1 :]
1805
+ case _:
1806
+ new_path = best_path[: i + 1] + best_path[j + 1 : k + 1][::-1] + best_path[i + 1 : j + 1] + best_path[k + 1 :]
1807
+
1808
+ dists[l] = path_length_streaming(new_path, G_func)
1809
+ paths[l] = new_path
1810
+
1811
+ for l in range(7):
1812
+ if dists[l] < best_dist:
1813
+ best_path, best_dist, improved = paths[l], dists[l], True
1814
+
1815
+ if improved:
1816
+ break
1817
+
1818
+ if improved:
1819
+ break
1820
+
1821
+ if improved:
1822
+ break
1823
+
1824
+ path = best_path[:]
1825
+
1826
+ return best_path, best_dist
1827
+
1828
+
1829
+ @njit(cache=True)
1830
+ def stitch_singlet_streaming(G_func, singlet, bulk):
1831
+ best_path = bulk.copy()
1832
+ best_weight = G_func(singlet, bulk[0])
1833
+ weight = G_func(singlet, bulk[-1])
1834
+ if weight < best_weight:
1835
+ best_weight = weight
1836
+ best_path += [singlet]
1837
+ else:
1838
+ best_path = [singlet] + best_path
1839
+
1840
+ for i in range(1, len(bulk)):
1841
+ weight = G_func(singlet, bulk[i - 1]) + G_func(singlet, bulk[i]) - G_func(bulk[i - 1], bulk[i])
1842
+ if weight < best_weight:
1843
+ best_weight = weight
1844
+ best_path = bulk.copy()
1845
+ best_path.insert(i, singlet)
1846
+
1847
+ return best_path
1848
+
1849
+
1850
+ @njit(cache=True)
1851
+ def stitch_streaming_symmetric(G_func, path_a, path_b):
1852
+ if len(path_a) == 1:
1853
+ return stitch_singlet_streaming(G_func, path_a[0], path_b)
1854
+
1855
+ if len(path_b) == 1:
1856
+ return stitch_singlet_streaming(G_func, path_b[0], path_a)
1857
+
1858
+ terminals_a = [path_a[0], path_a[-1]]
1859
+ terminals_b = [path_b[0], path_b[-1]]
1860
+
1861
+ best_connect = G_func(terminals_a[1], terminals_b[0])
1862
+ best_path = path_b.copy()
1863
+ weight = G_func(terminals_a[0], terminals_b[1])
1864
+ if weight < best_connect:
1865
+ best_connect = weight
1866
+ best_path += path_a
1867
+ else:
1868
+ best_path = path_a + best_path
1869
+
1870
+ for _ in range(2):
1871
+ for _ in range(2):
1872
+ for i in range(1, len(path_b)):
1873
+ weight = G_func(terminals_a[0], path_b[i - 1]) + G_func(terminals_a[1], path_b[i]) - G_func(path_b[i - 1], path_b[i])
1874
+ if weight < best_connect:
1875
+ best_connect = weight
1876
+ best_path = path_b.copy()
1877
+ best_path[i:i] = path_a
1878
+ path_a.reverse()
1879
+ terminals_a.reverse()
1880
+ path_a, path_b = path_b, path_a
1881
+ terminals_a, terminals_b = terminals_b, terminals_a
1882
+
1883
+ return best_path
1884
+
1885
+
1886
+ @njit(cache=True)
1887
+ def restitch_streaming(G_func, path):
1888
+ l = len(path)
1889
+ mid = ((l + 1) if (l & 1) and (np.random.random() < 0.5) else l) >> 1
1890
+
1891
+ if mid < 4:
1892
+ return path
1893
+
1894
+ path_a = restitch_streaming(G_func, path[:mid])
1895
+ path_b = restitch_streaming(G_func, path[mid:])
1896
+
1897
+ return stitch_streaming_symmetric(G_func, path_a, path_b)
1898
+
1899
+
1900
+ @njit(cache=True)
1901
+ def tsp_streaming_brute_force_driver(G_func, n_nodes, nodes):
1902
+ if n_nodes == 3:
1903
+ w_012 = G_func(0, 1) + G_func(1, 2)
1904
+ w_021 = G_func(0, 1) + G_func(0, 2)
1905
+ w_120 = G_func(0, 2) + G_func(1, 2)
1906
+
1907
+ if w_012 >= w_021 and w_012 >= w_120:
1908
+ return (nodes, w_012)
1909
+
1910
+ if w_021 >= w_012 and w_021 >= w_120:
1911
+ return ([nodes[1], nodes[0], nodes[2]], w_021)
1912
+
1913
+ return ([nodes[0], nodes[2], nodes[1]], w_120)
1914
+
1915
+ if n_nodes == 2:
1916
+ return (nodes, G_func(0, 1))
1917
+
1918
+ return (nodes, 0)
1919
+
1920
+
1921
+ @njit(cache=True)
1922
+ def tsp_streaming_bruteforce(G_func, perms, n):
1923
+ best_weight = float("inf")
1924
+ best_path = None
1925
+
1926
+ # Must fix node 0 at start to remove rotational symmetry in cyclic case!
1927
+
1928
+ max_i = len(perms[0]) - 1
1929
+
1930
+ for path in perms:
1931
+ weight = 0.0
1932
+ for i in range(max_i):
1933
+ weight += G_func(path[i], path[i + 1])
1934
+
1935
+ if weight < best_weight:
1936
+ best_weight = weight
1937
+ best_path = path
1938
+
1939
+ best_path = list(best_path)
1940
+
1941
+ return best_path, best_weight
1942
+
1943
+
1944
+ @njit(cache=True)
1945
+ def tsp_symmetric_streaming_driver(G_func, is_top_level, k_neighbors, nodes, path_a, path_b, neighbor_lists, is_parallel):
1946
+ best_path = stitch_streaming_symmetric(G_func, path_a, path_b)
1947
+
1948
+ if is_top_level:
1949
+ if is_parallel:
1950
+ best_path, _ = one_way_two_opt_streaming_parallel(best_path, G_func)
1951
+ else:
1952
+ best_path, _ = one_way_two_opt_streaming(best_path, G_func)
1953
+
1954
+ if k_neighbors > 0:
1955
+ if is_parallel:
1956
+ best_path, _ = targeted_three_opt_streaming_parallel(best_path, G_func, neighbor_lists, k_neighbors)
1957
+ else:
1958
+ best_path, _ = targeted_three_opt_streaming(best_path, G_func, neighbor_lists, k_neighbors)
1959
+
1960
+ best_path = restitch_streaming(G_func, best_path)
1961
+
1962
+ best_weight = path_length_streaming(best_path, G_func)
1963
+
1964
+ return [nodes[x] for x in best_path], best_weight
1965
+
1966
+
1967
+ def tsp_symmetric_streaming(G_func, nodes, k_neighbors=20, is_top_level=True, is_parallel=True, parallel_level=0):
1968
+ dtype = opencl_context.dtype
1969
+ n_nodes = len(nodes)
1970
+
1971
+ if n_nodes < 7:
1972
+ if n_nodes > 3:
1973
+ best_path, best_weight = tsp_streaming_bruteforce(G_func, list(itertools.permutations(nodes)), n_nodes)
1974
+
1975
+ return best_path, best_weight
1976
+
1977
+ return tsp_streaming_brute_force_driver(G_func, n_nodes, nodes)
1978
+
1979
+ a, b = monte_carlo_loop(n_nodes)
1980
+
1981
+ if is_parallel and (parallel_level < max_parallel_level) and (len(a) > 3) and (len(b) > 3):
1982
+ with ProcessPoolExecutor(max_workers=1) as executor:
1983
+ f = executor.submit(tsp_symmetric_streaming, G_func, a, 0, False, True, parallel_level + 1)
1984
+ sol_b = tsp_symmetric_streaming(G_func, b, 0, False, True, parallel_level + 1)
1985
+ sol_a = f.result()
1986
+ else:
1987
+ sol_a = tsp_symmetric_streaming(G_func, a, is_top_level=False, k_neighbors=0, is_parallel=False)
1988
+ sol_b = tsp_symmetric_streaming(G_func, b, is_top_level=False, k_neighbors=0, is_parallel=False)
1989
+
1990
+ neighbor_lists = [[0]]
1991
+ if k_neighbors > 0:
1992
+ # Precompute nearest neighbors for each node
1993
+ neighbor_lists = [([(float("inf"), 0)] * k_neighbors) for i in range(n_nodes)]
1994
+
1995
+ for i in nodes:
1996
+ for j in nodes:
1997
+ val = G_func(i, j)
1998
+ if val < neighbor_lists[i][-1][0]:
1999
+ neighbor_lists[i][-1] = (val, j)
2000
+ neighbor_lists[i].sort(key=lambda x: x[0])
2001
+
2002
+ for i in range(len(neighbor_lists)):
2003
+ neighbor_lists[i] = [x[1] for x in neighbor_lists[i]]
2004
+
2005
+ return tsp_symmetric_streaming_driver(
2006
+ G_func,
2007
+ is_top_level,
2008
+ k_neighbors,
2009
+ nodes,
2010
+ sol_a[0],
2011
+ sol_b[0],
2012
+ np.array(neighbor_lists),
2013
+ is_parallel,
2014
+ )