PyQrackIsing 3.4.5__tar.gz → 3.5.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 (24) hide show
  1. {pyqrackising-3.4.5/pyqrackising.egg-info → pyqrackising-3.5.0}/PKG-INFO +1 -1
  2. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/README.md +5 -5
  3. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyproject.toml +1 -1
  4. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/__init__.py +2 -0
  5. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/maxcut_tfim.py +40 -38
  6. pyqrackising-3.5.0/pyqrackising/maxcut_tfim_sparse.py +391 -0
  7. pyqrackising-3.5.0/pyqrackising/spin_glass_solver_sparse.py +144 -0
  8. {pyqrackising-3.4.5 → pyqrackising-3.5.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  9. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising.egg-info/SOURCES.txt +2 -0
  10. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/setup.py +1 -1
  11. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/CMakeLists.txt +0 -0
  12. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/LICENSE.md +0 -0
  13. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/MANIFEST.in +0 -0
  14. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/_pyqrack_ising.cpp +0 -0
  15. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/generate_tfim_samples.py +0 -0
  16. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/kernels.cl +0 -0
  17. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/spin_glass_solver.py +0 -0
  18. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/tfim_magnetization.py +0 -0
  19. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/tfim_square_magnetization.py +0 -0
  20. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising/tsp.py +0 -0
  21. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  22. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  23. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/pyqrackising.egg-info/top_level.txt +0 -0
  24. {pyqrackising-3.4.5 → pyqrackising-3.5.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 3.4.5
3
+ Version: 3.5.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -46,18 +46,18 @@ There are two other functions, `tfim_magnetization()` and `tfim_square_magnetiza
46
46
 
47
47
  The library also provides a TFIM-inspired (approximate) MAXCUT solver:
48
48
  ```py
49
- from PyQrackIsing import maxcut_tfim
49
+ from pyqrackising import maxcut_tfim
50
50
  import networkx as nx
51
51
 
52
52
  G = nx.petersen_graph()
53
53
  best_solution_bit_string, best_cut_value, best_node_groups = maxcut_tfim(G, quality=3)
54
54
  ```
55
55
 
56
- The (integer) `quality` setting is optional, with a default value of `3`, but you can turn it up for higher-quality results, or turn it down to save time. (You can also optionally specify the number of measurement `shots` as an argument, if you want specific fine-grained control over resource usage.) If you want to run MAXCUT on a graph with non-uniform edge weights, specify them as the `weight` attribute of each edge, with `networkx`. (If any `weight` attribute is not defined, the solver assumes it's `1.0` for that edge.)
56
+ We also provide `maxcut_tfim_sparse(G)`, for `scipy` CSR sparse arrays (or `networkx` graphs). The (integer) `quality` setting is optional, with a default value of `3`, but you can turn it up for higher-quality results, or turn it down to save time. (You can also optionally specify the number of measurement `shots` as an argument, if you want specific fine-grained control over resource usage.) If you want to run MAXCUT on a graph with non-uniform edge weights, specify them as the `weight` attribute of each edge, with `networkx`. (If any `weight` attribute is not defined, the solver assumes it's `1.0` for that edge.)
57
57
 
58
58
  Based on a combination of the TFIM-inspired MAXCUT solver and another technique for finding ground-state energy in quantum chemistry that we call the _"binary Clifford eigensolver,"_ we also provide an (approximate) spin glass ground-state solver:
59
59
  ```py
60
- from PyQrackIsing import spin_glass_solver
60
+ from pyqrackising import spin_glass_solver
61
61
  import networkx as nx
62
62
  import numpy as np
63
63
 
@@ -76,11 +76,11 @@ G = generate_spin_glass_graph(n_nodes=64, seed=42)
76
76
  solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quality=3, correction_quality=2, best_guess=None)
77
77
  # solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, best_guess=maxcut_tfim(G, quality=8)[0])
78
78
  ```
79
- The (integer) `quality` setting is the same as `maxcut_tfim`. `correction_quality` controls an additional convex optimization procedure on top of `best_guess` and defaults to 4. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention.
79
+ We also provide `spin_glass_solver_sparse(G)`, for `scipy` CSR sparse arrays (or `networkx` graphs). The (integer) `quality` setting is the same as `maxcut_tfim`. `correction_quality` controls an additional convex optimization procedure on top of `best_guess` and defaults to 4. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention.
80
80
 
81
81
  From the `spin_glass_solver()`, we provide a (recursive) Traveling Salesman Problem (TSP) solver:
82
82
  ```py
83
- from PyQrackIsing import tsp_symmetric
83
+ from pyqrackising import tsp_symmetric
84
84
  import networkx as nx
85
85
  import numpy as np
86
86
 
@@ -11,7 +11,7 @@ build-backend = "setuptools.build_meta"
11
11
 
12
12
  [project]
13
13
  name = "pyqrackising"
14
- version = "3.4.5"
14
+ version = "3.5.0"
15
15
  requires-python = ">=3.8"
16
16
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
17
17
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -2,5 +2,7 @@ from .generate_tfim_samples import generate_tfim_samples
2
2
  from .tfim_magnetization import tfim_magnetization
3
3
  from .tfim_square_magnetization import tfim_square_magnetization
4
4
  from .maxcut_tfim import maxcut_tfim
5
+ from .maxcut_tfim_sparse import maxcut_tfim_sparse
5
6
  from .spin_glass_solver import spin_glass_solver
7
+ from .spin_glass_solver_sparse import spin_glass_solver_sparse
6
8
  from .tsp import tsp_symmetric, tsp_asymmetric
@@ -106,17 +106,16 @@ def maxcut_hamming_cdf(n_qubits, J_func, degrees, quality, hamming_prob):
106
106
  hamming_prob[-1] = 2.0
107
107
 
108
108
 
109
- # Written by Elara (OpenAI custom GPT)
109
+ # Written by Elara (OpenAI custom GPT) and improved by Dan Strano
110
110
  @njit
111
- def local_repulsion_choice(adjacency, degrees, weights, n, m):
111
+ def local_repulsion_choice(adjacency_data, adjacency_rows, weights, n, m):
112
112
  """
113
113
 
114
+
114
115
  Pick m nodes out of n with repulsion bias:
115
116
  - High-degree nodes are already less likely
116
117
  - After choosing a node, its neighbors' probabilities are further reduced
117
- adjacency: 2D int array (n x max_deg), padded with -1
118
-
119
- degrees: int array of shape (n,)
118
+ adjacency_data, adjacency_rows: CSR-format sparse adjacency data
120
119
  weights: float64 array of shape (n,)
121
120
  """
122
121
 
@@ -156,10 +155,8 @@ def local_repulsion_choice(adjacency, degrees, weights, n, m):
156
155
  mask[node] = True
157
156
 
158
157
  # Repulsion: penalize neighbors
159
- for j in range(degrees[node]):
160
- nbr = adjacency[node, j]
161
- if nbr < 0:
162
- break
158
+ for j in range(adjacency_rows[node], adjacency_rows[node + 1]):
159
+ nbr = adjacency_data[j]
163
160
  if available[nbr]:
164
161
  weights[nbr] *= 0.5 # tunable penalty factor
165
162
 
@@ -171,19 +168,38 @@ def compute_energy(sample, G_m, n_qubits):
171
168
  energy = 0
172
169
  for u in range(n_qubits):
173
170
  for v in range(u + 1, n_qubits):
174
- eigen = 1 if sample[u] == sample[v] else -1
175
- energy += G_m[u, v] * eigen
171
+ energy += G_m[u, v] * (1 if sample[u] == sample[v] else -1)
176
172
 
177
173
  return energy
178
174
 
179
175
 
180
176
  @njit(parallel=True)
181
- def sample_for_solution(G_m, shots, thresholds, degrees, J_eff, n):
182
- adjacency = compute_adjacency(G_m, degrees.max())
177
+ def compute_adjacency(G_m, size):
178
+ n_qubits = G_m.shape[0]
179
+ adjacency_rows = np.empty(n_qubits + 1, dtype=np.int32)
180
+ adjacency_rows[0] = 0
181
+ adjacency_data = np.full(size, -1, dtype=np.int32)
182
+ k = 0
183
+ for i in prange(n_qubits):
184
+ for j in range(n_qubits):
185
+ if (i == j) or (G_m[i, j] <= 0.0):
186
+ continue
187
+ adjacency_data[k] = j
188
+ k += 1
189
+ adjacency_rows[i + 1] = k
190
+
191
+ np.resize(adjacency_data, k)
192
+
193
+ return adjacency_data, adjacency_rows
194
+
195
+
196
+ @njit(parallel=True)
197
+ def sample_for_solution(G_m, shots, thresholds, degrees_sum, J_eff, n):
198
+ adjacency_data, adjacency_rows = compute_adjacency(G_m, degrees_sum)
183
199
  weights = 1.0 / (1.0 + (2 ** -52) - J_eff)
184
200
 
185
- best_solution = np.zeros(n, dtype=np.bool_)
186
- best_energy = compute_energy(best_solution, G_m, n)
201
+ solutions = np.empty((shots, n), dtype=np.bool_)
202
+ energies = np.empty(shots, dtype=np.float64)
187
203
 
188
204
  for s in prange(shots):
189
205
  # First dimension: Hamming weight
@@ -194,20 +210,20 @@ def sample_for_solution(G_m, shots, thresholds, degrees, J_eff, n):
194
210
  m += 1
195
211
 
196
212
  # Second dimension: permutation within Hamming weight
197
- sample = local_repulsion_choice(adjacency, degrees, weights, n, m)
213
+ sample = local_repulsion_choice(adjacency_data, adjacency_rows, weights, n, m)
198
214
 
199
- energy = compute_energy(sample, G_m, n)
200
- if energy < best_energy:
201
- best_energy = energy
202
- best_solution = sample
215
+ solutions[s] = sample
216
+ energies[s] = compute_energy(sample, G_m, n)
203
217
 
204
- best_value = 0
218
+ best_solution = solutions[np.argmin(energies)]
219
+
220
+ best_value = 0.0
205
221
  for u in range(n):
206
222
  for v in range(u + 1, n):
207
223
  if best_solution[u] != best_solution[v]:
208
224
  best_value += G_m[u, v]
209
225
 
210
- return best_solution, float(best_value)
226
+ return best_solution, best_value
211
227
 
212
228
 
213
229
  @njit
@@ -228,6 +244,7 @@ def init_J_and_z(G_m):
228
244
 
229
245
  return J_eff, degrees
230
246
 
247
+
231
248
  @njit
232
249
  def init_thresholds(n_qubits):
233
250
  n_bias = n_qubits - 1
@@ -267,21 +284,6 @@ def init_theta(delta_t, tot_t, h_mult, n_qubits, J_eff, degrees):
267
284
 
268
285
  return theta
269
286
 
270
- @njit(parallel=True)
271
- def compute_adjacency(G_m, max_degree):
272
- n_qubits = len(G_m)
273
- adjacency = np.full((n_qubits, max_degree), -1, dtype=np.int32)
274
- for i in prange(n_qubits):
275
- k = 0
276
- for j in range(n_qubits):
277
- if i == j:
278
- continue
279
- if G_m[i, j] > 0.0:
280
- adjacency[i, k] = j
281
- k += 1
282
-
283
- return adjacency
284
-
285
287
 
286
288
  def maxcut_tfim(
287
289
  G,
@@ -368,7 +370,7 @@ def maxcut_tfim(
368
370
  else:
369
371
  maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, hamming_prob)
370
372
 
371
- best_solution, best_value = sample_for_solution(G_m, shots, hamming_prob, degrees, J_eff, n_qubits)
373
+ best_solution, best_value = sample_for_solution(G_m, shots, hamming_prob, degrees.sum(), J_eff, n_qubits)
372
374
 
373
375
  bit_string = ""
374
376
  l, r = [], []
@@ -0,0 +1,391 @@
1
+ import math
2
+ import networkx as nx
3
+ import numpy as np
4
+ import os
5
+ from numba import njit, prange
6
+
7
+
8
+ IS_OPENCL_AVAILABLE = True
9
+ ctx = None
10
+ queue = None
11
+ try:
12
+ import pyopencl as cl
13
+
14
+ # Pick a device (GPU if available)
15
+ ctx = cl.create_some_context()
16
+ queue = cl.CommandQueue(ctx)
17
+
18
+ # Load and build OpenCL kernels
19
+ kernel_src = open(os.path.dirname(os.path.abspath(__file__)) + "/kernels.cl").read()
20
+ program = cl.Program(ctx, kernel_src).build()
21
+ maxcut_hamming_cdf_kernel = program.maxcut_hamming_cdf
22
+ except ImportError:
23
+ IS_OPENCL_AVAILABLE = False
24
+
25
+
26
+ @njit
27
+ def probability_by_hamming_weight(J, h, z, theta, t, n_qubits):
28
+ bias = np.empty(n_qubits - 1, dtype=np.float64)
29
+
30
+ # critical angle
31
+ theta_c = np.arcsin(max(-1.0, min(1.0, abs(h) / (z * J))))
32
+
33
+ p = (
34
+ pow(2.0, abs(J / h) - 1.0)
35
+ * (1.0 + np.sin(theta - theta_c) * np.cos(1.5 * np.pi * J * t + theta) / (1.0 + np.sqrt(t)))
36
+ - 0.5
37
+ )
38
+
39
+ if (p * n_qubits) >= 1024:
40
+ return bias
41
+
42
+ tot_n = 1.0 + 1.0 / pow(2.0, p * n_qubits)
43
+ factor = pow(2.0, -p)
44
+ n = 1.0
45
+ for q in range(1, n_qubits):
46
+ n *= factor
47
+ bias[q - 1] = n
48
+ tot_n += n
49
+ bias /= tot_n
50
+
51
+ if J > 0.0:
52
+ return bias[::-1]
53
+
54
+ return bias
55
+
56
+
57
+ @njit(parallel=True)
58
+ def maxcut_hamming_cdf(n_qubits, J_func, degrees, quality, hamming_prob):
59
+ if n_qubits < 2:
60
+ hamming_prob.fill(0.0)
61
+ return
62
+
63
+ n_steps = 1 << quality
64
+ delta_t = 1.0 / n_steps
65
+ tot_t = 2.0 * n_steps * delta_t
66
+ h_mult = 2.0 / tot_t
67
+ n_bias = n_qubits - 1
68
+
69
+ theta = np.empty(n_qubits, dtype=np.float64)
70
+ for q in range(n_qubits):
71
+ J = J_func[q]
72
+ z = degrees[q]
73
+ theta[q] = np.arcsin(
74
+ max(
75
+ -1.0,
76
+ min(
77
+ 1.0,
78
+ (1.0 if J > 0.0 else -1.0) if np.isclose(abs(z * J), 0.0) else (abs(h_mult) / (z * J)),
79
+ ),
80
+ )
81
+ )
82
+
83
+ for qc in prange(n_qubits, n_steps * n_qubits):
84
+ step = qc // n_qubits
85
+ q = qc % n_qubits
86
+ J_eff = J_func[q]
87
+ if np.isclose(abs(J_eff), 0.0):
88
+ continue
89
+ z = degrees[q]
90
+ theta_eff = theta[q]
91
+ t = step * delta_t
92
+ tm1 = (step - 1) * delta_t
93
+ h_t = h_mult * (tot_t - t)
94
+ bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, t, n_qubits)
95
+ last_bias = probability_by_hamming_weight(J_eff, h_t, z, theta_eff, tm1, n_qubits)
96
+ for i in range(n_bias):
97
+ hamming_prob[i] += bias[i] - last_bias[i]
98
+
99
+ tot_prob = hamming_prob.sum()
100
+ hamming_prob /= tot_prob
101
+
102
+ tot_prob = 0.0
103
+ for i in range(n_bias):
104
+ tot_prob += hamming_prob[i]
105
+ hamming_prob[i] = tot_prob
106
+ hamming_prob[-1] = 2.0
107
+
108
+
109
+ # Written by Elara (OpenAI custom GPT) and improved by Dan Strano
110
+ @njit
111
+ def local_repulsion_choice(adjacency_data, adjacency_rows, weights, n, m):
112
+ """
113
+
114
+ Pick m nodes out of n with repulsion bias:
115
+ - High-degree nodes are already less likely
116
+ - After choosing a node, its neighbors' probabilities are further reduced
117
+ adjacency_data, adjacency_rows: CSR-format sparse adjacency data
118
+ weights: float64 array of shape (n,)
119
+ """
120
+
121
+ weights = weights.copy()
122
+ chosen = np.zeros(m, dtype=np.int32) # store chosen indices
123
+ available = np.ones(n, dtype=np.bool_) # True = available, False = not
124
+ mask = np.zeros(n, dtype=np.bool_)
125
+ chosen_count = 0
126
+
127
+ for _ in range(m):
128
+ # Count available
129
+ total_w = 0.0
130
+ for i in range(n):
131
+ if available[i]:
132
+ total_w += weights[i]
133
+ if total_w <= 0:
134
+ break
135
+
136
+ # Normalize & sample
137
+ r = np.random.rand()
138
+ cum = 0.0
139
+ node = -1
140
+ for i in range(n):
141
+ if available[i]:
142
+ cum += weights[i] / total_w
143
+ if r < cum:
144
+ node = i
145
+ break
146
+
147
+ if node == -1:
148
+ continue
149
+
150
+ # Select node
151
+ chosen[chosen_count] = node
152
+ chosen_count += 1
153
+ available[node] = False
154
+ mask[node] = True
155
+
156
+ # Repulsion: penalize neighbors
157
+ for j in range(adjacency_rows[node], adjacency_rows[node + 1]):
158
+ nbr = adjacency_data[j]
159
+ if available[nbr]:
160
+ weights[nbr] *= 0.5 # tunable penalty factor
161
+
162
+ return mask
163
+
164
+
165
+ @njit
166
+ def compute_energy(sample, G_data, G_rows, G_cols):
167
+ n_qubits = G_rows.shape[0] - 1
168
+ energy = 0
169
+ for u in range(n_qubits):
170
+ for col in range(G_rows[u], G_rows[u + 1]):
171
+ v = G_cols[col]
172
+ if v < (u + 1):
173
+ continue
174
+ energy += G_data[col] * (1 if sample[u] == sample[v] else -1)
175
+
176
+ return energy
177
+
178
+
179
+ @njit(parallel=True)
180
+ def compute_adjacency(G_data, G_rows, G_cols):
181
+ n_qubits = G_rows.shape[0] - 1
182
+ adjacency_rows = np.empty(n_qubits + 1, dtype=np.int32)
183
+ adjacency_rows[0] = 0
184
+ adjacency_data = np.full(G_data.shape[0], -1, dtype=np.int32)
185
+ k = 0
186
+ for i in prange(n_qubits):
187
+ for j in range(G_rows[i], G_rows[i + 1]):
188
+ if G_data[j] > 0.0:
189
+ adjacency_data[k] = G_cols[j]
190
+ k += 1
191
+ adjacency_rows[i + 1] = k
192
+
193
+ np.resize(adjacency_data, k)
194
+
195
+ return adjacency_data, adjacency_rows
196
+
197
+
198
+ @njit(parallel=True)
199
+ def sample_for_solution(G_data, G_rows, G_cols, shots, thresholds, J_eff):
200
+ n = G_rows.shape[0] - 1
201
+ adjacency_data, adjacency_rows = compute_adjacency(G_data, G_rows, G_cols)
202
+ weights = 1.0 / (1.0 + (2 ** -52) - J_eff)
203
+
204
+ solutions = np.empty((shots, n), dtype=np.bool_)
205
+ energies = np.empty(shots, dtype=np.float64)
206
+
207
+ for s in prange(shots):
208
+ # First dimension: Hamming weight
209
+ mag_prob = np.random.random()
210
+ m = 0
211
+ while thresholds[m] < mag_prob:
212
+ m += 1
213
+ m += 1
214
+
215
+ # Second dimension: permutation within Hamming weight
216
+ sample = local_repulsion_choice(adjacency_data, adjacency_rows, weights, n, m)
217
+ solutions[s] = sample
218
+ energies[s] = compute_energy(sample, G_data, G_rows, G_cols)
219
+
220
+ best_solution = solutions[np.argmin(energies)]
221
+
222
+ best_value = 0.0
223
+ for u in range(n):
224
+ for col in range(G_rows[u], G_rows[u + 1]):
225
+ v = G_cols[col]
226
+ if v < (u + 1):
227
+ continue
228
+ if best_solution[u] != best_solution[v]:
229
+ best_value += G_data[col]
230
+
231
+ return best_solution, best_value
232
+
233
+
234
+ @njit
235
+ def init_J_and_z(G_data, G_rows, G_cols):
236
+ n_qubits = G_rows.shape[0] - 1
237
+ degrees = np.empty(n_qubits, dtype=np.uint32)
238
+ J_eff = np.empty(n_qubits, dtype=np.float64)
239
+ J_max = -float("inf")
240
+ for n in range(n_qubits):
241
+ start = G_rows[n]
242
+ end = G_rows[n + 1]
243
+ degree = end - start
244
+ J = -np.mean(G_data[start:end]) / degree if degree > 0 else 0
245
+ degrees[n] = degree
246
+ J_eff[n] = J
247
+ J_abs = abs(J)
248
+ if J_abs > J_max:
249
+ J_max = J_abs
250
+ J_eff /= J_max
251
+
252
+ return J_eff, degrees
253
+
254
+ @njit
255
+ def init_thresholds(n_qubits):
256
+ n_bias = n_qubits - 1
257
+ thresholds = np.empty(n_bias, dtype=np.float64)
258
+ tot_prob = 0
259
+ p = 1.0
260
+ if n_qubits & 1:
261
+ q = n_qubits // 2
262
+ thresholds[q - 1] = p
263
+ tot_prob = p
264
+ p /= 2
265
+ for q in range(1, n_qubits // 2):
266
+ thresholds[q - 1] = p
267
+ thresholds[n_bias - q] = p
268
+ tot_prob += 2 * p
269
+ p /= 2
270
+ thresholds /= tot_prob
271
+
272
+ return thresholds
273
+
274
+
275
+ @njit
276
+ def init_theta(delta_t, tot_t, h_mult, n_qubits, J_eff, degrees):
277
+ theta = np.empty(n_qubits, dtype=np.float64)
278
+ for q in range(n_qubits):
279
+ J = J_eff[q]
280
+ z = degrees[q]
281
+ theta[q] = np.arcsin(
282
+ max(
283
+ -1.0,
284
+ min(
285
+ 1.0,
286
+ (1.0 if J > 0.0 else -1.0) if np.isclose(abs(z * J), 0.0) else (abs(h_mult) / (z * J)),
287
+ ),
288
+ )
289
+ )
290
+
291
+ return theta
292
+
293
+
294
+ def maxcut_tfim_sparse(
295
+ G,
296
+ quality=None,
297
+ shots=None,
298
+ ):
299
+ nodes = None
300
+ n_qubits = 0
301
+ G_m = None
302
+ if isinstance(G, nx.Graph):
303
+ nodes = list(G.nodes())
304
+ n_qubits = len(nodes)
305
+ G_m = nx.to_scipy_sparse_array(G, weight='weight')
306
+ else:
307
+ n_qubits = G.shape[0]
308
+ nodes = list(range(n_qubits))
309
+ G_m = G
310
+
311
+ if n_qubits == 0:
312
+ return "", 0, ([], [])
313
+
314
+ if n_qubits == 1:
315
+ return "0", 0, (nodes, [])
316
+
317
+ if n_qubits == 2:
318
+ weight = G_m[0, 1]
319
+ if weight < 0.0:
320
+ return "00", 0, (nodes, [])
321
+
322
+ return "01", weight, ([nodes[0]], [nodes[1]])
323
+
324
+ if quality is None:
325
+ quality = 8
326
+
327
+ if shots is None:
328
+ # Number of measurement shots
329
+ shots = n_qubits << quality
330
+
331
+ n_steps = 1 << quality
332
+ grid_size = n_steps * n_qubits
333
+
334
+ J_eff, degrees = init_J_and_z(G_m.data, G_m.indptr, G_m.indices)
335
+ hamming_prob = init_thresholds(n_qubits)
336
+
337
+ if IS_OPENCL_AVAILABLE and grid_size >= 128:
338
+ delta_t = 1.0 / n_steps
339
+ tot_t = 2.0 * n_steps * delta_t
340
+ h_mult = 2.0 / tot_t
341
+ theta = init_theta(delta_t, tot_t, h_mult, n_qubits, J_eff, degrees)
342
+ args = np.empty(3, dtype=np.float32)
343
+ args[0] = delta_t
344
+ args[1] = tot_t
345
+ args[2] = h_mult
346
+
347
+ # Warp size is 32:
348
+ group_size = n_qubits - 1
349
+ if group_size > 256:
350
+ group_size = 256
351
+ grid_dim = n_steps * n_qubits * group_size
352
+
353
+ # Move to GPU
354
+ mf = cl.mem_flags
355
+ args_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=args)
356
+ J_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=J_eff)
357
+ deg_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=degrees)
358
+ theta_buf = cl.Buffer(ctx, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=theta)
359
+ ham_buf = cl.Buffer(ctx, mf.READ_WRITE | mf.COPY_HOST_PTR, hostbuf=hamming_prob)
360
+
361
+ # Kernel execution
362
+ maxcut_hamming_cdf_kernel(
363
+ queue, (grid_dim,), (group_size,),
364
+ np.int32(n_qubits), deg_buf, args_buf, J_buf, theta_buf, ham_buf
365
+ )
366
+
367
+ # Fetch results
368
+ cl.enqueue_copy(queue, hamming_prob, ham_buf)
369
+
370
+ hamming_prob /= hamming_prob.sum()
371
+ tot_prob = 0.0
372
+ for i in range(n_qubits - 1):
373
+ tot_prob += hamming_prob[i]
374
+ hamming_prob[i] = tot_prob
375
+ hamming_prob[-1] = 2.0
376
+ else:
377
+ maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, hamming_prob)
378
+
379
+ best_solution, best_value = sample_for_solution(G_m.data, G_m.indptr, G_m.indices, shots, hamming_prob, J_eff)
380
+
381
+ bit_string = ""
382
+ l, r = [], []
383
+ for i in range(len(best_solution)):
384
+ if best_solution[i]:
385
+ bit_string += "1"
386
+ r.append(nodes[i])
387
+ else:
388
+ bit_string += "0"
389
+ l.append(nodes[i])
390
+
391
+ return bit_string, best_value, (l, r)
@@ -0,0 +1,144 @@
1
+ from .maxcut_tfim_sparse import maxcut_tfim_sparse
2
+ import itertools
3
+ import networkx as nx
4
+ import numpy as np
5
+ from numba import njit, prange
6
+ import os
7
+
8
+
9
+ @njit
10
+ def evaluate_cut_edges(theta_bits, G_data, G_rows, G_cols):
11
+ n = G_rows.shape[0] - 1
12
+ cut = 0.0
13
+ for u in range(n):
14
+ for col in range(G_rows[u], G_rows[u + 1]):
15
+ v = G_cols[col]
16
+ if v < (u + 1):
17
+ continue
18
+ if theta_bits[u] != theta_bits[v]:
19
+ cut += G_data[col]
20
+
21
+ return cut
22
+
23
+
24
+ @njit
25
+ def compute_energy(sample, G_data, G_rows, G_cols):
26
+ n_qubits = G_rows.shape[0] - 1
27
+ energy = 0
28
+ for u in range(n_qubits):
29
+ for col in range(G_rows[u], G_rows[u + 1]):
30
+ v = G_cols[col]
31
+ if v < (u + 1):
32
+ continue
33
+ energy += G_data[col] * (1 if sample[u] == sample[v] else -1)
34
+
35
+ return energy
36
+
37
+
38
+ @njit
39
+ def bootstrap_worker(theta, G_data, G_rows, G_cols, indices):
40
+ local_theta = theta.copy()
41
+ for i in indices:
42
+ local_theta[i] = not local_theta[i]
43
+ energy = compute_energy(local_theta, G_data, G_rows, G_cols)
44
+
45
+ return energy
46
+
47
+
48
+ @njit(parallel=True)
49
+ def bootstrap(theta, G_data, G_rows, G_cols, k, indices_array):
50
+ n = len(indices_array) // k
51
+ energies = np.empty(n, dtype=np.float64)
52
+ for i in prange(n):
53
+ j = i * k
54
+ energies[i] = bootstrap_worker(theta, G_data, G_rows, G_cols, indices_array[j : j + k])
55
+
56
+ return energies
57
+
58
+
59
+ # By Gemini (Google Search AI)
60
+ def int_to_bitstring(integer, length):
61
+ return (bin(integer)[2:].zfill(length))[::-1]
62
+
63
+
64
+ def spin_glass_solver_sparse(G, quality=None, shots=None, correction_quality=None, best_guess=None):
65
+ nodes = None
66
+ n_qubits = 0
67
+ G_m = None
68
+ if isinstance(G, nx.Graph):
69
+ nodes = list(G.nodes())
70
+ n_qubits = len(nodes)
71
+ G_m = nx.to_scipy_sparse_array(G, weight='weight')
72
+ else:
73
+ n_qubits = G.shape[0]
74
+ nodes = list(range(n_qubits))
75
+ G_m = G
76
+
77
+ if n_qubits == 0:
78
+ return "", 0, ([], []), 0
79
+
80
+ if n_qubits == 1:
81
+ return "0", 0, (nodes, []), 0
82
+
83
+ if n_qubits == 2:
84
+ weight = G_m[0, 1]
85
+ if weight < 0.0:
86
+ return "00", 0, (nodes, []), weight
87
+
88
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
89
+
90
+ if correction_quality is None:
91
+ correction_quality = 2
92
+
93
+ bitstring = ""
94
+ if isinstance(best_guess, str):
95
+ bitstring = best_guess
96
+ elif isinstance(best_guess, int):
97
+ bitstring = int_to_bitstring(best_guess, n_qubits)
98
+ elif isinstance(best_guess, list):
99
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
100
+ else:
101
+ bitstring, _, _ = maxcut_tfim_sparse(G_m, quality=quality, shots=shots)
102
+ best_theta = [b == "1" for b in list(bitstring)]
103
+
104
+
105
+
106
+ min_energy = compute_energy(best_theta, G_m.data, G_m.indptr, G_m.indices)
107
+ improved = True
108
+ while improved:
109
+ improved = False
110
+ for k in range(1, max(1, correction_quality + 1)):
111
+ if n_qubits < k:
112
+ break
113
+
114
+ theta = best_theta.copy()
115
+
116
+ combos = list(
117
+ item for sublist in itertools.combinations(range(n_qubits), k) for item in sublist
118
+ )
119
+ energies = bootstrap(theta, G_m.data, G_m.indptr, G_m.indices, k, combos)
120
+
121
+ energy = energies.min()
122
+ if energy < min_energy:
123
+ index_match = np.random.choice(np.where(energies == energy)[0])
124
+ indices = combos[(index_match * k) : ((index_match + 1) * k)]
125
+ min_energy = energy
126
+ for i in indices:
127
+ best_theta[i] = not best_theta[i]
128
+ improved = True
129
+ break
130
+
131
+ bitstring = ""
132
+ l, r = [], []
133
+ for i in range(len(best_theta)):
134
+ b = best_theta[i]
135
+ if b:
136
+ bitstring += "1"
137
+ r.append(nodes[i])
138
+ else:
139
+ bitstring += "0"
140
+ l.append(nodes[i])
141
+
142
+ cut_value = evaluate_cut_edges(best_theta, G_m.data, G_m.indptr, G_m.indices)
143
+
144
+ return bitstring, float(cut_value), (l, r), float(min_energy)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 3.4.5
3
+ Version: 3.5.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -9,7 +9,9 @@ pyqrackising/_pyqrack_ising.cpp
9
9
  pyqrackising/generate_tfim_samples.py
10
10
  pyqrackising/kernels.cl
11
11
  pyqrackising/maxcut_tfim.py
12
+ pyqrackising/maxcut_tfim_sparse.py
12
13
  pyqrackising/spin_glass_solver.py
14
+ pyqrackising/spin_glass_solver_sparse.py
13
15
  pyqrackising/tfim_magnetization.py
14
16
  pyqrackising/tfim_square_magnetization.py
15
17
  pyqrackising/tsp.py
@@ -51,7 +51,7 @@ ext_modules = [CMakeExtension('tfim_sampler')]
51
51
 
52
52
  setup(
53
53
  name='pyqrackising',
54
- version='3.4.5',
54
+ version='3.5.0',
55
55
  author='Dan Strano',
56
56
  author_email='stranoj@gmail.com',
57
57
  description='Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)',
File without changes
File without changes
File without changes