-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add cirq.TensoredConfusionMatrices
for readout error mitigation.
#4854
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 10 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
7f3998b
Add for readout error mitigation.
tanujkhattar 5ac4f45
Merge branch 'master' of https://github.com/quantumlib/cirq into conf…
tanujkhattar 05a036c
Merge branch 'master' of https://github.com/quantumlib/cirq into conf…
tanujkhattar 0c3ec58
Improve docstrings, switch to alternate einsum API, raise error for r…
tanujkhattar aab3a14
Fix lint and typo
tanujkhattar a91e120
Merge branch 'master' of https://github.com/quantumlib/cirq into conf…
tanujkhattar 802fbc2
Address comments
tanujkhattar 09f9242
Merge branch 'master' of https://github.com/quantumlib/cirq into conf…
tanujkhattar 30d8035
Address comments
tanujkhattar fee5e0d
Fix mypy issues
tanujkhattar a68a49a
Merge branch 'master' of https://github.com/quantumlib/cirq into conf…
tanujkhattar a237a26
Raise instead of warning if optimization fails
tanujkhattar dddfc89
Merge branch 'master' into confusion_matrix
CirqBot c9a4e49
Merge branch 'master' into confusion_matrix
CirqBot 40544f7
Merge branch 'master' into confusion_matrix
CirqBot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
140 changes: 140 additions & 0 deletions
140
cirq-core/cirq/experiments/readout_confusion_matrix_test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
# Copyright 2022 The Cirq Developers | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# https://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import numpy as np | ||
import cirq | ||
import pytest | ||
|
||
from cirq.experiments.single_qubit_readout_calibration_test import NoisySingleQubitReadoutSampler | ||
|
||
|
||
def get_expected_cm(num_qubits: int, p0: float, p1: float): | ||
expected_cm = np.zeros((2 ** num_qubits,) * 2) | ||
for i in range(2 ** num_qubits): | ||
for j in range(2 ** num_qubits): | ||
p = 1.0 | ||
for k in range(num_qubits): | ||
b0 = (i >> k) & 1 | ||
b1 = (j >> k) & 1 | ||
if b0 == 0: | ||
p *= p0 * b1 + (1 - p0) * (1 - b1) | ||
else: | ||
p *= p1 * (1 - b1) + (1 - p1) * b1 | ||
expected_cm[i][j] = p | ||
return expected_cm | ||
|
||
|
||
@pytest.mark.parametrize('p0, p1', [(0, 0), (0.2, 0.4), (0.5, 0.5), (0.6, 0.3), (1.0, 1.0)]) | ||
def test_measure_confusion_matrix_with_noise(p0, p1): | ||
sampler = NoisySingleQubitReadoutSampler(p0, p1, seed=1234) | ||
num_qubits = 4 | ||
qubits = cirq.LineQubit.range(num_qubits) | ||
expected_cm = get_expected_cm(num_qubits, p0, p1) | ||
qubits_small = qubits[:2] | ||
expected_cm_small = get_expected_cm(2, p0, p1) | ||
repetitions = 12_000 | ||
# Build entire confusion matrix by running 2 ** 4 = 16 circuits. | ||
readout_cm = cirq.measure_confusion_matrix(sampler, qubits, repetitions=repetitions) | ||
assert readout_cm.repetitions == repetitions | ||
for q, expected in zip([None, qubits_small], [expected_cm, expected_cm_small]): | ||
np.testing.assert_allclose(readout_cm.confusion_matrix(q), expected, atol=1e-2) | ||
np.testing.assert_allclose( | ||
readout_cm.confusion_matrix(q) @ readout_cm.correction_matrix(q), | ||
np.eye(expected.shape[0]), | ||
atol=1e-2, | ||
) | ||
|
||
# Build a tensored confusion matrix using smaller single qubit confusion matrices. | ||
# This works because the error is uncorrelated and requires only 4 * 2 = 8 circuits. | ||
readout_cm = cirq.measure_confusion_matrix( | ||
sampler, [[q] for q in qubits], repetitions=repetitions | ||
) | ||
assert readout_cm.repetitions == repetitions | ||
for q, expected in zip([None, qubits_small], [expected_cm, expected_cm_small]): | ||
np.testing.assert_allclose(readout_cm.confusion_matrix(q), expected, atol=1e-2) | ||
np.testing.assert_allclose( | ||
readout_cm.confusion_matrix(q) @ readout_cm.correction_matrix(q), | ||
np.eye(expected.shape[0]), | ||
atol=1e-2, | ||
) | ||
|
||
# Apply corrections to sampled probabilities using readout_cm. | ||
qs = qubits_small | ||
circuit = cirq.Circuit(cirq.H.on_each(*qs), cirq.measure(*qs)) | ||
reps = 100_000 | ||
sampled_result = cirq.get_state_histogram(sampler.run(circuit, repetitions=reps)) / reps | ||
expected_result = [1 / 4] * 4 | ||
|
||
def l2norm(result: np.ndarray): | ||
return np.sum((expected_result - result) ** 2) | ||
|
||
corrected_result = readout_cm.apply(sampled_result, qs) | ||
assert l2norm(corrected_result) <= l2norm(sampled_result) | ||
|
||
|
||
def test_readout_confusion_matrix_raises(): | ||
num_qubits = 2 | ||
confusion_matrix = get_expected_cm(num_qubits, 0.1, 0.2) | ||
qubits = cirq.LineQubit.range(4) | ||
with pytest.raises(ValueError, match=r"measure_qubits cannot be empty"): | ||
_ = cirq.TensoredConfusionMatrices([], [], repetitions=0, timestamp=0) | ||
|
||
with pytest.raises(ValueError, match=r"len\(confusion_matrices\)"): | ||
_ = cirq.TensoredConfusionMatrices( | ||
[confusion_matrix], [qubits[:2], qubits[2:]], repetitions=0, timestamp=0 | ||
) | ||
|
||
with pytest.raises(ValueError, match="Shape mismatch for confusion matrix"): | ||
_ = cirq.TensoredConfusionMatrices(confusion_matrix, qubits, repetitions=0, timestamp=0) | ||
|
||
with pytest.raises(ValueError, match="Repeated qubits not allowed"): | ||
_ = cirq.TensoredConfusionMatrices( | ||
[confusion_matrix, confusion_matrix], | ||
[qubits[:2], qubits[1:3]], | ||
repetitions=0, | ||
timestamp=0, | ||
) | ||
|
||
readout_cm = cirq.TensoredConfusionMatrices( | ||
[confusion_matrix, confusion_matrix], [qubits[:2], qubits[2:]], repetitions=0, timestamp=0 | ||
) | ||
|
||
with pytest.raises(ValueError, match="should be a subset of"): | ||
_ = readout_cm.confusion_matrix([cirq.NamedQubit("a")]) | ||
|
||
with pytest.raises(ValueError, match="should be a subset of"): | ||
_ = readout_cm.correction_matrix([cirq.NamedQubit("a")]) | ||
|
||
with pytest.raises(ValueError, match="result.shape .* should be"): | ||
_ = readout_cm.apply(np.asarray([100]), qubits[:2]) | ||
|
||
with pytest.raises(ValueError, match="method.* should be"): | ||
_ = readout_cm.apply(np.asarray([1 / 16] * 16), method='l1norm') | ||
|
||
|
||
def test_readout_confusion_matrix_repr_and_equality(): | ||
mat1 = cirq.testing.random_orthogonal(4, random_state=1234) | ||
mat2 = cirq.testing.random_orthogonal(2, random_state=1234) | ||
q = cirq.LineQubit.range(3) | ||
a = cirq.TensoredConfusionMatrices([mat1, mat2], [q[:2], q[2:]], repetitions=0, timestamp=0) | ||
b = cirq.TensoredConfusionMatrices(mat1, q[:2], repetitions=0, timestamp=0) | ||
c = cirq.TensoredConfusionMatrices(mat2, q[2:], repetitions=0, timestamp=0) | ||
for x in [a, b, c]: | ||
cirq.testing.assert_equivalent_repr(x) | ||
assert cirq.approx_eq(x, x) | ||
assert x._approx_eq_(mat1, 1e-6) is NotImplemented | ||
eq = cirq.testing.EqualsTester() | ||
eq.add_equality_group(a, a) | ||
eq.add_equality_group(b, b) | ||
eq.add_equality_group(c, c) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
cirq-core/cirq/protocols/json_test_data/TensoredConfusionMatrices.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
{ | ||
"cirq_type": "TensoredConfusionMatrices", | ||
"confusion_matrices": [ | ||
[ | ||
[ | ||
0.6395, | ||
0.1594, | ||
0.1592, | ||
0.0419 | ||
], | ||
[ | ||
0.5617, | ||
0.2368, | ||
0.1401, | ||
0.0614 | ||
], | ||
[ | ||
0.5655, | ||
0.1367, | ||
0.2403, | ||
0.0575 | ||
], | ||
[ | ||
0.4835, | ||
0.2185, | ||
0.2048, | ||
0.0932 | ||
] | ||
], | ||
[ | ||
[ | ||
0.7999, | ||
0.2001 | ||
], | ||
[ | ||
0.7046, | ||
0.2954 | ||
] | ||
] | ||
], | ||
"measure_qubits": [ | ||
[ | ||
{ | ||
"cirq_type": "LineQubit", | ||
"x": 0 | ||
}, | ||
{ | ||
"cirq_type": "LineQubit", | ||
"x": 1 | ||
} | ||
], | ||
[ | ||
{ | ||
"cirq_type": "NamedQubit", | ||
"name": "a" | ||
} | ||
] | ||
], | ||
"repetitions": 10000, | ||
"timestamp": 1642630636.966274 | ||
} |
17 changes: 17 additions & 0 deletions
17
cirq-core/cirq/protocols/json_test_data/TensoredConfusionMatrices.repr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
cirq.TensoredConfusionMatrices( | ||
[ | ||
np.array( | ||
[ | ||
[0.6395, 0.1594, 0.1592, 0.0419], | ||
[0.5617, 0.2368, 0.1401, 0.0614], | ||
[0.5655, 0.1367, 0.2403, 0.0575], | ||
[0.4835, 0.2185, 0.2048, 0.0932], | ||
], | ||
dtype=np.float64, | ||
), | ||
np.array([[0.7999, 0.2001], [0.7046, 0.2954]], dtype=np.float64), | ||
], | ||
[[cirq.LineQubit(0), cirq.LineQubit(1)], [cirq.NamedQubit('a')]], | ||
repetitions=10000, | ||
timestamp=1642630636.966274, | ||
) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.