PyQrackIsing 1.14.12__tar.gz → 1.15.0__tar.gz

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.
Files changed (22) hide show
  1. {pyqrackising-1.14.12/PyQrackIsing.egg-info → pyqrackising-1.15.0}/PKG-INFO +1 -1
  2. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/maxcut_tfim.py +82 -66
  3. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/spin_glass_solver.py +30 -9
  4. pyqrackising-1.15.0/PyQrackIsing/tsp_symmetric.py +248 -0
  5. {pyqrackising-1.14.12 → pyqrackising-1.15.0/PyQrackIsing.egg-info}/PKG-INFO +1 -1
  6. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/README.md +2 -2
  7. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/pyproject.toml +1 -1
  8. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/setup.py +1 -1
  9. pyqrackising-1.14.12/PyQrackIsing/tsp_symmetric.py +0 -146
  10. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/CMakeLists.txt +0 -0
  11. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/LICENSE.md +0 -0
  12. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/MANIFEST.in +0 -0
  13. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/__init__.py +0 -0
  14. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/_pyqrack_ising.cpp +0 -0
  15. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/generate_tfim_samples.py +0 -0
  16. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/tfim_magnetization.py +0 -0
  17. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing/tfim_square_magnetization.py +0 -0
  18. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing.egg-info/SOURCES.txt +0 -0
  19. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing.egg-info/dependency_links.txt +0 -0
  20. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing.egg-info/not-zip-safe +0 -0
  21. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/PyQrackIsing.egg-info/top_level.txt +0 -0
  22. {pyqrackising-1.14.12 → pyqrackising-1.15.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyQrackIsing
3
- Version: 1.14.12
3
+ Version: 1.15.0
4
4
  Summary: Near-ideal closed-form solutions for transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -257,6 +257,61 @@ def evaluate_cut_edges(samples, edge_keys, edge_values):
257
257
  return best_solution, float(best_value)
258
258
 
259
259
 
260
+ @njit
261
+ def init_thresholds(n_qubits):
262
+ n_bias = n_qubits - 1
263
+ thresholds = np.zeros(n_bias, dtype=np.float64)
264
+ tot_prob = 0
265
+ p = 1.0
266
+ if n_qubits & 1:
267
+ q = n_qubits // 2
268
+ thresholds[q - 1] = p
269
+ tot_prob = p
270
+ p /= 2
271
+ for q in range(1, n_qubits // 2):
272
+ thresholds[q - 1] = p
273
+ thresholds[n_bias - q] = p
274
+ tot_prob += 2 * p
275
+ p /= 2
276
+ thresholds /= tot_prob
277
+
278
+ return thresholds
279
+
280
+
281
+ @njit
282
+ def init_theta(delta_t, tot_t, h_mult, n_qubits, J_eff, degrees):
283
+ theta = np.zeros(n_qubits)
284
+ for q in range(n_qubits):
285
+ J = J_eff[q]
286
+ z = degrees[q]
287
+ theta[q] = np.arcsin(
288
+ max(
289
+ -1.0,
290
+ min(
291
+ 1.0,
292
+ (1.0 if J > 0.0 else -1.0) if np.isclose(abs(z * J), 0.0) else (abs(h_mult) / (z * J)),
293
+ ),
294
+ )
295
+ )
296
+
297
+ return theta
298
+
299
+ @njit
300
+ def compute_adjacency(G_m):
301
+ n_qubits = len(G_m)
302
+ adjacency = np.full((n_qubits, n_qubits), -1, dtype=np.int32)
303
+ for i in range(n_qubits):
304
+ k = 0
305
+ for j in range(n_qubits):
306
+ if i == j:
307
+ continue
308
+ if G_m[i, j] != 0.0:
309
+ adjacency[i, k] = j
310
+ k += 1
311
+
312
+ return adjacency
313
+
314
+
260
315
  # By Gemini (Google Search AI)
261
316
  def int_to_bitstring(integer, length):
262
317
  return (bin(integer)[2:].zfill(length))[::-1]
@@ -267,22 +322,26 @@ def maxcut_tfim(
267
322
  quality=None,
268
323
  shots=None,
269
324
  ):
270
- # Number of qubits/nodes
271
- nodes = list(G.nodes())
272
- n_qubits = len(nodes)
325
+ nodes = None
326
+ n_qubits = 0
327
+ G_m = None
328
+ if isinstance(G, nx.Graph):
329
+ nodes = list(G.nodes())
330
+ n_qubits = len(nodes)
331
+ G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0)
332
+ else:
333
+ n_qubits = len(G)
334
+ nodes = list(range(n_qubits))
335
+ G_m = G
273
336
 
274
337
  if n_qubits == 0:
275
338
  return "", 0, ([], [])
276
339
 
277
340
  if n_qubits == 1:
278
- return "0", 0, ([nodes[0]], [])
341
+ return "0", 0, (nodes, [])
279
342
 
280
343
  if n_qubits == 2:
281
- ed = G.get_edge_data(nodes[0], nodes[1], default={})
282
- if ed == {}:
283
- return "01", 0, ([nodes[0]], [nodes[1]])
284
-
285
- weight = ed.get("weight", 1.0)
344
+ weight = G_m[0, 1]
286
345
  if weight < 0.0:
287
346
  return "00", 0, (nodes, [])
288
347
 
@@ -302,56 +361,16 @@ def maxcut_tfim(
302
361
  grid_size = n_steps * n_qubits
303
362
  grid_dims = (n_steps, n_qubits)
304
363
 
305
- J_eff = np.array(
306
- [
307
- -sum(edge_attributes.get("weight", 1.0) for _, edge_attributes in G.adj[n].items())
308
- for n in nodes
309
- ],
310
- dtype=np.float64,
311
- )
312
- degrees = np.array(
313
- [
314
- sum(abs(edge_attributes.get("weight", 1.0)) for _, edge_attributes in G.adj[n].items())
315
- for n in nodes
316
- ],
317
- dtype=np.float64,
318
- )
319
- # thresholds = tfim_sampler._maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality)
364
+ J_eff = np.array([-sum(G_m[n]) for n in range(n_qubits)], dtype=np.float64)
365
+ degrees = np.array([sum(abs(G_m[n])) for n in range(n_qubits)], dtype=np.float64)
320
366
 
321
- n_bias = n_qubits - 1
322
- thresholds = np.zeros(n_bias, dtype=np.float64)
323
- tot_prob = 0
324
- p = 1.0
325
- if n_qubits & 1:
326
- q = n_qubits // 2
327
- thresholds[q - 1] = p
328
- tot_prob = p
329
- p /= 2
330
- for q in range(1, n_qubits // 2):
331
- thresholds[q - 1] = p
332
- thresholds[n_bias - q] = p
333
- tot_prob += 2 * p
334
- p /= 2
335
- thresholds /= tot_prob
367
+ thresholds = init_thresholds(n_qubits)
336
368
 
337
369
  if IS_CUDA_AVAILABLE and cuda.is_available() and grid_size >= 128:
338
370
  delta_t = 1.0 / n_steps
339
371
  tot_t = n_steps * delta_t
340
372
  h_mult = 32.0 / tot_t
341
-
342
- theta = np.zeros(n_qubits)
343
- for q in range(n_qubits):
344
- J = J_eff[q]
345
- z = degrees[q]
346
- theta[q] = np.arcsin(
347
- max(
348
- -1.0,
349
- min(
350
- 1.0,
351
- (1.0 if J > 0.0 else -1.0) if np.isclose(abs(z * J), 0.0) else (abs(h_mult) / (z * J)),
352
- ),
353
- )
354
- )
373
+ theta = init_theta(delta_t, tot_t, h_mult, n_qubits, J_eff, degrees)
355
374
 
356
375
  cuda_maxcut_hamming_cdf[grid_dims, group_size](delta_t, tot_t, h_mult, J_eff, degrees, theta, thresholds)
357
376
 
@@ -359,21 +378,14 @@ def maxcut_tfim(
359
378
  thresholds /= tot_prob
360
379
 
361
380
  tot_prob = 0.0
362
- for i in range(n_bias):
381
+ for i in range(n_qubits - 1):
363
382
  tot_prob += thresholds[i]
364
383
  thresholds[i] = tot_prob
365
384
  thresholds[-1] = 2.0
366
385
  else:
367
386
  maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, thresholds)
368
387
 
369
- G_dict = nx.to_dict_of_lists(G)
370
- max_degree = max(len(x) for x in G_dict.values())
371
- adjacency = np.full((len(nodes), max_degree), -1, dtype=np.int32)
372
- for i in range(len(nodes)):
373
- adj = G_dict.get(nodes[i], [])
374
- for j in range(len(adj)):
375
- adjacency[i, j] = nodes.index(adj[j])
376
-
388
+ adjacency = compute_adjacency(G_m)
377
389
  J_max = max(J_eff)
378
390
  weights = 1.0 / (1.0 + (J_max - J_eff))
379
391
  # We only need unique instances
@@ -381,10 +393,14 @@ def maxcut_tfim(
381
393
 
382
394
  edge_keys = []
383
395
  edge_values = []
384
- for u, v, data in G.edges(data=True):
385
- edge_keys.append(nodes.index(u))
386
- edge_keys.append(nodes.index(v))
387
- edge_values.append(data.get("weight", 1.0))
396
+ for i in range(n_qubits):
397
+ for j in range(i + 1, n_qubits):
398
+ weight = G_m[i, j]
399
+ if weight == 0.0:
400
+ continue
401
+ edge_keys.append(i)
402
+ edge_keys.append(j)
403
+ edge_values.append(weight)
388
404
 
389
405
  best_solution, best_value = evaluate_cut_edges(samples, edge_keys, edge_values)
390
406
 
@@ -1,5 +1,6 @@
1
1
  from .maxcut_tfim import maxcut_tfim
2
2
  import itertools
3
+ import networkx as nx
3
4
  import numpy as np
4
5
  from numba import njit, prange
5
6
  import os
@@ -57,14 +58,30 @@ def int_to_bitstring(integer, length):
57
58
 
58
59
 
59
60
  def spin_glass_solver(G, quality=None, shots=None, correction_quality=None, best_guess=None):
60
- nodes = list(G.nodes())
61
- n_qubits = len(nodes)
61
+ nodes = None
62
+ n_qubits = 0
63
+ G_m = None
64
+ if isinstance(G, nx.Graph):
65
+ nodes = list(G.nodes())
66
+ n_qubits = len(nodes)
67
+ G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0)
68
+ else:
69
+ n_qubits = len(G)
70
+ nodes = list(range(n_qubits))
71
+ G_m = G
62
72
 
63
73
  if n_qubits == 0:
64
74
  return "", 0, ([], []), 0
65
75
 
66
76
  if n_qubits == 1:
67
- return "0", 0, ([nodes[0]], [])
77
+ return "0", 0, (nodes, []), 0
78
+
79
+ if n_qubits == 2:
80
+ weight = G_m[0, 1]
81
+ if weight < 0.0:
82
+ return "00", 0, (nodes, []), weight
83
+
84
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
68
85
 
69
86
  if correction_quality is None:
70
87
  # maxcut_tfim(G) scales roughly like n^4,
@@ -75,19 +92,23 @@ def spin_glass_solver(G, quality=None, shots=None, correction_quality=None, best
75
92
  if isinstance(best_guess, str):
76
93
  bitstring = best_guess
77
94
  elif isinstance(best_guess, int):
78
- bitstring = int_to_bitstring(best_guess, G.number_of_nodes())
95
+ bitstring = int_to_bitstring(best_guess, n_qubits)
79
96
  elif isinstance(best_guess, list):
80
97
  bitstring = "".join(["1" if b else "0" for b in best_guess])
81
98
  else:
82
- bitstring, _, _ = maxcut_tfim(G, quality=quality, shots=shots)
99
+ bitstring, _, _ = maxcut_tfim(G_m, quality=quality, shots=shots)
83
100
  best_theta = [b == "1" for b in list(bitstring)]
84
101
 
85
102
  edge_keys = []
86
103
  edge_values = []
87
- for u, v, data in G.edges(data=True):
88
- edge_keys.append(nodes.index(u))
89
- edge_keys.append(nodes.index(v))
90
- edge_values.append(data.get("weight", 1.0))
104
+ for i in range(n_qubits):
105
+ for j in range(i + 1, n_qubits):
106
+ weight = G_m[i, j]
107
+ if weight == 0.0:
108
+ continue
109
+ edge_keys.append(i)
110
+ edge_keys.append(j)
111
+ edge_values.append(weight)
91
112
 
92
113
  min_energy = compute_energy(best_theta, edge_keys, edge_values)
93
114
  improved = True
@@ -0,0 +1,248 @@
1
+ from .spin_glass_solver import spin_glass_solver
2
+ import networkx as nx
3
+ from numba import njit
4
+ import numpy as np
5
+
6
+
7
+ # two_opt() and targeted_three_opt() written by Elara (OpenAI ChatGPT instance)
8
+ @njit
9
+ def path_length(path, G_m):
10
+ tot_len = 0.0
11
+ for i in range(len(path)-1):
12
+ tot_len += G_m[path[i], path[i+1]]
13
+
14
+ return tot_len
15
+
16
+ @njit
17
+ def two_opt(path, G):
18
+ improved = True
19
+ best_path = path
20
+ best_dist = path_length(best_path, G)
21
+
22
+ while improved:
23
+ improved = False
24
+ for i in range(1, len(path) - 2):
25
+ for j in range(i+1, len(path) - 1):
26
+ if j - i == 1: # adjacent edges, skip
27
+ continue
28
+ new_path = best_path[:]
29
+ new_path[i:j] = best_path[j-1:i-1:-1] # reverse segment
30
+ new_dist = path_length(new_path, G)
31
+ if new_dist < best_dist:
32
+ best_path, best_dist = new_path, new_dist
33
+ improved = True
34
+ path = best_path
35
+ return best_path, best_dist
36
+
37
+ @njit
38
+ def targeted_three_opt(path, W, k_neighbors=20):
39
+ """
40
+ Lin-Kernighan style 3-opt heuristic for TSP improvement.
41
+
42
+ path: list of node indices (tour)
43
+ W: adjacency matrix (numpy array)
44
+ k_neighbors: restrict 3-opt to nearest neighbors for efficiency
45
+ """
46
+
47
+ n = len(path)
48
+ best_path = path[:]
49
+ best_dist = path_length(best_path, W)
50
+ improved = True
51
+
52
+ # Precompute nearest neighbors for each node
53
+ neighbor_lists = [
54
+ np.argsort(W[i])[:k_neighbors] for i in range(n)
55
+ ]
56
+
57
+ while improved:
58
+ improved = False
59
+ for i in range(n - 5):
60
+ for j in neighbor_lists[path[i]]:
61
+ if j <= i or j >= n-3:
62
+ continue
63
+ for k in neighbor_lists[path[j]]:
64
+ if k <= j or k >= n-1:
65
+ continue
66
+
67
+ # Extract indices
68
+ A, B, C, D, E, F = path[i], path[i+1], path[j], path[j+1], path[k], path[k+1]
69
+
70
+ # 7 unique cases (same as brute force, but restricted)
71
+ new_path = best_path[:i+1] + best_path[i+1:j+1][::-1] + best_path[j+1:]
72
+ dist = path_length(new_path, W)
73
+ if dist < best_dist:
74
+ best_path, best_dist, improved = new_path, dist, True
75
+ break
76
+
77
+ new_path = best_path[:j+1] + best_path[j+1:k+1][::-1] + best_path[k+1:]
78
+ dist = path_length(new_path, W)
79
+ if dist < best_dist:
80
+ best_path, best_dist, improved = new_path, dist, True
81
+ break
82
+
83
+ new_path = best_path[:i+1] + best_path[i+1:j+1][::-1] + best_path[j+1:k+1][::-1] + best_path[k+1:]
84
+ dist = path_length(new_path, W)
85
+ if dist < best_dist:
86
+ best_path, best_dist, improved = new_path, dist, True
87
+ break
88
+
89
+ new_path = best_path[:i+1] + best_path[j+1:k+1] + best_path[i+1:j+1] + best_path[k+1:]
90
+ dist = path_length(new_path, W)
91
+ if dist < best_dist:
92
+ best_path, best_dist, improved = new_path, dist, True
93
+ break
94
+
95
+ new_path = best_path[:i+1] + best_path[j+1:k+1][::-1] + best_path[i+1:j+1][::-1] + best_path[k+1:]
96
+ dist = path_length(new_path, W)
97
+ if dist < best_dist:
98
+ best_path, best_dist, improved = new_path, dist, True
99
+ break
100
+
101
+ new_path = best_path[:i+1] + best_path[j+1:k+1] + best_path[i+1:j+1][::-1] + best_path[k+1:]
102
+ dist = path_length(new_path, W)
103
+ if dist < best_dist:
104
+ best_path, best_dist, improved = new_path, dist, True
105
+ break
106
+
107
+ new_path = best_path[:i+1] + best_path[j+1:k+1][::-1] + best_path[i+1:j+1] + best_path[k+1:]
108
+ dist = path_length(new_path, W)
109
+ if dist < best_dist:
110
+ best_path, best_dist, improved = new_path, dist, True
111
+ break
112
+
113
+ if improved:
114
+ break
115
+
116
+ if improved:
117
+ break
118
+
119
+ path = best_path[:]
120
+
121
+ return best_path, best_dist
122
+
123
+ def tsp_symmetric(G, quality=0, shots=None, correction_quality=2, start_node=None, is_cyclic=True, is_3_opt=True, k_neighbors=20):
124
+ nodes = None
125
+ n_nodes = 0
126
+ G_m = None
127
+ if isinstance(G, nx.Graph):
128
+ nodes = list(G.nodes())
129
+ n_nodes = len(nodes)
130
+ G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0)
131
+ else:
132
+ n_nodes = len(G)
133
+ nodes = list(range(n_nodes))
134
+ G_m = G
135
+
136
+ if n_nodes == 0:
137
+ return ([], 0)
138
+ if n_nodes == 1:
139
+ return ([nodes[0]], 0)
140
+ if n_nodes == 2:
141
+ return ([nodes[0], nodes[1]], G_m[nodes[0], nodes[1]])
142
+
143
+ a = []
144
+ b = []
145
+ if not (start_node is None):
146
+ a = [start_node]
147
+ b = nodes
148
+ b.remove(start_node)
149
+ else:
150
+ while (len(a) == 0) or (len(b) == 0):
151
+ bits = ''
152
+ _, _, bits, _ = spin_glass_solver(G, quality=quality, shots=shots, correction_quality=correction_quality)
153
+ a = list(bits[0])
154
+ b = list(bits[1])
155
+
156
+ n_a_nodes = len(a)
157
+ n_b_nodes = len(b)
158
+ G_a = np.zeros((n_a_nodes, n_a_nodes), dtype=np.float64)
159
+ G_b = np.zeros((n_b_nodes, n_b_nodes), dtype=np.float64)
160
+ for i in range(n_a_nodes):
161
+ for j in range(n_a_nodes):
162
+ if i == j:
163
+ continue
164
+ G_a[i, j] = G_m[a[i], a[j]]
165
+ for i in range(n_b_nodes):
166
+ for j in range(n_b_nodes):
167
+ if i == j:
168
+ continue
169
+ G_b[i, j] = G_m[b[i], b[j]]
170
+
171
+ sol_a = tsp_symmetric(G_a, quality=quality, is_cyclic=False, is_3_opt=False)
172
+ sol_b = tsp_symmetric(G_b, quality=quality, is_cyclic=False, is_3_opt=False)
173
+
174
+ path_a = [a[x] for x in sol_a[0]]
175
+ path_b = [b[x] for x in sol_b[0]]
176
+
177
+ sol_weight = sol_a[1] + sol_b[1]
178
+
179
+ single = None
180
+ is_single_a = len(path_a) == 1
181
+ is_single_b = len(path_b) == 1
182
+
183
+ if is_single_a and is_single_b:
184
+ return (path_a + path_b, sol_weight + G_m[path_a[0], path_b[0]])
185
+
186
+ singlet = None
187
+ bulk = None
188
+ if is_single_a:
189
+ singlet = path_a[0]
190
+ bulk = path_b
191
+ elif is_single_b:
192
+ singlet = path_b[0]
193
+ bulk = path_a
194
+
195
+ if not singlet is None:
196
+ best_weight = G_m[singlet, bulk[0]]
197
+ best_path = [singlet] + bulk
198
+ weight = G_m[singlet, bulk[-1]]
199
+ if weight < best_weight:
200
+ best_weight = weight
201
+ best_path = bulk + [singlet]
202
+ for i in range(len(bulk) - 1):
203
+ weight = (
204
+ G_m[singlet, bulk[i]] +
205
+ G_m[singlet, bulk[i + 1]] -
206
+ G_m[bulk[i], bulk[i + 1]]
207
+ )
208
+ if weight < best_weight:
209
+ best_weight = weight
210
+ best_path = bulk.copy()
211
+ best_path.insert(i + 1, singlet)
212
+ else:
213
+ terminals_a = [path_a[0], path_a[-1]]
214
+ terminals_b = [path_b[0], path_b[-1]]
215
+
216
+ for _ in range(2):
217
+ for _ in range(2):
218
+ best_weight = G_m[terminals_a[1], terminals_b[0]]
219
+ best_path = path_a + path_b
220
+ weight = G_m[terminals_b[1], terminals_a[0]]
221
+ if weight < best_weight:
222
+ best_weight = weight
223
+ best_path = path_b + path_a
224
+ for i in range(len(path_b) - 1):
225
+ weight = (
226
+ G_m[terminals_a[0], path_b[i]] +
227
+ G_m[terminals_a[1], path_b[i + 1]] -
228
+ G_m[path_b[i], path_b[i + 1]]
229
+ )
230
+ if weight < best_weight:
231
+ best_weight = weight
232
+ best_path = path_b.copy()
233
+ best_path[i + 1:i + 1] = path_a
234
+ path_a.reverse()
235
+ terminals_a.reverse()
236
+ path_a, path_b = path_b, path_a
237
+ terminals_a, terminals_b = terminals_b, terminals_a
238
+
239
+ best_path, best_weight = two_opt(best_path, G_m)
240
+
241
+ if is_3_opt:
242
+ best_path, best_weight = targeted_three_opt(best_path, G_m, k_neighbors)
243
+
244
+ if is_cyclic:
245
+ best_weight += G_m[best_path[-1], best_path[0]]
246
+ best_path += [best_path[0]]
247
+
248
+ return [nodes[x] for x in best_path], best_weight
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyQrackIsing
3
- Version: 1.14.12
3
+ Version: 1.15.0
4
4
  Summary: Near-ideal closed-form solutions for transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -93,13 +93,13 @@ def generate_tsp_graph(n_nodes=64, seed=None):
93
93
 
94
94
  n_nodes = 128
95
95
  G = generate_tsp_graph(n_nodes=n_nodes, seed=42)
96
- circuit, path_length = tsp_symmetric(G, quality=0, correction_quality=2, is_cyclic=True, start_node=None)
96
+ circuit, path_length = tsp_symmetric(G, quality=0, correction_quality=2, start_node=None, is_cyclic=True, is_3_opt=True, k_neighbors=20)
97
97
 
98
98
  print(f"Node count: {n_nodes}")
99
99
  print(f"Path: {circuit}")
100
100
  print(f"Path length: {path_length}")
101
101
  ```
102
- We only provide a solver for the symmetric version of the TSP (i.e., the distance from "A" to "B" is considered the same as from "B" to "A"). `is_cyclic` controls whether the path must ultimately complete a circuit, if `True`, or a one-way trip, if `False`. When the desired route is acyclic, a fixed starting point can optionally be specified via passing the node label to `start_node` (or, without this parameter, the solver will also attempt to pick an optimal starting point).
102
+ We only provide a solver for the symmetric version of the TSP (i.e., the distance from "A" to "B" is considered the same as from "B" to "A"). `is_cyclic` controls whether the path must ultimately complete a circuit, if `True`, or a one-way trip, if `False`. When the desired route is acyclic, a fixed starting point can optionally be specified via passing the node label to `start_node` (or, without this parameter, the solver will also attempt to pick an optimal starting point). Set `is_3_opt=False` or reduce the 3-opt `k_neighbors` to save time, with slightly lower-quality results.
103
103
 
104
104
  ## About
105
105
  Transverse field Ising model (TFIM) is the basis of most claimed algorithmic "quantum advantage," circa 2025, with the notable exception of Shor's integer factoring algorithm.
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
12
12
 
13
13
  [project]
14
14
  name = "PyQrackIsing"
15
- version = "1.14.12"
15
+ version = "1.15.0"
16
16
  requires-python = ">=3.8"
17
17
  description = "Near-ideal closed-form solutions for transverse field Ising model (TFIM)"
18
18
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -51,7 +51,7 @@ ext_modules = [CMakeExtension('tfim_sampler')]
51
51
 
52
52
  setup(
53
53
  name='PyQrackIsing',
54
- version='1.14.12',
54
+ version='1.15.0',
55
55
  author='Dan Strano',
56
56
  author_email='stranoj@gmail.com',
57
57
  description='Near-ideal closed-form solutions for transverse field Ising model (TFIM)',
@@ -1,146 +0,0 @@
1
- from .spin_glass_solver import spin_glass_solver
2
- import networkx as nx
3
-
4
-
5
- # two_opt() written by Elara (OpenAI ChatGPT instance)
6
- def two_opt(path, G):
7
- improved = True
8
- best_path = path
9
- best_dist = path_length(best_path, G)
10
-
11
- while improved:
12
- improved = False
13
- for i in range(1, len(path) - 2):
14
- for j in range(i+1, len(path) - 1):
15
- if j - i == 1: # adjacent edges, skip
16
- continue
17
- new_path = best_path[:]
18
- new_path[i:j] = best_path[j-1:i-1:-1] # reverse segment
19
- new_dist = path_length(new_path, G)
20
- if new_dist < best_dist:
21
- best_path, best_dist = new_path, new_dist
22
- improved = True
23
- path = best_path
24
- return best_path, best_dist
25
-
26
- def path_length(path, G):
27
- return sum(G[path[i]][path[i+1]].get("weight", 1.0) for i in range(len(path)-1))
28
-
29
- def tsp_symmetric(G, quality=0, shots=None, correction_quality=2, is_cyclic=True, start_node=None):
30
- nodes = list(G.nodes())
31
- n_nodes = len(nodes)
32
-
33
- if n_nodes == 0:
34
- return ([], 0)
35
- if n_nodes == 1:
36
- return ([nodes[0]], 0)
37
- if n_nodes == 2:
38
- return ([nodes[0], nodes[1]], G[nodes[0]][nodes[1]].get("weight", 1.0))
39
-
40
- a = []
41
- b = []
42
- if not (start_node is None):
43
- a = [start_node]
44
- b = nodes
45
- b.remove(start_node)
46
- else:
47
- while (len(a) == 0) or (len(b) == 0):
48
- bits = ''
49
- _, _, bits, _ = spin_glass_solver(G, quality=quality, shots=shots, correction_quality=correction_quality)
50
- a = list(bits[0])
51
- b = list(bits[1])
52
-
53
- G_a = nx.Graph()
54
- G_b = nx.Graph()
55
- G_a.add_nodes_from(a)
56
- G_b.add_nodes_from(b)
57
- for u, v, data in G.edges(data=True):
58
- if (u in a) and (v in a):
59
- G_a.add_edge(u, v, weight=data.get("weight", 1.0))
60
- continue
61
-
62
- if (u in b) and (v in b):
63
- G_b.add_edge(u, v, weight=data.get("weight", 1.0))
64
-
65
- sol_a = tsp_symmetric(G_a, quality=quality, is_cyclic=False)
66
- sol_b = tsp_symmetric(G_b, quality=quality, is_cyclic=False)
67
-
68
- path_a = sol_a[0]
69
- path_b = sol_b[0]
70
-
71
- sol_weight = sol_a[1] + sol_b[1]
72
-
73
- single = None
74
- is_single_a = len(path_a) == 1
75
- is_single_b = len(path_b) == 1
76
-
77
- if is_single_a and is_single_b:
78
- return (path_a + path_b, sol_weight + G[path_a[0]][path_b[0]].get("weight", 1.0))
79
-
80
- singlet = None
81
- bulk = None
82
- if is_single_a:
83
- singlet = path_a[0]
84
- bulk = path_b
85
- elif is_single_b:
86
- singlet = path_b[0]
87
- bulk = path_a
88
-
89
- if not singlet is None:
90
- best_weight = G[singlet][bulk[0]].get("weight", 1.0)
91
- best_path = [singlet] + bulk
92
- weight = G[singlet][bulk[-1]].get("weight", 1.0)
93
- if weight < best_weight:
94
- best_weight = weight
95
- best_path = bulk + [singlet]
96
- for i in range(len(bulk) - 1):
97
- weight = (
98
- G[singlet][bulk[i]].get("weight", 1.0) +
99
- G[singlet][bulk[i + 1]].get("weight", 1.0) -
100
- G[bulk[i]][bulk[i + 1]].get("weight", 1.0)
101
- )
102
- if weight < best_weight:
103
- best_weight = weight
104
- best_path = bulk.copy().insert(singlet, i + 1)
105
-
106
- best_path, best_weight = two_opt(best_path, G)
107
-
108
- if is_cyclic:
109
- best_weight += G[best_path[-1]][best_path[0]].get("weight", 1.0)
110
- best_path += [best_path[0]]
111
-
112
- return best_path, best_weight
113
-
114
- terminals_a = [path_a[0], path_a[-1]]
115
- terminals_b = [path_b[0], path_b[-1]]
116
-
117
- for _ in range(2):
118
- for _ in range(2):
119
- best_weight = G[terminals_a[1]][terminals_b[0]].get("weight", 1.0)
120
- best_path = path_a + path_b
121
- weight = G[terminals_b[1]][terminals_a[0]].get("weight", 1.0)
122
- if weight < best_weight:
123
- best_weight = weight
124
- best_path = path_b + path_a
125
- for i in range(len(path_b) - 1):
126
- weight = (
127
- G[terminals_a[0]][path_b[i]].get("weight", 1.0) +
128
- G[terminals_a[1]][path_b[i + 1]].get("weight", 1.0) -
129
- G[path_b[i]][path_b[i + 1]].get("weight", 1.0)
130
- )
131
- if weight < best_weight:
132
- best_weight = weight
133
- best_path = path_b.copy()
134
- best_path[i + 1:i + 1] = path_a
135
- path_a.reverse()
136
- terminals_a.reverse()
137
- path_a, path_b = path_b, path_a
138
- terminals_a, terminals_b = terminals_b, terminals_a
139
-
140
- best_path, best_weight = two_opt(best_path, G)
141
-
142
- if is_cyclic:
143
- best_weight += G[best_path[-1]][best_path[0]].get("weight", 1.0)
144
- best_path += [best_path[0]]
145
-
146
- return best_path, best_weight
File without changes
File without changes