calibmap 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.
Files changed (47) hide show
  1. calibmap-0.1.0/LICENSE +74 -0
  2. calibmap-0.1.0/MANIFEST.in +3 -0
  3. calibmap-0.1.0/PKG-INFO +41 -0
  4. calibmap-0.1.0/README.md +23 -0
  5. calibmap-0.1.0/benchmarks/device_study.py +107 -0
  6. calibmap-0.1.0/benchmarks/interop-local.json +57 -0
  7. calibmap-0.1.0/benchmarks/interoperability.py +62 -0
  8. calibmap-0.1.0/benchmarks/plot_results.py +38 -0
  9. calibmap-0.1.0/benchmarks/principal.json +23 -0
  10. calibmap-0.1.0/benchmarks/principal.py +51 -0
  11. calibmap-0.1.0/benchmarks/provider.py +17 -0
  12. calibmap-0.1.0/benchmarks/scenarios.json +154 -0
  13. calibmap-0.1.0/benchmarks/scenarios.py +108 -0
  14. calibmap-0.1.0/benchmarks/sensitivity.json +116 -0
  15. calibmap-0.1.0/benchmarks/sensitivity.py +73 -0
  16. calibmap-0.1.0/calibmap/__init__.py +99 -0
  17. calibmap-0.1.0/calibmap/diagnostics.py +92 -0
  18. calibmap-0.1.0/calibmap/experiment.py +177 -0
  19. calibmap-0.1.0/calibmap/history.py +98 -0
  20. calibmap-0.1.0/calibmap/planning.py +193 -0
  21. calibmap-0.1.0/calibmap/py.typed +0 -0
  22. calibmap-0.1.0/calibmap/readout.py +100 -0
  23. calibmap-0.1.0/calibmap/records.py +123 -0
  24. calibmap-0.1.0/calibmap/reporting.py +86 -0
  25. calibmap-0.1.0/calibmap/series.py +145 -0
  26. calibmap-0.1.0/calibmap/uncertainty.py +58 -0
  27. calibmap-0.1.0/calibmap.egg-info/PKG-INFO +41 -0
  28. calibmap-0.1.0/calibmap.egg-info/SOURCES.txt +45 -0
  29. calibmap-0.1.0/calibmap.egg-info/dependency_links.txt +1 -0
  30. calibmap-0.1.0/calibmap.egg-info/requires.txt +9 -0
  31. calibmap-0.1.0/calibmap.egg-info/top_level.txt +1 -0
  32. calibmap-0.1.0/docs/acceptance-report.md +11 -0
  33. calibmap-0.1.0/docs/advanced.md +33 -0
  34. calibmap-0.1.0/docs/api.md +20 -0
  35. calibmap-0.1.0/docs/methodology.md +41 -0
  36. calibmap-0.1.0/docs/release-checklist.md +10 -0
  37. calibmap-0.1.0/docs/traceability.md +25 -0
  38. calibmap-0.1.0/pyproject.toml +26 -0
  39. calibmap-0.1.0/setup.cfg +4 -0
  40. calibmap-0.1.0/tests/test_diagnostics.py +63 -0
  41. calibmap-0.1.0/tests/test_experiment.py +64 -0
  42. calibmap-0.1.0/tests/test_history.py +31 -0
  43. calibmap-0.1.0/tests/test_properties.py +25 -0
  44. calibmap-0.1.0/tests/test_references.py +90 -0
  45. calibmap-0.1.0/tests/test_science.py +140 -0
  46. calibmap-0.1.0/tests/test_temporal.py +88 -0
  47. calibmap-0.1.0/tests/test_uncertainty.py +71 -0
