forked from quantumlib/Cirq
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathglobal_phase_op_test.py
302 lines (243 loc) · 9.58 KB
/
global_phase_op_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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# Copyright 2019 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 sympy
import cirq
def test_init():
op = cirq.global_phase_operation(1j)
assert op.gate.coefficient == 1j
assert op.qubits == ()
assert op.with_qubits() == op
assert cirq.has_stabilizer_effect(op)
with pytest.raises(ValueError, match='not unitary'):
_ = cirq.global_phase_operation(2)
with pytest.raises(ValueError, match='0 qubits'):
_ = cirq.global_phase_operation(1j).with_qubits(cirq.LineQubit(0))
def test_protocols():
for p in [1, 1j, -1]:
cirq.testing.assert_implements_consistent_protocols(cirq.global_phase_operation(p))
np.testing.assert_allclose(
cirq.unitary(cirq.global_phase_operation(1j)), np.array([[1j]]), atol=1e-8
)
@pytest.mark.parametrize('phase', [1, 1j, -1])
def test_act_on_tableau(phase):
original_tableau = cirq.CliffordTableau(0)
args = cirq.CliffordTableauSimulationState(original_tableau.copy(), np.random.RandomState())
cirq.act_on(cirq.global_phase_operation(phase), args, allow_decompose=False)
assert args.tableau == original_tableau
@pytest.mark.parametrize('phase', [1, 1j, -1])
def test_act_on_ch_form(phase):
state = cirq.StabilizerStateChForm(0)
args = cirq.StabilizerChFormSimulationState(
qubits=[], prng=np.random.RandomState(), initial_state=state
)
cirq.act_on(cirq.global_phase_operation(phase), args, allow_decompose=False)
assert state.state_vector() == [[phase]]
def test_str():
assert str(cirq.global_phase_operation(1j)) == '1j'
def test_repr():
op = cirq.global_phase_operation(1j)
cirq.testing.assert_equivalent_repr(op)
def test_diagram():
a, b = cirq.LineQubit.range(2)
x, y = cirq.LineQubit.range(10, 12)
cirq.testing.assert_has_diagram(
cirq.Circuit(
[cirq.Moment([cirq.CNOT(a, x), cirq.CNOT(b, y), cirq.global_phase_operation(-1)])]
),
"""
┌──┐
0: ──────────────@─────
│
1: ──────────────┼@────
││
10: ─────────────X┼────
│
11: ──────────────X────
global phase: π
└──┘
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit(
[
cirq.Moment(
[
cirq.CNOT(a, x),
cirq.CNOT(b, y),
cirq.global_phase_operation(-1),
cirq.global_phase_operation(-1),
]
)
]
),
"""
┌──┐
0: ──────────────@─────
│
1: ──────────────┼@────
││
10: ─────────────X┼────
│
11: ──────────────X────
global phase:
└──┘
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit(
[
cirq.Moment(
[
cirq.CNOT(a, x),
cirq.CNOT(b, y),
cirq.global_phase_operation(-1),
cirq.global_phase_operation(-1),
]
),
cirq.Moment([cirq.global_phase_operation(1j)]),
cirq.Moment([cirq.X(a)]),
]
),
"""
┌──┐
0: ──────────────@────────────X───
│
1: ──────────────┼@───────────────
││
10: ─────────────X┼───────────────
│
11: ──────────────X───────────────
global phase: 0.5π
└──┘
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit([cirq.Moment([cirq.X(a)]), cirq.Moment([cirq.global_phase_operation(-1j)])]),
"""
0: ─────────────X───────────
global phase: -0.5π
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit([cirq.Moment([cirq.X(a), cirq.global_phase_operation(np.exp(1j))])]),
"""
0: ─────────────X────────
global phase: 0.318π
""",
)
cirq.testing.assert_has_diagram(
cirq.Circuit([cirq.Moment([cirq.X(a), cirq.global_phase_operation(np.exp(1j))])]),
"""
0: ─────────────X──────────
global phase: 0.31831π
""",
precision=5,
)
cirq.testing.assert_has_diagram(
cirq.Circuit(
[
cirq.Moment([cirq.X(a), cirq.global_phase_operation(1j)]),
cirq.Moment([cirq.global_phase_operation(-1j)]),
]
),
"""
0: -------------X----------------
global phase: 0.5pi -0.5pi
""",
use_unicode_characters=False,
)
cirq.testing.assert_has_diagram(
cirq.Circuit([cirq.Moment([cirq.global_phase_operation(-1j)])]),
"""
global phase: -0.5π
""",
)
def test_gate_init():
gate = cirq.GlobalPhaseGate(1j)
assert gate.coefficient == 1j
assert isinstance(gate.on(), cirq.GateOperation)
assert gate.on().gate == gate
assert cirq.has_stabilizer_effect(gate)
with pytest.raises(ValueError, match='Coefficient is not unitary'):
_ = cirq.GlobalPhaseGate(2)
with pytest.raises(ValueError, match='Wrong number of qubits'):
_ = gate.on(cirq.LineQubit(0))
def test_gate_protocols():
for p in [1, 1j, -1]:
cirq.testing.assert_implements_consistent_protocols(cirq.GlobalPhaseGate(p))
np.testing.assert_allclose(cirq.unitary(cirq.GlobalPhaseGate(1j)), np.array([[1j]]), atol=1e-8)
@pytest.mark.parametrize('phase', [1, 1j, -1])
def test_gate_act_on_tableau(phase):
original_tableau = cirq.CliffordTableau(0)
args = cirq.CliffordTableauSimulationState(original_tableau.copy(), np.random.RandomState())
cirq.act_on(cirq.GlobalPhaseGate(phase), args, qubits=(), allow_decompose=False)
assert args.tableau == original_tableau
@pytest.mark.parametrize('phase', [1, 1j, -1])
def test_gate_act_on_ch_form(phase):
state = cirq.StabilizerStateChForm(0)
args = cirq.StabilizerChFormSimulationState(
qubits=[], prng=np.random.RandomState(), initial_state=state
)
cirq.act_on(cirq.GlobalPhaseGate(phase), args, qubits=(), allow_decompose=False)
assert state.state_vector() == [[phase]]
def test_gate_str():
assert str(cirq.GlobalPhaseGate(1j)) == '1j'
def test_gate_repr():
gate = cirq.GlobalPhaseGate(1j)
cirq.testing.assert_equivalent_repr(gate)
def test_gate_op_repr():
gate = cirq.GlobalPhaseGate(1j)
cirq.testing.assert_equivalent_repr(gate.on())
def test_gate_global_phase_op_json_dict():
assert cirq.GlobalPhaseGate(-1j)._json_dict_() == {'coefficient': -1j}
def test_parameterization():
t = sympy.Symbol('t')
gpt = cirq.GlobalPhaseGate(coefficient=t)
assert cirq.is_parameterized(gpt)
assert cirq.parameter_names(gpt) == {'t'}
assert not cirq.has_unitary(gpt)
assert gpt.coefficient == t
assert (gpt**2).coefficient == t**2
@pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once])
def test_resolve(resolve_fn):
t = sympy.Symbol('t')
gpt = cirq.GlobalPhaseGate(coefficient=t)
assert resolve_fn(gpt, {'t': -1}) == cirq.GlobalPhaseGate(coefficient=-1)
@pytest.mark.parametrize('resolve_fn', [cirq.resolve_parameters, cirq.resolve_parameters_once])
def test_resolve_error(resolve_fn):
t = sympy.Symbol('t')
gpt = cirq.GlobalPhaseGate(coefficient=t)
with pytest.raises(ValueError, match='Coefficient is not unitary'):
resolve_fn(gpt, {'t': -2})
@pytest.mark.parametrize(
'coeff, exp', [(-1, 1), (1j, 0.5), (-1j, -0.5), (1 / np.sqrt(2) * (1 + 1j), 0.25)]
)
def test_global_phase_gate_controlled(coeff, exp):
g = cirq.GlobalPhaseGate(coeff)
op = cirq.global_phase_operation(coeff)
q = cirq.LineQubit.range(3)
for num_controls, target_gate in zip(range(1, 4), [cirq.Z, cirq.CZ, cirq.CCZ]):
assert g.controlled(num_controls) == target_gate**exp
np.testing.assert_allclose(
cirq.unitary(cirq.ControlledGate(g, num_controls)),
cirq.unitary(g.controlled(num_controls)),
)
assert op.controlled_by(*q[:num_controls]) == target_gate(*q[:num_controls]) ** exp
assert g.controlled(control_values=[0]) == cirq.ControlledGate(g, control_values=[0])
xor_control_values = cirq.SumOfProducts(((0, 0), (1, 1)))
assert g.controlled(control_values=xor_control_values) == cirq.ControlledGate(
g, control_values=xor_control_values
)