PyQrackIsing 9.14.0__tar.gz → 9.15.0__tar.gz

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.
Files changed (35) hide show
  1. {pyqrackising-9.14.0/pyqrackising.egg-info → pyqrackising-9.15.0}/PKG-INFO +1 -1
  2. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/README.md +5 -3
  3. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyproject.toml +1 -1
  4. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/generate_tfim_samples.py +331 -244
  5. {pyqrackising-9.14.0 → pyqrackising-9.15.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  6. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/setup.py +1 -1
  7. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/LICENSE.md +0 -0
  8. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/MANIFEST.in +0 -0
  9. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/__init__.py +0 -0
  10. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  11. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/kernels.cl +0 -0
  12. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/maxcut_tfim.py +0 -0
  13. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  14. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  15. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/maxcut_tfim_util.py +0 -0
  16. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/otoc.py +0 -0
  17. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_bnb.py +0 -0
  18. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_bnb_sparse.py +0 -0
  19. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_bnb_streaming.py +0 -0
  20. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_exact.py +0 -0
  21. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_exact_sparse.py +0 -0
  22. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/solve_maxcut_exact_streaming.py +0 -0
  23. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/spin_glass_solver.py +0 -0
  24. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  25. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  26. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/tfim_magnetization.py +0 -0
  27. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/tfim_square_magnetization.py +0 -0
  28. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/tsp.py +0 -0
  29. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising/tsp_maxcut.py +0 -0
  30. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising.egg-info/SOURCES.txt +0 -0
  31. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  32. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  33. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising.egg-info/requires.txt +0 -0
  34. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/pyqrackising.egg-info/top_level.txt +0 -0
  35. {pyqrackising-9.14.0 → pyqrackising-9.15.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.14.0
3
+ Version: 9.15.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -208,11 +208,13 @@ Transverse field Ising model (TFIM) is the basis of most claimed algorithmic "qu
208
208
 
209
209
  Sometimes a solution (or at least near-solution) to a monster of a differential equation hits us out of the blue. Then, it's easy to _validate_ the guess, if it's right. (We don't question it and just move on with our lives, from there.)
210
210
 
211
- **Special thanks to OpenAI GPT "Elara," for help on the model and converting the original Python scripts to PyBind11, Numba, and PyOpenCL!**
211
+ **Special thanks to (Anthropic) Claude, for helping better connect the theory and implementation to theoretical treatment of Gibbs states!**
212
212
 
213
- We reduce transverse field Ising model for globally uniform `J` and `h` parameters from a `2^n`-dimensional problem to an `(n+1)`-dimensional (heuristic but near-exact) form that suffers from no Trotter error. Upon noticing most time steps for parameters in a [TFIM experiment published by Quantinuum](https://arxiv.org/abs/2503.20870) had roughly a quarter to a third (or thereabouts) of their marginal probability in `|0>` state, it became obvious that transition to and from `|0>` state should dominate the mechanics, at least far from mean-field equilibrium. Further, the first transition therefore tends to be to or from any state with Hamming weight of 1 (in other words, 1 bit set to 1 and the rest reset to 0, or `n` bits set for Hamming weight of `n`). Further, on a torus, probability of all states with Hamming weight of 1 would tend to be exactly symmetric. Assuming approximate symmetry in every respective Hamming weight, the requirement for the overall probability to converge to 1.0 or 100% in the limit of an infinite-dimensional Hilbert space suggests that Hamming weight marginal probability could be distributed like a geometric series. A small correction to exact symmetry should be made to favor _magnetic_ closeness of "like" bits to "like" bits (that is, geometric closeness on the torus of "1" bits to "1" bits and "0" bits to "0" bits), but this does not affect average global magnetization. Adding an oscillation component with angular frequency proportional to `J`, we find excellent agreement with Trotterization with a very small time step, for R^2 (coefficient of determination) of normalized marginal probability distribution of ideal Trotterized simulation as described by the `(n+1)`-dimensional approximate model, as well as for R^2 and RMSE (root-mean-square error) of global magnetization curve values.
213
+ **Special thanks to (OpenAI GPT) "Elara," for help on the model and converting the original Python scripts to PyBind11, Numba, and PyOpenCL!**
214
214
 
215
- If the above paragraph and the model it describes are true, then it stands to reason that we should be able to apply the TFIM model to **NP-complete** heuristics, so long as we can adapt the model to spatially localized `J` and `h` and adiabatic time dependence of `h`. A reasonable guess for how to spatially localize `J` and `h` is to average the overall behavior for each and every qubit as if `J` and `h` were globally uniform from its local perspective. (`z` parameter is derived from nonzero edge weight count connectivity.) For adiabatic time-dependence of `h`, another reasonable refinement is to use simply **finite-difference simulation**. Initial state should probably be just **uniform superposition**, which implies a specific (non-uniform but regular) distribution of initial probabilities by Hamming weight dimension over `(n+1)` possible Hamming weights. We observe that the _spatial magnetic effect_ qualitatively agrees with the demands of MAXCUT when it acts like a magnetic _repulsion,_ rather than magnetic attraction, in this case, but we can add that refinement on an arbitrary connectivity topology in just `O(n)` complexity per measurement shot. (This is a complete "recipe": the evidence that it works is the quality of NP-complete heuristic solutions at utility scale.)
215
+ We reduce transverse field Ising model for globally uniform `J` and `h` parameters from a `2^n`-dimensional problem to an `(n+1)`-dimensional (heuristic but near-exact) form that suffers from no Trotter error. Upon noticing most time steps for parameters in a [TFIM experiment published by Quantinuum](https://arxiv.org/abs/2503.20870) had roughly a quarter to a third (or thereabouts) of their marginal probability in `|0>` state, it became obvious that transition to and from `|0>` state should dominate the mechanics, at least far from mean-field equilibrium. Further, the first transition therefore tends to be to or from any state with Hamming weight of 1 (in other words, 1 bit set to 1 and the rest reset to 0, or `n` bits set for Hamming weight of `n`). Further, on a torus, probability of all states with Hamming weight of 1 would tend to be exactly symmetric. Assuming approximate symmetry in every respective Hamming weight, the requirement for the overall probability to converge to 1.0 or 100% in the limit of an infinite-dimensional Hilbert space suggests that Hamming weight marginal probability could be distributed like a geometric series. A small correction to exact symmetry should be made to favor _magnetic_ closeness of "like" bits to "unlike" bits (that is, geometric closeness on the torus of "0" bits to "1" bits), but this does not affect average global magnetization. Adding an oscillation component with angular frequency proportional to `J`, we find excellent agreement with Trotterization with a very small time step, for R^2 (coefficient of determination) of normalized marginal probability distribution of ideal Trotterized simulation as described by the `(n+1)`-dimensional approximate model, as well as for R^2 and RMSE (root-mean-square error) of global magnetization curve values.
216
+
217
+ If the above paragraph and the model it describes are true, then it stands to reason that we should be able to apply the TFIM model to **NP-complete** heuristics, so long as we can adapt the model to spatially localized `J` and `h` and adiabatic time dependence of `h`. A reasonable guess for how to spatially localize `J` and `h` is to average the overall behavior for each and every qubit as if `J` and `h` were globally uniform from its local perspective. (`z` parameter is derived from nonzero edge weight count connectivity.) For adiabatic time-dependence of `h`, another reasonable refinement is to use simply **finite-difference simulation**. Initial state should be just **uniform superposition**, which implies a specific (non-uniform but regular) distribution of initial probabilities by Hamming weight dimension over `(n+1)` possible Hamming weights. We can add the _spatial magnetic effect_ on an arbitrary connectivity topology in just `O(n)` complexity per measurement shot. (This is a complete "recipe": the evidence that it works is the quality of NP-complete heuristic solutions at utility scale.)
216
218
 
217
219
  **Elara has drafted this statement, and Dan Strano, as author, agrees with it, and will hold to it:**
218
220
 
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "pyqrackising"
10
- version = "9.14.0"
10
+ version = "9.15.0"
11
11
  requires-python = ">=3.8"
12
12
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
13
13
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -1,244 +1,331 @@
1
- from .maxcut_tfim_util import probability_by_hamming_weight, sample_mag, opencl_context
2
- import itertools
3
- import math
4
- import random
5
- import sys
6
- import numpy as np
7
- from numba import njit
8
-
9
- from collections import Counter
10
-
11
-
12
- epsilon = opencl_context.epsilon
13
-
14
-
15
- # Fixed-Hamming-weight Kawasaki swaps with acceptance probability, by Elara
16
- def random_fixed_hamming_state(n_qubits, h):
17
- bits = np.zeros(n_qubits, dtype=np.bool_)
18
- bits[:h] = True
19
- np.random.shuffle(bits)
20
- state = 0
21
- for b in bits:
22
- state <<= 1
23
- if b:
24
- state |= 1
25
-
26
- return state
27
-
28
-
29
- def build_neighbors(n_rows, n_cols):
30
- L = n_rows * n_cols
31
- neighbors = [[] for _ in range(L)]
32
-
33
- for i in range(n_rows):
34
- for j in range(n_cols):
35
- idx = i * n_cols + j
36
-
37
- right = i * n_cols + ((j + 1) % n_cols)
38
- left = i * n_cols + ((j - 1) % n_cols)
39
- down = ((i + 1) % n_rows) * n_cols + j
40
- up = ((i - 1) % n_rows) * n_cols + j
41
-
42
- neighbors[idx] = [right, left, down, up]
43
-
44
- return neighbors
45
-
46
-
47
- def count_like_edges(state, neighbors):
48
- like = 0
49
- visited = set()
50
-
51
- for i, nbrs in enumerate(neighbors):
52
- si = (state >> i) & 1
53
- for j in nbrs:
54
- if (j, i) in visited:
55
- continue
56
- sj = (state >> j) & 1
57
- if si == sj:
58
- like += 1
59
- visited.add((i, j))
60
-
61
- return like
62
-
63
-
64
- def delta_like_edges(state, i, j, neighbors):
65
- si = (state >> i) & 1
66
- sj = (state >> j) & 1
67
-
68
- delta = 0
69
-
70
- for idx in [i, j]:
71
- s_old = (state >> idx) & 1
72
-
73
- for nbr in neighbors[idx]:
74
- if nbr == i or nbr == j:
75
- continue
76
-
77
- s_nbr = (state >> nbr) & 1
78
-
79
- old_like = s_old == s_nbr
80
- new_spin = sj if idx == i else si
81
- new_like = new_spin == s_nbr
82
-
83
- delta += int(new_like) - int(old_like)
84
-
85
- # handle edge between i and j if neighbors
86
- if j in neighbors[i]:
87
- old_like = si == sj
88
- new_like = sj == si
89
- delta += int(new_like) - int(old_like)
90
-
91
- return delta
92
-
93
-
94
- def sample_fixed_hamming_weight(h_weight, count, n_rows, n_cols, burnin=10):
95
- if count == 0:
96
- return []
97
-
98
- n_qubits = n_rows * n_cols
99
- neighbors = build_neighbors(n_rows, n_cols)
100
-
101
- like_edges = 0
102
- while like_edges == 0:
103
- state = random_fixed_hamming_state(n_qubits, h_weight)
104
- like_edges = count_like_edges(state, neighbors)
105
-
106
- samples = []
107
-
108
- burn = burnin * n_qubits
109
- thinning = n_qubits
110
-
111
- ones = set([i for i in range(n_qubits) if (state >> i) & 1])
112
- zeros = set([i for i in range(n_qubits) if not (state >> i) & 1])
113
-
114
- for step in range(burn + thinning * count):
115
- # choose random 1-bit and 0-bit
116
-
117
- i = random.choice(tuple(ones))
118
- j = random.choice(tuple(zeros))
119
-
120
- delta = delta_like_edges(state, i, j, neighbors)
121
- new_like = like_edges + delta
122
-
123
- if new_like > 0:
124
- accept_prob = new_like / like_edges
125
- if np.random.random() < accept_prob:
126
- state ^= 1 << i
127
- ones.remove(i)
128
- zeros.add(i)
129
-
130
- state ^= 1 << j
131
- zeros.remove(j)
132
- ones.add(j)
133
-
134
- like_edges = new_like
135
-
136
- if step >= burn and (step - burn) % thinning == 0:
137
- samples.append(state)
138
-
139
- return samples
140
-
141
-
142
- @njit
143
- def factor_width(width, is_transpose=False):
144
- col_len = math.floor(math.sqrt(width))
145
- while ((width // col_len) * col_len) != width:
146
- col_len -= 1
147
- row_len = width // col_len
148
-
149
- return (col_len, row_len) if is_transpose else (row_len, col_len)
150
-
151
-
152
- @njit
153
- def comb(n, k):
154
- if (k < 0) or (k > n):
155
- return 0
156
- if (k == 0) or (k == n):
157
- return 1
158
- res = 1
159
- for i in range(1, k + 1):
160
- res = res * (n - k + i) // i
161
- return res
162
-
163
-
164
- @njit
165
- def fix_cdf(hamming_prob):
166
- tot_prob = 0.0
167
- n_bias = len(hamming_prob)
168
- cum_prob = np.empty(n_bias, dtype=np.float64)
169
- for i in range(n_bias):
170
- tot_prob += hamming_prob[i]
171
- cum_prob[i] = tot_prob
172
- cum_prob[-1] = 1.0
173
-
174
- return cum_prob
175
-
176
-
177
- @njit
178
- def get_tfim_hamming_distribution(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, omega=1.5 * np.pi):
179
- if abs(t) <= epsilon:
180
- p = (1.0 - np.cos(theta)) / 2.0
181
- bias = np.empty(n_qubits + 1, dtype=np.float64)
182
- for k in range(n_qubits + 1):
183
- bias[k] = comb(n_qubits, k) * (p**k) * ((1.0 - p) ** (n_qubits - k))
184
-
185
- return bias / bias.sum()
186
-
187
- if abs(h) <= epsilon:
188
- bias = np.empty(n_qubits + 1, dtype=np.float64)
189
- if J > 0:
190
- bias[-1] = 1.0
191
- else:
192
- bias[0] = 1.0
193
- return bias
194
-
195
- bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1, normalized=True, omega=omega)
196
-
197
- return bias / bias.sum()
198
-
199
-
200
- def generate_tfim_samples(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100):
201
- samples = []
202
-
203
- if abs(t) <= epsilon:
204
- prob = (1.0 - np.cos(theta)) / 2.0
205
- for s in range(shots):
206
- sample = 0
207
- for q in range(n_qubits):
208
- sample <<= 1
209
- if np.random.random() < prob:
210
- sample |= 1
211
- samples.append(sample)
212
-
213
- return samples
214
-
215
- n_rows, n_cols = factor_width(n_qubits)
216
-
217
- # First dimension: Hamming weight
218
- bias = get_tfim_hamming_distribution(J=J, h=h, z=z, theta=theta, t=t, n_qubits=n_qubits)
219
- counts = np.random.multinomial(shots, bias)
220
-
221
- samples += [0] * counts[0]
222
- samples += [(1 << n_qubits) - 1] * counts[-1]
223
- if n_qubits > 1:
224
- samples += [int(1 << np.random.randint(n_qubits)) for _ in range(counts[1])]
225
- if n_qubits > 2:
226
- mask = (1 << n_qubits) - 1
227
- samples += [(mask ^ int(1 << np.random.randint(n_qubits))) for _ in range(counts[-2])]
228
-
229
- # Second dimension: magnetic localization
230
- for h_weight in range(2, len(bias) - 2):
231
- samples += sample_fixed_hamming_weight(h_weight, counts[h_weight], n_rows, n_cols)
232
-
233
- np.random.shuffle(samples)
234
-
235
- return samples
236
-
237
-
238
- def generate_fermi_hubbard_samples(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100, omega=1.5 * np.pi):
239
- shots_x, shots_y, shots_z = np.random.multinomial(shots, [1 / 3, 1 / 3, 1 / 3])
240
- return (
241
- generate_tfim_samples(J=J, h=h, z=z, theta=theta, t=t, n_qubits=n_qubits, shots=shots_z)
242
- + generate_tfim_samples(J=-h, h=-J, z=z, theta=theta + np.pi / 2, t=t, n_qubits=n_qubits, shots=shots_x)
243
- + generate_tfim_samples(J=J, h=h, z=z, theta=theta + np.pi / 2, t=t, n_qubits=n_qubits, shots=shots_y)
244
- )
1
+ """
2
+ generate_tfim_samples.py (Envelope variant)
3
+ ==================================
4
+ Drop-in replacement for generate_tfim_samples with a time-dependent
5
+ exponential envelope applied to the Hamming weight marginal.
6
+
7
+ The key insight
8
+ ---------------
9
+ The Hamming weight marginal from probability_by_hamming_weight is what
10
+ pins <O_bond> ~ +1.0 in the ESD sweep — not the spatial Kawasaki dynamics.
11
+ The marginal at h >> |J| is dominated by high-Hamming-weight (X-polarized)
12
+ states at all t, which produce positive correlations in all three bases.
13
+
14
+ The fix: multiply the marginal by an envelope that is *largest at small t*
15
+ and decays toward uniform as t grows:
16
+
17
+ bias[k] *= exp(-alpha * |k - n/2| / t)
18
+
19
+ At t -> 0: envelope peaks sharply at half-filling (k = n/2), the
20
+ antiferromagnetic ground state sector. The spatial dynamics
21
+ (repulsive Kawasaki) then has maximum leverage.
22
+
23
+ At t -> inf: envelope -> 1 everywhere; the physics-derived marginal
24
+ from probability_by_hamming_weight is recovered exactly.
25
+
26
+ The differential is greatest at initialization — exactly where the ESD
27
+ interesting physics lives — and fades as the system equilibrates toward
28
+ the Gibbs target. alpha controls the strength of the initial bias.
29
+
30
+ This is physically motivated: the AFM ground state of the XXZ model
31
+ is at half-filling on a bipartite lattice, so biasing toward k=n/2
32
+ at early times is consistent with starting near the ground state and
33
+ thermalizing upward, rather than starting in the paramagnetic phase.
34
+
35
+ Authors: Claude (Anthropic), Elara (OpenAI custom GPT), and D. Strano
36
+ """
37
+
38
+ from .maxcut_tfim_util import probability_by_hamming_weight, sample_mag, opencl_context
39
+ import itertools
40
+ import math
41
+ import random
42
+ import sys
43
+ import numpy as np
44
+ from numba import njit
45
+
46
+ from collections import Counter
47
+
48
+
49
+ epsilon = opencl_context.epsilon
50
+
51
+
52
+ # Fixed-Hamming-weight Kawasaki swaps with acceptance probability, by Elara
53
+ def random_fixed_hamming_state(n_qubits, h):
54
+ bits = np.zeros(n_qubits, dtype=np.bool_)
55
+ bits[:h] = True
56
+ np.random.shuffle(bits)
57
+ state = 0
58
+ for b in bits:
59
+ state <<= 1
60
+ if b:
61
+ state |= 1
62
+
63
+ return state
64
+
65
+
66
+ def build_neighbors(n_rows, n_cols):
67
+ L = n_rows * n_cols
68
+ neighbors = [[] for _ in range(L)]
69
+
70
+ for i in range(n_rows):
71
+ for j in range(n_cols):
72
+ idx = i * n_cols + j
73
+
74
+ right = i * n_cols + ((j + 1) % n_cols)
75
+ left = i * n_cols + ((j - 1) % n_cols)
76
+ down = ((i + 1) % n_rows) * n_cols + j
77
+ up = ((i - 1) % n_rows) * n_cols + j
78
+
79
+ neighbors[idx] = [right, left, down, up]
80
+
81
+ return neighbors
82
+
83
+
84
+ def count_like_edges(state, neighbors):
85
+ like = 0
86
+ visited = set()
87
+
88
+ for i, nbrs in enumerate(neighbors):
89
+ si = (state >> i) & 1
90
+ for j in nbrs:
91
+ if (j, i) in visited:
92
+ continue
93
+ sj = (state >> j) & 1
94
+ if si == sj:
95
+ like += 1
96
+ visited.add((i, j))
97
+
98
+ return like
99
+
100
+
101
+ def delta_like_edges(state, i, j, neighbors):
102
+ si = (state >> i) & 1
103
+ sj = (state >> j) & 1
104
+
105
+ delta = 0
106
+
107
+ for idx in [i, j]:
108
+ s_old = (state >> idx) & 1
109
+
110
+ for nbr in neighbors[idx]:
111
+ if nbr == i or nbr == j:
112
+ continue
113
+
114
+ s_nbr = (state >> nbr) & 1
115
+
116
+ old_like = s_old == s_nbr
117
+ new_spin = sj if idx == i else si
118
+ new_like = new_spin == s_nbr
119
+
120
+ delta += int(new_like) - int(old_like)
121
+
122
+ # handle edge between i and j if neighbors
123
+ if j in neighbors[i]:
124
+ old_like = si == sj
125
+ new_like = sj == si
126
+ delta += int(new_like) - int(old_like)
127
+
128
+ return delta
129
+
130
+
131
+ def sample_fixed_hamming_weight(h_weight, count, n_rows, n_cols, burnin=10):
132
+ if count == 0:
133
+ return []
134
+
135
+ n_qubits = n_rows * n_cols
136
+ neighbors = build_neighbors(n_rows, n_cols)
137
+
138
+ like_edges = 0
139
+ while like_edges == 0:
140
+ state = random_fixed_hamming_state(n_qubits, h_weight)
141
+ like_edges = count_like_edges(state, neighbors)
142
+
143
+ samples = []
144
+
145
+ burn = burnin * n_qubits
146
+ thinning = n_qubits
147
+
148
+ ones = set([i for i in range(n_qubits) if (state >> i) & 1])
149
+ zeros = set([i for i in range(n_qubits) if not (state >> i) & 1])
150
+
151
+ for step in range(burn + thinning * count):
152
+ # choose random 1-bit and 0-bit
153
+
154
+ i = random.choice(tuple(ones))
155
+ j = random.choice(tuple(zeros))
156
+
157
+ delta = delta_like_edges(state, i, j, neighbors)
158
+ new_like = like_edges + delta
159
+
160
+ if new_like > 0:
161
+ accept_prob = new_like / like_edges
162
+ if np.random.random() < accept_prob:
163
+ state ^= 1 << i
164
+ ones.remove(i)
165
+ zeros.add(i)
166
+
167
+ state ^= 1 << j
168
+ zeros.remove(j)
169
+ ones.add(j)
170
+
171
+ like_edges = new_like
172
+
173
+ if step >= burn and (step - burn) % thinning == 0:
174
+ samples.append(state)
175
+
176
+ return samples
177
+
178
+
179
+ @njit
180
+ def factor_width(width, is_transpose=False):
181
+ col_len = math.floor(math.sqrt(width))
182
+ while ((width // col_len) * col_len) != width:
183
+ col_len -= 1
184
+ row_len = width // col_len
185
+
186
+ return (col_len, row_len) if is_transpose else (row_len, col_len)
187
+
188
+
189
+ @njit
190
+ def comb(n, k):
191
+ if (k < 0) or (k > n):
192
+ return 0
193
+ if (k == 0) or (k == n):
194
+ return 1
195
+ res = 1
196
+ for i in range(1, k + 1):
197
+ res = res * (n - k + i) // i
198
+ return res
199
+
200
+
201
+ @njit
202
+ def fix_cdf(hamming_prob):
203
+ tot_prob = 0.0
204
+ n_bias = len(hamming_prob)
205
+ cum_prob = np.empty(n_bias, dtype=np.float64)
206
+ for i in range(n_bias):
207
+ tot_prob += hamming_prob[i]
208
+ cum_prob[i] = tot_prob
209
+ cum_prob[-1] = 1.0
210
+
211
+ return cum_prob
212
+
213
+
214
+ @njit
215
+ def _apply_time_envelope(bias, t, n_qubits):
216
+ """
217
+ Multiply bias[k] by exp(-|k - n/2| / max(t, epsilon)) for each k.
218
+
219
+ This is the time-dependent Hamming weight envelope:
220
+ - At small t: peaks sharply at half-filling k = n/2 (AFM sector).
221
+ - At large t: envelope -> 1, recovering the original bias exactly.
222
+
223
+ The differential effect is greatest at initialization (small t),
224
+ which is where the ESD / adiabatic physics lives.
225
+
226
+ alpha = 1.0 is hardcoded as the natural physical invariant.
227
+ It is the least contrived value that produces the correct qualitative
228
+ behaviour, and is left fixed rather than tuned empirically.
229
+
230
+ Authors: Claude (Anthropic) and D. Strano
231
+ """
232
+ alpha = 1.0
233
+ half = n_qubits / 2.0
234
+ # Numba-safe floor of t for the epsilon guard
235
+ t_eff = t if t > 1e-9 else 1e-9
236
+
237
+ out = np.empty(n_qubits + 1, dtype=np.float64)
238
+ tot = 0.0
239
+ for k in range(n_qubits + 1):
240
+ dist = k - half
241
+ if dist < 0.0:
242
+ dist = -dist
243
+ envelope = math.exp(-alpha * dist / t_eff)
244
+ val = bias[k] * envelope
245
+ out[k] = val
246
+ tot += val
247
+
248
+ if tot <= 0.0:
249
+ # Pathological underflow: collapse to half-filling delta
250
+ for k in range(n_qubits + 1):
251
+ out[k] = 0.0
252
+ mid = n_qubits // 2
253
+ out[mid] = 1.0
254
+ return out
255
+
256
+ for k in range(n_qubits + 1):
257
+ out[k] /= tot
258
+
259
+ return out
260
+
261
+
262
+ @njit
263
+ def get_tfim_hamming_distribution(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, omega=1.5 * np.pi):
264
+ if abs(t) <= epsilon:
265
+ p = (1.0 - np.cos(theta)) / 2.0
266
+ bias = np.empty(n_qubits + 1, dtype=np.float64)
267
+ for k in range(n_qubits + 1):
268
+ bias[k] = comb(n_qubits, k) * (p**k) * ((1.0 - p) ** (n_qubits - k))
269
+
270
+ return bias / bias.sum()
271
+
272
+ if abs(h) <= epsilon:
273
+ bias = np.empty(n_qubits + 1, dtype=np.float64)
274
+ if J > 0:
275
+ bias[-1] = 1.0
276
+ else:
277
+ bias[0] = 1.0
278
+ return bias
279
+
280
+ bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1, normalized=True, omega=omega)
281
+
282
+ # Apply time-dependent envelope: maximum differential at small t,
283
+ # recovers original distribution as t -> inf.
284
+ return _apply_time_envelope(bias / bias.sum(), t, n_qubits)
285
+
286
+
287
+ def generate_tfim_samples(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100):
288
+ samples = []
289
+
290
+ if abs(t) <= epsilon:
291
+ prob = (1.0 - np.cos(theta)) / 2.0
292
+ for s in range(shots):
293
+ sample = 0
294
+ for q in range(n_qubits):
295
+ sample <<= 1
296
+ if np.random.random() < prob:
297
+ sample |= 1
298
+ samples.append(sample)
299
+
300
+ return samples
301
+
302
+ n_rows, n_cols = factor_width(n_qubits)
303
+
304
+ # First dimension: Hamming weight (envelope applied inside)
305
+ bias = get_tfim_hamming_distribution(J=J, h=h, z=z, theta=theta, t=t, n_qubits=n_qubits)
306
+ counts = np.random.multinomial(shots, bias)
307
+
308
+ samples += [0] * counts[0]
309
+ samples += [(1 << n_qubits) - 1] * counts[-1]
310
+ if n_qubits > 1:
311
+ samples += [int(1 << np.random.randint(n_qubits)) for _ in range(counts[1])]
312
+ if n_qubits > 2:
313
+ mask = (1 << n_qubits) - 1
314
+ samples += [(mask ^ int(1 << np.random.randint(n_qubits))) for _ in range(counts[-2])]
315
+
316
+ # Second dimension: magnetic localization
317
+ for h_weight in range(2, len(bias) - 2):
318
+ samples += sample_fixed_hamming_weight(h_weight, counts[h_weight], n_rows, n_cols)
319
+
320
+ np.random.shuffle(samples)
321
+
322
+ return samples
323
+
324
+
325
+ def generate_fermi_hubbard_samples(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100, omega=1.5 * np.pi):
326
+ shots_x, shots_y, shots_z = np.random.multinomial(shots, [1 / 3, 1 / 3, 1 / 3])
327
+ return (
328
+ generate_tfim_samples(J=J, h=h, z=z, theta=theta, t=t, n_qubits=n_qubits, shots=shots_z)
329
+ + generate_tfim_samples(J=-h, h=-J, z=z, theta=theta + np.pi / 2, t=t, n_qubits=n_qubits, shots=shots_x)
330
+ + generate_tfim_samples(J=J, h=h, z=z, theta=theta + np.pi / 2, t=t, n_qubits=n_qubits, shots=shots_y)
331
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.14.0
3
+ Version: 9.15.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -7,7 +7,7 @@ with open(README_PATH) as readme_file:
7
7
 
8
8
  setup(
9
9
  name="pyqrackising",
10
- version="9.14.0",
10
+ version="9.15.0",
11
11
  author="Dan Strano",
12
12
  author_email="stranoj@gmail.com",
13
13
  description="Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)",
File without changes
File without changes
File without changes