-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
x.py
1247 lines (1063 loc) · 42.8 KB
/
x.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
# 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.
"""X, CX, CCX and multi-controlled X gates."""
from __future__ import annotations
from typing import Optional, Union, Type
from math import ceil, pi
import numpy
from qiskit.circuit.controlledgate import ControlledGate
from qiskit.circuit.gate import Gate
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit._utils import _compute_control_matrix, _ctrl_state_to_int
from .h import HGate
from .t import TGate, TdgGate
from .u1 import U1Gate
from .u2 import U2Gate
from .sx import SXGate
class XGate(Gate):
r"""The single-qubit Pauli-X gate (:math:`\sigma_x`).
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.x` method.
**Matrix Representation:**
.. math::
X = \begin{pmatrix}
0 & 1 \\
1 & 0
\end{pmatrix}
**Circuit symbol:**
.. parsed-literal::
┌───┐
q_0: ┤ X ├
└───┘
Equivalent to a :math:`\pi` radian rotation about the X axis.
.. note::
A global phase difference exists between the definitions of
:math:`RX(\pi)` and :math:`X`.
.. math::
RX(\pi) = \begin{pmatrix}
0 & -i \\
-i & 0
\end{pmatrix}
= -i X
The gate is equivalent to a classical bit flip.
.. math::
|0\rangle \rightarrow |1\rangle \\
|1\rangle \rightarrow |0\rangle
"""
def __init__(self, label: Optional[str] = None):
"""Create new X gate."""
super().__init__("x", 1, [], label=label)
def _define(self):
"""
gate x a { u3(pi,0,pi) a; }
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .u3 import U3Gate
q = QuantumRegister(1, "q")
qc = QuantumCircuit(q, name=self.name)
rules = [(U3Gate(pi, 0, pi), [q[0]], [])]
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Return a (multi-)controlled-X gate.
One control returns a CX gate. Two controls returns a CCX 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.
Returns:
ControlledGate: controlled version of this gate.
"""
gate = MCXGate(num_ctrl_qubits=num_ctrl_qubits, label=label, ctrl_state=ctrl_state)
gate.base_gate.label = self.label
return gate
def inverse(self):
r"""Return inverted X gate (itself)."""
return XGate() # self-inverse
def __array__(self, dtype=None):
"""Return a numpy.array for the X gate."""
return numpy.array([[0, 1], [1, 0]], dtype=dtype)
class CXGate(ControlledGate):
r"""Controlled-X gate.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.cx` and
:meth:`~qiskit.circuit.QuantumCircuit.cnot` methods.
**Circuit symbol:**
.. parsed-literal::
q_0: ──■──
┌─┴─┐
q_1: ┤ X ├
└───┘
**Matrix representation:**
.. math::
CX\ q_0, q_1 =
I \otimes |0\rangle\langle0| + X \otimes |1\rangle\langle1| =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0 \\
0 & 1 & 0 & 0
\end{pmatrix}
.. note::
In Qiskit's convention, higher qubit indices are more significant
(little endian convention). In many textbooks, controlled gates are
presented with the assumption of more significant qubits as control,
which in our case would be q_1. Thus a textbook matrix for this
gate will be:
.. parsed-literal::
┌───┐
q_0: ┤ X ├
└─┬─┘
q_1: ──■──
.. math::
CX\ q_1, q_0 =
|0 \rangle\langle 0| \otimes I + |1 \rangle\langle 1| \otimes X =
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0
\end{pmatrix}
In the computational basis, this gate flips the target qubit
if the control qubit is in the :math:`|1\rangle` state.
In this sense it is similar to a classical XOR gate.
.. math::
`|a, b\rangle \rightarrow |a, a \oplus b\rangle`
"""
def __init__(self, label: Optional[str] = None, ctrl_state: Optional[Union[str, int]] = None):
"""Create new CX gate."""
super().__init__(
"cx", 2, [], num_ctrl_qubits=1, label=label, ctrl_state=ctrl_state, base_gate=XGate()
)
def _define_qasm3(self):
from qiskit.qasm3.ast import (
Constant,
Identifier,
Integer,
QuantumBlock,
QuantumGateModifier,
QuantumGateModifierName,
QuantumGateSignature,
QuantumGateDefinition,
QuantumGateCall,
)
control, target = Identifier("c"), Identifier("t")
call = QuantumGateCall(
Identifier("U"),
[control, target],
parameters=[Constant.PI, Integer(0), Constant.PI],
modifiers=[QuantumGateModifier(QuantumGateModifierName.CTRL)],
)
return QuantumGateDefinition(
QuantumGateSignature(Identifier("cx"), [control, target]),
QuantumBlock([call]),
)
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Return a controlled-X gate with more control lines.
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.
Returns:
ControlledGate: controlled version of this gate.
"""
ctrl_state = _ctrl_state_to_int(ctrl_state, num_ctrl_qubits)
new_ctrl_state = (self.ctrl_state << num_ctrl_qubits) | ctrl_state
gate = MCXGate(num_ctrl_qubits=num_ctrl_qubits + 1, label=label, ctrl_state=new_ctrl_state)
gate.base_gate.label = self.label
return gate
def inverse(self):
"""Return inverted CX gate (itself)."""
return CXGate(ctrl_state=self.ctrl_state) # self-inverse
def __array__(self, dtype=None):
"""Return a numpy.array for the CX gate."""
if self.ctrl_state:
return numpy.array(
[[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=dtype
)
else:
return numpy.array(
[[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]], dtype=dtype
)
class CCXGate(ControlledGate):
r"""CCX gate, also known as Toffoli gate.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.ccx` and
:meth:`~qiskit.circuit.QuantumCircuit.toffoli` methods.
**Circuit symbol:**
.. parsed-literal::
q_0: ──■──
│
q_1: ──■──
┌─┴─┐
q_2: ┤ X ├
└───┘
**Matrix representation:**
.. math::
CCX q_0, q_1, q_2 =
I \otimes I \otimes |0 \rangle \langle 0| + CX \otimes |1 \rangle \langle 1| =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0\\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0
\end{pmatrix}
.. note::
In Qiskit's convention, higher qubit indices are more significant
(little endian convention). In many textbooks, controlled gates are
presented with the assumption of more significant qubits as control,
which in our case would be q_2 and q_1. Thus a textbook matrix for this
gate will be:
.. parsed-literal::
┌───┐
q_0: ┤ X ├
└─┬─┘
q_1: ──■──
│
q_2: ──■──
.. math::
CCX\ q_2, q_1, q_0 =
|0 \rangle \langle 0| \otimes I \otimes I + |1 \rangle \langle 1| \otimes CX =
\begin{pmatrix}
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 1 & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 1\\
0 & 0 & 0 & 0 & 0 & 0 & 1 & 0
\end{pmatrix}
"""
def __init__(self, label: Optional[str] = None, ctrl_state: Optional[Union[str, int]] = None):
"""Create new CCX gate."""
super().__init__(
"ccx", 3, [], num_ctrl_qubits=2, label=label, ctrl_state=ctrl_state, base_gate=XGate()
)
def _define(self):
"""
gate ccx a,b,c
{
h c; cx b,c; tdg c; cx a,c;
t c; cx b,c; tdg c; cx a,c;
t b; t c; h c; cx a,b;
t a; tdg b; cx a,b;}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
# ┌───┐
# q_0: ───────────────────■─────────────────────■────■───┤ T ├───■──
# │ ┌───┐ │ ┌─┴─┐┌┴───┴┐┌─┴─┐
# q_1: ───────■───────────┼─────────■───┤ T ├───┼──┤ X ├┤ Tdg ├┤ X ├
# ┌───┐┌─┴─┐┌─────┐┌─┴─┐┌───┐┌─┴─┐┌┴───┴┐┌─┴─┐├───┤└┬───┬┘└───┘
# q_2: ┤ H ├┤ X ├┤ Tdg ├┤ X ├┤ T ├┤ X ├┤ Tdg ├┤ X ├┤ T ├─┤ H ├──────
# └───┘└───┘└─────┘└───┘└───┘└───┘└─────┘└───┘└───┘ └───┘
q = QuantumRegister(3, "q")
qc = QuantumCircuit(q, name=self.name)
rules = [
(HGate(), [q[2]], []),
(CXGate(), [q[1], q[2]], []),
(TdgGate(), [q[2]], []),
(CXGate(), [q[0], q[2]], []),
(TGate(), [q[2]], []),
(CXGate(), [q[1], q[2]], []),
(TdgGate(), [q[2]], []),
(CXGate(), [q[0], q[2]], []),
(TGate(), [q[1]], []),
(TGate(), [q[2]], []),
(HGate(), [q[2]], []),
(CXGate(), [q[0], q[1]], []),
(TGate(), [q[0]], []),
(TdgGate(), [q[1]], []),
(CXGate(), [q[0], q[1]], []),
]
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""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.
Returns:
ControlledGate: controlled version of this gate.
"""
ctrl_state = _ctrl_state_to_int(ctrl_state, num_ctrl_qubits)
new_ctrl_state = (self.ctrl_state << num_ctrl_qubits) | ctrl_state
gate = MCXGate(num_ctrl_qubits=num_ctrl_qubits + 2, label=label, ctrl_state=new_ctrl_state)
gate.base_gate.label = self.label
return gate
def inverse(self):
"""Return an inverted CCX gate (also a CCX)."""
return CCXGate(ctrl_state=self.ctrl_state) # self-inverse
def __array__(self, dtype=None):
"""Return a numpy.array for the CCX gate."""
mat = _compute_control_matrix(
self.base_gate.to_matrix(), self.num_ctrl_qubits, ctrl_state=self.ctrl_state
)
if dtype:
return numpy.asarray(mat, dtype=dtype)
return mat
class RCCXGate(Gate):
"""The simplified Toffoli gate, also referred to as Margolus gate.
The simplified Toffoli gate implements the Toffoli gate up to relative phases.
This implementation requires three CX gates which is the minimal amount possible,
as shown in https://arxiv.org/abs/quant-ph/0312225.
Note, that the simplified Toffoli is not equivalent to the Toffoli. But can be used in places
where the Toffoli gate is uncomputed again.
This concrete implementation is from https://arxiv.org/abs/1508.03273, the dashed box
of Fig. 3.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.rccx` method.
"""
def __init__(self, label: Optional[str] = None):
"""Create a new simplified CCX gate."""
super().__init__("rccx", 3, [], label=label)
def _define(self):
"""
gate rccx a,b,c
{ u2(0,pi) c;
u1(pi/4) c;
cx b, c;
u1(-pi/4) c;
cx a, c;
u1(pi/4) c;
cx b, c;
u1(-pi/4) c;
u2(0,pi) c;
}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
q = QuantumRegister(3, "q")
qc = QuantumCircuit(q, name=self.name)
rules = [
(U2Gate(0, pi), [q[2]], []), # H gate
(U1Gate(pi / 4), [q[2]], []), # T gate
(CXGate(), [q[1], q[2]], []),
(U1Gate(-pi / 4), [q[2]], []), # inverse T gate
(CXGate(), [q[0], q[2]], []),
(U1Gate(pi / 4), [q[2]], []),
(CXGate(), [q[1], q[2]], []),
(U1Gate(-pi / 4), [q[2]], []), # inverse T gate
(U2Gate(0, pi), [q[2]], []), # H gate
]
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def __array__(self, dtype=None):
"""Return a numpy.array for the simplified CCX gate."""
return numpy.array(
[
[1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, -1j],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, -1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 1j, 0, 0, 0, 0],
],
dtype=dtype,
)
class C3SXGate(ControlledGate):
"""The 3-qubit controlled sqrt-X gate.
This implementation is based on Page 17 of [1].
References:
[1] Barenco et al., 1995. https://arxiv.org/pdf/quant-ph/9503016.pdf
"""
def __init__(
self,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Create a new 3-qubit controlled sqrt-X gate.
Args:
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.
"""
super().__init__(
"c3sx", 4, [], num_ctrl_qubits=3, label=label, ctrl_state=ctrl_state, base_gate=SXGate()
)
def _define(self):
"""
gate c3sqrtx a,b,c,d
{
h d; cu1(pi/8) a,d; h d;
cx a,b;
h d; cu1(-pi/8) b,d; h d;
cx a,b;
h d; cu1(pi/8) b,d; h d;
cx b,c;
h d; cu1(-pi/8) c,d; h d;
cx a,c;
h d; cu1(pi/8) c,d; h d;
cx b,c;
h d; cu1(-pi/8) c,d; h d;
cx a,c;
h d; cu1(pi/8) c,d; h d;
}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .u1 import CU1Gate
angle = numpy.pi / 8
q = QuantumRegister(4, name="q")
rules = [
(HGate(), [q[3]], []),
(CU1Gate(angle), [q[0], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[0], q[1]], []),
(HGate(), [q[3]], []),
(CU1Gate(-angle), [q[1], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[0], q[1]], []),
(HGate(), [q[3]], []),
(CU1Gate(angle), [q[1], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[1], q[2]], []),
(HGate(), [q[3]], []),
(CU1Gate(-angle), [q[2], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[0], q[2]], []),
(HGate(), [q[3]], []),
(CU1Gate(angle), [q[2], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[1], q[2]], []),
(HGate(), [q[3]], []),
(CU1Gate(-angle), [q[2], q[3]], []),
(HGate(), [q[3]], []),
(CXGate(), [q[0], q[2]], []),
(HGate(), [q[3]], []),
(CU1Gate(angle), [q[2], q[3]], []),
(HGate(), [q[3]], []),
]
qc = QuantumCircuit(q)
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def qasm(self):
# Gross hack to override the Qiskit name with the name this gate has in Terra's version of
# 'qelib1.inc'. In general, the larger exporter mechanism should know about this to do the
# mapping itself, but right now that's not possible without a complete rewrite of the OQ2
# exporter code (low priority), or we would need to modify 'qelib1.inc' which would be
# needlessly disruptive this late in OQ2's lifecycle. The current OQ2 exporter _always_
# outputs the `include 'qelib1.inc' line. ---Jake, 2022-11-21.
old_name = self.name
self.name = "c3sqrtx"
try:
return super().qasm()
finally:
self.name = old_name
class C3XGate(ControlledGate):
r"""The X gate controlled on 3 qubits.
This implementation uses :math:`\sqrt{T}` and 14 CNOT gates.
"""
def __init__(
self,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Create a new 3-qubit controlled X gate."""
super().__init__(
"mcx", 4, [], num_ctrl_qubits=3, label=label, ctrl_state=ctrl_state, base_gate=XGate()
)
# seems like open controls not hapening?
def _define(self):
"""
gate c3x a,b,c,d
{
h d;
p(pi/8) a;
p(pi/8) b;
p(pi/8) c;
p(pi/8) d;
cx a, b;
p(-pi/8) b;
cx a, b;
cx b, c;
p(-pi/8) c;
cx a, c;
p(pi/8) c;
cx b, c;
p(-pi/8) c;
cx a, c;
cx c, d;
p(-pi/8) d;
cx b, d;
p(pi/8) d;
cx c, d;
p(-pi/8) d;
cx a, d;
p(pi/8) d;
cx c, d;
p(-pi/8) d;
cx b, d;
p(pi/8) d;
cx c, d;
p(-pi/8) d;
cx a, d;
h d;
}
"""
from qiskit.circuit.quantumcircuit import QuantumCircuit
q = QuantumRegister(4, name="q")
qc = QuantumCircuit(q, name=self.name)
qc.h(3)
qc.p(pi / 8, [0, 1, 2, 3])
qc.cx(0, 1)
qc.p(-pi / 8, 1)
qc.cx(0, 1)
qc.cx(1, 2)
qc.p(-pi / 8, 2)
qc.cx(0, 2)
qc.p(pi / 8, 2)
qc.cx(1, 2)
qc.p(-pi / 8, 2)
qc.cx(0, 2)
qc.cx(2, 3)
qc.p(-pi / 8, 3)
qc.cx(1, 3)
qc.p(pi / 8, 3)
qc.cx(2, 3)
qc.p(-pi / 8, 3)
qc.cx(0, 3)
qc.p(pi / 8, 3)
qc.cx(2, 3)
qc.p(-pi / 8, 3)
qc.cx(1, 3)
qc.p(pi / 8, 3)
qc.cx(2, 3)
qc.p(-pi / 8, 3)
qc.cx(0, 3)
qc.h(3)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""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.
Returns:
ControlledGate: controlled version of this gate.
"""
ctrl_state = _ctrl_state_to_int(ctrl_state, num_ctrl_qubits)
new_ctrl_state = (self.ctrl_state << num_ctrl_qubits) | ctrl_state
gate = MCXGate(num_ctrl_qubits=num_ctrl_qubits + 3, label=label, ctrl_state=new_ctrl_state)
gate.base_gate.label = self.label
return gate
def inverse(self):
"""Invert this gate. The C4X is its own inverse."""
return C3XGate(ctrl_state=self.ctrl_state)
def __array__(self, dtype=None):
"""Return a numpy.array for the C4X gate."""
mat = _compute_control_matrix(
self.base_gate.to_matrix(), self.num_ctrl_qubits, ctrl_state=self.ctrl_state
)
if dtype:
return numpy.asarray(mat, dtype=dtype)
return mat
class RC3XGate(Gate):
"""The simplified 3-controlled Toffoli gate.
The simplified Toffoli gate implements the Toffoli gate up to relative phases.
Note, that the simplified Toffoli is not equivalent to the Toffoli. But can be used in places
where the Toffoli gate is uncomputed again.
This concrete implementation is from https://arxiv.org/abs/1508.03273, the complete circuit
of Fig. 4.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.rcccx` method.
"""
def __init__(self, label: Optional[str] = None):
"""Create a new RC3X gate."""
super().__init__("rcccx", 4, [], label=label)
def _define(self):
"""
gate rc3x a,b,c,d
{ u2(0,pi) d;
u1(pi/4) d;
cx c,d;
u1(-pi/4) d;
u2(0,pi) d;
cx a,d;
u1(pi/4) d;
cx b,d;
u1(-pi/4) d;
cx a,d;
u1(pi/4) d;
cx b,d;
u1(-pi/4) d;
u2(0,pi) d;
u1(pi/4) d;
cx c,d;
u1(-pi/4) d;
u2(0,pi) d;
}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
q = QuantumRegister(4, "q")
qc = QuantumCircuit(q, name=self.name)
rules = [
(U2Gate(0, pi), [q[3]], []), # H gate
(U1Gate(pi / 4), [q[3]], []), # T gate
(CXGate(), [q[2], q[3]], []),
(U1Gate(-pi / 4), [q[3]], []), # inverse T gate
(U2Gate(0, pi), [q[3]], []),
(CXGate(), [q[0], q[3]], []),
(U1Gate(pi / 4), [q[3]], []),
(CXGate(), [q[1], q[3]], []),
(U1Gate(-pi / 4), [q[3]], []),
(CXGate(), [q[0], q[3]], []),
(U1Gate(pi / 4), [q[3]], []),
(CXGate(), [q[1], q[3]], []),
(U1Gate(-pi / 4), [q[3]], []),
(U2Gate(0, pi), [q[3]], []),
(U1Gate(pi / 4), [q[3]], []),
(CXGate(), [q[2], q[3]], []),
(U1Gate(-pi / 4), [q[3]], []),
(U2Gate(0, pi), [q[3]], []),
]
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def __array__(self, dtype=None):
"""Return a numpy.array for the RC3X gate."""
return numpy.array(
[
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1j, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1j, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0],
],
dtype=dtype,
)
class C4XGate(ControlledGate):
"""The 4-qubit controlled X gate.
This implementation is based on Page 21, Lemma 7.5, of [1], with the use
of the relative phase version of c3x, the rc3x [2].
References:
[1] Barenco et al., 1995. https://arxiv.org/pdf/quant-ph/9503016.pdf
[2] Maslov, 2015. https://arxiv.org/abs/1508.03273
"""
def __init__(self, label: Optional[str] = None, ctrl_state: Optional[Union[str, int]] = None):
"""Create a new 4-qubit controlled X gate."""
super().__init__(
"mcx", 5, [], num_ctrl_qubits=4, label=label, ctrl_state=ctrl_state, base_gate=XGate()
)
# seems like open controls not hapening?
def _define(self):
"""
gate c3sqrtx a,b,c,d
{
h d; cu1(pi/8) a,d; h d;
cx a,b;
h d; cu1(-pi/8) b,d; h d;
cx a,b;
h d; cu1(pi/8) b,d; h d;
cx b,c;
h d; cu1(-pi/8) c,d; h d;
cx a,c;
h d; cu1(pi/8) c,d; h d;
cx b,c;
h d; cu1(-pi/8) c,d; h d;
cx a,c;
h d; cu1(pi/8) c,d; h d;
}
gate c4x a,b,c,d,e
{
h e; cu1(pi/2) d,e; h e;
rc3x a,b,c,d;
h e; cu1(-pi/2) d,e; h e;
rc3x a,b,c,d;
c3sqrtx a,b,c,e;
}
"""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
from .u1 import CU1Gate
q = QuantumRegister(5, name="q")
qc = QuantumCircuit(q, name=self.name)
rules = [
(HGate(), [q[4]], []),
(CU1Gate(numpy.pi / 2), [q[3], q[4]], []),
(HGate(), [q[4]], []),
(RC3XGate(), [q[0], q[1], q[2], q[3]], []),
(HGate(), [q[4]], []),
(CU1Gate(-numpy.pi / 2), [q[3], q[4]], []),
(HGate(), [q[4]], []),
(RC3XGate().inverse(), [q[0], q[1], q[2], q[3]], []),
(C3SXGate(), [q[0], q[1], q[2], q[4]], []),
]
for instr, qargs, cargs in rules:
qc._append(instr, qargs, cargs)
self.definition = qc
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""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.
Returns:
ControlledGate: controlled version of this gate.
"""
ctrl_state = _ctrl_state_to_int(ctrl_state, num_ctrl_qubits)
new_ctrl_state = (self.ctrl_state << num_ctrl_qubits) | ctrl_state
gate = MCXGate(num_ctrl_qubits=num_ctrl_qubits + 4, label=label, ctrl_state=new_ctrl_state)
gate.base_gate.label = self.label
return gate
def inverse(self):
"""Invert this gate. The C4X is its own inverse."""
return C4XGate(ctrl_state=self.ctrl_state)
def __array__(self, dtype=None):
"""Return a numpy.array for the C4X gate."""
mat = _compute_control_matrix(
self.base_gate.to_matrix(), self.num_ctrl_qubits, ctrl_state=self.ctrl_state
)
if dtype:
return numpy.asarray(mat, dtype=dtype)
return mat
class MCXGate(ControlledGate):
"""The general, multi-controlled X gate.
Can be applied to a :class:`~qiskit.circuit.QuantumCircuit`
with the :meth:`~qiskit.circuit.QuantumCircuit.mcx` method.
"""
def __new__(
cls,
num_ctrl_qubits: Optional[int] = None,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Create a new MCX instance.
Depending on the number of controls and which mode of the MCX, this creates an
explicit CX, CCX, C3X or C4X instance or a generic MCX gate.
"""
# The CXGate and CCXGate will be implemented for all modes of the MCX, and
# the C3XGate and C4XGate will be implemented in the MCXGrayCode class.
explicit: dict[int, Type[ControlledGate]] = {1: CXGate, 2: CCXGate}
if num_ctrl_qubits in explicit:
gate_class = explicit[num_ctrl_qubits]
gate = gate_class.__new__(gate_class, label=label, ctrl_state=ctrl_state)
# if __new__ does not return the same type as cls, init is not called
gate.__init__(label=label, ctrl_state=ctrl_state)
return gate
return super().__new__(cls)
def __init__(
self,
num_ctrl_qubits: int,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
_name="mcx",
):
"""Create new MCX gate."""
num_ancilla_qubits = self.__class__.get_num_ancilla_qubits(num_ctrl_qubits)
super().__init__(
_name,
num_ctrl_qubits + 1 + num_ancilla_qubits,
[],
num_ctrl_qubits=num_ctrl_qubits,
label=label,
ctrl_state=ctrl_state,
base_gate=XGate(),
)
def inverse(self):
"""Invert this gate. The MCX is its own inverse."""
return MCXGate(num_ctrl_qubits=self.num_ctrl_qubits, ctrl_state=self.ctrl_state)
@staticmethod
def get_num_ancilla_qubits(num_ctrl_qubits: int, mode: str = "noancilla") -> int:
"""Get the number of required ancilla qubits without instantiating the class.
This staticmethod might be necessary to check the number of ancillas before
creating the gate, or to use the number of ancillas in the initialization.
"""
if mode == "noancilla":
return 0
if mode in ["recursion", "advanced"]:
return int(num_ctrl_qubits > 4)
if mode[:7] == "v-chain" or mode[:5] == "basic":
return max(0, num_ctrl_qubits - 2)
raise AttributeError(f"Unsupported mode ({mode}) specified!")
def _define(self):
"""The standard definition used the Gray code implementation."""
# pylint: disable=cyclic-import
from qiskit.circuit.quantumcircuit import QuantumCircuit
q = QuantumRegister(self.num_qubits, name="q")
qc = QuantumCircuit(q)
qc._append(MCXGrayCode(self.num_ctrl_qubits), q[:], [])
self.definition = qc
@property
def num_ancilla_qubits(self):
"""The number of ancilla qubits."""
return self.__class__.get_num_ancilla_qubits(self.num_ctrl_qubits)
def control(
self,
num_ctrl_qubits: int = 1,
label: Optional[str] = None,
ctrl_state: Optional[Union[str, int]] = None,
):
"""Return a multi-controlled-X gate with more control lines.