PyQrackIsing 9.11.4__tar.gz → 9.12.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 (32) hide show
  1. {pyqrackising-9.11.4/pyqrackising.egg-info → pyqrackising-9.12.0}/PKG-INFO +1 -1
  2. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/README.md +11 -0
  3. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyproject.toml +1 -1
  4. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/__init__.py +3 -0
  5. pyqrackising-9.12.0/pyqrackising/solve_maxcut_exact.py +484 -0
  6. pyqrackising-9.12.0/pyqrackising/solve_maxcut_exact_sparse.py +500 -0
  7. pyqrackising-9.12.0/pyqrackising/solve_maxcut_exact_streaming.py +449 -0
  8. {pyqrackising-9.11.4 → pyqrackising-9.12.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  9. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising.egg-info/SOURCES.txt +3 -0
  10. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/setup.py +1 -1
  11. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/LICENSE.md +0 -0
  12. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/MANIFEST.in +0 -0
  13. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  14. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/generate_tfim_samples.py +0 -0
  15. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/kernels.cl +0 -0
  16. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/maxcut_tfim.py +0 -0
  17. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  18. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  19. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/maxcut_tfim_util.py +0 -0
  20. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/otoc.py +0 -0
  21. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/spin_glass_solver.py +0 -0
  22. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  23. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  24. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/tfim_magnetization.py +0 -0
  25. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/tfim_square_magnetization.py +0 -0
  26. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/tsp.py +0 -0
  27. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising/tsp_maxcut.py +0 -0
  28. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  29. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  30. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising.egg-info/requires.txt +0 -0
  31. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/pyqrackising.egg-info/top_level.txt +0 -0
  32. {pyqrackising-9.11.4 → pyqrackising-9.12.0}/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.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
@@ -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.0"
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,484 @@
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
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
+ # Numba is used for all inner loops (cut evaluation, branching heuristic,
20
+ # fixed-contribution accounting). The LP solver call (scipy HiGHS) stays
21
+ # in Python since JIT-compiling an LP solver is not practical.
22
+
23
+ import time
24
+ import numpy as np
25
+ from numba import njit, prange
26
+ from .maxcut_tfim_util import compute_cut, compute_energy
27
+
28
+ try:
29
+ from scipy.optimize import linprog
30
+ _HAVE_SCIPY = True
31
+ except ImportError:
32
+ _HAVE_SCIPY = False
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Numba-compiled inner loops
37
+ # ---------------------------------------------------------------------------
38
+
39
+ # Scoring delegates to maxcut_tfim_util so all PyQrackIsing solvers
40
+ # use a single consistent implementation.
41
+ def _cut_value(Q, bits, n_qubits=None):
42
+ if n_qubits is None:
43
+ n_qubits = len(bits)
44
+ return compute_cut(bits, Q, n_qubits)
45
+
46
+
47
+ def _energy_value(Q, bits, n_qubits=None):
48
+ if n_qubits is None:
49
+ n_qubits = len(bits)
50
+ return compute_energy(bits, Q, n_qubits)
51
+
52
+
53
+ @njit(cache=True)
54
+ def _fixed_fixed(Q, fixed_idx, fixed_val):
55
+ """
56
+ Exact cut contribution from already-branched variable pairs.
57
+ fixed_idx / fixed_val are parallel int64 arrays of (variable, value) pairs.
58
+ """
59
+ total = 0.0
60
+ nf = len(fixed_idx)
61
+ for a in range(nf):
62
+ i = fixed_idx[a]
63
+ fi = fixed_val[a]
64
+ for b in range(a + 1, nf):
65
+ j = fixed_idx[b]
66
+ fj = fixed_val[b]
67
+ ii, jj = (i, j) if i < j else (j, i)
68
+ if Q[ii, jj] != 0.0 and fi != fj:
69
+ total += Q[ii, jj]
70
+ return total
71
+
72
+
73
+ @njit(cache=True)
74
+ def _fixed_free_linear(Q, free_arr, fixed_idx, fixed_val):
75
+ """
76
+ Decompose fixed-to-free edge contributions into a scalar constant and a
77
+ per-free-variable linear coefficient vector, for use in the LP objective.
78
+
79
+ MAXCUT contribution of fixed-free edges
80
+ = fixed_free_const + sum_k coeff[k] * x_k
81
+
82
+ where:
83
+ fixed_free_const = sum_{k,fj} w_{k,fj} * fval_fj
84
+ coeff[k] = sum_{fj} w_{k,fj} * (1 - 2 * fval_fj)
85
+ """
86
+ n_free = len(free_arr)
87
+ nf = len(fixed_idx)
88
+ coeff = np.zeros(n_free)
89
+ const = 0.0
90
+ for k in range(n_free):
91
+ i = free_arr[k]
92
+ for a in range(nf):
93
+ j = fixed_idx[a]
94
+ fval = fixed_val[a]
95
+ ii, jj = (i, j) if i < j else (j, i)
96
+ w = Q[ii, jj]
97
+ if w == 0.0:
98
+ continue
99
+ const += w * fval
100
+ coeff[k] += w * (1.0 - 2.0 * fval)
101
+ return const, coeff
102
+
103
+
104
+ @njit(cache=True)
105
+ def _influence_scores(Q, free_arr):
106
+ """
107
+ Branch-variable selection heuristic: for each free variable, sum the
108
+ absolute weights of its edges to all other free variables (plus diagonal).
109
+ The variable with the highest score is chosen to branch on next.
110
+ """
111
+ n_free = len(free_arr)
112
+ scores = np.zeros(n_free)
113
+ for k in range(n_free):
114
+ i = free_arr[k]
115
+ scores[k] += abs(Q[i, i])
116
+ for m in range(n_free):
117
+ if k == m:
118
+ continue
119
+ j = free_arr[m]
120
+ ii, jj = (i, j) if i < j else (j, i)
121
+ scores[k] += abs(Q[ii, jj])
122
+ return scores
123
+
124
+
125
+ # ---------------------------------------------------------------------------
126
+ # LP upper bound (Python, calls scipy HiGHS)
127
+ # ---------------------------------------------------------------------------
128
+
129
+ def _lp_upper_bound(Q, free_arr, fixed_idx, fixed_val, n):
130
+ """
131
+ LP relaxation upper bound for the MAXCUT subproblem defined by fixed_idx /
132
+ fixed_val. Fixed-variable contributions are computed via Numba helpers;
133
+ the free-free relaxation is solved by scipy HiGHS.
134
+
135
+ Falls back to a loose but valid bound when scipy is unavailable.
136
+ """
137
+ ff = _fixed_fixed(Q, fixed_idx, fixed_val)
138
+ n_free = len(free_arr)
139
+
140
+ if n_free == 0:
141
+ return ff
142
+
143
+ ff_const, coeff = _fixed_free_linear(Q, free_arr, fixed_idx, fixed_val)
144
+
145
+ if not _HAVE_SCIPY:
146
+ # Loose valid bound: take the best-case value of every free edge.
147
+ bound = ff + ff_const
148
+ for k in range(n_free):
149
+ bound += max(0.0, coeff[k])
150
+ for a in range(n_free):
151
+ i = free_arr[a]
152
+ for b in range(a + 1, n_free):
153
+ j = free_arr[b]
154
+ bound += max(0.0, Q[i, j])
155
+ return bound
156
+
157
+ pairs = [(free_arr[a], free_arr[b])
158
+ for a in range(n_free) for b in range(a + 1, n_free)
159
+ if Q[free_arr[a], free_arr[b]] != 0.0]
160
+ n_pairs = len(pairs)
161
+ total_vars = n_free + n_pairs
162
+ free_idx_map = {int(v): k for k, v in enumerate(free_arr)}
163
+
164
+ # LP objective (negated for minimisation).
165
+ # Free-free edge (i,j) contributes w*(x_i + x_j - 2*y_ij) to the MAXCUT
166
+ # objective, so in the minimisation objective:
167
+ # c[x_i] -= w, c[x_j] -= w, c[y_ij] += 2*w
168
+ c = np.zeros(total_vars)
169
+ for k in range(n_free):
170
+ c[k] = -coeff[k]
171
+ for p, (i, j) in enumerate(pairs):
172
+ w = Q[i, j]
173
+ c[free_idx_map[i]] -= w
174
+ c[free_idx_map[j]] -= w
175
+ c[n_free + p] += 2.0 * w
176
+
177
+ bounds = [(0.0, 1.0)] * total_vars
178
+
179
+ if not pairs:
180
+ lp_val = sum(-c[k] if c[k] < 0.0 else 0.0 for k in range(n_free))
181
+ return ff + ff_const + lp_val
182
+
183
+ # Linearisation constraints: y_ij <= x_i, y_ij <= x_j, x_i+x_j-y_ij <= 1
184
+ rows = 3 * n_pairs
185
+ A = np.zeros((rows, total_vars))
186
+ b_ub = np.empty(rows)
187
+ for p, (i, j) in enumerate(pairs):
188
+ ki, kj = free_idx_map[i], free_idx_map[j]
189
+ r = 3 * p
190
+ A[r, ki] = -1.0; A[r, n_free + p] = 1.0; b_ub[r] = 0.0
191
+ A[r+1, kj] = -1.0; A[r+1, n_free + p] = 1.0; b_ub[r+1] = 0.0
192
+ A[r+2, ki] = 1.0; A[r+2, kj] = 1.0
193
+ A[r+2, n_free + p] = -1.0; b_ub[r+2] = 1.0
194
+
195
+ res = linprog(c, A_ub=A, b_ub=b_ub, bounds=bounds,
196
+ method="highs", options={"disp": False})
197
+
198
+ return (ff + ff_const + (-res.fun)) if res.success else float("inf")
199
+
200
+
201
+ # ---------------------------------------------------------------------------
202
+ # Warm-start parser (matches PyQrackIsing solver convention)
203
+ # ---------------------------------------------------------------------------
204
+
205
+ def _parse_warm_start(
206
+ best_guess,
207
+ n_qubits,
208
+ Q,
209
+ G=None,
210
+ quality=None,
211
+ shots=None,
212
+ is_spin_glass=False,
213
+ anneal_t=None,
214
+ anneal_h=None,
215
+ repulsion_base=None,
216
+ is_maxcut_gpu=True,
217
+ ):
218
+ """
219
+ Resolve a warm-start hint into (bits: ndarray[bool], cut_val: float).
220
+
221
+ Accepted formats (matching PyQrackIsing solver convention):
222
+ str — bitstring of '0'/'1' characters, length n_qubits
223
+ int — integer whose binary representation is the bitstring
224
+ (LSB = node 0, matching int_to_bitstring convention)
225
+ list[bool] — list of per-node boolean / 0-1 values
226
+ None — call spin_glass_solver_sparse if G is provided,
227
+ otherwise fall back to a random partition
228
+ """
229
+ bitstring = ""
230
+ cut_val = None
231
+
232
+ if isinstance(best_guess, str):
233
+ bitstring = best_guess
234
+
235
+ elif isinstance(best_guess, int):
236
+ bitstring = format(best_guess, f"0{n_qubits}b")[::-1]
237
+
238
+ elif isinstance(best_guess, list):
239
+ bitstring = "".join("1" if b else "0" for b in best_guess)
240
+
241
+ else:
242
+ if G is not None:
243
+ from .spin_glass_solver import spin_glass_solver
244
+ kwargs = {}
245
+ if quality is not None: kwargs["quality"] = quality
246
+ if shots is not None: kwargs["shots"] = shots
247
+ if anneal_t is not None: kwargs["anneal_t"] = anneal_t
248
+ if anneal_h is not None: kwargs["anneal_h"] = anneal_h
249
+ if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
250
+ kwargs["is_maxcut_gpu"] = is_maxcut_gpu
251
+ bitstring, cut_val, _, _ = spin_glass_solver(
252
+ G, is_spin_glass=is_spin_glass, **kwargs
253
+ )
254
+ else:
255
+ bits = np.random.randint(0, 2, size=n_qubits).astype(np.bool_)
256
+ score_fn = _energy_value if is_spin_glass else _cut_value
257
+ return bits, float(score_fn(Q, bits, n_qubits))
258
+
259
+ bits = np.array([b == "1" for b in bitstring], dtype=np.bool_)
260
+ # Always recompute using the util scoring so the heuristic value shown
261
+ # is guaranteed consistent with the warm-start incumbent.
262
+ n_qubits = len(bits)
263
+ cut_val = float(
264
+ _energy_value(Q, bits, n_qubits) if is_spin_glass
265
+ else _cut_value(Q, bits, n_qubits)
266
+ )
267
+ return bits, cut_val
268
+
269
+
270
+ # ---------------------------------------------------------------------------
271
+ # Public API
272
+ # ---------------------------------------------------------------------------
273
+
274
+ def maxcut_branch_and_bound(
275
+ Q,
276
+ best_guess=None,
277
+ G=None,
278
+ quality=None,
279
+ shots=None,
280
+ is_spin_glass=False,
281
+ anneal_t=None,
282
+ anneal_h=None,
283
+ repulsion_base=None,
284
+ is_maxcut_gpu=True,
285
+ verbose=True,
286
+ time_limit=None,
287
+ ):
288
+ """
289
+ Exact MAXCUT solver via branch and bound with LP relaxation upper bounds.
290
+
291
+ All inner loops (cut evaluation, fixed-contribution accounting, branching
292
+ heuristic) are Numba JIT-compiled. The LP bound uses scipy HiGHS.
293
+
294
+ Parameters
295
+ ----------
296
+ Q : (n, n) float64 ndarray
297
+ Dense upper-triangular edge weight matrix, no diagonal.
298
+ Objective: maximise sum_{i<j, bits[i]!=bits[j]} Q[i,j].
299
+ best_guess : str | int | list[bool] | None
300
+ Warm-start hint in any PyQrackIsing-compatible format:
301
+ str — '0101...' bitstring
302
+ int — integer encoding of the bitstring (LSB = node 0)
303
+ list[bool] — list of per-node boolean values
304
+ None — call spin_glass_solver_sparse (requires G) or
305
+ use a random partition
306
+ G : networkx.Graph or None
307
+ Passed to spin_glass_solver_sparse when best_guess is None.
308
+ quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu, is_spin_glass
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 before returning best-so-far (not certified).
313
+
314
+ Returns
315
+ -------
316
+ best_bits : ndarray[bool]
317
+ best_value : float
318
+ certified : bool
319
+ True iff the returned solution is provably optimal.
320
+ """
321
+ Q = np.asarray(Q, dtype=np.float64)
322
+ n = Q.shape[0]
323
+ assert Q.shape == (n, n), "Q must be square"
324
+
325
+ best_bits, best_value = _parse_warm_start(
326
+ best_guess, n, Q, G=G,
327
+ quality=quality, shots=shots, is_spin_glass=is_spin_glass,
328
+ anneal_t=anneal_t, anneal_h=anneal_h,
329
+ repulsion_base=repulsion_base, is_maxcut_gpu=is_maxcut_gpu,
330
+ )
331
+
332
+ if verbose:
333
+ print(f"Warm-start incumbent: {best_value:.6f}")
334
+
335
+ t_start = time.monotonic()
336
+ nodes_explored = 0
337
+ nodes_pruned = 0
338
+
339
+ stack = [(np.empty(0, dtype=np.int64), np.empty(0, dtype=np.int64))]
340
+
341
+ while stack:
342
+ if time_limit is not None and (time.monotonic() - t_start) > time_limit:
343
+ if verbose:
344
+ print(f"Time limit reached. "
345
+ f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
346
+ return best_bits, best_value, False
347
+
348
+ fixed_idx, fixed_val = stack.pop()
349
+ nodes_explored += 1
350
+
351
+ fixed_set = set(int(fixed_idx[k]) for k in range(len(fixed_idx)))
352
+ free_arr = np.array([i for i in range(n) if i not in fixed_set],
353
+ dtype=np.int64)
354
+
355
+ ub = _lp_upper_bound(Q, free_arr, fixed_idx, fixed_val, n)
356
+
357
+ if ub <= best_value + 1e-9:
358
+ nodes_pruned += 1
359
+ continue
360
+
361
+ if len(free_arr) == 0:
362
+ bits = np.zeros(n, dtype=np.bool_)
363
+ for k in range(len(fixed_idx)):
364
+ bits[fixed_idx[k]] = bool(fixed_val[k])
365
+ val = float(
366
+ _energy_value(Q, bits, n) if is_spin_glass
367
+ else _cut_value(Q, bits, n)
368
+ )
369
+ if val > best_value:
370
+ best_value = val
371
+ best_bits = bits.copy()
372
+ if verbose:
373
+ print(f" New incumbent: {best_value:.6f}"
374
+ f" (nodes: {nodes_explored})")
375
+ continue
376
+
377
+ scores = _influence_scores(Q, free_arr)
378
+ branch_var = int(free_arr[int(np.argmax(scores))])
379
+
380
+ warm_val = int(best_bits[branch_var])
381
+ for val in [warm_val, 1 - warm_val]:
382
+ stack.append((
383
+ np.append(fixed_idx, branch_var).astype(np.int64),
384
+ np.append(fixed_val, val).astype(np.int64),
385
+ ))
386
+
387
+ elapsed = time.monotonic() - t_start
388
+ if verbose:
389
+ print(f"\nExact optimum: {best_value:.6f}")
390
+ print(f"Nodes explored: {nodes_explored} | "
391
+ f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
392
+
393
+ return best_bits, best_value, True
394
+
395
+
396
+ def solve_maxcut_exact(
397
+ G,
398
+ best_guess=None,
399
+ quality=None,
400
+ shots=None,
401
+ is_spin_glass=False,
402
+ anneal_t=None,
403
+ anneal_h=None,
404
+ repulsion_base=None,
405
+ is_maxcut_gpu=True,
406
+ verbose=True,
407
+ time_limit=None,
408
+ ):
409
+ """
410
+ Run spin_glass_solver_sparse on G to produce a warm start (unless
411
+ best_guess is supplied), then certify it via branch and bound.
412
+
413
+ Parameters
414
+ ----------
415
+ G : networkx.Graph
416
+ Graph with arbitrary edge weights, no self-loops.
417
+ Node labels must be contiguous integers 0..n-1.
418
+ best_guess : str | int | list[bool] | None
419
+ Optional warm-start hint in any PyQrackIsing-compatible format.
420
+ If None, spin_glass_solver_sparse is called to produce one.
421
+ quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu, is_spin_glass
422
+ Forwarded to spin_glass_solver_sparse when best_guess is None.
423
+ verbose : bool
424
+ time_limit : float or None
425
+ Wall-clock seconds for the B&B phase.
426
+
427
+ Returns
428
+ -------
429
+ heuristic_bits : ndarray[bool]
430
+ heuristic_value : float
431
+ exact_bits : ndarray[bool]
432
+ exact_value : float
433
+ certified : bool
434
+ """
435
+ Q = _graph_to_dense_upper(G)
436
+ n = Q.shape[0]
437
+
438
+ if verbose and best_guess is None:
439
+ print("Running PyQrackIsing heuristic...")
440
+
441
+ t0 = time.monotonic()
442
+ heuristic_bits, heuristic_value = _parse_warm_start(
443
+ best_guess, n, Q, G=G,
444
+ quality=quality, shots=shots, is_spin_glass=is_spin_glass,
445
+ anneal_t=anneal_t, anneal_h=anneal_h,
446
+ repulsion_base=repulsion_base, is_maxcut_gpu=is_maxcut_gpu,
447
+ )
448
+ t_heuristic = time.monotonic() - t0
449
+
450
+ if verbose:
451
+ print(f"Heuristic value: {heuristic_value:.6f} ({t_heuristic:.3f}s)")
452
+ print("Starting branch and bound...")
453
+
454
+ exact_bits, exact_value, certified = maxcut_branch_and_bound(
455
+ Q,
456
+ best_guess=heuristic_bits,
457
+ verbose=verbose,
458
+ time_limit=time_limit,
459
+ )
460
+
461
+ if verbose:
462
+ gap = exact_value - heuristic_value
463
+ print(f"\nHeuristic gap closed: {gap:.6f} "
464
+ f"({'certified exact' if certified else 'time-limited'})")
465
+
466
+ return heuristic_bits, heuristic_value, exact_bits, exact_value, certified
467
+
468
+
469
+ # ---------------------------------------------------------------------------
470
+ # Internal helper
471
+ # ---------------------------------------------------------------------------
472
+
473
+ def _graph_to_dense_upper(G):
474
+ """
475
+ Convert a NetworkX graph to a dense upper-triangular float64 numpy matrix.
476
+ Node labels must be contiguous integers 0..n-1.
477
+ """
478
+ nodes = sorted(G.nodes())
479
+ n = len(nodes)
480
+ Q = np.zeros((n, n), dtype=np.float64)
481
+ for u, v, data in G.edges(data=True):
482
+ i, j = (u, v) if u < v else (v, u)
483
+ Q[i, j] = float(data.get("weight", 1.0))
484
+ return Q