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,305 @@
|
|
|
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
|
+
# maxcut_exact.py — exact MAXCUT solver via weighted MaxSAT (RC2 / PySAT)
|
|
7
|
+
#
|
|
8
|
+
# Uses the RC2 MaxSAT solver from PySAT (MIT license, compatible with LGPL).
|
|
9
|
+
# PySAT: https://pysathq.github.io — pip install python-sat
|
|
10
|
+
#
|
|
11
|
+
# Encoding
|
|
12
|
+
# --------
|
|
13
|
+
# For each edge (i, j, w):
|
|
14
|
+
# Introduce a selector variable s_ij (var index n + edge_idx + 1).
|
|
15
|
+
# Hard clauses encode s_ij <=> (x_i XOR x_j):
|
|
16
|
+
# [ x_i v x_j v ~s_ij ] xi=0,xj=0 -> s=0 (always added)
|
|
17
|
+
# [~x_i v ~x_j v ~s_ij ] xi=1,xj=1 -> s=0 (always added)
|
|
18
|
+
# [~x_i v x_j v s_ij ] xi=1,xj=0 -> s=1 (only when min_w < 0)
|
|
19
|
+
# [ x_i v ~x_j v s_ij ] xi=0,xj=1 -> s=1 (only when min_w < 0)
|
|
20
|
+
# When all weights are non-negative RC2 already wants s=1 to claim the
|
|
21
|
+
# reward, so the ->s clauses are redundant and omitted to halve the
|
|
22
|
+
# clause count. When negative edges are present the ->s clauses are
|
|
23
|
+
# critical: without them s can stay 0 while the edge is cut, letting
|
|
24
|
+
# RC2 fraudulently claim the [-s] soft reward.
|
|
25
|
+
#
|
|
26
|
+
# Positive weight w > 0: we *want* the edge cut.
|
|
27
|
+
# Soft clause [s_ij] with weight round(w * SCALE).
|
|
28
|
+
# Contribution to objective when satisfied: +w.
|
|
29
|
+
#
|
|
30
|
+
# Negative weight w < 0: we *want* the edge NOT cut.
|
|
31
|
+
# Soft clause [~s_ij] with weight round(-w * SCALE).
|
|
32
|
+
# Equivalently: penalise cutting it by |w|.
|
|
33
|
+
# Baseline offset += w (this weight is lost if the edge is cut).
|
|
34
|
+
#
|
|
35
|
+
# The MaxSAT objective maximises sum of satisfied soft clause weights.
|
|
36
|
+
# RC2 minimises cost = total_weight - satisfied_weight, so:
|
|
37
|
+
# cut_value = (total_pos_weight - rc2.cost / SCALE) + baseline_neg
|
|
38
|
+
#
|
|
39
|
+
# Warm start
|
|
40
|
+
# ----------
|
|
41
|
+
# RC2 does not expose a direct assignment-injection API, but the underlying
|
|
42
|
+
# SAT oracle (Glucose3 by default) supports phase-saving / polarity hints.
|
|
43
|
+
# We inject the warm-start assignment by adding temporary unit soft clauses
|
|
44
|
+
# of very high weight for each variable set to its warm-start value, solve
|
|
45
|
+
# once to seed the oracle's internal state, then retract them and solve to
|
|
46
|
+
# optimality. In practice, because PyQrackIsing's warm start is already
|
|
47
|
+
# near-optimal, RC2's core-guided search terminates almost immediately.
|
|
48
|
+
|
|
49
|
+
import time
|
|
50
|
+
import networkx as nx
|
|
51
|
+
import numpy as np
|
|
52
|
+
from .maxcut_tfim_util import (
|
|
53
|
+
compute_cut,
|
|
54
|
+
compute_energy,
|
|
55
|
+
get_cut,
|
|
56
|
+
int_to_bitstring,
|
|
57
|
+
opencl_context,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
from pysat.examples.rc2 import RC2
|
|
62
|
+
from pysat.formula import WCNF
|
|
63
|
+
_HAVE_PYSAT = True
|
|
64
|
+
except ImportError:
|
|
65
|
+
_HAVE_PYSAT = False
|
|
66
|
+
|
|
67
|
+
dtype = opencl_context.dtype
|
|
68
|
+
|
|
69
|
+
# Integer scaling factor: edge weights are multiplied by this and rounded
|
|
70
|
+
# to integers for the WCNF encoding. 2**32 gives sub-ppb precision for
|
|
71
|
+
# weights in the typical PyQrackIsing range of [-1, 1] and is half 64-bit
|
|
72
|
+
# integer precision.
|
|
73
|
+
_SCALE = 2 ** 32
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---------------------------------------------------------------------------
|
|
77
|
+
# Encoding helpers
|
|
78
|
+
# ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
def _build_wcnf(edges, n, has_negative):
|
|
81
|
+
"""
|
|
82
|
+
Build a WCNF formula for MAXCUT on n nodes with the given edge list.
|
|
83
|
+
|
|
84
|
+
edges : list of (i, j, w) — zero-indexed node indices, float weight
|
|
85
|
+
n : number of nodes
|
|
86
|
+
|
|
87
|
+
Returns (wcnf, total_pos_scaled, baseline_neg) where:
|
|
88
|
+
total_pos_scaled = sum of scaled weights of positive soft clauses
|
|
89
|
+
baseline_neg = sum of w for all negative-weight edges
|
|
90
|
+
(cut value offset; cutting a negative edge loses |w|)
|
|
91
|
+
"""
|
|
92
|
+
wcnf = WCNF()
|
|
93
|
+
total_pos_scaled = 0
|
|
94
|
+
neg_scaled_total = 0
|
|
95
|
+
baseline_neg = 0.0
|
|
96
|
+
|
|
97
|
+
for idx, (i, j, w) in enumerate(edges):
|
|
98
|
+
xi = i + 1 # 1-indexed SAT variable for node i
|
|
99
|
+
xj = j + 1 # 1-indexed SAT variable for node j
|
|
100
|
+
s = n + idx + 1 # selector variable for this edge
|
|
101
|
+
|
|
102
|
+
# s=1 when edge not cut is always suboptimal for positive edges,
|
|
103
|
+
# so the two ->s direction clauses are only needed when negative
|
|
104
|
+
# edges are present (otherwise they would double the clause count
|
|
105
|
+
# for no benefit).
|
|
106
|
+
wcnf.append([ xi, xj, -s]) # xi=0,xj=0 -> s=0
|
|
107
|
+
wcnf.append([-xi, -xj, -s]) # xi=1,xj=1 -> s=0
|
|
108
|
+
if has_negative:
|
|
109
|
+
wcnf.append([-xi, xj, s]) # xi=1,xj=0 -> s=1
|
|
110
|
+
wcnf.append([ xi, -xj, s]) # xi=0,xj=1 -> s=1
|
|
111
|
+
|
|
112
|
+
if w >= 0.0:
|
|
113
|
+
iw = max(1, int(round(w * _SCALE)))
|
|
114
|
+
total_pos_scaled += iw
|
|
115
|
+
wcnf.append([s], weight=iw) # soft: want edge cut
|
|
116
|
+
else:
|
|
117
|
+
iw = max(1, int(round(-w * _SCALE)))
|
|
118
|
+
baseline_neg += w # this is already negative
|
|
119
|
+
neg_scaled_total += iw
|
|
120
|
+
wcnf.append([-s], weight=iw) # soft: want edge NOT cut
|
|
121
|
+
|
|
122
|
+
return wcnf, total_pos_scaled, neg_scaled_total, baseline_neg
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _model_to_bits(model, n):
|
|
126
|
+
"""Convert a PySAT model (list of signed literals) to a bool array."""
|
|
127
|
+
bits = np.zeros(n, dtype=np.bool_)
|
|
128
|
+
for lit in model:
|
|
129
|
+
var = abs(lit) - 1 # back to 0-indexed
|
|
130
|
+
if 0 <= var < n:
|
|
131
|
+
bits[var] = lit > 0
|
|
132
|
+
return bits
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ---------------------------------------------------------------------------
|
|
136
|
+
# Public API
|
|
137
|
+
# ---------------------------------------------------------------------------
|
|
138
|
+
|
|
139
|
+
def solve_maxcut_exact(
|
|
140
|
+
G,
|
|
141
|
+
best_guess=None,
|
|
142
|
+
quality=None,
|
|
143
|
+
shots=None,
|
|
144
|
+
is_spin_glass=False,
|
|
145
|
+
anneal_t=None,
|
|
146
|
+
anneal_h=None,
|
|
147
|
+
repulsion_base=None,
|
|
148
|
+
is_maxcut_gpu=True,
|
|
149
|
+
verbose=True,
|
|
150
|
+
time_limit=None,
|
|
151
|
+
gray_iterations=None,
|
|
152
|
+
gray_seed_multiple=None,
|
|
153
|
+
):
|
|
154
|
+
"""
|
|
155
|
+
Exact MAXCUT/spin-glass solver via weighted MaxSAT (RC2).
|
|
156
|
+
|
|
157
|
+
Warm-starts from spin_glass_solver (or a caller-supplied hint) then hands
|
|
158
|
+
the problem to RC2, which uses CDCL conflict learning to certify or improve
|
|
159
|
+
the solution. Because PyQrackIsing's heuristic is already near-optimal in
|
|
160
|
+
practice, RC2's core-guided search typically terminates in seconds.
|
|
161
|
+
|
|
162
|
+
Requires: pip install python-sat
|
|
163
|
+
|
|
164
|
+
Accepts the same G input and warm-start formats as spin_glass_solver.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
G : networkx.Graph or ndarray
|
|
169
|
+
best_guess : str | int | list[bool] | None
|
|
170
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
|
|
171
|
+
is_spin_glass, gray_iterations, gray_seed_multiple
|
|
172
|
+
Forwarded to spin_glass_solver when best_guess is None.
|
|
173
|
+
verbose : bool
|
|
174
|
+
time_limit : float or None
|
|
175
|
+
Wall-clock seconds passed to RC2 (approximate; RC2 checks internally).
|
|
176
|
+
|
|
177
|
+
Returns
|
|
178
|
+
-------
|
|
179
|
+
bitstring : str
|
|
180
|
+
cut_value : float
|
|
181
|
+
partition : tuple(list, list)
|
|
182
|
+
min_energy : float
|
|
183
|
+
certified : bool
|
|
184
|
+
"""
|
|
185
|
+
if not _HAVE_PYSAT:
|
|
186
|
+
raise ImportError(
|
|
187
|
+
"python-sat is required for solve_maxcut_exact. "
|
|
188
|
+
"Install it with: pip install python-sat"
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
# --- G -> G_m (mirrors spin_glass_solver exactly) ---
|
|
192
|
+
if isinstance(G, nx.Graph):
|
|
193
|
+
nodes = list(G.nodes())
|
|
194
|
+
n_qubits = len(nodes)
|
|
195
|
+
G_m = nx.to_numpy_array(G, weight="weight", nonedge=0.0, dtype=dtype)
|
|
196
|
+
else:
|
|
197
|
+
n_qubits = len(G)
|
|
198
|
+
nodes = list(range(n_qubits))
|
|
199
|
+
G_m = np.asarray(G, dtype=dtype)
|
|
200
|
+
|
|
201
|
+
if n_qubits < 3:
|
|
202
|
+
if n_qubits == 0:
|
|
203
|
+
return "", 0, ([], []), 0, True
|
|
204
|
+
if n_qubits == 1:
|
|
205
|
+
return "0", 0, (nodes, []), 0, True
|
|
206
|
+
if n_qubits == 2:
|
|
207
|
+
weight = G_m[0, 1]
|
|
208
|
+
if weight < 0.0:
|
|
209
|
+
return "00", 0, (nodes, []), weight, True
|
|
210
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
211
|
+
|
|
212
|
+
# --- warm-start parser (mirrors spin_glass_solver exactly) ---
|
|
213
|
+
if isinstance(best_guess, str):
|
|
214
|
+
bitstring = best_guess
|
|
215
|
+
elif isinstance(best_guess, int):
|
|
216
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
217
|
+
elif isinstance(best_guess, list):
|
|
218
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
219
|
+
else:
|
|
220
|
+
if verbose:
|
|
221
|
+
print("Running PyQrackIsing heuristic...")
|
|
222
|
+
from .spin_glass_solver import spin_glass_solver
|
|
223
|
+
kwargs = {}
|
|
224
|
+
if quality is not None: kwargs["quality"] = quality
|
|
225
|
+
if shots is not None: kwargs["shots"] = shots
|
|
226
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
227
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
228
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
229
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
230
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
231
|
+
kwargs["is_maxcut_gpu"] = is_maxcut_gpu
|
|
232
|
+
t0 = time.monotonic()
|
|
233
|
+
bitstring, cut_value, _, _ = spin_glass_solver(
|
|
234
|
+
G_m, is_spin_glass=is_spin_glass, **kwargs
|
|
235
|
+
)
|
|
236
|
+
if verbose:
|
|
237
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
238
|
+
|
|
239
|
+
warm_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
240
|
+
|
|
241
|
+
# --- build edge list from upper-triangular G_m ---
|
|
242
|
+
edges = []
|
|
243
|
+
for i in range(n_qubits):
|
|
244
|
+
for j in range(i + 1, n_qubits):
|
|
245
|
+
w = float(G_m[i, j])
|
|
246
|
+
if w != 0.0:
|
|
247
|
+
edges.append((i, j, w))
|
|
248
|
+
|
|
249
|
+
if not edges:
|
|
250
|
+
# No edges: any partition is trivially optimal
|
|
251
|
+
bitstring, l, r = get_cut(warm_theta, nodes, n_qubits)
|
|
252
|
+
return bitstring, 0.0, (l, r), 0.0, True
|
|
253
|
+
|
|
254
|
+
has_negative = any(w < 0.0 for _, _, w in edges)
|
|
255
|
+
wcnf, total_pos_scaled, neg_scaled_total, baseline_neg = _build_wcnf(edges, n_qubits, has_negative)
|
|
256
|
+
|
|
257
|
+
if verbose:
|
|
258
|
+
print("Starting RC2 MaxSAT solver...")
|
|
259
|
+
|
|
260
|
+
t0 = time.monotonic()
|
|
261
|
+
|
|
262
|
+
rc2_kwargs = {}
|
|
263
|
+
if time_limit is not None:
|
|
264
|
+
rc2_kwargs["time_limit"] = time_limit
|
|
265
|
+
|
|
266
|
+
with RC2(wcnf, solver="g3", **rc2_kwargs) as rc2:
|
|
267
|
+
# Seed the SAT oracle's phase heuristic with the warm-start assignment.
|
|
268
|
+
# RC2 uses Glucose3 internally; we set variable polarities to match the
|
|
269
|
+
# warm start so the first SAT call explores the warm-start region first.
|
|
270
|
+
try:
|
|
271
|
+
phases = [i + 1 if warm_theta[i] else -(i + 1)
|
|
272
|
+
for i in range(len(warm_theta))]
|
|
273
|
+
rc2.oracle.set_phases(phases)
|
|
274
|
+
except AttributeError:
|
|
275
|
+
pass # solver doesn't support phase setting; continue without
|
|
276
|
+
|
|
277
|
+
model = rc2.compute()
|
|
278
|
+
cost_scaled = rc2.cost
|
|
279
|
+
certified = model is not None
|
|
280
|
+
|
|
281
|
+
elapsed = time.monotonic() - t0
|
|
282
|
+
|
|
283
|
+
if model is None:
|
|
284
|
+
# Time limit hit before optimum found — return warm start
|
|
285
|
+
if verbose:
|
|
286
|
+
print(f"RC2 time limit reached ({elapsed:.3f}s). "
|
|
287
|
+
f"Returning warm start.")
|
|
288
|
+
best_theta = warm_theta
|
|
289
|
+
else:
|
|
290
|
+
best_theta = _model_to_bits(model, n_qubits)
|
|
291
|
+
|
|
292
|
+
if verbose and model is not None:
|
|
293
|
+
cut_opt = baseline_neg + (total_pos_scaled + neg_scaled_total - cost_scaled) / _SCALE
|
|
294
|
+
print(f"RC2 optimum: {cut_opt:.6f} ({elapsed:.3f}s)")
|
|
295
|
+
|
|
296
|
+
# --- final scoring (matches spin_glass_solver return convention) ---
|
|
297
|
+
bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
|
|
298
|
+
if is_spin_glass:
|
|
299
|
+
cut_value = compute_cut(best_theta, G_m, n_qubits)
|
|
300
|
+
min_energy = -float(compute_energy(best_theta, G_m, n_qubits))
|
|
301
|
+
else:
|
|
302
|
+
cut_value = float(compute_cut(best_theta, G_m, n_qubits))
|
|
303
|
+
min_energy = float(compute_energy(best_theta, G_m, n_qubits))
|
|
304
|
+
|
|
305
|
+
return bitstring, cut_value, (l, r), min_energy, certified
|
|
@@ -0,0 +1,227 @@
|
|
|
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
|
+
# maxcut_exact_sparse.py — exact MAXCUT solver via weighted MaxSAT (sparse)
|
|
7
|
+
#
|
|
8
|
+
# Same encoding as maxcut_exact.py; edge list built from CSR arrays.
|
|
9
|
+
# See maxcut_exact.py for full encoding documentation.
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
import networkx as nx
|
|
13
|
+
import numpy as np
|
|
14
|
+
from .maxcut_tfim_util import (
|
|
15
|
+
compute_cut_sparse,
|
|
16
|
+
compute_energy_sparse,
|
|
17
|
+
get_cut,
|
|
18
|
+
int_to_bitstring,
|
|
19
|
+
opencl_context,
|
|
20
|
+
to_scipy_sparse_upper_triangular,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from pysat.examples.rc2 import RC2
|
|
25
|
+
from pysat.formula import WCNF
|
|
26
|
+
_HAVE_PYSAT = True
|
|
27
|
+
except ImportError:
|
|
28
|
+
_HAVE_PYSAT = False
|
|
29
|
+
|
|
30
|
+
dtype = opencl_context.dtype
|
|
31
|
+
|
|
32
|
+
# Integer scaling factor: edge weights are multiplied by this and rounded
|
|
33
|
+
# to integers for the WCNF encoding. 2**32 gives sub-ppb precision for
|
|
34
|
+
# weights in the typical PyQrackIsing range of [-1, 1] and is half 64-bit
|
|
35
|
+
# integer precision.
|
|
36
|
+
_SCALE = 2 ** 32
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _build_wcnf_sparse(G_data, G_rows, G_cols, n, has_negative):
|
|
40
|
+
wcnf = WCNF()
|
|
41
|
+
total_pos_scaled = 0
|
|
42
|
+
neg_scaled_total = 0
|
|
43
|
+
baseline_neg = 0.0
|
|
44
|
+
edge_idx = 0
|
|
45
|
+
for i in range(n):
|
|
46
|
+
for r in range(G_rows[i], G_rows[i + 1]):
|
|
47
|
+
j = int(G_cols[r])
|
|
48
|
+
if j <= i:
|
|
49
|
+
continue
|
|
50
|
+
w = float(G_data[r])
|
|
51
|
+
if w == 0.0:
|
|
52
|
+
continue
|
|
53
|
+
xi = i + 1
|
|
54
|
+
xj = j + 1
|
|
55
|
+
s = n + edge_idx + 1
|
|
56
|
+
wcnf.append([ xi, xj, -s]) # xi=0,xj=0 -> s=0
|
|
57
|
+
wcnf.append([-xi, -xj, -s]) # xi=1,xj=1 -> s=0
|
|
58
|
+
if has_negative:
|
|
59
|
+
wcnf.append([-xi, xj, s]) # xi=1,xj=0 -> s=1
|
|
60
|
+
wcnf.append([ xi, -xj, s]) # xi=0,xj=1 -> s=1
|
|
61
|
+
if w >= 0.0:
|
|
62
|
+
iw = max(1, int(round(w * _SCALE)))
|
|
63
|
+
total_pos_scaled += iw
|
|
64
|
+
wcnf.append([s], weight=iw)
|
|
65
|
+
else:
|
|
66
|
+
iw = max(1, int(round(-w * _SCALE)))
|
|
67
|
+
baseline_neg += w
|
|
68
|
+
neg_scaled_total += iw
|
|
69
|
+
wcnf.append([-s], weight=iw)
|
|
70
|
+
edge_idx += 1
|
|
71
|
+
return wcnf, total_pos_scaled, neg_scaled_total, baseline_neg
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _model_to_bits(model, n):
|
|
75
|
+
bits = np.zeros(n, dtype=np.bool_)
|
|
76
|
+
for lit in model:
|
|
77
|
+
var = abs(lit) - 1
|
|
78
|
+
if 0 <= var < n:
|
|
79
|
+
bits[var] = lit > 0
|
|
80
|
+
return bits
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def solve_maxcut_exact_sparse(
|
|
84
|
+
G,
|
|
85
|
+
best_guess=None,
|
|
86
|
+
quality=None,
|
|
87
|
+
shots=None,
|
|
88
|
+
is_spin_glass=False,
|
|
89
|
+
anneal_t=None,
|
|
90
|
+
anneal_h=None,
|
|
91
|
+
repulsion_base=None,
|
|
92
|
+
is_maxcut_gpu=True,
|
|
93
|
+
verbose=True,
|
|
94
|
+
time_limit=None,
|
|
95
|
+
gray_iterations=None,
|
|
96
|
+
gray_seed_multiple=None,
|
|
97
|
+
):
|
|
98
|
+
"""
|
|
99
|
+
Exact MAXCUT/spin-glass solver via weighted MaxSAT (RC2), sparse variant.
|
|
100
|
+
|
|
101
|
+
Accepts the same G input as spin_glass_solver_sparse (NetworkX graph or
|
|
102
|
+
scipy CSR matrix) and the same warm-start formats (str, int, list, None).
|
|
103
|
+
|
|
104
|
+
Requires: pip install python-sat
|
|
105
|
+
|
|
106
|
+
Parameters
|
|
107
|
+
----------
|
|
108
|
+
G : networkx.Graph or scipy CSR matrix
|
|
109
|
+
best_guess : str | int | list[bool] | None
|
|
110
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_maxcut_gpu,
|
|
111
|
+
is_spin_glass, gray_iterations, gray_seed_multiple
|
|
112
|
+
Forwarded to spin_glass_solver_sparse when best_guess is None.
|
|
113
|
+
verbose : bool
|
|
114
|
+
time_limit : float or None
|
|
115
|
+
|
|
116
|
+
Returns
|
|
117
|
+
-------
|
|
118
|
+
bitstring : str
|
|
119
|
+
cut_value : float
|
|
120
|
+
partition : tuple(list, list)
|
|
121
|
+
min_energy : float
|
|
122
|
+
certified : bool
|
|
123
|
+
"""
|
|
124
|
+
if not _HAVE_PYSAT:
|
|
125
|
+
raise ImportError(
|
|
126
|
+
"python-sat is required for solve_maxcut_exact_sparse. "
|
|
127
|
+
"Install it with: pip install python-sat"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
if isinstance(G, nx.Graph):
|
|
131
|
+
nodes = list(G.nodes())
|
|
132
|
+
n_qubits = len(nodes)
|
|
133
|
+
G_m = to_scipy_sparse_upper_triangular(G, nodes, n_qubits)
|
|
134
|
+
else:
|
|
135
|
+
n_qubits = G.shape[0]
|
|
136
|
+
nodes = list(range(n_qubits))
|
|
137
|
+
G_m = G
|
|
138
|
+
|
|
139
|
+
if n_qubits < 3:
|
|
140
|
+
if n_qubits == 0:
|
|
141
|
+
return "", 0, ([], []), 0, True
|
|
142
|
+
if n_qubits == 1:
|
|
143
|
+
return "0", 0, (nodes, []), 0, True
|
|
144
|
+
if n_qubits == 2:
|
|
145
|
+
weight = G_m[0, 1]
|
|
146
|
+
if weight < 0.0:
|
|
147
|
+
return "00", 0, (nodes, []), weight, True
|
|
148
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
149
|
+
|
|
150
|
+
G_data = np.asarray(G_m.data, dtype=np.float64)
|
|
151
|
+
G_rows = np.asarray(G_m.indptr, dtype=np.int64)
|
|
152
|
+
G_cols = np.asarray(G_m.indices, dtype=np.int64)
|
|
153
|
+
|
|
154
|
+
if isinstance(best_guess, str):
|
|
155
|
+
bitstring = best_guess
|
|
156
|
+
elif isinstance(best_guess, int):
|
|
157
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
158
|
+
elif isinstance(best_guess, list):
|
|
159
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
160
|
+
else:
|
|
161
|
+
if verbose:
|
|
162
|
+
print("Running PyQrackIsing heuristic...")
|
|
163
|
+
from .spin_glass_solver_sparse import spin_glass_solver_sparse
|
|
164
|
+
kwargs = {}
|
|
165
|
+
if quality is not None: kwargs["quality"] = quality
|
|
166
|
+
if shots is not None: kwargs["shots"] = shots
|
|
167
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
168
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
169
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
170
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
171
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
172
|
+
kwargs["is_maxcut_gpu"] = is_maxcut_gpu
|
|
173
|
+
t0 = time.monotonic()
|
|
174
|
+
bitstring, cut_value, _, _ = spin_glass_solver_sparse(
|
|
175
|
+
G_m, is_spin_glass=is_spin_glass, **kwargs
|
|
176
|
+
)
|
|
177
|
+
if verbose:
|
|
178
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
179
|
+
|
|
180
|
+
warm_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
181
|
+
has_negative = float(G_data.min()) < 0.0 if len(G_data) > 0 else False
|
|
182
|
+
wcnf, total_pos_scaled, neg_scaled_total, baseline_neg = _build_wcnf_sparse(
|
|
183
|
+
G_data, G_rows, G_cols, n_qubits, has_negative
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
if verbose:
|
|
187
|
+
print("Starting RC2 MaxSAT solver...")
|
|
188
|
+
|
|
189
|
+
rc2_kwargs = {}
|
|
190
|
+
if time_limit is not None:
|
|
191
|
+
rc2_kwargs["time_limit"] = time_limit
|
|
192
|
+
|
|
193
|
+
t0 = time.monotonic()
|
|
194
|
+
with RC2(wcnf, solver="g3", **rc2_kwargs) as rc2:
|
|
195
|
+
try:
|
|
196
|
+
phases = [i + 1 if warm_theta[i] else -(i + 1)
|
|
197
|
+
for i in range(len(warm_theta))]
|
|
198
|
+
rc2.oracle.set_phases(phases)
|
|
199
|
+
except AttributeError:
|
|
200
|
+
pass
|
|
201
|
+
model = rc2.compute()
|
|
202
|
+
cost_scaled = rc2.cost
|
|
203
|
+
certified = model is not None
|
|
204
|
+
|
|
205
|
+
elapsed = time.monotonic() - t0
|
|
206
|
+
|
|
207
|
+
if model is None:
|
|
208
|
+
if verbose:
|
|
209
|
+
print(f"RC2 time limit reached ({elapsed:.3f}s). "
|
|
210
|
+
f"Returning warm start.")
|
|
211
|
+
best_theta = warm_theta
|
|
212
|
+
else:
|
|
213
|
+
best_theta = _model_to_bits(model, n_qubits)
|
|
214
|
+
|
|
215
|
+
if verbose and model is not None:
|
|
216
|
+
cut_opt = baseline_neg + (total_pos_scaled + neg_scaled_total - cost_scaled) / _SCALE
|
|
217
|
+
print(f"RC2 optimum: {cut_opt:.6f} ({elapsed:.3f}s)")
|
|
218
|
+
|
|
219
|
+
bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
|
|
220
|
+
if is_spin_glass:
|
|
221
|
+
cut_value = float(compute_cut_sparse(best_theta, G_data, G_rows, G_cols, n_qubits))
|
|
222
|
+
min_energy = -float(compute_energy_sparse(best_theta, G_data, G_rows, G_cols, n_qubits))
|
|
223
|
+
else:
|
|
224
|
+
cut_value = float(compute_cut_sparse(best_theta, G_data, G_rows, G_cols, n_qubits))
|
|
225
|
+
min_energy = float(compute_energy_sparse(best_theta, G_data, G_rows, G_cols, n_qubits))
|
|
226
|
+
|
|
227
|
+
return bitstring, cut_value, (l, r), min_energy, certified
|