Skip to content

Add testing helper for consistent channel/mixture #5247

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 6 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 11 additions & 11 deletions cirq-core/cirq/ops/common_channels_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def test_asymmetric_depolarizing_channel():
cirq.kraus(d),
(np.sqrt(0.4) * np.eye(2), np.sqrt(0.1) * X, np.sqrt(0.2) * Y, np.sqrt(0.3) * Z),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)

assert cirq.AsymmetricDepolarizingChannel(p_x=0, p_y=0.1, p_z=0).num_qubits() == 1

Expand Down Expand Up @@ -145,7 +145,7 @@ def test_depolarizing_channel():
np.sqrt(0.1) * Z,
),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)


def test_depolarizing_channel_two_qubits():
Expand All @@ -171,7 +171,7 @@ def test_depolarizing_channel_two_qubits():
np.sqrt(0.01) * np.kron(Z, Z),
),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)

assert d.num_qubits() == 2
cirq.testing.assert_has_diagram(
Expand Down Expand Up @@ -332,7 +332,7 @@ def test_generalized_amplitude_damping_channel():
np.sqrt(0.9) * np.array([[0.0, 0.0], [np.sqrt(0.3), 0.0]]),
),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)
assert not cirq.has_mixture(d)


Expand Down Expand Up @@ -396,7 +396,7 @@ def test_amplitude_damping_channel():
np.array([[0.0, np.sqrt(0.3)], [0.0, 0.0]]),
),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)
assert not cirq.has_mixture(d)


Expand Down Expand Up @@ -448,7 +448,7 @@ def test_reset_channel():
np.testing.assert_almost_equal(
cirq.kraus(r), (np.array([[1.0, 0.0], [0.0, 0]]), np.array([[0.0, 1.0], [0.0, 0.0]]))
)
assert cirq.has_kraus(r)
cirq.testing.assert_consistent_channel(r)
assert not cirq.has_mixture(r)
assert cirq.qid_shape(r) == (2,)

Expand All @@ -461,7 +461,7 @@ def test_reset_channel():
np.array([[0, 0, 1], [0, 0, 0], [0, 0, 0]]),
),
) # yapf: disable
assert cirq.has_kraus(r)
cirq.testing.assert_consistent_channel(r)
assert not cirq.has_mixture(r)
assert cirq.qid_shape(r) == (3,)

Expand Down Expand Up @@ -538,7 +538,7 @@ def test_phase_damping_channel():
np.array([[0.0, 0.0], [0.0, np.sqrt(0.3)]]),
),
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)
assert not cirq.has_mixture(d)


Expand Down Expand Up @@ -590,7 +590,7 @@ def test_phase_flip_channel():
np.testing.assert_almost_equal(
cirq.kraus(d), (np.sqrt(1.0 - 0.3) * np.eye(2), np.sqrt(0.3) * Z)
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)


def test_phase_flip_mixture():
Expand Down Expand Up @@ -654,7 +654,7 @@ def test_bit_flip_channel():
np.testing.assert_almost_equal(
cirq.kraus(d), (np.sqrt(1.0 - 0.3) * np.eye(2), np.sqrt(0.3) * X)
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)


def test_bit_flip_mixture():
Expand Down Expand Up @@ -760,7 +760,7 @@ def test_multi_asymmetric_depolarizing_channel():
np.testing.assert_almost_equal(
cirq.kraus(d), (np.sqrt(0.8) * np.eye(4), np.sqrt(0.2) * np.kron(X, X))
)
assert cirq.has_kraus(d)
cirq.testing.assert_consistent_channel(d)
np.testing.assert_equal(d._num_qubits_(), 2)

with pytest.raises(ValueError, match="num_qubits should be 1"):
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/ops/kraus_channel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def test_kraus_channel_from_channel():
dp = cirq.depolarize(0.1)
kc = cirq.KrausChannel.from_channel(dp, key='dp')
assert cirq.measurement_key_name(kc) == 'dp'
cirq.testing.assert_consistent_channel(kc)

