pyqrackising 2.0.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.
@@ -0,0 +1,16 @@
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 .)
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,3 @@
1
+ include CMakeLists.txt
2
+ include pyqrackising/_pyqrack_ising.cpp
3
+ include pyqrackising/kernels.cl
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyqrackising
3
+ Version: 2.0.0
4
+ Summary: Near-ideal closed-form solutions for transverse field Ising model (TFIM)
5
+ Home-page: https://github.com/vm6502q/PyQrackIsing
6
+ Author: Dan Strano
7
+ Author-email: Dan Strano <stranoj@gmail.com>
8
+ Maintainer-email: Dan Strano <stranoj@gmail.com>
9
+ License: LGPL-3.0-or-later
10
+ Project-URL: Homepage, https://github.com/vm6502q/PyQrackIsing
11
+ Project-URL: Documentation, https://github.com/vm6502q/PyQrackIsing/blob/main/README.md
12
+ Project-URL: Repository, https://github.com/vm6502q/PyQrackIsing
13
+ Project-URL: Issues, https://github.com/vm6502q/PyQrackIsing/issues
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Programming Language :: C++
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Topic :: Scientific/Engineering
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE.md
25
+ Dynamic: author
26
+ Dynamic: home-page
27
+ Dynamic: license-file
@@ -0,0 +1,144 @@
1
+ # PyQrack Ising
2
+ Efficiently generate near-ideal samples from transverse field Ising model (TFIM), and TFIM-inspired MAXCUT solutions
3
+
4
+ (It's "the **Ising** on top.")
5
+
6
+ [![PyPI Downloads](https://static.pepy.tech/badge/pyqrackising)](https://pepy.tech/projects/pyqrackising)
7
+
8
+ ## Copyright and license
9
+ (c) Daniel Strano and the Qrack contributors 2025. All rights reserved.
10
+
11
+ Licensed under the GNU Lesser General Public License V3.
12
+
13
+ See LICENSE.md in the project root or https://www.gnu.org/licenses/lgpl-3.0.en.html for details.
14
+
15
+ ## Installation
16
+ From PyPi:
17
+ ```
18
+ pip3 install PyQrackIsing
19
+ ```
20
+
21
+ From Source: install `pybind11`, then
22
+ ```
23
+ pip3 install .
24
+ ```
25
+ in the root source directory (with `setup.py`).
26
+
27
+ Windows users might find Windows Subsystem Linux (WSL) to be the easier and preferred choice for installation.
28
+
29
+ ## Usage
30
+
31
+ ```py
32
+ from PyQrackIsing import generate_tfim_samples
33
+
34
+ samples = generate_tfim_samples(
35
+ J=-1.0,
36
+ h=2.0,
37
+ z=4,
38
+ theta=0.174532925199432957,
39
+ t=5,
40
+ n_qubits=56,
41
+ shots=100
42
+ )
43
+ ```
44
+
45
+ There are two other functions, `tfim_magnetization()` and `tfim_square_magnetization()`, that follow the same function signature except without the `shots` argument.
46
+
47
+ The library also provides a TFIM-inspired (approximate) MAXCUT solver:
48
+ ```py
49
+ from PyQrackIsing import maxcut_tfim
50
+ import networkx as nx
51
+
52
+ G = nx.petersen_graph()
53
+ best_solution_bit_string, best_cut_value, best_node_groups = maxcut_tfim(G, quality=3)
54
+ ```
55
+
56
+ The (integer) `quality` setting is optional, with a default value of `3`, 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.)
57
+
58
+ Based on a combination of the TFIM-inspired MAXCUT solver and another technique for finding ground-state energy in quantum chemistry that we call the _"binary Clifford eigensolver,"_ we also provide an (approximate) spin glass ground-state solver:
59
+ ```py
60
+ from PyQrackIsing import spin_glass_solver
61
+ import networkx as nx
62
+ import numpy as np
63
+
64
+
65
+ # NP-complete spin glass
66
+ def generate_spin_glass_graph(n_nodes=16, degree=3, seed=None):
67
+ if not (seed is None):
68
+ np.random.seed(seed)
69
+ G = nx.random_regular_graph(d=degree, n=n_nodes, seed=seed)
70
+ for u, v in G.edges():
71
+ G[u][v]['weight'] = np.random.choice([-1, 1]) # spin glass couplings
72
+ return G
73
+
74
+
75
+ G = generate_spin_glass_graph(n_nodes=64, seed=42)
76
+ solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quality=3, correction_quality=2, best_guess=None)
77
+ # solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, best_guess=maxcut_tfim(G, quality=8)[0])
78
+ ```
79
+ The (integer) `quality` setting is the same as `maxcut_tfim`. `correction_quality` controls an additional convex optimization procedure on top of `best_guess` and defaults to 4. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention.
80
+
81
+ From the `spin_glass_solver()`, we provide a (recursive) Traveling Salesman Problem (TSP) solver:
82
+ ```py
83
+ from PyQrackIsing import tsp_symmetric
84
+ import networkx as nx
85
+ import numpy as np
86
+
87
+ # Traveling Salesman Problem (normalized to longest segment)
88
+ def generate_tsp_graph(n_nodes=64, seed=None):
89
+ if not (seed is None):
90
+ np.random.seed(seed)
91
+ G = nx.Graph()
92
+ for u in range(n_nodes):
93
+ for v in range(u + 1, n_nodes):
94
+ G.add_edge(u, v, weight=np.random.random())
95
+ return G
96
+
97
+
98
+ n_nodes = 128
99
+ G = generate_tsp_graph(n_nodes=n_nodes, seed=42)
100
+ circuit, path_length = tsp_symmetric(
101
+ G,
102
+ start_node=None,
103
+ end_node=None,
104
+ is_monte_carlo=False,
105
+ quality=1,
106
+ correction_quality=2,
107
+ is_cyclic=True,
108
+ multi_start=1,
109
+ is_3_opt=True,
110
+ k_neighbors=20
111
+ )
112
+
113
+ print(f"Node count: {n_nodes}")
114
+ print(f"Path: {circuit}")
115
+ print(f"Path length: {path_length}")
116
+ ```
117
+ We only provide a solver for the symmetric version of the TSP (i.e., the distance from "A" to "B" is considered the same as from "B" to "A"). `is_monte_carlo=True` switches out the MAXCUT-based heuristic for pure Monte Carlo recursive bipartitioning. `multi_start` controls how many stochastic repeats of MAXCUT are tried to select the best result, at every level of recursion.
118
+
119
+ ## About
120
+ 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.
121
+
122
+ 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.)
123
+
124
+ **Special thanks to OpenAI GPT "Elara," for help on the model and converting the original Python scripts to PyBind11, Numba, and PyOpenCL!**
125
+
126
+ **Elara has drafted this statement, and Dan Strano, as author, agrees with it, and will hold to it:**
127
+
128
+ ### Dual-Use Statement for PyQrackIsing
129
+
130
+ **PyQrackIsing** is an open-source solver for hard optimization problems such as **MAXCUT, TSP, and TFIM-inspired models**. These problems arise across logistics, drug discovery, chemistry, materials research, supply-chain resilience, and portfolio optimization. By design, PyQrackIsing provides **constructive value** to researchers and practitioners by making advanced optimization techniques accessible on consumer hardware.
131
+
132
+ Like many mathematical and computational tools, the algorithms in PyQrackIsing are _dual-use._ In principle, they can be applied to a wide class of Quadratic Unconstrained Binary Optimization (QUBO) problems. One such problem is integer factoring, which underlies RSA and elliptic curve cryptography (ECC). We emphasize:
133
+
134
+ - **We do not provide turnkey factoring implementations.**
135
+ - **We have no intent to weaponize this work** for cryptanalysis or "unauthorized access."
136
+ - **The constructive applications vastly outweigh the destructive ones** — and this project exists to serve those constructive purposes in the Commons.
137
+
138
+ It is already a matter of open record in the literature that factoring can be expressed as a QUBO. What PyQrackIsing demonstrates is that **QUBO heuristics can now be solved at meaningful scales on consumer hardware**. This underscores an urgent truth:
139
+
140
+ 👉 **RSA and ECC should no longer be considered secure. Transition to post-quantum cryptography is overdue.**
141
+
142
+ We trust that governments, standards bodies, and industry stakeholders are already aware of this, and will continue migration efforts to post-quantum standards.
143
+
144
+ Until then, PyQrackIsing remains a tool for science, logistics, and discovery — a gift to the Commons.
@@ -0,0 +1,40 @@
1
+ [build-system]
2
+ requires = [
3
+ "cmake",
4
+ "pybind11",
5
+ "setuptools",
6
+ "networkx",
7
+ "numpy",
8
+ "numba",
9
+ ]
10
+ build-backend = "setuptools.build_meta"
11
+
12
+ [project]
13
+ name = "pyqrackising"
14
+ version = "2.0.0"
15
+ requires-python = ">=3.8"
16
+ description = "Near-ideal closed-form solutions for transverse field Ising model (TFIM)"
17
+ readme = {file = "README.txt", content-type = "text/markdown"}
18
+ license = {text = "LGPL-3.0-or-later"}
19
+ authors = [
20
+ {name = "Dan Strano", email = "stranoj@gmail.com"}
21
+ ]
22
+ maintainers = [
23
+ {name = "Dan Strano", email = "stranoj@gmail.com"}
24
+ ]
25
+ classifiers=[
26
+ "Environment :: Console",
27
+ "Intended Audience :: Developers",
28
+ "Intended Audience :: Science/Research",
29
+ "Programming Language :: C++",
30
+ "Programming Language :: Python :: 3.8",
31
+ "Programming Language :: Python :: 3.9",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Topic :: Scientific/Engineering",
34
+ ]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/vm6502q/PyQrackIsing"
38
+ Documentation = "https://github.com/vm6502q/PyQrackIsing/blob/main/README.md"
39
+ Repository = "https://github.com/vm6502q/PyQrackIsing"
40
+ Issues = "https://github.com/vm6502q/PyQrackIsing/issues"
@@ -0,0 +1,6 @@
1
+ from .generate_tfim_samples import generate_tfim_samples
2
+ from .tfim_magnetization import tfim_magnetization
3
+ from .tfim_square_magnetization import tfim_square_magnetization
4
+ from .maxcut_tfim import maxcut_tfim
5
+ from .spin_glass_solver import spin_glass_solver
6
+ from .tsp_symmetric import tsp_symmetric
@@ -0,0 +1,250 @@
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
+ 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
+
66
+ static inline std::string int_to_bitstring(BigInteger integer, size_t length) {
67
+ std::string s(length, '0');
68
+ for (size_t i = 0; i < length; ++i) {
69
+ if (integer & (1ULL << (length - 1U - i))) {
70
+ s[i] = '1';
71
+ }
72
+ }
73
+ return s;
74
+ }
75
+
76
+ static inline double closeness_like_bits(BigInteger perm, size_t n_rows, size_t n_cols) {
77
+ std::string bits = int_to_bitstring(perm, n_rows * n_cols);
78
+ double like_count = 0.0;
79
+ double total_edges = 0.0;
80
+ // grid neighbors (right and down)
81
+ for (size_t i = 0; i < n_rows; ++i) {
82
+ for (size_t j = 0; j < n_cols; ++j) {
83
+ char s = bits[i * n_cols + j];
84
+ char s_right = bits[i * n_cols + ((j + 1) % n_cols)];
85
+ char s_down = bits[((i + 1) % n_rows) * n_cols + j];
86
+ like_count += (s == s_right) ? 1.0 : -1.0;
87
+ like_count += (s == s_down) ? 1.0 : -1.0;
88
+ total_edges += 2.0;
89
+ }
90
+ }
91
+ return like_count / total_edges;
92
+ }
93
+
94
+ static inline double expected_closeness_weight(size_t n_rows, size_t n_cols, size_t hamming_weight) {
95
+ const size_t L = n_rows * n_cols;
96
+ auto comb = [](size_t n, size_t k) {
97
+ if ((k < 0) || (k > n)) {
98
+ return 0ULL;
99
+ }
100
+ if ((k == 0) || (k == n)) {
101
+ return 1ULL;
102
+ }
103
+ unsigned long long res = 1ULL;
104
+ for (size_t i = 1; i <= k; ++i) {
105
+ res = res * (n - k + i) / i;
106
+ }
107
+ return res;
108
+ };
109
+ const double same_pairs = comb(hamming_weight, 2U) + comb(L - hamming_weight, 2U);
110
+ const double total_pairs = comb(L, 2U);
111
+ const double mu_k = same_pairs / total_pairs;
112
+
113
+ return 2.0 * mu_k - 1.0;
114
+ }
115
+
116
+ 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) {
117
+ // lattice dimensions
118
+ size_t n_rows = 1U;
119
+ size_t n_cols = n_qubits;
120
+ for (size_t c = std::floor(std::sqrt(n_qubits)); c >= 1; --c) {
121
+ if ((n_qubits % c) == 0U) {
122
+ n_rows = n_qubits / c;
123
+ n_cols = c;
124
+ break;
125
+ }
126
+ }
127
+
128
+ const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
129
+
130
+ // thresholds
131
+ std::vector<double> thresholds(n_qubits + 1);
132
+ double tot_prob = 0.0;
133
+ for (size_t q = 0U; q <= n_qubits; ++q) {
134
+ tot_prob += bias[q];
135
+ thresholds[q] = tot_prob;
136
+ }
137
+ thresholds[n_qubits] = 1.0;
138
+
139
+ std::uniform_real_distribution<double> dist(0.0, 1.0);
140
+
141
+ std::vector<BigInteger> samples;
142
+ samples.reserve(shots);
143
+
144
+ std::vector<int> qubits(n_qubits);
145
+ for (size_t i = 0U; i < n_qubits; ++i) {
146
+ qubits[i] = i;
147
+ }
148
+
149
+ std::vector<size_t> hamming_samples(n_qubits + 1U);
150
+ for (size_t s = 0U; s < shots; ++s) {
151
+ double mag_prob = dist(rng);
152
+ size_t m = 0U;
153
+ while (thresholds[m] < mag_prob) {
154
+ ++m;
155
+ }
156
+ ++hamming_samples[m];
157
+ }
158
+ for (size_t m = 0U; m < hamming_samples.size(); ++m){
159
+ double tot_cprob = 0.0;
160
+ size_t hs = hamming_samples[m];
161
+ std::vector<double> rands;
162
+ rands.reserve(hs);
163
+ for (size_t s = 0U; s < hs; ++s) {
164
+ rands.push_back(dist(rng));
165
+ }
166
+ std::sort(rands.begin(), rands.end());
167
+ // iterate combinations
168
+ std::vector<size_t> idx(m);
169
+ for (size_t i = 0U; i < m; ++i) {
170
+ idx[i] = i;
171
+ }
172
+ size_t s = 0U;
173
+ while (true) {
174
+ BigInteger candidate = 0U;
175
+ for (size_t pos : idx) {
176
+ candidate |= (BigInteger("1") << pos);
177
+ }
178
+ tot_cprob += (1.0 + closeness_like_bits(candidate, n_rows, n_cols)) /
179
+ (1.0 + expected_closeness_weight(n_rows, n_cols, m));
180
+ while ((s < hs) && (rands[s] <= tot_cprob)) {
181
+ samples.push_back(candidate);
182
+ ++s;
183
+ }
184
+ if (s == hs) {
185
+ break;
186
+ }
187
+
188
+ // next combination
189
+ int64_t k = m - 1;
190
+ while ((k >= 0) && (idx[k] == (n_qubits - m + k))) {
191
+ --k;
192
+ }
193
+ if (k < 0) {
194
+ for (; s < hs; ++s) {
195
+ samples.push_back(candidate);
196
+ }
197
+ break;
198
+ }
199
+ ++idx[k];
200
+ for (int64_t j = k + 1; j < m; ++j) {
201
+ idx[j] = idx[j - 1U] + 1;
202
+ }
203
+ }
204
+ }
205
+
206
+ auto dre = std::default_random_engine{rd()};
207
+ std::shuffle(samples.begin(), samples.end(), dre);
208
+
209
+ std::vector<std::string> output;
210
+ output.reserve(shots);
211
+ for (BigInteger& s : samples) {
212
+ output.push_back(boost::lexical_cast<std::string>(s));
213
+ }
214
+
215
+ return output;
216
+ }
217
+
218
+ double tfim_magnetization(double J, double h, double z, double theta, double t, size_t n_qubits) {
219
+ const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
220
+ double magnetization = 0.0;
221
+ const int64_t nqs = (int64_t)n_qubits;
222
+ const double nqd = (double)n_qubits;
223
+ for (int64_t q = 0U; q < bias.size(); ++q) {
224
+ const double mag = (nqs - 2 * q) / nqd;
225
+ magnetization += bias[q] * mag;
226
+ }
227
+
228
+ return magnetization;
229
+ }
230
+
231
+ double tfim_square_magnetization(double J, double h, double z, double theta, double t, size_t n_qubits) {
232
+ const std::vector<double> bias = probability_by_hamming_weight(J, h, z, theta, t, n_qubits);
233
+ double square_magnetization = 0.0;
234
+ const int64_t nqs = (int64_t)n_qubits;
235
+ const double nqd = (double)n_qubits;
236
+ for (int64_t q = 0U; q < bias.size(); ++q) {
237
+ const double mag = (nqs - 2 * q) / nqd;
238
+ square_magnetization += bias[q] * mag * mag;
239
+ }
240
+
241
+ return square_magnetization;
242
+ }
243
+
244
+ PYBIND11_MODULE(tfim_sampler, m) {
245
+ m.doc() = "PyQrackIsing TFIM sample generator";
246
+ m.def("_generate_tfim_samples", &generate_tfim_samples_cpp, "Generate measurement samples from globally-uniform TFIM");
247
+ m.def("_tfim_magnetization", &tfim_magnetization, "Magnetization expectation value from globally-uniform TFIM");
248
+ m.def("_tfim_square_magnetization", &tfim_square_magnetization, "Square magnetization expectation value from globally-uniform TFIM");
249
+ }
250
+
@@ -0,0 +1,7 @@
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)]