iqm-error-reduction-tools 0.2.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.
- iqm/error_reduction_tools/__init__.py +28 -0
- iqm/error_reduction_tools/readout_characterization/__init__.py +22 -0
- iqm/error_reduction_tools/readout_characterization/data_collection.py +342 -0
- iqm/error_reduction_tools/readout_characterization/data_processing.py +640 -0
- iqm/error_reduction_tools/readout_characterization/readout_error_characterization.py +399 -0
- iqm/error_reduction_tools/readout_characterization/topologies.py +241 -0
- iqm/error_reduction_tools/readout_characterization/visualization.py +874 -0
- iqm/error_reduction_tools/rem/__init__.py +26 -0
- iqm/error_reduction_tools/rem/rem_api.py +460 -0
- iqm/error_reduction_tools/rem/rem_processors.py +793 -0
- iqm/error_reduction_tools/twirling/__init__.py +15 -0
- iqm/error_reduction_tools/twirling/twirling_api.py +711 -0
- iqm/error_reduction_tools/twirling/twirling_modifiers.py +554 -0
- iqm/error_reduction_tools/twirling/twirling_processors.py +119 -0
- iqm/error_reduction_tools/utils/__init__.py +15 -0
- iqm/error_reduction_tools/utils/circuit_utils.py +146 -0
- iqm/error_reduction_tools/utils/general_utils.py +168 -0
- iqm/error_reduction_tools/utils/hadamard.py +88 -0
- iqm/error_reduction_tools/utils/qiskit_utils.py +110 -0
- iqm/error_reduction_tools/utils/readout_twirling_strings.py +329 -0
- iqm/error_reduction_tools/utils/topology_utils.py +276 -0
- iqm_error_reduction_tools-0.2.0.dist-info/METADATA +374 -0
- iqm_error_reduction_tools-0.2.0.dist-info/RECORD +25 -0
- iqm_error_reduction_tools-0.2.0.dist-info/WHEEL +4 -0
- iqm_error_reduction_tools-0.2.0.dist-info/licenses/LICENSE.txt +6 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Copyright 2022-2026 IQM
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""IQM Error Reduction Tools.
|
|
16
|
+
|
|
17
|
+
A library for mitigating errors in quantum circuits and related utilities.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
DIST_NAME = "iqm-error-reduction-tools"
|
|
24
|
+
__version__ = version(DIST_NAME)
|
|
25
|
+
except PackageNotFoundError:
|
|
26
|
+
__version__ = "unknown"
|
|
27
|
+
finally:
|
|
28
|
+
del version, PackageNotFoundError
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Copyright 2022-2026 IQM
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Readout error characterization methods."""
|
|
16
|
+
|
|
17
|
+
from .readout_error_characterization import (
|
|
18
|
+
ReadoutErrorCharacterization,
|
|
19
|
+
RECConfiguration,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = ["RECConfiguration", "ReadoutErrorCharacterization"]
|
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
# Copyright 2022-2026 IQM
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Utility functions for generating calibration circuits for readout error characterization."""
|
|
16
|
+
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from time import sleep
|
|
20
|
+
from typing import Any
|
|
21
|
+
import warnings
|
|
22
|
+
|
|
23
|
+
from iqm.error_reduction_tools.twirling.twirling_processors import sum_counts
|
|
24
|
+
from iqm.error_reduction_tools.utils.topology_utils import operational_qubits_from_qc
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from iqm.pulla.pulla import Pulla, PullaJob
|
|
28
|
+
from iqm.pulla.utils_qiskit import sweep_job_to_qiskit
|
|
29
|
+
from iqm.pulse import Circuit, CircuitOperation
|
|
30
|
+
|
|
31
|
+
from .data_processing import CalibrationData
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class CalibrationJobInfo:
|
|
36
|
+
"""Metadata about a submitted calibration job."""
|
|
37
|
+
|
|
38
|
+
num_circuits: int
|
|
39
|
+
"""Total number of calibration circuits generated."""
|
|
40
|
+
shots_per_circuit: int
|
|
41
|
+
"""Number of shots allocated to each circuit."""
|
|
42
|
+
prep_strings: list[str]
|
|
43
|
+
"""List of preparation strings corresponding to each circuit."""
|
|
44
|
+
qubits: list[str]
|
|
45
|
+
"""List of qubits that were characterized."""
|
|
46
|
+
context: Any
|
|
47
|
+
"""Execution context returned from the compiler."""
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def generate_strings(
|
|
51
|
+
number_of_qubits: int,
|
|
52
|
+
number_of_circuits: int,
|
|
53
|
+
rgen: np.random.Generator,
|
|
54
|
+
symmetrize: bool = True,
|
|
55
|
+
) -> list[str]:
|
|
56
|
+
"""Generate random preparation strings of 'I' and 'X' characters.
|
|
57
|
+
|
|
58
|
+
Each string encodes a preparation state for a multi-qubit system:
|
|
59
|
+
'I' = prepare |0>, 'X' = prepare |1> (via X gate).
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
number_of_qubits: Length of each preparation string (number of qubits).
|
|
63
|
+
number_of_circuits: Total number of preparation strings to generate.
|
|
64
|
+
rgen: NumPy random number generator instance.
|
|
65
|
+
symmetrize: If ``True``, generates pairs of complementary strings (I↔X)
|
|
66
|
+
to balance |0> and |1> preparations.
|
|
67
|
+
|
|
68
|
+
Returns:
|
|
69
|
+
List of preparation strings, each of length ``number_of_qubits``.
|
|
70
|
+
|
|
71
|
+
"""
|
|
72
|
+
strings: list[str] = []
|
|
73
|
+
num_pairs = number_of_circuits // 2
|
|
74
|
+
|
|
75
|
+
for _ in range(num_pairs):
|
|
76
|
+
base_string = "".join(rgen.choice(["I", "X"], size=number_of_qubits))
|
|
77
|
+
strings.append(base_string)
|
|
78
|
+
if symmetrize:
|
|
79
|
+
# Add the bit-flipped version
|
|
80
|
+
inverted_string = "".join(["I" if bit == "X" else "X" for bit in base_string])
|
|
81
|
+
strings.append(inverted_string)
|
|
82
|
+
else:
|
|
83
|
+
# Add another random string if not symmetrizing
|
|
84
|
+
strings.append("".join(rgen.choice(["I", "X"], size=number_of_qubits)))
|
|
85
|
+
|
|
86
|
+
# Handle odd number of circuits
|
|
87
|
+
if number_of_circuits % 2 != 0:
|
|
88
|
+
strings.append("".join(rgen.choice(["I", "X"], size=number_of_qubits)))
|
|
89
|
+
|
|
90
|
+
return strings
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def create_calibration_circuits(
|
|
94
|
+
qubits: list[str],
|
|
95
|
+
number_of_circuits: int,
|
|
96
|
+
symmetrize: bool = True,
|
|
97
|
+
seed: int | None = None,
|
|
98
|
+
equatorial_randomization: bool = False,
|
|
99
|
+
) -> tuple[list[Circuit], list[str]]:
|
|
100
|
+
"""Generate readout error characterization (REC) circuits and preparation strings.
|
|
101
|
+
|
|
102
|
+
Creates circuits that prepare qubits in computational basis states (|0> or |1>)
|
|
103
|
+
using I (identity) or X gates, then measure all qubits. Optionally applies
|
|
104
|
+
equatorial randomization to X gates for improved error characterization.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
qubits: IQM qubit names to characterize (e.g., ['QB1', 'QB2']).
|
|
108
|
+
number_of_circuits: Number of calibration circuits to generate.
|
|
109
|
+
symmetrize: If ``True``, generates complementary circuit pairs (I↔X) to
|
|
110
|
+
balance |0> and |1> state preparations across all qubits.
|
|
111
|
+
seed: Random seed for reproducible circuit generation.
|
|
112
|
+
equatorial_randomization: If ``True``, randomize X gate phase angles (phi)
|
|
113
|
+
around the Bloch sphere equator. This distributes state preparation over
|
|
114
|
+
the XY plane.
|
|
115
|
+
|
|
116
|
+
Returns:
|
|
117
|
+
- Circuits ready for compilation.
|
|
118
|
+
- Preparation strings (same length as circuits), where each
|
|
119
|
+
character is 'I' (prepare |0>) or 'X' (prepare |1>).
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
ValueError: If qubits list is empty or ``number_of_circuits`` < 1.
|
|
123
|
+
|
|
124
|
+
Example:
|
|
125
|
+
>>> circuits, preps = create_calibration_circuits(['QB1', 'QB2'], 4, symmetrize=True)
|
|
126
|
+
>>> len(circuits), len(preps)
|
|
127
|
+
(4, 4)
|
|
128
|
+
|
|
129
|
+
"""
|
|
130
|
+
num_qubits: int = len(qubits)
|
|
131
|
+
|
|
132
|
+
if num_qubits == 0:
|
|
133
|
+
raise ValueError("The qubit list is empty. Please provide a valid list of qubits.")
|
|
134
|
+
|
|
135
|
+
if number_of_circuits < 1:
|
|
136
|
+
raise ValueError("The number of circuits must be at least 1.")
|
|
137
|
+
|
|
138
|
+
rgen = np.random.default_rng(seed)
|
|
139
|
+
|
|
140
|
+
prep_strings: list[str] = generate_strings(num_qubits, number_of_circuits, rgen, symmetrize)
|
|
141
|
+
|
|
142
|
+
circuits: list[Circuit] = []
|
|
143
|
+
|
|
144
|
+
for i, prep_str in enumerate(prep_strings):
|
|
145
|
+
# Define measurement instructions
|
|
146
|
+
measure_instructions: list[CircuitOperation] = [
|
|
147
|
+
CircuitOperation(name="measure", locus=(qb_name,), args={"key": f"m_{num_qubits}_0_{q}"})
|
|
148
|
+
for q, qb_name in enumerate(qubits)
|
|
149
|
+
]
|
|
150
|
+
# Defaults to X
|
|
151
|
+
equatorial_angles = np.zeros(shape=num_qubits, dtype=float)
|
|
152
|
+
if equatorial_randomization:
|
|
153
|
+
equatorial_angles = rgen.uniform(0, 2 * np.pi, size=num_qubits)
|
|
154
|
+
|
|
155
|
+
# Create a circuit for each string
|
|
156
|
+
instruction_list: list[CircuitOperation] = []
|
|
157
|
+
for q, op in enumerate(prep_str):
|
|
158
|
+
if op == "X":
|
|
159
|
+
instruction_list.append(
|
|
160
|
+
CircuitOperation(
|
|
161
|
+
name="prx",
|
|
162
|
+
locus=(qubits[q],),
|
|
163
|
+
args={"angle": np.pi, "phase": equatorial_angles[q]},
|
|
164
|
+
)
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
# Combine preparation instructions and measurements
|
|
168
|
+
full_instructions = tuple(instruction_list + measure_instructions)
|
|
169
|
+
circuits.append(Circuit(name=f"calibration_circuit_{i}", instructions=full_instructions))
|
|
170
|
+
|
|
171
|
+
return circuits, prep_strings
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def run_calibration_circuits(
|
|
175
|
+
client: Pulla,
|
|
176
|
+
qubits: Sequence[str] | None = None,
|
|
177
|
+
number_of_circuits: int = 50,
|
|
178
|
+
shots: int = 50000,
|
|
179
|
+
symmetrize: bool = True,
|
|
180
|
+
seed: int | None = None,
|
|
181
|
+
equatorial_randomization: bool = True,
|
|
182
|
+
) -> tuple[PullaJob, CalibrationJobInfo]:
|
|
183
|
+
"""Execute readout error characterization circuits on a quantum computer and collect measurement results.
|
|
184
|
+
|
|
185
|
+
Generates random basis state preparation circuits and runs them on the specified QC.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
client: Client for connecting to an IQM quantum computer.
|
|
189
|
+
qubits: Use ``None`` to characterize every *operational* QPU qubit
|
|
190
|
+
(qubits with a calibrated ``measure`` gate), or a list of specific qubit names
|
|
191
|
+
(e.g., ``["QB1", "QB2"]``). Explicitly requested qubits that are not operational
|
|
192
|
+
are dropped with a warning.
|
|
193
|
+
number_of_circuits: Number of distinct calibration circuits to run.
|
|
194
|
+
shots: Total measurement shots distributed across all circuits.
|
|
195
|
+
Each circuit receives ``shots // number_of_circuits`` shots.
|
|
196
|
+
symmetrize: If ``True``, generates complementary preparation pairs (I↔X).
|
|
197
|
+
seed: Random seed for reproducible preparation string generation.
|
|
198
|
+
equatorial_randomization: If ``True``, randomizes X gate phase angles.
|
|
199
|
+
|
|
200
|
+
Returns:
|
|
201
|
+
Submitted job, metadata about the job.
|
|
202
|
+
|
|
203
|
+
Raises:
|
|
204
|
+
ValueError: If ``shots`` < ``number_of_circuits`` (no shots per circuit), or if no
|
|
205
|
+
operational qubits remain to characterize.
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
"""
|
|
209
|
+
# Resolve the operational qubits (those with a calibrated measure gate).
|
|
210
|
+
operational = operational_qubits_from_qc(client)
|
|
211
|
+
if operational is None:
|
|
212
|
+
# DQA unavailable or empty. Fall back to whatever qubits the chip topology reports
|
|
213
|
+
# so characterization can still proceed, and let the user know we could not confirm
|
|
214
|
+
# they are actually operational.
|
|
215
|
+
try:
|
|
216
|
+
chip_topo = client.get_chip_topology()
|
|
217
|
+
operational = list(chip_topo.qubits_sorted)
|
|
218
|
+
except Exception as exc:
|
|
219
|
+
raise ValueError(
|
|
220
|
+
"Could not determine operational qubits from the dynamic quantum architecture, "
|
|
221
|
+
"and chip topology fallback also failed. The server may be unavailable or misconfigured."
|
|
222
|
+
) from exc
|
|
223
|
+
warnings.warn(
|
|
224
|
+
"Could not determine operational qubits from the dynamic quantum architecture; "
|
|
225
|
+
f"falling back to chip topology qubits {operational}. "
|
|
226
|
+
"Some of these qubits may not have a calibrated measure gate.",
|
|
227
|
+
stacklevel=2,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
qubit_list: list[str]
|
|
231
|
+
if qubits is None:
|
|
232
|
+
qubit_list = operational
|
|
233
|
+
else:
|
|
234
|
+
operational_set = set(operational)
|
|
235
|
+
requested = list(qubits)
|
|
236
|
+
qubit_list = [qubit for qubit in requested if qubit in operational_set]
|
|
237
|
+
dropped = [qubit for qubit in requested if qubit not in operational_set]
|
|
238
|
+
if dropped:
|
|
239
|
+
warnings.warn(
|
|
240
|
+
f"Dropping non-operational qubit(s) {dropped} from readout error characterization; "
|
|
241
|
+
"they have no calibrated measure gate and cannot be characterized or mitigated.",
|
|
242
|
+
stacklevel=2,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
if not qubit_list:
|
|
246
|
+
raise ValueError(
|
|
247
|
+
"No operational qubits to characterize. The requested qubits are not operational, "
|
|
248
|
+
"or the QPU reports no operational qubits."
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
compiler = client.get_standard_compiler()
|
|
252
|
+
circuits, prep_strings = create_calibration_circuits(
|
|
253
|
+
qubit_list,
|
|
254
|
+
number_of_circuits,
|
|
255
|
+
symmetrize,
|
|
256
|
+
seed,
|
|
257
|
+
equatorial_randomization,
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
shots_per_circuit = shots // number_of_circuits
|
|
261
|
+
if shots_per_circuit == 0:
|
|
262
|
+
raise ValueError(
|
|
263
|
+
f"Total shots ({shots}) is less than the number of circuits "
|
|
264
|
+
f"({number_of_circuits}). Increase shots or decrease number_of_circuits."
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
# playlist, context = compiler.compile(circuits)
|
|
268
|
+
# settings, context = compiler.build_settings(context, shots=shots_per_circuit)
|
|
269
|
+
#
|
|
270
|
+
# job = client.submit_playlist(playlist=playlist, settings=settings, context=context)
|
|
271
|
+
|
|
272
|
+
job_definition, context = compiler.compile(circuits=circuits)
|
|
273
|
+
job = client.submit_playlist(job_definition, context=context)
|
|
274
|
+
|
|
275
|
+
job_info = CalibrationJobInfo(
|
|
276
|
+
num_circuits=number_of_circuits,
|
|
277
|
+
shots_per_circuit=shots_per_circuit,
|
|
278
|
+
prep_strings=prep_strings,
|
|
279
|
+
qubits=qubit_list,
|
|
280
|
+
context=context,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
return job, job_info
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def retrieve_calibration_results(
|
|
287
|
+
job: PullaJob,
|
|
288
|
+
job_info: CalibrationJobInfo,
|
|
289
|
+
) -> CalibrationData:
|
|
290
|
+
"""Retrieve and organize measurement results from the calibration circuits.
|
|
291
|
+
|
|
292
|
+
Groups raw measurement counts by their preparation string. The raw counts are preserved
|
|
293
|
+
so that :func:`~iqm.error_reduction_tools.readout_characterization.data_processing.compute_error_probabilities`
|
|
294
|
+
can compare them directly against the preparation string to compute P(0|1) and P(1|0).
|
|
295
|
+
|
|
296
|
+
Args:
|
|
297
|
+
job: Job tracker for the calibration job.
|
|
298
|
+
job_info: Metadata about the submitted calibration job.
|
|
299
|
+
|
|
300
|
+
Returns:
|
|
301
|
+
Calibration results. Multiple circuits with the same preparation string have merged counts.
|
|
302
|
+
|
|
303
|
+
Raises:
|
|
304
|
+
RuntimeError: If the job did not complete after multiple wait attempts.
|
|
305
|
+
|
|
306
|
+
"""
|
|
307
|
+
num_circuits = job_info.num_circuits
|
|
308
|
+
shots_per_circuit = job_info.shots_per_circuit
|
|
309
|
+
prep_strings = job_info.prep_strings
|
|
310
|
+
qubit_list = job_info.qubits
|
|
311
|
+
|
|
312
|
+
max_retries = 10
|
|
313
|
+
retry_delay_s = 30.0
|
|
314
|
+
for attempt in range(max_retries):
|
|
315
|
+
job.wait_for_completion()
|
|
316
|
+
try:
|
|
317
|
+
qiskit_results = sweep_job_to_qiskit(job, shots=shots_per_circuit)
|
|
318
|
+
break
|
|
319
|
+
except ValueError as exc:
|
|
320
|
+
if "WAITING" in str(exc) and attempt < max_retries - 1:
|
|
321
|
+
sleep(retry_delay_s)
|
|
322
|
+
else:
|
|
323
|
+
raise
|
|
324
|
+
else:
|
|
325
|
+
raise RuntimeError("Job did not complete after multiple wait attempts.")
|
|
326
|
+
|
|
327
|
+
# Group counts by preparation string and merge duplicates
|
|
328
|
+
counts_per_prep: dict[str, list[dict[str, float]]] = {}
|
|
329
|
+
for i in range(num_circuits):
|
|
330
|
+
counts = qiskit_results.get_counts(i)
|
|
331
|
+
prep_str = prep_strings[i]
|
|
332
|
+
counts_per_prep.setdefault(prep_str, []).append(counts)
|
|
333
|
+
|
|
334
|
+
# Merge counts for each preparation string
|
|
335
|
+
counts_by_prep = {prep_str: sum_counts(counts_list) for prep_str, counts_list in counts_per_prep.items()}
|
|
336
|
+
|
|
337
|
+
output_data: CalibrationData = {
|
|
338
|
+
"counts_by_prep": counts_by_prep,
|
|
339
|
+
"measured_qubits": qubit_list,
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
return output_data
|