-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathcommon_gates.py
1469 lines (1212 loc) · 53.4 KB
/
common_gates.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2018 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.
"""Quantum gates that are commonly used in the literature.
This module creates Gate instances for the following gates:
X,Y,Z: Pauli gates.
H,S: Clifford gates.
T: A non-Clifford gate.
CZ: Controlled phase gate.
CNOT: Controlled not gate.
Each of these are implemented as EigenGates, which means that they can be
raised to a power (i.e. cirq.H**0.5). See the definition in EigenGate.
"""
from typing import (
Any,
cast,
Collection,
List,
Dict,
Optional,
Sequence,
Tuple,
TYPE_CHECKING,
Union,
)
import numpy as np
import sympy
import cirq
from cirq import protocols, value
from cirq._compat import proper_repr
from cirq._doc import document
from cirq.ops import controlled_gate, eigen_gate, gate_features, raw_types, control_values as cv
from cirq.type_workarounds import NotImplementedType
from cirq.ops.swap_gates import ISWAP, SWAP, ISwapPowGate, SwapPowGate
from cirq.ops.measurement_gate import MeasurementGate
if TYPE_CHECKING:
import cirq
assert all(
[ISWAP, SWAP, ISwapPowGate, SwapPowGate, MeasurementGate]
), """
Included for compatibility. Please continue to use top-level cirq.{thing}
imports.
"""
def _pi(rads):
return sympy.pi if protocols.is_parameterized(rads) else np.pi
@value.value_equality
class XPowGate(eigen_gate.EigenGate):
r"""A gate that rotates around the X axis of the Bloch sphere.
The unitary matrix of `cirq.XPowGate(exponent=t, global_shift=s)` is:
$$
e^{i \pi s t}
\begin{bmatrix}
e^{i \pi t /2} \cos(\pi t) & -i e^{i \pi t /2} \sin(\pi t) \\
-i e^{i \pi t /2} \sin(\pi t) & e^{i \pi t /2} \cos(\pi t)
\end{bmatrix}
$$
Note in particular that this gate has a global phase factor of
$e^{i \pi t / 2}$ vs the traditionally defined rotation matrices
about the Pauli X axis. See `cirq.Rx` for rotations without the global
phase. The global phase factor can be adjusted by using the `global_shift`
parameter when initializing.
`cirq.X`, the Pauli X gate, is an instance of this gate at `exponent=1`.
"""
_eigencomponents: Dict[int, List[Tuple[float, np.ndarray]]] = {}
def __init__(
self, *, exponent: value.TParamVal = 1.0, global_shift: float = 0.0, dimension: int = 2
):
"""Initialize an XPowGate.
Args:
exponent: The t in gate**t. Determines how much the eigenvalues of
the gate are phased by. For example, eigenvectors phased by -1
when `gate**1` is applied will gain a relative phase of
e^{i pi exponent} when `gate**exponent` is applied (relative to
eigenvectors unaffected by `gate**1`).
global_shift: Offsets the eigenvalues of the gate at exponent=1.
In effect, this controls a global phase factor on the gate's
unitary matrix. The factor for global_shift=s is:
exp(i * pi * s * t)
For example, `cirq.X**t` uses a `global_shift` of 0 but
`cirq.rx(t)` uses a `global_shift` of -0.5, which is why
`cirq.unitary(cirq.rx(pi))` equals -iX instead of X.
dimension: Qudit dimension of this gate. For qu*b*its (the default),
this is set to 2.
Raises:
ValueError: If the supplied exponent is a complex number with an
imaginary component.
"""
super().__init__(exponent=exponent, global_shift=global_shift)
self._dimension = dimension
def _num_qubits_(self) -> int:
return 1
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> Optional[np.ndarray]:
if self._exponent != 1 or self._dimension != 2:
return NotImplemented
zero = args.subspace_index(0)
one = args.subspace_index(1)
args.available_buffer[zero] = args.target_tensor[one]
args.available_buffer[one] = args.target_tensor[zero]
p = 1j ** (2 * self._exponent * self._global_shift)
if p != 1:
args.available_buffer *= p
return args.available_buffer
def in_su2(self) -> 'Rx':
"""Returns an equal-up-global-phase gate from the group SU2."""
return Rx(rads=self._exponent * _pi(self._exponent))
def with_canonical_global_phase(self) -> 'XPowGate':
"""Returns an equal-up-global-phase standardized form of the gate."""
return XPowGate(exponent=self._exponent, dimension=self._dimension)
def _qid_shape_(self) -> Tuple[int, ...]:
return (self._dimension,)
def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:
if self._dimension not in XPowGate._eigencomponents:
components = []
root = 1j ** (4 / self._dimension)
for i in range(self._dimension):
half_turns = i * 2 / self._dimension
v = np.array([root ** (i * j) / self._dimension for j in range(self._dimension)])
m = np.array([np.roll(v, j) for j in range(self._dimension)])
components.append((half_turns, m))
XPowGate._eigencomponents[self._dimension] = components
return XPowGate._eigencomponents[self._dimension]
def _with_exponent(self, exponent: 'cirq.TParamVal') -> 'cirq.XPowGate':
return XPowGate(
exponent=exponent, global_shift=self._global_shift, dimension=self._dimension
)
def _decompose_into_clifford_with_qubits_(self, qubits):
from cirq.ops.clifford_gate import SingleQubitCliffordGate
if self.exponent % 2 == 0:
return []
if self.exponent % 2 == 0.5:
return SingleQubitCliffordGate.X_sqrt.on(*qubits)
if self.exponent % 2 == 1:
return SingleQubitCliffordGate.X.on(*qubits)
if self.exponent % 2 == 1.5:
return SingleQubitCliffordGate.X_nsqrt.on(*qubits)
return NotImplemented
def _trace_distance_bound_(self) -> Optional[float]:
if self._is_parameterized_() or self._dimension != 2:
return None
return abs(np.sin(self._exponent * 0.5 * np.pi))
def controlled(
self,
num_controls: int = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
control_qid_shape: Optional[Tuple[int, ...]] = None,
) -> raw_types.Gate:
"""Returns a controlled `XPowGate`, using a `CXPowGate` where possible.
The `controlled` method of the `Gate` class, of which this class is a
child, returns a `ControlledGate`. This method overrides this behavior
to return a `CXPowGate` or a `ControlledGate` of a `CXPowGate`, when
this is possible.
The conditions for the override to occur are:
* The `global_shift` of the `XPowGate` is 0.
* The `control_values` and `control_qid_shape` are compatible with
the `CXPowGate`:
* The last value of `control_qid_shape` is a qubit.
* The last value of `control_values` corresponds to the
control being satisfied if that last qubit is 1 and
not satisfied if the last qubit is 0.
If these conditions are met, then the returned object is a `CXPowGate`
or, in the case that there is more than one controlled qudit, a
`ControlledGate` with the `Gate` being a `CXPowGate`. In the
latter case the `ControlledGate` is controlled by one less qudit
than specified in `control_values` and `control_qid_shape` (since
one of these, the last qubit, is used as the control for the
`CXPowGate`).
If the above conditions are not met, a `ControlledGate` of this
gate will be returned.
Args:
num_controls: Total number of control qubits.
control_values: Which control computational basis state to apply the
sub gate. A sequence of length `num_controls` where each
entry is an integer (or set of integers) corresponding to the
computational basis state (or set of possible values) where that
control is enabled. When all controls are enabled, the sub gate is
applied. If unspecified, control values default to 1.
control_qid_shape: The qid shape of the controls. A tuple of the
expected dimension of each control qid. Defaults to
`(2,) * num_controls`. Specify this argument when using qudits.
Returns:
A `cirq.ControlledGate` (or `cirq.CXPowGate` if possible) representing
`self` controlled by the given control values and qubits.
"""
result = super().controlled(num_controls, control_values, control_qid_shape)
if (
self._global_shift == 0
and isinstance(result, controlled_gate.ControlledGate)
and result.control_values[-1] == (1,)
and result.control_qid_shape[-1] == 2
):
return cirq.CXPowGate(
exponent=self._exponent, global_shift=self._global_shift
).controlled(
result.num_controls() - 1, result.control_values[:-1], result.control_qid_shape[:-1]
)
return result
def _pauli_expansion_(self) -> value.LinearDict[str]:
if protocols.is_parameterized(self) or self._dimension != 2:
return NotImplemented
phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5))
angle = np.pi * self._exponent / 2
return value.LinearDict({'I': phase * np.cos(angle), 'X': -1j * phase * np.sin(angle)})
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
return protocols.CircuitDiagramInfo(
wire_symbols=('X',), exponent=self._diagram_exponent(args)
)
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
if self._global_shift == 0:
if self._exponent == 1:
return args.format('x {0};\n', qubits[0])
elif self._exponent == 0.5:
return args.format('sx {0};\n', qubits[0])
elif self._exponent == -0.5:
return args.format('sxdg {0};\n', qubits[0])
return args.format('rx({0:half_turns}) {1};\n', self._exponent, qubits[0])
@property
def phase_exponent(self):
return 0.0
def _phase_by_(self, phase_turns, qubit_index):
"""See `cirq.SupportsPhase`."""
return cirq.ops.phased_x_gate.PhasedXPowGate(
exponent=self._exponent, phase_exponent=phase_turns * 2
)
def _has_stabilizer_effect_(self) -> Optional[bool]:
if self._is_parameterized_() or self._dimension != 2:
return None
return self.exponent % 0.5 == 0
def __str__(self) -> str:
if self._global_shift == 0:
if self._exponent == 1:
return 'X'
return f'X**{self._exponent}'
return f'XPowGate(exponent={self._exponent}, global_shift={self._global_shift!r})'
def __repr__(self) -> str:
if self._global_shift == 0 and self._dimension == 2:
if self._exponent == 1:
return 'cirq.X'
return f'(cirq.X**{proper_repr(self._exponent)})'
args = []
if self._exponent != 1:
args.append(f'exponent={proper_repr(self._exponent)}')
if self._global_shift != 0:
args.append(f'global_shift={self._global_shift}')
if self._dimension != 2:
args.append(f'dimension={self._dimension}')
all_args = ', '.join(args)
return f'cirq.XPowGate({all_args})'
class Rx(XPowGate):
r"""A gate with matrix $e^{-i X t/2}$ that rotates around the X axis of the Bloch sphere by $t$.
The unitary matrix of `cirq.Rx(rads=t)` is:
$$
e^{-i X t /2} =
\begin{bmatrix}
\cos(t/2) & -i \sin(t/2) \\
-i \sin(t/2) & \cos(t/2)
\end{bmatrix}
$$
This gate corresponds to the traditionally defined rotation matrices about the Pauli X axis.
"""
def __init__(self, *, rads: value.TParamVal):
"""Initialize an Rx (`cirq.XPowGate`).
Args:
rads: Radians to rotate about the X axis of the Bloch sphere.
"""
self._rads = rads
super().__init__(exponent=rads / _pi(rads), global_shift=-0.5)
def _with_exponent(self: 'Rx', exponent: value.TParamVal) -> 'Rx':
return Rx(rads=exponent * _pi(exponent))
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
angle_str = self._format_exponent_as_angle(args)
return f'Rx({angle_str})'
def __str__(self) -> str:
if self._exponent == 1:
return 'Rx(π)'
return f'Rx({self._exponent}π)'
def __repr__(self) -> str:
return f'cirq.Rx(rads={proper_repr(self._rads)})'
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
return args.format('rx({0:half_turns}) {1};\n', self._exponent, qubits[0])
def _json_dict_(self) -> Dict[str, Any]:
return {'rads': self._rads}
@classmethod
def _from_json_dict_(cls, rads, **kwargs) -> 'Rx':
return cls(rads=rads)
@value.value_equality
class YPowGate(eigen_gate.EigenGate):
r"""A gate that rotates around the Y axis of the Bloch sphere.
The unitary matrix of `cirq.YPowGate(exponent=t)` is:
$$
\begin{bmatrix}
e^{i \pi t /2} \cos(\pi t /2) & - e^{i \pi t /2} \sin(\pi t /2) \\
e^{i \pi t /2} \sin(\pi t /2) & e^{i \pi t /2} \cos(\pi t /2)
\end{bmatrix}
$$
Note in particular that this gate has a global phase factor of
$e^{i \pi t / 2}$ vs the traditionally defined rotation matrices
about the Pauli Y axis. See `cirq.Ry` for rotations without the global
phase. The global phase factor can be adjusted by using the `global_shift`
parameter when initializing.
`cirq.Y`, the Pauli Y gate, is an instance of this gate at `exponent=1`.
"""
def _num_qubits_(self) -> int:
return 1
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> Optional[np.ndarray]:
if self._exponent != 1:
return NotImplemented
zero = args.subspace_index(0)
one = args.subspace_index(1)
args.available_buffer[zero] = -1j * args.target_tensor[one]
args.available_buffer[one] = 1j * args.target_tensor[zero]
p = 1j ** (2 * self._exponent * self._global_shift)
if p != 1:
args.available_buffer *= p
return args.available_buffer
def in_su2(self) -> 'Ry':
"""Returns an equal-up-global-phase gate from the group SU2."""
return Ry(rads=self._exponent * _pi(self._exponent))
def with_canonical_global_phase(self) -> 'YPowGate':
"""Returns an equal-up-global-phase standardized form of the gate."""
return YPowGate(exponent=self._exponent)
def _decompose_into_clifford_with_qubits_(self, qubits):
from cirq.ops.clifford_gate import SingleQubitCliffordGate
if self.exponent % 2 == 0:
return []
if self.exponent % 2 == 0.5:
return SingleQubitCliffordGate.Y_sqrt.on(*qubits)
if self.exponent % 2 == 1:
return SingleQubitCliffordGate.Y.on(*qubits)
if self.exponent % 2 == 1.5:
return SingleQubitCliffordGate.Y_nsqrt.on(*qubits)
return NotImplemented
def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:
return [
(0, np.array([[0.5, -0.5j], [0.5j, 0.5]])),
(1, np.array([[0.5, 0.5j], [-0.5j, 0.5]])),
]
def _trace_distance_bound_(self) -> Optional[float]:
if self._is_parameterized_():
return None
return abs(np.sin(self._exponent * 0.5 * np.pi))
def _pauli_expansion_(self) -> value.LinearDict[str]:
if protocols.is_parameterized(self):
return NotImplemented
phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5))
angle = np.pi * self._exponent / 2
return value.LinearDict({'I': phase * np.cos(angle), 'Y': -1j * phase * np.sin(angle)})
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
return protocols.CircuitDiagramInfo(
wire_symbols=('Y',), exponent=self._diagram_exponent(args)
)
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
if self._exponent == 1 and self.global_shift != -0.5:
return args.format('y {0};\n', qubits[0])
return args.format('ry({0:half_turns}) {1};\n', self._exponent, qubits[0])
@property
def phase_exponent(self):
return 0.5
def _phase_by_(self, phase_turns, qubit_index):
"""See `cirq.SupportsPhase`."""
return cirq.ops.phased_x_gate.PhasedXPowGate(
exponent=self._exponent, phase_exponent=0.5 + phase_turns * 2
)
def _has_stabilizer_effect_(self) -> Optional[bool]:
if self._is_parameterized_():
return None
return self.exponent % 0.5 == 0
def __str__(self) -> str:
if self._global_shift == 0:
if self._exponent == 1:
return 'Y'
return f'Y**{self._exponent}'
return f'YPowGate(exponent={self._exponent}, global_shift={self._global_shift!r})'
def __repr__(self) -> str:
if self._global_shift == 0:
if self._exponent == 1:
return 'cirq.Y'
return f'(cirq.Y**{proper_repr(self._exponent)})'
return 'cirq.YPowGate(exponent={}, global_shift={!r})'.format(
proper_repr(self._exponent), self._global_shift
)
class Ry(YPowGate):
r"""A gate with matrix $e^{-i Y t/2}$ that rotates around the Y axis of the Bloch sphere by $t$.
The unitary matrix of `cirq.Ry(rads=t)` is:
$$
e^{-i Y t / 2} =
\begin{bmatrix}
\cos(t/2) & -\sin(t/2) \\
\sin(t/2) & \cos(t/2)
\end{bmatrix}
$$
This gate corresponds to the traditionally defined rotation matrices about the Pauli Y axis.
"""
def __init__(self, *, rads: value.TParamVal):
"""Initialize an Ry (`cirq.YPowGate`).
Args:
rads: Radians to rotate about the Y axis of the Bloch sphere.
"""
self._rads = rads
super().__init__(exponent=rads / _pi(rads), global_shift=-0.5)
def _with_exponent(self: 'Ry', exponent: value.TParamVal) -> 'Ry':
return Ry(rads=exponent * _pi(exponent))
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
angle_str = self._format_exponent_as_angle(args)
return f'Ry({angle_str})'
def __str__(self) -> str:
if self._exponent == 1:
return 'Ry(π)'
return f'Ry({self._exponent}π)'
def __repr__(self) -> str:
return f'cirq.Ry(rads={proper_repr(self._rads)})'
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
return args.format('ry({0:half_turns}) {1};\n', self._exponent, qubits[0])
def _json_dict_(self) -> Dict[str, Any]:
return {'rads': self._rads}
@classmethod
def _from_json_dict_(cls, rads, **kwargs) -> 'Ry':
return cls(rads=rads)
@value.value_equality
class ZPowGate(eigen_gate.EigenGate):
r"""A gate that rotates around the Z axis of the Bloch sphere.
The unitary matrix of `cirq.ZPowGate(exponent=t, global_shift=s)` is:
$$
e^{i \pi s t}
\begin{bmatrix}
1 & 0 \\
0 & e^{i \pi t}
\end{bmatrix}
$$
Note in particular that this gate has a global phase factor of
$e^{i\pi t/2}$ vs the traditionally defined rotation matrices
about the Pauli Z axis. See `cirq.Rz` for rotations without the global
phase. The global phase factor can be adjusted by using the `global_shift`
parameter when initializing.
`cirq.Z`, the Pauli Z gate, is an instance of this gate at `exponent=1`.
"""
_eigencomponents: Dict[int, List[Tuple[float, np.ndarray]]] = {}
def __init__(
self, *, exponent: value.TParamVal = 1.0, global_shift: float = 0.0, dimension: int = 2
):
"""Initialize a ZPowGate.
Args:
exponent: The t in gate**t. Determines how much the eigenvalues of
the gate are phased by. For example, eigenvectors phased by -1
when `gate**1` is applied will gain a relative phase of
e^{i pi exponent} when `gate**exponent` is applied (relative to
eigenvectors unaffected by `gate**1`).
global_shift: Offsets the eigenvalues of the gate at exponent=1.
In effect, this controls a global phase factor on the gate's
unitary matrix. The factor for global_shift=s is:
exp(i * pi * s * t)
For example, `cirq.X**t` uses a `global_shift` of 0 but
`cirq.rx(t)` uses a `global_shift` of -0.5, which is why
`cirq.unitary(cirq.rx(pi))` equals -iX instead of X.
dimension: Qudit dimension of this gate. For qu*b*its (the default),
this is set to 2.
Raises:
ValueError: If the supplied exponent is a complex number with an
imaginary component.
"""
super().__init__(exponent=exponent, global_shift=global_shift)
self._dimension = dimension
def _num_qubits_(self) -> int:
return 1
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> Optional[np.ndarray]:
if protocols.is_parameterized(self):
return None
for i in range(1, self._dimension):
subspace = args.subspace_index(i)
c = 1j ** (self._exponent * 4 * i / self._dimension)
args.target_tensor[subspace] *= c
p = 1j ** (2 * self._exponent * self._global_shift)
if p != 1:
args.target_tensor *= p
return args.target_tensor
def _decompose_into_clifford_with_qubits_(self, qubits):
from cirq.ops.clifford_gate import SingleQubitCliffordGate
if self.exponent % 2 == 0:
return []
if self.exponent % 2 == 0.5:
return SingleQubitCliffordGate.Z_sqrt.on(*qubits)
if self.exponent % 2 == 1:
return SingleQubitCliffordGate.Z.on(*qubits)
if self.exponent % 2 == 1.5:
return SingleQubitCliffordGate.Z_nsqrt.on(*qubits)
return NotImplemented
def in_su2(self) -> 'Rz':
"""Returns an equal-up-global-phase gate from the group SU2."""
return Rz(rads=self._exponent * _pi(self._exponent))
def with_canonical_global_phase(self) -> 'ZPowGate':
"""Returns an equal-up-global-phase standardized form of the gate."""
return ZPowGate(exponent=self._exponent, dimension=self._dimension)
def controlled(
self,
num_controls: int = None,
control_values: Optional[
Union[cv.AbstractControlValues, Sequence[Union[int, Collection[int]]]]
] = None,
control_qid_shape: Optional[Tuple[int, ...]] = None,
) -> raw_types.Gate:
"""Returns a controlled `ZPowGate`, using a `CZPowGate` where possible.
The `controlled` method of the `Gate` class, of which this class is a
child, returns a `ControlledGate`. This method overrides this behavior
to return a `CZPowGate` or a `ControlledGate` of a `CZPowGate`, when
this is possible.
The conditions for the override to occur are:
* The `global_shift` of the `ZPowGate` is 0.
* The `control_values` and `control_qid_shape` are compatible with
the `CZPowGate`:
* The last value of `control_qid_shape` is a qubit.
* The last value of `control_values` corresponds to the
control being satisfied if that last qubit is 1 and
not satisfied if the last qubit is 0.
If these conditions are met, then the returned object is a `CZPowGate`
or, in the case that there is more than one controlled qudit, a
`ControlledGate` with the `Gate` being a `CZPowGate`. In the
latter case the `ControlledGate` is controlled by one less qudit
than specified in `control_values` and `control_qid_shape` (since
one of these, the last qubit, is used as the control for the
`CZPowGate`).
If the above conditions are not met, a `ControlledGate` of this
gate will be returned.
Args:
num_controls: Total number of control qubits.
control_values: Which control computational basis state to apply the
sub gate. A sequence of length `num_controls` where each
entry is an integer (or set of integers) corresponding to the
computational basis state (or set of possible values) where that
control is enabled. When all controls are enabled, the sub gate is
applied. If unspecified, control values default to 1.
control_qid_shape: The qid shape of the controls. A tuple of the
expected dimension of each control qid. Defaults to
`(2,) * num_controls`. Specify this argument when using qudits.
Returns:
A `cirq.ControlledGate` (or `cirq.CZPowGate` if possible) representing
`self` controlled by the given control values and qubits.
"""
result = super().controlled(num_controls, control_values, control_qid_shape)
if (
self._global_shift == 0
and isinstance(result, controlled_gate.ControlledGate)
and result.control_values[-1] == (1,)
and result.control_qid_shape[-1] == 2
):
return cirq.CZPowGate(
exponent=self._exponent, global_shift=self._global_shift
).controlled(
result.num_controls() - 1, result.control_values[:-1], result.control_qid_shape[:-1]
)
return result
def _qid_shape_(self) -> Tuple[int, ...]:
return (self._dimension,)
def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:
if self._dimension not in ZPowGate._eigencomponents:
components = []
for i in range(self._dimension):
half_turns = i * 2 / self._dimension
m = np.zeros((self._dimension, self._dimension))
m[i][i] = 1
components.append((half_turns, m))
ZPowGate._eigencomponents[self._dimension] = components
return ZPowGate._eigencomponents[self._dimension]
def _with_exponent(self, exponent: 'cirq.TParamVal') -> 'cirq.ZPowGate':
return ZPowGate(
exponent=exponent, global_shift=self._global_shift, dimension=self._dimension
)
def _trace_distance_bound_(self) -> Optional[float]:
if self._is_parameterized_() or self._dimension != 2:
return None
return abs(np.sin(self._exponent * 0.5 * np.pi))
def _pauli_expansion_(self) -> value.LinearDict[str]:
if protocols.is_parameterized(self) or self._dimension != 2:
return NotImplemented
phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5))
angle = np.pi * self._exponent / 2
return value.LinearDict({'I': phase * np.cos(angle), 'Z': -1j * phase * np.sin(angle)})
def _phase_by_(self, phase_turns: float, qubit_index: int):
return self
def _has_stabilizer_effect_(self) -> Optional[bool]:
if self._is_parameterized_() or self._dimension != 2:
return None
return self.exponent % 0.5 == 0
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
e = self._diagram_exponent(args)
if e in [-0.25, 0.25]:
return protocols.CircuitDiagramInfo(wire_symbols=('T',), exponent=cast(float, e) * 4)
if e in [-0.5, 0.5]:
return protocols.CircuitDiagramInfo(wire_symbols=('S',), exponent=cast(float, e) * 2)
return protocols.CircuitDiagramInfo(wire_symbols=('Z',), exponent=e)
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
if self.global_shift == 0:
if self._exponent == 1:
return args.format('z {0};\n', qubits[0])
elif self._exponent == 0.5:
return args.format('s {0};\n', qubits[0])
elif self._exponent == -0.5:
return args.format('sdg {0};\n', qubits[0])
elif self._exponent == 0.25:
return args.format('t {0};\n', qubits[0])
elif self._exponent == -0.25:
return args.format('tdg {0};\n', qubits[0])
return args.format('rz({0:half_turns}) {1};\n', self._exponent, qubits[0])
def __str__(self) -> str:
if self._global_shift == 0:
if self._exponent == 0.25:
return 'T'
if self._exponent == -0.25:
return 'T**-1'
if self._exponent == 0.5:
return 'S'
if self._exponent == -0.5:
return 'S**-1'
if self._exponent == 1:
return 'Z'
return f'Z**{self._exponent}'
return f'ZPowGate(exponent={self._exponent}, global_shift={self._global_shift!r})'
def __repr__(self) -> str:
if self._global_shift == 0 and self._dimension == 2:
if self._exponent == 0.25:
return 'cirq.T'
if self._exponent == -0.25:
return '(cirq.T**-1)'
if self._exponent == 0.5:
return 'cirq.S'
if self._exponent == -0.5:
return '(cirq.S**-1)'
if self._exponent == 1:
return 'cirq.Z'
return f'(cirq.Z**{proper_repr(self._exponent)})'
args = []
if self._exponent != 1:
args.append(f'exponent={proper_repr(self._exponent)}')
if self._global_shift != 0:
args.append(f'global_shift={self._global_shift}')
if self._dimension != 2:
args.append(f'dimension={self._dimension}')
all_args = ', '.join(args)
return f'cirq.ZPowGate({all_args})'
def _commutes_on_qids_(
self, qids: 'Sequence[cirq.Qid]', other: Any, *, atol: float = 1e-8
) -> Union[bool, NotImplementedType, None]:
from cirq.ops.parity_gates import ZZPowGate
if not isinstance(other, raw_types.Operation):
return NotImplemented
if not isinstance(other.gate, (ZPowGate, CZPowGate, ZZPowGate)):
return NotImplemented
return True
class Rz(ZPowGate):
r"""A gate with matrix $e^{-i Z t/2}$ that rotates around the Z axis of the Bloch sphere by $t$.
The unitary matrix of `cirq.Rz(rads=t)` is:
$$
e^{-i Z t /2} =
\begin{bmatrix}
e^{-it/2} & 0 \\
0 & e^{it/2}
\end{bmatrix}
$$
This gate corresponds to the traditionally defined rotation matrices about the Pauli Z axis.
"""
def __init__(self, *, rads: value.TParamVal):
"""Initialize an Rz (`cirq.ZPowGate`).
Args:
rads: Radians to rotate about the Z axis of the Bloch sphere.
"""
self._rads = rads
super().__init__(exponent=rads / _pi(rads), global_shift=-0.5)
def _with_exponent(self: 'Rz', exponent: value.TParamVal) -> 'Rz':
return Rz(rads=exponent * _pi(exponent))
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> Union[str, 'protocols.CircuitDiagramInfo']:
angle_str = self._format_exponent_as_angle(args)
return f'Rz({angle_str})'
def __str__(self) -> str:
if self._exponent == 1:
return 'Rz(π)'
return f'Rz({self._exponent}π)'
def __repr__(self) -> str:
return f'cirq.Rz(rads={proper_repr(self._rads)})'
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
return args.format('rz({0:half_turns}) {1};\n', self._exponent, qubits[0])
def _json_dict_(self) -> Dict[str, Any]:
return {'rads': self._rads}
@classmethod
def _from_json_dict_(cls, rads, **kwargs) -> 'Rz':
return cls(rads=rads)
class HPowGate(eigen_gate.EigenGate):
r"""A Gate that performs a rotation around the X+Z axis of the Bloch sphere.
The unitary matrix of `cirq.HPowGate(exponent=t)` is:
$$
\begin{bmatrix}
e^{i\pi t/2} \left(\cos(\pi t/2) - i \frac{\sin (\pi t /2)}{\sqrt{2}}\right)
&& -i e^{i\pi t/2} \frac{\sin(\pi t /2)}{\sqrt{2}} \\
-i e^{i\pi t/2} \frac{\sin(\pi t /2)}{\sqrt{2}}
&& e^{i\pi t/2} \left(\cos(\pi t/2) + i \frac{\sin (\pi t /2)}{\sqrt{2}}\right)
\end{bmatrix}
$$
Note in particular that for $t=1$, this gives the Hadamard matrix
$$
\begin{bmatrix}
\frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\
\frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}
\end{bmatrix}
$$
`cirq.H`, the Hadamard gate, is an instance of this gate at `exponent=1`.
"""
def _eigen_components(self) -> List[Tuple[float, np.ndarray]]:
s = np.sqrt(2)
component0 = np.array([[3 + 2 * s, 1 + s], [1 + s, 1]]) / (4 + 2 * s)
component1 = np.array([[3 - 2 * s, 1 - s], [1 - s, 1]]) / (4 - 2 * s)
return [(0, component0), (1, component1)]
def _num_qubits_(self) -> int:
return 1
def _trace_distance_bound_(self) -> Optional[float]:
if self._is_parameterized_():
return None
return abs(np.sin(self._exponent * 0.5 * np.pi))
def _pauli_expansion_(self) -> value.LinearDict[str]:
if protocols.is_parameterized(self):
return NotImplemented
phase = 1j ** (2 * self._exponent * (self._global_shift + 0.5))
angle = np.pi * self._exponent / 2
return value.LinearDict(
{
'I': phase * np.cos(angle),
'X': -1j * phase * np.sin(angle) / np.sqrt(2),
'Z': -1j * phase * np.sin(angle) / np.sqrt(2),
}
)
def _decompose_into_clifford_with_qubits_(self, qubits):
from cirq.ops.clifford_gate import SingleQubitCliffordGate
if self.exponent % 2 == 1:
return SingleQubitCliffordGate.H.on(*qubits)
if self.exponent % 2 == 0:
return []
return NotImplemented
def _apply_unitary_(self, args: 'protocols.ApplyUnitaryArgs') -> Optional[np.ndarray]:
if self._exponent != 1:
return NotImplemented
zero = args.subspace_index(0)
one = args.subspace_index(1)
args.target_tensor[one] -= args.target_tensor[zero]
args.target_tensor[one] *= -0.5
args.target_tensor[zero] -= args.target_tensor[one]
p = 1j ** (2 * self._exponent * self._global_shift)
args.target_tensor *= np.sqrt(2) * p
return args.target_tensor
def _decompose_(self, qubits):
q = qubits[0]
if self._exponent == 1:
yield cirq.Y(q) ** 0.5
yield cirq.XPowGate(global_shift=-0.25 + self.global_shift).on(q)
return
yield YPowGate(exponent=0.25).on(q)
yield XPowGate(exponent=self._exponent, global_shift=self.global_shift).on(q)
yield YPowGate(exponent=-0.25).on(q)
def _circuit_diagram_info_(
self, args: 'cirq.CircuitDiagramInfoArgs'
) -> 'cirq.CircuitDiagramInfo':
return protocols.CircuitDiagramInfo(
wire_symbols=('H',), exponent=self._diagram_exponent(args)
)
def _qasm_(self, args: 'cirq.QasmArgs', qubits: Tuple['cirq.Qid', ...]) -> Optional[str]:
args.validate_version('2.0')
if self._exponent == 0:
return args.format('id {0};\n', qubits[0])
elif self._exponent == 1 and self._global_shift == 0:
return args.format('h {0};\n', qubits[0])
return args.format(
'ry({0:half_turns}) {3};\nrx({1:half_turns}) {3};\nry({2:half_turns}) {3};\n',
0.25,
self._exponent,
-0.25,
qubits[0],
)
def _has_stabilizer_effect_(self) -> Optional[bool]:
if self._is_parameterized_():
return None
return self.exponent % 1 == 0
def __str__(self) -> str:
if self._exponent == 1:
return 'H'
return f'H**{self._exponent}'
def __repr__(self) -> str:
if self._global_shift == 0:
if self._exponent == 1:
return 'cirq.H'
return f'(cirq.H**{proper_repr(self._exponent)})'
return (
f'cirq.HPowGate(exponent={proper_repr(self._exponent)}, '
f'global_shift={self._global_shift!r})'
)
class CZPowGate(gate_features.InterchangeableQubitsGate, eigen_gate.EigenGate):
r"""A gate that applies a phase to the |11⟩ state of two qubits.
The unitary matrix of `CZPowGate(exponent=t)` is: