PyQrackIsing 1.3.4__tar.gz → 1.4.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.
@@ -3,12 +3,9 @@ project(PyQrackIsing LANGUAGES CXX)
3
3
 
4
4
  set(PYBIND11_FINDPYTHON ON)
5
5
  find_package(pybind11 CONFIG REQUIRED)
6
-
6
+ find_package(Boost CONFIG REQUIRED)
7
7
  pybind11_add_module(tfim_sampler PyQrackIsing/_pyqrack_ising.cpp)
8
-
9
- if (DEFINED ENV{BOOST_ROOT})
10
- target_include_directories(tfim_sampler PUBLIC $ENV{BOOST_ROOT}/include/boost)
11
- endif (DEFINED ENV{BOOST_ROOT})
8
+ target_include_directories(tfim_sampler PUBLIC ${Boost_INCLUDE_DIR})
12
9
 
13
10
  if (MSVC)
14
11
  target_compile_options(tfim_sampler PUBLIC /O2 /std:c++17)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyQrackIsing
3
- Version: 1.3.4
3
+ Version: 1.4.0
4
4
  Summary: Near-ideal closed-form solutions for transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -1,3 +1,4 @@
1
1
  from .generate_tfim_samples import generate_tfim_samples
2
2
  from .tfim_magnetization import tfim_magnetization
3
3
  from .tfim_square_magnetization import tfim_square_magnetization
4
+ from .maxcut_tfim import maxcut_tfim
@@ -1,5 +1,9 @@
1
+ // C++/pybind11 translation of TFIM function and maxcut_tfim()
2
+ // Original algorithm by Dan Strano and Elara (OpenAI GPT), 2024
3
+
1
4
  #define _USE_MATH_DEFINES
2
5
  #include <pybind11/pybind11.h>
6
+ #include <pybind11/numpy.h>
3
7
  #include <pybind11/stl.h>
4
8
  #include <cmath>
5
9
  #include <limits>
@@ -8,12 +12,57 @@
8
12
  #include <vector>
9
13
  #include <bitset>
10
14
  #include <algorithm>
15
+ #include <numeric>
16
+ #include <unordered_set>
17
+ #include <unordered_map>
18
+ #include <tuple>
11
19
  #include <boost/multiprecision/cpp_int.hpp>
20
+ #include <boost/functional/hash.hpp>
12
21
 
13
22
  namespace py = pybind11;
14
23
 
15
24
  typedef boost::multiprecision::cpp_int BigInteger;
