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/otoc.py ADDED
@@ -0,0 +1,248 @@
1
+ from .maxcut_tfim_util import init_thresholds, probability_by_hamming_weight, sample_mag, opencl_context
2
+ import math
3
+ from numba import njit
4
+ import numpy as np
5
+ import sys
6
+
7
+
8
+ epsilon = opencl_context.epsilon
9
+
10
+
11
+ def hadamard(dist):
12
+ """Krawtchouk/MacWilliams transform -- the bitwise Hadamard transform
13
+ restricted to Hamming-weight-symmetric distributions. Built via the
14
+ stable 3-term Krawtchouk recurrence rather than the closed-form
15
+ alternating sum of binomial coefficients, which suffers catastrophic
16
+ cancellation for larger n_qubits.
17
+
18
+ Provided by (Anthropic) Claude."""
19
+ n = len(dist) - 1
20
+ k_arr = np.arange(n + 1)
21
+ K_prev = np.ones(n + 1) # K_0(x) = 1
22
+ result = np.empty(n + 1)
23
+ result[0] = np.dot(dist, K_prev)
24
+ if n >= 1:
25
+ K_curr = n - 2 * k_arr # K_1(x) = n - 2x
26
+ result[1] = np.dot(dist, K_curr)
27
+ for j in range(1, n):
28
+ K_next = ((n - 2 * k_arr) * K_curr - (n - j + 1) * K_prev) / (j + 1)
29
+ result[j + 1] = np.dot(dist, K_next)
30
+ K_prev, K_curr = K_curr, K_next
31
+ tmp = result / (2 ** n)
32
+ tmp /= tmp.sum()
33
+
34
+ return tmp
35
+
36
+
37
+ def get_otoc_hamming_distribution(J=-1.0, h=2.0, z=4, theta=0.0, t=5, n_qubits=65, pauli_strings=["X" + "I" * 64]):
38
+ n_bias = n_qubits + 1
39
+ if (abs(h) <= epsilon) or (abs(t) <= epsilon):
40
+ bias = np.empty(n_bias, dtype=np.float64)
41
+ bias[0] = 1.0
42
+ return bias
43
+
44
+ # The removed items are identity operation, round-trip.
45
+ pauli_strings = [item for item in pauli_strings if item.count("I") != n_qubits]
46
+
47
+ signal_frac_x = 0
48
+ signal_frac_z = 0
49
+
50
+ for pauli_string in pauli_strings:
51
+ pauli_string = list(pauli_string)
52
+ if len(pauli_string) != n_qubits:
53
+ raise ValueError("OTOCS pauli_string must be same length as n_qubits! (Use 'I' for qubits that aren't changed.)")
54
+
55
+ count_y = pauli_string.count("Y")
56
+ signal_frac_x += pauli_string.count("X") + count_y
57
+ signal_frac_z += pauli_string.count("Z") + count_y
58
+
59
+ x_basis = init_thresholds(n_qubits, theta)
60
+ if signal_frac_x:
61
+ phi = theta + np.pi / 2
62
+ fwd_x = probability_by_hamming_weight(-h, -J, z, phi, t, n_qubits + 1)
63
+ rev = probability_by_hamming_weight(h, J, z, phi - np.pi, t, n_qubits + 1)
64
+ diff_x = rev - fwd_x
65
+ diff_x -= diff_x.mean()
66
+ signal_frac_x /= n_qubits
67
+ fwd_x += signal_frac_x * diff_x
68
+ signal_frac_x /= len(pauli_strings)
69
+ x_basis = (1.0 - signal_frac_x) * x_basis + signal_frac_x * fwd_x
70
+ x_min = x_basis.min()
71
+ x_max = x_basis.max()
72
+ is_norm = False
73
+ if x_min < 0:
74
+ x_basis -= x_min
75
+ is_norm = True
76
+ elif x_max > 1:
77
+ x_basis -= x_max - 1
78
+ is_norm = True
79
+ if is_norm:
80
+ x_basis /= x_basis.sum()
81
+
82
+ z_basis = hadamard(x_basis)
83
+ if signal_frac_z:
84
+ fwd_z = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1)
85
+ rev = probability_by_hamming_weight(-J, -h, z, theta + np.pi, t, n_qubits + 1)
86
+ diff_z = rev - fwd_z
87
+ diff_z -= diff_z.mean()
88
+ signal_frac_z /= n_qubits
89
+ fwd_z += signal_frac_z * diff_z
90
+ signal_frac_z /= len(pauli_strings)
91
+ z_basis = (1.0 - signal_frac_z) * z_basis + signal_frac_z * fwd_z
92
+ z_min = z_basis.min()
93
+ z_max = z_basis.max()
94
+ is_norm = False
95
+ if z_min < 0:
96
+ z_basis -= z_min
97
+ is_norm = True
98
+ elif z_max > 1:
99
+ z_basis -= z_max - 1
100
+ is_norm = True
101
+ if is_norm:
102
+ z_basis /= z_basis.sum()
103
+
104
+ return z_basis
105
+
106
+
107
+ @njit
108
+ def fix_cdf(hamming_prob):
109
+ tot_prob = 0.0
110
+ n_bias = len(hamming_prob)
111
+ cum_prob = np.empty(n_bias, dtype=np.float64)
112
+ for i in range(n_bias):
113
+ tot_prob += hamming_prob[i]
114
+ cum_prob[i] = tot_prob
115
+ cum_prob[-1] = 2.0
116
+
117
+ return cum_prob
118
+
119
+
120
+ @njit
121
+ def factor_width(width):
122
+ col_len = int(np.floor(np.sqrt(width)))
123
+ while ((width // col_len) * col_len) != width:
124
+ col_len -= 1
125
+ row_len = width // col_len
126
+
127
+ return row_len, col_len
128
+
129
+
130
+ # Provided by Google search AI
131
+ def find_all_bit_flips(main_string):
132
+ indices = []
133
+ start_index = 0
134
+ while True:
135
+ index = main_string.find("X", start_index)
136
+ if index == -1:
137
+ break
138
+ indices.append(index)
139
+ start_index = index + 1 # Start searching after the found occurrence
140
+ start_index = 0
141
+ while True:
142
+ index = main_string.find("Y", start_index)
143
+ if index == -1:
144
+ break
145
+ indices.append(index)
146
+ start_index = index + 1 # Start searching after the found occurrence
147
+
148
+ return indices
149
+
150
+
151
+ def take_sample(n_qubits, sample, m, inv_dist):
152
+ indices = [i for i in range(n_qubits)]
153
+ tot_inv_dist = 0.0
154
+ for i in range(n_qubits):
155
+ tot_inv_dist += inv_dist[i]
156
+ selected = []
157
+ for i in range(m):
158
+ r = tot_inv_dist * np.random.random()
159
+ p = inv_dist[indices[0]]
160
+ idx = 0
161
+ while p < r:
162
+ idx += 1
163
+ if idx >= len(indices):
164
+ idx = len(indices) - 1
165
+ break
166
+ p += inv_dist[indices[idx]]
167
+ i = indices[idx]
168
+ del indices[idx]
169
+ selected.append(i)
170
+ tot_inv_dist -= inv_dist[i]
171
+ for i in selected:
172
+ sample |= 1 << i
173
+
174
+ return sample
175
+
176
+
177
+ def get_willow_inv_dist(butterfly_idx_x, n_qubits, row_len, col_len, t):
178
+ inv_dist = np.zeros(n_qubits, dtype=np.float64)
179
+ for idx in butterfly_idx_x:
180
+ b_row, b_col = divmod(idx, row_len)
181
+ for q in range(n_qubits):
182
+ q_row, q_col = divmod(q, row_len)
183
+ inv_dist[q] -= abs(q_row - b_row) + abs(q_col - b_col)
184
+ inv_dist /= t
185
+
186
+ return inv_dist
187
+
188
+
189
+ def get_inv_dist(butterfly_idx_x, n_qubits, row_len, col_len, t):
190
+ inv_dist = np.zeros(n_qubits, dtype=np.float64)
191
+ half_row = row_len >> 1
192
+ half_col = col_len >> 1
193
+ for idx in butterfly_idx_x:
194
+ b_row, b_col = divmod(idx, row_len)
195
+ for q in range(n_qubits):
196
+ q_row, q_col = divmod(q, row_len)
197
+ row_d = abs(q_row - b_row)
198
+ if row_d > half_row:
199
+ row_d = row_len - row_d
200
+ col_d = abs(q_col - b_col)
201
+ if col_d > half_col:
202
+ col_d = col_len - col_d
203
+ inv_dist[q] -= row_d + col_d
204
+ inv_dist /= t
205
+
206
+ return inv_dist
207
+
208
+
209
+ def generate_otoc_samples(
210
+ J=-1.0,
211
+ h=2.0,
212
+ z=4,
213
+ theta=0.0,
214
+ t=5,
215
+ n_qubits=65,
216
+ pauli_strings=["X" + "I" * 64],
217
+ shots=100,
218
+ is_orbifold=True,
219
+ ):
220
+ thresholds = fix_cdf(get_otoc_hamming_distribution(J, h, z, theta, t, n_qubits, pauli_strings))
221
+ row_len, col_len = factor_width(n_qubits)
222
+ inv_dist = np.zeros(n_qubits, dtype=np.float64)
223
+ for i, pauli_string in enumerate(pauli_strings):
224
+ if pauli_string.count("I") == n_qubits:
225
+ continue
226
+ butterfly_idx_x = find_all_bit_flips(pauli_string)
227
+ if is_orbifold:
228
+ inv_dist = 0.5 * inv_dist + get_inv_dist(butterfly_idx_x, n_qubits, row_len, col_len, t)
229
+ else:
230
+ inv_dist = 0.5 * inv_dist + get_willow_inv_dist(butterfly_idx_x, n_qubits, row_len, col_len, t)
231
+ inv_dist = 2 ** inv_dist
232
+
233
+ qubit_pows = [1 << q for q in range(n_qubits)]
234
+ samples = []
235
+ for _ in range(shots):
236
+ # First dimension: Hamming weight
237
+ m = sample_mag(thresholds)
238
+ if m == 0:
239
+ samples.append(0)
240
+ continue
241
+ if m >= n_qubits:
242
+ samples.append((1 << n_qubits) - 1)
243
+ continue
244
+
245
+ # Second dimension: permutation within Hamming weight
246
+ samples.append(take_sample(n_qubits, 0, m, inv_dist))
247
+
248
+ return samples
@@ -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