circuit = cirq.Circuit(kc.on(q0))
sim = cirq.Simulator(seed=0)
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/ops/measurement_gate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ def test_measurement_channel():
cirq.kraus(cirq.MeasurementGate(1, 'a')),
(np.array([[1, 0], [0, 0]]), np.array([[0, 0], [0, 1]])),
)
cirq.testing.assert_consistent_channel(cirq.MeasurementGate(1, 'a'))
# yapf: disable
np.testing.assert_allclose(
cirq.kraus(cirq.MeasurementGate(2, 'a')),
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/ops/mixed_unitary_channel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def test_matrix_mixture_from_mixture():
dp = cirq.depolarize(0.1)
mm = cirq.MixedUnitaryChannel.from_mixture(dp, key='dp')
assert cirq.measurement_key_name(mm) == 'dp'
cirq.testing.assert_consistent_channel(mm)

circuit = cirq.Circuit(mm.on(q0))
sim = cirq.Simulator(seed=0)
Expand Down
2 changes: 1 addition & 1 deletion cirq-core/cirq/ops/projector.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(
projector_dict: Dict[raw_types.Qid, int],
coefficient: Union[int, float, complex] = 1,
):
"""Contructor for ProjectorString
"""Constructor for ProjectorString

Args:
projector_dict: A python dictionary mapping from cirq.Qid to integers. A key value pair
Expand Down
6 changes: 3 additions & 3 deletions cirq-core/cirq/ops/random_gate_channel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,9 +175,9 @@ def num_qubits(self) -> int:
assert not cirq.has_kraus(NoDetailsGate().with_probability(0.5))
assert cirq.kraus(NoDetailsGate().with_probability(0.5), None) is None
assert cirq.kraus(cirq.X.with_probability(sympy.Symbol('x')), None) is None
assert_channel_sums_to_identity(cirq.X.with_probability(0.25))
assert_channel_sums_to_identity(cirq.bit_flip(0.75).with_probability(0.25))
assert_channel_sums_to_identity(cirq.amplitude_damp(0.75).with_probability(0.25))
cirq.testing.assert_consistent_channel(cirq.X.with_probability(0.25))
cirq.testing.assert_consistent_channel(cirq.bit_flip(0.75).with_probability(0.25))
cirq.testing.assert_consistent_channel(cirq.amplitude_damp(0.75).with_probability(0.25))

m = cirq.kraus(cirq.X.with_probability(0.25))
assert len(m) == 2
Expand Down
1 change: 1 addition & 0 deletions cirq-core/cirq/ops/state_preparation_channel_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
def test_state_prep_channel_kraus(state):
qubits = cirq.LineQubit.range(2)
gate = cirq.StatePreparationChannel(state)(qubits[0], qubits[1])
cirq.testing.assert_consistent_channel(gate)
state = state / np.linalg.norm(state)
np.testing.assert_almost_equal(
cirq.kraus(gate),
Expand Down
4 changes: 4 additions & 0 deletions cirq-core/cirq/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@
assert_all_implemented_act_on_effects_match_unitary,
)

from cirq.testing.consistent_channel import (
assert_consistent_channel,
)

from cirq.testing.consistent_controlled_gate_op import (
assert_controlled_and_controlled_by_identical,
)
Expand Down
26 changes: 26 additions & 0 deletions cirq-core/cirq/testing/consistent_channel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# 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.

from typing import Any

import cirq


def assert_consistent_channel(gate: Any, rtol: float = 1e-5, atol: float = 1e-8):
assert cirq.has_kraus(gate), f"Given gate {gate!r} does not return True cirq.has_kraus."
kraus_ops = cirq.kraus(gate)
assert cirq.is_cptp(kraus_ops=kraus_ops, rtol=rtol, atol=atol), (
f"Kraus operators for {gate!r} did not sum to identity up to expected tolerances. "
f"Summed to {sum(m.T.conj() @ m for m in kraus_ops)}"
)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also add tests for has_mixture and mixture.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is now done

47 changes: 47 additions & 0 deletions cirq-core/cirq/testing/consistent_channel_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# 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 pytest
import numpy as np
import cirq


def test_assert_consistent_channel_valid():
channel = cirq.KrausChannel(kraus_ops=(np.array([[0, 1], [0, 0]]), np.array([[1, 0], [0, 0]])))
cirq.testing.assert_consistent_channel(channel)


def test_assert_consistent_channel_tolerances():
# This channel is off by 1e-5 from the identity matrix in the consistency condition.
channel = cirq.KrausChannel(
kraus_ops=(np.array([[0, np.sqrt(1 - 1e-5)], [0, 0]]), np.array([[1, 0], [0, 0]]))
)
# We are comparing to identity, so rtol is same as atol for non-zero entries.
cirq.testing.assert_consistent_channel(channel, rtol=1e-5, atol=0)
with pytest.raises(AssertionError):
cirq.testing.assert_consistent_channel(channel, rtol=1e-6, atol=0)
cirq.testing.assert_consistent_channel(channel, rtol=0, atol=1e-5)
with pytest.raises(AssertionError):
cirq.testing.assert_consistent_channel(channel, rtol=0, atol=1e-6)


def test_assert_consistent_channel_invalid():
channel = cirq.KrausChannel(kraus_ops=(np.array([[1, 1], [0, 0]]), np.array([[1, 0], [0, 0]])))
with pytest.raises(AssertionError, match=r"cirq.KrausChannel.*2 1"):
cirq.testing.assert_consistent_channel(channel)


def test_assert_consistent_channel_not_kraus():
with pytest.raises(AssertionError, match="12.*has_kraus"):
cirq.testing.assert_consistent_channel(12)