16
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
+ const double omega = 1.5 * M_PI;
43
+ const 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 >= 1024) {
46
+ bias[0] = 1.0;
47
+ } else {
48
+ double tot_n = 0.0;
49
+ for (size_t q = 0U; q <= n_qubits; ++q) {
50
+ double n = 1.0 / ((n_qubits + 1) * std::pow(2.0, p * q));
51
+ bias[q] = n;
52
+ tot_n += n;
53
+ }
54
+ for (size_t q = 0U; q <= n_qubits; ++q) {
55
+ bias[q] /= tot_n;
56
+ }
57
+ }
58
+ }
59
+ if (J > 0) {
60
+ std::reverse(bias.begin(), bias.end());
61
+ }
62
+
63
+ return bias;
64
+ }
65
+
17
66
  static inline std::string int_to_bitstring(BigInteger integer, size_t length) {
18
67
  std::string s(length, '0');
19
68
  for (size_t i = 0; i < length; ++i) {
@@ -24,6 +73,52 @@ static inline std::string int_to_bitstring(BigInteger integer, size_t length) {
24
73
  return s;
25
74
  }
26
75
 
76
+ std::vector<double> maxcut_hamming_cdf(py::array_t<double, py::array::c_style | py::array::forcecast> _degrees, int mult_log2) {
77
+ auto buf = _degrees.request();
78
+ size_t n_qubits = buf.shape[0];
79
+ double* degrees = static_cast<double*>(buf.ptr);
80
+ const int n_steps = n_qubits << mult_log2;
81
+ const int shots = n_qubits << mult_log2;
82
+ const double delta_t = 1.0 / (n_steps << (mult_log2 >> 1));
83
+ const double h_mult = (1 << (mult_log2 >> 1)) / (n_steps * delta_t);
84
+ std::vector<double> hamming_prob(n_qubits - 1, 0.0);
85
+
86
+ for (int step = 0; step < n_steps; ++step) {
87
+ double t = step * delta_t;
88
+ double tm1 = (step - 1) * delta_t;
89
+ for (int q = 0; q < n_qubits; ++q) {
90
+ const double& z = degrees[q];
91
+ const double J_eff = -z;
92
+ const double h_t = h_mult * t;
93
+ auto bias = probability_by_hamming_weight(J_eff, h_t, z, 0.0, t, n_qubits);
94
+ if (step == 0) {
95
+ for (size_t i = 0U; i < hamming_prob.size(); ++i) {
96
+ hamming_prob[i] += bias[i + 1];
97
+ }
98
+ continue;
99
+ }
100
+ auto last_bias = probability_by_hamming_weight(J_eff, h_t, z, 0.0, tm1, n_qubits);
101
+ for (size_t i = 0U; i < hamming_prob.size(); ++i) {
102
+ hamming_prob[i] += bias[i + 1] - last_bias[i + 1];
103
+ }
104
+ }
105
+ }
106
+
107
+ double tot_prob = std::accumulate(hamming_prob.begin(), hamming_prob.end(), 0.0);
108
+ for (auto& x : hamming_prob) {
109
+ x /= tot_prob;
110
+ }
111
+
112
+ tot_prob = 0.0;
113
+ for (size_t i = 0U; i < hamming_prob.size(); ++i) {
114
+ tot_prob += hamming_prob[i];
115
+ hamming_prob[i] = tot_prob;
116
+ }
117
+ hamming_prob.back() = 1.0;
118
+
119
+ return hamming_prob;
120
+ }
121
+
27
122
  static inline double closeness_like_bits(BigInteger perm, size_t n_rows, size_t n_cols) {
28
123
  std::string bits = int_to_bitstring(perm, n_rows * n_cols);
29
124
  double like_count = 0.0;
@@ -64,45 +159,6 @@ static inline double expected_closeness_weight(size_t n_rows, size_t n_cols, siz
64
159
  return 2.0 * mu_k - 1.0;
65
160
  }
66
161
 
67
- static inline std::vector<double> probability_by_hamming_weight(double J, double h, double z, double theta, double t, size_t n_qubits)
68
- {
69
- // critical angle
70
- 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))));
71
- const double delta_theta = theta - theta_c;
72
- std::vector<double> bias;
73
- if (std::abs(h) < 1e-12) {
74
- bias.assign(n_qubits + 1, 0.0);
75
- bias[0] = 1.0;
76
- } else if (std::abs(J) < 1e-12) {
77
- bias.assign(n_qubits + 1, 1.0 / (n_qubits + 1));
78
- } else {
79
- const double sin_delta = std::sin(delta_theta);
80
- const double omega = 1.5 * M_PI;
81
- const double t2 = 1.0;
82
- 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;
83
- if (p >= 1024) {
84
- bias.assign(n_qubits + 1U, 0.0);
85
- bias[0] = 1.0;
86
- } else {
87
- double tot_n = 0.0;
88
- bias.resize(n_qubits + 1);
89
- for (size_t q = 0U; q <= n_qubits; ++q) {
90
- double n = 1.0 / ((n_qubits + 1) * std::pow(2.0, p * q));
91
- bias[q] = n;
92
- tot_n += n;
93
- }
94
- for (size_t q = 0U; q <= n_qubits; ++q) {
95
- bias[q] /= tot_n;
96
- }
97
- }
98
- }
99
- if (J > 0) {
100
- std::reverse(bias.begin(), bias.end());
101
- }
102
-
103
- return bias;
104
- }
105
-
106
162
  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) {
107
163
  // lattice dimensions
108
164
  size_t n_rows = 1U;
@@ -126,8 +182,6 @@ std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z,
126
182
  }
