shadowsim 1.0.0__py3-none-any.whl

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 (92) hide show
  1. shadowsim/__init__.py +13 -0
  2. shadowsim/_optional.py +54 -0
  3. shadowsim/backends/__init__.py +69 -0
  4. shadowsim/backends/_arguments.py +123 -0
  5. shadowsim/backends/aer.py +317 -0
  6. shadowsim/backends/catalog.py +151 -0
  7. shadowsim/backends/circuit.py +314 -0
  8. shadowsim/backends/cirq.py +401 -0
  9. shadowsim/backends/numpy.py +118 -0
  10. shadowsim/backends/numpy_statevector.py +212 -0
  11. shadowsim/backends/pauli_propagation.py +347 -0
  12. shadowsim/backends/program.py +305 -0
  13. shadowsim/backends/qulacs.py +255 -0
  14. shadowsim/benchmarking/__init__.py +3 -0
  15. shadowsim/benchmarking/benchmark.py +293 -0
  16. shadowsim/cli/__init__.py +1 -0
  17. shadowsim/cli/catalog.py +666 -0
  18. shadowsim/cli/commands.py +463 -0
  19. shadowsim/cli/document.py +360 -0
  20. shadowsim/cli/main.py +33 -0
  21. shadowsim/cli/new_backend.py +620 -0
  22. shadowsim/cli/new_simulator.py +671 -0
  23. shadowsim/cli/run.py +1639 -0
  24. shadowsim/cli/serve.py +1311 -0
  25. shadowsim/cli/site/builder.js +4008 -0
  26. shadowsim/cli/site/chart.js +863 -0
  27. shadowsim/cli/site/checks.js +1496 -0
  28. shadowsim/cli/site/dom.js +16 -0
  29. shadowsim/cli/site/index.html +26 -0
  30. shadowsim/cli/site/styles.css +999 -0
  31. shadowsim/core/__init__.py +13 -0
  32. shadowsim/core/combined_hamiltonian_matrix.py +80 -0
  33. shadowsim/core/density_operator.py +92 -0
  34. shadowsim/core/hamiltonian.py +112 -0
  35. shadowsim/core/hamiltonian_set.py +54 -0
  36. shadowsim/core/local_hamiltonian.py +61 -0
  37. shadowsim/core/local_operator.py +153 -0
  38. shadowsim/core/operator.py +199 -0
  39. shadowsim/core/operator_set.py +54 -0
  40. shadowsim/core/pauli.py +93 -0
  41. shadowsim/core/pauli_string.py +109 -0
  42. shadowsim/core/pauli_sum.py +235 -0
  43. shadowsim/core/state.py +96 -0
  44. shadowsim/encoding/__init__.py +21 -0
  45. shadowsim/encoding/amplitude.py +76 -0
  46. shadowsim/encoding/angle.py +66 -0
  47. shadowsim/encoding/computational_basis.py +95 -0
  48. shadowsim/encoding/gray.py +67 -0
  49. shadowsim/encoding/load.py +100 -0
  50. shadowsim/encoding/state_encoder.py +27 -0
  51. shadowsim/interop/__init__.py +36 -0
  52. shadowsim/interop/qutip.py +183 -0
  53. shadowsim/models/__init__.py +20 -0
  54. shadowsim/models/catalog.py +251 -0
  55. shadowsim/models/ising.py +260 -0
  56. shadowsim/models/jaynes_cummings.py +108 -0
  57. shadowsim/models/jaynes_cummings_hubbard.py +114 -0
  58. shadowsim/models/tavis_cummings.py +300 -0
  59. shadowsim/models/tavis_cummings_hubbard.py +213 -0
  60. shadowsim/py.typed +0 -0
  61. shadowsim/shadow/__init__.py +18 -0
  62. shadowsim/shadow/change_of_basis.py +149 -0
  63. shadowsim/shadow/invariance.py +108 -0
  64. shadowsim/shadow/run_shadow_simulation.py +536 -0
  65. shadowsim/shadow/shadow_hamiltonian.py +353 -0
  66. shadowsim/shadow/shadow_state.py +73 -0
  67. shadowsim/simulators/__init__.py +59 -0
  68. shadowsim/simulators/_time_points.py +59 -0
  69. shadowsim/simulators/catalog.py +284 -0
  70. shadowsim/simulators/hybrid_wml_simulator.py +472 -0
  71. shadowsim/simulators/job.py +133 -0
  72. shadowsim/simulators/product_formula_simulator.py +372 -0
  73. shadowsim/simulators/qutip_simulator.py +102 -0
  74. shadowsim/simulators/reducers.py +265 -0
  75. shadowsim/simulators/result.py +367 -0
  76. shadowsim/simulators/simulator.py +266 -0
  77. shadowsim/simulators/splitjmatrix_simulator.py +257 -0
  78. shadowsim/simulators/trotterization_simulator.py +281 -0
  79. shadowsim/utils/__init__.py +10 -0
  80. shadowsim/utils/constants.py +10 -0
  81. shadowsim/utils/definiteness.py +176 -0
  82. shadowsim/utils/flip_dict.py +29 -0
  83. shadowsim/utils/hermitian.py +39 -0
  84. shadowsim/utils/next_power_of_two.py +34 -0
  85. shadowsim/utils/tensor.py +39 -0
  86. shadowsim/utils/unitary.py +38 -0
  87. shadowsim-1.0.0.dist-info/METADATA +710 -0
  88. shadowsim-1.0.0.dist-info/RECORD +92 -0
  89. shadowsim-1.0.0.dist-info/WHEEL +5 -0
  90. shadowsim-1.0.0.dist-info/entry_points.txt +4 -0
  91. shadowsim-1.0.0.dist-info/licenses/LICENSE +21 -0
  92. shadowsim-1.0.0.dist-info/top_level.txt +1 -0
