From 046b8840058978ee4c061145a279f2873e687175 Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Tue, 7 Dec 2021 11:34:20 -0800 Subject: [PATCH 1/7] Remove files for subsequent PRs --- cirq-core/cirq/__init__.py | 1 + cirq-core/cirq/devices/__init__.py | 12 + cirq-core/cirq/devices/noise_utils.py | 232 ++++++++++++++++++ cirq-core/cirq/devices/noise_utils_test.py | 140 +++++++++++ cirq-core/cirq/json_resolver_cache.py | 1 + .../json_test_data/OpIdentifier.json | 10 + .../json_test_data/OpIdentifier.repr | 4 + 7 files changed, 400 insertions(+) create mode 100644 cirq-core/cirq/devices/noise_utils.py create mode 100644 cirq-core/cirq/devices/noise_utils_test.py create mode 100644 cirq-core/cirq/protocols/json_test_data/OpIdentifier.json create mode 100644 cirq-core/cirq/protocols/json_test_data/OpIdentifier.repr diff --git a/cirq-core/cirq/__init__.py b/cirq-core/cirq/__init__.py index 35b84ca21da..b9e3b5121b1 100644 --- a/cirq-core/cirq/__init__.py +++ b/cirq-core/cirq/__init__.py @@ -88,6 +88,7 @@ NO_NOISE, NOISE_MODEL_LIKE, NoiseModel, + OpIdentifier, SymmetricalQidPair, UNCONSTRAINED_DEVICE, NamedTopology, diff --git a/cirq-core/cirq/devices/__init__.py b/cirq-core/cirq/devices/__init__.py index 1060f7aea0e..72f793a7e46 100644 --- a/cirq-core/cirq/devices/__init__.py +++ b/cirq-core/cirq/devices/__init__.py @@ -47,3 +47,15 @@ get_placements, draw_placements, ) + +from cirq.devices.noise_utils import ( + OpIdentifier, + decay_constant_to_xeb_fidelity, + decay_constant_to_pauli_error, + pauli_error_to_decay_constant, + xeb_fidelity_to_decay_constant, + pauli_error_from_t1, + pauli_error_from_depolarization, + average_error, + decoherence_pauli_error, +) diff --git a/cirq-core/cirq/devices/noise_utils.py b/cirq-core/cirq/devices/noise_utils.py new file mode 100644 index 00000000000..e02ed8baf45 --- /dev/null +++ b/cirq-core/cirq/devices/noise_utils.py @@ -0,0 +1,232 @@ +# Copyright 2021 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 TYPE_CHECKING, Any, Dict, Tuple, Type, Union +import warnings +import numpy as np + +from cirq import ops, protocols, value + +if TYPE_CHECKING: + import cirq + + +# Tag for gates to which noise must be applied. +PHYSICAL_GATE_TAG = 'physical_gate' + + +@value.value_equality(distinct_child_types=True) +class OpIdentifier: + """Identifies an operation by gate and (optionally) target qubits.""" + + def __init__(self, gate_type: Type['cirq.Gate'], *qubits: 'cirq.Qid'): + self._gate_type = gate_type + self._gate_family = ops.GateFamily(gate_type) + self._qubits: Tuple['cirq.Qid', ...] = tuple(qubits) + + @property + def gate_type(self) -> Type['cirq.Gate']: + # set to a type during initialization, never modified + return self._gate_type + + @property + def qubits(self) -> Tuple['cirq.Qid', ...]: + return self._qubits + + def _predicate(self, *args, **kwargs): + return self._gate_family._predicate(*args, **kwargs) + + def swapped(self): + return OpIdentifier(self.gate_type, *self.qubits[::-1]) + + def is_proper_subtype_of(self, op_id: 'OpIdentifier'): + """Returns true if this is contained within op_id, but not equal to it. + + If this returns true, (x in self) implies (x in op_id), but the reverse + implication does not hold. op_id must be more general than self (either + by accepting any qubits or having a more general gate type) for this + to return true. + """ + more_specific_qubits = self.qubits and not op_id.qubits + more_specific_gate = self.gate_type != op_id.gate_type and issubclass( + self.gate_type, op_id.gate_type + ) + return ( + (more_specific_qubits or more_specific_gate) + and (more_specific_qubits or self.qubits == op_id.qubits) + and (more_specific_gate or self.gate_type == op_id.gate_type) + ) + + def __contains__(self, item: Union[ops.Gate, ops.Operation]) -> bool: + if isinstance(item, ops.Gate): + return (not self._qubits) and self._predicate(item) + return ( + (not self.qubits or (item.qubits == self._qubits)) + and item.gate is not None + and self._predicate(item.gate) + ) + + def __str__(self): + return f'{self.gate_type}{self.qubits}' + + def __repr__(self) -> str: + fullname = f'{self.gate_type.__module__}.{self.gate_type.__qualname__}' + qubits = ', '.join(map(repr, self.qubits)) + return f'cirq.devices.noise_utils.OpIdentifier({fullname}, {qubits})' + + def _value_equality_values_(self) -> Any: + return (self.gate_type, self.qubits) + + def _json_dict_(self) -> Dict[str, Any]: + gate_json = protocols.json_cirq_type(self._gate_type) + return { + 'gate_type': gate_json, + 'qubits': self._qubits, + } + + @classmethod + def _from_json_dict_(cls, gate_type, qubits, **kwargs) -> 'OpIdentifier': + gate_type = protocols.cirq_type_from_json(gate_type) + return cls(gate_type, *qubits) + + +# TODO: expose all from top-level cirq? +def decay_constant_to_xeb_fidelity(decay_constant: float, num_qubits: int = 2) -> float: + """Calculates the XEB fidelity from the depolarization decay constant. + + Args: + decay_constant: Depolarization decay constant. + num_qubits: Number of qubits. + + Returns: + Calculated XEB fidelity. + """ + N = 2 ** num_qubits + return 1 - ((1 - decay_constant) * (1 - 1 / N)) + + +def decay_constant_to_pauli_error(decay_constant: float, num_qubits: int = 1) -> float: + """Calculates pauli error from the depolarization decay constant. + + Args: + decay_constant: Depolarization decay constant. + num_qubits: Number of qubits. + + Returns: + Calculated Pauli error. + """ + N = 2 ** num_qubits + return (1 - decay_constant) * (1 - 1 / N / N) + + +def pauli_error_to_decay_constant(pauli_error: float, num_qubits: int = 1) -> float: + """Calculates depolarization decay constant from pauli error. + + Args: + pauli_error: The pauli error. + num_qubits: Number of qubits. + + Returns: + Calculated depolarization decay constant. + """ + N = 2 ** num_qubits + return 1 - (pauli_error / (1 - 1 / N / N)) + + +def xeb_fidelity_to_decay_constant(xeb_fidelity: float, num_qubits: int = 2) -> float: + """Calculates the depolarization decay constant from XEB fidelity. + + Args: + xeb_fidelity: The XEB fidelity. + num_qubits: Number of qubits. + + Returns: + Calculated depolarization decay constant. + """ + N = 2 ** num_qubits + return 1 - (1 - xeb_fidelity) / (1 - 1 / N) + + +def pauli_error_from_t1(t_ns: float, t1_ns: float) -> float: + """Calculates the pauli error from T1 decay constant. + + This computes error for a specific duration, `t`. + + Args: + t_ns: The duration of the gate in ns. + t1_ns: The T1 decay constant in ns. + + Returns: + Calculated Pauli error resulting from T1 decay. + """ + t2 = 2 * t1_ns + return (1 - np.exp(-t_ns / t2)) / 2 + (1 - np.exp(-t_ns / t1_ns)) / 4 + + +def pauli_error_from_depolarization(t_ns: float, t1_ns: float, pauli_error: float = 0) -> float: + """Calculates the amount of pauli error from depolarization. + + This computes non-T1 error for a specific duration, `t`. If pauli error + from T1 decay is more than total pauli error, this returns zero; otherwise, + it returns the portion of pauli error not attributable to T1 error. + + Args: + t_ns: The duration of the gate in ns. + t1_ns: The T1 decay constant in ns. + pauli_error: The total pauli error. + + Returns: + Calculated Pauli error resulting from depolarization. + """ + t1_pauli_error = pauli_error_from_t1(t_ns, t1_ns) + if pauli_error >= t1_pauli_error: + return pauli_error - t1_pauli_error + + warnings.warn("Pauli error from T1 decay is greater than total Pauli error", RuntimeWarning) + return 0 + + +def average_error(decay_constant: float, num_qubits: int = 1) -> float: + """Calculates the average error from the depolarization decay constant. + + Args: + decay_constant: Depolarization decay constant. + num_qubits: Number of qubits. + + Returns: + Calculated average error. + """ + N = 2 ** num_qubits + return (1 - decay_constant) * (1 - 1 / N) + + +def decoherence_pauli_error(t1_ns: float, tphi_ns: float, gate_time_ns: float) -> float: + """The component of Pauli error caused by decoherence. + + Args: + t1_ns: T1 time in nanoseconds. + tphi_ns: Tphi time in nanoseconds. + gate_time_ns: Duration in nanoseconds of the gate affected by this error. + + Returns: + Calculated Pauli error resulting from decoherence. + """ + Gamma2 = (1 / (2 * t1_ns)) + 1 / tphi_ns + + exp1 = np.exp(-gate_time_ns / t1_ns) + exp2 = np.exp(-gate_time_ns * Gamma2) + px = 0.25 * (1 - exp1) + py = px + pz = 0.5 * (1 - exp2) - px + return px + py + pz diff --git a/cirq-core/cirq/devices/noise_utils_test.py b/cirq-core/cirq/devices/noise_utils_test.py new file mode 100644 index 00000000000..61b5852ced4 --- /dev/null +++ b/cirq-core/cirq/devices/noise_utils_test.py @@ -0,0 +1,140 @@ +# Copyright 2021 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 pytest + +import cirq +from cirq.devices.noise_utils import ( + OpIdentifier, + decay_constant_to_xeb_fidelity, + decay_constant_to_pauli_error, + pauli_error_to_decay_constant, + xeb_fidelity_to_decay_constant, + pauli_error_from_t1, + pauli_error_from_depolarization, + average_error, + decoherence_pauli_error, +) + + +def test_op_id(): + op_id = OpIdentifier(cirq.XPowGate) + assert cirq.X(cirq.LineQubit(1)) in op_id + assert cirq.Rx(rads=1) in op_id + + +@pytest.mark.parametrize( + 'decay_constant,num_qubits,expected_output', + [ + (0.01, 1, 1 - (0.99 * 1 / 2)), + (0.05, 2, 1 - (0.95 * 3 / 4)), + ], +) +def test_decay_constant_to_xeb_fidelity(decay_constant, num_qubits, expected_output): + val = decay_constant_to_xeb_fidelity(decay_constant, num_qubits) + assert val == expected_output + + +@pytest.mark.parametrize( + 'decay_constant,num_qubits,expected_output', + [ + (0.01, 1, 0.99 * 3 / 4), + (0.05, 2, 0.95 * 15 / 16), + ], +) +def test_decay_constant_to_pauli_error(decay_constant, num_qubits, expected_output): + val = decay_constant_to_pauli_error(decay_constant, num_qubits) + assert val == expected_output + + +@pytest.mark.parametrize( + 'pauli_error,num_qubits,expected_output', + [ + (0.01, 1, 1 - (0.01 / (3 / 4))), + (0.05, 2, 1 - (0.05 / (15 / 16))), + ], +) +def test_pauli_error_to_decay_constant(pauli_error, num_qubits, expected_output): + val = pauli_error_to_decay_constant(pauli_error, num_qubits) + assert val == expected_output + + +@pytest.mark.parametrize( + 'xeb_fidelity,num_qubits,expected_output', + [ + (0.01, 1, 1 - 0.99 / (1 / 2)), + (0.05, 2, 1 - 0.95 / (3 / 4)), + ], +) +def test_xeb_fidelity_to_decay_constant(xeb_fidelity, num_qubits, expected_output): + val = xeb_fidelity_to_decay_constant(xeb_fidelity, num_qubits) + assert val == expected_output + + +@pytest.mark.parametrize( + 't,t1_ns,expected_output', + [ + (20, 1e5, (1 - np.exp(-20 / 2e5)) / 2 + (1 - np.exp(-20 / 1e5)) / 4), + (4000, 1e4, (1 - np.exp(-4000 / 2e4)) / 2 + (1 - np.exp(-4000 / 1e4)) / 4), + ], +) +def test_pauli_error_from_t1(t, t1_ns, expected_output): + val = pauli_error_from_t1(t, t1_ns) + assert val == expected_output + + +@pytest.mark.parametrize( + 't,t1_ns,pauli_error,expected_output', + [ + (20, 1e5, 0.01, 0.01 - ((1 - np.exp(-20 / 2e5)) / 2 + (1 - np.exp(-20 / 1e5)) / 4)), + # In this case, the formula produces a negative result. + (4000, 1e4, 0.01, 0), + ], +) +def test_pauli_error_from_depolarization(t, t1_ns, pauli_error, expected_output): + val = pauli_error_from_depolarization(t, t1_ns, pauli_error) + assert val == expected_output + + +@pytest.mark.parametrize( + 'decay_constant,num_qubits,expected_output', + [ + (0.01, 1, 0.99 * 1 / 2), + (0.05, 2, 0.95 * 3 / 4), + ], +) +def test_average_error(decay_constant, num_qubits, expected_output): + val = average_error(decay_constant, num_qubits) + assert val == expected_output + + +@pytest.mark.parametrize( + 'T1_ns,Tphi_ns,gate_time_ns', + [ + (1e4, 2e4, 25), + (1e5, 2e3, 25), + (1e4, 2e4, 4000), + ], +) +def test_decoherence_pauli_error(T1_ns, Tphi_ns, gate_time_ns): + val = decoherence_pauli_error(T1_ns, Tphi_ns, gate_time_ns) + # Expected value is of the form: + # + # (1/4) * [1 - e^(-t/T1)] + (1/2) * [1 - e^(-t/(2*T1) - t/Tphi] + # + expected_output = 0.25 * (1 - np.exp(-gate_time_ns / T1_ns)) + 0.5 * ( + 1 - np.exp(-gate_time_ns * ((1 / (2 * T1_ns)) + 1 / Tphi_ns)) + ) + assert val == expected_output diff --git a/cirq-core/cirq/json_resolver_cache.py b/cirq-core/cirq/json_resolver_cache.py index f18fbc90c91..3692c3b191d 100644 --- a/cirq-core/cirq/json_resolver_cache.py +++ b/cirq-core/cirq/json_resolver_cache.py @@ -114,6 +114,7 @@ def _parallel_gate_op(gate, qubits): 'NamedQubit': cirq.NamedQubit, 'NamedQid': cirq.NamedQid, 'NoIdentifierQubit': cirq.testing.NoIdentifierQubit, + 'OpIdentifier': cirq.OpIdentifier, '_PauliX': cirq.ops.pauli_gates._PauliX, '_PauliY': cirq.ops.pauli_gates._PauliY, '_PauliZ': cirq.ops.pauli_gates._PauliZ, diff --git a/cirq-core/cirq/protocols/json_test_data/OpIdentifier.json b/cirq-core/cirq/protocols/json_test_data/OpIdentifier.json new file mode 100644 index 00000000000..d33b909367d --- /dev/null +++ b/cirq-core/cirq/protocols/json_test_data/OpIdentifier.json @@ -0,0 +1,10 @@ +{ + "cirq_type": "OpIdentifier", + "gate_type": "XPowGate", + "qubits": [ + { + "cirq_type": "LineQubit", + "x": 1 + } + ] +} \ No newline at end of file diff --git a/cirq-core/cirq/protocols/json_test_data/OpIdentifier.repr b/cirq-core/cirq/protocols/json_test_data/OpIdentifier.repr new file mode 100644 index 00000000000..6b991bb0b2c --- /dev/null +++ b/cirq-core/cirq/protocols/json_test_data/OpIdentifier.repr @@ -0,0 +1,4 @@ +cirq.devices.noise_utils.OpIdentifier( + cirq.ops.common_gates.XPowGate, + cirq.LineQubit(1) +) \ No newline at end of file From 55069a968eaa8ef2c55b40b509c4b670bda4036e Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Tue, 7 Dec 2021 11:49:19 -0800 Subject: [PATCH 2/7] Add coverage for OpId --- cirq-core/cirq/devices/noise_utils_test.py | 32 +++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/cirq-core/cirq/devices/noise_utils_test.py b/cirq-core/cirq/devices/noise_utils_test.py index 61b5852ced4..d49d9e6508a 100644 --- a/cirq-core/cirq/devices/noise_utils_test.py +++ b/cirq-core/cirq/devices/noise_utils_test.py @@ -29,12 +29,42 @@ ) -def test_op_id(): +def test_op_identifier(): op_id = OpIdentifier(cirq.XPowGate) assert cirq.X(cirq.LineQubit(1)) in op_id assert cirq.Rx(rads=1) in op_id +def test_op_identifier_subtypes(): + gate_id = OpIdentifier(cirq.Gate) + xpow_id = OpIdentifier(cirq.XPowGate) + x_on_q0_id = OpIdentifier(cirq.XPowGate, cirq.LineQubit(0)) + assert xpow_id.is_proper_subtype_of(gate_id) + assert x_on_q0_id.is_proper_subtype_of(xpow_id) + assert x_on_q0_id.is_proper_subtype_of(gate_id) + assert not xpow_id.is_proper_subtype_of(xpow_id) + + +def test_op_id_str(): + op_id = OpIdentifier(cirq.XPowGate, cirq.LineQubit(0)) + print(op_id) + print(repr(op_id)) + assert str(op_id) == "(cirq.LineQubit(0),)" + assert repr(op_id) == ( + "cirq.devices.noise_utils.OpIdentifier(cirq.ops.common_gates.XPowGate, cirq.LineQubit(0))" + ) + + +def test_op_id_swap(): + q0, q1 = cirq.LineQubit.range(2) + base_id = OpIdentifier(cirq.CZPowGate, q0, q1) + swap_id = base_id.swapped() + assert cirq.CZ(q0, q1) in base_id + assert cirq.CZ(q0, q1) not in swap_id + assert cirq.CZ(q1, q0) not in base_id + assert cirq.CZ(q1, q0) in swap_id + + @pytest.mark.parametrize( 'decay_constant,num_qubits,expected_output', [ From 75dc3e84ff76d5ddea6b47c626006ea243beaf06 Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Tue, 7 Dec 2021 14:29:13 -0800 Subject: [PATCH 3/7] Clarify if-case --- cirq-core/cirq/devices/noise_utils.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cirq-core/cirq/devices/noise_utils.py b/cirq-core/cirq/devices/noise_utils.py index e02ed8baf45..35c84ce2a25 100644 --- a/cirq-core/cirq/devices/noise_utils.py +++ b/cirq-core/cirq/devices/noise_utils.py @@ -62,11 +62,12 @@ def is_proper_subtype_of(self, op_id: 'OpIdentifier'): more_specific_gate = self.gate_type != op_id.gate_type and issubclass( self.gate_type, op_id.gate_type ) - return ( - (more_specific_qubits or more_specific_gate) - and (more_specific_qubits or self.qubits == op_id.qubits) - and (more_specific_gate or self.gate_type == op_id.gate_type) - ) + if more_specific_qubits: + return more_specific_gate or self.gate_type == op_id.gate_type + elif more_specific_gate: + return more_specific_qubits or self.qubits == op_id.qubits + else: + return False def __contains__(self, item: Union[ops.Gate, ops.Operation]) -> bool: if isinstance(item, ops.Gate): From 4f9fdc0c8a156eee1a9cd665b32e6e19a65b5a2e Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Mon, 13 Dec 2021 11:38:45 -0800 Subject: [PATCH 4/7] snake_case_gamma --- cirq-core/cirq/devices/noise_utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cirq-core/cirq/devices/noise_utils.py b/cirq-core/cirq/devices/noise_utils.py index 35c84ce2a25..fe59d94a9c1 100644 --- a/cirq-core/cirq/devices/noise_utils.py +++ b/cirq-core/cirq/devices/noise_utils.py @@ -223,10 +223,10 @@ def decoherence_pauli_error(t1_ns: float, tphi_ns: float, gate_time_ns: float) - Returns: Calculated Pauli error resulting from decoherence. """ - Gamma2 = (1 / (2 * t1_ns)) + 1 / tphi_ns + gamma_2 = (1 / (2 * t1_ns)) + 1 / tphi_ns exp1 = np.exp(-gate_time_ns / t1_ns) - exp2 = np.exp(-gate_time_ns * Gamma2) + exp2 = np.exp(-gate_time_ns * gamma_2) px = 0.25 * (1 - exp1) py = px pz = 0.5 * (1 - exp2) - px From 2baaaa7d41fda2bb1619b725e97befbf0b121fa2 Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Fri, 12 Nov 2021 09:47:15 -0800 Subject: [PATCH 5/7] Add insertion noise model. --- cirq-core/cirq/devices/__init__.py | 4 + .../cirq/devices/insertion_noise_model.py | 75 +++++++++++++ .../devices/insertion_noise_model_test.py | 104 ++++++++++++++++++ 3 files changed, 183 insertions(+) create mode 100644 cirq-core/cirq/devices/insertion_noise_model.py create mode 100644 cirq-core/cirq/devices/insertion_noise_model_test.py diff --git a/cirq-core/cirq/devices/__init__.py b/cirq-core/cirq/devices/__init__.py index 72f793a7e46..89f5d1e22b5 100644 --- a/cirq-core/cirq/devices/__init__.py +++ b/cirq-core/cirq/devices/__init__.py @@ -48,6 +48,10 @@ draw_placements, ) +from cirq.devices.insertion_noise_model import ( + InsertionNoiseModel, +) + from cirq.devices.noise_utils import ( OpIdentifier, decay_constant_to_xeb_fidelity, diff --git a/cirq-core/cirq/devices/insertion_noise_model.py b/cirq-core/cirq/devices/insertion_noise_model.py new file mode 100644 index 00000000000..6fc3d44b1cc --- /dev/null +++ b/cirq-core/cirq/devices/insertion_noise_model.py @@ -0,0 +1,75 @@ +# Copyright 2021 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 dataclasses import dataclass, field +from typing import TYPE_CHECKING, Dict, List, Sequence + +from cirq import devices, ops +from cirq.devices.noise_utils import ( + OpIdentifier, + PHYSICAL_GATE_TAG, +) + +if TYPE_CHECKING: + import cirq + + +@dataclass +class InsertionNoiseModel(devices.NoiseModel): + """Simple base noise model for inserting operations. + + Operations generated by this model for a given moment are all added into a + single "noise moment", which is added before or after the original moment + based on `prepend`. + + Args: + ops_added: a map of gate types (and optionally, qubits they act on) to + operations that should be added. + prepend: whether to add the new moment before the current one. + require_physical_tag: whether to only apply noise to operations tagged + with PHYSICAL_GATE_TAG. + """ + + ops_added: Dict[OpIdentifier, 'cirq.Operation'] = field(default_factory=dict) + prepend: bool = False + require_physical_tag: bool = True + + def noisy_moment( + self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid'] + ) -> 'cirq.OP_TREE': + noise_ops: List['cirq.Operation'] = [] + for op in moment: + if self.require_physical_tag and PHYSICAL_GATE_TAG not in op.tags: + # Only non-virtual gates get noise applied. + continue + op_id = OpIdentifier(type(op.gate), *op.qubits) + if op_id in self.ops_added: + noise_ops.append(self.ops_added[op_id]) + continue + # Find the closest match, if one exists. + parent_id = OpIdentifier(object, *op.qubits) + for added_id in self.ops_added: + if added_id.qubits != parent_id.qubits: + continue + if not issubclass(op_id.gate_type, added_id.gate_type): + continue + if issubclass(added_id.gate_type, parent_id.gate_type): + parent_id = added_id + if parent_id.gate_type != object: + noise_ops.append(self.ops_added[parent_id]) + if not noise_ops: + return [moment] + if self.prepend: + return [ops.Moment(noise_ops), moment] + return [moment, ops.Moment(noise_ops)] diff --git a/cirq-core/cirq/devices/insertion_noise_model_test.py b/cirq-core/cirq/devices/insertion_noise_model_test.py new file mode 100644 index 00000000000..cd11de19b18 --- /dev/null +++ b/cirq-core/cirq/devices/insertion_noise_model_test.py @@ -0,0 +1,104 @@ +# Copyright 2021 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 cirq +from cirq.devices.insertion_noise_model import InsertionNoiseModel +from cirq.devices.noise_utils import ( + PHYSICAL_GATE_TAG, + OpIdentifier, +) + + +def test_insertion_noise(): + q0, q1 = cirq.LineQubit.range(2) + op_id0 = OpIdentifier(cirq.XPowGate, q0) + op_id1 = OpIdentifier(cirq.PhasedXZGate, q1) + model = InsertionNoiseModel( + {op_id0: cirq.T(q0), op_id1: cirq.H(q1)}, require_physical_tag=False + ) + assert not model.prepend + + phased_xz = cirq.PhasedXZGate(x_exponent=1.0, z_exponent=0.5, axis_phase_exponent=0.25) + moment_0 = cirq.Moment(cirq.X(q0), cirq.X(q1)) + assert model.noisy_moment(moment_0, system_qubits=[q0, q1]) == [ + moment_0, + cirq.Moment(cirq.T(q0)), + ] + + moment_1 = cirq.Moment(phased_xz.on(q0), phased_xz.on(q1)) + assert model.noisy_moment(moment_1, system_qubits=[q0, q1]) == [ + moment_1, + cirq.Moment(cirq.H(q1)), + ] + + moment_2 = cirq.Moment(cirq.X(q0), phased_xz.on(q1)) + assert model.noisy_moment(moment_2, system_qubits=[q0, q1]) == [ + moment_2, + cirq.Moment(cirq.T(q0), cirq.H(q1)), + ] + + moment_3 = cirq.Moment(phased_xz.on(q0), cirq.X(q1)) + assert model.noisy_moment(moment_3, system_qubits=[q0, q1]) == [moment_3] + + +def test_prepend(): + q0, q1 = cirq.LineQubit.range(2) + op_id0 = OpIdentifier(cirq.XPowGate, q0) + op_id1 = OpIdentifier(cirq.ZPowGate, q1) + model = InsertionNoiseModel( + {op_id0: cirq.T(q0), op_id1: cirq.H(q1)}, prepend=True, require_physical_tag=False + ) + + moment_0 = cirq.Moment(cirq.X(q0), cirq.Z(q1)) + assert model.noisy_moment(moment_0, system_qubits=[q0, q1]) == [ + cirq.Moment(cirq.T(q0), cirq.H(q1)), + moment_0, + ] + + +def test_require_physical_tag(): + q0, q1 = cirq.LineQubit.range(2) + op_id0 = OpIdentifier(cirq.XPowGate, q0) + op_id1 = OpIdentifier(cirq.ZPowGate, q1) + model = InsertionNoiseModel({op_id0: cirq.T(q0), op_id1: cirq.H(q1)}) + assert model.require_physical_tag + + moment_0 = cirq.Moment(cirq.X(q0).with_tags(PHYSICAL_GATE_TAG), cirq.Z(q1)) + assert model.noisy_moment(moment_0, system_qubits=[q0, q1]) == [ + moment_0, + cirq.Moment(cirq.T(q0)), + ] + + +def test_supertype_matching(): + # Demonstrate that the model applies the closest matching type + # if multiple types match a given gate. + q0 = cirq.LineQubit(0) + op_id0 = OpIdentifier(cirq.Gate, q0) + op_id1 = OpIdentifier(cirq.XPowGate, q0) + model = InsertionNoiseModel( + {op_id0: cirq.T(q0), op_id1: cirq.S(q0)}, require_physical_tag=False + ) + + moment_0 = cirq.Moment(cirq.Rx(rads=1).on(q0)) + assert model.noisy_moment(moment_0, system_qubits=[q0]) == [ + moment_0, + cirq.Moment(cirq.S(q0)), + ] + + moment_1 = cirq.Moment(cirq.Y(q0)) + assert model.noisy_moment(moment_1, system_qubits=[q0]) == [ + moment_1, + cirq.Moment(cirq.T(q0)), + ] From 224ee36c8febac28a33a1b8b9ad1f70706adf75c Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Mon, 13 Dec 2021 14:09:50 -0800 Subject: [PATCH 6/7] Update to use new match methods --- .../cirq/devices/insertion_noise_model.py | 24 ++++++++----------- .../devices/insertion_noise_model_test.py | 9 ++++--- 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/cirq-core/cirq/devices/insertion_noise_model.py b/cirq-core/cirq/devices/insertion_noise_model.py index 6fc3d44b1cc..ed8409c3ca6 100644 --- a/cirq-core/cirq/devices/insertion_noise_model.py +++ b/cirq-core/cirq/devices/insertion_noise_model.py @@ -13,7 +13,7 @@ # limitations under the License. from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Dict, List, Sequence +from typing import TYPE_CHECKING, Dict, List, Optional, Sequence from cirq import devices, ops from cirq.devices.noise_utils import ( @@ -53,21 +53,17 @@ def noisy_moment( if self.require_physical_tag and PHYSICAL_GATE_TAG not in op.tags: # Only non-virtual gates get noise applied. continue - op_id = OpIdentifier(type(op.gate), *op.qubits) - if op_id in self.ops_added: - noise_ops.append(self.ops_added[op_id]) - continue - # Find the closest match, if one exists. - parent_id = OpIdentifier(object, *op.qubits) - for added_id in self.ops_added: - if added_id.qubits != parent_id.qubits: + match_id: Optional[OpIdentifier] = None + for op_id in self.ops_added: + if op not in op_id: continue - if not issubclass(op_id.gate_type, added_id.gate_type): + elif match_id is None: + match_id = op_id continue - if issubclass(added_id.gate_type, parent_id.gate_type): - parent_id = added_id - if parent_id.gate_type != object: - noise_ops.append(self.ops_added[parent_id]) + elif op_id.is_proper_subtype_of(match_id): + match_id = op_id + if match_id is not None: + noise_ops.append(self.ops_added[match_id]) if not noise_ops: return [moment] if self.prepend: diff --git a/cirq-core/cirq/devices/insertion_noise_model_test.py b/cirq-core/cirq/devices/insertion_noise_model_test.py index cd11de19b18..15216def58c 100644 --- a/cirq-core/cirq/devices/insertion_noise_model_test.py +++ b/cirq-core/cirq/devices/insertion_noise_model_test.py @@ -23,32 +23,31 @@ def test_insertion_noise(): q0, q1 = cirq.LineQubit.range(2) op_id0 = OpIdentifier(cirq.XPowGate, q0) - op_id1 = OpIdentifier(cirq.PhasedXZGate, q1) + op_id1 = OpIdentifier(cirq.ZPowGate, q1) model = InsertionNoiseModel( {op_id0: cirq.T(q0), op_id1: cirq.H(q1)}, require_physical_tag=False ) assert not model.prepend - phased_xz = cirq.PhasedXZGate(x_exponent=1.0, z_exponent=0.5, axis_phase_exponent=0.25) moment_0 = cirq.Moment(cirq.X(q0), cirq.X(q1)) assert model.noisy_moment(moment_0, system_qubits=[q0, q1]) == [ moment_0, cirq.Moment(cirq.T(q0)), ] - moment_1 = cirq.Moment(phased_xz.on(q0), phased_xz.on(q1)) + moment_1 = cirq.Moment(cirq.Z(q0), cirq.Z(q1)) assert model.noisy_moment(moment_1, system_qubits=[q0, q1]) == [ moment_1, cirq.Moment(cirq.H(q1)), ] - moment_2 = cirq.Moment(cirq.X(q0), phased_xz.on(q1)) + moment_2 = cirq.Moment(cirq.X(q0), cirq.Z(q1)) assert model.noisy_moment(moment_2, system_qubits=[q0, q1]) == [ moment_2, cirq.Moment(cirq.T(q0), cirq.H(q1)), ] - moment_3 = cirq.Moment(phased_xz.on(q0), cirq.X(q1)) + moment_3 = cirq.Moment(cirq.Z(q0), cirq.X(q1)) assert model.noisy_moment(moment_3, system_qubits=[q0, q1]) == [moment_3] From 4d460c20381e443d5a25f7868a501e9f30002f38 Mon Sep 17 00:00:00 2001 From: Orion Martin <40585662+95-martin-orion@users.noreply.github.com> Date: Tue, 14 Dec 2021 13:24:30 -0800 Subject: [PATCH 7/7] Apply review cleanup --- .../cirq/devices/insertion_noise_model.py | 35 +++++++++---------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/cirq-core/cirq/devices/insertion_noise_model.py b/cirq-core/cirq/devices/insertion_noise_model.py index ed8409c3ca6..6d6cf66a068 100644 --- a/cirq-core/cirq/devices/insertion_noise_model.py +++ b/cirq-core/cirq/devices/insertion_noise_model.py @@ -12,20 +12,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -from dataclasses import dataclass, field +import dataclasses from typing import TYPE_CHECKING, Dict, List, Optional, Sequence from cirq import devices, ops -from cirq.devices.noise_utils import ( - OpIdentifier, - PHYSICAL_GATE_TAG, -) +from cirq.devices import noise_utils if TYPE_CHECKING: import cirq -@dataclass +@dataclasses.dataclass class InsertionNoiseModel(devices.NoiseModel): """Simple base noise model for inserting operations. @@ -41,7 +38,9 @@ class InsertionNoiseModel(devices.NoiseModel): with PHYSICAL_GATE_TAG. """ - ops_added: Dict[OpIdentifier, 'cirq.Operation'] = field(default_factory=dict) + ops_added: Dict[noise_utils.OpIdentifier, 'cirq.Operation'] = dataclasses.field( + default_factory=dict + ) prepend: bool = False require_physical_tag: bool = True @@ -49,18 +48,16 @@ def noisy_moment( self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid'] ) -> 'cirq.OP_TREE': noise_ops: List['cirq.Operation'] = [] - for op in moment: - if self.require_physical_tag and PHYSICAL_GATE_TAG not in op.tags: - # Only non-virtual gates get noise applied. - continue - match_id: Optional[OpIdentifier] = None - for op_id in self.ops_added: - if op not in op_id: - continue - elif match_id is None: - match_id = op_id - continue - elif op_id.is_proper_subtype_of(match_id): + candidate_ops = [ + op + for op in moment + if (not self.require_physical_tag) or noise_utils.PHYSICAL_GATE_TAG in op.tags + ] + for op in candidate_ops: + match_id: Optional[noise_utils.OpIdentifier] = None + candidate_ids = [op_id for op_id in self.ops_added if op in op_id] + for op_id in candidate_ids: + if match_id is None or op_id.is_proper_subtype_of(match_id): match_id = op_id if match_id is not None: noise_ops.append(self.ops_added[match_id])