127
183
  thresholds[n_qubits] = 1.0;
128
184
 
129
- // random engine
130
- std::mt19937_64 rng(std::random_device{}());
131
185
  std::uniform_real_distribution<double> dist(0.0, 1.0);
132
186
 
133
187
  std::vector<BigInteger> samples;
@@ -138,20 +192,30 @@ std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z,
138
192
  qubits[i] = i;
139
193
  }
140
194
 
195
+ std::vector<size_t> hamming_samples(n_qubits + 1U);
141
196
  for (size_t s = 0U; s < shots; ++s) {
142
197
  double mag_prob = dist(rng);
143
198
  size_t m = 0U;
144
199
  while (thresholds[m] < mag_prob) {
145
200
  ++m;
146
201
  }
147
- double closeness_prob = dist(rng);
202
+ ++hamming_samples[m];
203
+ }
204
+ for (size_t m = 0U; m < hamming_samples.size(); ++m){
148
205
  double tot_cprob = 0.0;
149
- BigInteger state_int = 0;
206
+ size_t hs = hamming_samples[m];
207
+ std::vector<double> rands;
208
+ rands.reserve(hs);
209
+ for (size_t s = 0U; s < hs; ++s) {
210
+ rands.push_back(dist(rng));
211
+ }
212
+ std::sort(rands.begin(), rands.end());
150
213
  // iterate combinations
151
214
  std::vector<size_t> idx(m);
152
215
  for (size_t i = 0U; i < m; ++i) {
153
216
  idx[i] = i;
154
217
  }
218
+ size_t s = 0U;
155
219
  while (true) {
156
220
  BigInteger candidate = 0U;
157
221
  for (size_t pos : idx) {
@@ -159,8 +223,11 @@ std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z,
159
223
  }
160
224
  tot_cprob += (1.0 + closeness_like_bits(candidate, n_rows, n_cols)) /
161
225
  (1.0 + expected_closeness_weight(n_rows, n_cols, m));
162
- if (closeness_prob <= tot_cprob) {
163
- state_int = candidate;
226
+ while ((s < hs) && (rands[s] <= tot_cprob)) {
227
+ samples.push_back(candidate);
228
+ ++s;
229
+ }
230
+ if (s == hs) {
164
231
  break;
165
232
  }
166
233
 
@@ -170,6 +237,9 @@ std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z,
170
237
  --k;
171
238
  }
172
239
  if (k < 0) {
240
+ for (; s < hs; ++s) {
241
+ samples.push_back(candidate);
242
+ }
173
243
  break;
174
244
  }
175
245
  ++idx[k];
@@ -177,9 +247,11 @@ std::vector<std::string> generate_tfim_samples_cpp(double J, double h, double z,
177
247
  idx[j] = idx[j - 1U] + 1;
178
248
  }
179
249
  }
180
- samples.push_back(state_int);
181
250
  }
182
251
 
252
+ auto dre = std::default_random_engine{rd()};
253
+ std::shuffle(samples.begin(), samples.end(), dre);
254
+
183
255
  std::vector<std::string> output;
184
256
  output.reserve(shots);
