PyQrackIsing 9.11.4__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 (32) hide show
  1. {pyqrackising-9.11.4/pyqrackising.egg-info → pyqrackising-9.12.1}/PKG-INFO +1 -1
  2. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/README.md +11 -0
  3. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyproject.toml +1 -1
  4. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/__init__.py +3 -0
  5. pyqrackising-9.12.1/pyqrackising/solve_maxcut_exact.py +355 -0
  6. pyqrackising-9.12.1/pyqrackising/solve_maxcut_exact_sparse.py +404 -0
  7. pyqrackising-9.12.1/pyqrackising/solve_maxcut_exact_streaming.py +356 -0
  8. {pyqrackising-9.11.4 → pyqrackising-9.12.1/pyqrackising.egg-info}/PKG-INFO +1 -1
  9. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising.egg-info/SOURCES.txt +3 -0
  10. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/setup.py +1 -1
  11. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/LICENSE.md +0 -0
  12. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/MANIFEST.in +0 -0
  13. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  14. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/generate_tfim_samples.py +0 -0
  15. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/kernels.cl +0 -0
  16. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim.py +0 -0
  17. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  18. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  19. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/maxcut_tfim_util.py +0 -0
  20. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/otoc.py +0 -0
  21. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver.py +0 -0
  22. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  23. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  24. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/tfim_magnetization.py +0 -0
  25. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/tfim_square_magnetization.py +0 -0
  26. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/tsp.py +0 -0
  27. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising/tsp_maxcut.py +0 -0
  28. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising.egg-info/dependency_links.txt +0 -0
  29. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising.egg-info/not-zip-safe +0 -0
  30. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising.egg-info/requires.txt +0 -0
  31. {pyqrackising-9.11.4 → pyqrackising-9.12.1}/pyqrackising.egg-info/top_level.txt +0 -0
  32. {pyqrackising-9.11.4 → 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.11.4
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
@@ -78,6 +78,17 @@ solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quali
78
78
  ```
79
79
  We also provide `spin_glass_solver_sparse(G)` and `spin_glass_solver_streaming(G_func, nodes)`. `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. `is_spin_glass` controls whether the solver optimizes for cut value or spin-glass energy. 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. `gray_iterations` gives manual control over how many iterations are carried out of a parallel Gray-code search on `best_guess`. `gray_seed_multiple` controls how many parallel search seeds (as a multiple of your CPU thread count) are tested for the best parallel seeds, and a value of `1` will perfectly cover the search space without collision if your node count is a power of 2.
80
80
 
81
+ These solvers above can be used as a "warm state" for _branch and bound,_ potentially to reach _exact_ solutions to MAXCUT:
82
+
83
+ ```py
84
+ from pyqrackising import solve_maxcut_exact, solve_maxcut_exact_sparse, solve_maxcut_exact_streaming
85
+ import networkx as nx
86
+
87
+ G = nx.petersen_graph()
88
+ best_solution_bit_string, best_cut_value, best_node_groups = solve_maxcut_exact(G, time_limit=None)
89
+ ```
90
+ Pass a time limit (in seconds) if desired.
91
+
81
92
  From the MAXCUT solvers, we provide a (recursive) Traveling Salesman Problem (TSP) solver:
82
93
  ```py
83
94
  from pyqrackising import tsp_symmetric
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "pyqrackising"
10
- version = "9.11.4"
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"}
@@ -12,3 +12,6 @@ from .spin_glass_solver_streaming import spin_glass_solver_streaming
12
12
  from .tsp import tsp_symmetric, tsp_asymmetric
13
13
  from .tsp_maxcut import tsp_maxcut, tsp_maxcut_sparse, tsp_maxcut_streaming
14
14
  from .convert_tensor_network_to_tsp import convert_tensor_network_to_tsp, convert_quimb_tree_to_tsp
15
+ from .solve_maxcut_exact import solve_maxcut_exact
16
+ from .solve_maxcut_exact_sparse import solve_maxcut_exact_sparse
17
+ from .solve_maxcut_exact_streaming import solve_maxcut_exact_streaming
@@ -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
@@ -0,0 +1,404 @@
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_sparse.py — warm-start branch-and-bound exact MAXCUT solver (sparse)
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_sparse,
25
+ compute_energy_sparse,
26
+ get_cut,
27
+ heuristic_threshold_sparse,
28
+ int_to_bitstring,
29
+ opencl_context,
30
+ to_scipy_sparse_upper_triangular,
31
+ )
32
+
33
+ try:
34
+ from scipy.optimize import linprog
35
+ _HAVE_SCIPY = True
36
+ except ImportError:
37
+ _HAVE_SCIPY = False
38
+
39
+
40
+ dtype = opencl_context.dtype
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Numba-compiled inner loops (sparse CSR)
45
+ # ---------------------------------------------------------------------------
46
+
47
+ @njit(cache=True)
48
+ def _fixed_fixed_sparse(G_data, G_rows, G_cols, fixed_idx, fixed_val):
49
+ total = 0.0
50
+ nf = len(fixed_idx)
51
+ n = G_rows.shape[0] - 1
52
+ fixed_pos = np.full(n, -1, dtype=np.int64)
53
+ for a in range(nf):
54
+ fixed_pos[fixed_idx[a]] = a
55
+ for a in range(nf):
56
+ i = fixed_idx[a]
57
+ fi = fixed_val[a]
58
+ for r in range(G_rows[i], G_rows[i + 1]):
59
+ j = G_cols[r]
60
+ b = fixed_pos[j]
61
+ if b >= 0 and j > i and fi != fixed_val[b]:
62
+ total += G_data[r]
63
+ return total
64
+
65
+
66
+ @njit(cache=True)
67
+ def _fixed_free_linear_sparse(G_data, G_rows, G_cols, free_arr, fixed_idx, fixed_val):
68
+ n_free = len(free_arr)
69
+ nf = len(fixed_idx)
70
+ n = G_rows.shape[0] - 1
71
+ coeff = np.zeros(n_free)
72
+ const = 0.0
73
+ fixed_pos = np.full(n, -1, dtype=np.int64)
74
+ for a in range(nf):
75
+ fixed_pos[fixed_idx[a]] = a
76
+ for k in range(n_free):
77
+ i = free_arr[k]
78
+ # edges where i is the row (i < j, j fixed)
79
+ for r in range(G_rows[i], G_rows[i + 1]):
80
+ j = G_cols[r]
81
+ a = fixed_pos[j]
82
+ if a < 0:
83
+ continue
84
+ fval = fixed_val[a]
85
+ w = G_data[r]
86
+ const += w * fval
87
+ coeff[k] += w * (1.0 - 2.0 * fval)
88
+ # edges where i is the column (j < i, j fixed)
89
+ for a in range(nf):
90
+ j = fixed_idx[a]
91
+ if j >= i:
92
+ continue
93
+ fval = fixed_val[a]
94
+ for r in range(G_rows[j], G_rows[j + 1]):
95
+ if G_cols[r] == i:
96
+ w = G_data[r]
97
+ const += w * fval
98
+ coeff[k] += w * (1.0 - 2.0 * fval)
99
+ break
100
+ return const, coeff
101
+
102
+
103
+ @njit(cache=True)
104
+ def _influence_scores_sparse(G_data, G_rows, G_cols, free_arr):
105
+ n_free = len(free_arr)
106
+ n = G_rows.shape[0] - 1
107
+ scores = np.zeros(n_free)
108
+ free_set = np.zeros(n, dtype=np.bool_)
109
+ for k in range(n_free):
110
+ free_set[free_arr[k]] = True
111
+ for k in range(n_free):
112
+ i = free_arr[k]
113
+ for r in range(G_rows[i], G_rows[i + 1]):
114
+ j = G_cols[r]
115
+ if free_set[j]:
116
+ scores[k] += abs(G_data[r])
117
+ for m in range(n_free):
118
+ j = free_arr[m]
119
+ if j >= i:
120
+ continue
121
+ for r in range(G_rows[j], G_rows[j + 1]):
122
+ if G_cols[r] == i:
123
+ scores[k] += abs(G_data[r])
124
+ break
125
+ return scores
126
+
127
+
128
+ # ---------------------------------------------------------------------------
129
+ # LP upper bound
130
+ # ---------------------------------------------------------------------------
131
+
132
+ def _lp_upper_bound(G_data, G_rows, G_cols, free_arr, fixed_idx, fixed_val, n):
133
+ ff = _fixed_fixed_sparse(G_data, G_rows, G_cols, fixed_idx, fixed_val)
134
+ n_free = len(free_arr)
135
+
136
+ if n_free == 0:
137
+ return ff
138
+
139
+ ff_const, coeff = _fixed_free_linear_sparse(
140
+ G_data, G_rows, G_cols, free_arr, fixed_idx, fixed_val
141
+ )
142
+
143
+ free_set_map = {int(free_arr[k]): k for k in range(n_free)}
144
+ pairs = []
145
+ for a in range(n_free):
146
+ i = int(free_arr[a])
147
+ for r in range(G_rows[i], G_rows[i + 1]):
148
+ j = int(G_cols[r])
149
+ if j in free_set_map and j > i:
150
+ pairs.append((i, j, float(G_data[r])))
151
+
152
+ if not _HAVE_SCIPY:
153
+ bound = ff + ff_const
154
+ for k in range(n_free):
155
+ bound += max(0.0, coeff[k])
156
+ for _, _, w in pairs:
157
+ bound += max(0.0, w)
158
+ return bound
159
+
160
+ n_pairs = len(pairs)
161
+ total_vars = n_free + n_pairs
162
+
163
+ c = np.zeros(total_vars)
164
+ for k in range(n_free):
165
+ c[k] = -coeff[k]
166
+ for p, (i, j, w) in enumerate(pairs):
167
+ ki, kj = free_set_map[i], free_set_map[j]
168
+ c[ki] -= w
169
+ c[kj] -= w
170
+ c[n_free + p] += 2.0 * w
171
+
172
+ bounds = [(0.0, 1.0)] * total_vars
173
+
174
+ if not pairs:
175
+ lp_val = sum(-c[k] if c[k] < 0.0 else 0.0 for k in range(n_free))
176
+ return ff + ff_const + lp_val
177
+
178
+ rows = 3 * n_pairs
179
+ A = np.zeros((rows, total_vars))
180
+ b_ub = np.empty(rows)
181
+ for p, (i, j, _) in enumerate(pairs):
182
+ ki, kj = free_set_map[i], free_set_map[j]
183
+ r = 3 * p
184
+ A[r, ki] = -1.0; A[r, n_free + p] = 1.0; b_ub[r] = 0.0
185
+ A[r+1, kj] = -1.0; A[r+1, n_free + p] = 1.0; b_ub[r+1] = 0.0
186
+ A[r+2, ki] = 1.0; A[r+2, kj] = 1.0
187
+ A[r+2, n_free + p] = -1.0; b_ub[r+2] = 1.0
188
+
189
+ res = linprog(c, A_ub=A, b_ub=b_ub, bounds=bounds,
190
+ method="highs", options={"disp": False})
191
+
192
+ return (ff + ff_const + (-res.fun)) if res.success else float("inf")
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # Branch and bound (internal)
197
+ # ---------------------------------------------------------------------------
198
+
199
+ def _branch_and_bound_sparse(G_m, warm_theta, warm_energy, n, is_spin_glass,
200
+ verbose=True, time_limit=None):
201
+ G_data = np.asarray(G_m.data, dtype=np.float64)
202
+ G_rows = np.asarray(G_m.indptr, dtype=np.int64)
203
+ G_cols = np.asarray(G_m.indices, dtype=np.int64)
204
+
205
+ best_bits = warm_theta.copy()
206
+ best_value = warm_energy
207
+
208
+ if verbose:
209
+ print(f"Warm-start incumbent: {best_value:.6f}")
210
+
211
+ t_start = time.monotonic()
212
+ nodes_explored = 0
213
+ nodes_pruned = 0
214
+
215
+ stack = [(np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64))]
216
+
217
+ while stack:
218
+ if time_limit is not None and (time.monotonic() - t_start) > time_limit:
219
+ if verbose:
220
+ print(f"Time limit reached. "
221
+ f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
222
+ return best_bits, best_value, False
223
+
224
+ fixed_idx, fixed_val = stack.pop()
225
+ nodes_explored += 1
226
+
227
+ fixed_set = set(int(fixed_idx[k]) for k in range(len(fixed_idx)))
228
+ free_arr = np.array([i for i in range(n) if i not in fixed_set],
229
+ dtype=np.int64)
230
+
231
+ ub = _lp_upper_bound(G_data, G_rows, G_cols, free_arr,
232
+ fixed_idx, fixed_val, n)
233
+
234
+ if ub <= best_value + 1e-9:
235
+ nodes_pruned += 1
236
+ continue
237
+
238
+ if len(free_arr) == 0:
239
+ bits = np.zeros(n, dtype=np.bool_)
240
+ for k in range(len(fixed_idx)):
241
+ bits[fixed_idx[k]] = bool(fixed_val[k])
242
+ val = float(
243
+ compute_energy_sparse(bits, G_data, G_rows, G_cols, n)
244
+ if is_spin_glass
245
+ else compute_cut_sparse(bits, G_data, G_rows, G_cols, n)
246
+ )
247
+ if val > best_value:
248
+ best_value = val
249
+ best_bits = bits.copy()
250
+ if verbose:
251
+ print(f" New incumbent: {best_value:.6f}"
252
+ f" (nodes: {nodes_explored})")
253
+ continue
254
+
255
+ scores = _influence_scores_sparse(G_data, G_rows, G_cols, free_arr)
256
+ branch_var = int(free_arr[int(np.argmax(scores))])
257
+
258
+ warm_val = int(best_bits[branch_var])
259
+ for val in [warm_val, 1 - warm_val]:
260
+ stack.append((
261
+ np.append(fixed_idx, branch_var).astype(np.int64),
262
+ np.append(fixed_val, val).astype(np.int64),
263
+ ))
264
+
265
+ elapsed = time.monotonic() - t_start
266
+ if verbose:
267
+ print(f"\nExact optimum: {best_value:.6f}")
268
+ print(f"Nodes explored: {nodes_explored} | "
269
+ f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
270
+
271
+ return best_bits, best_value, True
272
+
273
+
274
+ # ---------------------------------------------------------------------------
275
+ # Public API
276
+ # ---------------------------------------------------------------------------
277
+
278
+ def solve_maxcut_exact_sparse(
279
+ G,
280
+ best_guess=None,
281
+ quality=None,
282
+ shots=None,
283
+ is_spin_glass=False,
284
+ anneal_t=None,
285
+ anneal_h=None,
286
+ repulsion_base=None,
287
+ is_maxcut_gpu=True,
288
+ verbose=True,
289
+ time_limit=None,
290
+ gray_iterations=None,
291
+ gray_seed_multiple=None,
292
+ ):
293
+ """
294
+ Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver_sparse
295
+ then certify via branch and bound.
296
+
297
+ Accepts the same G input as spin_glass_solver_sparse (NetworkX graph or
298
+ scipy CSR matrix) and the same warm-start formats (str, int, list, None).
299
+
300
+ Parameters
301
+ ----------
302
+ G : networkx.Graph or scipy CSR matrix
303
+ Graph or pre-built sparse adjacency matrix.
304
+ best_guess : str | int | list[bool] | None
305
+ Warm-start hint in any PyQrackIsing-compatible format. If None,
306
+ spin_glass_solver_sparse is called to produce one.
307
+ quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
308
+ is_spin_glass, gray_iterations, gray_seed_multiple
309
+ Forwarded to spin_glass_solver_sparse when best_guess is None.
310
+ verbose : bool
311
+ time_limit : float or None
312
+ Wall-clock seconds for the B&B phase.
313
+
314
+ Returns
315
+ -------
316
+ bitstring : str
317
+ cut_value : float
318
+ partition : tuple(list, list)
319
+ min_energy : float
320
+ certified : bool
321
+ """
322
+ # Mirror spin_glass_solver_sparse's G -> G_m conversion exactly
323
+ if isinstance(G, nx.Graph):
324
+ nodes = list(G.nodes())
325
+ n_qubits = len(nodes)
326
+ G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
327
+ else:
328
+ n_qubits = G.shape[0]
329
+ nodes = list(range(n_qubits))
330
+ G_m = G
331
+
332
+ if n_qubits < 3:
333
+ if n_qubits == 0:
334
+ return "", 0, ([], []), 0, True
335
+ if n_qubits == 1:
336
+ return "0", 0, (nodes, []), 0, True
337
+ if n_qubits == 2:
338
+ weight = G_m[0, 1]
339
+ if weight < 0.0:
340
+ return "00", 0, (nodes, []), weight, True
341
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
342
+
343
+ G_data = np.asarray(G_m.data, dtype=np.float64)
344
+ G_rows = np.asarray(G_m.indptr, dtype=np.int64)
345
+ G_cols = np.asarray(G_m.indices, dtype=np.int64)
346
+
347
+ # Warm-start parser — mirrors spin_glass_solver_sparse exactly
348
+ bitstring = ""
349
+ cut_value = 0.0
350
+ if isinstance(best_guess, str):
351
+ bitstring = best_guess
352
+ elif isinstance(best_guess, int):
353
+ bitstring = int_to_bitstring(best_guess, n_qubits)
354
+ elif isinstance(best_guess, list):
355
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
356
+ else:
357
+ if verbose:
358
+ print("Running PyQrackIsing heuristic...")
359
+ from .spin_glass_solver_sparse import spin_glass_solver_sparse
360
+ kwargs = {}
361
+ if quality is not None: kwargs["quality"] = quality
362
+ if shots is not None: kwargs["shots"] = shots
363
+ if anneal_t is not None: kwargs["anneal_t"] = anneal_t
364
+ if anneal_h is not None: kwargs["anneal_h"] = anneal_h
365
+ if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
366
+ if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
367
+ if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
368
+ kwargs["is_maxcut_gpu"] = is_maxcut_gpu
369
+ t0 = time.monotonic()
370
+ bitstring, cut_value, _, _ = spin_glass_solver_sparse(
371
+ G_m, is_spin_glass=is_spin_glass, **kwargs
372
+ )
373
+ if verbose:
374
+ print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
375
+
376
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
377
+ if is_spin_glass:
378
+ max_energy = compute_energy_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
379
+ elif cut_value is None:
380
+ max_energy = compute_cut_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
381
+ else:
382
+ max_energy = cut_value
383
+
384
+ if verbose:
385
+ print("Starting branch and bound...")
386
+
387
+ best_theta, max_energy, certified = _branch_and_bound_sparse(
388
+ G_m, best_theta, max_energy, n_qubits, is_spin_glass,
389
+ verbose=verbose, time_limit=time_limit,
390
+ )
391
+
392
+ G_data = np.asarray(G_m.data, dtype=np.float64)
393
+ G_rows = np.asarray(G_m.indptr, dtype=np.int64)
394
+ G_cols = np.asarray(G_m.indices, dtype=np.int64)
395
+
396
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
397
+ if is_spin_glass:
398
+ cut_value = compute_cut_sparse(best_theta, G_data, G_rows, G_cols, n_qubits)
399
+ min_energy = -max_energy
400
+ else:
401
+ cut_value = max_energy
402
+ min_energy = compute_energy_sparse(best_theta, G_data, G_rows, G_cols, n_qubits)
403
+
404
+ return bitstring, float(cut_value), (l, r), float(min_energy), certified
@@ -0,0 +1,356 @@
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_streaming.py — warm-start branch-and-bound exact MAXCUT solver
7
+ # (streaming / G_func + nodes variant)
8
+ #
9
+ # Objective convention (matches PyQrackIsing throughout):
10
+ # Maximise sum_{(i,j) in cut} w_{ij}
11
+ # i.e. edge (i,j) contributes w_{ij} when bits[i] != bits[j].
12
+ # Edge weights may be positive or negative; no diagonal / self-loops.
13
+ #
14
+ # Upper bound per B&B node: LP relaxation of the MAXCUT objective.
15
+ # Linearisation: introduce y_ij = x_i * x_j for each free edge pair;
16
+ # edge contribution becomes w_{ij} * (x_i + x_j - 2*y_ij).
17
+ # Constraints: y_ij <= x_i, y_ij <= x_j, x_i + x_j - y_ij <= 1.
18
+ # Users may swap in a tighter SDP bound by replacing _lp_upper_bound.
19
+
20
+ import time
21
+ import numpy as np
22
+ from numba import njit, prange
23
+ from .maxcut_tfim_util import (
24
+ compute_cut_streaming,
25
+ compute_energy_streaming,
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 (streaming / G_func)
44
+ # ---------------------------------------------------------------------------
45
+
46
+ @njit(cache=True)
47
+ def _fixed_fixed_streaming(G_func, nodes, 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
+ if fi != fj:
57
+ ii, jj = (i, j) if i < j else (j, i)
58
+ w = G_func(nodes[ii], nodes[jj])
59
+ if w != 0.0:
60
+ total += w
61
+ return total
62
+
63
+
64
+ @njit(cache=True)
65
+ def _fixed_free_linear_streaming(G_func, nodes, free_arr, fixed_idx, fixed_val):
66
+ n_free = len(free_arr)
67
+ nf = len(fixed_idx)
68
+ coeff = np.zeros(n_free)
69
+ const = 0.0
70
+ for k in range(n_free):
71
+ i = free_arr[k]
72
+ for a in range(nf):
73
+ j = fixed_idx[a]
74
+ fval = fixed_val[a]
75
+ ii, jj = (i, j) if i < j else (j, i)
76
+ w = G_func(nodes[ii], nodes[jj])
77
+ if w == 0.0:
78
+ continue
79
+ const += w * fval
80
+ coeff[k] += w * (1.0 - 2.0 * fval)
81
+ return const, coeff
82
+
83
+
84
+ @njit(cache=True)
85
+ def _influence_scores_streaming(G_func, nodes, free_arr):
86
+ n_free = len(free_arr)
87
+ scores = np.zeros(n_free)
88
+ for k in range(n_free):
89
+ i = free_arr[k]
90
+ for m in range(n_free):
91
+ if k == m:
92
+ continue
93
+ j = free_arr[m]
94
+ ii, jj = (i, j) if i < j else (j, i)
95
+ scores[k] += abs(G_func(nodes[ii], nodes[jj]))
96
+ return scores
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # LP upper bound
101
+ # ---------------------------------------------------------------------------
102
+
103
+ def _lp_upper_bound(G_func, nodes, free_arr, fixed_idx, fixed_val, n):
104
+ ff = _fixed_fixed_streaming(G_func, nodes, fixed_idx, fixed_val)
105
+ n_free = len(free_arr)
106
+
107
+ if n_free == 0:
108
+ return ff
109
+
110
+ ff_const, coeff = _fixed_free_linear_streaming(
111
+ G_func, nodes, free_arr, fixed_idx, fixed_val
112
+ )
113
+
114
+ # indices into free_arr, not node indices, since LP vars are indexed by position
115
+ pairs = []
116
+ for a in range(n_free):
117
+ i = int(free_arr[a])
118
+ for b in range(a + 1, n_free):
119
+ j = int(free_arr[b])
120
+ ii, jj = (i, j) if i < j else (j, i)
121
+ w = float(G_func(nodes[ii], nodes[jj]))
122
+ if w != 0.0:
123
+ pairs.append((a, b, w))
124
+
125
+ if not _HAVE_SCIPY:
126
+ bound = ff + ff_const
127
+ for k in range(n_free):
128
+ bound += max(0.0, coeff[k])
129
+ for _, _, w in pairs:
130
+ bound += max(0.0, w)
131
+ return bound
132
+
133
+ n_pairs = len(pairs)
134
+ total_vars = n_free + n_pairs
135
+
136
+ c = np.zeros(total_vars)
137
+ for k in range(n_free):
138
+ c[k] = -coeff[k]
139
+ for p, (ka, kb, w) in enumerate(pairs):
140
+ c[ka] -= w
141
+ c[kb] -= w
142
+ c[n_free + p] += 2.0 * w
143
+
144
+ bounds = [(0.0, 1.0)] * total_vars
145
+
146
+ if not pairs:
147
+ lp_val = sum(-c[k] if c[k] < 0.0 else 0.0 for k in range(n_free))
148
+ return ff + ff_const + lp_val
149
+
150
+ rows = 3 * n_pairs
151
+ A = np.zeros((rows, total_vars))
152
+ b_ub = np.empty(rows)
153
+ for p, (ka, kb, _) in enumerate(pairs):
154
+ r = 3 * p
155
+ A[r, ka] = -1.0; A[r, n_free + p] = 1.0; b_ub[r] = 0.0
156
+ A[r+1, kb] = -1.0; A[r+1, n_free + p] = 1.0; b_ub[r+1] = 0.0
157
+ A[r+2, ka] = 1.0; A[r+2, kb] = 1.0
158
+ A[r+2, n_free + p] = -1.0; b_ub[r+2] = 1.0
159
+
160
+ res = linprog(c, A_ub=A, b_ub=b_ub, bounds=bounds,
161
+ method="highs", options={"disp": False})
162
+
163
+ return (ff + ff_const + (-res.fun)) if res.success else float("inf")
164
+
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # Branch and bound (internal)
168
+ # ---------------------------------------------------------------------------
169
+
170
+ def _branch_and_bound_streaming(G_func, nodes, warm_theta, warm_energy, n,
171
+ is_spin_glass, verbose=True, time_limit=None):
172
+ best_bits = warm_theta.copy()
173
+ best_value = warm_energy
174
+
175
+ if verbose:
176
+ print(f"Warm-start incumbent: {best_value:.6f}")
177
+
178
+ t_start = time.monotonic()
179
+ nodes_explored = 0
180
+ nodes_pruned = 0
181
+
182
+ stack = [(np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64))]
183
+
184
+ while stack:
185
+ if time_limit is not None and (time.monotonic() - t_start) > time_limit:
186
+ if verbose:
187
+ print(f"Time limit reached. "
188
+ f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
189
+ return best_bits, best_value, False
190
+
191
+ fixed_idx, fixed_val = stack.pop()
192
+ nodes_explored += 1
193
+
194
+ fixed_set = set(int(fixed_idx[k]) for k in range(len(fixed_idx)))
195
+ free_arr = np.array([i for i in range(n) if i not in fixed_set],
196
+ dtype=np.int64)
197
+
198
+ ub = _lp_upper_bound(G_func, nodes, free_arr, fixed_idx, fixed_val, n)
199
+
200
+ if ub <= best_value + 1e-9:
201
+ nodes_pruned += 1
202
+ continue
203
+
204
+ if len(free_arr) == 0:
205
+ bits = np.zeros(n, dtype=np.bool_)
206
+ for k in range(len(fixed_idx)):
207
+ bits[fixed_idx[k]] = bool(fixed_val[k])
208
+ val = float(
209
+ compute_energy_streaming(bits, G_func, nodes, n)
210
+ if is_spin_glass
211
+ else compute_cut_streaming(bits, G_func, nodes, n)
212
+ )
213
+ if val > best_value:
214
+ best_value = val
215
+ best_bits = bits.copy()
216
+ if verbose:
217
+ print(f" New incumbent: {best_value:.6f}"
218
+ f" (nodes: {nodes_explored})")
219
+ continue
220
+
221
+ scores = _influence_scores_streaming(G_func, nodes, free_arr)
222
+ branch_var = int(free_arr[int(np.argmax(scores))])
223
+
224
+ warm_val = int(best_bits[branch_var])
225
+ for val in [warm_val, 1 - warm_val]:
226
+ stack.append((
227
+ np.append(fixed_idx, branch_var).astype(np.int64),
228
+ np.append(fixed_val, val).astype(np.int64),
229
+ ))
230
+
231
+ elapsed = time.monotonic() - t_start
232
+ if verbose:
233
+ print(f"\nExact optimum: {best_value:.6f}")
234
+ print(f"Nodes explored: {nodes_explored} | "
235
+ f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
236
+
237
+ return best_bits, best_value, True
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # Public API
242
+ # ---------------------------------------------------------------------------
243
+
244
+ def solve_maxcut_exact_streaming(
245
+ G_func,
246
+ nodes,
247
+ best_guess=None,
248
+ quality=None,
249
+ shots=None,
250
+ is_spin_glass=False,
251
+ anneal_t=None,
252
+ anneal_h=None,
253
+ repulsion_base=None,
254
+ verbose=True,
255
+ time_limit=None,
256
+ gray_iterations=None,
257
+ gray_seed_multiple=None,
258
+ ):
259
+ """
260
+ Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver_streaming
261
+ then certify via branch and bound.
262
+
263
+ Accepts the same G_func + nodes input as spin_glass_solver_streaming and
264
+ the same warm-start formats (str, int, list, or None).
265
+
266
+ Parameters
267
+ ----------
268
+ G_func : callable(u, v) -> float
269
+ Edge weight function (Numba-callable). Returns 0.0 for absent edges.
270
+ nodes : array-like
271
+ Ordered sequence of node identifiers passed to G_func.
272
+ best_guess : str | int | list[bool] | None
273
+ Warm-start hint in any PyQrackIsing-compatible format. If None,
274
+ spin_glass_solver_streaming is called to produce one.
275
+ quality, shots, anneal_t, anneal_h, repulsion_base, is_spin_glass,
276
+ gray_iterations, gray_seed_multiple
277
+ Forwarded to spin_glass_solver_streaming when best_guess is None.
278
+ verbose : bool
279
+ time_limit : float or None
280
+ Wall-clock seconds for the B&B phase.
281
+
282
+ Returns
283
+ -------
284
+ bitstring : str
285
+ cut_value : float
286
+ partition : tuple(list, list)
287
+ min_energy : float
288
+ certified : bool
289
+ """
290
+ nodes = np.asarray(nodes)
291
+ n_qubits = len(nodes)
292
+
293
+ if n_qubits < 3:
294
+ if n_qubits == 0:
295
+ return "", 0, ([], []), 0, True
296
+ if n_qubits == 1:
297
+ return "0", 0, (list(nodes), []), 0, True
298
+ if n_qubits == 2:
299
+ weight = G_func(nodes[0], nodes[1])
300
+ if weight < 0.0:
301
+ return "00", 0, (list(nodes), []), weight, True
302
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
303
+
304
+ # Warm-start parser — mirrors spin_glass_solver_streaming exactly
305
+ bitstring = ""
306
+ cut_value = 0.0
307
+ if isinstance(best_guess, str):
308
+ bitstring = best_guess
309
+ elif isinstance(best_guess, int):
310
+ bitstring = int_to_bitstring(best_guess, n_qubits)
311
+ elif isinstance(best_guess, list):
312
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
313
+ else:
314
+ if verbose:
315
+ print("Running PyQrackIsing heuristic...")
316
+ from .spin_glass_solver_streaming import spin_glass_solver_streaming
317
+ kwargs = {}
318
+ if quality is not None: kwargs["quality"] = quality
319
+ if shots is not None: kwargs["shots"] = shots
320
+ if anneal_t is not None: kwargs["anneal_t"] = anneal_t
321
+ if anneal_h is not None: kwargs["anneal_h"] = anneal_h
322
+ if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
323
+ if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
324
+ if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
325
+ t0 = time.monotonic()
326
+ bitstring, cut_value, _, _ = spin_glass_solver_streaming(
327
+ G_func, nodes, is_spin_glass=is_spin_glass, **kwargs
328
+ )
329
+ if verbose:
330
+ print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
331
+
332
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
333
+ if is_spin_glass:
334
+ max_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
335
+ elif cut_value is None:
336
+ max_energy = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
337
+ else:
338
+ max_energy = cut_value
339
+
340
+ if verbose:
341
+ print("Starting branch and bound...")
342
+
343
+ best_theta, max_energy, certified = _branch_and_bound_streaming(
344
+ G_func, nodes, best_theta, max_energy, n_qubits, is_spin_glass,
345
+ verbose=verbose, time_limit=time_limit,
346
+ )
347
+
348
+ bitstring, l, r = get_cut(best_theta, list(nodes), n_qubits)
349
+ if is_spin_glass:
350
+ cut_value = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
351
+ min_energy = -max_energy
352
+ else:
353
+ cut_value = max_energy
354
+ min_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
355
+
356
+ return bitstring, float(cut_value), (l, r), float(min_energy), certified
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.11.4
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
@@ -12,6 +12,9 @@ pyqrackising/maxcut_tfim_sparse.py
12
12
  pyqrackising/maxcut_tfim_streaming.py
13
13
  pyqrackising/maxcut_tfim_util.py
14
14
  pyqrackising/otoc.py
15
+ pyqrackising/solve_maxcut_exact.py
16
+ pyqrackising/solve_maxcut_exact_sparse.py
17
+ pyqrackising/solve_maxcut_exact_streaming.py
15
18
  pyqrackising/spin_glass_solver.py
16
19
  pyqrackising/spin_glass_solver_sparse.py
17
20
  pyqrackising/spin_glass_solver_streaming.py
@@ -7,7 +7,7 @@ with open(README_PATH) as readme_file:
7
7
 
8
8
  setup(
9
9
  name="pyqrackising",
10
- version="9.11.4",
10
+ version="9.12.1",
11
11
  author="Dan Strano",
12
12
  author_email="stranoj@gmail.com",
13
13
  description="Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)",
File without changes
File without changes
File without changes