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.
@@ -0,0 +1,294 @@
1
+ from .maxcut_tfim_streaming import maxcut_tfim_streaming
2
+ from .local_search import local_search
3
+ from .maxcut_tfim_util import (
4
+ compute_cut_streaming,
5
+ compute_energy_streaming,
6
+ compute_cut_diff_streaming,
7
+ compute_cut_diff_2_streaming,
8
+ compute_cut_diff_between_streaming,
9
+ get_cut,
10
+ get_cut_base,
11
+ gray_code_next,
12
+ gray_mutation,
13
+ heuristic_threshold,
14
+ int_to_bitstring,
15
+ opencl_context,
16
+ )
17
+ import networkx as nx
18
+ import numpy as np
19
+ from numba import njit, prange
20
+ import os
21
+ import time
22
+
23
+
24
+ dtype = opencl_context.dtype
25
+
26
+
27
+ # Belief propagation was added by (Anthropic) Claude
28
+ def belief_propagation_marginals_streaming(G_func, nodes, n, bp_scale=1.0, damping=0.5):
29
+ """
30
+ Run loopy belief propagation using the streaming edge accessor to produce
31
+ per-node marginals for warm-starting the partition.
32
+
33
+ Since the streaming solver has no pre-built adjacency structure, we make
34
+ one O(n^2) pass over node pairs to discover non-zero edges before running
35
+ BP iterations. This matches the streaming solver's own access pattern and
36
+ keeps total cost O(n * m) iterations on top of the O(n^2) discovery pass,
37
+ remaining <= O(n^3) overall.
38
+
39
+ Parameters
40
+ ----------
41
+ G_func : callable
42
+ Edge weight accessor: G_func(u, v) -> float. Returns 0.0 for absent edges.
43
+ nodes : sequence
44
+ Node identifiers corresponding to qubit indices.
45
+ n : int
46
+ Number of nodes.
47
+ bp_scale : float
48
+ Iteration cap = int(bp_scale * n). User-controlled; default 1.0
49
+ keeps total work <= O(n^3).
50
+ damping : float
51
+ Message damping factor in [0, 1).
52
+
53
+ Returns
54
+ -------
55
+ marginals : ndarray, shape (n,)
56
+ Soft assignment in (-1, +1).
57
+ """
58
+ max_iterations = max(1, int(bp_scale * n))
59
+
60
+ # Discover edges via one O(n^2) pass — unavoidable for the streaming case
61
+ us = []
62
+ vs = []
63
+ ws = []
64
+ for i in range(n):
65
+ for j in range(i + 1, n):
66
+ w = G_func(nodes[i], nodes[j])
67
+ if abs(w) > 1e-12:
68
+ us.append(i)
69
+ vs.append(j)
70
+ ws.append(w)
71
+
72
+ m = len(us)
73
+ if m == 0:
74
+ return np.zeros(n, dtype=np.float64)
75
+
76
+ us = np.array(us, dtype=np.int32)
77
+ vs = np.array(vs, dtype=np.int32)
78
+ ws = np.array(ws, dtype=np.float64)
79
+
80
+ # msg_fwd[k] = message from us[k] -> vs[k]
81
+ # msg_bwd[k] = message from vs[k] -> us[k]
82
+ msg_fwd = np.zeros(m, dtype=np.float64)
83
+ msg_bwd = np.zeros(m, dtype=np.float64)
84
+
85
+ # Build neighbour index: node -> list of (edge_idx, direction)
86
+ # direction=0: node is 'u' end, incoming = msg_bwd[k]
87
+ # direction=1: node is 'v' end, incoming = msg_fwd[k]
88
+ node_edges = [[] for _ in range(n)]
89
+ for k in range(m):
90
+ node_edges[us[k]].append((k, 0))
91
+ node_edges[vs[k]].append((k, 1))
92
+
93
+ for _ in range(max_iterations):
94
+ new_fwd = np.empty(m, dtype=np.float64)
95
+ new_bwd = np.empty(m, dtype=np.float64)
96
+
97
+ for k in range(m):
98
+ u = us[k]
99
+ v = vs[k]
100
+ w = ws[k]
101
+
102
+ # Message u -> v: aggregate incoming to u excluding v
103
+ h_u = 0.0
104
+ for (ek, direction) in node_edges[u]:
105
+ if ek == k:
106
+ continue
107
+ h_u += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
108
+
109
+ tanh_w = np.tanh(w)
110
+ product = tanh_w * np.tanh(h_u)
111
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
112
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * np.arctanh(product)
113
+
114
+ # Message v -> u: aggregate incoming to v excluding u
115
+ h_v = 0.0
116
+ for (ek, direction) in node_edges[v]:
117
+ if ek == k:
118
+ continue
119
+ h_v += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
120
+
121
+ product_v = tanh_w * np.tanh(h_v)
122
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
123
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * np.arctanh(product_v)
124
+
125
+ msg_fwd = new_fwd
126
+ msg_bwd = new_bwd
127
+
128
+ # Marginals: sum all incoming messages per node
129
+ marginals = np.zeros(n, dtype=np.float64)
130
+ for k in range(m):
131
+ marginals[us[k]] += msg_bwd[k]
132
+ marginals[vs[k]] += msg_fwd[k]
133
+
134
+ return np.tanh(marginals)
135
+
136
+
137
+ def bp_warm_start_streaming(G_func, nodes, n, bp_scale=1.0, damping=0.5):
138
+ """Partition bitstring from BP marginals over the streaming graph."""
139
+ marginals = belief_propagation_marginals_streaming(G_func, nodes, n, bp_scale, damping)
140
+ return marginals > 0.0
141
+
142
+
143
+ def spin_glass_solver_streaming(
144
+ G_func,
145
+ nodes,
146
+ quality=None,
147
+ shots=None,
148
+ best_guess=None,
149
+ is_maxcut_gpu=True,
150
+ is_spin_glass=True,
151
+ anneal_t=None,
152
+ anneal_h=None,
153
+ repulsion_base=None,
154
+ is_log=False,
155
+ gray_iterations=None,
156
+ gray_seed_multiple=None,
157
+ bp_scale=None,
158
+ bp_damping=0.5,
159
+ seed=None,
160
+ time_limit=None,
161
+ ):
162
+ """
163
+ Streaming spin glass / MaxCut solver with optional belief propagation warm-start.
164
+
165
+ Parameters
166
+ ----------
167
+ seed, time_limit : as for spin_glass_solver.
168
+ bp_scale : float or None
169
+ Controls BP iteration count as int(bp_scale * n_qubits).
170
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
171
+ (<=O(n^3) for any graph density). Note: the streaming solver incurs
172
+ an additional O(n^2) edge-discovery pass when BP is enabled, since
173
+ no adjacency structure is pre-built.
174
+ bp_damping : float
175
+ Message damping in [0, 1). Default 0.5.
176
+ """
177
+ dtype = opencl_context.dtype
178
+ deadline = float("inf") if time_limit is None else time.perf_counter() + time_limit
179
+ remaining = lambda: None if time_limit is None else max(0.0, deadline - time.perf_counter())
180
+ n_qubits = len(nodes)
181
+
182
+ if n_qubits < 3:
183
+ if n_qubits == 0:
184
+ return "", 0, ([], []), 0
185
+
186
+ if n_qubits == 1:
187
+ return "0", 0, (nodes, []), 0
188
+
189
+ if n_qubits == 2:
190
+ weight = G_func(nodes[0], nodes[1])
191
+ if weight < 0.0:
192
+ return "00", 0, (nodes, []), weight
193
+
194
+ return "01", weight, ([nodes[0]], [nodes[1]]), -weight
195
+
196
+ if n_qubits < heuristic_threshold:
197
+ best_guess = None
198
+
199
+ bitstring = ""
200
+ cut_value = None
201
+ if isinstance(best_guess, str):
202
+ bitstring = best_guess
203
+ elif isinstance(best_guess, int):
204
+ bitstring = int_to_bitstring(best_guess, n_qubits)
205
+ elif isinstance(best_guess, list):
206
+ bitstring = "".join(["1" if b else "0" for b in best_guess])
207
+ else:
208
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
209
+ # so that the cascade local search begins from a sign-aware partition
210
+ # rather than the TFIM prior alone.
211
+ if bp_scale is not None and n_qubits >= heuristic_threshold:
212
+ bp_theta = bp_warm_start_streaming(G_func, nodes, n_qubits, bp_scale, bp_damping)
213
+ bitstring, cut_value, _ = maxcut_tfim_streaming(
214
+ G_func,
215
+ nodes,
216
+ quality=quality,
217
+ shots=shots,
218
+ is_spin_glass=is_spin_glass,
219
+ anneal_t=anneal_t,
220
+ anneal_h=anneal_h,
221
+ repulsion_base=repulsion_base,
222
+ seed=seed,
223
+ time_limit=remaining(),
224
+ )
225
+ # Keep whichever of BP or sampling gave the better cut
226
+ bp_energy = (
227
+ compute_energy_streaming(bp_theta, G_func, nodes, n_qubits)
228
+ if is_spin_glass
229
+ else compute_cut_streaming(bp_theta, G_func, nodes, n_qubits)
230
+ )
231
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
232
+ sample_energy = (
233
+ compute_energy_streaming(sample_theta, G_func, nodes, n_qubits)
234
+ if is_spin_glass
235
+ else compute_cut_streaming(sample_theta, G_func, nodes, n_qubits)
236
+ )
237
+ if bp_energy > sample_energy:
238
+ bitstring = "".join(["1" if b else "0" for b in bp_theta])
239
+ cut_value = bp_energy if not is_spin_glass else None
240
+ else:
241
+ bitstring, cut_value, _ = maxcut_tfim_streaming(
242
+ G_func,
243
+ nodes,
244
+ quality=quality,
245
+ shots=shots,
246
+ is_spin_glass=is_spin_glass,
247
+ anneal_t=anneal_t,
248
+ anneal_h=anneal_h,
249
+ repulsion_base=repulsion_base,
250
+ seed=seed,
251
+ time_limit=remaining(),
252
+ )
253
+
254
+ best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
255
+ if is_spin_glass:
256
+ max_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
257
+ elif cut_value is None:
258
+ max_energy = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
259
+ else:
260
+ max_energy = cut_value
261
+
262
+ if n_qubits < heuristic_threshold:
263
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
264
+ if is_spin_glass:
265
+ cut_value = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
266
+ min_energy = -max_energy
267
+ else:
268
+ cut_value = max_energy
269
+ min_energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
270
+
271
+ return bitstring, float(cut_value), (l, r), float(min_energy)
272
+
273
+ if gray_iterations is None:
274
+ gray_iterations = n_qubits * n_qubits
275
+
276
+ if gray_seed_multiple is None:
277
+ gray_seed_multiple = max(2, os.cpu_count())
278
+
279
+ best_theta = local_search(
280
+ best_theta,
281
+ is_spin_glass,
282
+ (None, None, None, None, G_func, nodes),
283
+ gray_iterations,
284
+ gray_seed_multiple,
285
+ deadline,
286
+ )
287
+
288
+ bitstring, l, r = get_cut(best_theta, nodes, n_qubits)
289
+ # Report values recomputed from the returned bits.
290
+ cut_value = compute_cut_streaming(best_theta, G_func, nodes, n_qubits)
291
+ energy = compute_energy_streaming(best_theta, G_func, nodes, n_qubits)
292
+ min_energy = -energy if is_spin_glass else energy
293
+
294
+ return bitstring, float(cut_value), (l, r), float(min_energy)
@@ -0,0 +1,23 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight, opencl_context
2
+ from numba import njit
3
+ import numpy as np
4
+
5
+
6
+ epsilon = opencl_context.epsilon
7
+
8
+
9
+ @njit
10
+ def tfim_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
11
+ if abs(t) <= epsilon:
12
+ return np.cos(theta)
13
+
14
+ bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1)
15
+ bias /= bias.sum()
16
+ magnetization = 0.0
17
+ nqs = int(n_qubits)
18
+ nqd = float(n_qubits)
19
+ for q in range(n_qubits + 1):
20
+ mag = (nqs - 2 * q) / nqd
21
+ magnetization += bias[q] * mag
22
+
23
+ return magnetization
@@ -0,0 +1,22 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight, opencl_context
2
+ from numba import njit
3
+ import numpy as np
4
+
5
+
6
+ epsilon = opencl_context.epsilon
7
+
8
+
9
+ @njit
10
+ def tfim_square_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
11
+ if abs(t) <= epsilon:
12
+ return np.cos(theta) ** 2
13
+
14
+ bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1)
15
+ bias /= bias.sum()
16
+ square_magnetization = 0.0
17
+ nqs = int(n_qubits)
18
+ nqd = float(n_qubits)
19
+ for q in range(n_qubits + 1):
20
+ mag = (nqs - 2 * q) / nqd
21
+ square_magnetization += bias[q] * mag * mag
22
+ return square_magnetization