qcbench 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.
@@ -0,0 +1,10 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Added canonical hardware plans for readout, GHZ fidelity, mirror survival, T1 and echo T2.
6
+ - Added OpenQASM 3 export, strict integer-count validation and plan-bound datasets.
7
+ - Added Wilson intervals, multi-setting GHZ analysis and bounded coherence decay fits with diagnostics.
8
+ - Added optional Qiskit device preparation, effective delay recording and IBM Runtime opt-in submission/collection.
9
+ - Added explicit hardware/simulator/synthetic provenance and JSON/CSV reports.
10
+ - Added offline demonstrations and independent mathematical/local-adapter tests, with no cloud jobs.
@@ -0,0 +1,9 @@
1
+ # Contributing
2
+
3
+ Contribute protocols, provider adapters and analysis improvements through issues and pull requests. Implementations must be independently authored or include required licenses and attribution. Preserve scholarly credit for measurement methods.
4
+
5
+ A protocol must state the physical experiment, state/gate conventions, timing units, output counts format, estimator, statistical assumptions and limits of interpretation. Include independent mathematical tests and validation of malformed inputs. Distinguish fitted parameters, circuit success and gate fidelity; do not invent aggregate hardware scores.
6
+
7
+ Adapters must preserve publication order, bit order, register mapping and effective timing metadata. Keep SDKs optional. No tests, CI or examples may submit cloud jobs by default. All live submission paths require an explicit opt-in; tests must use local backends or stubs. Never include account credentials, raw private device data or unsupported performance claims.
8
+
9
+ Changing existing circuits or estimators requires a suite or package version change. Do not silently reinterpret historical datasets. Keep synthetic data visibly labelled in all exports.
qcbench-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ include METHODS.md CONTRIBUTING.md RELEASING.md CHANGELOG.md
2
+ recursive-include examples *.py *.json
3
+ recursive-include tests *.py
@@ -0,0 +1,50 @@
1
+ # Methods and scope
2
+
3
+ All probabilities are computed directly from integer counts. No readout mitigation, noise inversion or SPAM separation is performed. The generator and analysis implementations are original; the scientific observables and statistical estimators below are standard mathematical methods.
4
+
5
+ ## Readout and mirror success
6
+
7
+ For a qubit prepared in b, the assignment-error estimate is the number of shots with measured value 1-b divided by shots. Preparation pulses and initialization errors can contribute to this statistic. A mirror circuit estimates the fraction returning all selected measured bits to zero. Its forward layers and inverse have explicit barriers. It is a circuit-level return probability, not randomized benchmarking, gate fidelity, quantum volume or a proof of quantum advantage.
8
+
9
+ For k successes in N independent shots, Wilson intervals use p=k/N and z equal to the standard normal quantile for the chosen two-sided confidence:
10
+
11
+ center = (p + z²/(2N)) / (1 + z²/N)
12
+ half = z sqrt(p(1-p)/N + z²/(4N²)) / (1 + z²/N)
13
+
14
+ Interval endpoints are center +/- half. This avoids a falsely zero-width uncertainty at observed p=0 or p=1. Coverage remains approximate, especially at extreme probabilities and low shots. Reference: E. B. Wilson, *Probable Inference, the Law of Succession, and Statistical Inference* (1927), [DOI](https://doi.org/10.1080/01621459.1927.10502953).
15
+
16
+ ## GHZ fidelity
17
+
18
+ Target |GHZ+> = (|0...0> + |1...1>)/sqrt(2). For a stable state rho,
19
+
20
+ F = (P(0...0) + P(1...1) + C) / 2
21
+ C = (1/n) sum_{k=0}^{n-1} (-1)^k <M(k*pi/n) tensor ... tensor M(k*pi/n)>
22
+ M(theta) = cos(theta) X + sin(theta) Y
23
+
24
+ Z-basis shots estimate the population term. Apply RZ(-theta) then H on each qubit before computational-basis measurement to obtain M(theta). Even parity corresponds to expectation +1. Defining p_k as the probability that parity equals k modulo 2 gives
25
+
26
+ F_hat = population_hat/2 + (1/n) sum_k p_k_hat - 1/2.
27
+
28
+ A Z-only measurement cannot distinguish an ideal GHZ state from its incoherent 50:50 mixture. Both have population one, but fidelities one and one-half respectively. The test suite checks the full formula against independently calculated Born probabilities for arbitrary complex states on two, three and four qubits.
29
+
30
+ For a requested error probability alpha, each of the n+1 component Wilson intervals uses confidence 1-alpha/(n+1). Their weighted endpoints produce the reported combined interval, clipped to the physical fidelity range [0,1]. The point estimator is not clipped and can be negative due to finite shots or inconsistent measurements. Bonferroni does not make an approximate component interval exact; this result does not constitute device-independent certification. State drift and errors in the measurement rotations can bias it. The n+1-setting method is described by O. Gühne, C.-Y. Lu, W.-B. Gao and J.-W. Pan, *Toolbox for entanglement detection and fidelity estimation* ([arXiv:0706.2432](https://arxiv.org/abs/0706.2432)).
31
+
32
+ ## Coherence experiments
33
+
34
+ T1: prepare |1>, idle for t, then measure probability one.
35
+
36
+ Echo: RY(pi/2), idle t/2, X, idle t/2, RY(pi/2), then measure probability one. The ideal zero-noise sequence returns |1>. Its decay constant is an echo coherence estimate, not Ramsey T2*.
37
+
38
+ For both experiments, fit
39
+
40
+ p(t) = p_inf + (p_zero - p_inf) exp(-t/T),
41
+
42
+ with p_zero and p_inf bounded to [0,1] and positive T. Times are rescaled by the longest delay for numerical conditioning. Fit weights use a plug-in binomial variance with a finite floor to avoid singular weights at observed zero/one probabilities. Uncertainty is the local asymptotic covariance from weighted nonlinear least squares, not a bootstrap or a model-independent coverage guarantee. A free asymptote can be difficult to identify without a sufficiently long delay range.
43
+
44
+ At least five distinct effective times are needed. Very small contrast, covariance failure, a time error as large as the fitted time, negligible fitted decaying contrast or an upper-bound fit returns unidentifiable. Reduced chi-squared above five is flagged as model_mismatch; this threshold is a diagnostic heuristic, not a calibrated hypothesis test. Raw time points, shots and probabilities are preserved.
45
+
46
+ Effective times from the device adapter include rounded explicit idle delays and exclude pulse durations. Different providers may implement delays, echo pulses, resets, scheduling and dynamical decoupling differently. Compare experiments only after reviewing these settings and the compiled circuit. Calibration drift, heating, leakage and correlated shots are outside the single-exponential model and covariance uncertainty.
47
+
48
+ ## Provenance
49
+
50
+ A deterministic plan fingerprint binds the generator version, parameters, physical mapping and all logical operations. Dataset labels are declared by the caller; they are not signatures or independent hardware attestations. Sampler collection assumes the original publication order and fixed `meas` register. Preserve raw counts, plan, job ID, compiled execution metadata and acquisition conditions when publishing measurements. Synthetic demonstrations must remain labelled synthetic.
qcbench-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: qcbench
3
+ Version: 0.1.0
4
+ Summary: Reproducible quantum computer characterization from hardware circuits and shot counts
5
+ Author: QCBench contributors
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/qcbench-org/qcbench
8
+ Project-URL: Repository, https://github.com/qcbench-org/qcbench
9
+ Project-URL: Issues, https://github.com/qcbench-org/qcbench/issues
10
+ Keywords: quantum,QPU,hardware,benchmark,characterization
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Physics
15
+ Requires-Python: >=3.11
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: scipy>=1.10
20
+ Provides-Extra: qiskit
21
+ Requires-Dist: qiskit<3,>=1.2; extra == "qiskit"
22
+ Provides-Extra: ibm
23
+ Requires-Dist: qiskit<3,>=1.2; extra == "ibm"
24
+ Requires-Dist: qiskit-ibm-runtime<1,>=0.30; extra == "ibm"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7; extra == "dev"
27
+ Requires-Dist: build; extra == "dev"
28
+ Requires-Dist: twine; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # QCBench
32
+
33
+ [![PyPI](https://img.shields.io/pypi/v/qcbench)](https://pypi.org/project/qcbench/)
34
+ [![CI](https://github.com/qcbench-org/qcbench/actions/workflows/ci.yml/badge.svg)](https://github.com/qcbench-org/qcbench/actions/workflows/ci.yml)
35
+
36
+ **Reproducible quantum computer characterization from hardware experiments and shot counts.**
37
+
38
+ QCBench plans small QPU experiments, exports circuits, collects shot-count results and produces quantitative reports with uncertainty and provenance. Its first release measures **readout assignment error, GHZ state fidelity, mirror-circuit survival, T1 and spin-echo T2**. The focus is quantum-computer behavior under an actual experiment, rather than SDK operation speed.
39
+
40
+ Version 0.1.0 includes independently implemented circuit generators and analysis, an optional Qiskit device compiler, IBM Runtime submission and result collection, and a fully offline synthetic demonstration. It is an initial characterization toolkit, not a comprehensive hardware ranking, vendor-certified calibration suite or composite quantum-computer score. No real-device performance numbers are bundled or claimed.
41
+
42
+ ## Install
43
+
44
+ Requires Python 3.11 or newer. Core dependencies are NumPy and SciPy; quantum SDKs are optional.
45
+
46
+ ```bash
47
+ pip install qcbench
48
+ pip install 'qcbench[qiskit]' # Native circuits and device-aware compilation
49
+ pip install 'qcbench[ibm]' # Also IBM Runtime submission and collection
50
+ ```
51
+
52
+ ## Try it offline
53
+
54
+ ```bash
55
+ qcbench list
56
+ qcbench demo --directory demo-results
57
+ qcbench analyze demo-results/plan.json demo-results/counts.json \
58
+ --output report.json --csv report.csv
59
+ ```
60
+
61
+ The demo writes a deterministic experiment plan, synthetic shot records, JSON analysis and CSV metrics. Every dataset and report carries `execution_kind="synthetic"`. The synthetic fixture uses family-specific outcome distributions; it is not a gate-level noise simulator or a hardware result.
62
+
63
+ ## Prepare an experiment
64
+
65
+ ```bash
66
+ qcbench plan --physical-qubits 0 1 --output plan.json
67
+ qcbench export plan.json --directory circuits
68
+
69
+ # Select only readout checks for one physical qubit.
70
+ qcbench plan --physical-qubits 7 --benchmark readout --output readout-plan.json
71
+
72
+ # Customize the time range and mirror circuits.
73
+ qcbench plan --physical-qubits 0 1 2 --times-us 0 10 25 50 100 200 \
74
+ --mirror-depths 1 4 8 --mirror-sequences 3 --seed 42 --output plan.json
75
+ ```
76
+
77
+ The default two-qubit plan contains **40 circuits**. Plan generation and OpenQASM export do not connect to a provider or submit jobs. OpenQASM 3 exports use logical wires; the accompanying plan contains the requested physical-qubit mapping. A provider must compile these programs for its device before execution. Delay and instruction support vary by hardware.
78
+
79
+ Selected physical indices must be unique nonnegative integers; up to 32 selected qubits are supported. GHZ needs at least two. Coherence experiments require at least five unique increasing delay times starting at zero. Times are in microseconds. Mirror depth counts forward layers; each forward circuit is followed by its inverse.
80
+
81
+ ## Measurements
82
+
83
+ | Family | Experiment | Reported quantity |
84
+ | --- | --- | --- |
85
+ | `readout` | Prepare 0 and 1 on each selected qubit | P(measure 1 \| prepare 0) and P(measure 0 \| prepare 1), with Wilson intervals |
86
+ | `ghz` | Prepare a GHZ state and measure Z populations plus n equatorial parity settings | Estimated GHZ fidelity, component results and approximate combined interval |
87
+ | `mirror` | Seeded local rotations/CNOT layers followed by the inverse | All-zero return probability at each depth and sequence, with Wilson interval |
88
+ | `t1` | X preparation followed by a variable idle delay | Single-exponential probability-one decay time in microseconds |
89
+ | `t2_echo` | RY(pi/2), half delay, X, half delay, RY(pi/2) | Spin-echo probability-one decay time in microseconds |
90
+
91
+ GHZ fidelity uses **n+1 measurement settings** and includes coherence; all-zero/all-one population alone is not treated as fidelity. Readout results include preparation and gate errors. Mirror survival is not randomized benchmarking, and no per-gate error or quantum-volume value is inferred from it. There is no error mitigation in this release. See [METHODS.md](METHODS.md) for equations, assumptions and limitations.
92
+
93
+ ## Import hardware shot counts
94
+
95
+ All counts use fixed-width binary strings, with the **most significant bit on the left**. Logical qubit 0 is the rightmost bit. Logical index i maps initially to `plan['config']['physical_qubits'][i]`. Counts must be nonnegative integers with a positive total, not quasi-probabilities, floating-point weights, hex strings or multiple-register strings.
96
+
97
+ For example, make and analyze a single-qubit readout dataset:
98
+
99
+ ```python
100
+ from qcbench import make_plan, make_dataset, analyze, write_json
101
+
102
+ plan = make_plan(physical_qubits=[7], benchmarks=['readout'])
103
+ # Replace these illustrative counts with your measured results.
104
+ counts = {
105
+ 'readout.q0.p0': {'0': 980, '1': 20},
106
+ 'readout.q0.p1': {'0': 35, '1': 965},
107
+ }
108
+ data = make_dataset(
109
+ plan, counts,
110
+ execution_kind='synthetic', # Use 'hardware' only for actual device counts.
111
+ backend_name='illustrative-counts',
112
+ )
113
+ report = analyze(plan, data)
114
+ write_json(plan, 'plan.json')
115
+ write_json(data, 'counts.json')
116
+ write_json(report, 'report.json')
117
+ ```
118
+
119
+ For real measurements, declare `execution_kind='hardware'`, supply the device name and job ID, and include relevant execution metadata. Use `simulator` for simulated circuits and `synthetic` for constructed data. Provenance is caller-declared, not independently authenticated. Merely setting the hardware label does not establish that data came from a QPU.
120
+
121
+ A dataset is bound to its exact plan by SHA-256. Analysis rejects missing, duplicate or unknown circuit IDs and mismatched plans. A complete dataset must contain one counts object for every planned circuit; partial jobs should be completed before analysis. Canonical version-1 plans are generated by `make_plan`; editing their circuit definitions or metadata is rejected. Custom experiment families require a new implementation and suite version.
122
+
123
+ ## Qiskit preparation and sampler results
124
+
125
+ ```python
126
+ from qcbench import make_plan, analyze
127
+ from qcbench.qiskit_adapter import prepare_qiskit, collect_sampler_result
128
+ from qiskit.primitives import StatevectorSampler
129
+
130
+ plan = make_plan(benchmarks=['readout', 'ghz', 'mirror'])
131
+ circuits, execution = prepare_qiskit(plan)
132
+ # Local simulator example; no cloud access or QPU submission.
133
+ result = StatevectorSampler(seed=7).run(circuits, shots=1024).result()
134
+ data = collect_sampler_result(
135
+ plan, result, execution_kind='simulator',
136
+ backend_name='StatevectorSampler', execution_metadata=execution,
137
+ )
138
+ report = analyze(plan, data)
139
+ ```
140
+
141
+ For device compilation, call `prepare_qiskit(plan, backend)`. It uses optimization level 0, the requested initial layout and a fixed compiler seed. Barriers separate mirror layers, the inversion boundary, state preparation and final measurement so the intended mirror experiment is not trivially optimized into an empty circuit. Review the compiled gate counts and layout before submission; other provider optimizers may treat barriers differently.
142
+
143
+ When a backend exposes `dt`, idle delays are rounded to a multiple of its advertised granularity and pulse alignment. Effective idle times are recorded and used in decay analysis when the execution metadata is passed to the collector. These times exclude pulse durations. The requested physical list is an initial layout, not a promise that routing never uses other qubits. Compiled width, layout and gate counts are retained. Backend-specific timing and instruction constraints still require review.
144
+
145
+ ## IBM QPU execution
146
+
147
+ The source repository includes [examples/ibm_hardware.py](https://github.com/qcbench-org/qcbench/blob/main/examples/ibm_hardware.py). By default, it writes a plan without connecting to IBM. It requires `--submit` and an explicit accessible backend to run a job:
148
+
149
+ ```bash
150
+ # Plan only. No account lookup, cloud connection or job submission.
151
+ python examples/ibm_hardware.py --physical-qubits 0 1
152
+
153
+ # After reviewing the plan and configuring your IBM account locally:
154
+ python examples/ibm_hardware.py --backend YOUR_BACKEND_NAME \
155
+ --physical-qubits 0 1 --shots 1024 --submit
156
+ ```
157
+
158
+ The Python API `submit_ibm(plan, backend, shots=1024, allow_submit=True)` returns `(job, execution_metadata)`. Omitting the explicit opt-in raises an error before submission. A job can consume paid QPU time; review the backend, plan, circuit count, shot count and provider limits first. No cloud jobs run as part of installation, tests, demo, plan, export or analysis. Credentials use the provider SDK's existing account configuration and are never stored by QCBench.
159
+
160
+ The example records the submission/job ID, raw counts and report. It expects the ordered Sampler V2 result format and one classical register named `meas`. Retain the exact plan and publication order when retrieving a job later. Device submission is implemented but has not been validated on a paid QPU as part of this release; local compilation, local sampler collection and a stubbed submission protocol are tested.
161
+
162
+ ## Reports and interpretation
163
+
164
+ Reports include package/suite versions, analysis timestamp and software environment, device/provenance labels, job ID, plan fingerprint, requested physical mapping, raw experiment configuration, total circuits/shots, per-metric statistics and fit diagnostics. Raw counts stay in the dataset for independent reanalysis. The report timestamp is analysis time, not a claim about when a device executed the experiment. Put execution timestamps, calibration identifiers and provider/compiler options in dataset metadata when available; keep credentials out of metadata.
165
+
166
+ Default confidence is 95%, adjustable with `qcbench analyze --confidence`. Wilson intervals are approximate frequentist intervals, not posterior probabilities. GHZ components use a Bonferroni adjustment with approximate Wilson intervals, so the combined result is not an exact-coverage or device-independent entanglement certificate. Shots must be independent and measurement settings stable for the statistical interpretation to apply.
167
+
168
+ Coherence fitting uses a bounded, weighted three-parameter exponential, with free initial probability and asymptote. It reports covariance-based standard error, chi-squared and degrees of freedom. Flat signals, too few effective times or poorly constrained parameters return `status='unidentifiable'` instead of a fabricated T value. A large reduced chi-squared is flagged as a model mismatch; a fitted value alone does not validate the model. Inspect time coverage, pulse calibration, residuals and drift before comparing devices. No bootstrap or calibration-systematic uncertainty is claimed.
169
+
170
+ Successful report production exits 0, including reports containing unidentifiable fits. Input, validation and file errors exit 2. Invalid performance should remain visible in reports, not be confused with an I/O failure.
171
+
172
+ ## Development
173
+
174
+ ```bash
175
+ python -m pip install -e '.[ibm,dev]'
176
+ python -m pytest -q
177
+ python -m build
178
+ python -m twine check --strict dist/*
179
+ ```
180
+
181
+ Tests cover statistical boundaries, arbitrary-state GHZ fidelity, analytic decay recovery, provenance/count validation, ideal circuits, local sampler integration, device compilation and submission opt-in without cloud jobs. Core-only environments skip the optional adapter tests. See [CONTRIBUTING.md](CONTRIBUTING.md) and [RELEASING.md](RELEASING.md). Code and original experiment definitions are Apache-2.0 licensed.
182
+
183
+ ## Roadmap
184
+
185
+ Additional QPU providers, richer job recovery, calibration snapshots, gate-set and randomized benchmarking protocols, application-level workloads, drift-aware repeats, systematic uncertainty, connectivity sweeps and cross-device result views. Each added protocol must define its experiment, statistical estimator and scope of valid interpretation.
186
+
187
+ ## 中文说明
188
+
189
+ QCBench 面向量子计算真机的测评与表征,首版提供读出分配误差、GHZ 态保真度、镜像电路成功率、T1 和回波 T2 的电路生成与 counts 分析,支持 OpenQASM 3 导出、Qiskit 设备编译、IBM Runtime 显式提交/结果采集以及 JSON/CSV 报告。真机、模拟器和合成数据必须明确区分。默认离线演示不连接云平台,也不提交真机任务;首版尚未执行付费 QPU 验证,不包含真实设备排名或虚构真机分数。
@@ -0,0 +1,159 @@
1
+ # QCBench
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/qcbench)](https://pypi.org/project/qcbench/)
4
+ [![CI](https://github.com/qcbench-org/qcbench/actions/workflows/ci.yml/badge.svg)](https://github.com/qcbench-org/qcbench/actions/workflows/ci.yml)
5
+
6
+ **Reproducible quantum computer characterization from hardware experiments and shot counts.**
7
+
8
+ QCBench plans small QPU experiments, exports circuits, collects shot-count results and produces quantitative reports with uncertainty and provenance. Its first release measures **readout assignment error, GHZ state fidelity, mirror-circuit survival, T1 and spin-echo T2**. The focus is quantum-computer behavior under an actual experiment, rather than SDK operation speed.
9
+
10
+ Version 0.1.0 includes independently implemented circuit generators and analysis, an optional Qiskit device compiler, IBM Runtime submission and result collection, and a fully offline synthetic demonstration. It is an initial characterization toolkit, not a comprehensive hardware ranking, vendor-certified calibration suite or composite quantum-computer score. No real-device performance numbers are bundled or claimed.
11
+
12
+ ## Install
13
+
14
+ Requires Python 3.11 or newer. Core dependencies are NumPy and SciPy; quantum SDKs are optional.
15
+
16
+ ```bash
17
+ pip install qcbench
18
+ pip install 'qcbench[qiskit]' # Native circuits and device-aware compilation
19
+ pip install 'qcbench[ibm]' # Also IBM Runtime submission and collection
20
+ ```
21
+
22
+ ## Try it offline
23
+
24
+ ```bash
25
+ qcbench list
26
+ qcbench demo --directory demo-results
27
+ qcbench analyze demo-results/plan.json demo-results/counts.json \
28
+ --output report.json --csv report.csv
29
+ ```
30
+
31
+ The demo writes a deterministic experiment plan, synthetic shot records, JSON analysis and CSV metrics. Every dataset and report carries `execution_kind="synthetic"`. The synthetic fixture uses family-specific outcome distributions; it is not a gate-level noise simulator or a hardware result.
32
+
33
+ ## Prepare an experiment
34
+
35
+ ```bash
36
+ qcbench plan --physical-qubits 0 1 --output plan.json
37
+ qcbench export plan.json --directory circuits
38
+
39
+ # Select only readout checks for one physical qubit.
40
+ qcbench plan --physical-qubits 7 --benchmark readout --output readout-plan.json
41
+
42
+ # Customize the time range and mirror circuits.
43
+ qcbench plan --physical-qubits 0 1 2 --times-us 0 10 25 50 100 200 \
44
+ --mirror-depths 1 4 8 --mirror-sequences 3 --seed 42 --output plan.json
45
+ ```
46
+
47
+ The default two-qubit plan contains **40 circuits**. Plan generation and OpenQASM export do not connect to a provider or submit jobs. OpenQASM 3 exports use logical wires; the accompanying plan contains the requested physical-qubit mapping. A provider must compile these programs for its device before execution. Delay and instruction support vary by hardware.
48
+
49
+ Selected physical indices must be unique nonnegative integers; up to 32 selected qubits are supported. GHZ needs at least two. Coherence experiments require at least five unique increasing delay times starting at zero. Times are in microseconds. Mirror depth counts forward layers; each forward circuit is followed by its inverse.
50
+
51
+ ## Measurements
52
+
53
+ | Family | Experiment | Reported quantity |
54
+ | --- | --- | --- |
55
+ | `readout` | Prepare 0 and 1 on each selected qubit | P(measure 1 \| prepare 0) and P(measure 0 \| prepare 1), with Wilson intervals |
56
+ | `ghz` | Prepare a GHZ state and measure Z populations plus n equatorial parity settings | Estimated GHZ fidelity, component results and approximate combined interval |
57
+ | `mirror` | Seeded local rotations/CNOT layers followed by the inverse | All-zero return probability at each depth and sequence, with Wilson interval |
58
+ | `t1` | X preparation followed by a variable idle delay | Single-exponential probability-one decay time in microseconds |
59
+ | `t2_echo` | RY(pi/2), half delay, X, half delay, RY(pi/2) | Spin-echo probability-one decay time in microseconds |
60
+
61
+ GHZ fidelity uses **n+1 measurement settings** and includes coherence; all-zero/all-one population alone is not treated as fidelity. Readout results include preparation and gate errors. Mirror survival is not randomized benchmarking, and no per-gate error or quantum-volume value is inferred from it. There is no error mitigation in this release. See [METHODS.md](METHODS.md) for equations, assumptions and limitations.
62
+
63
+ ## Import hardware shot counts
64
+
65
+ All counts use fixed-width binary strings, with the **most significant bit on the left**. Logical qubit 0 is the rightmost bit. Logical index i maps initially to `plan['config']['physical_qubits'][i]`. Counts must be nonnegative integers with a positive total, not quasi-probabilities, floating-point weights, hex strings or multiple-register strings.
66
+
67
+ For example, make and analyze a single-qubit readout dataset:
68
+
69
+ ```python
70
+ from qcbench import make_plan, make_dataset, analyze, write_json
71
+
72
+ plan = make_plan(physical_qubits=[7], benchmarks=['readout'])
73
+ # Replace these illustrative counts with your measured results.
74
+ counts = {
75
+ 'readout.q0.p0': {'0': 980, '1': 20},
76
+ 'readout.q0.p1': {'0': 35, '1': 965},
77
+ }
78
+ data = make_dataset(
79
+ plan, counts,
80
+ execution_kind='synthetic', # Use 'hardware' only for actual device counts.
81
+ backend_name='illustrative-counts',
82
+ )
83
+ report = analyze(plan, data)
84
+ write_json(plan, 'plan.json')
85
+ write_json(data, 'counts.json')
86
+ write_json(report, 'report.json')
87
+ ```
88
+
89
+ For real measurements, declare `execution_kind='hardware'`, supply the device name and job ID, and include relevant execution metadata. Use `simulator` for simulated circuits and `synthetic` for constructed data. Provenance is caller-declared, not independently authenticated. Merely setting the hardware label does not establish that data came from a QPU.
90
+
91
+ A dataset is bound to its exact plan by SHA-256. Analysis rejects missing, duplicate or unknown circuit IDs and mismatched plans. A complete dataset must contain one counts object for every planned circuit; partial jobs should be completed before analysis. Canonical version-1 plans are generated by `make_plan`; editing their circuit definitions or metadata is rejected. Custom experiment families require a new implementation and suite version.
92
+
93
+ ## Qiskit preparation and sampler results
94
+
95
+ ```python
96
+ from qcbench import make_plan, analyze
97
+ from qcbench.qiskit_adapter import prepare_qiskit, collect_sampler_result
98
+ from qiskit.primitives import StatevectorSampler
99
+
100
+ plan = make_plan(benchmarks=['readout', 'ghz', 'mirror'])
101
+ circuits, execution = prepare_qiskit(plan)
102
+ # Local simulator example; no cloud access or QPU submission.
103
+ result = StatevectorSampler(seed=7).run(circuits, shots=1024).result()
104
+ data = collect_sampler_result(
105
+ plan, result, execution_kind='simulator',
106
+ backend_name='StatevectorSampler', execution_metadata=execution,
107
+ )
108
+ report = analyze(plan, data)
109
+ ```
110
+
111
+ For device compilation, call `prepare_qiskit(plan, backend)`. It uses optimization level 0, the requested initial layout and a fixed compiler seed. Barriers separate mirror layers, the inversion boundary, state preparation and final measurement so the intended mirror experiment is not trivially optimized into an empty circuit. Review the compiled gate counts and layout before submission; other provider optimizers may treat barriers differently.
112
+
113
+ When a backend exposes `dt`, idle delays are rounded to a multiple of its advertised granularity and pulse alignment. Effective idle times are recorded and used in decay analysis when the execution metadata is passed to the collector. These times exclude pulse durations. The requested physical list is an initial layout, not a promise that routing never uses other qubits. Compiled width, layout and gate counts are retained. Backend-specific timing and instruction constraints still require review.
114
+
115
+ ## IBM QPU execution
116
+
117
+ The source repository includes [examples/ibm_hardware.py](https://github.com/qcbench-org/qcbench/blob/main/examples/ibm_hardware.py). By default, it writes a plan without connecting to IBM. It requires `--submit` and an explicit accessible backend to run a job:
118
+
119
+ ```bash
120
+ # Plan only. No account lookup, cloud connection or job submission.
121
+ python examples/ibm_hardware.py --physical-qubits 0 1
122
+
123
+ # After reviewing the plan and configuring your IBM account locally:
124
+ python examples/ibm_hardware.py --backend YOUR_BACKEND_NAME \
125
+ --physical-qubits 0 1 --shots 1024 --submit
126
+ ```
127
+
128
+ The Python API `submit_ibm(plan, backend, shots=1024, allow_submit=True)` returns `(job, execution_metadata)`. Omitting the explicit opt-in raises an error before submission. A job can consume paid QPU time; review the backend, plan, circuit count, shot count and provider limits first. No cloud jobs run as part of installation, tests, demo, plan, export or analysis. Credentials use the provider SDK's existing account configuration and are never stored by QCBench.
129
+
130
+ The example records the submission/job ID, raw counts and report. It expects the ordered Sampler V2 result format and one classical register named `meas`. Retain the exact plan and publication order when retrieving a job later. Device submission is implemented but has not been validated on a paid QPU as part of this release; local compilation, local sampler collection and a stubbed submission protocol are tested.
131
+
132
+ ## Reports and interpretation
133
+
134
+ Reports include package/suite versions, analysis timestamp and software environment, device/provenance labels, job ID, plan fingerprint, requested physical mapping, raw experiment configuration, total circuits/shots, per-metric statistics and fit diagnostics. Raw counts stay in the dataset for independent reanalysis. The report timestamp is analysis time, not a claim about when a device executed the experiment. Put execution timestamps, calibration identifiers and provider/compiler options in dataset metadata when available; keep credentials out of metadata.
135
+
136
+ Default confidence is 95%, adjustable with `qcbench analyze --confidence`. Wilson intervals are approximate frequentist intervals, not posterior probabilities. GHZ components use a Bonferroni adjustment with approximate Wilson intervals, so the combined result is not an exact-coverage or device-independent entanglement certificate. Shots must be independent and measurement settings stable for the statistical interpretation to apply.
137
+
138
+ Coherence fitting uses a bounded, weighted three-parameter exponential, with free initial probability and asymptote. It reports covariance-based standard error, chi-squared and degrees of freedom. Flat signals, too few effective times or poorly constrained parameters return `status='unidentifiable'` instead of a fabricated T value. A large reduced chi-squared is flagged as a model mismatch; a fitted value alone does not validate the model. Inspect time coverage, pulse calibration, residuals and drift before comparing devices. No bootstrap or calibration-systematic uncertainty is claimed.
139
+
140
+ Successful report production exits 0, including reports containing unidentifiable fits. Input, validation and file errors exit 2. Invalid performance should remain visible in reports, not be confused with an I/O failure.
141
+
142
+ ## Development
143
+
144
+ ```bash
145
+ python -m pip install -e '.[ibm,dev]'
146
+ python -m pytest -q
147
+ python -m build
148
+ python -m twine check --strict dist/*
149
+ ```
150
+
151
+ Tests cover statistical boundaries, arbitrary-state GHZ fidelity, analytic decay recovery, provenance/count validation, ideal circuits, local sampler integration, device compilation and submission opt-in without cloud jobs. Core-only environments skip the optional adapter tests. See [CONTRIBUTING.md](CONTRIBUTING.md) and [RELEASING.md](RELEASING.md). Code and original experiment definitions are Apache-2.0 licensed.
152
+
153
+ ## Roadmap
154
+
155
+ Additional QPU providers, richer job recovery, calibration snapshots, gate-set and randomized benchmarking protocols, application-level workloads, drift-aware repeats, systematic uncertainty, connectivity sweeps and cross-device result views. Each added protocol must define its experiment, statistical estimator and scope of valid interpretation.
156
+
157
+ ## 中文说明
158
+
159
+ QCBench 面向量子计算真机的测评与表征,首版提供读出分配误差、GHZ 态保真度、镜像电路成功率、T1 和回波 T2 的电路生成与 counts 分析,支持 OpenQASM 3 导出、Qiskit 设备编译、IBM Runtime 显式提交/结果采集以及 JSON/CSV 报告。真机、模拟器和合成数据必须明确区分。默认离线演示不连接云平台,也不提交真机任务;首版尚未执行付费 QPU 验证,不包含真实设备排名或虚构真机分数。