PyQrackIsing 8.9.4__tar.gz → 8.10.1__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.4/pyqrackising.egg-info → pyqrackising-8.10.1}/PKG-INFO +1 -1
  2. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/README.md +1 -1
  3. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyproject.toml +1 -3
  4. pyqrackising-8.10.1/pyqrackising/generate_tfim_samples.py +142 -0
  5. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/maxcut_tfim.py +35 -18
  6. pyqrackising-8.10.1/pyqrackising/tfim_magnetization.py +15 -0
  7. pyqrackising-8.10.1/pyqrackising/tfim_square_magnetization.py +14 -0
  8. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/tsp.py +89 -71
  9. {pyqrackising-8.9.4 → pyqrackising-8.10.1/pyqrackising.egg-info}/PKG-INFO +1 -1
  10. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising.egg-info/SOURCES.txt +0 -2
  11. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising.egg-info/top_level.txt +0 -1
  12. pyqrackising-8.10.1/setup.py +30 -0
  13. pyqrackising-8.9.4/CMakeLists.txt +0 -16
  14. pyqrackising-8.9.4/pyqrackising/_pyqrack_ising.cpp +0 -252
  15. pyqrackising-8.9.4/pyqrackising/generate_tfim_samples.py +0 -7
  16. pyqrackising-8.9.4/pyqrackising/tfim_magnetization.py +0 -5
  17. pyqrackising-8.9.4/pyqrackising/tfim_square_magnetization.py +0 -5
  18. pyqrackising-8.9.4/setup.py +0 -77
  19. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/LICENSE.md +0 -0
  20. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/MANIFEST.in +0 -0
  21. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/__init__.py +0 -0
  22. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  23. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/kernels.cl +0 -0
  24. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  25. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  26. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/maxcut_tfim_util.py +0 -0
  27. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/spin_glass_solver.py +0 -0
  28. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/spin_glass_solver_sparse.py +0 -0
  29. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/spin_glass_solver_streaming.py +0 -0
  30. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/spin_glass_solver_util.py +0 -0
  31. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising/tsp_maxcut.py +0 -0
  32. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising.egg-info/dependency_links.txt +0 -0
  33. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/pyqrackising.egg-info/not-zip-safe +0 -0
  34. {pyqrackising-8.9.4 → pyqrackising-8.10.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.9.4
3
+ Version: 8.10.1
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.4"
13
+ version = "8.10.1"
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
@@ -158,8 +158,10 @@ def cpu_footer(shots, quality, n_qubits, G_m, nodes, is_spin_glass, anneal_t, an
158
158
  return bit_string, best_value, (l, r)
159
159
 
160
160
 
161
- def maxcut_tfim(
162
- G,
161
+ @njit
162
+ def maxcut_tfim_pure_numba(
163
+ G_m,
164
+ nodes,
163
165
  quality=None,
164
166
  shots=None,
165
167
  is_spin_glass=False,
@@ -167,30 +169,22 @@ def maxcut_tfim(
167
169
  anneal_h=None,
168
170
  repulsion_base=None
169
171
  ):
170
- wgs = opencl_context.work_group_size
171
- nodes = None
172
- n_qubits = 0
173
- G_m = None
174
- if isinstance(G, nx.Graph):
175
- nodes = list(G.nodes())
176
- n_qubits = len(nodes)
177
- G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0, dtype=dtype)
178
- else:
179
- n_qubits = len(G)
180
- nodes = list(range(n_qubits))
181
- G_m = G
172
+ n_qubits = len(G_m)
182
173
 
183
174
  if n_qubits < 3:
175
+ empty = [nodes[0]]
176
+ empty.clear()
177
+
184
178
  if n_qubits == 0:
185
- return "", 0, ([], [])
179
+ return "", 0, (empty, empty.copy())
186
180
 
187
181
  if n_qubits == 1:
188
- return "0", 0, (nodes, [])
182
+ return "0", 0, (nodes, empty)
189
183
 
190
184
  if n_qubits == 2:
191
185
  weight = G_m[0, 1]
192
186
  if weight < 0.0:
193
- return "00", 0, (nodes, [])
187
+ return "00", 0, (nodes, empty)
194
188
 
195
189
  return "01", weight, ([nodes[0]], [nodes[1]])
196
190
 
@@ -214,6 +208,29 @@ def maxcut_tfim(
214
208
 
215
209
  if best_value < 0.0:
216
210
  # Best cut is trivial partition, all/empty
217
- return '0' * n_qubits, 0.0, (nodes, [])
211
+ empty = [nodes[0]]
212
+ empty.clear()
213
+
214
+ return '0' * n_qubits, 0.0, (nodes, empty)
218
215
 
219
216
  return bit_string, best_value, partition
217
+
218
+ def maxcut_tfim(
219
+ G,
220
+ quality=None,
221
+ shots=None,
222
+ is_spin_glass=False,
223
+ anneal_t=None,
224
+ anneal_h=None,
225
+ repulsion_base=None
226
+ ):
227
+ nodes = None
228
+ G_m = None
229
+ if isinstance(G, nx.Graph):
230
+ nodes = list(G.nodes())
231
+ G_m = nx.to_numpy_array(G, weight='weight', nonedge=0.0, dtype=dtype)
232
+ else:
233
+ nodes = list(range(len(G)))
234
+ G_m = G
235
+
236
+ return maxcut_tfim_pure_numba(G_m, nodes, quality, shots, is_spin_glass, anneal_t, anneal_h, repulsion_base)
@@ -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,5 +1,5 @@
1
1
  from .maxcut_tfim_util import binary_search, opencl_context, to_scipy_sparse_upper_triangular
2
- from .maxcut_tfim import maxcut_tfim
2
+ from .maxcut_tfim import maxcut_tfim_pure_numba
3
3
  from concurrent.futures import ProcessPoolExecutor
4
4
  import time
5
5
  import itertools
@@ -621,6 +621,47 @@ def tsp_symmetric_driver(G_m, is_cyclic, is_top_level, start_node, end_node, k_n
621
621
  return [nodes[x] for x in best_path], best_weight
622
622
 
623
623
 
624
+ @njit
625
+ def tsp_symmetric_header(G_m, nodes, quality, shots, anneal_t, anneal_h, repulsion_base, start_node, end_node, monte_carlo, is_cyclic, n_nodes, multi_start):
626
+ if is_cyclic:
627
+ start_node = None
628
+ end_node = None
629
+
630
+ if (start_node is None) and not (end_node is None):
631
+ start_node = end_node
632
+ end_node = None
633
+
634
+ a, b, c = [0], [0], [0]
635
+ a.clear()
636
+ b.clear()
637
+ c.clear()
638
+ if (start_node is None) and (end_node is None):
639
+ if monte_carlo:
640
+ a, b = monte_carlo_loop(n_nodes)
641
+ else:
642
+ best_cut = -float("inf")
643
+ for _ in range(multi_start):
644
+ bits = ([0], [0])
645
+ bits[0].clear()
646
+ bits[1].clear()
647
+ while (len(bits[0]) == 0) or (len(bits[1]) == 0):
648
+ _, cut_value, bits = maxcut_tfim_pure_numba(G_m, nodes, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h, repulsion_base=repulsion_base)
649
+ if cut_value > best_cut:
650
+ best_cut = cut_value
651
+ a, b = bits
652
+ else:
653
+ is_cyclic = False
654
+ a.append(nodes.index(start_node))
655
+ b = list(range(n_nodes))
656
+ b.remove(a[0])
657
+ if end_node is not None:
658
+ c.append(nodes.index(end_node))
659
+ b.remove(c[0])
660
+
661
+ G_a, G_b = init_G_a_b(G_m, a, b)
662
+
663
+ return a, b, c, G_a, G_b, is_cyclic
664
+
624
665
  def tsp_symmetric(
625
666
  G,
626
667
  start_node=None,
@@ -651,10 +692,6 @@ def tsp_symmetric(
651
692
  nodes = list(range(n_nodes))
652
693
  G_m = G
653
694
 
654
- if is_cyclic:
655
- start_node = None
656
- end_node = None
657
-
658
695
  if n_nodes < 7:
659
696
  if n_nodes > 3:
660
697
  if is_cyclic:
@@ -666,35 +703,7 @@ def tsp_symmetric(
666
703
 
667
704
  return tsp_symmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic)
668
705
 
669
- if (start_node is None) and not (end_node is None):
670
- start_node = end_node
671
- end_node = None
672
-
673
- a = []
674
- b = []
675
- c = []
676
- if (start_node is None) and (end_node is None):
677
- if monte_carlo:
678
- a, b = monte_carlo_loop(n_nodes)
679
- else:
680
- best_cut = -float("inf")
681
- for _ in range(multi_start):
682
- bits = ([], [])
683
- while (len(bits[0]) == 0) or (len(bits[1]) == 0):
684
- _, cut_value, bits = maxcut_tfim(G_m, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h, repulsion_base=repulsion_base)
685
- if cut_value > best_cut:
686
- best_cut = cut_value
687
- a, b = bits
688
- else:
689
- is_cyclic = False
690
- a.append(nodes.index(start_node))
691
- b = list(range(n_nodes))
692
- b.remove(a[0])
693
- if end_node is not None:
694
- c.append(nodes.index(end_node))
695
- b.remove(c[0])
696
-
697
- G_a, G_b = init_G_a_b(G_m, a, b)
706
+ a, b, c, G_a, G_b, is_cylic = tsp_symmetric_header(G_m, nodes, quality, shots, anneal_t, anneal_h, repulsion_base, start_node, end_node, monte_carlo, is_cyclic, n_nodes, multi_start)
698
707
 
699
708
  if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 3) and (len(b) > 3):
700
709
  with ProcessPoolExecutor(max_workers=1) as executor:
@@ -827,6 +836,51 @@ def tsp_asymmetric_driver(G_m, is_reversed, is_cyclic, is_top_level, start_node,
827
836
  return [nodes[x] for x in final_path], best_weight
828
837
 
829
838
 
839
+ @njit
840
+ def tsp_asymmetric_header(G_m, nodes, quality, shots, anneal_t, anneal_h, repulsion_base, start_node, end_node, monte_carlo, is_cyclic, n_nodes, multi_start):
841
+ if is_cyclic:
842
+ start_node = None
843
+ end_node = None
844
+
845
+ is_reversed = False
846
+ if (start_node is None) and not (end_node is None):
847
+ is_reversed = True
848
+ start_node = end_node
849
+ end_node = None
850
+ G_m = G_m.T
851
+
852
+ a, b, c = [0], [0], [0]
853
+ a.clear()
854
+ b.clear()
855
+ c.clear()
856
+ if (start_node is None) and (end_node is None):
857
+ if monte_carlo:
858
+ a, b = monte_carlo_loop(n_nodes)
859
+ else:
860
+ best_cut = -float("inf")
861
+ for _ in range(multi_start):
862
+ bits = ([0], [0])
863
+ bits[0].clear()
864
+ bits[1].clear()
865
+ while (len(bits[0]) == 0) or (len(bits[1]) == 0):
866
+ _, cut_value, bits = maxcut_tfim_pure_numba((G_m + G_m.T) / 2, nodes, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h, repulsion_base=repulsion_base)
867
+ if cut_value > best_cut:
868
+ best_cut = cut_value
869
+ a, b = bits
870
+ else:
871
+ is_cyclic = False
872
+ a.append(nodes.index(start_node))
873
+ b = list(range(n_nodes))
874
+ b.remove(a[0])
875
+ if end_node is not None:
876
+ c.append(nodes.index(end_node))
877
+ b.remove(c[0])
878
+
879
+ G_a, G_b = init_G_a_b(G_m, a, b)
880
+
881
+ return a, b, c, G_a, G_b, is_cyclic, is_reversed
882
+
883
+
830
884
  def tsp_asymmetric(
831
885
  G,
832
886
  start_node=None,
@@ -857,10 +911,6 @@ def tsp_asymmetric(
857
911
  nodes = list(range(n_nodes))
858
912
  G_m = G
859
913
 
860
- if is_cyclic:
861
- start_node = None
862
- end_node = None
863
-
864
914
  if n_nodes < 7:
865
915
  if n_nodes > 2:
866
916
  if is_cyclic:
@@ -872,39 +922,7 @@ def tsp_asymmetric(
872
922
 
873
923
  return tsp_asymmetric_brute_force_driver(G_m, n_nodes, nodes, is_cyclic)
874
924
 
875
-
876
- is_reversed = False
877
- if (start_node is None) and not (end_node is None):
878
- is_reversed = True
879
- start_node = end_node
880
- end_node = None
881
- G_m = G_m.T
882
-
883
- a = []
884
- b = []
885
- c = []
886
- if (start_node is None) and (end_node is None):
887
- if monte_carlo:
888
- a, b = monte_carlo_loop(n_nodes)
889
- else:
890
- best_cut = -float("inf")
891
- for _ in range(multi_start):
892
- bits = ([], [])
893
- while (len(bits[0]) == 0) or (len(bits[1]) == 0):
894
- _, cut_value, bits = maxcut_tfim((G_m + G_m.T) / 2, quality=quality, shots=shots, anneal_t=anneal_t, anneal_h=anneal_h, repulsion_base=repulsion_base)
895
- if cut_value > best_cut:
896
- best_cut = cut_value
897
- a, b = bits
898
- else:
899
- is_cyclic = False
900
- a.append(nodes.index(start_node))
901
- b = list(range(n_nodes))
902
- b.remove(a[0])
903
- if end_node is not None:
904
- c.append(nodes.index(end_node))
905
- b.remove(c[0])
906
-
907
- G_a, G_b = init_G_a_b(G_m, a, b)
925
+ a, b, c, G_a, G_b, is_cyclic, is_reversed = tsp_asymmetric_header(G_m, nodes, quality, shots, anneal_t, anneal_h, repulsion_base, start_node, end_node, monte_carlo, is_cyclic, n_nodes, multi_start)
908
926
 
909
927
  if monte_carlo and is_parallel and (parallel_level < max_parallel_level) and (len(a) > 2) and (len(b) > 2):
910
928
  with ProcessPoolExecutor(max_workers=1) as executor:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 8.9.4
3
+ Version: 8.10.1
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.1',
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.4',
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