qnmlab 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 (44) hide show
  1. qnmlab-0.1.0/LICENSE +22 -0
  2. qnmlab-0.1.0/PKG-INFO +143 -0
  3. qnmlab-0.1.0/README.md +113 -0
  4. qnmlab-0.1.0/pyproject.toml +51 -0
  5. qnmlab-0.1.0/setup.cfg +4 -0
  6. qnmlab-0.1.0/src/qnmlab/__init__.py +23 -0
  7. qnmlab-0.1.0/src/qnmlab/_core/__init__.py +0 -0
  8. qnmlab-0.1.0/src/qnmlab/_core/grouping.py +177 -0
  9. qnmlab-0.1.0/src/qnmlab/_core/hardware.py +405 -0
  10. qnmlab-0.1.0/src/qnmlab/_core/hardware_run.py +724 -0
  11. qnmlab-0.1.0/src/qnmlab/_core/hyperboloidal.py +246 -0
  12. qnmlab-0.1.0/src/qnmlab/_core/hyperboloidal_metric.py +243 -0
  13. qnmlab-0.1.0/src/qnmlab/_core/leaver.py +67 -0
  14. qnmlab-0.1.0/src/qnmlab/_core/metrics.py +98 -0
  15. qnmlab-0.1.0/src/qnmlab/_core/mitigation.py +134 -0
  16. qnmlab-0.1.0/src/qnmlab/_core/pencil.py +100 -0
  17. qnmlab-0.1.0/src/qnmlab/_core/pipeline.py +186 -0
  18. qnmlab-0.1.0/src/qnmlab/_core/quantum.py +155 -0
  19. qnmlab-0.1.0/src/qnmlab/_core/rayleigh.py +415 -0
  20. qnmlab-0.1.0/src/qnmlab/_core/recurrence.py +169 -0
  21. qnmlab-0.1.0/src/qnmlab/_core/scaling.py +69 -0
  22. qnmlab-0.1.0/src/qnmlab/_core/search2d.py +293 -0
  23. qnmlab-0.1.0/src/qnmlab/_core/ultra_rayleigh.py +292 -0
  24. qnmlab-0.1.0/src/qnmlab/benchmarks.py +61 -0
  25. qnmlab-0.1.0/src/qnmlab/cli.py +61 -0
  26. qnmlab-0.1.0/src/qnmlab/data/__init__.py +0 -0
  27. qnmlab-0.1.0/src/qnmlab/data/emerald_2026.json +389 -0
  28. qnmlab-0.1.0/src/qnmlab/hardware.py +74 -0
  29. qnmlab-0.1.0/src/qnmlab/models.py +75 -0
  30. qnmlab-0.1.0/src/qnmlab/operators.py +87 -0
  31. qnmlab-0.1.0/src/qnmlab/readout.py +139 -0
  32. qnmlab-0.1.0/src/qnmlab/reference.py +32 -0
  33. qnmlab-0.1.0/src/qnmlab/search.py +93 -0
  34. qnmlab-0.1.0/src/qnmlab.egg-info/PKG-INFO +143 -0
  35. qnmlab-0.1.0/src/qnmlab.egg-info/SOURCES.txt +42 -0
  36. qnmlab-0.1.0/src/qnmlab.egg-info/dependency_links.txt +1 -0
  37. qnmlab-0.1.0/src/qnmlab.egg-info/entry_points.txt +2 -0
  38. qnmlab-0.1.0/src/qnmlab.egg-info/requires.txt +13 -0
  39. qnmlab-0.1.0/src/qnmlab.egg-info/top_level.txt +1 -0
  40. qnmlab-0.1.0/tests/test_api.py +155 -0
  41. qnmlab-0.1.0/tests/test_core_extensions.py +91 -0
  42. qnmlab-0.1.0/tests/test_core_hardware.py +239 -0
  43. qnmlab-0.1.0/tests/test_core_hyperboloidal.py +133 -0
  44. qnmlab-0.1.0/tests/test_core_readout.py +145 -0
