bornlens 0.1.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.
bornlens-0.1.0/LICENSE ADDED
@@ -0,0 +1,74 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
74
+
@@ -0,0 +1,2 @@
1
+ recursive-include benchmarks *.py *.csv
2
+ recursive-include tests *.py
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: bornlens
3
+ Version: 0.1.0
4
+ Summary: Finite-shot comparisons of Pauli expectations
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Provides-Extra: qiskit
10
+ Requires-Dist: qiskit<3,>=2.6; extra == "qiskit"
11
+ Dynamic: license-file
12
+
13
+ # BornLens
14
+
15
+ BornLens compares a Pauli expectation before and after a quantum circuit change.
16
+ It reports the measured change, a finite-sample confidence interval and a tolerance verdict.
17
+ Part of the PhaseTensor Quantum Computing Suite.
18
+
19
+ Install from a checkout with `python -m pip install .`. For ideal Qiskit simulation use
20
+ `python -m pip install '.[qiskit]'`.
21
+
22
+ ```python
23
+ from bornlens import Sample, compare, shots_per_circuit
24
+
25
+ before = Sample("Z", plus=7500, minus=2500)
26
+ after = Sample("Z", plus=7550, minus=2450)
27
+ result = compare(before, after, tolerance=0.05)
28
+ print(result.verdict, result.delta, result.interval)
29
+ # within_tolerance, approximately 0.01 and (-0.0284, 0.0484)
30
+ print(shots_per_circuit(0.05)) # 5903 shots per circuit at 95% confidence
31
+ ```
32
+
33
+ ## Statistical protocol
34
+
35
+ Fix the observable, tolerance, confidence and sample sizes before collecting data.
36
+ Assume independent shots within and between circuits, with a stable outcome distribution
37
+ for each circuit. Each measured eigenvalue is +1 or -1. The sample mean is
38
+ (plus - minus) / shots. The estimated change is mean B minus mean A.
39
+
40
+ For confidence 1 - alpha, apply the two-sided Hoeffding bound to the weighted sum
41
+ of the independent signed outcomes. Each A contribution has range width 2/nA and
42
+ each B contribution has width 2/nB. The resulting half-width is
43
+ sqrt(2 log(2/alpha) (1/nA + 1/nB)). Intersect the interval with [-2, 2].
44
+ For the identity observable the change is exactly zero. Hoeffding gives a
45
+ conservative finite-sample bound even for unanimous outcomes. A normal approximation
46
+ using empirical variance can give zero width for those samples.
47
+
48
+ An interval contained in the closed tolerance band gives within_tolerance.
49
+ An interval strictly above or below the band gives beyond_tolerance. All other
50
+ intervals give inconclusive. Touching a boundary from outside is inconclusive.
51
+ Coverage concerns one prespecified comparison. Drift, correlated shots, repeated
52
+ looks and multiple comparisons require separate treatment.
53
+
54
+ For equal sample sizes the sufficient shots per circuit for half-width h are
55
+ ceil(4 log(2/alpha) / h²). This controls precision. The verdict also depends
56
+ on the distance of the true change from the tolerance boundary.
57
+
58
+ Reference: [Hoeffding (1963), Probability Inequalities for Sums of Bounded Random Variables](https://doi.org/10.1080/01621459.1963.10500830).
59
+
60
+ ## Qiskit
61
+
62
+ ```python
63
+ from qiskit import QuantumCircuit
64
+ from bornlens.qiskit import compare_circuits
65
+
66
+ a = QuantumCircuit(1)
67
+ b = a.copy()
68
+ b.x(0)
69
+ result = compare_circuits(a, b, "Z", shots_a=1000, shots_b=1500,
70
+ tolerance=0.1, seed=17)
71
+ print(result.verdict) # beyond_tolerance
72
+ ```
73
+
74
+ Pass bound gate circuits before measurements. Rightmost Pauli factor acts on qubit 0.
75
+ The adapter rotates X with H and Y with S-dagger followed by H, then computes parity
76
+ over nonidentity factors. For external integer counts use from_counts(counts, label)
77
+ after applying these basis rotations and measuring qubit i into classical bit i
78
+ of one full-width register. The caller supplies the measurement basis and mapping.
79
+ The simulator uses separate random streams for A and B. Run the checks with
80
+ `python -m unittest discover -s tests -v`.
81
+
82
+ ## Validation and release 0.1.0
83
+
84
+ Install the release with `python -m pip install bornlens==0.1.0`.
85
+ For development install the checkout with the Qiskit extra and run
86
+ `python benchmarks/coverage.py` to reproduce [the benchmark counts](benchmarks/results.csv).
87
+ Each row contains 5,000 independent trials with a fixed seed, tolerance 0.1 and
88
+ nominal coverage 95%. The samples follow the exact Z measurement law of ideal
89
+ single-qubit Ry circuits. Incorrect counts exclude inconclusive decisions.
90
+ The benchmark covers five true changes and three shot budgets. It measures
91
+ ideal fixed-shot behavior; hardware drift and correlated noise require separate experiments.
@@ -0,0 +1,79 @@
1
+ # BornLens
2
+
3
+ BornLens compares a Pauli expectation before and after a quantum circuit change.
4
+ It reports the measured change, a finite-sample confidence interval and a tolerance verdict.
5
+ Part of the PhaseTensor Quantum Computing Suite.
6
+
7
+ Install from a checkout with `python -m pip install .`. For ideal Qiskit simulation use
8
+ `python -m pip install '.[qiskit]'`.
9
+
10
+ ```python
11
+ from bornlens import Sample, compare, shots_per_circuit
12
+
13
+ before = Sample("Z", plus=7500, minus=2500)
14
+ after = Sample("Z", plus=7550, minus=2450)
15
+ result = compare(before, after, tolerance=0.05)
16
+ print(result.verdict, result.delta, result.interval)
17
+ # within_tolerance, approximately 0.01 and (-0.0284, 0.0484)
18
+ print(shots_per_circuit(0.05)) # 5903 shots per circuit at 95% confidence
19
+ ```
20
+
21
+ ## Statistical protocol
22
+
23
+ Fix the observable, tolerance, confidence and sample sizes before collecting data.
24
+ Assume independent shots within and between circuits, with a stable outcome distribution
25
+ for each circuit. Each measured eigenvalue is +1 or -1. The sample mean is
26
+ (plus - minus) / shots. The estimated change is mean B minus mean A.
27
+
28
+ For confidence 1 - alpha, apply the two-sided Hoeffding bound to the weighted sum
29
+ of the independent signed outcomes. Each A contribution has range width 2/nA and
30
+ each B contribution has width 2/nB. The resulting half-width is
31
+ sqrt(2 log(2/alpha) (1/nA + 1/nB)). Intersect the interval with [-2, 2].
32
+ For the identity observable the change is exactly zero. Hoeffding gives a
33
+ conservative finite-sample bound even for unanimous outcomes. A normal approximation
34
+ using empirical variance can give zero width for those samples.
35
+
36
+ An interval contained in the closed tolerance band gives within_tolerance.
37
+ An interval strictly above or below the band gives beyond_tolerance. All other
38
+ intervals give inconclusive. Touching a boundary from outside is inconclusive.
39
+ Coverage concerns one prespecified comparison. Drift, correlated shots, repeated
40
+ looks and multiple comparisons require separate treatment.
41
+
42
+ For equal sample sizes the sufficient shots per circuit for half-width h are
43
+ ceil(4 log(2/alpha) / h²). This controls precision. The verdict also depends
44
+ on the distance of the true change from the tolerance boundary.
45
+
46
+ Reference: [Hoeffding (1963), Probability Inequalities for Sums of Bounded Random Variables](https://doi.org/10.1080/01621459.1963.10500830).
47
+
48
+ ## Qiskit
49
+
50
+ ```python
51
+ from qiskit import QuantumCircuit
52
+ from bornlens.qiskit import compare_circuits
53
+
54
+ a = QuantumCircuit(1)
55
+ b = a.copy()
56
+ b.x(0)
57
+ result = compare_circuits(a, b, "Z", shots_a=1000, shots_b=1500,
58
+ tolerance=0.1, seed=17)
59
+ print(result.verdict) # beyond_tolerance
60
+ ```
61
+
62
+ Pass bound gate circuits before measurements. Rightmost Pauli factor acts on qubit 0.
63
+ The adapter rotates X with H and Y with S-dagger followed by H, then computes parity
64
+ over nonidentity factors. For external integer counts use from_counts(counts, label)
65
+ after applying these basis rotations and measuring qubit i into classical bit i
66
+ of one full-width register. The caller supplies the measurement basis and mapping.
67
+ The simulator uses separate random streams for A and B. Run the checks with
68
+ `python -m unittest discover -s tests -v`.
69
+
70
+ ## Validation and release 0.1.0
71
+
72
+ Install the release with `python -m pip install bornlens==0.1.0`.
73
+ For development install the checkout with the Qiskit extra and run
74
+ `python benchmarks/coverage.py` to reproduce [the benchmark counts](benchmarks/results.csv).
75
+ Each row contains 5,000 independent trials with a fixed seed, tolerance 0.1 and
76
+ nominal coverage 95%. The samples follow the exact Z measurement law of ideal
77
+ single-qubit Ry circuits. Incorrect counts exclude inconclusive decisions.
78
+ The benchmark covers five true changes and three shot budgets. It measures
79
+ ideal fixed-shot behavior; hardware drift and correlated noise require separate experiments.
@@ -0,0 +1,25 @@
1
+ """Reproduce CSV with python benchmarks/coverage.py from an installed checkout."""
2
+ import csv
3
+ import sys
4
+
5
+ import numpy as np
6
+
7
+ from bornlens import Sample, compare
8
+
9
+ rng = np.random.default_rng(20261127)
10
+ writer = csv.writer(sys.stdout, lineterminator="\n")
11
+ writer.writerow(("delta", "shots_each", "trials", "covered", "incorrect", "inconclusive"))
12
+ # For Ry(arccos(mu)) applied to |0>, Z has mean mu. Sample this circuit law exactly.
13
+ for delta in (0, 0.05, 0.1, 0.15, -0.3):
14
+ for n in (250, 2000, 10000):
15
+ trials = 5000
16
+ before = rng.binomial(n, .5, trials)
17
+ after = rng.binomial(n, (1 + delta) / 2, trials)
18
+ covered = incorrect = undecided = 0
19
+ truth = "within_tolerance" if abs(delta) <= .1 else "beyond_tolerance"
20
+ for a, b in zip(before, after):
21
+ r = compare(Sample("Z", a, n-a), Sample("Z", b, n-b), tolerance=.1)
22
+ covered += r.interval[0] <= delta <= r.interval[1]
23
+ undecided += r.verdict == "inconclusive"
24
+ incorrect += r.verdict not in (truth, "inconclusive")
25
+ writer.writerow((delta, n, trials, covered, incorrect, undecided))
@@ -0,0 +1,16 @@
1
+ delta,shots_each,trials,covered,incorrect,inconclusive
2
+ 0,250,5000,4961,1,4999
3
+ 0,2000,5000,4973,0,3268
4
+ 0,10000,5000,4977,0,0
5
+ 0.05,250,5000,4964,6,4994
6
+ 0.05,2000,5000,4972,0,4462
7
+ 0.05,10000,5000,4965,0,1076
8
+ 0.1,250,5000,4964,23,4977
9
+ 0.1,2000,5000,4964,15,4964
10
+ 0.1,10000,5000,4969,19,4969
11
+ 0.15,250,5000,4964,0,4915
12
+ 0.15,2000,5000,4978,0,4321
13
+ 0.15,10000,5000,4974,0,1022
14
+ -0.3,250,5000,4973,0,3368
15
+ -0.3,2000,5000,4974,0,1
16
+ -0.3,10000,5000,4979,0,0
@@ -0,0 +1,102 @@
1
+ """Compare independent, fixed-size samples of the same Pauli observable."""
2
+
3
+ from dataclasses import dataclass
4
+ from math import ceil, isfinite, log, sqrt
5
+ from numbers import Integral, Real
6
+
7
+
8
+ def _integer(value, name, minimum=0):
9
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < minimum:
10
+ raise ValueError(f"{name} must be an integer >= {minimum}")
11
+ return int(value)
12
+
13
+
14
+ def _real(value, name):
15
+ if isinstance(value, bool) or not isinstance(value, Real) or not isfinite(value):
16
+ raise ValueError(f"{name} must be a finite real number")
17
+ return float(value)
18
+
19
+
20
+ def _log_factor(confidence):
21
+ confidence = _real(confidence, "confidence")
22
+ if not 0 < confidence < 1:
23
+ raise ValueError("confidence must be strictly between zero and one")
24
+ return log(2 / (1 - confidence))
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Sample:
29
+ """Pauli label in Qiskit order (rightmost factor acts on qubit 0)."""
30
+
31
+ observable: str
32
+ plus: int
33
+ minus: int
34
+
35
+ def __post_init__(self):
36
+ label = self.observable
37
+ if not isinstance(label, str) or not label or any(p not in "IXYZ" for p in label):
38
+ raise ValueError("observable must be a nonempty uppercase Pauli string")
39
+ for name in ("plus", "minus"):
40
+ object.__setattr__(self, name, _integer(getattr(self, name), name))
41
+ if self.shots == 0:
42
+ raise ValueError("sample is empty")
43
+ if set(label) == {"I"} and self.minus:
44
+ raise ValueError("identity has only positive outcomes")
45
+
46
+ @property
47
+ def shots(self):
48
+ return self.plus + self.minus
49
+
50
+ @property
51
+ def mean(self):
52
+ return (self.plus - self.minus) / self.shots
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class Comparison:
57
+ observable: str
58
+ mean_a: float
59
+ mean_b: float
60
+ delta: float
61
+ interval: tuple
62
+ tolerance: float
63
+ confidence: float
64
+ shots_a: int
65
+ shots_b: int
66
+ verdict: str
67
+
68
+
69
+ def _verdict(lower, upper, tolerance):
70
+ if lower >= -tolerance and upper <= tolerance:
71
+ return "within_tolerance"
72
+ if upper < -tolerance or lower > tolerance:
73
+ return "beyond_tolerance"
74
+ return "inconclusive"
75
+
76
+
77
+ def compare(a: Sample, b: Sample, *, tolerance, confidence=0.95):
78
+ """Return a two-sided Hoeffding interval and its tolerance verdict."""
79
+ if not isinstance(a, Sample) or not isinstance(b, Sample):
80
+ raise TypeError("both inputs must be Sample instances")
81
+ if a.observable != b.observable:
82
+ raise ValueError("observables must match")
83
+ tolerance = _real(tolerance, "tolerance")
84
+ if not 0 <= tolerance <= 2:
85
+ raise ValueError("tolerance must be between zero and two")
86
+ factor = _log_factor(confidence)
87
+ delta = b.mean - a.mean
88
+ radius = sqrt(2 * factor * (1 / a.shots + 1 / b.shots))
89
+ if set(a.observable) == {"I"}:
90
+ radius = 0.0
91
+ lower, upper = max(-2, delta - radius), min(2, delta + radius)
92
+ return Comparison(a.observable, a.mean, b.mean, delta, (lower, upper),
93
+ tolerance, confidence, a.shots, b.shots,
94
+ _verdict(lower, upper, tolerance))
95
+
96
+
97
+ def shots_per_circuit(half_width, *, confidence=0.95):
98
+ """Equal fixed sample sizes sufficient for the requested interval precision."""
99
+ half_width = _real(half_width, "half_width")
100
+ if not 0 < half_width <= 2:
101
+ raise ValueError("half_width must be in (0, 2]")
102
+ return ceil(4 * _log_factor(confidence) / half_width / half_width)
@@ -0,0 +1,59 @@
1
+ """Ideal statevector sampling for bound unitary Qiskit circuits."""
2
+
3
+ from collections.abc import Mapping
4
+
5
+ import numpy as np
6
+ from qiskit.circuit import Gate, QuantumCircuit
7
+ from qiskit.quantum_info import Statevector
8
+
9
+ from . import Sample, _integer, compare
10
+
11
+
12
+ def from_counts(counts, observable):
13
+ """Convert basis-rotated counts with one classical bit per qubit."""
14
+ Sample(observable, 1, 0)
15
+ if not isinstance(counts, Mapping):
16
+ raise TypeError("counts must be a mapping")
17
+ mask = int("".join("0" if p == "I" else "1" for p in observable), 2)
18
+ totals = [0, 0]
19
+ for bits, count in counts.items():
20
+ if (not isinstance(bits, str) or len(bits) != len(observable)
21
+ or any(bit not in "01" for bit in bits)):
22
+ raise ValueError("expected one binary digit per qubit, in a single register")
23
+ parity = bin(int(bits, 2) & mask).count("1") % 2
24
+ totals[parity] += _integer(count, "count")
25
+ return Sample(observable, *totals)
26
+
27
+
28
+ def sample_counts(circuit, observable, shots, *, seed=None):
29
+ """Sample after rotating each measured Pauli axis to the Z basis."""
30
+ Sample(observable, 1, 0)
31
+ shots = _integer(shots, "shots", 1)
32
+ if not isinstance(circuit, QuantumCircuit) or circuit.num_qubits != len(observable):
33
+ raise ValueError("circuit width must match the Pauli string")
34
+ if circuit.num_parameters or any(
35
+ not isinstance(item.operation, Gate) and item.operation.name != "barrier"
36
+ for item in circuit.data
37
+ ):
38
+ raise ValueError("expected a bound gate circuit without measurements or resets")
39
+ rotated = circuit.copy()
40
+ for qubit, axis in enumerate(reversed(observable)):
41
+ if axis == "Y":
42
+ rotated.sdg(qubit)
43
+ if axis in "XY":
44
+ rotated.h(qubit)
45
+ state = Statevector.from_instruction(rotated)
46
+ state.seed(seed)
47
+ return dict(state.sample_counts(shots))
48
+
49
+
50
+ def compare_circuits(a, b, observable, *, shots_a, shots_b, tolerance,
51
+ confidence=0.95, seed=None):
52
+ """Run both ideal circuits using separate random streams."""
53
+ streams = np.random.SeedSequence(seed).spawn(2)
54
+ samples = [
55
+ from_counts(sample_counts(circuit, observable, shots,
56
+ seed=np.random.default_rng(stream)), observable)
57
+ for circuit, shots, stream in zip((a, b), (shots_a, shots_b), streams)
58
+ ]
59
+ return compare(*samples, tolerance=tolerance, confidence=confidence)
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: bornlens
3
+ Version: 0.1.0
4
+ Summary: Finite-shot comparisons of Pauli expectations
5
+ License-Expression: Apache-2.0
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Provides-Extra: qiskit
10
+ Requires-Dist: qiskit<3,>=2.6; extra == "qiskit"
11
+ Dynamic: license-file
12
+
13
+ # BornLens
14
+
15
+ BornLens compares a Pauli expectation before and after a quantum circuit change.
16
+ It reports the measured change, a finite-sample confidence interval and a tolerance verdict.
17
+ Part of the PhaseTensor Quantum Computing Suite.
18
+
19
+ Install from a checkout with `python -m pip install .`. For ideal Qiskit simulation use
20
+ `python -m pip install '.[qiskit]'`.
21
+
22
+ ```python
23
+ from bornlens import Sample, compare, shots_per_circuit
24
+
25
+ before = Sample("Z", plus=7500, minus=2500)
26
+ after = Sample("Z", plus=7550, minus=2450)
27
+ result = compare(before, after, tolerance=0.05)
28
+ print(result.verdict, result.delta, result.interval)
29
+ # within_tolerance, approximately 0.01 and (-0.0284, 0.0484)
30
+ print(shots_per_circuit(0.05)) # 5903 shots per circuit at 95% confidence
31
+ ```
32
+
33
+ ## Statistical protocol
34
+
35
+ Fix the observable, tolerance, confidence and sample sizes before collecting data.
36
+ Assume independent shots within and between circuits, with a stable outcome distribution
37
+ for each circuit. Each measured eigenvalue is +1 or -1. The sample mean is
38
+ (plus - minus) / shots. The estimated change is mean B minus mean A.
39
+
40
+ For confidence 1 - alpha, apply the two-sided Hoeffding bound to the weighted sum
41
+ of the independent signed outcomes. Each A contribution has range width 2/nA and
42
+ each B contribution has width 2/nB. The resulting half-width is
43
+ sqrt(2 log(2/alpha) (1/nA + 1/nB)). Intersect the interval with [-2, 2].
44
+ For the identity observable the change is exactly zero. Hoeffding gives a
45
+ conservative finite-sample bound even for unanimous outcomes. A normal approximation
46
+ using empirical variance can give zero width for those samples.
47
+
48
+ An interval contained in the closed tolerance band gives within_tolerance.
49
+ An interval strictly above or below the band gives beyond_tolerance. All other
50
+ intervals give inconclusive. Touching a boundary from outside is inconclusive.
51
+ Coverage concerns one prespecified comparison. Drift, correlated shots, repeated
52
+ looks and multiple comparisons require separate treatment.
53
+
54
+ For equal sample sizes the sufficient shots per circuit for half-width h are
55
+ ceil(4 log(2/alpha) / h²). This controls precision. The verdict also depends
56
+ on the distance of the true change from the tolerance boundary.
57
+
58
+ Reference: [Hoeffding (1963), Probability Inequalities for Sums of Bounded Random Variables](https://doi.org/10.1080/01621459.1963.10500830).
59
+
60
+ ## Qiskit
61
+
62
+ ```python
63
+ from qiskit import QuantumCircuit
64
+ from bornlens.qiskit import compare_circuits
65
+
66
+ a = QuantumCircuit(1)
67
+ b = a.copy()
68
+ b.x(0)
69
+ result = compare_circuits(a, b, "Z", shots_a=1000, shots_b=1500,
70
+ tolerance=0.1, seed=17)
71
+ print(result.verdict) # beyond_tolerance
72
+ ```
73
+
74
+ Pass bound gate circuits before measurements. Rightmost Pauli factor acts on qubit 0.
75
+ The adapter rotates X with H and Y with S-dagger followed by H, then computes parity
76
+ over nonidentity factors. For external integer counts use from_counts(counts, label)
77
+ after applying these basis rotations and measuring qubit i into classical bit i
78
+ of one full-width register. The caller supplies the measurement basis and mapping.
79
+ The simulator uses separate random streams for A and B. Run the checks with
80
+ `python -m unittest discover -s tests -v`.
81
+
82
+ ## Validation and release 0.1.0
83
+
84
+ Install the release with `python -m pip install bornlens==0.1.0`.
85
+ For development install the checkout with the Qiskit extra and run
86
+ `python benchmarks/coverage.py` to reproduce [the benchmark counts](benchmarks/results.csv).
87
+ Each row contains 5,000 independent trials with a fixed seed, tolerance 0.1 and
88
+ nominal coverage 95%. The samples follow the exact Z measurement law of ideal
89
+ single-qubit Ry circuits. Incorrect counts exclude inconclusive decisions.
90
+ The benchmark covers five true changes and three shot budgets. It measures
91
+ ideal fixed-shot behavior; hardware drift and correlated noise require separate experiments.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ benchmarks/coverage.py
6
+ benchmarks/results.csv
7
+ bornlens/__init__.py
8
+ bornlens/qiskit.py
9
+ bornlens.egg-info/PKG-INFO
10
+ bornlens.egg-info/SOURCES.txt
11
+ bornlens.egg-info/dependency_links.txt
12
+ bornlens.egg-info/requires.txt
13
+ bornlens.egg-info/top_level.txt
14
+ tests/test_adapter.py
15
+ tests/test_core.py
@@ -0,0 +1,3 @@
1
+
2
+ [qiskit]
3
+ qiskit<3,>=2.6
@@ -0,0 +1 @@
1
+ bornlens
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bornlens"
7
+ version = "0.1.0"
8
+ description = "Finite-shot comparisons of Pauli expectations"
9
+ requires-python = ">=3.9"
10
+ readme = "README.md"
11
+ license = "Apache-2.0"
12
+
13
+ [project.optional-dependencies]
14
+ qiskit = ["qiskit>=2.6,<3"]
15
+
16
+ [tool.setuptools]
17
+ packages = ["bornlens"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,56 @@
1
+ import importlib.util
2
+ import unittest
3
+
4
+ from bornlens import Sample, compare
5
+
6
+
7
+ @unittest.skipUnless(importlib.util.find_spec("qiskit"), "optional Qiskit dependency")
8
+ class AdapterTests(unittest.TestCase):
9
+ def test_axes_and_order(self):
10
+ from qiskit import QuantumCircuit
11
+ from bornlens.qiskit import from_counts, sample_counts
12
+
13
+ circuit = QuantumCircuit(2)
14
+ circuit.x(0)
15
+ circuit.h(1)
16
+ circuit.s(1)
17
+ for label, sign in [("YZ", -1), ("YI", 1), ("IZ", -1)]:
18
+ counts = sample_counts(circuit, label, 60, seed=31)
19
+ self.assertEqual(from_counts(counts, label).mean, sign)
20
+ x = QuantumCircuit(1)
21
+ x.h(0)
22
+ self.assertEqual(sample_counts(x, "X", 60, seed=4), {"0": 60})
23
+
24
+ def test_same_counts(self):
25
+ from unittest.mock import patch
26
+ from qiskit import QuantumCircuit
27
+ from bornlens.qiskit import compare_circuits, sample_counts
28
+
29
+ a = QuantumCircuit(1)
30
+ a.h(0)
31
+ b = QuantumCircuit(1)
32
+ b.ry(.4, 0)
33
+ observed = []
34
+
35
+ def record(*args, **kwargs):
36
+ counts = sample_counts(*args, **kwargs)
37
+ observed.append(Sample("Z", counts.get("0", 0), counts.get("1", 0)))
38
+ return counts
39
+
40
+ with patch("bornlens.qiskit.sample_counts", side_effect=record):
41
+ actual = compare_circuits(a, b, "Z", shots_a=900, shots_b=1600,
42
+ tolerance=.1, seed=19)
43
+ self.assertEqual(actual, compare(*observed, tolerance=.1))
44
+ self.assertEqual(actual.verdict, "beyond_tolerance")
45
+
46
+ def test_invalid_inputs(self):
47
+ from qiskit import QuantumCircuit
48
+ from bornlens.qiskit import from_counts, sample_counts
49
+
50
+ for counts in [{}, {"01": 4}, {"0 1": 3}, {"1": -1}]:
51
+ with self.assertRaises(ValueError):
52
+ from_counts(counts, "Z")
53
+ circuit = QuantumCircuit(1)
54
+ circuit.measure_all()
55
+ with self.assertRaises(ValueError):
56
+ sample_counts(circuit, "Z", 100)
@@ -0,0 +1,46 @@
1
+ import math
2
+ import unittest
3
+
4
+ from bornlens import Sample, _verdict, compare, shots_per_circuit
5
+
6
+
7
+ class CoreTests(unittest.TestCase):
8
+ def test_three_decisions(self):
9
+ a = Sample("Z", 7500, 2500)
10
+ for b, verdict in [(Sample("Z", 7550, 2450), "within_tolerance"),
11
+ (Sample("Z", 2500, 7500), "beyond_tolerance"),
12
+ (Sample("Z", 7750, 2250), "inconclusive")]:
13
+ self.assertEqual(compare(a, b, tolerance=.05).verdict, verdict)
14
+
15
+ def test_boundaries(self):
16
+ for sign in (-1, 1):
17
+ edge = sign * .25
18
+ self.assertEqual(_verdict(edge, edge, .25), "within_tolerance")
19
+ lo, hi = sorted((edge, sign * .5))
20
+ self.assertEqual(_verdict(lo, hi, .25), "inconclusive")
21
+
22
+ def test_unequal_sizes(self):
23
+ a, b = Sample("X", 3, 1), Sample("X", 2, 6)
24
+ r = compare(a, b, tolerance=.2)
25
+ self.assertEqual((r.delta, r.shots_a, r.shots_b), (-1, 4, 8))
26
+ self.assertEqual(r.interval[0], -2)
27
+ self.assertAlmostEqual(r.interval[1], -1 + math.sqrt(.75 * math.log(40)))
28
+
29
+ def test_validation(self):
30
+ for args in [("z", 1, 1), ("Z", 0, 0), ("Z", True, 0),
31
+ ("I", 0, 1), ("X", -1, 3), ("Z", 1.2, 1)]:
32
+ with self.assertRaises(ValueError):
33
+ Sample(*args)
34
+ a = Sample("I", 10, 0)
35
+ self.assertEqual(compare(a, a, tolerance=0).interval, (0, 0))
36
+ for b, tol, conf in [(Sample("X", 1, 0), 1, .95),
37
+ (a, float("nan"), .95), (a, 1, 1)]:
38
+ with self.assertRaises(ValueError):
39
+ compare(a, b, tolerance=tol, confidence=conf)
40
+
41
+ def test_planner(self):
42
+ n = shots_per_circuit(.05)
43
+ self.assertEqual(n, 5903)
44
+ for shots in (n, n - 1):
45
+ a = Sample("Y", shots, 0)
46
+ self.assertEqual(compare(a, a, tolerance=.05).interval[1] <= .05, shots == n)