calibmap-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,3 @@
1
+ recursive-include docs *.md
2
+ recursive-include tests *.py
3
+ recursive-include benchmarks *.py *.json
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: calibmap
3
+ Version: 0.1.0
4
+ Summary: Offline quantum calibration analytics and hardware stability diagnostics
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Repository, https://github.com/Phasetensor/CalibMap
7
+ Requires-Python: >=3.11
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy>=1.23
11
+ Requires-Dist: scipy>=1.9
12
+ Provides-Extra: ibm
13
+ Requires-Dist: qiskit-ibm-runtime; extra == "ibm"
14
+ Provides-Extra: interop
15
+ Requires-Dist: shotweave==0.2.0; extra == "interop"
16
+ Requires-Dist: bornlens==0.3.1; extra == "interop"
17
+ Dynamic: license-file
18
+
19
+ # CalibMap
20
+
21
+ Offline quantum calibration analytics for PhaseTensor. Development branch. Use timezone-aware calibration, acquisition and publication timestamps to reconstruct historical evidence. Keep provider estimates, synthetic experiments and acquired measurements identifiable throughout analysis.
22
+
23
+ ## Running the examples
24
+
25
+ With NumPy, SciPy and pytest installed, run the following from the checkout.
26
+
27
+ python -m pytest
28
+ PYTHONPATH=. python benchmarks/principal.py
29
+ PYTHONPATH=. python benchmarks/interoperability.py
30
+
31
+ The interoperability example also needs ShotWeave 0.2.0 and BornLens 0.3.1. It uses independent random calibration and confirmatory draws, fixed physical qubit ordering and a 10,000-shot design budget. The examples incur no hardware charges.
32
+
33
+ ## Methods
34
+
35
+ See [scientific design](docs/methodology.md) and [benchmark results](benchmarks/principal.json). Assignment matrices use observed rows and prepared columns. Converting a measured frequency back to prepared probability requires directional calibration and a well-conditioned matrix. The Gaussian monitoring thresholds require a prespecified mean and variance. Offline segmentation uses future observations and supports retrospective analysis only.
36
+
37
+ ## Evidence and installation
38
+
39
+ The development package builds with python -m build. Install the optional interop extra for the integrated example or the ibm extra for IBM Runtime property objects. The public API and limits are indexed in [the module matrix](docs/traceability.md). [Reproduction instructions](docs/advanced.md) cover the three case studies and figures. The scientific-studies artifact in Actions contains the generated figures and numerical results from the same run.
40
+
41
+ The [API guide](docs/api.md) lists input and output contracts by module. Python 3.11–3.14 have been exercised in CI. IBM Runtime and interoperation workflows are tested separately on the environments recorded in the validation workflow.
@@ -0,0 +1,23 @@
1
+ # CalibMap
2
+
3
+ Offline quantum calibration analytics for PhaseTensor. Development branch. Use timezone-aware calibration, acquisition and publication timestamps to reconstruct historical evidence. Keep provider estimates, synthetic experiments and acquired measurements identifiable throughout analysis.
4
+
5
+ ## Running the examples
6
+
7
+ With NumPy, SciPy and pytest installed, run the following from the checkout.
8
+
9
+ python -m pytest
10
+ PYTHONPATH=. python benchmarks/principal.py
11
+ PYTHONPATH=. python benchmarks/interoperability.py
12
+
13
+ The interoperability example also needs ShotWeave 0.2.0 and BornLens 0.3.1. It uses independent random calibration and confirmatory draws, fixed physical qubit ordering and a 10,000-shot design budget. The examples incur no hardware charges.
14
+
15
+ ## Methods
16
+
17
+ See [scientific design](docs/methodology.md) and [benchmark results](benchmarks/principal.json). Assignment matrices use observed rows and prepared columns. Converting a measured frequency back to prepared probability requires directional calibration and a well-conditioned matrix. The Gaussian monitoring thresholds require a prespecified mean and variance. Offline segmentation uses future observations and supports retrospective analysis only.
18
+
19
+ ## Evidence and installation
20
+
21
+ The development package builds with python -m build. Install the optional interop extra for the integrated example or the ibm extra for IBM Runtime property objects. The public API and limits are indexed in [the module matrix](docs/traceability.md). [Reproduction instructions](docs/advanced.md) cover the three case studies and figures. The scientific-studies artifact in Actions contains the generated figures and numerical results from the same run.
22
+
23
+ The [API guide](docs/api.md) lists input and output contracts by module. Python 3.11–3.14 have been exercised in CI. IBM Runtime and interoperation workflows are tested separately on the environments recorded in the validation workflow.
@@ -0,0 +1,107 @@
1
+ """Seeded offline device diagnostics. All measurements in this study are synthetic."""
2
+
3
+ import itertools
4
+ from datetime import UTC, datetime, timedelta
5
+ from pathlib import Path
6
+
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+
10
+ from calibmap import Record
11
+ from calibmap.diagnostics import dependence
12
+ from calibmap.experiment import Criterion, evaluate
13
+ from calibmap.history import stability
14
+ from calibmap.planning import forecast, shortest_path
15
+ from calibmap.readout import Binary
16
+ from calibmap.series import decay_diagnostics, monitor, segments
17
+
18
+ rng = np.random.default_rng(138)
19
+ t = np.cumsum(rng.integers(1, 4, 40))
20
+ x = rng.normal(0, 1, len(t))
21
+ x[20:] += 4
22
+ base = datetime(2025, 1, 1, tzinfo=UTC)
23
+ rows = []
24
+ for i, (dt, y) in enumerate(zip(t, x)):
25
+ stamp = base + timedelta(hours=int(dt))
26
+ rows.append(
27
+ Record(
28
+ "fixture",
29
+ "gate_error",
30
+ (0, 1),
31
+ stamp,
32
+ stamp,
33
+ None,
34
+ 0.02 + 0.002 * y,
35
+ "1",
36
+ "fixture",
37
+ "synthetic",
38
+ "cx",
39
+ )
40
+ )
41
+ latest = rows[-1]
42
+ key = latest.identity("1")
43
+ rolling = [
44
+ stability(rows, r.acquired, timedelta(hours=15), timedelta(hours=5))[key][
45
+ "statistics"
46
+ ]
47
+ for r in rows
48
+ ]
49
+ fig, axes = plt.subplots(3, 3, figsize=(12, 9), layout="constrained")
50
+ ax = axes.flat
51
+ ax[0].plot(t, [r.value for r in rows], ".-")
52
+ ax[0].set(title="Directed CX error timeline", xlabel="Hours")
53
+ ax[1].plot(t, [s["mad"] if s else np.nan for s in rolling])
54
+ ax[1].set(title="15-hour rolling MAD", xlabel="Hours")
55
+ ax[2].hist([r.value for r in rows], bins=9)
56
+ ax[2].set(title="Gate error estimates", ylabel="Count")
57
+ im = ax[3].imshow(Binary(0.07, 0.13).matrix, vmin=0, vmax=1)
58
+ fig.colorbar(im, ax=ax[3])
59
+ ax[3].set(title="Assignment probability", xlabel="Prepared", ylabel="Observed")
60
+ delay = np.linspace(0, 60, 50)
61
+ signal = 0.78 * np.exp(-delay / 18) + 0.12 + rng.normal(0, 0.01, len(delay))
62
+ fit = decay_diagnostics(delay, signal)
63
+ a, tau, b = fit["parameters"]
64
+ ax[4].scatter(delay, signal, s=8)
65
+ ax[4].plot(delay, a * np.exp(-delay / tau) + b)
66
+ ax[4].set(title="Synthetic relaxation", xlabel="Delay (µs)")
67
+ ax[5].plot(t, x)
68
+ alarms = monitor(x, 0, 1)
69
+ ax[5].scatter(t[alarms], x[alarms], marker="x", label="Alarm")
70
+ for boundary in segments(x, 12):
71
+ ax[5].axvline(t[boundary], linestyle="--")
72
+ ax[5].set(title="Online alarms and offline boundaries", xlabel="Hours")
73
+ pair = dependence(
74
+ {"A": dict(zip(t, x)), "B": dict(zip(t, x + rng.normal(size=len(t))))}
75
+ )
76
+ sd = np.sqrt(np.diag(pair["covariance"]))
77
+ ax[6].imshow(pair["covariance"] / np.outer(sd, sd), vmin=-1, vmax=1, cmap="coolwarm")
78
+ ax[6].set(title="Aligned correlation", xticks=[0, 1], xticklabels=pair["labels"])
79
+ edges = {(0, 1): 0.1, (1, 2): 0.1, (0, 2): 0.4}
80
+ _, path = shortest_path(edges, 0, 2)
81
+ positions = np.array([[0, 0], [1, 1], [2, 0]])
82
+ for u, v in edges:
83
+ ax[7].annotate(
84
+ "",
85
+ xy=positions[v],
86
+ xytext=positions[u],
87
+ arrowprops={
88
+ "arrowstyle": "->",
89
+ "color": "green" if (u, v) in itertools.pairwise(path) else "gray",
90
+ },
91
+ )
92
+ for i, (xx, yy) in enumerate(positions):
93
+ ax[7].text(xx, yy, str(i))
94
+ ax[7].set(title="Minimum calibrated path", xlim=(-0.2, 2.2), ylim=(-0.2, 1.2))
95
+ pred = [forecast(t[:i], x[:i], t[i] - t[i - 1], 0.1, 1) for i in range(5, len(x))]
96
+ mean, low, high = np.array(pred).T
97
+ ax[8].plot(t[5:], x[5:], ".", label="Held out")
98
+ ax[8].plot(t[5:], mean)
99
+ ax[8].fill_between(t[5:], low, high, alpha=0.25)
100
+ ax[8].set(title="Future observation intervals", xlabel="Hours")
101
+ result = evaluate(
102
+ rows, latest.acquired, timedelta(days=1), [Criterion(key, upper=0.03)]
103
+ )
104
+ fig.suptitle(
105
+ f"Synthetic device diagnostics | Readiness for error ≤ 0.03: {result.status}"
106
+ )
107
+ fig.savefig(Path(__file__).with_name("device-study.svg"), metadata={"Date": None})
@@ -0,0 +1,57 @@
1
+ {
2
+ "seed": 512,
3
+ "evidence": "synthetic",
4
+ "physical_qubits": [
5
+ 0,
6
+ 1
7
+ ],
8
+ "allocation": [
9
+ 4314,
10
+ 5686
11
+ ],
12
+ "calibration_shots": 12000,
13
+ "pilot_shots": 0,
14
+ "confirmatory_shots": 20000,
15
+ "planning_variance": 0.0001605563509489431,
16
+ "equal_allocation_variance": 0.00016357747679424589,
17
+ "calibration": [
18
+ {
19
+ "qubit": 0,
20
+ "counts": [
21
+ 80,
22
+ 176
23
+ ],
24
+ "simultaneous_intervals": [
25
+ [
26
+ 0.01986843254133326,
27
+ 0.03492456744882955
28
+ ],
29
+ [
30
+ 0.048453161586913956,
31
+ 0.07022886961818259
32
+ ]
33
+ ]
34
+ },
35
+ {
36
+ "qubit": 1,
37
+ "counts": [
38
+ 571,
39
+ 347
40
+ ],
41
+ "simultaneous_intervals": [
42
+ [
43
+ 0.17274204366868956,
44
+ 0.20886322654172482
45
+ ],
46
+ [
47
+ 0.10150218057644417,
48
+ 0.13099934724821474
49
+ ]
50
+ ]
51
+ }
52
+ ],
53
+ "held_out_observed_Z": [
54
+ "within_tolerance",
55
+ "within_tolerance"
56
+ ]
57
+ }
@@ -0,0 +1,62 @@
1
+ """Synthetic independent calibration, planning and held-out Z comparison."""
2
+
3
+ import json
4
+
5
+ import numpy as np
6
+ from bornlens import Sample, compare
7
+ from shotweave import Readout, optimal_allocation
8
+
9
+ from calibmap.readout import Binary, interval
10
+
11
+ rng = np.random.default_rng(512)
12
+ channels = [Binary(0.03, 0.06), Binary(0.19, 0.12)]
13
+ weights = []
14
+ calibration = []
15
+ for q, channel in enumerate(channels):
16
+ counts = [int(rng.binomial(3000, p)) for p in (channel.e0, channel.e1)]
17
+ fitted = Binary(*(x / 3000 for x in counts))
18
+ _, amplification = fitted.invert(0.5)
19
+ _, conditional = Readout(fitted.e0, fitted.e1).correct(0.5, 0.25)
20
+ np.testing.assert_allclose(conditional, 0.25 * amplification)
21
+ weights.append(np.sqrt(conditional))
22
+ calibration.append(
23
+ {
24
+ "qubit": q,
25
+ "counts": counts,
26
+ "simultaneous_intervals": [interval(x, 3000, 0.05 / 4) for x in counts],
27
+ }
28
+ )
29
+ allocation = optimal_allocation(10000, weights)
30
+ assert sum(allocation) == 10000
31
+ out = []
32
+ for q, (channel, n) in enumerate(zip(channels, allocation)):
33
+ observed = channel.e0 + channel.contrast * 0.4
34
+ a, b = rng.binomial(n, observed, size=2)
35
+ label = ("IZ", "ZI")[q]
36
+ comparison = compare(
37
+ Sample(label, n - int(a), int(a)),
38
+ Sample(label, n - int(b), int(b)),
39
+ tolerance=0.12,
40
+ confidence=0.975,
41
+ )
42
+ out.append(comparison.verdict)
43
+ print(
44
+ json.dumps(
45
+ {
46
+ "seed": 512,
47
+ "evidence": "synthetic",
48
+ "physical_qubits": [0, 1],
49
+ "allocation": allocation,
50
+ "calibration_shots": 12000,
51
+ "pilot_shots": 0,
52
+ "confirmatory_shots": 2 * sum(allocation),
53
+ "planning_variance": sum(w**2 / n for w, n in zip(weights, allocation)),
54
+ "equal_allocation_variance": sum(w**2 / 5000 for w in weights),
55
+ "calibration": calibration,
56
+ "held_out_observed_Z": out,
57
+ },
58
+ indent=2,
59
+ )
60
+ )
61
+ # Each fixed allocation applies separately to two independent confirmatory samples.
62
+ assert sum(allocation) * 2 + len(channels) * 2 * 3000 == 32000
@@ -0,0 +1,38 @@
1
+ """Render the recorded simulation results without rerunning random experiments."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import matplotlib.pyplot as plt
7
+ import numpy as np
8
+
9
+ root = Path(__file__).resolve().parent
10
+ data = json.loads((root / "scenarios.json").read_text())
11
+ fig, axes = plt.subplots(1, 3, figsize=(13, 4), layout="constrained")
12
+ scenarios = list(data["drift"])
13
+ rates = [data["drift"][s]["conditional_detection"] for s in scenarios]
14
+ axes[0].bar(scenarios, rates, color="#276681")
15
+ axes[0].set(
16
+ title="Detection among surviving paths", ylabel="Probability", ylim=(0, 1.06)
17
+ )
18
+ axes[0].tick_params(axis="x", rotation=30)
19
+ regimes = list(data["forecast"])
20
+ x = np.arange(len(regimes))
21
+ for i, method in enumerate(("last", "mean5", "ewma", "local_level")):
22
+ axes[1].bar(
23
+ x + (i - 1.5) * 0.18,
24
+ [data["forecast"][s][method]["rmse"] for s in regimes],
25
+ 0.18,
26
+ label=method,
27
+ )
28
+ axes[1].set(xticks=x, xticklabels=regimes, title="Forward prediction", ylabel="RMSE")
29
+ axes[1].legend(fontsize=7)
30
+ methods = ["known_variance", "delta", "mc"]
31
+ axes[2].bar(
32
+ ["Known", "Delta", "Monte Carlo"],
33
+ [data["readout"][s] * 1e6 for s in methods],
34
+ color="#497a61",
35
+ )
36
+ axes[2].set(title="Readout correction variance", ylabel="Variance × 1,000,000")
37
+ fig.suptitle("CalibMap | Synthetic calibration studies")
38
+ fig.savefig(root / "study-results.svg", metadata={"Date": None})
@@ -0,0 +1,23 @@
1
+ {
2
+ "seed": 4701,
3
+ "replications": 10000,
4
+ "false_alarm": {
5
+ "rate": 0.053,
6
+ "monte_carlo_se": 0.0022403347964087867
7
+ },
8
+ "power": {
9
+ "rate": 1.0,
10
+ "monte_carlo_se": 0.0
11
+ },
12
+ "conditional_delay_mean": 0.9908,
13
+ "readout_coverage": {
14
+ "rate": 0.9592,
15
+ "monte_carlo_se": 0.0019782659073036657
16
+ },
17
+ "readout_rmse": 0.029715820702110856,
18
+ "readout_bias": -0.00013500000000000382,
19
+ "exact_change_only": 0.925,
20
+ "segmentation_replications": 200,
21
+ "seconds": 0.71397975,
22
+ "peak_rss_bytes": 110788608
23
+ }
@@ -0,0 +1,51 @@
1
+ """Seeded simulation under known Gaussian null and independent binomial sampling."""
2
+
3
+ import json
4
+ import resource
5
+ import sys
6
+ import time
7
+
8
+ import numpy as np
9
+
10
+ from calibmap.readout import interval
11
+ from calibmap.series import monitor, segments
12
+
13
+ rng = np.random.default_rng(4701)
14
+ start = time.perf_counter()
15
+ n = 10000
16
+ x = rng.normal(size=(n, 40))
17
+ false = np.array([monitor(path, 0, 1).any() for path in x])
18
+ x[:, 20:] += 4
19
+ alarms = np.array([monitor(path, 0, 1)[20:] for path in x])
20
+ hits = alarms.any(axis=1)
21
+ k = rng.binomial(100, 0.1, n)
22
+ bounds = np.array([interval(count, 100) for count in range(101)])
23
+ lo, hi = bounds[k].T
24
+
25
+
26
+ def rate(mask):
27
+ p = float(mask.mean())
28
+ return {"rate": p, "monte_carlo_se": float(np.sqrt(p * (1 - p) / len(mask)))}
29
+
30
+
31
+ cuts = [segments(v, 12) for v in x[:200]]
32
+ print(
33
+ json.dumps(
34
+ {
35
+ "seed": 4701,
36
+ "replications": n,
37
+ "false_alarm": rate(false),
38
+ "power": rate(hits),
39
+ "conditional_delay_mean": float(alarms[hits].argmax(axis=1).mean()),
40
+ "readout_coverage": rate((lo <= 0.1) & (0.1 <= hi)),
41
+ "readout_rmse": float(np.sqrt(np.mean((k / 100 - 0.1) ** 2))),
42
+ "readout_bias": float(np.mean(k / 100 - 0.1)),
43
+ "exact_change_only": float(np.mean([c == (20,) for c in cuts])),
44
+ "segmentation_replications": len(cuts),
45
+ "seconds": time.perf_counter() - start,
46
+ "peak_rss_bytes": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
47
+ * (1 if sys.platform == "darwin" else 1024),
48
+ },
49
+ indent=2,
50
+ )
51
+ )
@@ -0,0 +1,17 @@
1
+ """Offline integration against an IBM Runtime object shipped with the fake provider."""
2
+
3
+ from datetime import UTC, datetime
4
+ from importlib.metadata import version
5
+
6
+ from qiskit_ibm_runtime.fake_provider import FakeAthensV2
7
+
8
+ from calibmap.records import export, ibm_properties, load
9
+
10
+ props = FakeAthensV2().properties()
11
+ acquired = datetime.now(UTC)
12
+ rows = ibm_properties(props, acquired)
13
+ assert rows and all(r.published is None and r.acquired == acquired for r in rows)
14
+ assert load(export(rows)) == rows
15
+ print(
16
+ version("qiskit-ibm-runtime"), props.backend_name, len(rows), acquired.isoformat()
17
+ )
@@ -0,0 +1,154 @@
1
+ {
2
+ "seed": 1047,
3
+ "python": "3.9.6",
4
+ "numpy": "2.0.2",
5
+ "scipy": "1.13.1",
6
+ "drift": {
7
+ "null": {
8
+ "eligible": 9552,
9
+ "early_alarms": 448,
10
+ "missed": 9544,
11
+ "conditional_detection": 0.0008375209380234506,
12
+ "ci": [
13
+ 0.0003616492369260106,
14
+ 0.001649579577812956
15
+ ],
16
+ "mean_delay": 5.75,
17
+ "segmented_paths": 1,
18
+ "segmentation_total": 200,
19
+ "nearest_boundary_error": 14.0
20
+ },
21
+ "small": {
22
+ "eligible": 9509,
23
+ "early_alarms": 491,
24
+ "missed": 9484,
25
+ "conditional_detection": 0.0026290882322010725,
26
+ "ci": [
27
+ 0.0017021076731415761,
28
+ 0.0038786229003711513
29
+ ],
30
+ "mean_delay": 6.2,
31
+ "segmented_paths": 22,
32
+ "segmentation_total": 200,
33
+ "nearest_boundary_error": 4.863636363636363
34
+ },
35
+ "large": {
36
+ "eligible": 9495,
37
+ "early_alarms": 505,
38
+ "missed": 0,
39
+ "conditional_detection": 1.0,
40
+ "ci": [
41
+ 0.9996115678811909,
42
+ 1.0
43
+ ],
44
+ "mean_delay": 0.992838335966298,
45
+ "segmented_paths": 200,
46
+ "segmentation_total": 200,
47
+ "nearest_boundary_error": 0.045
48
+ },
49
+ "gradual": {
50
+ "eligible": 9498,
51
+ "early_alarms": 502,
52
+ "missed": 6506,
53
+ "conditional_detection": 0.3150136870920194,
54
+ "ci": [
55
+ 0.3056769790864412,
56
+ 0.3244639595297434
57
+ ],
58
+ "mean_delay": 16.34124331550802,
59
+ "segmented_paths": 200,
60
+ "segmentation_total": 200,
61
+ "nearest_boundary_error": 7.37
62
+ },
63
+ "variance": {
64
+ "eligible": 9505,
65
+ "early_alarms": 495,
66
+ "missed": 4345,
67
+ "conditional_detection": 0.542872172540768,
68
+ "ci": [
69
+ 0.5327929719297199,
70
+ 0.5529250861646846
71
+ ],
72
+ "mean_delay": 7.533333333333333,
73
+ "segmented_paths": 95,
74
+ "segmentation_total": 200,
75
+ "nearest_boundary_error": 8.631578947368421
76
+ }
77
+ },
78
+ "forecast": {
79
+ "stationary": {
80
+ "last": {
81
+ "mae": 1.1411824478793606,
82
+ "rmse": 1.430179091817339
83
+ },
84
+ "mean5": {
85
+ "mae": 0.8841115077087761,
86
+ "rmse": 1.1044635232490896
87
+ },
88
+ "ewma": {
89
+ "mae": 0.8795699354351304,
90
+ "rmse": 1.0997310528520279
91
+ },
92
+ "local_level": {
93
+ "mae": 0.8724231455494125,
94
+ "rmse": 1.0895795232643524
95
+ },
96
+ "future_observation_interval": {
97
+ "coverage": 0.9628571428571429,
98
+ "mean_width": 4.582944041858107
99
+ }
100
+ },
101
+ "drift": {
102
+ "last": {
103
+ "mae": 1.12953384691719,
104
+ "rmse": 1.4066492766683754
105
+ },
106
+ "mean5": {
107
+ "mae": 0.8985413264873594,
108
+ "rmse": 1.121324851594704
109
+ },
110
+ "ewma": {
111
+ "mae": 0.8902339220263105,
112
+ "rmse": 1.1087538532117733
113
+ },
114
+ "local_level": {
115
+ "mae": 0.8878700566988008,
116
+ "rmse": 1.1046105164476425
117
+ },
118
+ "future_observation_interval": {
119
+ "coverage": 0.9642857142857143,
120
+ "mean_width": 4.581500308055396
121
+ }
122
+ },
123
+ "shift": {
124
+ "last": {
125
+ "mae": 1.1019174031858803,
126
+ "rmse": 1.390149416674452
127
+ },
128
+ "mean5": {
129
+ "mae": 1.0875752717218279,
130
+ "rmse": 1.4341429309911504
131
+ },
132
+ "ewma": {
133
+ "mae": 1.0598597071408589,
134
+ "rmse": 1.3695829937025976
135
+ },
136
+ "local_level": {
137
+ "mae": 1.081136488086225,
138
+ "rmse": 1.3996346348751085
139
+ },
140
+ "future_observation_interval": {
141
+ "coverage": 0.8928571428571429,
142
+ "mean_width": 4.586878886017041
143
+ }
144
+ }
145
+ },
146
+ "readout": {
147
+ "replicates": 10000,
148
+ "known_variance": 6.683002895967921e-06,
149
+ "delta": 4.9870178438211945e-06,
150
+ "mc": 4.939617275272159e-06,
151
+ "condition": 1.5142215040001137,
152
+ "near_singular_condition": 10003999.954786446
153
+ }
154
+ }