PyQrackIsing 9.17.0__py3-none-any.whl
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/__init__.py +22 -0
- pyqrackising/convert_tensor_network_to_tsp.py +93 -0
- pyqrackising/generate_tfim_samples.py +351 -0
- pyqrackising/kernels.cl +1238 -0
- pyqrackising/local_search.py +401 -0
- pyqrackising/maxcut_tfim.py +474 -0
- pyqrackising/maxcut_tfim_sparse.py +518 -0
- pyqrackising/maxcut_tfim_streaming.py +295 -0
- pyqrackising/maxcut_tfim_util.py +791 -0
- pyqrackising/otoc.py +248 -0
- pyqrackising/solve_maxcut_bnb.py +321 -0
- pyqrackising/solve_maxcut_bnb_sparse.py +322 -0
- pyqrackising/solve_maxcut_bnb_streaming.py +292 -0
- pyqrackising/solve_maxcut_exact.py +305 -0
- pyqrackising/solve_maxcut_exact_sparse.py +227 -0
- pyqrackising/solve_maxcut_exact_streaming.py +217 -0
- pyqrackising/solve_qubo.py +133 -0
- pyqrackising/spin_glass_solver.py +545 -0
- pyqrackising/spin_glass_solver_hybrid.py +53 -0
- pyqrackising/spin_glass_solver_sparse.py +611 -0
- pyqrackising/spin_glass_solver_streaming.py +294 -0
- pyqrackising/tfim_magnetization.py +23 -0
- pyqrackising/tfim_square_magnetization.py +22 -0
- pyqrackising/tsp.py +2014 -0
- pyqrackising/tsp_maxcut.py +312 -0
- pyqrackising-9.17.0.dist-info/METADATA +299 -0
- pyqrackising-9.17.0.dist-info/RECORD +30 -0
- pyqrackising-9.17.0.dist-info/WHEEL +5 -0
- pyqrackising-9.17.0.dist-info/licenses/LICENSE.md +165 -0
- pyqrackising-9.17.0.dist-info/top_level.txt +1 -0
|
@@ -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
|