forked from Qiskit/qiskit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp.py
401 lines (325 loc) · 12.6 KB
/
p.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Phase Gate."""
from __future__ import annotations
from cmath import exp
import numpy
from qiskit.circuit.controlledgate import ControlledGate
from qiskit.circuit.gate import Gate
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit.parameterexpression import ParameterValueType
class PhaseGate(Gate):
r"""Single-qubit rotation about the Z axis.
This is a diagonal gate. It can be implemented virtually in hardware
via framechanges (i.e. at zero error and duration).
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.p` method.
**Circuit symbol:**
.. parsed-literal::
┌──────┐
q_0: ┤ P(λ) ├
└──────┘
**Matrix Representation:**
.. math::
P(\lambda) =
\begin{pmatrix}
1 & 0 \\
0 & e^{i\lambda}
\end{pmatrix}
**Examples:**
.. math::
P(\lambda = \pi) = Z
.. math::
P(\lambda = \pi/2) = S
.. math::
P(\lambda = \pi/4) = T
.. seealso::
:class:`~qiskit.circuit.library.standard_gates.RZGate`:
This gate is equivalent to RZ up to a phase factor.
.. math::
P(\lambda) = e^{i{\lambda}/2} RZ(\lambda)
Reference for virtual Z gate implementation:
`1612.00858 <https://arxiv.org/abs/1612.00858>`_
"""
def __init__(
self, theta: ParameterValueType, label: str | None = None, *, duration=None, unit="dt"
):
"""Create new Phase gate."""
super().__init__("p", 1, [theta], label=label, duration=duration, unit=unit)
def _define(self):
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .u import UGate
q = QuantumRegister(1, "q")
qc = QuantumCircuit(q, name=self.name)
qc.append(UGate(0, 0, self.params[0]), [0])
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: str | None = None,
ctrl_state: str | int | None = None,
annotated: bool = False,
):
"""Return a (multi-)controlled-Phase gate.
Args:
num_ctrl_qubits (int): number of control qubits.
label (str or None): An optional label for the gate [Default: None]
ctrl_state (int or str or None): control state expressed as integer,
string (e.g. '110'), or None. If None, use all 1s.
annotated: indicates whether the controlled gate can be implemented
as an annotated gate.
Returns:
ControlledGate: controlled version of this gate.
"""
if not annotated and num_ctrl_qubits == 1:
gate = CPhaseGate(self.params[0], label=label, ctrl_state=ctrl_state)
gate.base_gate.label = self.label
elif not annotated and ctrl_state is None and num_ctrl_qubits > 1:
gate = MCPhaseGate(self.params[0], num_ctrl_qubits, label=label)
gate.base_gate.label = self.label
else:
gate = super().control(
num_ctrl_qubits=num_ctrl_qubits,
label=label,
ctrl_state=ctrl_state,
annotated=annotated,
)
return gate
def inverse(self):
r"""Return inverted Phase gate (:math:`Phase(\lambda)^{\dagger} = Phase(-\lambda)`)"""
return PhaseGate(-self.params[0])
def __array__(self, dtype=None):
"""Return a numpy.array for the Phase gate."""
lam = float(self.params[0])
return numpy.array([[1, 0], [0, exp(1j * lam)]], dtype=dtype)
def power(self, exponent: float):
"""Raise gate to a power."""
(theta,) = self.params
return PhaseGate(exponent * theta)
def __eq__(self, other):
if isinstance(other, PhaseGate):
return self._compare_parameters(other)
return False
class CPhaseGate(ControlledGate):
r"""Controlled-Phase gate.
This is a diagonal and symmetric gate that induces a
phase on the state of the target qubit, depending on the control state.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.cp` method.
**Circuit symbol:**
.. parsed-literal::
q_0: ─■──
│λ
q_1: ─■──
**Matrix representation:**
.. math::
CPhase =
I \otimes |0\rangle\langle 0| + P \otimes |1\rangle\langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 1 & 0 \\
0 & 0 & 0 & e^{i\lambda}
\end{pmatrix}
.. seealso::
:class:`~qiskit.circuit.library.standard_gates.CRZGate`:
Due to the global phase difference in the matrix definitions
of Phase and RZ, CPhase and CRZ are different gates with a relative
phase difference.
"""
def __init__(
self,
theta: ParameterValueType,
label: str | None = None,
ctrl_state: str | int | None = None,
*,
duration=None,
unit="dt",
_base_label=None,
):
"""Create new CPhase gate."""
super().__init__(
"cp",
2,
[theta],
num_ctrl_qubits=1,
label=label,
ctrl_state=ctrl_state,
base_gate=PhaseGate(theta, label=_base_label),
duration=duration,
unit=unit,
)
def _define(self):
"""
gate cphase(lambda) a,b
{ phase(lambda/2) a; cx a,b;
phase(-lambda/2) b; cx a,b;
phase(lambda/2) b;
}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
# ┌────────┐
# q_0: ┤ P(λ/2) ├──■───────────────■────────────
# └────────┘┌─┴─┐┌─────────┐┌─┴─┐┌────────┐
# q_1: ──────────┤ X ├┤ P(-λ/2) ├┤ X ├┤ P(λ/2) ├
# └───┘└─────────┘└───┘└────────┘
q = QuantumRegister(2, "q")
qc = QuantumCircuit(q, name=self.name)
qc.p(self.params[0] / 2, 0)
qc.cx(0, 1)
qc.p(-self.params[0] / 2, 1)
qc.cx(0, 1)
qc.p(self.params[0] / 2, 1)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: str | None = None,
ctrl_state: str | int | None = None,
annotated: bool = False,
):
"""Controlled version of this gate.
Args:
num_ctrl_qubits (int): number of control qubits.
label (str or None): An optional label for the gate [Default: None]
ctrl_state (int or str or None): control state expressed as integer,
string (e.g. '110'), or None. If None, use all 1s.
annotated: indicates whether the controlled gate can be implemented
as an annotated gate.
Returns:
ControlledGate: controlled version of this gate.
"""
if not annotated and ctrl_state is None:
gate = MCPhaseGate(self.params[0], num_ctrl_qubits=num_ctrl_qubits + 1, label=label)
gate.base_gate.label = self.label
else:
gate = super().control(
num_ctrl_qubits=num_ctrl_qubits,
label=label,
ctrl_state=ctrl_state,
annotated=annotated,
)
return gate
def inverse(self):
r"""Return inverted CPhase gate (:math:`CPhase(\lambda)^{\dagger} = CPhase(-\lambda)`)"""
return CPhaseGate(-self.params[0], ctrl_state=self.ctrl_state)
def __array__(self, dtype=None):
"""Return a numpy.array for the CPhase gate."""
eith = exp(1j * float(self.params[0]))
if self.ctrl_state:
return numpy.array(
[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, eith]], dtype=dtype
)
return numpy.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, eith, 0], [0, 0, 0, 1]], dtype=dtype)
def power(self, exponent: float):
"""Raise gate to a power."""
(theta,) = self.params
return CPhaseGate(exponent * theta)
def __eq__(self, other):
if isinstance(other, CPhaseGate):
return self._compare_parameters(other) and self.ctrl_state == other.ctrl_state
return False
class MCPhaseGate(ControlledGate):
r"""Multi-controlled-Phase gate.
This is a diagonal and symmetric gate that induces a
phase on the state of the target qubit, depending on the state of the control qubits.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.mcp` method.
**Circuit symbol:**
.. parsed-literal::
q_0: ───■────
│
.
│
q_(n-1): ───■────
┌──┴───┐
q_n: ┤ P(λ) ├
└──────┘
.. seealso::
:class:`~qiskit.circuit.library.standard_gates.CPhaseGate`:
The singly-controlled-version of this gate.
"""
def __init__(
self,
lam: ParameterValueType,
num_ctrl_qubits: int,
label: str | None = None,
*,
duration=None,
unit="dt",
_base_label=None,
):
"""Create new MCPhase gate."""
super().__init__(
"mcphase",
num_ctrl_qubits + 1,
[lam],
num_ctrl_qubits=num_ctrl_qubits,
label=label,
base_gate=PhaseGate(lam, label=_base_label),
duration=duration,
unit=unit,
)
def _define(self):
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
q = QuantumRegister(self.num_qubits, "q")
qc = QuantumCircuit(q, name=self.name)
if self.num_ctrl_qubits == 0:
qc.p(self.params[0], 0)
if self.num_ctrl_qubits == 1:
qc.cp(self.params[0], 0, 1)
else:
from .u3 import _gray_code_chain
scaled_lam = self.params[0] / (2 ** (self.num_ctrl_qubits - 1))
bottom_gate = CPhaseGate(scaled_lam)
for operation, qubits, clbits in _gray_code_chain(q, self.num_ctrl_qubits, bottom_gate):
qc._append(operation, qubits, clbits)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: str | None = None,
ctrl_state: str | int | None = None,
annotated: bool = False,
):
"""Controlled version of this gate.
Args:
num_ctrl_qubits (int): number of control qubits.
label (str or None): An optional label for the gate [Default: None]
ctrl_state (int or str or None): control state expressed as integer,
string (e.g. '110'), or None. If None, use all 1s.
annotated: indicates whether the controlled gate can be implemented
as an annotated gate.
Returns:
ControlledGate: controlled version of this gate.
"""
if not annotated and ctrl_state is None:
gate = MCPhaseGate(
self.params[0],
num_ctrl_qubits=num_ctrl_qubits + self.num_ctrl_qubits,
label=label,
)
gate.base_gate.label = self.label
else:
gate = super().control(
num_ctrl_qubits=num_ctrl_qubits,
label=label,
ctrl_state=ctrl_state,
annotated=annotated,
)
return gate
def inverse(self):
r"""Return inverted MCU1 gate (:math:`MCU1(\lambda)^{\dagger} = MCU1(-\lambda)`)"""
return MCPhaseGate(-self.params[0], self.num_ctrl_qubits)