shadowsim/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """ShadowSim package namespace."""
2
+
3
+ __all__ = [
4
+ "backends",
5
+ "benchmarking",
6
+ "core",
7
+ "encoding",
8
+ "interop",
9
+ "models",
10
+ "shadow",
11
+ "simulators",
12
+ "utils",
13
+ ]
shadowsim/_optional.py ADDED
@@ -0,0 +1,54 @@
1
+ """Import helpers for optional extras."""
2
+
3
+ import importlib
4
+ from types import ModuleType
5
+
6
+ # Top-level import names provided by each published extra.
7
+ _EXTRA_MODULES: dict[str, frozenset[str]] = {
8
+ "qutip": frozenset({"qutip"}),
9
+ "qiskit": frozenset({"qiskit", "qiskit_aer", "scipy"}),
10
+ "viz": frozenset({"matplotlib"}),
11
+ "pauli_propagation": frozenset({"juliacall"}),
12
+ "qulacs": frozenset({"qulacs"}),
13
+ "cirq": frozenset({"cirq"}),
14
+ "circuits": frozenset({"scipy"}),
15
+ }
16
+
17
+
18
+ def import_optional(module: str, *, extra: str) -> ModuleType:
19
+ """Import ``module``, or raise if a library from ``extra`` is not installed.
20
+
21
+ Args:
22
+ module: Absolute module name to import.
23
+ extra: Extra that provides the optional library, as in ``shadowsim[extra]``.
24
+
25
+ Returns:
26
+ The imported module.
27
+
28
+ Raises:
29
+ ImportError: If importing ``module`` fails because a library from
30
+ ``extra`` is missing. The message names the extra and
31
+ ``pip install 'shadowsim[<extra>]'``. Other import failures are
32
+ re-raised unchanged.
33
+ """
34
+ try:
35
+ return importlib.import_module(module)
36
+ except ImportError as exc:
37
+ missing = _top_level_name(exc.name)
38
+ if missing is not None and missing in _modules_for_extra(extra):
39
+ raise ImportError(
40
+ f"{module} requires the {extra} extra. Install it with: pip install 'shadowsim[{extra}]'"
41
+ ) from exc
42
+ raise
43
+
44
+
45
+ def _top_level_name(name: str | None) -> str | None:
46
+ """Return the top-level package in an import name."""
47
+ if not name:
48
+ return None
49
+ return name.partition(".")[0]
50
+
51
+
52
+ def _modules_for_extra(extra: str) -> frozenset[str]:
53
+ """Return the top-level modules that ``extra`` is expected to provide."""
54
+ return _EXTRA_MODULES.get(extra, frozenset({extra}))
@@ -0,0 +1,69 @@
1
+ """Circuit execution backends for shot-based simulators."""
2
+
3
+ import importlib
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from shadowsim._optional import import_optional
7
+
8
+ if TYPE_CHECKING:
9
+ from shadowsim.backends.aer import AerCircuitBackend as AerCircuitBackend
10
+ from shadowsim.backends.circuit import CircuitBackend as CircuitBackend
11
+ from shadowsim.backends.circuit import from_qiskit as from_qiskit
12
+ from shadowsim.backends.circuit import to_qiskit as to_qiskit
13
+ from shadowsim.backends.cirq import CirqCircuitBackend as CirqCircuitBackend
14
+ from shadowsim.backends.numpy import NumpyCircuitBackend as NumpyCircuitBackend
15
+ from shadowsim.backends.pauli_propagation import PauliPropagationBackend as PauliPropagationBackend
16
+ from shadowsim.backends.qulacs import QulacsCircuitBackend as QulacsCircuitBackend
17
+
18
+ # ``CircuitBackend`` does not import Qiskit. ``from_qiskit`` and ``to_qiskit`` share
19
+ # that module, so the loader checks for Qiskit before returning those two names.
20
+ _QISKIT_TRANSLATION = frozenset({"from_qiskit", "to_qiskit"})
21
+ _EXPORTS: dict[str, tuple[str, str | None]] = {
22
+ "AerCircuitBackend": ("shadowsim.backends.aer", "qiskit"),
23
+ "NumpyCircuitBackend": ("shadowsim.backends.numpy", None),
24
+ "QulacsCircuitBackend": ("shadowsim.backends.qulacs", "qulacs"),
25
+ "CirqCircuitBackend": ("shadowsim.backends.cirq", "cirq"),
26
+ "CircuitBackend": ("shadowsim.backends.circuit", None),
27
+ "PauliPropagationBackend": ("shadowsim.backends.pauli_propagation", "pauli_propagation"),
28
+ "from_qiskit": ("shadowsim.backends.circuit", "qiskit"),
29
+ "to_qiskit": ("shadowsim.backends.circuit", "qiskit"),
30
+ }
31
+
32
+ # Imported after ``_EXPORTS`` so the catalog can read that map while this module loads.
33
+ from shadowsim.backends.catalog import ListedBackend as ListedBackend
34
+ from shadowsim.backends.catalog import listed_backends as listed_backends
35
+
36
+ __all__ = [
37
+ "AerCircuitBackend",
38
+ "CircuitBackend",
39
+ "CirqCircuitBackend",
40
+ "ListedBackend",
41
+ "NumpyCircuitBackend",
42
+ "PauliPropagationBackend",
43
+ "QulacsCircuitBackend",
44
+ "from_qiskit",
45
+ "listed_backends",
46
+ "to_qiskit",
47
+ ]
48
+
49
+
50
+ def __getattr__(name: str) -> Any:
51
+ """Import a circuit backend the first time it is accessed."""
52
+ try:
53
+ module_name, extra = _EXPORTS[name]
54
+ except KeyError:
55
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None
56
+ if name in _QISKIT_TRANSLATION:
57
+ import_optional("qiskit", extra="qiskit")
58
+ if extra is None:
59
+ module = importlib.import_module(module_name)
60
+ else:
61
+ module = import_optional(module_name, extra=extra)
62
+ value = getattr(module, name)
63
+ globals()[name] = value
64
+ return value
65
+
66
+
67
+ def __dir__() -> list[str]:
68
+ """Return module attributes, including backends that have not been imported yet."""
69
+ return sorted(set(globals()) | set(_EXPORTS))
@@ -0,0 +1,123 @@
1
+ """Shared argument checks and circuit-metric rejections for circuit backends."""
2
+
3
+ from collections.abc import Sequence
4
+ from typing import Literal, NoReturn
5
+
6
+
7
+ def _require_shots(shots: object) -> int:
8
+ """Return ``shots`` when it is a positive integer.
9
+
10
+ Raises:
11
+ ValueError: ``shots`` is a ``bool``, not an ``int``, or not positive.
12
+ """
13
+ if isinstance(shots, bool) or not isinstance(shots, int) or shots <= 0:
14
+ raise ValueError("shots must be a positive integer")
15
+ return shots
16
+
17
+
18
+ def _require_seed(seed: object) -> int | None:
19
+ """Return ``seed`` when it is an ``int`` or ``None``.
20
+
21
+ Raises:
22
+ TypeError: ``seed`` is not an ``int`` or ``None``.
23
+ """
24
+ if seed is None:
25
+ return None
26
+ if isinstance(seed, bool) or not isinstance(seed, int):
27
+ raise TypeError("seed must be an int or None")
28
+ return seed
29
+
30
+
31
+ def _qubit_indexes(
32
+ qubits: Sequence[int],
33
+ num_qubits: int,
34
+ *,
35
+ register: Literal["circuit", "program"],
36
+ ) -> tuple[int, ...]:
37
+ """Return ``qubits`` when every entry is an index in a register of ``num_qubits``.
38
+
39
+ Args:
40
+ qubits: Indexes to check. A ``bool`` is rejected.
41
+ num_qubits: Size of the register.
42
+ register: Noun used in the error, ``circuit`` or ``program``.
43
+
44
+ Raises:
45
+ ValueError: An entry is outside the register.
46
+ """
47
+ indexes: list[int] = []
48
+ for qubit in qubits:
49
+ if isinstance(qubit, bool) or not isinstance(qubit, int) or qubit < 0 or qubit >= num_qubits:
50
+ raise ValueError(f"qubit {qubit!r} is outside a {register} of {num_qubits} qubits")
51
+ indexes.append(qubit)
52
+ return tuple(indexes)
53
+
54
+
55
+ def _reject_circuit_metric(name: str, program: object) -> NoReturn:
56
+ """Raise because the backend named ``name`` does not count gates."""
57
+ del program
58
+ raise NotImplementedError(f"{name} does not support circuit metrics")
59
+
60
+
61
+ class _UnsupportedCircuitMetrics:
62
+ """Reject requests for transpiled circuit metrics.
63
+
64
+ Subclasses set ``name`` and inherit the five metric methods. Each method
65
+ raises ``NotImplementedError``.
66
+ """
67
+
68
+ name: str
69
+
70
+ def depth(self, program: object) -> int:
71
+ """Reject a request for transpiled circuit depth.
72
+
73
+ Args:
74
+ program: Unused. This backend does not count gates.
75
+
76
+ Raises:
77
+ NotImplementedError: This backend does not support circuit metrics.
78
+ """
79
+ _reject_circuit_metric(self.name, program)
80
+
81
+ def width(self, program: object) -> int:
82
+ """Reject a request for transpiled qubit count.
83
+
84
+ Args:
85
+ program: Unused. This backend does not count gates.
86
+
87
+ Raises:
88
+ NotImplementedError: This backend does not support circuit metrics.
89
+ """
90
+ _reject_circuit_metric(self.name, program)
91
+
92
+ def gate_count(self, program: object) -> int:
93
+ """Reject a request for a transpiled instruction count.
94
+
95
+ Args:
96
+ program: Unused. This backend does not count gates.
97
+
98
+ Raises:
99
+ NotImplementedError: This backend does not support circuit metrics.
100
+ """
101
+ _reject_circuit_metric(self.name, program)
102
+
103
+ def t_count(self, program: object) -> int:
104
+ """Reject a request for a transpiled ``t`` count.
105
+
106
+ Args:
107
+ program: Unused. This backend does not count gates.
108
+
109
+ Raises:
110
+ NotImplementedError: This backend does not support circuit metrics.
111
+ """
112
+ _reject_circuit_metric(self.name, program)
113
+
114
+ def toffoli_count(self, program: object) -> int:
115
+ """Reject a request for a transpiled Toffoli count.
116
+
117
+ Args:
118
+ program: Unused. This backend does not count gates.
119
+
120
+ Raises:
121
+ NotImplementedError: This backend does not support circuit metrics.
122
+ """
123
+ _reject_circuit_metric(self.name, program)
@@ -0,0 +1,317 @@
1
+ """Run shot circuits on Qiskit Aer."""
2
+
3
+ import re
4
+ from collections.abc import Sequence
5
+
6
+ from qiskit import QuantumCircuit, transpile
7
+ from qiskit.circuit import ClassicalRegister
8
+ from qiskit.transpiler.exceptions import TranspilerError
9
+ from qiskit_aer import AerSimulator
10
+ from qiskit_aer.backends.backend_utils import BASIS_GATES
11
+
12
+ from shadowsim.backends._arguments import _qubit_indexes, _require_shots
13
+ from shadowsim.backends.circuit import to_qiskit
14
+ from shadowsim.backends.program import Program
15
+ from shadowsim.utils.flip_dict import flip_dict
16
+
17
+ # ``store`` is a simulator instruction, not a gate a circuit can be compiled into.
18
+ _EXCLUDED_BASIS_GATES = frozenset({"store"})
19
+ _BASIS_GATE_NAMES = tuple(name for name in BASIS_GATES["statevector"] if name not in _EXCLUDED_BASIS_GATES)
20
+ _IGNORED_TRANSLATION_OPS = frozenset({"measure", "barrier", "reset", "delay", "snapshot"})
21
+ _TRANSLATION_OPS = re.compile(r"""\((['"])([A-Za-z0-9_]+)\1,\s*\d+\)""")
22
+
23
+
24
+ class AerCircuitBackend:
25
+ """Run a program on Qiskit Aer and return shot counts.
26
+
27
+ The program is translated to a Qiskit circuit and transpiled for
28
+ ``AerSimulator``. A set ``seed`` is passed as ``seed_simulator``.
29
+ ``basis_gates`` is passed the same way when it is set. ``z_expectations``
30
+ and ``x_expectations`` estimate Pauli expectations from those counts.
31
+ ``depth``, ``width``, ``gate_count``, ``t_count``, and ``toffoli_count``
32
+ read that transpiled circuit. A unitary stays one instruction, so ``t``
33
+ and ``ccx`` counts stay zero unless transpilation emits those names.
34
+
35
+ Attributes:
36
+ name: ``"aer"``. Stored on simulation result metadata.
37
+ shots: Shot budget passed to each ``run_counts`` call by a simulator.
38
+ basis_gates: Gate names passed to ``AerSimulator``, or ``None`` for
39
+ Aer's own basis.
40
+ BASIS_GATE_NAMES: Gate names ``basis_gates`` may contain.
41
+ """
42
+
43
+ BASIS_GATE_NAMES = _BASIS_GATE_NAMES
44
+
45
+ def __init__(self, shots: int = 10000, basis_gates: Sequence[str] | None = None) -> None:
46
+ """Store the shot budget and optional compilation basis.
47
+
48
+ Args:
49
+ shots: Number of shots for each circuit. Must be a positive integer.
50
+ basis_gates: Gate names ``transpile`` may use. ``None`` keeps Aer's
51
+ own basis. Names are stripped, lowercased, and de-duplicated.
52
+ Each name must be in ``BASIS_GATE_NAMES``.
53
+
54
+ Raises:
55
+ ValueError: ``shots`` is not a positive integer, ``basis_gates`` is
56
+ not a sequence of gate names, the sequence is empty, or a name
57
+ is not a gate Aer can compile into.
58
+ """
59
+ self.name = "aer"
60
+ self.shots = _require_shots(shots)
61
+ self.basis_gates = _basis_gates(basis_gates)
62
+
63
+ def run_counts(self, program: Program, *, shots: int, seed: int | None) -> dict[str, int]:
64
+ """Translate ``program`` to Qiskit, transpile that for Aer, and return counts.
65
+
66
+ Args:
67
+ program: Program to execute.
68
+ shots: Number of shots.
69
+ seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.
70
+
71
+ Returns:
72
+ Mapping from bitstring to shot count.
73
+
74
+ Raises:
75
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
76
+ """
77
+ return self._run_counts(to_qiskit(program), shots=shots, seed=seed)
78
+
79
+ def z_expectations(
80
+ self,
81
+ program: Program,
82
+ qubits: Sequence[int],
83
+ *,
84
+ shots: int,
85
+ seed: int | None,
86
+ ) -> list[float]:
87
+ """Estimate ``⟨Z⟩`` on ``qubits`` from computational-basis shots.
88
+
89
+ Args:
90
+ program: Program to execute, before the computational-basis measurement.
91
+ qubits: 0-based indexes in ``program``. The result follows this order.
92
+ shots: Number of shots.
93
+ seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.
94
+
95
+ Returns:
96
+ One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.
97
+
98
+ Raises:
99
+ ValueError: An index is outside ``program``, or ``program`` cannot be
100
+ compiled into ``basis_gates``.
101
+ """
102
+ return _expectations(self, program, qubits, shots=shots, seed=seed, basis="z")
103
+
104
+ def x_expectations(
105
+ self,
106
+ program: Program,
107
+ qubits: Sequence[int],
108
+ *,
109
+ shots: int,
110
+ seed: int | None,
111
+ ) -> list[float]:
112
+ """Estimate ``⟨X⟩`` on ``qubits`` by applying Hadamard and then measuring.
113
+
114
+ Args:
115
+ program: Program to execute, before the X-basis measurement.
116
+ qubits: 0-based indexes in ``program``. The result follows this order.
117
+ shots: Number of shots.
118
+ seed: Passed as ``seed_simulator`` when set. Omitted when ``None``.
119
+
120
+ Returns:
121
+ One estimate per entry of ``qubits``, each ``(n0 - n1) / shots``.
122
+
123
+ Raises:
124
+ ValueError: An index is outside ``program``, or ``program`` cannot be
125
+ compiled into ``basis_gates``.
126
+ """
127
+ return _expectations(self, program, qubits, shots=shots, seed=seed, basis="x")
128
+
129
+ def depth(self, program: Program) -> int:
130
+ """Return the depth of ``program`` after transpilation for Aer.
131
+
132
+ Args:
133
+ program: Program to measure. It is translated and transpiled for this basis.
134
+
135
+ Returns:
136
+ Length of the critical path on the transpiled circuit.
137
+
138
+ Raises:
139
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
140
+ """
141
+ return int(self._compiled(program).depth())
142
+
143
+ def width(self, program: Program) -> int:
144
+ """Return the qubit count of ``program`` after transpilation for Aer.
145
+
146
+ Args:
147
+ program: Program to measure. It is translated and transpiled for this basis.
148
+
149
+ Returns:
150
+ Number of qubits on the transpiled circuit. Classical bits are not included.
151
+
152
+ Raises:
153
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
154
+ """
155
+ return int(self._compiled(program).num_qubits)
156
+
157
+ def gate_count(self, program: Program) -> int:
158
+ """Return the instruction count of ``program`` after transpilation for Aer.
159
+
160
+ Args:
161
+ program: Program to measure. It is translated and transpiled for this basis.
162
+
163
+ Returns:
164
+ Total number of instructions on the transpiled circuit, including
165
+ measurements when ``program`` contains them.
166
+
167
+ Raises:
168
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
169
+ """
170
+ return int(self._compiled(program).size())
171
+
172
+ def t_count(self, program: Program) -> int:
173
+ """Return the number of ``t`` gates after transpilation for Aer.
174
+
175
+ ``tdg`` is not included. A multi-qubit unitary stays one instruction, so
176
+ a program built only from unitaries reports zero.
177
+
178
+ Args:
179
+ program: Program to measure. It is translated and transpiled for this basis.
180
+
181
+ Returns:
182
+ Count of instructions named ``t``.
183
+
184
+ Raises:
185
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
186
+ """
187
+ return int(self._compiled(program).count_ops().get("t", 0))
188
+
189
+ def toffoli_count(self, program: Program) -> int:
190
+ """Return the number of ``ccx`` and ``ccz`` gates after transpilation for Aer.
191
+
192
+ A multi-qubit unitary stays one instruction, so a program built only
193
+ from unitaries reports zero.
194
+
195
+ Args:
196
+ program: Program to measure. It is translated and transpiled for this basis.
197
+
198
+ Returns:
199
+ Sum of ``ccx`` and ``ccz`` instructions.
200
+
201
+ Raises:
202
+ ValueError: ``program`` cannot be compiled into ``basis_gates``.
203
+ """
204
+ counts = self._compiled(program).count_ops()
205
+ return int(counts.get("ccx", 0)) + int(counts.get("ccz", 0))
206
+
207
+ def _simulator(self, seed: int | None) -> AerSimulator:
208
+ """Return an Aer simulator for this basis and, when set, ``seed``."""
209
+ options: dict[str, object] = {}
210
+ if seed is not None:
211
+ options["seed_simulator"] = seed
212
+ if self.basis_gates is not None:
213
+ options["basis_gates"] = list(self.basis_gates)
214
+ return AerSimulator(**options)
215
+
216
+ def _run_counts(self, circuit: QuantumCircuit, *, shots: int, seed: int | None) -> dict[str, int]:
217
+ """Transpile ``circuit`` for Aer and return counts."""
218
+ backend = self._simulator(seed)
219
+ compiled = _transpile(circuit, backend, self.basis_gates)
220
+ job = backend.run(compiled, shots=shots)
221
+ return job.result().get_counts()
222
+
223
+ def _compiled(self, program: Program) -> QuantumCircuit:
224
+ """Translate ``program`` and transpile it for this backend's basis."""
225
+ return _transpile(to_qiskit(program), self._simulator(None), self.basis_gates)
226
+
227
+
228
+ def _basis_gates(basis_gates: Sequence[str] | None) -> tuple[str, ...] | None:
229
+ """Return ``basis_gates`` as lowercase names, or ``None`` when unset."""
230
+ if basis_gates is None:
231
+ return None
232
+ if isinstance(basis_gates, (str, bytes)) or not isinstance(basis_gates, Sequence):
233
+ raise ValueError("basis_gates must be a sequence of gate names")
234
+ allowed = set(_BASIS_GATE_NAMES)
235
+ chosen: list[str] = []
236
+ seen: set[str] = set()
237
+ for gate in basis_gates:
238
+ if not isinstance(gate, str):
239
+ raise ValueError("basis_gates must be a sequence of gate names")
240
+ name = gate.strip().lower()
241
+ if not name:
242
+ continue
243
+ if name not in allowed:
244
+ raise ValueError(f"Unknown gate {name}.")
245
+ if name in seen:
246
+ continue
247
+ seen.add(name)
248
+ chosen.append(name)
249
+ if not chosen:
250
+ raise ValueError("Enter at least one gate.")
251
+ return tuple(chosen)
252
+
253
+
254
+ def _transpile(circuit: QuantumCircuit, backend: AerSimulator, basis_gates: tuple[str, ...] | None) -> QuantumCircuit:
255
+ """Transpile ``circuit`` for ``backend``, or raise a short basis error."""
256
+ try:
257
+ return transpile(circuit, backend)
258
+ except TranspilerError as exc:
259
+ raise ValueError(_compile_message(basis_gates, exc)) from exc
260
+
261
+
262
+ def _compile_message(basis_gates: tuple[str, ...] | None, exc: TranspilerError) -> str:
263
+ """Return the page-facing reason ``exc`` could not reach ``basis_gates``."""
264
+ found = {match.group(2) for match in _TRANSLATION_OPS.finditer(str(exc))}
265
+ operations = sorted(found - _IGNORED_TRANSLATION_OPS)
266
+ subject = "this circuit" if not operations else _joined(operations)
267
+ target = "Aer's gates" if not basis_gates else _joined(basis_gates)
268
+ return f"Cannot compile {subject} into {target}."
269
+
270
+
271
+ def _joined(names: Sequence[str]) -> str:
272
+ """Return ``names`` as a phrase with a serial comma."""
273
+ if len(names) == 1:
274
+ return names[0]
275
+ if len(names) == 2:
276
+ return f"{names[0]} and {names[1]}"
277
+ return f"{', '.join(names[:-1])}, and {names[-1]}"
278
+
279
+
280
+ def _expectations(
281
+ backend: AerCircuitBackend,
282
+ program: Program,
283
+ qubits: Sequence[int],
284
+ *,
285
+ shots: int,
286
+ seed: int | None,
287
+ basis: str,
288
+ ) -> list[float]:
289
+ """Measure ``qubits`` in ``basis`` and return one Pauli expectation per index."""
290
+ indexes = _qubit_indexes(qubits, program.num_qubits, register="program")
291
+ if not indexes:
292
+ return []
293
+ measured = to_qiskit(program)
294
+ if basis == "x":
295
+ for index in dict.fromkeys(indexes):
296
+ measured.h(index)
297
+ offset = measured.num_clbits
298
+ measured.add_register(ClassicalRegister(len(indexes)))
299
+ for slot, index in enumerate(indexes):
300
+ measured.measure(index, offset + slot)
301
+ counts = backend._run_counts(measured, shots=shots, seed=seed)
302
+ # Qiskit separates classical registers with a space. Dropping it leaves
303
+ # clbit 0 at the right, which is the order ``flip_dict`` turns into an index.
304
+ flat = {key.replace(" ", ""): count for key, count in counts.items()}
305
+ flipped = flip_dict(flat)
306
+ return [_outcome_difference(flipped, offset + slot) / shots for slot in range(len(indexes))]
307
+
308
+
309
+ def _outcome_difference(counts: dict[str, int], bit: int) -> int:
310
+ """Return ``n0 - n1`` for classical bit ``bit`` in already-flipped counts."""
311
+ difference = 0
312
+ for bitstring, count in counts.items():
313
+ if bitstring[bit] == "0":
314
+ difference += count
315
+ else:
316
+ difference -= count
317
+ return difference