-
Notifications
You must be signed in to change notification settings - Fork 975
/
and_gate_test.py
225 lines (197 loc) · 9.21 KB
/
and_gate_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# Copyright 2023 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 itertools
import random
from typing import List, Tuple
import cirq
import cirq_ft
import numpy as np
import pytest
from cirq_ft.infra.jupyter_tools import execute_notebook
random.seed(12345)
@pytest.mark.parametrize("cv", [(0, 0), (0, 1), (1, 0), (1, 1)])
def test_and_gate(cv: Tuple[int, int]):
c1, c2, t = cirq.LineQubit.range(3)
input_states = [(0, 0, 0), (0, 1, 0), (1, 0, 0), (1, 1, 0)]
output_states = [inp[:2] + (1 if inp[:2] == cv else 0,) for inp in input_states]
and_gate = cirq_ft.And(cv)
circuit = cirq.Circuit(and_gate.on(c1, c2, t))
for inp, out in zip(input_states, output_states):
cirq_ft.testing.assert_circuit_inp_out_cirqsim(circuit, [c1, c2, t], inp, out)
def random_cv(n: int) -> List[int]:
return [random.randint(0, 1) for _ in range(n)]
@pytest.mark.parametrize("cv", [[1] * 3, random_cv(5), random_cv(6), random_cv(7)])
def test_multi_controlled_and_gate(cv: List[int]):
gate = cirq_ft.And(cv)
r = gate.registers
assert r['ancilla'].total_bits() == r['control'].total_bits() - 2
quregs = r.get_named_qubits()
and_op = gate.on_registers(**quregs)
circuit = cirq.Circuit(and_op)
input_controls = [cv] + [random_cv(len(cv)) for _ in range(10)]
qubit_order = gate.registers.merge_qubits(**quregs)
for input_control in input_controls:
initial_state = input_control + [0] * (r['ancilla'].total_bits() + 1)
result = cirq.Simulator(dtype=np.complex128).simulate(
circuit, initial_state=initial_state, qubit_order=qubit_order
)
expected_output = np.asarray([0, 1] if input_control == cv else [1, 0])
assert cirq.equal_up_to_global_phase(
cirq.sub_state_vector(
result.final_state_vector, keep_indices=[cirq.num_qubits(gate) - 1]
),
expected_output,
)
# Test adjoint.
cirq_ft.testing.assert_circuit_inp_out_cirqsim(
circuit + cirq.Circuit(cirq.inverse(and_op)),
qubit_order=qubit_order,
inputs=initial_state,
outputs=initial_state,
)
def test_and_gate_diagram():
gate = cirq_ft.And((1, 0, 1, 0, 1, 0))
qubit_regs = gate.registers.get_named_qubits()
op = gate.on_registers(**qubit_regs)
# Qubit order should be alternating (control, ancilla) pairs.
c_and_a = sum(zip(qubit_regs["control"][1:], qubit_regs["ancilla"]), ()) + (
qubit_regs["control"][-1],
)
qubit_order = np.concatenate([qubit_regs["control"][0:1], c_and_a, qubit_regs["target"]])
# Test diagrams.
cirq.testing.assert_has_diagram(
cirq.Circuit(op),
"""
control0: ───@─────
│
control1: ───(0)───
│
ancilla0: ───Anc───
│
control2: ───@─────
│
ancilla1: ───Anc───
│
control3: ───(0)───
│
ancilla2: ───Anc───
│
control4: ───@─────
│
ancilla3: ───Anc───
│
control5: ───(0)───
│
target: ─────And───
""",
qubit_order=qubit_order,
)
cirq.testing.assert_has_diagram(
cirq.Circuit(op**-1),
"""
control0: ───@──────
│
control1: ───(0)────
│
ancilla0: ───Anc────
│
control2: ───@──────
│
ancilla1: ───Anc────
│
control3: ───(0)────
│
ancilla2: ───Anc────
│
control4: ───@──────
│
ancilla3: ───Anc────
│
control5: ───(0)────
│
target: ─────And†───
""",
qubit_order=qubit_order,
)
# Test diagram of decomposed 3-qubit and ladder.
decomposed_circuit = cirq.Circuit(cirq.decompose_once(op)) + cirq.Circuit(
cirq.decompose_once(op**-1)
)
cirq.testing.assert_has_diagram(
decomposed_circuit,
"""
control0: ───@─────────────────────────────────────────────────────────@──────
│ │
control1: ───(0)───────────────────────────────────────────────────────(0)────
│ │
ancilla0: ───And───@────────────────────────────────────────────@──────And†───
│ │
control2: ─────────@────────────────────────────────────────────@─────────────
│ │
ancilla1: ─────────And───@───────────────────────────────@──────And†──────────
│ │
control3: ───────────────(0)─────────────────────────────(0)──────────────────
│ │
ancilla2: ───────────────And───@──────────────────@──────And†─────────────────
│ │
control4: ─────────────────────@──────────────────@───────────────────────────
│ │
ancilla3: ─────────────────────And───@─────@──────And†────────────────────────
│ │
control5: ───────────────────────────(0)───(0)────────────────────────────────
│ │
target: ─────────────────────────────And───And†───────────────────────────────
""",
qubit_order=qubit_order,
)
@pytest.mark.parametrize(
"cv, adjoint, str_output",
[
((1, 1, 1), False, "And"),
((1, 0, 1), False, "And(1, 0, 1)"),
((1, 1, 1), True, "And†"),
((1, 0, 1), True, "And†(1, 0, 1)"),
],
)
def test_and_gate_str_and_repr(cv, adjoint, str_output):
gate = cirq_ft.And(cv, adjoint=adjoint)
assert str(gate) == str_output
cirq.testing.assert_equivalent_repr(gate, setup_code="import cirq_ft\n")
@pytest.mark.parametrize("cv", [(0, 0), (0, 1), (1, 0), (1, 1)])
def test_and_gate_adjoint(cv: Tuple[int, int]):
c1, c2, t = cirq.LineQubit.range(3)
all_cvs = [(0, 0), (0, 1), (1, 0), (1, 1)]
input_states = [inp + (1 if inp == cv else 0,) for inp in all_cvs]
output_states = [inp + (0,) for inp in all_cvs]
circuit = cirq.Circuit(cirq_ft.And(cv, adjoint=True).on(c1, c2, t))
for inp, out in zip(input_states, output_states):
cirq_ft.testing.assert_circuit_inp_out_cirqsim(circuit, [c1, c2, t], inp, out)
def test_notebook():
execute_notebook('and_gate')
@pytest.mark.parametrize(
"cv", [*itertools.chain(*[itertools.product(range(2), repeat=n) for n in range(2, 7 + 1)])]
)
@pytest.mark.parametrize("adjoint", [*range(2)])
def test_t_complexity(cv, adjoint):
gate = cirq_ft.And(cv=cv, adjoint=adjoint)
cirq_ft.testing.assert_decompose_is_consistent_with_t_complexity(gate)
def test_and_gate_raises():
with pytest.raises(ValueError, match="at-least 2 control values"):
_ = cirq_ft.And(cv=(1,))
def test_and_gate_power():
cv = (1, 0)
and_gate = cirq_ft.And(cv)
assert and_gate**1 is and_gate
assert and_gate**-1 == cirq_ft.And(cv, adjoint=True)
assert (and_gate**-1) ** -1 == cirq_ft.And(cv)