PyQrackIsing 9.12.0__tar.gz → 9.12.1__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 (33) hide show
  1. {pyqrackising-9.12.0/pyqrackising.egg-info → pyqrackising-9.12.1}/PKG-INFO +1 -1
  2. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyproject.toml +1 -1
  3. pyqrackising-9.12.1/pyqrackising/solve_maxcut_exact.py +355 -0
  4. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/solve_maxcut_exact_sparse.py +125 -221
  5. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/solve_maxcut_exact_streaming.py +103 -196
  6. {pyqrackising-9.12.0 → pyqrackising-9.12.1/pyqrackising.egg-info}/PKG-INFO +1 -1
  7. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/setup.py +1 -1
  8. pyqrackising-9.12.0/pyqrackising/solve_maxcut_exact.py +0 -484
  9. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/LICENSE.md +0 -0
  10. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/MANIFEST.in +0 -0
  11. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/README.md +0 -0
  12. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/__init__.py +0 -0
  13. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  14. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/generate_tfim_samples.py +0 -0
  15. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/kernels.cl +0 -0
  16. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim.py +0 -0
  17. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  18. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  19. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_util.py +0 -0
  20. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/otoc.py +0 -0
  21. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver.py +0 -0
  22. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  23. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  24. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/tfim_magnetization.py +0 -0
  25. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/tfim_square_magnetization.py +0 -0
  26. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/tsp.py +0 -0
  27. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising/tsp_maxcut.py +0 -0
  28. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising.egg-info/SOURCES.txt +0 -0
  29. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising.egg-info/dependency_links.txt +0 -0
  30. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising.egg-info/not-zip-safe +0 -0
  31. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising.egg-info/requires.txt +0 -0
  32. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/pyqrackising.egg-info/top_level.txt +0 -0
  33. {pyqrackising-9.12.0 → pyqrackising-9.12.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.12.0
3
+ Version: 9.12.1
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
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "pyqrackising"
10
- version = "9.12.0"
10
+ version = "9.12.1"
11
11
  requires-python = ">=3.8"
12
12
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
13
13
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -0,0 +1,355 @@
1
+ # SPDX-License-Identifier: LGPL-3.0-or-later
2
+ # Copyright (C) 2026 Daniel Strano and the Qrack contributors
3
+ #
4
+ # Initial draft produced by (Anthropic) Claude (Sonnet 4.6).
5
+ #
6
+ # bnb_exact.py — warm-start branch-and-bound exact MAXCUT solver (dense)
7
+ #
8
+ # Objective convention (matches PyQrackIsing throughout):
9
+ # Maximise sum_{(i,j) in cut} w_{ij}
10
+ # i.e. edge (i,j) contributes w_{ij} when bits[i] != bits[j].
11
+ # Edge weights may be positive or negative; no diagonal / self-loops.
12
+ #
13
+ # Upper bound per B&B node: LP relaxation of the MAXCUT objective.
14
+ # Linearisation: introduce y_ij = x_i * x_j for each free edge pair;
15
+ # edge contribution becomes w_{ij} * (x_i + x_j - 2*y_ij).
16
+ # Constraints: y_ij <= x_i, y_ij <= x_j, x_i + x_j - y_ij <= 1.
17
+ # Users may swap in a tighter SDP bound by replacing _lp_upper_bound.
18
+
19
+ import time
20
+ import networkx as nx
21
+ import numpy as np
22
+ from numba import njit, prange
23
+ from .maxcut_tfim_util import (
24
+ compute_cut,
25
+ compute_energy,
26
+ get_cut,
27
+ heuristic_threshold,
28
+ int_to_bitstring,
29
+ opencl_context,
30
+ )
31
+
32
+ try:
33
+ from scipy.optimize import linprog
34
+ _HAVE_SCIPY = True
35
+ except ImportError:
36
+ _HAVE_SCIPY = False
37
+
38
+
39
+ dtype = opencl_context.dtype
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Numba-compiled inner loops
44
+ # ---------------------------------------------------------------------------
45
+
46
+ @njit(cache=True)
47
+ def _fixed_fixed(G_m, fixed_idx, fixed_val):
48
+ total = 0.0
49
+ nf = len(fixed_idx)
50
+ for a in range(nf):
51
+ i = fixed_idx[a]
52
+ fi = fixed_val[a]
53
+ for b in range(a + 1, nf):
54
+ j = fixed_idx[b]
55
+ fj = fixed_val[b]
56
+ ii, jj = (i, j) if i < j else (j, i)
57
+ if G_m[ii, jj] != 0.0 and fi != fj:
58
+ total += G_m[ii, jj]
59
+ return total
60
+
61
+
62
+ @njit(cache=True)
63
+ def _fixed_free_linear(G_m, free_arr, fixed_idx, fixed_val):
64
+ n_free = len(free_arr)
65
+ nf = len(fixed_idx)
66
+ coeff = np.zeros(n_free)
67
+ const = 0.0
68
+ for k in range(n_free):
69
+ i = free_arr[k]
70
+ for a in range(nf):
71
+ j = fixed_idx[a]
72
+ fval = fixed_val[a]
73
+ ii, jj = (i, j) if i < j else (j, i)
74
+ w = G_m[ii, jj]
75
+ if w == 0.0:
76
+ continue
77
+ const += w * fval
78
+ coeff[k] += w * (1.0 - 2.0 * fval)
79
+ return const, coeff
80
+
81
+
82
+ @njit(cache=True)
83
+ def _influence_scores(G_m, free_arr):
84
+ n_free = len(free_arr)
85
+ scores = np.zeros(n_free)
86
+ for k in range(n_free):
87
+ i = free_arr[k]
88
+ for m in range(n_free):
89
+ if k == m:
90
+ continue
91
+ j = free_arr[m]
92
+ ii, jj = (i, j) if i < j else (j, i)
93
+ scores[k] += abs(G_m[ii, jj])
94
+ return scores
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # LP upper bound
99
+ # ---------------------------------------------------------------------------
100
+
101
+ def _lp_upper_bound(G_m, free_arr, fixed_idx, fixed_val, n):
102
+ ff = _fixed_fixed(G_m, fixed_idx, fixed_val)
103
+ n_free = len(free_arr)
104
+
105
+ if n_free == 0:
106
+ return ff
107
+
108
+ ff_const, coeff = _fixed_free_linear(G_m, free_arr, fixed_idx, fixed_val)
109
+
110
+ if not _HAVE_SCIPY:
111
+ bound = ff + ff_const
112
+ for k in range(n_free):
113
+ bound += max(0.0, coeff[k])
114
+ for a in range(n_free):
115
+ i = free_arr[a]
116
+ for b in range(a + 1, n_free):
117
+ j = free_arr[b]
118
+ bound += max(0.0, G_m[i, j])
119
+ return bound
120
+
121
+ pairs = [(free_arr[a], free_arr[b])
122
+ for a in range(n_free) for b in range(a + 1, n_free)
123
+ if G_m[free_arr[a], free_arr[b]] != 0.0]
124
+ n_pairs = len(pairs)
125
+ total_vars = n_free + n_pairs
126
+ free_idx_map = {int(v): k for k, v in enumerate(free_arr)}
127
+
128
+ c = np.zeros(total_vars)
129
+ for k in range(n_free):
130
+ c[k] = -coeff[k]
131
+ for p, (i, j) in enumerate(pairs):
132
+ w = G_m[i, j]
133
+ c[free_idx_map[i]] -= w
134
+ c[free_idx_map[j]] -= w
135
+ c[n_free + p] += 2.0 * w
136
+
137
+ bounds = [(0.0, 1.0)] * total_vars
138
+
139
+ if not pairs:
140
+ lp_val = sum(-c[k] if c[k] < 0.0 else 0.0 for k in range(n_free))
141
+ return ff + ff_const + lp_val
142
+
143
+ rows = 3 * n_pairs
144
+ A = np.zeros((rows, total_vars))
145
+ b_ub = np.empty(rows)
146
+ for p, (i, j) in enumerate(pairs):
147
+ ki, kj = free_idx_map[i], free_idx_map[j]
148
+ r = 3 * p
149
+ A[r, ki] = -1.0; A[r, n_free + p] = 1.0; b_ub[r] = 0.0
150
+ A[r+1, kj] = -1.0; A[r+1, n_free + p] = 1.0; b_ub[r+1] = 0.0
151
+ A[r+2, ki] = 1.0; A[r+2, kj] = 1.0
152
+ A[r+2, n_free + p] = -1.0; b_ub[r+2] = 1.0
153
+
154
+ res = linprog(c, A_ub=A, b_ub=b_ub, bounds=bounds,
155
+ method="highs", options={"disp": False})
156
+
157
+ return (ff + ff_const + (-res.fun)) if res.success else float("inf")
158
+
159
+
160
+ # ---------------------------------------------------------------------------
161
+ # Branch and bound (internal)
162
+ # ---------------------------------------------------------------------------
163
+
164
+ def _branch_and_bound(G_m, warm_theta, warm_energy, n, is_spin_glass,
165
+ verbose=True, time_limit=None):
166
+ best_bits = warm_theta.copy()
167
+ best_value = warm_energy
168
+
169
+ if verbose:
170
+ print(f"Warm-start incumbent: {best_value:.6f}")
171
+
172
+ t_start = time.monotonic()
173
+ nodes_explored = 0
174
+ nodes_pruned = 0
175
+
176
+ stack = [(np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64))]
177
+
178
+ while stack:
179
+ if time_limit is not None and (time.monotonic() - t_start) > time_limit:
180
+ if verbose:
181
+ print(f"Time limit reached. "
182
+ f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
183
+ return best_bits, best_value, False
184
+
185
+ fixed_idx, fixed_val = stack.pop()
186
+ nodes_explored += 1
187
+
188
+ fixed_set = set(int(fixed_idx[k]) for k in range(len(fixed_idx)))
189
+ free_arr = np.array([i for i in range(n) if i not in fixed_set],
190
+ dtype=np.int64)
191
+
192
+ ub = _lp_upper_bound(G_m, free_arr, fixed_idx, fixed_val, n)
193
+
194
+ if ub <= best_value + 1e-9:
195
+ nodes_pruned += 1
196
+ continue
197
+
198
+ if len(free_arr) == 0:
199
+ bits = np.zeros(n, dtype=np.bool_)
200
+ for k in range(len(fixed_idx)):
201
+ bits[fixed_idx[k]] = bool(fixed_val[k])
202
+ val = float(
203
+ compute_energy(bits, G_m, n) if is_spin_glass
204
+ else compute_cut(bits, G_m, n)
205
+ )
206
+ if val > best_value:
207
+ best_value = val
208
+ best_bits = bits.copy()
209
+ if verbose:
210
+ print(f" New incumbent: {best_value:.6f}"
211
+ f" (nodes: {nodes_explored})")
212
+ continue
213
+
214
+ scores = _influence_scores(G_m, free_arr)
215
+ branch_var = int(free_arr[int(np.argmax(scores))])
216
+
217
+ warm_val = int(best_bits[branch_var])
218
+ for val in [warm_val, 1 - warm_val]:
219
+ stack.append((
220
+ np.append(fixed_idx, branch_var).astype(np.int64),
221
+ np.append(fixed_val, val).astype(np.int64),
222
+ ))
223
+
224
+ elapsed = time.monotonic() - t_start
225
+ if verbose:
226
+ print(f"\nExact optimum: {best_value:.6f}")
227
+ print(f"Nodes explored: {nodes_explored} | "
228
+ f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
229
+
230
+ return best_bits, best_value, True
231
+
232
+
233
+ # ---------------------------------------------------------------------------
234
+ # Public API
235
+ # ---------------------------------------------------------------------------
236
+
237
+ def solve_maxcut_exact(
238
+ G,
239
+ best_guess=None,
240
+ quality=None,
241
+ shots=None,
242
+ is_spin_glass=False,
243
+ anneal_t=None,
244
+ anneal_h=None,
245
+ repulsion_base=None,
246
+ is_maxcut_gpu=True,
247
+ verbose=True,
248
+ time_limit=None,
249
+ gray_iterations=None,
250
+ gray_seed_multiple=None,
251
+ ):
252
+ """
253
+ Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver then
254
+ certify via branch and bound.
255
+
256
+ Accepts the same G input as spin_glass_solver (NetworkX graph or dense
257
+ matrix) and the same warm-start formats (str, int, list, or None).
258
+
259
+ Parameters
260
+ ----------
261
+ G : networkx.Graph or ndarray
262
+ Graph or pre-built dense adjacency matrix.
263
+ best_guess : str | int | list[bool] | None
264
+ Warm-start hint in any PyQrackIsing-compatible format. If None,
265
+ spin_glass_solver is called to produce one.
266
+ quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
267
+ is_spin_glass, gray_iterations, gray_seed_multiple
268
+ Forwarded to spin_glass_solver when best_guess is None.
269
+ verbose : bool
270
+ time_limit : float or None
271
+ Wall-clock seconds for the B&B phase.
272
+
273
+ Returns
274
+ -------
275
+ bitstring : str
276
+ cut_value : float
277
+ partition : tuple(list, list)
278
+ min_energy : float
279
+ certified : bool
280
+ """
281
+ # Mirror spin_glass_solver's G -> G_m conversion exactly
282
+ if isinstance(G, nx.Graph):
283
+ nodes = list(G.nodes())
284
+ n_qubits = len(nodes)
285
+ G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
286
+ else:
287
+ n_qubits = len(G)
288
+ nodes = list(range(n_qubits))
289
+ G_m = np.asarray(G, dtype=dtype)
290
+
291
+ if n_qubits < 3:
292
+ if n_qubits == 0:
293
+ return "", 0, ([], []), 0, True
294
+ if n_qubits == 1:
295
+ return "0", 0, (nodes, []), 0, True
296
+ if n_qubits == 2:
297
+ weight = G_m[0, 1]
298
+ if weight < 0.0:
299
+ return "00", 0, (nodes, []), weight, True
300
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
301
+
302
+ # Warm-start parser — mirrors spin_glass_solver exactly
303
+ bitstring = ""
304
+ cut_value = 0.0
305
+ if isinstance(best_guess, str):
306
+ bitstring = best_guess
307
+ elif isinstance(best_guess, int):
308
+ bitstring = int_to_bitstring(best_guess, n_qubits)
309
+ elif isinstance(best_guess, list):
310
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
311
+ else:
312
+ if verbose:
313
+ print("Running PyQrackIsing heuristic...")
314
+ from .spin_glass_solver import spin_glass_solver
315
+ kwargs = {}
316
+ if quality is not None: kwargs["quality"] = quality
317
+ if shots is not None: kwargs["shots"] = shots
318
+ if anneal_t is not None: kwargs["anneal_t"] = anneal_t
319
+ if anneal_h is not None: kwargs["anneal_h"] = anneal_h
320
+ if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
321
+ if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
322
+ if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
323
+ kwargs["is_maxcut_gpu"] = is_maxcut_gpu
324
+ t0 = time.monotonic()
325
+ bitstring, cut_value, _, _ = spin_glass_solver(
326
+ G_m, is_spin_glass=is_spin_glass, **kwargs
327
+ )
328
+ if verbose:
329
+ print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
330
+
331
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
332
+ if is_spin_glass:
333
+ max_energy = compute_energy(best_theta, G_m, n_qubits)
334
+ elif cut_value is None:
335
+ max_energy = compute_cut(best_theta, G_m, n_qubits)
336
+ else:
337
+ max_energy = cut_value
338
+
339
+ if verbose:
340
+ print("Starting branch and bound...")
341
+
342
+ best_theta, max_energy, certified = _branch_and_bound(
343
+ G_m, best_theta, max_energy, n_qubits, is_spin_glass,
344
+ verbose=verbose, time_limit=time_limit,
345
+ )
346
+
347
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
348
+ if is_spin_glass:
349
+ cut_value = compute_cut(best_theta, G_m, n_qubits)
350
+ min_energy = -max_energy
351
+ else:
352
+ cut_value = max_energy
353
+ min_energy = compute_energy(best_theta, G_m, n_qubits)
354
+
355
+ return bitstring, float(cut_value), (l, r), float(min_energy), certified