185
257
  for (BigInteger& s : samples) {
@@ -226,5 +298,6 @@ PYBIND11_MODULE(tfim_sampler, m) {
226
298
  m.def("_tfim_square_magnetization", &tfim_square_magnetization,
227
299
  py::arg("J"), py::arg("h"), py::arg("z"), py::arg("theta"),
228
300
  py::arg("t"), py::arg("n_qubits"));
301
+ m.def("_maxcut_hamming_cdf", &maxcut_hamming_cdf, "Adiabatic TFIM Hamming weight probability density function");
229
302
  }
230
303
 
@@ -0,0 +1,105 @@
1
+ import networkx as nx
2
+ import numpy as np
3
+ import tfim_sampler
4
+
5
+
6
+ # Written by Elara (OpenAI custom GPT)
7
+ def local_repulsion_choice(adjacency, degrees, weights, n, m):
8
+ """
9
+ Pick m nodes (bit positions) out of n with repulsion bias:
10
+ - High-degree nodes are already less likely
11
+ - After choosing a node, its neighbors' probabilities are further reduced
12
+ """
13
+
14
+ # Base weights: inverse degree
15
+ # degrees = np.array([len(adjacency.get(i, [])) for i in range(n)], dtype=np.float64)
16
+ # weights = 1.0 / (degrees + 1.0)
17
+ weights = weights.copy()
18
+
19
+ chosen = []
20
+ available = set(range(n))
21
+
22
+ for _ in range(m):
23
+ if not available:
24
+ break
25
+
26
+ # Normalize weights over remaining nodes
27
+ sub_weights = np.array([weights[i] for i in available], dtype=np.float64)
28
+ sub_weights /= sub_weights.sum()
29
+ sub_nodes = list(available)
30
+
31
+ # Sample one node
32
+ idx = np.random.choice(len(sub_nodes), p=sub_weights)
33
+ node = sub_nodes[idx]
34
+ chosen.append(node)
35
+
36
+ # Remove node from available
37
+ available.remove(node)
38
+
39
+ # Repulsion: penalize neighbors
40
+ for nbr in adjacency.get(node, []):
41
+ if nbr in available:
42
+ weights[nbr] *= 0.5 # halve neighbor's weight (tunable!)
43
+
44
+ # Build integer mask
45
+ mask = 0
46
+ for pos in chosen:
47
+ mask |= (1 << pos)
48
+
49
+ return mask
50
+
51
+
52
+ def evaluate_cut_edges(samples, flat_edges):
53
+ best_value = -1
54
+ best_solution = None
55
+ best_cut_edges = None
56
+ for state in samples:
57
+ cut_edges = []
58
+ for i in range(len(flat_edges) // 2):
59
+ i2 = i << 1
60
+ u, v = flat_edges[i2], flat_edges[i2 + 1]
61
+ if ((state >> u) & 1) != ((state >> v) & 1):
62
+ cut_edges.append((u, v))
63
+ cut_size = len(cut_edges)
64
+ if cut_size > best_value:
65
+ best_value = cut_size
66
+ best_solution = state
67
+ best_cut_edges = cut_edges
68
+
69
+ return best_value, best_solution, best_cut_edges
70
+
71
+
72
+ # By Gemini (Google Search AI)
73
+ def int_to_bitstring(integer, length):
74
+ return (bin(integer)[2:].zfill(length))[::-1]
75
+
76
+
77
+ def maxcut_tfim(
78
+ G,
79
+ quality = 10,
80
+ shots = None,
81
+ ):
82
+ # Number of qubits/nodes
83
+ n_qubits = G.number_of_nodes()
84
+ if shots is None:
85
+ # Number of measurement shots
86
+ shots = n_qubits << quality
87
+
88
+ degrees = np.array([sum(edge_attributes.get('weight', 1.0) for neighbor, edge_attributes in G.adj[i].items()) for i in range(n_qubits)], dtype=np.float64)
89
+ thresholds = tfim_sampler._maxcut_hamming_cdf(degrees, quality)
90
+ G_dict = nx.to_dict_of_lists(G)
91
+ weights = 1.0 / (degrees + 1.0)
92
+ samples = []
93
+ for s in range(shots):
94
+ # First dimension: Hamming weight
95
+ mag_prob = np.random.random()
96
+ m = 0
97
+ while thresholds[m] < mag_prob:
98
+ m += 1
99
+ m += 1
100
+ # Second dimension: permutation within Hamming weight
101
+ samples.append(local_repulsion_choice(G_dict, degrees, weights, n_qubits, m))
102
+
103
+ best_value, best_solution, best_cut_edges = evaluate_cut_edges(samples, [int(item) for tup in G.edges() for item in tup])
104
+
105
+ return best_value, int_to_bitstring(best_solution, n_qubits), best_cut_edges
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: PyQrackIsing
3
- Version: 1.3.4
3
+ Version: 1.4.0
4
4
  Summary: Near-ideal closed-form solutions for transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -7,6 +7,7 @@ setup.py
7
7
  PyQrackIsing/__init__.py
8
8
  PyQrackIsing/_pyqrack_ising.cpp
9
9
  PyQrackIsing/generate_tfim_samples.py
10
+ PyQrackIsing/maxcut_tfim.py
10
11
  PyQrackIsing/tfim_magnetization.py
11
12
  PyQrackIsing/tfim_square_magnetization.py
12
13
  PyQrackIsing.egg-info/PKG-INFO
@@ -38,7 +38,18 @@ samples = generate_tfim_samples(
38
38
  )
39
39
  ```
40
40
 
41
- There are two more functions, `tfim_magnetization()` and `tfim_square_magnetization()`, that follow the same function signature except without the `shots` argument.
41
+ There are two other functions, `tfim_magnetization()` and `tfim_square_magnetization()`, that follow the same function signature except without the `shots` argument.
42
+
43
+ The library also provides a TFIM-inspired (approximate) MAXCUT solver:
44
+ ```py
45
+ from PyQrackIsing import maxcut_tfim
46
+ import networkx as nx
47
+
48
+ G = nx.petersen_graph()
49
+ best_cut_value, best_solution_bit_string, best_cut_edges = maxcut_tfim(G, quality=10)
50
+ ```
51
+
52
+ The (integer) `quality` setting is optional, with a default value of `10`, but you can turn it up for higher-quality results, or turn it down to save time. (You can also optionally specify the number of measurement `shots` as an argument, if you want specific fine-grained control over resource usage.) If you want to run MAXCUT on a graph with non-uniform edge weights, specify them as the `weight` attribute of each edge, with `networkx`. (If any `weight` attribute is not defined, the solver assumes it's `1.0` for that edge.)
42
53
 
43
54
  ## About
44
55
  Transverse field Ising model (TFIM) is the basis of most claimed algorithmic "quantum advantage," circa 2025, with the notable exception of Shor's integer factoring algorithm.
@@ -2,13 +2,15 @@
2
2
  requires = [
3
3
  "cmake",
4
4
  "pybind11",
5
- "setuptools"
5
+ "setuptools",
6
+ "networkx",
7
+ "numpy",
6
8
  ]
7
9
  build-backend = "setuptools.build_meta"
8
10
 
9
11
  [project]
10
12
  name = "PyQrackIsing"
11
- version = "1.3.4"
13
+ version = "1.4.0"
12
14
  requires-python = ">=3.8"
13
15
  description = "Near-ideal closed-form solutions for transverse field Ising model (TFIM)"
14
16
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -23,7 +23,10 @@ class CMakeBuild(build_ext):
23
23
  wd = os.getcwd()
24
24
  os.makedirs(self.build_temp, exist_ok=True)
25
25
  os.chdir(self.build_temp)
26
- cmake_args = ['-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + extdir]
26
+ cmake_args = ['-DCMAKE_BUILD_TYPE=Release', f'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}']
27
+ toolchain = os.environ.get("BOOST_TOOLCHAIN_FILE")
28
+ if toolchain:
29
+ cmake_args += [f'-DCMAKE_TOOLCHAIN_FILE={toolchain}']
27
30
  self.spawn(['cmake', ext.sourcedir] + cmake_args)
28
31
  self.spawn(['cmake', '--build', '.', '--config', 'Release'])
29
32
  if os.name == 'nt':
@@ -40,7 +43,7 @@ ext_modules = [CMakeExtension('tfim_sampler')]
40
43
 
41
44
  setup(
42
45
  name='PyQrackIsing',
43
- version='1.3.4',
46
+ version='1.4.0',
44
47
  author='Dan Strano',
45
48
  author_email='stranoj@gmail.com',
46
49
  description='Near-ideal closed-form solutions for transverse field Ising model (TFIM)',
File without changes
File without changes
File without changes