PyQrackIsing 9.12.3__tar.gz → 9.13.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.
- {pyqrackising-9.12.3/pyqrackising.egg-info → pyqrackising-9.13.0}/PKG-INFO +1 -1
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/README.md +3 -2
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyproject.toml +1 -1
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/__init__.py +3 -0
- pyqrackising-9.13.0/pyqrackising/solve_maxcut_bnb.py +321 -0
- pyqrackising-9.13.0/pyqrackising/solve_maxcut_bnb_sparse.py +322 -0
- pyqrackising-9.13.0/pyqrackising/solve_maxcut_bnb_streaming.py +292 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0/pyqrackising.egg-info}/PKG-INFO +1 -1
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising.egg-info/SOURCES.txt +3 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/setup.py +1 -1
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/LICENSE.md +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/MANIFEST.in +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/generate_tfim_samples.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/kernels.cl +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/maxcut_tfim.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/maxcut_tfim_sparse.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/maxcut_tfim_streaming.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/maxcut_tfim_util.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/otoc.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/solve_maxcut_exact.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/solve_maxcut_exact_sparse.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/solve_maxcut_exact_streaming.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/spin_glass_solver.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/spin_glass_solver_sparse.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/spin_glass_solver_streaming.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/tfim_magnetization.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/tfim_square_magnetization.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/tsp.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising/tsp_maxcut.py +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising.egg-info/not-zip-safe +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising.egg-info/requires.txt +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/pyqrackising.egg-info/top_level.txt +0 -0
- {pyqrackising-9.12.3 → pyqrackising-9.13.0}/setup.cfg +0 -0
|
@@ -78,14 +78,15 @@ 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
|
|
81
|
+
These solvers above can be used as a "warm state" for _MaxSAT-based_ solvers or _branch-and-bound_ solvers, potentially to reach _exact_ solutions to MAXCUT:
|
|
82
82
|
|
|
83
83
|
```py
|
|
84
84
|
from pyqrackising import solve_maxcut_exact, solve_maxcut_exact_sparse, solve_maxcut_exact_streaming
|
|
85
|
+
from pyqrackising import solve_maxcut_bnb, solve_maxcut_bnb_sparse, solve_maxcut_bnb_streaming
|
|
85
86
|
import networkx as nx
|
|
86
87
|
|
|
87
88
|
G = nx.petersen_graph()
|
|
88
|
-
best_solution_bit_string, best_cut_value, best_node_groups =
|
|
89
|
+
best_solution_bit_string, best_cut_value, best_node_groups = solve_maxcut_bnb(G, time_limit=None)
|
|
89
90
|
```
|
|
90
91
|
Pass a time limit (in seconds) if desired.
|
|
91
92
|
|
|
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
|
|
7
7
|
|
|
8
8
|
[project]
|
|
9
9
|
name = "pyqrackising"
|
|
10
|
-
version = "9.
|
|
10
|
+
version = "9.13.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"}
|
|
@@ -15,3 +15,6 @@ from .convert_tensor_network_to_tsp import convert_tensor_network_to_tsp, conver
|
|
|
15
15
|
from .solve_maxcut_exact import solve_maxcut_exact
|
|
16
16
|
from .solve_maxcut_exact_sparse import solve_maxcut_exact_sparse
|
|
17
17
|
from .solve_maxcut_exact_streaming import solve_maxcut_exact_streaming
|
|
18
|
+
from .solve_maxcut_bnb import solve_maxcut_bnb
|
|
19
|
+
from .solve_maxcut_bnb_sparse import solve_maxcut_bnb_sparse
|
|
20
|
+
from .solve_maxcut_bnb_streaming import solve_maxcut_bnb_streaming
|
|
@@ -0,0 +1,321 @@
|
|
|
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
|
+
# Parallelism strategy
|
|
14
|
+
# --------------------
|
|
15
|
+
# The serial LP relaxation bound used in earlier drafts costs O(n^3) per
|
|
16
|
+
# node, making it useless at scale. We replace it with a parallelised
|
|
17
|
+
# decoupled upper bound that costs O(n^2) parallel work per node:
|
|
18
|
+
#
|
|
19
|
+
# UB(node) = fixed_fixed_cut (exact)
|
|
20
|
+
# + for each free-free edge (i,j): max(w_ij, 0)
|
|
21
|
+
# + for each fixed-free edge (i,j): max(w_ij, 0) if i free, etc.
|
|
22
|
+
#
|
|
23
|
+
# This bound is valid and is computed entirely inside @njit(parallel=True)
|
|
24
|
+
# kernels. A batch of frontier nodes is evaluated simultaneously, and leaf
|
|
25
|
+
# scoring is also parallelised across the batch.
|
|
26
|
+
|
|
27
|
+
import time
|
|
28
|
+
import os
|
|
29
|
+
import networkx as nx
|
|
30
|
+
import numpy as np
|
|
31
|
+
from numba import njit, prange
|
|
32
|
+
from .maxcut_tfim_util import (
|
|
33
|
+
compute_cut,
|
|
34
|
+
compute_energy,
|
|
35
|
+
get_cut,
|
|
36
|
+
heuristic_threshold,
|
|
37
|
+
int_to_bitstring,
|
|
38
|
+
opencl_context,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
dtype = opencl_context.dtype
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ---------------------------------------------------------------------------
|
|
45
|
+
# Parallel kernels
|
|
46
|
+
# ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
@njit(parallel=True, cache=True)
|
|
49
|
+
def _upper_bound_batch(G_m, fixed_vars, n, batch_size):
|
|
50
|
+
"""
|
|
51
|
+
Parallel upper bound for a batch of B&B nodes.
|
|
52
|
+
fixed_vars : (batch_size, n) int8, -1=free, 0/1=fixed.
|
|
53
|
+
For each node b, accumulates:
|
|
54
|
+
- exact cut for fixed-fixed pairs
|
|
55
|
+
- max(w, 0) for any edge touching at least one free variable
|
|
56
|
+
Returns ub[batch_size].
|
|
57
|
+
"""
|
|
58
|
+
ub = np.empty(batch_size)
|
|
59
|
+
for b in prange(batch_size):
|
|
60
|
+
total = 0.0
|
|
61
|
+
for i in range(n):
|
|
62
|
+
fi = fixed_vars[b, i]
|
|
63
|
+
for j in range(i + 1, n):
|
|
64
|
+
w = G_m[i, j]
|
|
65
|
+
if w == 0.0:
|
|
66
|
+
continue
|
|
67
|
+
fj = fixed_vars[b, j]
|
|
68
|
+
if fi >= 0 and fj >= 0:
|
|
69
|
+
if fi != fj:
|
|
70
|
+
total += w
|
|
71
|
+
else:
|
|
72
|
+
if w > 0.0:
|
|
73
|
+
total += w
|
|
74
|
+
ub[b] = total
|
|
75
|
+
return ub
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@njit(parallel=True, cache=True)
|
|
79
|
+
def _eval_leaves_cut(G_m, fixed_vars, n, batch_size):
|
|
80
|
+
vals = np.empty(batch_size)
|
|
81
|
+
for b in prange(batch_size):
|
|
82
|
+
cut = 0.0
|
|
83
|
+
for i in range(n):
|
|
84
|
+
bi = fixed_vars[b, i]
|
|
85
|
+
for j in range(i + 1, n):
|
|
86
|
+
if G_m[i, j] != 0.0 and bi != fixed_vars[b, j]:
|
|
87
|
+
cut += G_m[i, j]
|
|
88
|
+
vals[b] = cut
|
|
89
|
+
return vals
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@njit(parallel=True, cache=True)
|
|
93
|
+
def _eval_leaves_energy(G_m, fixed_vars, n, batch_size):
|
|
94
|
+
vals = np.empty(batch_size)
|
|
95
|
+
for b in prange(batch_size):
|
|
96
|
+
energy = 0.0
|
|
97
|
+
for i in range(n):
|
|
98
|
+
bi = fixed_vars[b, i]
|
|
99
|
+
for j in range(i + 1, n):
|
|
100
|
+
val = G_m[i, j]
|
|
101
|
+
energy += -val if bi == fixed_vars[b, j] else val
|
|
102
|
+
vals[b] = energy
|
|
103
|
+
return vals
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@njit(cache=True)
|
|
107
|
+
def _influence_scores(G_m, fixed_row, n):
|
|
108
|
+
"""Sum of absolute free-to-free edge weights for each free variable."""
|
|
109
|
+
scores = np.full(n, -1.0)
|
|
110
|
+
for i in range(n):
|
|
111
|
+
if fixed_row[i] >= 0:
|
|
112
|
+
continue
|
|
113
|
+
s = 0.0
|
|
114
|
+
for j in range(n):
|
|
115
|
+
if i == j or fixed_row[j] >= 0:
|
|
116
|
+
continue
|
|
117
|
+
ii = i if i < j else j
|
|
118
|
+
jj = j if i < j else i
|
|
119
|
+
s += abs(G_m[ii, jj])
|
|
120
|
+
scores[i] = s
|
|
121
|
+
return scores
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ---------------------------------------------------------------------------
|
|
125
|
+
# B&B loop
|
|
126
|
+
# ---------------------------------------------------------------------------
|
|
127
|
+
|
|
128
|
+
def _branch_and_bound(G_m, warm_theta, warm_energy, n, is_spin_glass,
|
|
129
|
+
verbose=True, time_limit=None):
|
|
130
|
+
best_bits = warm_theta.copy()
|
|
131
|
+
best_value = warm_energy
|
|
132
|
+
|
|
133
|
+
if verbose:
|
|
134
|
+
print(f"Warm-start incumbent: {best_value:.6f}")
|
|
135
|
+
|
|
136
|
+
root = np.full(n, -1, dtype=np.int8)
|
|
137
|
+
stack = [root]
|
|
138
|
+
|
|
139
|
+
t_start = time.monotonic()
|
|
140
|
+
nodes_explored = 0
|
|
141
|
+
nodes_pruned = 0
|
|
142
|
+
batch_cap = os.cpu_count() ** 2
|
|
143
|
+
|
|
144
|
+
while stack:
|
|
145
|
+
if time_limit is not None and (time.monotonic() - t_start) > time_limit:
|
|
146
|
+
if verbose:
|
|
147
|
+
print(f"Time limit reached. "
|
|
148
|
+
f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
|
|
149
|
+
return best_bits, best_value, False
|
|
150
|
+
|
|
151
|
+
batch_size = min(batch_cap, len(stack))
|
|
152
|
+
batch_nodes = [stack.pop() for _ in range(batch_size)]
|
|
153
|
+
batch_arr = np.array(batch_nodes, dtype=np.int8)
|
|
154
|
+
|
|
155
|
+
nodes_explored += batch_size
|
|
156
|
+
|
|
157
|
+
ubs = _upper_bound_batch(G_m, batch_arr, n, batch_size)
|
|
158
|
+
|
|
159
|
+
leaves = []
|
|
160
|
+
interior = []
|
|
161
|
+
for k in range(batch_size):
|
|
162
|
+
if ubs[k] <= best_value + 1e-9:
|
|
163
|
+
nodes_pruned += 1
|
|
164
|
+
continue
|
|
165
|
+
if int(np.sum(batch_arr[k] < 0)) == 0:
|
|
166
|
+
leaves.append(k)
|
|
167
|
+
else:
|
|
168
|
+
interior.append(k)
|
|
169
|
+
|
|
170
|
+
if leaves:
|
|
171
|
+
leaf_arr = batch_arr[np.array(leaves, dtype=np.int64)]
|
|
172
|
+
leaf_vals = (
|
|
173
|
+
_eval_leaves_energy(G_m, leaf_arr, n, len(leaves))
|
|
174
|
+
if is_spin_glass
|
|
175
|
+
else _eval_leaves_cut(G_m, leaf_arr, n, len(leaves))
|
|
176
|
+
)
|
|
177
|
+
best_leaf = int(np.argmax(leaf_vals))
|
|
178
|
+
if leaf_vals[best_leaf] > best_value:
|
|
179
|
+
best_value = float(leaf_vals[best_leaf])
|
|
180
|
+
best_bits = (leaf_arr[best_leaf] >= 1).copy()
|
|
181
|
+
if verbose:
|
|
182
|
+
print(f" New incumbent: {best_value:.6f}"
|
|
183
|
+
f" (nodes: {nodes_explored})")
|
|
184
|
+
|
|
185
|
+
for k in interior:
|
|
186
|
+
row = batch_arr[k]
|
|
187
|
+
scores = _influence_scores(G_m, row, n)
|
|
188
|
+
branch_var = int(np.argmax(scores))
|
|
189
|
+
warm_val = int(best_bits[branch_var])
|
|
190
|
+
for val in [warm_val, 1 - warm_val]:
|
|
191
|
+
child = row.copy()
|
|
192
|
+
child[branch_var] = np.int8(val)
|
|
193
|
+
stack.append(child)
|
|
194
|
+
|
|
195
|
+
elapsed = time.monotonic() - t_start
|
|
196
|
+
if verbose:
|
|
197
|
+
print(f"\nExact optimum: {best_value:.6f}")
|
|
198
|
+
print(f"Nodes explored: {nodes_explored} | "
|
|
199
|
+
f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
|
|
200
|
+
|
|
201
|
+
return best_bits, best_value, True
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
# ---------------------------------------------------------------------------
|
|
205
|
+
# Public API
|
|
206
|
+
# ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
def solve_maxcut_bnb(
|
|
209
|
+
G,
|
|
210
|
+
best_guess=None,
|
|
211
|
+
quality=None,
|
|
212
|
+
shots=None,
|
|
213
|
+
is_spin_glass=False,
|
|
214
|
+
anneal_t=None,
|
|
215
|
+
anneal_h=None,
|
|
216
|
+
repulsion_base=None,
|
|
217
|
+
is_maxcut_gpu=True,
|
|
218
|
+
verbose=True,
|
|
219
|
+
time_limit=None,
|
|
220
|
+
gray_iterations=None,
|
|
221
|
+
gray_seed_multiple=None,
|
|
222
|
+
):
|
|
223
|
+
"""
|
|
224
|
+
Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver then
|
|
225
|
+
certify via branch and bound with parallel Numba kernels.
|
|
226
|
+
|
|
227
|
+
Accepts the same G input as spin_glass_solver (NetworkX graph or dense
|
|
228
|
+
matrix) and the same warm-start formats (str, int, list, or None).
|
|
229
|
+
|
|
230
|
+
Parameters
|
|
231
|
+
----------
|
|
232
|
+
G : networkx.Graph or ndarray
|
|
233
|
+
best_guess : str | int | list[bool] | None
|
|
234
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
|
|
235
|
+
is_spin_glass, gray_iterations, gray_seed_multiple
|
|
236
|
+
Forwarded to spin_glass_solver when best_guess is None.
|
|
237
|
+
verbose : bool
|
|
238
|
+
time_limit : float or None
|
|
239
|
+
|
|
240
|
+
Returns
|
|
241
|
+
-------
|
|
242
|
+
bitstring : str
|
|
243
|
+
cut_value : float
|
|
244
|
+
partition : tuple(list, list)
|
|
245
|
+
min_energy : float
|
|
246
|
+
certified : bool
|
|
247
|
+
"""
|
|
248
|
+
if isinstance(G, nx.Graph):
|
|
249
|
+
nodes = list(G.nodes())
|
|
250
|
+
n_qubits = len(nodes)
|
|
251
|
+
G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
|
|
252
|
+
else:
|
|
253
|
+
n_qubits = len(G)
|
|
254
|
+
nodes = list(range(n_qubits))
|
|
255
|
+
G_m = np.asarray(G, dtype=dtype)
|
|
256
|
+
|
|
257
|
+
if n_qubits < 3:
|
|
258
|
+
if n_qubits == 0:
|
|
259
|
+
return "", 0, ([], []), 0, True
|
|
260
|
+
if n_qubits == 1:
|
|
261
|
+
return "0", 0, (nodes, []), 0, True
|
|
262
|
+
if n_qubits == 2:
|
|
263
|
+
weight = G_m[0, 1]
|
|
264
|
+
if weight < 0.0:
|
|
265
|
+
return "00", 0, (nodes, []), weight, True
|
|
266
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
267
|
+
|
|
268
|
+
bitstring = ""
|
|
269
|
+
cut_value = None
|
|
270
|
+
energy_value = None
|
|
271
|
+
if isinstance(best_guess, str):
|
|
272
|
+
bitstring = best_guess
|
|
273
|
+
elif isinstance(best_guess, int):
|
|
274
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
275
|
+
elif isinstance(best_guess, list):
|
|
276
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
277
|
+
else:
|
|
278
|
+
if verbose:
|
|
279
|
+
print("Running PyQrackIsing heuristic...")
|
|
280
|
+
from .spin_glass_solver import spin_glass_solver
|
|
281
|
+
kwargs = {}
|
|
282
|
+
if quality is not None: kwargs["quality"] = quality
|
|
283
|
+
if shots is not None: kwargs["shots"] = shots
|
|
284
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
285
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
286
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
287
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
288
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
289
|
+
kwargs["is_maxcut_gpu"] = is_maxcut_gpu
|
|
290
|
+
t0 = time.monotonic()
|
|
291
|
+
bitstring, cut_value, _, energy_value = spin_glass_solver(
|
|
292
|
+
G_m, is_spin_glass=is_spin_glass, **kwargs
|
|
293
|
+
)
|
|
294
|
+
if verbose:
|
|
295
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
296
|
+
|
|
297
|
+
best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
298
|
+
if is_spin_glass:
|
|
299
|
+
max_energy = compute_energy(best_theta, G_m, n_qubits) if energy_value is None else energy_value
|
|
300
|
+
elif cut_value is None:
|
|
301
|
+
max_energy = compute_cut(best_theta, G_m, n_qubits)
|
|
302
|
+
else:
|
|
303
|
+
max_energy = cut_value
|
|
304
|
+
|
|
305
|
+
if verbose:
|
|
306
|
+
print("Starting branch and bound...")
|
|
307
|
+
|
|
308
|
+
best_theta, max_energy, certified = _branch_and_bound(
|
|
309
|
+
G_m, best_theta, max_energy, n_qubits, is_spin_glass,
|
|
310
|
+
verbose=verbose, time_limit=time_limit,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
|
|
314
|
+
if is_spin_glass:
|
|
315
|
+
cut_value = compute_cut(best_theta, G_m, n_qubits)
|
|
316
|
+
min_energy = -max_energy
|
|
317
|
+
else:
|
|
318
|
+
cut_value = max_energy
|
|
319
|
+
min_energy = compute_energy(best_theta, G_m, n_qubits)
|
|
320
|
+
|
|
321
|
+
return bitstring, float(cut_value), (l, r), float(min_energy), certified
|
|
@@ -0,0 +1,322 @@
|
|
|
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
|
+
# Same parallelism strategy as bnb_exact.py; inner loops work from CSR arrays.
|
|
9
|
+
|
|
10
|
+
import time
|
|
11
|
+
import os
|
|
12
|
+
import networkx as nx
|
|
13
|
+
import numpy as np
|
|
14
|
+
from numba import njit, prange
|
|
15
|
+
from .maxcut_tfim_util import (
|
|
16
|
+
compute_cut_sparse,
|
|
17
|
+
compute_energy_sparse,
|
|
18
|
+
get_cut,
|
|
19
|
+
heuristic_threshold_sparse,
|
|
20
|
+
int_to_bitstring,
|
|
21
|
+
opencl_context,
|
|
22
|
+
to_scipy_sparse_upper_triangular,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
dtype = opencl_context.dtype
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
# Parallel kernels (sparse CSR)
|
|
30
|
+
# ---------------------------------------------------------------------------
|
|
31
|
+
|
|
32
|
+
@njit(parallel=True, cache=True)
|
|
33
|
+
def _upper_bound_batch_sparse(G_data, G_rows, G_cols, fixed_vars, n, batch_size):
|
|
34
|
+
"""
|
|
35
|
+
Parallel upper bound for a batch of B&B nodes (sparse CSR).
|
|
36
|
+
fixed_vars : (batch_size, n) int8, -1=free, 0/1=fixed.
|
|
37
|
+
"""
|
|
38
|
+
ub = np.empty(batch_size)
|
|
39
|
+
for b in prange(batch_size):
|
|
40
|
+
total = 0.0
|
|
41
|
+
for i in range(n):
|
|
42
|
+
fi = fixed_vars[b, i]
|
|
43
|
+
for r in range(G_rows[i], G_rows[i + 1]):
|
|
44
|
+
j = G_cols[r]
|
|
45
|
+
if j <= i:
|
|
46
|
+
continue
|
|
47
|
+
w = G_data[r]
|
|
48
|
+
if w == 0.0:
|
|
49
|
+
continue
|
|
50
|
+
fj = fixed_vars[b, j]
|
|
51
|
+
if fi >= 0 and fj >= 0:
|
|
52
|
+
if fi != fj:
|
|
53
|
+
total += w
|
|
54
|
+
else:
|
|
55
|
+
if w > 0.0:
|
|
56
|
+
total += w
|
|
57
|
+
ub[b] = total
|
|
58
|
+
return ub
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@njit(parallel=True, cache=True)
|
|
62
|
+
def _eval_leaves_cut_sparse(G_data, G_rows, G_cols, fixed_vars, n, batch_size):
|
|
63
|
+
vals = np.empty(batch_size)
|
|
64
|
+
for b in prange(batch_size):
|
|
65
|
+
cut = 0.0
|
|
66
|
+
for i in range(n):
|
|
67
|
+
bi = fixed_vars[b, i]
|
|
68
|
+
for r in range(G_rows[i], G_rows[i + 1]):
|
|
69
|
+
j = G_cols[r]
|
|
70
|
+
if j > i and G_data[r] != 0.0 and bi != fixed_vars[b, j]:
|
|
71
|
+
cut += G_data[r]
|
|
72
|
+
vals[b] = cut
|
|
73
|
+
return vals
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@njit(parallel=True, cache=True)
|
|
77
|
+
def _eval_leaves_energy_sparse(G_data, G_rows, G_cols, fixed_vars, n, batch_size):
|
|
78
|
+
vals = np.empty(batch_size)
|
|
79
|
+
for b in prange(batch_size):
|
|
80
|
+
energy = 0.0
|
|
81
|
+
for i in range(n):
|
|
82
|
+
bi = fixed_vars[b, i]
|
|
83
|
+
for r in range(G_rows[i], G_rows[i + 1]):
|
|
84
|
+
j = G_cols[r]
|
|
85
|
+
val = G_data[r]
|
|
86
|
+
energy += -val if bi == fixed_vars[b, j] else val
|
|
87
|
+
vals[b] = energy
|
|
88
|
+
return vals
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@njit(parallel=True, cache=True)
|
|
92
|
+
def _influence_scores_sparse(G_data, G_rows, G_cols, fixed_row, n):
|
|
93
|
+
scores = np.full(n, -1.0)
|
|
94
|
+
free_set = np.zeros(n, dtype=np.bool_)
|
|
95
|
+
for i in range(n):
|
|
96
|
+
if fixed_row[i] < 0:
|
|
97
|
+
free_set[i] = True
|
|
98
|
+
for i in prange(n):
|
|
99
|
+
if not free_set[i]:
|
|
100
|
+
continue
|
|
101
|
+
s = 0.0
|
|
102
|
+
for r in range(G_rows[i], G_rows[i + 1]):
|
|
103
|
+
j = G_cols[r]
|
|
104
|
+
if free_set[j]:
|
|
105
|
+
s += abs(G_data[r])
|
|
106
|
+
# reverse edges (j < i stored in row j)
|
|
107
|
+
for j in range(i):
|
|
108
|
+
if not free_set[j]:
|
|
109
|
+
continue
|
|
110
|
+
for r in range(G_rows[j], G_rows[j + 1]):
|
|
111
|
+
if G_cols[r] == i:
|
|
112
|
+
s += abs(G_data[r])
|
|
113
|
+
break
|
|
114
|
+
scores[i] = s
|
|
115
|
+
return scores
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------------------
|
|
119
|
+
# B&B loop
|
|
120
|
+
# ---------------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def _branch_and_bound_sparse(G_data, G_rows, G_cols, warm_theta, warm_energy,
|
|
123
|
+
n, is_spin_glass, verbose=True, time_limit=None):
|
|
124
|
+
best_bits = warm_theta.copy()
|
|
125
|
+
best_value = warm_energy
|
|
126
|
+
|
|
127
|
+
if verbose:
|
|
128
|
+
print(f"Warm-start incumbent: {best_value:.6f}")
|
|
129
|
+
|
|
130
|
+
root = np.full(n, -1, dtype=np.int8)
|
|
131
|
+
stack = [root]
|
|
132
|
+
|
|
133
|
+
t_start = time.monotonic()
|
|
134
|
+
nodes_explored = 0
|
|
135
|
+
nodes_pruned = 0
|
|
136
|
+
batch_cap = os.cpu_count() ** 2
|
|
137
|
+
|
|
138
|
+
while stack:
|
|
139
|
+
if time_limit is not None and (time.monotonic() - t_start) > time_limit:
|
|
140
|
+
if verbose:
|
|
141
|
+
print(f"Time limit reached. "
|
|
142
|
+
f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
|
|
143
|
+
return best_bits, best_value, False
|
|
144
|
+
|
|
145
|
+
batch_size = min(batch_cap, len(stack))
|
|
146
|
+
batch_nodes = [stack.pop() for _ in range(batch_size)]
|
|
147
|
+
batch_arr = np.array(batch_nodes, dtype=np.int8)
|
|
148
|
+
|
|
149
|
+
nodes_explored += batch_size
|
|
150
|
+
|
|
151
|
+
ubs = _upper_bound_batch_sparse(G_data, G_rows, G_cols,
|
|
152
|
+
batch_arr, n, batch_size)
|
|
153
|
+
|
|
154
|
+
leaves = []
|
|
155
|
+
interior = []
|
|
156
|
+
for k in range(batch_size):
|
|
157
|
+
if ubs[k] <= best_value + 1e-9:
|
|
158
|
+
nodes_pruned += 1
|
|
159
|
+
continue
|
|
160
|
+
if int(np.sum(batch_arr[k] < 0)) == 0:
|
|
161
|
+
leaves.append(k)
|
|
162
|
+
else:
|
|
163
|
+
interior.append(k)
|
|
164
|
+
|
|
165
|
+
if leaves:
|
|
166
|
+
leaf_arr = batch_arr[np.array(leaves, dtype=np.int64)]
|
|
167
|
+
leaf_vals = (
|
|
168
|
+
_eval_leaves_energy_sparse(G_data, G_rows, G_cols,
|
|
169
|
+
leaf_arr, n, len(leaves))
|
|
170
|
+
if is_spin_glass
|
|
171
|
+
else _eval_leaves_cut_sparse(G_data, G_rows, G_cols,
|
|
172
|
+
leaf_arr, n, len(leaves))
|
|
173
|
+
)
|
|
174
|
+
best_leaf = int(np.argmax(leaf_vals))
|
|
175
|
+
if leaf_vals[best_leaf] > best_value:
|
|
176
|
+
best_value = float(leaf_vals[best_leaf])
|
|
177
|
+
best_bits = (leaf_arr[best_leaf] >= 1).copy()
|
|
178
|
+
if verbose:
|
|
179
|
+
print(f" New incumbent: {best_value:.6f}"
|
|
180
|
+
f" (nodes: {nodes_explored})")
|
|
181
|
+
|
|
182
|
+
for k in interior:
|
|
183
|
+
row = batch_arr[k]
|
|
184
|
+
scores = _influence_scores_sparse(G_data, G_rows, G_cols, row, n)
|
|
185
|
+
branch_var = int(np.argmax(scores))
|
|
186
|
+
warm_val = int(best_bits[branch_var])
|
|
187
|
+
for val in [warm_val, 1 - warm_val]:
|
|
188
|
+
child = row.copy()
|
|
189
|
+
child[branch_var] = np.int8(val)
|
|
190
|
+
stack.append(child)
|
|
191
|
+
|
|
192
|
+
elapsed = time.monotonic() - t_start
|
|
193
|
+
if verbose:
|
|
194
|
+
print(f"\nExact optimum: {best_value:.6f}")
|
|
195
|
+
print(f"Nodes explored: {nodes_explored} | "
|
|
196
|
+
f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
|
|
197
|
+
|
|
198
|
+
return best_bits, best_value, True
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
# Public API
|
|
203
|
+
# ---------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
def solve_maxcut_bnb_sparse(
|
|
206
|
+
G,
|
|
207
|
+
best_guess=None,
|
|
208
|
+
quality=None,
|
|
209
|
+
shots=None,
|
|
210
|
+
is_spin_glass=False,
|
|
211
|
+
anneal_t=None,
|
|
212
|
+
anneal_h=None,
|
|
213
|
+
repulsion_base=None,
|
|
214
|
+
is_maxcut_gpu=True,
|
|
215
|
+
verbose=True,
|
|
216
|
+
time_limit=None,
|
|
217
|
+
gray_iterations=None,
|
|
218
|
+
gray_seed_multiple=None,
|
|
219
|
+
):
|
|
220
|
+
"""
|
|
221
|
+
Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver_sparse
|
|
222
|
+
then certify via branch and bound with parallel Numba kernels.
|
|
223
|
+
|
|
224
|
+
Accepts the same G input as spin_glass_solver_sparse (NetworkX graph or
|
|
225
|
+
scipy CSR matrix) and the same warm-start formats (str, int, list, None).
|
|
226
|
+
|
|
227
|
+
Parameters
|
|
228
|
+
----------
|
|
229
|
+
G : networkx.Graph or scipy CSR matrix
|
|
230
|
+
best_guess : str | int | list[bool] | None
|
|
231
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
|
|
232
|
+
is_spin_glass, gray_iterations, gray_seed_multiple
|
|
233
|
+
Forwarded to spin_glass_solver_sparse when best_guess is None.
|
|
234
|
+
verbose : bool
|
|
235
|
+
time_limit : float or None
|
|
236
|
+
|
|
237
|
+
Returns
|
|
238
|
+
-------
|
|
239
|
+
bitstring : str
|
|
240
|
+
cut_value : float
|
|
241
|
+
partition : tuple(list, list)
|
|
242
|
+
min_energy : float
|
|
243
|
+
certified : bool
|
|
244
|
+
"""
|
|
245
|
+
if isinstance(G, nx.Graph):
|
|
246
|
+
nodes = list(G.nodes())
|
|
247
|
+
n_qubits = len(nodes)
|
|
248
|
+
G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
|
|
249
|
+
else:
|
|
250
|
+
n_qubits = G.shape[0]
|
|
251
|
+
nodes = list(range(n_qubits))
|
|
252
|
+
G_m = G
|
|
253
|
+
|
|
254
|
+
if n_qubits < 3:
|
|
255
|
+
if n_qubits == 0:
|
|
256
|
+
return "", 0, ([], []), 0, True
|
|
257
|
+
if n_qubits == 1:
|
|
258
|
+
return "0", 0, (nodes, []), 0, True
|
|
259
|
+
if n_qubits == 2:
|
|
260
|
+
weight = G_m[0, 1]
|
|
261
|
+
if weight < 0.0:
|
|
262
|
+
return "00", 0, (nodes, []), weight, True
|
|
263
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
264
|
+
|
|
265
|
+
G_data = np.asarray(G_m.data, dtype=np.float64)
|
|
266
|
+
G_rows = np.asarray(G_m.indptr, dtype=np.int64)
|
|
267
|
+
G_cols = np.asarray(G_m.indices, dtype=np.int64)
|
|
268
|
+
|
|
269
|
+
bitstring = ""
|
|
270
|
+
cut_value = None
|
|
271
|
+
energy_value = None
|
|
272
|
+
if isinstance(best_guess, str):
|
|
273
|
+
bitstring = best_guess
|
|
274
|
+
elif isinstance(best_guess, int):
|
|
275
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
276
|
+
elif isinstance(best_guess, list):
|
|
277
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
278
|
+
else:
|
|
279
|
+
if verbose:
|
|
280
|
+
print("Running PyQrackIsing heuristic...")
|
|
281
|
+
from .spin_glass_solver_sparse import spin_glass_solver_sparse
|
|
282
|
+
kwargs = {}
|
|
283
|
+
if quality is not None: kwargs["quality"] = quality
|
|
284
|
+
if shots is not None: kwargs["shots"] = shots
|
|
285
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
286
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
287
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
288
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
289
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
290
|
+
kwargs["is_maxcut_gpu"] = is_maxcut_gpu
|
|
291
|
+
t0 = time.monotonic()
|
|
292
|
+
bitstring, cut_value, _, energy_value = spin_glass_solver_sparse(
|
|
293
|
+
G_m, is_spin_glass=is_spin_glass, **kwargs
|
|
294
|
+
)
|
|
295
|
+
if verbose:
|
|
296
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
297
|
+
|
|
298
|
+
best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
299
|
+
if is_spin_glass:
|
|
300
|
+
max_energy = compute_energy_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits) if energy_value is None else energy_value
|
|
301
|
+
elif cut_value is None:
|
|
302
|
+
max_energy = compute_cut_sparse(best_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
|
|
303
|
+
else:
|
|
304
|
+
max_energy = cut_value
|
|
305
|
+
|
|
306
|
+
if verbose:
|
|
307
|
+
print("Starting branch and bound...")
|
|
308
|
+
|
|
309
|
+
best_theta, max_energy, certified = _branch_and_bound_sparse(
|
|
310
|
+
G_data, G_rows, G_cols, best_theta, max_energy, n_qubits, is_spin_glass,
|
|
311
|
+
verbose=verbose, time_limit=time_limit,
|
|
312
|
+
)
|
|
313
|
+
|
|
314
|
+
bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
|
|
315
|
+
if is_spin_glass:
|
|
316
|
+
cut_value = compute_cut_sparse(best_theta, G_data, G_rows, G_cols, n_qubits)
|
|
317
|
+
min_energy = -max_energy
|
|
318
|
+
else:
|
|
319
|
+
cut_value = max_energy
|
|
320
|
+
min_energy = compute_energy_sparse(best_theta, G_data, G_rows, G_cols, n_qubits)
|
|
321
|
+
|
|
322
|
+
return bitstring, float(cut_value), (l, r), float(min_energy), certified
|
|
@@ -0,0 +1,292 @@
|
|
|
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
|
+
# Same parallelism strategy as bnb_exact.py; inner loops call G_func.
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
import os
|
|
13
|
+
import numpy as np
|
|
14
|
+
from numba import njit, prange
|
|
15
|
+
from .maxcut_tfim_util import (
|
|
16
|
+
compute_cut_streaming,
|
|
17
|
+
compute_energy_streaming,
|
|
18
|
+
get_cut,
|
|
19
|
+
heuristic_threshold,
|
|
20
|
+
int_to_bitstring,
|
|
21
|
+
opencl_context,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
dtype = opencl_context.dtype
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# ---------------------------------------------------------------------------
|
|
28
|
+
# Parallel kernels (streaming)
|
|
29
|
+
# ---------------------------------------------------------------------------
|
|
30
|
+
|
|
31
|
+
@njit(parallel=True, cache=True)
|
|
32
|
+
def _upper_bound_batch_streaming(G_func, nodes, fixed_vars, n, batch_size):
|
|
33
|
+
ub = np.empty(batch_size)
|
|
34
|
+
for b in prange(batch_size):
|
|
35
|
+
total = 0.0
|
|
36
|
+
for i in range(n):
|
|
37
|
+
fi = fixed_vars[b, i]
|
|
38
|
+
for j in range(i + 1, n):
|
|
39
|
+
w = G_func(nodes[i], nodes[j])
|
|
40
|
+
if w == 0.0:
|
|
41
|
+
continue
|
|
42
|
+
fj = fixed_vars[b, j]
|
|
43
|
+
if fi >= 0 and fj >= 0:
|
|
44
|
+
if fi != fj:
|
|
45
|
+
total += w
|
|
46
|
+
else:
|
|
47
|
+
if w > 0.0:
|
|
48
|
+
total += w
|
|
49
|
+
ub[b] = total
|
|
50
|
+
return ub
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@njit(parallel=True, cache=True)
|
|
54
|
+
def _eval_leaves_cut_streaming(G_func, nodes, fixed_vars, n, batch_size):
|
|
55
|
+
vals = np.empty(batch_size)
|
|
56
|
+
for b in prange(batch_size):
|
|
57
|
+
cut = 0.0
|
|
58
|
+
for i in range(n):
|
|
59
|
+
bi = fixed_vars[b, i]
|
|
60
|
+
for j in range(i + 1, n):
|
|
61
|
+
w = G_func(nodes[i], nodes[j])
|
|
62
|
+
if w != 0.0 and bi != fixed_vars[b, j]:
|
|
63
|
+
cut += w
|
|
64
|
+
vals[b] = cut
|
|
65
|
+
return vals
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@njit(parallel=True, cache=True)
|
|
69
|
+
def _eval_leaves_energy_streaming(G_func, nodes, fixed_vars, n, batch_size):
|
|
70
|
+
vals = np.empty(batch_size)
|
|
71
|
+
for b in prange(batch_size):
|
|
72
|
+
energy = 0.0
|
|
73
|
+
for i in range(n):
|
|
74
|
+
bi = fixed_vars[b, i]
|
|
75
|
+
for j in range(i + 1, n):
|
|
76
|
+
val = G_func(nodes[i], nodes[j])
|
|
77
|
+
energy += -val if bi == fixed_vars[b, j] else val
|
|
78
|
+
vals[b] = energy
|
|
79
|
+
return vals
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@njit(cache=True)
|
|
83
|
+
def _influence_scores_streaming(G_func, nodes, fixed_row, n):
|
|
84
|
+
scores = np.full(n, -1.0)
|
|
85
|
+
for i in range(n):
|
|
86
|
+
if fixed_row[i] >= 0:
|
|
87
|
+
continue
|
|
88
|
+
s = 0.0
|
|
89
|
+
for j in range(n):
|
|
90
|
+
if i == j or fixed_row[j] >= 0:
|
|
91
|
+
continue
|
|
92
|
+
ii = i if i < j else j
|
|
93
|
+
jj = j if i < j else i
|
|
94
|
+
s += abs(G_func(nodes[ii], nodes[jj]))
|
|
95
|
+
scores[i] = s
|
|
96
|
+
return scores
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------------------
|
|
100
|
+
# B&B loop
|
|
101
|
+
# ---------------------------------------------------------------------------
|
|
102
|
+
|
|
103
|
+
def _branch_and_bound_streaming(G_func, nodes, warm_theta, warm_energy, n,
|
|
104
|
+
is_spin_glass, verbose=True, time_limit=None):
|
|
105
|
+
best_bits = warm_theta.copy()
|
|
106
|
+
best_value = warm_energy
|
|
107
|
+
|
|
108
|
+
if verbose:
|
|
109
|
+
print(f"Warm-start incumbent: {best_value:.6f}")
|
|
110
|
+
|
|
111
|
+
root = np.full(n, -1, dtype=np.int8)
|
|
112
|
+
stack = [root]
|
|
113
|
+
|
|
114
|
+
t_start = time.monotonic()
|
|
115
|
+
nodes_explored = 0
|
|
116
|
+
nodes_pruned = 0
|
|
117
|
+
batch_cap = os.cpu_count() ** 2
|
|
118
|
+
|
|
119
|
+
while stack:
|
|
120
|
+
if time_limit is not None and (time.monotonic() - t_start) > time_limit:
|
|
121
|
+
if verbose:
|
|
122
|
+
print(f"Time limit reached. "
|
|
123
|
+
f"Nodes: {nodes_explored}, Pruned: {nodes_pruned}")
|
|
124
|
+
return best_bits, best_value, False
|
|
125
|
+
|
|
126
|
+
batch_size = min(batch_cap, len(stack))
|
|
127
|
+
batch_nodes = [stack.pop() for _ in range(batch_size)]
|
|
128
|
+
batch_arr = np.array(batch_nodes, dtype=np.int8)
|
|
129
|
+
|
|
130
|
+
nodes_explored += batch_size
|
|
131
|
+
|
|
132
|
+
ubs = _upper_bound_batch_streaming(G_func, nodes, batch_arr, n, batch_size)
|
|
133
|
+
|
|
134
|
+
leaves = []
|
|
135
|
+
interior = []
|
|
136
|
+
for k in range(batch_size):
|
|
137
|
+
if ubs[k] <= best_value + 1e-9:
|
|
138
|
+
nodes_pruned += 1
|
|
139
|
+
continue
|
|
140
|
+
if int(np.sum(batch_arr[k] < 0)) == 0:
|
|
141
|
+
leaves.append(k)
|
|
142
|
+
else:
|
|
143
|
+
interior.append(k)
|
|
144
|
+
|
|
145
|
+
if leaves:
|
|
146
|
+
leaf_arr = batch_arr[np.array(leaves, dtype=np.int64)]
|
|
147
|
+
leaf_vals = (
|
|
148
|
+
_eval_leaves_energy_streaming(G_func, nodes, leaf_arr, n, len(leaves))
|
|
149
|
+
if is_spin_glass
|
|
150
|
+
else _eval_leaves_cut_streaming(G_func, nodes, leaf_arr, n, len(leaves))
|
|
151
|
+
)
|
|
152
|
+
best_leaf = int(np.argmax(leaf_vals))
|
|
153
|
+
if leaf_vals[best_leaf] > best_value:
|
|
154
|
+
best_value = float(leaf_vals[best_leaf])
|
|
155
|
+
best_bits = (leaf_arr[best_leaf] >= 1).copy()
|
|
156
|
+
if verbose:
|
|
157
|
+
print(f" New incumbent: {best_value:.6f}"
|
|
158
|
+
f" (nodes: {nodes_explored})")
|
|
159
|
+
|
|
160
|
+
for k in interior:
|
|
161
|
+
row = batch_arr[k]
|
|
162
|
+
scores = _influence_scores_streaming(G_func, nodes, row, n)
|
|
163
|
+
branch_var = int(np.argmax(scores))
|
|
164
|
+
warm_val = int(best_bits[branch_var])
|
|
165
|
+
for val in [warm_val, 1 - warm_val]:
|
|
166
|
+
child = row.copy()
|
|
167
|
+
child[branch_var] = np.int8(val)
|
|
168
|
+
stack.append(child)
|
|
169
|
+
|
|
170
|
+
elapsed = time.monotonic() - t_start
|
|
171
|
+
if verbose:
|
|
172
|
+
print(f"\nExact optimum: {best_value:.6f}")
|
|
173
|
+
print(f"Nodes explored: {nodes_explored} | "
|
|
174
|
+
f"Pruned: {nodes_pruned} | Time: {elapsed:.3f}s")
|
|
175
|
+
|
|
176
|
+
return best_bits, best_value, True
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
# Public API
|
|
181
|
+
# ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
def solve_maxcut_bnb_streaming(
|
|
184
|
+
G_func,
|
|
185
|
+
nodes,
|
|
186
|
+
best_guess=None,
|
|
187
|
+
quality=None,
|
|
188
|
+
shots=None,
|
|
189
|
+
is_spin_glass=False,
|
|
190
|
+
anneal_t=None,
|
|
191
|
+
anneal_h=None,
|
|
192
|
+
repulsion_base=None,
|
|
193
|
+
verbose=True,
|
|
194
|
+
time_limit=None,
|
|
195
|
+
gray_iterations=None,
|
|
196
|
+
gray_seed_multiple=None,
|
|
197
|
+
):
|
|
198
|
+
"""
|
|
199
|
+
Exact MAXCUT/spin-glass solver: warm-start from spin_glass_solver_streaming
|
|
200
|
+
then certify via branch and bound with parallel Numba kernels.
|
|
201
|
+
|
|
202
|
+
Accepts the same G_func + nodes input as spin_glass_solver_streaming and
|
|
203
|
+
the same warm-start formats (str, int, list, or None).
|
|
204
|
+
|
|
205
|
+
Parameters
|
|
206
|
+
----------
|
|
207
|
+
G_func : callable(u, v) -> float
|
|
208
|
+
Edge weight function (Numba-callable). Returns 0.0 for absent edges.
|
|
209
|
+
nodes : array-like
|
|
210
|
+
Ordered sequence of node identifiers passed to G_func.
|
|
211
|
+
best_guess : str | int | list[bool] | None
|
|
212
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_spin_glass,
|
|
213
|
+
gray_iterations, gray_seed_multiple
|
|
214
|
+
Forwarded to spin_glass_solver_streaming when best_guess is None.
|
|
215
|
+
verbose : bool
|
|
216
|
+
time_limit : float or None
|
|
217
|
+
|
|
218
|
+
Returns
|
|
219
|
+
-------
|
|
220
|
+
bitstring : str
|
|
221
|
+
cut_value : float
|
|
222
|
+
partition : tuple(list, list)
|
|
223
|
+
min_energy : float
|
|
224
|
+
certified : bool
|
|
225
|
+
"""
|
|
226
|
+
nodes = np.asarray(nodes)
|
|
227
|
+
n_qubits = len(nodes)
|
|
228
|
+
|
|
229
|
+
if n_qubits < 3:
|
|
230
|
+
if n_qubits == 0:
|
|
231
|
+
return "", 0, ([], []), 0, True
|
|
232
|
+
if n_qubits == 1:
|
|
233
|
+
return "0", 0, (list(nodes), []), 0, True
|
|
234
|
+
if n_qubits == 2:
|
|
235
|
+
weight = G_func(nodes[0], nodes[1])
|
|
236
|
+
if weight < 0.0:
|
|
237
|
+
return "00", 0, (list(nodes), []), weight, True
|
|
238
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
239
|
+
|
|
240
|
+
bitstring = ""
|
|
241
|
+
cut_value = None
|
|
242
|
+
energy_value = None
|
|
243
|
+
if isinstance(best_guess, str):
|
|
244
|
+
bitstring = best_guess
|
|
245
|
+
elif isinstance(best_guess, int):
|
|
246
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
247
|
+
elif isinstance(best_guess, list):
|
|
248
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
249
|
+
else:
|
|
250
|
+
if verbose:
|
|
251
|
+
print("Running PyQrackIsing heuristic...")
|
|
252
|
+
from .spin_glass_solver_streaming import spin_glass_solver_streaming
|
|
253
|
+
kwargs = {}
|
|
254
|
+
if quality is not None: kwargs["quality"] = quality
|
|
255
|
+
if shots is not None: kwargs["shots"] = shots
|
|
256
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
257
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
258
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
259
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
260
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
261
|
+
t0 = time.monotonic()
|
|
262
|
+
bitstring, cut_value, _, energy_value = spin_glass_solver_streaming(
|
|
263
|
+
G_func, nodes, is_spin_glass=is_spin_glass, **kwargs
|
|
264
|
+
)
|
|
265
|
+
if verbose:
|
|
266
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
267
|
+
|
|
268
|
+
best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
269
|
+
if is_spin_glass:
|
|
270
|
+
max_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits) if energy_value is None else energy_value
|
|
271
|
+
elif cut_value is None:
|
|
272
|
+
max_energy = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
|
|
273
|
+
else:
|
|
274
|
+
max_energy = cut_value
|
|
275
|
+
|
|
276
|
+
if verbose:
|
|
277
|
+
print("Starting branch and bound...")
|
|
278
|
+
|
|
279
|
+
best_theta, max_energy, certified = _branch_and_bound_streaming(
|
|
280
|
+
G_func, nodes, best_theta, max_energy, n_qubits, is_spin_glass,
|
|
281
|
+
verbose=verbose, time_limit=time_limit,
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
bitstring, l, r = get_cut(best_theta, list(nodes), n_qubits)
|
|
285
|
+
if is_spin_glass:
|
|
286
|
+
cut_value = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
|
|
287
|
+
min_energy = -max_energy
|
|
288
|
+
else:
|
|
289
|
+
cut_value = max_energy
|
|
290
|
+
min_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
|
|
291
|
+
|
|
292
|
+
return bitstring, float(cut_value), (l, r), float(min_energy), certified
|
|
@@ -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_bnb.py
|
|
16
|
+
pyqrackising/solve_maxcut_bnb_sparse.py
|
|
17
|
+
pyqrackising/solve_maxcut_bnb_streaming.py
|
|
15
18
|
pyqrackising/solve_maxcut_exact.py
|
|
16
19
|
pyqrackising/solve_maxcut_exact_sparse.py
|
|
17
20
|
pyqrackising/solve_maxcut_exact_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.
|
|
10
|
+
version="9.13.0",
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|