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