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,217 @@
|
|
|
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_streaming.py — exact MAXCUT solver via weighted MaxSAT (streaming)
|
|
7
|
+
#
|
|
8
|
+
# Same encoding as maxcut_exact.py; edge weights fetched via G_func(nodes[i], nodes[j]).
|
|
9
|
+
# See maxcut_exact.py for full encoding documentation.
|
|
10
|
+
|
|
11
|
+
import time
|
|
12
|
+
import numpy as np
|
|
13
|
+
from .maxcut_tfim_util import (
|
|
14
|
+
compute_cut_streaming,
|
|
15
|
+
compute_energy_streaming,
|
|
16
|
+
get_cut,
|
|
17
|
+
int_to_bitstring,
|
|
18
|
+
opencl_context,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
from pysat.examples.rc2 import RC2
|
|
23
|
+
from pysat.formula import WCNF
|
|
24
|
+
_HAVE_PYSAT = True
|
|
25
|
+
except ImportError:
|
|
26
|
+
_HAVE_PYSAT = False
|
|
27
|
+
|
|
28
|
+
dtype = opencl_context.dtype
|
|
29
|
+
|
|
30
|
+
# Integer scaling factor: edge weights are multiplied by this and rounded
|
|
31
|
+
# to integers for the WCNF encoding. 2**32 gives sub-ppb precision for
|
|
32
|
+
# weights in the typical PyQrackIsing range of [-1, 1] and is half 64-bit
|
|
33
|
+
# integer precision.
|
|
34
|
+
_SCALE = 2 ** 32
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _build_wcnf_streaming(G_func, nodes, n, has_negative):
|
|
38
|
+
wcnf = WCNF()
|
|
39
|
+
total_pos_scaled = 0
|
|
40
|
+
neg_scaled_total = 0
|
|
41
|
+
baseline_neg = 0.0
|
|
42
|
+
edge_idx = 0
|
|
43
|
+
for i in range(n):
|
|
44
|
+
for j in range(i + 1, n):
|
|
45
|
+
w = float(G_func(nodes[i], nodes[j]))
|
|
46
|
+
if w == 0.0:
|
|
47
|
+
continue
|
|
48
|
+
xi = i + 1
|
|
49
|
+
xj = j + 1
|
|
50
|
+
s = n + edge_idx + 1
|
|
51
|
+
wcnf.append([ xi, xj, -s]) # xi=0,xj=0 -> s=0
|
|
52
|
+
wcnf.append([-xi, -xj, -s]) # xi=1,xj=1 -> s=0
|
|
53
|
+
if has_negative:
|
|
54
|
+
wcnf.append([-xi, xj, s]) # xi=1,xj=0 -> s=1
|
|
55
|
+
wcnf.append([ xi, -xj, s]) # xi=0,xj=1 -> s=1
|
|
56
|
+
if w >= 0.0:
|
|
57
|
+
iw = max(1, int(round(w * _SCALE)))
|
|
58
|
+
total_pos_scaled += iw
|
|
59
|
+
wcnf.append([s], weight=iw)
|
|
60
|
+
else:
|
|
61
|
+
iw = max(1, int(round(-w * _SCALE)))
|
|
62
|
+
baseline_neg += w
|
|
63
|
+
neg_scaled_total += iw
|
|
64
|
+
wcnf.append([-s], weight=iw)
|
|
65
|
+
edge_idx += 1
|
|
66
|
+
return wcnf, total_pos_scaled, neg_scaled_total, baseline_neg
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _model_to_bits(model, n):
|
|
70
|
+
bits = np.zeros(n, dtype=np.bool_)
|
|
71
|
+
for lit in model:
|
|
72
|
+
var = abs(lit) - 1
|
|
73
|
+
if 0 <= var < n:
|
|
74
|
+
bits[var] = lit > 0
|
|
75
|
+
return bits
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def solve_maxcut_exact_streaming(
|
|
79
|
+
G_func,
|
|
80
|
+
nodes,
|
|
81
|
+
best_guess=None,
|
|
82
|
+
quality=None,
|
|
83
|
+
shots=None,
|
|
84
|
+
is_spin_glass=False,
|
|
85
|
+
anneal_t=None,
|
|
86
|
+
anneal_h=None,
|
|
87
|
+
repulsion_base=None,
|
|
88
|
+
verbose=True,
|
|
89
|
+
time_limit=None,
|
|
90
|
+
gray_iterations=None,
|
|
91
|
+
gray_seed_multiple=None,
|
|
92
|
+
):
|
|
93
|
+
"""
|
|
94
|
+
Exact MAXCUT/spin-glass solver via weighted MaxSAT (RC2), streaming variant.
|
|
95
|
+
|
|
96
|
+
Accepts the same G_func + nodes input as spin_glass_solver_streaming and
|
|
97
|
+
the same warm-start formats (str, int, list, or None).
|
|
98
|
+
|
|
99
|
+
Requires: pip install python-sat
|
|
100
|
+
|
|
101
|
+
Parameters
|
|
102
|
+
----------
|
|
103
|
+
G_func : callable(u, v) -> float
|
|
104
|
+
Edge weight function (Numba-callable). Returns 0.0 for absent edges.
|
|
105
|
+
nodes : array-like
|
|
106
|
+
Ordered sequence of node identifiers.
|
|
107
|
+
best_guess : str | int | list[bool] | None
|
|
108
|
+
quality, shots, anneal_t, anneal_h, repulsion_base, is_spin_glass,
|
|
109
|
+
gray_iterations, gray_seed_multiple
|
|
110
|
+
Forwarded to spin_glass_solver_streaming when best_guess is None.
|
|
111
|
+
verbose : bool
|
|
112
|
+
time_limit : float or None
|
|
113
|
+
|
|
114
|
+
Returns
|
|
115
|
+
-------
|
|
116
|
+
bitstring : str
|
|
117
|
+
cut_value : float
|
|
118
|
+
partition : tuple(list, list)
|
|
119
|
+
min_energy : float
|
|
120
|
+
certified : bool
|
|
121
|
+
"""
|
|
122
|
+
if not _HAVE_PYSAT:
|
|
123
|
+
raise ImportError(
|
|
124
|
+
"python-sat is required for solve_maxcut_exact_streaming. "
|
|
125
|
+
"Install it with: pip install python-sat"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
nodes = np.asarray(nodes)
|
|
129
|
+
n_qubits = len(nodes)
|
|
130
|
+
|
|
131
|
+
if n_qubits < 3:
|
|
132
|
+
if n_qubits == 0:
|
|
133
|
+
return "", 0, ([], []), 0, True
|
|
134
|
+
if n_qubits == 1:
|
|
135
|
+
return "0", 0, (list(nodes), []), 0, True
|
|
136
|
+
if n_qubits == 2:
|
|
137
|
+
weight = G_func(nodes[0], nodes[1])
|
|
138
|
+
if weight < 0.0:
|
|
139
|
+
return "00", 0, (list(nodes), []), weight, True
|
|
140
|
+
return "01", weight, ([nodes[0]], [nodes[1]]), -weight, True
|
|
141
|
+
|
|
142
|
+
if isinstance(best_guess, str):
|
|
143
|
+
bitstring = best_guess
|
|
144
|
+
elif isinstance(best_guess, int):
|
|
145
|
+
bitstring = int_to_bitstring(best_guess, n_qubits)
|
|
146
|
+
elif isinstance(best_guess, list):
|
|
147
|
+
bitstring = "".join(["1" if b else "0" for b in best_guess])
|
|
148
|
+
else:
|
|
149
|
+
if verbose:
|
|
150
|
+
print("Running PyQrackIsing heuristic...")
|
|
151
|
+
from .spin_glass_solver_streaming import spin_glass_solver_streaming
|
|
152
|
+
kwargs = {}
|
|
153
|
+
if quality is not None: kwargs["quality"] = quality
|
|
154
|
+
if shots is not None: kwargs["shots"] = shots
|
|
155
|
+
if anneal_t is not None: kwargs["anneal_t"] = anneal_t
|
|
156
|
+
if anneal_h is not None: kwargs["anneal_h"] = anneal_h
|
|
157
|
+
if repulsion_base is not None: kwargs["repulsion_base"] = repulsion_base
|
|
158
|
+
if gray_iterations is not None: kwargs["gray_iterations"] = gray_iterations
|
|
159
|
+
if gray_seed_multiple is not None: kwargs["gray_seed_multiple"] = gray_seed_multiple
|
|
160
|
+
t0 = time.monotonic()
|
|
161
|
+
bitstring, cut_value, _, _ = spin_glass_solver_streaming(
|
|
162
|
+
G_func, nodes, is_spin_glass=is_spin_glass, **kwargs
|
|
163
|
+
)
|
|
164
|
+
if verbose:
|
|
165
|
+
print(f"Heuristic value: {cut_value:.6f} ({time.monotonic()-t0:.3f}s)")
|
|
166
|
+
|
|
167
|
+
warm_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
|
|
168
|
+
has_negative = any(
|
|
169
|
+
G_func(nodes[i], nodes[j]) < 0.0
|
|
170
|
+
for i in range(n_qubits) for j in range(i + 1, n_qubits)
|
|
171
|
+
)
|
|
172
|
+
wcnf, total_pos_scaled, neg_scaled_total, baseline_neg = _build_wcnf_streaming(
|
|
173
|
+
G_func, nodes, n_qubits, has_negative
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if verbose:
|
|
177
|
+
print("Starting RC2 MaxSAT solver...")
|
|
178
|
+
|
|
179
|
+
rc2_kwargs = {}
|
|
180
|
+
if time_limit is not None:
|
|
181
|
+
rc2_kwargs["time_limit"] = time_limit
|
|
182
|
+
|
|
183
|
+
t0 = time.monotonic()
|
|
184
|
+
with RC2(wcnf, solver="g3", **rc2_kwargs) as rc2:
|
|
185
|
+
try:
|
|
186
|
+
phases = [i + 1 if warm_theta[i] else -(i + 1)
|
|
187
|
+
for i in range(len(warm_theta))]
|
|
188
|
+
rc2.oracle.set_phases(phases)
|
|
189
|
+
except AttributeError:
|
|
190
|
+
pass
|
|
191
|
+
model = rc2.compute()
|
|
192
|
+
cost_scaled = rc2.cost
|
|
193
|
+
certified = model is not None
|
|
194
|
+
|
|
195
|
+
elapsed = time.monotonic() - t0
|
|
196
|
+
|
|
197
|
+
if model is None:
|
|
198
|
+
if verbose:
|
|
199
|
+
print(f"RC2 time limit reached ({elapsed:.3f}s). "
|
|
200
|
+
f"Returning warm start.")
|
|
201
|
+
best_theta = warm_theta
|
|
202
|
+
else:
|
|
203
|
+
best_theta = _model_to_bits(model, n_qubits)
|
|
204
|
+
|
|
205
|
+
if verbose and model is not None:
|
|
206
|
+
cut_opt = baseline_neg + (total_pos_scaled + neg_scaled_total - cost_scaled) / _SCALE
|
|
207
|
+
print(f"RC2 optimum: {cut_opt:.6f} ({elapsed:.3f}s)")
|
|
208
|
+
|
|
209
|
+
bitstring, l, r = get_cut(best_theta, list(nodes), n_qubits)
|
|
210
|
+
if is_spin_glass:
|
|
211
|
+
cut_value = float(compute_cut_streaming(best_theta, G_func, nodes, n_qubits))
|
|
212
|
+
min_energy = -float(compute_energy_streaming(best_theta, G_func, nodes, n_qubits))
|
|
213
|
+
else:
|
|
214
|
+
cut_value = float(compute_cut_streaming(best_theta, G_func, nodes, n_qubits))
|
|
215
|
+
min_energy = float(compute_energy_streaming(best_theta, G_func, nodes, n_qubits))
|
|
216
|
+
|
|
217
|
+
return bitstring, cut_value, (l, r), min_energy, certified
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# SPDX-License-Identifier: LGPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Daniel Strano and the Qrack contributors
|
|
3
|
+
#
|
|
4
|
+
# Drafted by (Anthropic) Claude.
|
|
5
|
+
#
|
|
6
|
+
# QUBO and Ising front ends for the spin glass solvers.
|
|
7
|
+
#
|
|
8
|
+
# The spin glass solvers minimise H(s) = sum_{i<j} w_ij s_i s_j over
|
|
9
|
+
# s in {-1, +1}^n (couplings only). Local fields h_i are added exactly with
|
|
10
|
+
# one ancilla spin a coupled to every node: H'(s, s_a) = H(s) + sum_i h_i s_i s_a.
|
|
11
|
+
# H' is symmetric under a global flip, so any optimum can be flipped to
|
|
12
|
+
# s_a = +1, where H' = H + h.s. QUBOs map onto that Ising form with x = (1 - s)/2.
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import scipy.sparse as sp
|
|
16
|
+
|
|
17
|
+
from .spin_glass_solver import spin_glass_solver
|
|
18
|
+
from .spin_glass_solver_sparse import spin_glass_solver_sparse
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _ising_energy(J_upper, h, spins, offset=0.0):
|
|
22
|
+
s = spins.astype(np.float64)
|
|
23
|
+
if sp.issparse(J_upper):
|
|
24
|
+
coupling = float(s @ (J_upper @ s))
|
|
25
|
+
else:
|
|
26
|
+
coupling = float(s @ J_upper @ s)
|
|
27
|
+
return coupling + float(h @ s) + offset
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _upper(J):
|
|
31
|
+
"""Coefficient of s_i s_j (i < j) as a strict upper triangle: J_ij + J_ji."""
|
|
32
|
+
if sp.issparse(J):
|
|
33
|
+
J = sp.csr_matrix(J, dtype=np.float64)
|
|
34
|
+
return sp.triu(J + J.T, k=1, format="csr")
|
|
35
|
+
J = np.asarray(J, dtype=np.float64)
|
|
36
|
+
return np.triu(J + J.T, k=1)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def solve_ising(J, h=None, offset=0.0, **solver_kwargs):
|
|
40
|
+
"""
|
|
41
|
+
Approximately minimise E(s) = sum_{i<j} J_ij s_i s_j + sum_i h_i s_i + offset
|
|
42
|
+
over spins s_i in {-1, +1}.
|
|
43
|
+
|
|
44
|
+
J : (n, n) array or scipy sparse matrix. Both triangles are summed, so pass
|
|
45
|
+
couplings in either triangle (or symmetrically halved).
|
|
46
|
+
h : (n,) local fields, or None.
|
|
47
|
+
solver_kwargs : passed to spin_glass_solver (dense J) or
|
|
48
|
+
spin_glass_solver_sparse (sparse J), e.g. quality, seed, time_limit.
|
|
49
|
+
|
|
50
|
+
Returns (spins as an int8 array of +/-1, energy E(s) recomputed exactly in
|
|
51
|
+
float64 from the inputs).
|
|
52
|
+
"""
|
|
53
|
+
J_u = _upper(J)
|
|
54
|
+
n = J_u.shape[0]
|
|
55
|
+
h = np.zeros(n) if h is None else np.asarray(h, dtype=np.float64)
|
|
56
|
+
if h.shape != (n,):
|
|
57
|
+
raise ValueError("h must have shape (n,)")
|
|
58
|
+
has_fields = bool(np.any(h != 0.0))
|
|
59
|
+
is_sparse = sp.issparse(J_u)
|
|
60
|
+
|
|
61
|
+
if n == 0:
|
|
62
|
+
return np.zeros(0, dtype=np.int8), float(offset)
|
|
63
|
+
|
|
64
|
+
# Coupling matrix seen by the solver (symmetric for dense, upper for sparse).
|
|
65
|
+
if has_fields:
|
|
66
|
+
if is_sparse:
|
|
67
|
+
W = sp.bmat([[J_u, sp.csr_matrix(h.reshape(-1, 1))], [None, sp.csr_matrix((1, 1))]], format="csr")
|
|
68
|
+
else:
|
|
69
|
+
W = np.zeros((n + 1, n + 1))
|
|
70
|
+
W[:n, :n] = J_u
|
|
71
|
+
W[:n, n] = h
|
|
72
|
+
else:
|
|
73
|
+
W = J_u
|
|
74
|
+
|
|
75
|
+
if is_sparse:
|
|
76
|
+
bits, _, _, _ = spin_glass_solver_sparse(W, is_spin_glass=True, **solver_kwargs)
|
|
77
|
+
else:
|
|
78
|
+
W = W + W.T
|
|
79
|
+
bits, _, _, _ = spin_glass_solver(W.astype(np.float32), is_spin_glass=True, **solver_kwargs)
|
|
80
|
+
|
|
81
|
+
spins = np.array([1 if b == "0" else -1 for b in bits], dtype=np.int8)
|
|
82
|
+
if has_fields:
|
|
83
|
+
if spins[n] < 0:
|
|
84
|
+
spins = -spins # global flip symmetry: put the ancilla at +1
|
|
85
|
+
spins = spins[:n]
|
|
86
|
+
|
|
87
|
+
return spins, _ising_energy(J_u, h, spins, offset)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def qubo_to_ising(Q):
|
|
91
|
+
"""
|
|
92
|
+
Exact conversion of x^T Q x (x in {0,1}^n) to sum_{i<j} J_ij s_i s_j + h.s + offset
|
|
93
|
+
with x = (1 - s) / 2. Returns (J_upper, h, offset); J_upper is dense or
|
|
94
|
+
sparse to match Q.
|
|
95
|
+
"""
|
|
96
|
+
if sp.issparse(Q):
|
|
97
|
+
Q = sp.csr_matrix(Q, dtype=np.float64)
|
|
98
|
+
d = Q.diagonal()
|
|
99
|
+
Qs = (Q + Q.T) * 0.5
|
|
100
|
+
Qs = Qs - sp.diags(Qs.diagonal())
|
|
101
|
+
row = np.asarray(Qs.sum(axis=1)).ravel()
|
|
102
|
+
J_upper = sp.triu(Qs, k=1, format="csr") * 0.5
|
|
103
|
+
total_off = Qs.sum() * 0.5
|
|
104
|
+
else:
|
|
105
|
+
Q = np.asarray(Q, dtype=np.float64)
|
|
106
|
+
d = np.diag(Q).copy()
|
|
107
|
+
Qs = (Q + Q.T) * 0.5
|
|
108
|
+
np.fill_diagonal(Qs, 0.0)
|
|
109
|
+
row = Qs.sum(axis=1)
|
|
110
|
+
J_upper = np.triu(Qs, k=1) * 0.5
|
|
111
|
+
total_off = Qs.sum() * 0.5
|
|
112
|
+
# x_i x_j = (1 - s_i - s_j + s_i s_j) / 4 ; pair (i<j) coefficient in x^T Q x is 2 Qs_ij
|
|
113
|
+
h = -0.5 * d - 0.5 * row
|
|
114
|
+
offset = 0.5 * float(d.sum()) + 0.5 * float(total_off)
|
|
115
|
+
return J_upper, h, offset
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def solve_qubo(Q, **solver_kwargs):
|
|
119
|
+
"""
|
|
120
|
+
Approximately minimise x^T Q x over x in {0, 1}^n.
|
|
121
|
+
|
|
122
|
+
Q : (n, n) array or scipy sparse matrix (need not be symmetric; the
|
|
123
|
+
diagonal holds the linear terms).
|
|
124
|
+
solver_kwargs : as for solve_ising (quality, seed, time_limit, ...).
|
|
125
|
+
|
|
126
|
+
Returns (x as a bool array, x^T Q x recomputed exactly in float64).
|
|
127
|
+
"""
|
|
128
|
+
J_upper, h, offset = qubo_to_ising(Q)
|
|
129
|
+
spins, _ = solve_ising(J_upper, h, offset, **solver_kwargs)
|
|
130
|
+
x = spins < 0 # s = 1 - 2x
|
|
131
|
+
xf = x.astype(np.float64)
|
|
132
|
+
value = float(xf @ (Q @ xf)) if sp.issparse(Q) else float(xf @ np.asarray(Q, dtype=np.float64) @ xf)
|
|
133
|
+
return x, value
|