qnmlab-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Abir Chekroun, Hamed Al-Yoorby, Mouadh Abderrahmane Assal,
4
+ Zakaria Lourghi, and Achraf Boussahi
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
qnmlab-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: qnmlab
3
+ Version: 0.1.0
4
+ Summary: Black-hole quasinormal modes with quantum algorithms: phase readout, seedless search, hardware analysis
5
+ Author: Hamed Al-Yoorby, Mouadh Abderrahmane Assal, Zakaria Lourghi, Achraf Boussahi
6
+ Author-email: Abir Chekroun <a.chekroun@esi-sba.dz>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://github.com/abir-tech/qnmlab
9
+ Project-URL: Issues, https://github.com/abir-tech/qnmlab/issues
10
+ Keywords: quasinormal modes,black holes,quantum computing,variational quantum eigensolver,non-Hermitian,gravitational waves
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Topic :: Scientific/Engineering :: Physics
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: numpy>=1.24
20
+ Requires-Dist: scipy>=1.10
21
+ Requires-Dist: sympy>=1.12
22
+ Provides-Extra: hardware
23
+ Requires-Dist: qiskit>=1.0; extra == "hardware"
24
+ Provides-Extra: plot
25
+ Requires-Dist: matplotlib>=3.7; extra == "plot"
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=7; extra == "dev"
28
+ Requires-Dist: matplotlib>=3.7; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # qnmlab
32
+
33
+ **Black-hole quasinormal modes with quantum algorithms.**
34
+
35
+ `qnmlab` computes the ringing frequencies of black holes with variational quantum
36
+ algorithms. You choose a black hole, a size in qubits, a representation, and a simulated
37
+ or real quantum backend, and compare the result with trusted reference values.
38
+
39
+ The two ideas behind it:
40
+
41
+ - **Phase readout.** On hyperboloidal slices the modes are eigenvalues of one linear
42
+ operator, so a mode's frequency is two measured averages,
43
+ `Re ω = −⟨H₂⟩`, `Im ω = ⟨H₁⟩`. That costs about 130 times fewer shots than detecting
44
+ where a matrix becomes singular.
45
+ - **Seedless search.** A thresholded scan of the complex frequency plane produces a
46
+ shortlist of candidates, and the phase readout verifies each one. No starting guess is
47
+ needed.
48
+
49
+ Classical methods compute these modes faster; `qnmlab` is for studying, benchmarking and
50
+ running the quantum formulation, not for replacing them.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ pip install qnmlab # core: numpy, scipy, sympy
56
+ pip install "qnmlab[hardware]" # + Qiskit, to export circuits for real devices
57
+ ```
58
+
59
+ Latest development version:
60
+
61
+ ```bash
62
+ pip install git+https://github.com/abir-tech/qnmlab.git
63
+ ```
64
+
65
+ ## Quick start
66
+
67
+ ```python
68
+ import qnmlab as ql
69
+
70
+ bh = ql.KazakovSolodukhin(a=0.5) # or ql.Schwarzschild(), ql.ReissnerNordstrom(Q), ql.Hayward(l)
71
+ ql.reference_modes(bh, ell=2, n_modes=2) # classical ground truth
72
+
73
+ # read the fundamental on a simulated noisy 3-qubit device
74
+ r = ql.measure_mode(bh, qubits=3, noise=ql.NoiseModel.emerald_random(), shots=800)
75
+ print(r.omega, r.meta["error_vs_reference"])
76
+
77
+ # find modes with no starting guess (Schwarzschild, 4 qubits)
78
+ res = ql.find_modes(ql.Schwarzschild(), qubits=4)
79
+ print(res.modes) # the fundamental and the first overtone
80
+ ```
81
+
82
+ From the command line:
83
+
84
+ ```bash
85
+ qnmlab modes --model kazakov-solodukhin --parameter 0.5
86
+ qnmlab readout --model schwarzschild --qubits 3 --noise emerald-random --shots 800
87
+ qnmlab search --model schwarzschild --qubits 4
88
+ ```
89
+
90
+ ## What you can choose
91
+
92
+ | choice | options |
93
+ |---|---|
94
+ | black hole | `Schwarzschild()`, `KazakovSolodukhin(a)` — validated against published frequencies; `ReissnerNordstrom(Q)`, `Hayward(l)` — experimental (cross-checked against an independent method, not against published values) |
95
+ | size | qubits; operator dimension `2**qubits` |
96
+ | readout representation | `"hyperboloidal"` (any model), `"ultraspherical"` (banded generalised pencil, Schwarzschild) |
97
+ | search representation | `"leaver"` (tridiagonal, Schwarzschild), `"frobenius"` (any model) |
98
+ | search solver | `"exact"` (fast) or `"variational"` (a variational solver at every grid point) |
99
+ | noise | `NoiseModel.ideal()`, `.emerald_random()`, `.emerald_coherent()`, or your own `NoiseModel(p2, eps, readout)` |
100
+
101
+ ## Real hardware
102
+
103
+ ```python
104
+ op = ql.readout_operator(ql.Schwarzschild(), qubits=3)
105
+ state = ql.prepare_state(op, lead=0.48 - 0.097j, layers=2)
106
+ job = ql.hardware.build_job(op, state) # 11 circuits
107
+ ok = ql.hardware.verify(job) # Qiskit export matches the simulation
108
+ circuits = [ql.hardware.to_qiskit(c, 3) for c in job["circuits"]]
109
+ # ... run them with your provider, collect raw counts by circuit name ...
110
+ result = ql.hardware.analyse_counts(job, raw_counts) # measures bit order, mitigates readout
111
+ ```
112
+
113
+ `analyse_counts` measures the provider's bit order from two calibration circuits and stops
114
+ if a qubit is stuck — both happened on real devices while this package was developed.
115
+
116
+ The raw counts of the 2026 IQM Emerald run ship with the package:
117
+
118
+ ```python
119
+ ql.benchmarks.reanalyse_emerald_2026() # (0.43919 - 0.10430i), exact 0.48186 - 0.09674i
120
+ ```
121
+
122
+ ## Scope and honesty
123
+
124
+ - The end-to-end search ran in simulation; on hardware only the readout was run, from a
125
+ classically prepared state.
126
+ - The search costs about 10^13 measurement shots at 4 qubits.
127
+ - The hardware error (~0.04) is dominated by gate noise; more qubits help only once it falls.
128
+
129
+ ## Citing
130
+
131
+ If you use `qnmlab`, please cite the accompanying paper (see `CITATION.cff`):
132
+ A. Chekroun, H. Al-Yoorby, M. A. Assal, Z. Lourghi, A. Boussahi,
133
+ *Phase Readout and Seedless Search for Black-Hole Quasinormal Modes on Quantum Processors* (2026).
134
+
135
+ ## Development
136
+
137
+ ```bash
138
+ pip install -e ".[dev]"
139
+ pytest -m "not slow" # ~5 minutes
140
+ pytest # includes the ~40-minute end-to-end search
141
+ ```
142
+
143
+ MIT licence.
qnmlab-0.1.0/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # qnmlab
2
+
3
+ **Black-hole quasinormal modes with quantum algorithms.**
4
+
5
+ `qnmlab` computes the ringing frequencies of black holes with variational quantum
6
+ algorithms. You choose a black hole, a size in qubits, a representation, and a simulated
7
+ or real quantum backend, and compare the result with trusted reference values.
8
+
9
+ The two ideas behind it:
10
+
11
+ - **Phase readout.** On hyperboloidal slices the modes are eigenvalues of one linear
12
+ operator, so a mode's frequency is two measured averages,
13
+ `Re ω = −⟨H₂⟩`, `Im ω = ⟨H₁⟩`. That costs about 130 times fewer shots than detecting
14
+ where a matrix becomes singular.
15
+ - **Seedless search.** A thresholded scan of the complex frequency plane produces a
16
+ shortlist of candidates, and the phase readout verifies each one. No starting guess is
17
+ needed.
18
+
19
+ Classical methods compute these modes faster; `qnmlab` is for studying, benchmarking and
20
+ running the quantum formulation, not for replacing them.
21
+
22
+ ## Install
23
+
24
+ ```bash
25
+ pip install qnmlab # core: numpy, scipy, sympy
26
+ pip install "qnmlab[hardware]" # + Qiskit, to export circuits for real devices
27
+ ```
28
+
29
+ Latest development version:
30
+
31
+ ```bash
32
+ pip install git+https://github.com/abir-tech/qnmlab.git
33
+ ```
34
+
35
+ ## Quick start
36
+
37
+ ```python
38
+ import qnmlab as ql
39
+
40
+ bh = ql.KazakovSolodukhin(a=0.5) # or ql.Schwarzschild(), ql.ReissnerNordstrom(Q), ql.Hayward(l)
41
+ ql.reference_modes(bh, ell=2, n_modes=2) # classical ground truth
42
+
43
+ # read the fundamental on a simulated noisy 3-qubit device
44
+ r = ql.measure_mode(bh, qubits=3, noise=ql.NoiseModel.emerald_random(), shots=800)
45
+ print(r.omega, r.meta["error_vs_reference"])
46
+
47
+ # find modes with no starting guess (Schwarzschild, 4 qubits)
48
+ res = ql.find_modes(ql.Schwarzschild(), qubits=4)
49
+ print(res.modes) # the fundamental and the first overtone
50
+ ```
51
+
52
+ From the command line:
53
+
54
+ ```bash
55
+ qnmlab modes --model kazakov-solodukhin --parameter 0.5
56
+ qnmlab readout --model schwarzschild --qubits 3 --noise emerald-random --shots 800
57
+ qnmlab search --model schwarzschild --qubits 4
58
+ ```
59
+
60
+ ## What you can choose
61
+
62
+ | choice | options |
63
+ |---|---|
64
+ | black hole | `Schwarzschild()`, `KazakovSolodukhin(a)` — validated against published frequencies; `ReissnerNordstrom(Q)`, `Hayward(l)` — experimental (cross-checked against an independent method, not against published values) |
65
+ | size | qubits; operator dimension `2**qubits` |
66
+ | readout representation | `"hyperboloidal"` (any model), `"ultraspherical"` (banded generalised pencil, Schwarzschild) |
67
+ | search representation | `"leaver"` (tridiagonal, Schwarzschild), `"frobenius"` (any model) |
68
+ | search solver | `"exact"` (fast) or `"variational"` (a variational solver at every grid point) |
69
+ | noise | `NoiseModel.ideal()`, `.emerald_random()`, `.emerald_coherent()`, or your own `NoiseModel(p2, eps, readout)` |
70
+
71
+ ## Real hardware
72
+
73
+ ```python
74
+ op = ql.readout_operator(ql.Schwarzschild(), qubits=3)
75
+ state = ql.prepare_state(op, lead=0.48 - 0.097j, layers=2)
76
+ job = ql.hardware.build_job(op, state) # 11 circuits
77
+ ok = ql.hardware.verify(job) # Qiskit export matches the simulation
78
+ circuits = [ql.hardware.to_qiskit(c, 3) for c in job["circuits"]]
79
+ # ... run them with your provider, collect raw counts by circuit name ...
80
+ result = ql.hardware.analyse_counts(job, raw_counts) # measures bit order, mitigates readout
81
+ ```
82
+
83
+ `analyse_counts` measures the provider's bit order from two calibration circuits and stops
84
+ if a qubit is stuck — both happened on real devices while this package was developed.
85
+
86
+ The raw counts of the 2026 IQM Emerald run ship with the package:
87
+
88
+ ```python
89
+ ql.benchmarks.reanalyse_emerald_2026() # (0.43919 - 0.10430i), exact 0.48186 - 0.09674i
90
+ ```
91
+
92
+ ## Scope and honesty
93
+
94
+ - The end-to-end search ran in simulation; on hardware only the readout was run, from a
95
+ classically prepared state.
96
+ - The search costs about 10^13 measurement shots at 4 qubits.
97
+ - The hardware error (~0.04) is dominated by gate noise; more qubits help only once it falls.
98
+
99
+ ## Citing
100
+
101
+ If you use `qnmlab`, please cite the accompanying paper (see `CITATION.cff`):
102
+ A. Chekroun, H. Al-Yoorby, M. A. Assal, Z. Lourghi, A. Boussahi,
103
+ *Phase Readout and Seedless Search for Black-Hole Quasinormal Modes on Quantum Processors* (2026).
104
+
105
+ ## Development
106
+
107
+ ```bash
108
+ pip install -e ".[dev]"
109
+ pytest -m "not slow" # ~5 minutes
110
+ pytest # includes the ~40-minute end-to-end search
111
+ ```
112
+
113
+ MIT licence.
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "qnmlab"
7
+ version = "0.1.0"
8
+ description = "Black-hole quasinormal modes with quantum algorithms: phase readout, seedless search, hardware analysis"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [
13
+ { name = "Abir Chekroun", email = "a.chekroun@esi-sba.dz" },
14
+ { name = "Hamed Al-Yoorby" },
15
+ { name = "Mouadh Abderrahmane Assal" },
16
+ { name = "Zakaria Lourghi" },
17
+ { name = "Achraf Boussahi" },
18
+ ]
19
+ requires-python = ">=3.10"
20
+ dependencies = ["numpy>=1.24", "scipy>=1.10", "sympy>=1.12"]
21
+ keywords = ["quasinormal modes", "black holes", "quantum computing", "variational quantum eigensolver",
22
+ "non-Hermitian", "gravitational waves"]
23
+ classifiers = [
24
+ "Programming Language :: Python :: 3",
25
+ "Operating System :: OS Independent",
26
+ "Intended Audience :: Science/Research",
27
+ "Topic :: Scientific/Engineering :: Physics",
28
+ "Development Status :: 3 - Alpha",
29
+ ]
30
+
31
+ [project.optional-dependencies]
32
+ hardware = ["qiskit>=1.0"]
33
+ plot = ["matplotlib>=3.7"]
34
+ dev = ["pytest>=7", "matplotlib>=3.7"]
35
+
36
+ [project.scripts]
37
+ qnmlab = "qnmlab.cli:main"
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/abir-tech/qnmlab"
41
+ Issues = "https://github.com/abir-tech/qnmlab/issues"
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
45
+
46
+ [tool.setuptools.package-data]
47
+ "qnmlab.data" = ["*.json"]
48
+
49
+ [tool.pytest.ini_options]
50
+ testpaths = ["tests"]
51
+ markers = ["slow: takes more than a minute (deselect with -m 'not slow')"]
qnmlab-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,23 @@
1
+ """
2
+ qnmlab -- black-hole quasinormal modes with quantum algorithms.
3
+
4
+ import qnmlab as ql
5
+ bh = ql.KazakovSolodukhin(a=0.5)
6
+ ql.reference_modes(bh) # classical ground truth
7
+ op = ql.readout_operator(bh, qubits=3) # modes are its eigenvalues
8
+ r = ql.measure_mode(bh, qubits=3, noise=ql.NoiseModel.emerald_random(), shots=800)
9
+ res = ql.find_modes(ql.Schwarzschild(), qubits=4) # search with no starting guess
10
+ """
11
+ from . import benchmarks, hardware
12
+ from .models import BlackHole, Hayward, KazakovSolodukhin, ReissnerNordstrom, Schwarzschild, available_models
13
+ from .operators import readout_operator, search_pencil
14
+ from .readout import NoiseModel, measure_mode, phase_readout, prepare_state
15
+ from .reference import reference_modes
16
+ from .search import find_modes
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ __all__ = ["BlackHole", "Schwarzschild", "KazakovSolodukhin", "ReissnerNordstrom", "Hayward",
21
+ "available_models", "reference_modes", "readout_operator", "search_pencil", "NoiseModel",
22
+ "prepare_state", "phase_readout", "measure_mode", "find_modes", "benchmarks", "hardware",
23
+ "__version__"]
File without changes
@@ -0,0 +1,177 @@
1
+ """
2
+ grouping.py -- fewer measurement circuits via GENERAL-commuting (GC) grouping.
3
+
4
+ The hardware run used qubit-wise-commuting (QWC) groups: 28 circuits for the 63
5
+ Pauli strings of H1 and H2 at 3 qubits. QWC cannot do better than 27 here,
6
+ because every one of the 27 weight-3 strings needs its own local basis.
7
+
8
+ General commutation is weaker than qubit-wise commutation, so groups can be much
9
+ larger. For n qubits all 4^n - 1 non-identity Paulis partition into 2^n + 1
10
+ commuting families of 2^n - 1 (mutually unbiased bases): 9 circuits instead of
11
+ 28 at 3 qubits. The price is a short Clifford circuit that rotates each family
12
+ onto Z-strings, which adds two-qubit gates (found by search, minimising CX count).
13
+
14
+ Measured trade-off: see the accompanying paper (noise and mitigation section).
15
+ """
16
+ import heapq
17
+ import itertools
18
+ import math
19
+
20
+ import numpy as np
21
+
22
+ from .hardware_run import _cx_matrix, _embed, _mat1
23
+
24
+ PAULI = {"I": np.eye(2), "X": np.array([[0, 1], [1, 0]]),
25
+ "Y": np.array([[0, -1j], [1j, 0]]), "Z": np.diag([1.0, -1.0])}
26
+
27
+
28
+ def pmat(label):
29
+ M = np.array([[1.0 + 0j]])
30
+ for ch in label:
31
+ M = np.kron(M, PAULI[ch])
32
+ return M
33
+
34
+
35
+ def symp(label):
36
+ """(x bits, z bits) of a Pauli label."""
37
+ x = tuple(int(c in "XY") for c in label)
38
+ z = tuple(int(c in "ZY") for c in label)
39
+ return x, z
40
+
41
+
42
+ def commute(a, b):
43
+ xa, za = symp(a)
44
+ xb, zb = symp(b)
45
+ return (sum(i * j for i, j in zip(xa, zb)) + sum(i * j for i, j in zip(za, xb))) % 2 == 0
46
+
47
+
48
+ def gc_partition(labels):
49
+ """
50
+ Partition Pauli labels into mutually commuting families with as few families
51
+ as possible. Exact-cover search over maximal commuting sets (fine for n <= 3;
52
+ falls back to greedy colouring above that).
53
+ """
54
+ labels = list(labels)
55
+ n = len(labels[0])
56
+ if n <= 3:
57
+ alls = ["".join(t) for t in itertools.product("IXYZ", repeat=n)][1:]
58
+ fams = set()
59
+ for gens in itertools.combinations(alls, n):
60
+ if all(commute(a, b) for a, b in itertools.combinations(gens, 2)):
61
+ grp = {_mul_label(c) for c in _span(gens)} - {"I" * n, None}
62
+ if len(grp) == 2 ** n - 1:
63
+ fams.add(frozenset(grp))
64
+ fams = list(fams)
65
+ target = set(labels)
66
+ best = [None]
67
+
68
+ def search(rem, chosen):
69
+ if best[0] is not None and len(chosen) >= len(best[0]):
70
+ return
71
+ if not rem:
72
+ best[0] = list(chosen)
73
+ return
74
+ p = min(rem)
75
+ for f in fams:
76
+ if p in f and not (f & set().union(*chosen) if chosen else False):
77
+ search(rem - f, chosen + [f])
78
+ search(target, [])
79
+ return [sorted(set(f) & target) for f in best[0]]
80
+ groups = []
81
+ for lab in sorted(labels, key=lambda s: -sum(c != "I" for c in s)):
82
+ for g in groups:
83
+ if all(commute(lab, o) for o in g):
84
+ g.append(lab)
85
+ break
86
+ else:
87
+ groups.append([lab])
88
+ return groups
89
+
90
+
91
+ def _span(gens):
92
+ out = []
93
+ for bits in itertools.product((0, 1), repeat=len(gens)):
94
+ out.append(tuple(g for g, b in zip(gens, bits) if b))
95
+ return out
96
+
97
+
98
+ def _mul_label(factors):
99
+ n = len(factors[0]) if factors else 0
100
+ if not factors:
101
+ return None
102
+ x = [0] * n
103
+ z = [0] * n
104
+ for f in factors:
105
+ fx, fz = symp(f)
106
+ x = [a ^ b for a, b in zip(x, fx)]
107
+ z = [a ^ b for a, b in zip(z, fz)]
108
+ return "".join("I" if (a, b) == (0, 0) else "X" if (a, b) == (1, 0)
109
+ else "Z" if (a, b) == (0, 1) else "Y" for a, b in zip(x, z))
110
+
111
+
112
+ # ---------------------------------------------------------------- diagonalising Cliffords
113
+ def _apply_sym(gate, vecs, n):
114
+ out = []
115
+ for x, z in vecs:
116
+ x, z = list(x), list(z)
117
+ if gate[0] == "h":
118
+ q = gate[1]; x[q], z[q] = z[q], x[q]
119
+ elif gate[0] == "s":
120
+ q = gate[1]; z[q] ^= x[q]
121
+ elif gate[0] == "cx":
122
+ c, t = gate[1], gate[2]; x[t] ^= x[c]; z[c] ^= z[t]
123
+ out.append((tuple(x), tuple(z)))
124
+ return tuple(out)
125
+
126
+
127
+ def diagonalising_circuit(family, n):
128
+ """Cheapest {H, S, CX} circuit (CX cost 1, single-qubit 0.01) mapping every
129
+ member of a commuting family onto a Z-string."""
130
+ gens = [symp(l) for l in family]
131
+ moves = [("h", q) for q in range(n)] + [("s", q) for q in range(n)] + \
132
+ [("cx", c, t) for c in range(n) for t in range(n) if c != t]
133
+ start = tuple(gens)
134
+ pq = [(0.0, 0, start, ())]
135
+ seen = {start: 0.0}
136
+ k = 0
137
+ while pq:
138
+ cost, _, st, path = heapq.heappop(pq)
139
+ if all(not any(x) for x, _ in st):
140
+ return list(path)
141
+ if cost > 6:
142
+ break
143
+ for m in moves:
144
+ nst = _apply_sym(m, st, n)
145
+ nc = cost + (1.0 if m[0] == "cx" else 0.01)
146
+ if nst not in seen or nc < seen[nst] - 1e-12:
147
+ seen[nst] = nc
148
+ k += 1
149
+ heapq.heappush(pq, (nc, k, nst, path + (m,)))
150
+ raise RuntimeError("no diagonalising circuit found")
151
+
152
+
153
+ def to_sim_gates(path):
154
+ """Map {h, s, cx} to the simulator's gate set (S = RZ(pi/2) up to global phase)."""
155
+ return [("h", g[1]) if g[0] == "h" else ("rz", g[1], math.pi / 2) if g[0] == "s"
156
+ else ("cx", g[1], g[2]) for g in path]
157
+
158
+
159
+ def unitary(gates, n):
160
+ U = np.eye(2 ** n, dtype=complex)
161
+ for g in gates:
162
+ if g[0] == "cx":
163
+ G = _cx_matrix(g[1], g[2], n)
164
+ else:
165
+ G = _embed(_mat1(g[0], g[2] if len(g) > 2 else None), g[1], n)
166
+ U = G @ U
167
+ return U
168
+
169
+
170
+ def z_image(label, U, n):
171
+ """U P U^dag = sign * Z-string. Returns (sign, zlabel)."""
172
+ M = U @ pmat(label) @ U.conj().T
173
+ for zl in ("".join(t) for t in itertools.product("IZ", repeat=n)):
174
+ c = np.trace(pmat(zl) @ M) / 2 ** n
175
+ if abs(abs(c) - 1) < 1e-9:
176
+ return (1.0 if np.real(c) > 0 else -1.0), zl
177
+ raise RuntimeError(f"{label} is not diagonalised")