|
| 1 | +# Copyright 2023 The Cirq Developers |
| 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 | +# https://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 | +import functools |
| 15 | +import pytest |
| 16 | + |
| 17 | +import numpy as np |
| 18 | +from cirq.testing import sample_gates |
| 19 | +from cirq import protocols, ops |
| 20 | + |
| 21 | + |
| 22 | +@pytest.mark.parametrize('theta', np.linspace(0, 2 * np.pi, 20)) |
| 23 | +def test_GateThatAllocatesAQubit(theta: float): |
| 24 | + g = sample_gates.GateThatAllocatesAQubit(theta) |
| 25 | + |
| 26 | + want = np.array([[1, 0], [0, (-1 + 0j) ** theta]], dtype=np.complex128) |
| 27 | + # test unitary |
| 28 | + np.testing.assert_allclose(g.target_unitary(), want) |
| 29 | + |
| 30 | + # test decomposition |
| 31 | + np.testing.assert_allclose(protocols.unitary(g), g.target_unitary()) |
| 32 | + |
| 33 | + |
| 34 | +def test_GateThatAllocatesTwoQubits(): |
| 35 | + g = sample_gates.GateThatAllocatesTwoQubits() |
| 36 | + |
| 37 | + Z = np.array([[1, 0], [0, -1]]) |
| 38 | + want = -1j * np.kron(Z, Z) |
| 39 | + # test unitary |
| 40 | + np.testing.assert_allclose(g.target_unitary(), want) |
| 41 | + |
| 42 | + # test decomposition |
| 43 | + np.testing.assert_allclose(protocols.unitary(g), g.target_unitary()) |
| 44 | + |
| 45 | + |
| 46 | +@pytest.mark.parametrize('n', [*range(1, 6)]) |
| 47 | +@pytest.mark.parametrize('subgate', [ops.Z, ops.X, ops.Y, ops.T]) |
| 48 | +@pytest.mark.parametrize('theta', np.linspace(0, 2 * np.pi, 5)) |
| 49 | +def test_GateThatDecomposesIntoNGates(n: int, subgate: ops.Gate, theta: float): |
| 50 | + g = sample_gates.GateThatDecomposesIntoNGates(n, subgate, theta) |
| 51 | + |
| 52 | + U = np.array([[1, 0], [0, (-1 + 0j) ** theta]], dtype=np.complex128) |
| 53 | + want = functools.reduce(np.kron, [U] * n) |
| 54 | + # test unitary |
| 55 | + np.testing.assert_allclose(g.target_unitary(), want) |
| 56 | + |
| 57 | + # test decomposition |
| 58 | + np.testing.assert_allclose(protocols.unitary(g), g.target_unitary()) |
0 commit comments