PyQrackIsing 8.9.3__tar.gz → 8.10.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 (34) hide show
  1. {pyqrackising-8.9.3/pyqrackising.egg-info → pyqrackising-8.10.0}/PKG-INFO +1 -1
  2. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/README.md +1 -1
  3. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyproject.toml +1 -3
  4. pyqrackising-8.10.0/pyqrackising/generate_tfim_samples.py +142 -0
  5. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/maxcut_tfim.py +10 -44
  6. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/maxcut_tfim_sparse.py +10 -44
  7. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/maxcut_tfim_streaming.py +11 -44
  8. pyqrackising-8.10.0/pyqrackising/tfim_magnetization.py +15 -0
  9. pyqrackising-8.10.0/pyqrackising/tfim_square_magnetization.py +14 -0
  10. {pyqrackising-8.9.3 → pyqrackising-8.10.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  11. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising.egg-info/SOURCES.txt +0 -2
  12. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising.egg-info/top_level.txt +0 -1
  13. pyqrackising-8.10.0/setup.py +30 -0
  14. pyqrackising-8.9.3/CMakeLists.txt +0 -16
  15. pyqrackising-8.9.3/pyqrackising/_pyqrack_ising.cpp +0 -252
  16. pyqrackising-8.9.3/pyqrackising/generate_tfim_samples.py +0 -7
  17. pyqrackising-8.9.3/pyqrackising/tfim_magnetization.py +0 -5
  18. pyqrackising-8.9.3/pyqrackising/tfim_square_magnetization.py +0 -5
  19. pyqrackising-8.9.3/setup.py +0 -77
  20. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/LICENSE.md +0 -0
  21. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/MANIFEST.in +0 -0
  22. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/__init__.py +0 -0
  23. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  24. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/kernels.cl +0 -0
  25. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/maxcut_tfim_util.py +0 -0
  26. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/spin_glass_solver.py +0 -0
  27. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  28. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  29. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/spin_glass_solver_util.py +0 -0
  30. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/tsp.py +0 -0
  31. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising/tsp_maxcut.py +0 -0
  32. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  33. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  34. {pyqrackising-8.9.3 → pyqrackising-8.10.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.9.3
3
+ Version: 8.10.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
@@ -18,7 +18,7 @@ From PyPi:
18
18
  pip3 install PyQrackIsing
19
19
  ```
20
20
 
21
- From Source: install `pybind11`, then
21
+ From Source:
22
22
  ```
23
23
  pip3 install .
24
24
  ```
@@ -1,7 +1,5 @@
1
1
  [build-system]
2
2
  requires = [
3
- "cmake",
4
- "pybind11",
5
3
  "setuptools",
6
4
  "networkx",
7
5
  "numpy",
@@ -12,7 +10,7 @@ build-backend = "setuptools.build_meta"
12
10
 
13
11
  [project]
14
12
  name = "pyqrackising"
15
- version = "8.9.3"
13
+ version = "8.10.0"
16
14
  requires-python = ">=3.8"
17
15
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
18
16
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -0,0 +1,142 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight, sample_mag
2
+ import itertools
3
+ import math
4
+ import numpy as np
5
+ from numba import njit
6
+
7
+
8
+ @njit
9
+ def factor_width(width, is_transpose=False):
10
+ col_len = math.floor(math.sqrt(width))
11
+ while ((width // col_len) * col_len) != width:
12
+ col_len -= 1
13
+ row_len = width // col_len
14
+
15
+ return (col_len, row_len) if is_transpose else (row_len, col_len)
16
+
17
+
18
+ # By Gemini (Google Search AI)
19
+ def int_to_bitstring(integer, length):
20
+ return bin(integer)[2:].zfill(length)
21
+
22
+
23
+ # Drafted by Elara (OpenAI custom GPT), improved by Dan Strano
24
+ def closeness_like_bits(perm, n_rows, n_cols):
25
+ """
26
+ Compute closeness-of-like-bits metric C(state) for a given bitstring on an LxL toroidal grid.
27
+
28
+ Parameters:
29
+ perm: integer representing basis state, bit-length n_rows * n_cols
30
+ n_rows: row count of torus
31
+ n_cols: column count of torus
32
+
33
+ Returns:
34
+ normalized_closeness: float, in [-1, +1]
35
+ +1 means all neighbors are like-like, -1 means all neighbors are unlike
36
+ """
37
+ # reshape the bitstring into LxL grid
38
+ bitstring = list(int_to_bitstring(perm, n_rows * n_cols))
39
+ grid = np.array(bitstring).reshape((n_rows, n_cols))
40
+ total_edges = 0
41
+ like_count = 0
42
+
43
+ # iterate over each site, count neighbors (right and down to avoid double-count)
44
+ for i in range(n_rows):
45
+ for j in range(n_cols):
46
+ s = grid[i, j]
47
+
48
+ # right neighbor (wrap around)
49
+ s_right = grid[i, (j + 1) % n_cols]
50
+ like_count += 1 if s == s_right else -1
51
+ total_edges += 1
52
+
53
+ # down neighbor (wrap around)
54
+ s_down = grid[(i + 1) % n_rows, j]
55
+ like_count += 1 if s == s_down else -1
56
+ total_edges += 1
57
+
58
+ # normalize
59
+ normalized_closeness = like_count / total_edges
60
+ return normalized_closeness
61
+
62
+
63
+ @njit
64
+ def comb(n, k):
65
+ if (k < 0) or (k > n):
66
+ return 0
67
+ if (k == 0) or (k == n):
68
+ return 1
69
+ res = 1
70
+ for i in range(1, k + 1):
71
+ res = res * (n - k + i) // i
72
+ return res
73
+
74
+
75
+ @njit
76
+ def expected_closeness_weight(n_rows, n_cols, hamming_weight):
77
+ L = n_rows * n_cols
78
+ same_pairs = comb(hamming_weight, 2) + comb(L - hamming_weight, 2)
79
+ total_pairs = comb(L, 2)
80
+ mu_k = same_pairs / total_pairs
81
+ return 2.0 * mu_k - 1.0
82
+
83
+
84
+ @njit
85
+ def sample_hamming_weight(thresholds, shots):
86
+ hamming_samples = np.zeros(shots, dtype=np.int32)
87
+ for s in range(shots):
88
+ hamming_samples[s] = sample_mag(thresholds)
89
+
90
+ return hamming_samples
91
+
92
+ @njit
93
+ def fix_cdf(hamming_prob):
94
+ hamming_prob /= hamming_prob.sum()
95
+ tot_prob = 0.0
96
+ n_bias = len(hamming_prob)
97
+ cum_prob = np.empty(n_bias, dtype=np.float64)
98
+ for i in range(n_bias):
99
+ tot_prob += hamming_prob[i]
100
+ cum_prob[i] = tot_prob
101
+ cum_prob[-1] = 2.0
102
+
103
+ return cum_prob
104
+
105
+
106
+ def generate_tfim_samples(
107
+ J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100
108
+ ):
109
+ n_rows, n_cols = factor_width(n_qubits)
110
+
111
+ # First dimension: Hamming weight
112
+ thresholds = fix_cdf(probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1))
113
+ hamming_samples = sample_hamming_weight(thresholds, shots)
114
+
115
+ samples = []
116
+ for m in range(len(hamming_samples)):
117
+ # Second dimension: permutation within Hamming weight
118
+ # (Written with help from Elara, the custom OpenAI GPT)
119
+ hs = hamming_samples[m]
120
+ rands = []
121
+ for s in range(hs):
122
+ rands.append(np.random.random())
123
+ rands.sort()
124
+ state_int = 0
125
+ tot_prob = 0
126
+ s = 0
127
+ for combo in itertools.combinations(range(n_qubits), m):
128
+ state_int = sum(1 << pos for pos in combo)
129
+ tot_prob += (1.0 + closeness_like_bits(state_int, n_rows, n_cols)) / (
130
+ 1.0 + expected_closeness_weight(n_rows, n_cols, m)
131
+ )
132
+ while (s < hs) and (rands[s] <= tot_prob):
133
+ samples.append(state_int)
134
+ s += 1
135
+ if s == hs:
136
+ break
137
+ for r in range(hs - s):
138
+ samples.append(state_int)
139
+
140
+ np.random.shuffle(samples)
141
+
142
+ return samples
@@ -68,7 +68,7 @@ def compute_energy(sample, G_m, n_qubits):
68
68
  val = G_m[u, v]
69
69
  energy += val if sample[u] == sample[v] else -val
70
70
 
71
- return energy
71
+ return -energy
72
72
 
73
73
 
74
74
  @njit
@@ -83,7 +83,7 @@ def compute_cut(sample, G_m, n_qubits):
83
83
 
84
84
 
85
85
  @njit(parallel=True)
86
- def sample_for_energy(G_m, max_edge, shots, thresholds, weights, repulsion_base):
86
+ def sample_measurement(G_m, max_edge, shots, thresholds, weights, repulsion_base, is_spin_glass):
87
87
  shots = max(1, shots >> 1)
88
88
  n = len(G_m)
89
89
  tot_init_weight = weights.sum()
@@ -92,7 +92,7 @@ def sample_for_energy(G_m, max_edge, shots, thresholds, weights, repulsion_base)
92
92
  energies = np.empty(shots, dtype=dtype)
93
93
 
94
94
  best_solution = solutions[0]
95
- best_energy = float("inf")
95
+ best_energy = -float("inf")
96
96
 
97
97
  improved = True
98
98
  while improved:
@@ -104,50 +104,19 @@ def sample_for_energy(G_m, max_edge, shots, thresholds, weights, repulsion_base)
104
104
  # Second dimension: permutation within Hamming weight
105
105
  sample = local_repulsion_choice(G_m, max_edge, weights, tot_init_weight, repulsion_base, n, m)
106
106
  solutions[s] = sample
107
- energies[s] = compute_energy(sample, G_m, n)
107
+ energies[s] = compute_energy(sample, G_m, n) if is_spin_glass else compute_cut(sample, G_m, n)
108
108
 
109
- best_index = np.argmin(energies)
109
+ best_index = np.argmax(energies)
110
110
  energy = energies[best_index]
111
- if energy < best_energy:
111
+ if energy > best_energy:
112
112
  best_energy = energy
113
113
  best_solution = solutions[best_index].copy()
114
114
  improved = True
115
115
 
116
- return best_solution, compute_cut(best_solution, G_m, n)
117
-
118
-
119
- @njit(parallel=True)
120
- def sample_for_cut(G_m, max_edge, shots, thresholds, weights, repulsion_base):
121
- shots = max(1, shots >> 1)
122
- n = len(G_m)
123
- tot_init_weight = weights.sum()
124
-
125
- solutions = np.empty((shots, n), dtype=np.bool_)
126
- cuts = np.empty(shots, dtype=dtype)
127
-
128
- best_solution = solutions[0]
129
- best_cut = -float("inf")
130
-
131
- improved = True
132
- while improved:
133
- improved = False
134
- for s in prange(shots):
135
- # First dimension: Hamming weight
136
- m = sample_mag(thresholds)
137
-
138
- # Second dimension: permutation within Hamming weight
139
- sample = local_repulsion_choice(G_m, max_edge, weights, tot_init_weight, repulsion_base, n, m)
140
- solutions[s] = sample
141
- cuts[s] = compute_cut(sample, G_m, n)
142
-
143
- best_index = np.argmax(cuts)
144
- cut = cuts[best_index]
145
- if cut > best_cut:
146
- best_cut = cut
147
- best_solution = solutions[best_index].copy()
148
- improved = True
116
+ if is_spin_glass:
117
+ best_energy = compute_cut(best_solution, G_m, n)
149
118
 
150
- return best_solution, best_cut
119
+ return best_solution, best_energy
151
120
 
152
121
 
153
122
  @njit(parallel=True)
@@ -182,10 +151,7 @@ def cpu_footer(shots, quality, n_qubits, G_m, nodes, is_spin_glass, anneal_t, an
182
151
  degrees = None
183
152
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
184
153
 
185
- if is_spin_glass:
186
- best_solution, best_value = sample_for_energy(G_m, max_edge, shots, hamming_prob, J_eff, repulsion_base)
187
- else:
188
- best_solution, best_value = sample_for_cut(G_m, max_edge, shots, hamming_prob, J_eff, repulsion_base)
154
+ best_solution, best_value = sample_measurement(G_m, max_edge, shots, hamming_prob, J_eff, repulsion_base, is_spin_glass)
189
155
 
190
156
  bit_string, l, r = get_cut(best_solution, nodes)
191
157
 
@@ -78,7 +78,7 @@ def compute_energy(sample, G_data, G_rows, G_cols, n_qubits):
78
78
  val = G_data[col]
79
79
  energy += val if sample[u] == sample[v] else -val
80
80
 
81
- return energy
81
+ return -energy
82
82
 
83
83
 
84
84
  @njit
@@ -94,7 +94,7 @@ def compute_cut(sample, G_data, G_rows, G_cols, n_qubits):
94
94
 
95
95
 
96
96
  @njit(parallel=True)
97
- def sample_for_energy(max_edge, G_data, G_rows, G_cols, shots, thresholds, weights, repulsion_base):
97
+ def sample_measurement(max_edge, G_data, G_rows, G_cols, shots, thresholds, weights, repulsion_base, is_spin_glass):
98
98
  shots = max(1, shots >> 1)
99
99
  n = G_rows.shape[0] - 1
100
100
  tot_init_weight = weights.sum()
@@ -103,7 +103,7 @@ def sample_for_energy(max_edge, G_data, G_rows, G_cols, shots, thresholds, weigh
103
103
  energies = np.empty(shots, dtype=dtype)
104
104
 
105
105
  best_solution = solutions[0]
106
- best_energy = float("inf")
106
+ best_energy = -float("inf")
107
107
 
108
108
  improved = True
109
109
  while improved:
@@ -115,50 +115,19 @@ def sample_for_energy(max_edge, G_data, G_rows, G_cols, shots, thresholds, weigh
115
115
  # Second dimension: permutation within Hamming weight
116
116
  sample = local_repulsion_choice(G_cols, G_data, G_rows, max_edge, weights, tot_init_weight, repulsion_base, n, m)
117
117
  solutions[s] = sample
118
- energies[s] = compute_energy(sample, G_data, G_rows, G_cols, n)
118
+ energies[s] = compute_energy(sample, G_data, G_rows, G_cols, n) if is_spin_glass else compute_cut(sample, G_data, G_rows, G_cols, n)
119
119
 
120
- best_index = np.argmin(energies)
120
+ best_index = np.argmax(energies)
121
121
  energy = energies[best_index]
122
- if energy < best_energy:
122
+ if energy > best_energy:
123
123
  best_energy = energy
124
124
  best_solution = solutions[best_index].copy()
125
125
  improved = True
126
126
 
127
- return best_solution, compute_cut(best_solution, G_data, G_rows, G_cols, n)
128
-
129
-
130
- @njit(parallel=True)
131
- def sample_for_cut(max_edge, G_data, G_rows, G_cols, shots, thresholds, weights, repulsion_base):
132
- shots = max(1, shots >> 1)
133
- n = G_rows.shape[0] - 1
134
- tot_init_weight = weights.sum()
135
-
136
- solutions = np.empty((shots, n), dtype=np.bool_)
137
- cuts = np.empty(shots, dtype=dtype)
138
-
139
- best_solution = solutions[0]
140
- best_cut = -float("inf")
141
-
142
- improved = True
143
- while improved:
144
- improved = False
145
- for s in prange(shots):
146
- # First dimension: Hamming weight
147
- m = sample_mag(thresholds)
148
-
149
- # Second dimension: permutation within Hamming weight
150
- sample = local_repulsion_choice(G_cols, G_data, G_rows, max_edge, weights, tot_init_weight, repulsion_base, n, m)
151
- solutions[s] = sample
152
- cuts[s] = compute_cut(sample, G_data, G_rows, G_cols, n)
153
-
154
- best_index = np.argmax(cuts)
155
- cut = cuts[best_index]
156
- if cut > best_cut:
157
- best_cut = cut
158
- best_solution = solutions[best_index].copy()
159
- improved = True
127
+ if is_spin_glass:
128
+ best_energy = compute_cut(best_solution, G_data, G_rows, G_cols, n)
160
129
 
161
- return best_solution, best_cut
130
+ return best_solution, best_energy
162
131
 
163
132
 
164
133
  @njit(parallel=True)
@@ -197,10 +166,7 @@ def cpu_footer(shots, quality, n_qubits, max_edge, G_data, G_rows, G_col, nodes,
197
166
  degrees = None
198
167
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
199
168
 
200
- if is_spin_glass:
201
- best_solution, best_value = sample_for_energy(max_edge, G_data, G_rows, G_col, shots, hamming_prob, J_eff, repulsion_base)
202
- else:
203
- best_solution, best_value = sample_for_cut(max_edge, G_data, G_rows, G_col, shots, hamming_prob, J_eff, repulsion_base)
169
+ best_solution, best_value = sample_measurement(max_edge, G_data, G_rows, G_col, shots, hamming_prob, J_eff, repulsion_base, is_spin_glass)
204
170
 
205
171
  bit_string, l, r = get_cut(best_solution, nodes)
206
172
 
@@ -68,7 +68,7 @@ def compute_energy(sample, G_func, nodes, n_qubits):
68
68
  val = G_func(nodes[u], nodes[v])
69
69
  energy += val if sample[u] == sample[v] else -val
70
70
 
71
- return energy
71
+ return -energy
72
72
 
73
73
 
74
74
  @njit
@@ -83,7 +83,7 @@ def compute_cut(sample, G_func, nodes, n_qubits):
83
83
 
84
84
 
85
85
  @njit(parallel=True)
86
- def sample_for_energy(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n, repulsion_base):
86
+ def sample_measurement(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n, repulsion_base, is_spin_glass):
87
87
  shots = max(1, shots >> 1)
88
88
  tot_init_weight = weights.sum()
89
89
 
@@ -91,7 +91,7 @@ def sample_for_energy(G_func, nodes, max_edge, shots, thresholds, degrees_sum, w
91
91
  energies = np.empty(shots, dtype=dtype)
92
92
 
93
93
  best_solution = solutions[0]
94
- best_energy = float("inf")
94
+ best_energy = -float("inf")
95
95
 
96
96
  improved = True
97
97
  while improved:
@@ -103,49 +103,19 @@ def sample_for_energy(G_func, nodes, max_edge, shots, thresholds, degrees_sum, w
103
103
  # Second dimension: permutation within Hamming weight
104
104
  sample = local_repulsion_choice(G_func, nodes, max_edge, weights, tot_init_weight, repulsion_base, n, m)
105
105
  solutions[s] = sample
106
- energies[s] = compute_energy(sample, G_func, nodes, n)
106
+ energies[s] = compute_energy(sample, G_func, nodes, n) if is_spin_glass else compute_cut(sample, G_func, nodes, n)
107
107
 
108
- best_index = np.argmin(energies)
108
+ best_index = np.argmax(energies)
109
109
  energy = energies[best_index]
110
- if energy < best_energy:
110
+ if energy > best_energy:
111
111
  best_energy = energy
112
112
  best_solution = solutions[best_index].copy()
113
113
  improved = True
114
114
 
115
- return best_solution, compute_cut(best_solution, G_func, nodes, n)
116
-
117
-
118
- @njit(parallel=True)
119
- def sample_for_cut(G_func, nodes, max_edge, shots, thresholds, degrees_sum, weights, n, repulsion_base):
120
- shots = max(1, shots >> 1)
121
- tot_init_weight = weights.sum()
122
-
123
- solutions = np.empty((shots, n), dtype=np.bool_)
124
- cuts = np.empty(shots, dtype=dtype)
125
-
126
- best_solution = solutions[0]
127
- best_cut = -float("inf")
128
-
129
- improved = True
130
- while improved:
131
- improved = False
132
- for s in prange(shots):
133
- # First dimension: Hamming weight
134
- m = sample_mag(thresholds)
135
-
136
- # Second dimension: permutation within Hamming weight
137
- sample = local_repulsion_choice(G_func, nodes, max_edge, weights, tot_init_weight, repulsion_base, n, m)
138
- solutions[s] = sample
139
- cuts[s] = compute_cut(sample, G_func, nodes, n)
140
-
141
- best_index = np.argmax(cuts)
142
- cut = cuts[best_index]
143
- if cut > best_cut:
144
- best_cut = cut
145
- best_solution = solutions[best_index].copy()
146
- improved = True
115
+ if is_spin_glass:
116
+ best_energy = compute_cut(best_solution, G_func, nodes, n)
147
117
 
148
- return best_solution, best_cut
118
+ return best_solution, best_energy
149
119
 
150
120
 
151
121
  @njit(parallel=True)
@@ -176,15 +146,12 @@ def init_J_and_z(G_func, nodes):
176
146
  def cpu_footer(shots, quality, n_qubits, G_func, nodes, is_spin_glass, anneal_t, anneal_h, repulsion_base):
177
147
  J_eff, degrees, max_edge = init_J_and_z(G_func, nodes)
178
148
  hamming_prob = maxcut_hamming_cdf(n_qubits, J_eff, degrees, quality, anneal_t, anneal_h)
179
- max_edge = degrees.sum()
149
+ degrees_sum = degrees.sum()
180
150
 
181
151
  degrees = None
182
152
  J_eff = 1.0 / (1.0 + epsilon - J_eff)
183
153
 
184
- if is_spin_glass:
185
- best_solution, best_value = sample_for_energy(G_func, nodes, max_edge, shots, hamming_prob, max_edge, J_eff, n_qubits, repulsion_base)
186
- else:
187
- best_solution, best_value = sample_for_cut(G_func, nodes, max_edge, shots, hamming_prob, max_edge, J_eff, n_qubits, repulsion_base)
154
+ best_solution, best_value = sample_measurement(G_func, nodes, max_edge, shots, hamming_prob, degrees_sum, J_eff, n_qubits, repulsion_base, is_spin_glass)
188
155
 
189
156
  bit_string, l, r = get_cut(best_solution, nodes)
190
157
 
@@ -0,0 +1,15 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight
2
+ from numba import njit
3
+
4
+
5
+ @njit
6
+ def tfim_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
7
+ bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1)
8
+ bias /= bias.sum()
9
+ magnetization = 0.0
10
+ nqs = int(n_qubits)
11
+ nqd = float(n_qubits)
12
+ for q in range(n_qubits + 1):
13
+ mag = (nqs - 2 * q) / nqd
14
+ magnetization += bias[q] * mag
15
+ return magnetization
@@ -0,0 +1,14 @@
1
+ from .maxcut_tfim_util import probability_by_hamming_weight
2
+ from numba import njit
3
+
4
+ @njit
5
+ def tfim_square_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
6
+ bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits + 1)
7
+ bias /= bias.sum()
8
+ square_magnetization = 0.0
9
+ nqs = int(n_qubits)
10
+ nqd = float(n_qubits)
11
+ for q in range(n_qubits + 1):
12
+ mag = (nqs - 2 * q) / nqd
13
+ square_magnetization += bias[q] * mag * mag
14
+ return square_magnetization
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.9.3
3
+ Version: 8.10.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
@@ -1,11 +1,9 @@
1
- CMakeLists.txt
2
1
  LICENSE.md
3
2
  MANIFEST.in
4
3
  README.md
5
4
  pyproject.toml
6
5
  setup.py
7
6
  pyqrackising/__init__.py
8
- pyqrackising/_pyqrack_ising.cpp
9
7
  pyqrackising/convert_tensor_network_to_tsp.py
10
8
  pyqrackising/generate_tfim_samples.py
11
9
  pyqrackising/kernels.cl
@@ -1,2 +1 @@
1
1
  pyqrackising
2
- tfim_sampler
@@ -0,0 +1,30 @@
1
+ from setuptools import setup
2
+ import os
3
+
4
+ README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')
5
+ with open(README_PATH) as readme_file:
6
+ README = readme_file.read()
7
+
8
+ setup(
9
+ name='pyqrackising',
10
+ version='8.10.0',
11
+ author='Dan Strano',
12
+ author_email='stranoj@gmail.com',
13
+ description='Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)',
14
+ long_description=README,
15
+ long_description_content_type='text/markdown',
16
+ url="https://github.com/vm6502q/PyQrackIsing",
17
+ license="LGPL-3.0-or-later",
18
+ classifiers=[
19
+ "Environment :: Console",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: Science/Research",
22
+ "Programming Language :: C++",
23
+ "Programming Language :: Python :: 3.8",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Topic :: Scientific/Engineering",
27
+ ],
28
+ packages=['pyqrackising'],
29
+ zip_safe=False,
30
+ )
@@ -1,16 +0,0 @@
1
- cmake_minimum_required(VERSION 3.15...3.29)
2
- project(PyQrackIsing LANGUAGES CXX)
3
-
4
- set(PYBIND11_FINDPYTHON ON)
5
- find_package(pybind11 CONFIG REQUIRED)
6
- find_package(Boost CONFIG REQUIRED)
7
- pybind11_add_module(tfim_sampler pyqrackising/_pyqrack_ising.cpp)
8
- target_include_directories(tfim_sampler PUBLIC ${Boost_INCLUDE_DIR})
9
-
10
- if (MSVC)
11
- target_compile_options(tfim_sampler PUBLIC /O2 /std:c++17)
12
- else (MSVC)
13
- target_compile_options(tfim_sampler PUBLIC -O3 -std=c++17)
14
- endif (MSVC)
15
-
16
- install(TARGETS tfim_sampler DESTINATION .)
@@ -1,252 +0,0 @@
1
- // C++/pybind11 translation of TFIM function and maxcut_tfim()
2
- // Original algorithm by Dan Strano and Elara (OpenAI GPT), 2024
3
-
4
- #define _USE_MATH_DEFINES
5
- #include <pybind11/pybind11.h>
6
- #include <pybind11/numpy.h>
7
- #include <pybind11/stl.h>
8
- #include <cmath>
9
- #include <limits>
10
- #include <random>
11
- #include <string>
12
- #include <vector>
13
- #include <bitset>
14
- #include <algorithm>
15
- #include <numeric>
16
- #include <unordered_set>
17
- #include <unordered_map>
18
- #include <tuple>
19
- #include <boost/multiprecision/cpp_int.hpp>
20
- #include <boost/functional/hash.hpp>
21
-
22
- namespace py = pybind11;
23
-
24
- typedef boost::multiprecision::cpp_int BigInteger;
25
-
26
- std::random_device rd = std::random_device{};
27
- std::mt19937 rng(rd());
28
-
29
-
30
- static inline std::vector<double> probability_by_hamming_weight(double J, double h, double z, double theta, double t, size_t n_qubits)
31
- {
32
- // critical angle
33
- const double theta_c = std::asin(std::max(-1.0, std::min(1.0, (std::abs(z * J) >= (std::numeric_limits<double>::epsilon() / 2)) ? std::abs(h) / (z * J) : (J > 0 ? 1.0 : -1.0))));
34
- const double delta_theta = theta - theta_c;
35
- std::vector<double> bias(n_qubits + 1, 0.0);
36
- if (std::abs(h) < 1e-12) {
37
- bias[0] = 1.0;
38
- } else if (std::abs(J) < 1e-12) {
39
- std::fill(bias.begin(), bias.end(), 1.0 / (n_qubits + 1.0));
40
- } else {
41
- const double sin_delta = std::sin(delta_theta);
42
- constexpr double omega = 1.5 * M_PI;
43
- constexpr double t2 = 1.0;
44
- const double p = std::pow(2.0, std::abs(J / h) - 1.0) * (1.0 + sin_delta * std::cos(J * omega * t + theta) / (1.0 + std::sqrt(t / t2))) - 0.5;
45
- if ((p * n_qubits) >= 1024) {
46
- bias[0] = 1.0;
47
- } else {
48
- const double factor = std::pow(2.0, -p / (n_qubits + 1));
49
- double n = 1.0;
50
- double tot_n = 0.0;
51
- for (size_t q = 0U; q <= n_qubits; ++q) {
52
- bias[q] = n;
53
- tot_n += n;
54
- n *= factor;
55
- }
56
- for (size_t q = 0U; q <= n_qubits; ++q) {
57
- bias[q] /= tot_n;
58
- }
59
- }
60
- }
61
- if (J > 0) {
62
- std::reverse(bias.begin(), bias.end());
63
- }
64
-
65
- return bias;
66
- }
67
-
68
- static inline std::string int_to_bitstring(BigInteger integer, size_t length) {
69
- std::string s(length, '0');
70
- for (size_t i = 0; i < length; ++i) {
71
- if (integer & (1ULL << (length - 1U - i))) {
72
- s[i] = '1';
73
- }
74
- }
75
- return s;
76
- }
77
-
78
- static inline double closeness_like_bits(BigInteger perm, size_t n_rows, size_t n_cols) {
79
- std::string bits = int_to_bitstring(perm, n_rows * n_cols);
80
- double like_count = 0.0;
81
- double total_edges = 0.0;
82
- // grid neighbors (right and down)
83
- for (size_t i = 0; i < n_rows; ++i) {
84
- for (size_t j = 0; j < n_cols; ++j) {
85
- char s = bits[i * n_cols + j];
86
- char s_right = bits[i * n_cols + ((j + 1) % n_cols)];
87
- char s_down = bits[((i + 1) % n_rows) * n_cols + j];
88
- like_count += (s == s_right) ? 1.0 : -1.0;
89
- like_count += (s == s_down) ? 1.0 : -1.0;
90
- total_edges += 2.0;
91
- }
92
- }
93
- return like_count / total_edges;
94
- }
95
-
96
- static inline double expected_closeness_weight(size_t n_rows, size_t n_cols, size_t hamming_weight) {
97
- const size_t L = n_rows * n_cols;
98
- auto comb = [](size_t n, size_t k) {
99
- if ((k < 0) || (k > n)) {
100
- return 0ULL;
101
- }
102
- if ((k == 0) || (k == n)) {
103
- return 1ULL;
104
- }
105
- unsigned long long res = 1ULL;
106
- for (size_t i = 1; i <= k; ++i) {
107
- res = res * (n - k + i) / i;
108
- }
109
- return res;
110
- };
111
- const double same_pairs = comb(hamming_weight, 2U) + comb(L - hamming_weight, 2U);
112
- const double total_pairs = comb(L, 2U);
113
- const double mu_k = same_pairs / total_pairs;
114
-
115
- return 2.0 * mu_k - 1.0;
116
- }
117
-
118
- std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z, double theta, double t, size_t n_qubits, size_t shots) {
119
- // lattice dimensions
120
- size_t n_rows = 1U;
121
- size_t n_cols = n_qubits;
122
- for (size_t c = std::floor(std::sqrt(n_qubits)); c >= 1; --c) {
123
- if ((n_qubits % c) == 0U) {
124
- n_rows = n_qubits / c;
125
- n_cols = c;
126
- break;
127
- }
128
- }
129
-
130
- const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
131
-
132
- // thresholds
133
- std::vector<double> thresholds(n_qubits + 1);
134
- double tot_prob = 0.0;
135
- for (size_t q = 0U; q <= n_qubits; ++q) {
136
- tot_prob += bias[q];
137
- thresholds[q] = tot_prob;
138
- }
139
- thresholds[n_qubits] = 1.0;
140
-
141
- std::uniform_real_distribution<double> dist(0.0, 1.0);
142
-
143
- std::vector<BigInteger> samples;
144
- samples.reserve(shots);
145
-
146
- std::vector<int> qubits(n_qubits);
147
- for (size_t i = 0U; i < n_qubits; ++i) {
148
- qubits[i] = i;
149
- }
150
-
151
- std::vector<size_t> hamming_samples(n_qubits + 1U);
152
- for (size_t s = 0U; s < shots; ++s) {
153
- double mag_prob = dist(rng);
154
- size_t m = 0U;
155
- while (thresholds[m] < mag_prob) {
156
- ++m;
157
- }
158
- ++hamming_samples[m];
159
- }
160
- for (size_t m = 0U; m < hamming_samples.size(); ++m){
161
- double tot_cprob = 0.0;
162
- size_t hs = hamming_samples[m];
163
- std::vector<double> rands;
164
- rands.reserve(hs);
165
- for (size_t s = 0U; s < hs; ++s) {
166
- rands.push_back(dist(rng));
167
- }
168
- std::sort(rands.begin(), rands.end());
169
- // iterate combinations
170
- std::vector<size_t> idx(m);
171
- for (size_t i = 0U; i < m; ++i) {
172
- idx[i] = i;
173
- }
174
- size_t s = 0U;
175
- while (true) {
176
- BigInteger candidate = 0U;
177
- for (size_t pos : idx) {
178
- candidate |= (BigInteger("1") << pos);
179
- }
180
- tot_cprob += (1.0 + closeness_like_bits(candidate, n_rows, n_cols)) /
181
- (1.0 + expected_closeness_weight(n_rows, n_cols, m));
182
- while ((s < hs) && (rands[s] <= tot_cprob)) {
183
- samples.push_back(candidate);
184
- ++s;
185
- }
186
- if (s == hs) {
187
- break;
188
- }
189
-
190
- // next combination
191
- int64_t k = m - 1;
192
- while ((k >= 0) && (idx[k] == (n_qubits - m + k))) {
193
- --k;
194
- }
195
- if (k < 0) {
196
- for (; s < hs; ++s) {
197
- samples.push_back(candidate);
198
- }
199
- break;
200
- }
201
- ++idx[k];
202
- for (int64_t j = k + 1; j < m; ++j) {
203
- idx[j] = idx[j - 1U] + 1;
204
- }
205
- }
206
- }
207
-
208
- auto dre = std::default_random_engine{rd()};
209
- std::shuffle(samples.begin(), samples.end(), dre);
210
-
211
- std::vector<std::string> output;
212
- output.reserve(shots);
213
- for (BigInteger& s : samples) {
214
- output.push_back(boost::lexical_cast<std::string>(s));
215
- }
216
-
217
- return output;
218
- }
219
-
220
- double tfim_magnetization(double J, double h, double z, double theta, double t, size_t n_qubits) {
221
- const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
222
- double magnetization = 0.0;
223
- const int64_t nqs = (int64_t)n_qubits;
224
- const double nqd = (double)n_qubits;
225
- for (int64_t q = 0U; q < bias.size(); ++q) {
226
- const double mag = (nqs - 2 * q) / nqd;
227
- magnetization += bias[q] * mag;
228
- }
229
-
230
- return magnetization;
231
- }
232
-
233
- double tfim_square_magnetization(double J, double h, double z, double theta, double t, size_t n_qubits) {
234
- const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
235
- double square_magnetization = 0.0;
236
- const int64_t nqs = (int64_t)n_qubits;
237
- const double nqd = (double)n_qubits;
238
- for (int64_t q = 0U; q < bias.size(); ++q) {
239
- const double mag = (nqs - 2 * q) / nqd;
240
- square_magnetization += bias[q] * mag * mag;
241
- }
242
-
243
- return square_magnetization;
244
- }
245
-
246
- PYBIND11_MODULE(tfim_sampler, m) {
247
- m.doc() = "PyQrackIsing TFIM sample generator";
248
- m.def("_generate_tfim_samples", &generate_tfim_samples_cpp, "Generate measurement samples from globally-uniform TFIM");
249
- m.def("_tfim_magnetization", &tfim_magnetization, "Magnetization expectation value from globally-uniform TFIM");
250
- m.def("_tfim_square_magnetization", &tfim_square_magnetization, "Square magnetization expectation value from globally-uniform TFIM");
251
- }
252
-
@@ -1,7 +0,0 @@
1
- import tfim_sampler
2
-
3
-
4
- def generate_tfim_samples(
5
- J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56, shots=100
6
- ):
7
- return [int(s) for s in tfim_sampler._generate_tfim_samples(J, h, z, theta, t, n_qubits, shots)]
@@ -1,5 +0,0 @@
1
- import tfim_sampler
2
-
3
-
4
- def tfim_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
5
- return tfim_sampler._tfim_magnetization(J, h, z, theta, t, n_qubits)
@@ -1,5 +0,0 @@
1
- import tfim_sampler
2
-
3
-
4
- def tfim_square_magnetization(J=-1.0, h=2.0, z=4, theta=0.174532925199432957, t=5, n_qubits=56):
5
- return tfim_sampler._tfim_square_magnetization(J, h, z, theta, t, n_qubits)
@@ -1,77 +0,0 @@
1
- from setuptools import setup, Extension
2
- from setuptools.command.build_ext import build_ext
3
- import os
4
-
5
- class CMakeExtension(Extension):
6
- def __init__(self, name, sourcedir=''):
7
- Extension.__init__(self, name, sources=[])
8
- self.sourcedir = os.path.abspath(sourcedir)
9
-
10
- class CMakeBuild(build_ext):
11
- def run(self):
12
- try:
13
- import cmake
14
- except ImportError:
15
- raise RuntimeError("CMake must be installed to build the following extensions: " +
16
- ", ".join(e.name for e in self.extensions))
17
-
18
- for ext in self.extensions:
19
- self.build_extension(ext)
20
-
21
- def build_extension(self, ext):
22
- extdir = os.path.abspath(os.path.dirname(self.get_ext_fullpath(ext.name)))
23
- cfg = 'Release'
24
- cmake_args = [
25
- f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}',
26
- f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_{cfg.upper()}={extdir}',
27
- f'-DCMAKE_BUILD_TYPE={cfg}',
28
- ]
29
-
30
- cmake_args = ['-DCMAKE_BUILD_TYPE=Release', f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}']
31
- toolchain = os.environ.get("BOOST_TOOLCHAIN_FILE")
32
- if toolchain:
33
- cmake_args += [f'-DCMAKE_TOOLCHAIN_FILE={toolchain}']
34
- root = os.environ.get("BOOST_ROOT")
35
- if root:
36
- cmake_args += ['-DBoost_NO_SYSTEM_PATHS=TRUE', f'-DBOOST_ROOT={root}']
37
- include = os.environ.get("BOOST_INCLUDEDIR")
38
- if include:
39
- cmake_args += [f'-DBoost_INCLUDE_DIR={include}']
40
-
41
- build_temp = self.build_temp
42
- os.makedirs(build_temp, exist_ok=True)
43
- self.spawn(['cmake', '-B', build_temp, '-S', ext.sourcedir] + cmake_args)
44
- self.spawn(['cmake', '--build', build_temp, '--config', cfg])
45
-
46
- README_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.md')
47
- with open(README_PATH) as readme_file:
48
- README = readme_file.read()
49
-
50
- ext_modules = [CMakeExtension('tfim_sampler')]
51
-
52
- setup(
53
- name='pyqrackising',
54
- version='8.9.3',
55
- author='Dan Strano',
56
- author_email='stranoj@gmail.com',
57
- description='Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)',
58
- long_description=README,
59
- long_description_content_type='text/markdown',
60
- url="https://github.com/vm6502q/PyQrackIsing",
61
- license="LGPL-3.0-or-later",
62
- classifiers=[
63
- "Environment :: Console",
64
- "Intended Audience :: Developers",
65
- "Intended Audience :: Science/Research",
66
- "Programming Language :: C++",
67
- "Programming Language :: Python :: 3.8",
68
- "Programming Language :: Python :: 3.9",
69
- "Programming Language :: Python :: 3.10",
70
- "Topic :: Scientific/Engineering",
71
- ],
72
- install_requires=["pybind11"],
73
- ext_modules=ext_modules,
74
- cmdclass=dict(build_ext=CMakeBuild),
75
- packages=['pyqrackising'],
76
- zip_safe=False,
77
- )
File without changes
File without changes
File without changes