/
circuit.py
1671 lines (1487 loc) · 70.9 KB
/
circuit.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 file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in sourc e and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
from collections.abc import Iterable
from collections import defaultdict
from itertools import product
import warnings
import inspect
import numpy as np
from copy import deepcopy
from qutip.qip import circuit_latex as _latex
from qutip.qip.operations.gates import (rx, ry, rz, sqrtnot, snot, phasegate,
x_gate, y_gate, z_gate, cy_gate,
cz_gate, s_gate, t_gate, cs_gate,
qasmu_gate, ct_gate, cphase, cnot,
csign, berkeley, swapalpha, swap, iswap,
sqrtswap, sqrtiswap, fredkin,
toffoli, controlled_gate, globalphase,
expand_operator)
from qutip import tensor, basis, identity, fidelity
from qutip.qobj import Qobj
from qutip.measurement import measurement_statistics
try:
from IPython.display import Image as DisplayImage, SVG as DisplaySVG
except ImportError:
# If IPython doesn't exist, then we set the nice display hooks to be simple
# pass-throughs.
def DisplayImage(data, *args, **kwargs):
return data
def DisplaySVG(data, *args, **kwargs):
return data
__all__ = ['Gate', 'QubitCircuit', 'Measurement']
_single_qubit_gates = ["RX", "RY", "RZ", "SNOT", "SQRTNOT", "PHASEGATE",
"X", "Y", "Z", "S", "T", "QASMU"]
_para_gates = ["RX", "RY", "RZ", "CPHASE", "SWAPalpha", "PHASEGATE",
"GLOBALPHASE", "CRX", "CRY", "CRZ", "QASMU"]
_ctrl_gates = ["CNOT", "CSIGN", "CRX", "CRY", "CRZ", "CY", "CZ",
"CS", "CT"]
_swap_like = ["SWAP", "ISWAP", "SQRTISWAP", "SQRTSWAP", "BERKELEY",
"SWAPalpha"]
_toffoli_like = ["TOFFOLI"]
_fredkin_like = ["FREDKIN"]
class Gate:
"""
Representation of a quantum gate, with its required parametrs, and target
and control qubits.
Parameters
----------
name : string
Gate name.
targets : list or int
Gate targets.
controls : list or int
Gate controls.
arg_value : float
Argument value(phi).
arg_label : string
Label for gate representation.
classical_controls : int or list of int, optional
indices of classical bits to control gate on.
control_value : int, optional
value of classical bits to control on, the classical controls are
interpreted as an integer with lowest bit being the first one.
If not specified, then the value is interpreted to be
2 ** len(classical_controls) - 1 (i.e. all classical controls are 1).
"""
def __init__(self, name, targets=None, controls=None,
arg_value=None, arg_label=None,
classical_controls=None, control_value=None):
"""
Create a gate with specified parameters.
"""
self.name = name
self.targets = None
self.controls = None
self.classical_controls = None
self.control_value = None
if not isinstance(targets, Iterable) and targets is not None:
self.targets = [targets]
else:
self.targets = targets
if not isinstance(controls, Iterable) and controls is not None:
self.controls = [controls]
else:
self.controls = controls
if (not isinstance(classical_controls, Iterable) and
classical_controls is not None):
self.classical_controls = [classical_controls]
else:
self.classical_controls = classical_controls
if (control_value is not None
and control_value < 2 ** len(classical_controls)):
self.control_value = control_value
for ind_list in [self.targets, self.controls, self.classical_controls]:
if isinstance(ind_list, Iterable):
all_integer = all(
[isinstance(ind, np.int) for ind in ind_list])
if not all_integer:
raise ValueError("Index of a qubit must be an integer")
if name in _single_qubit_gates:
if self.targets is None or len(self.targets) != 1:
raise ValueError("Gate %s requires one target" % name)
if self.controls is not None:
raise ValueError("Gate %s cannot have a control" % name)
elif name in _swap_like:
if (self.targets is None) or (len(self.targets) != 2):
raise ValueError("Gate %s requires two targets" % name)
if self.controls is not None:
raise ValueError("Gate %s cannot have a control" % name)
elif name in _ctrl_gates:
if self.targets is None or len(self.targets) != 1:
raise ValueError("Gate %s requires one target" % name)
if self.controls is None or len(self.controls) != 1:
raise ValueError("Gate %s requires one control" % name)
elif name in _fredkin_like:
if self.targets is None or len(self.targets) != 2:
raise ValueError("Gate %s requires one target" % name)
if self.controls is None or len(self.controls) != 1:
raise ValueError("Gate %s requires two control" % name)
elif name in _toffoli_like:
if self.targets is None or len(self.targets) != 1:
raise ValueError("Gate %s requires one target" % name)
if self.controls is None or len(self.controls) != 2:
raise ValueError("Gate %s requires two control" % name)
if name in _para_gates:
if arg_value is None:
raise ValueError("Gate %s requires an argument value" % name)
else:
if (name in _GATE_NAME_TO_LABEL) and (arg_value is not None):
raise ValueError("Gate %s does not take argument value" % name)
self.arg_value = arg_value
self.arg_label = arg_label
def __str__(self):
str_name = (("Gate(%s, targets=%s, controls=%s,"
" classical controls=%s, control_value=%s)")
% (self.name, self.targets,
self.controls, self.classical_controls,
self.control_value))
return str_name
def __repr__(self):
return str(self)
def _repr_latex_(self):
return str(self)
_GATE_NAME_TO_LABEL = {
'X': r'X',
'Y': r'Y',
'CY': r'C_y',
'Z': r'Z',
'CZ': r'C_z',
'S': r'S',
'CS': r'C_s',
'T': r'T',
'CT': r'C_t',
'RX': r'R_x',
'RY': r'R_y',
'RZ': r'R_z',
'CRX': r'R_x',
'CRY': r'R_y',
'CRZ': r'R_z',
'SQRTNOT': r'\sqrt{\rm NOT}',
'SNOT': r'{\rm H}',
'PHASEGATE': r'{\rm PHASE}',
'QASMU': r'{\rm QASM-U}',
'CPHASE': r'{\rm R}',
'CNOT': r'{\rm CNOT}',
'CSIGN': r'{\rm Z}',
'BERKELEY': r'{\rm BERKELEY}',
'SWAPalpha': r'{\rm SWAPalpha}',
'SWAP': r'{\rm SWAP}',
'ISWAP': r'{i}{\rm SWAP}',
'SQRTSWAP': r'\sqrt{\rm SWAP}',
'SQRTISWAP': r'\sqrt{{i}\rm SWAP}',
'FREDKIN': r'{\rm FREDKIN}',
'TOFFOLI': r'{\rm TOFFOLI}',
'GLOBALPHASE': r'{\rm Ph}',
}
def _gate_label(name, arg_label):
if name in _GATE_NAME_TO_LABEL:
gate_label = _GATE_NAME_TO_LABEL[name]
else:
warnings.warn("Unknown gate %s" % name)
gate_label = name
if arg_label:
return r'%s(%s)' % (gate_label, arg_label)
return r'%s' % gate_label
class Measurement:
"""
Representation of a quantum measurement, with its required parameters,
and target qubits.
Parameters
----------
name : string
Measurement name.
targets : list or int
Gate targets.
classical_store : int
Result of the measurment is stored in this
classical register of the circuit.
"""
def __init__(self, name, targets=None, index=None, classical_store=None):
"""
Create a measurement with specified parameters.
"""
self.name = name
self.targets = None
self.classical_store = classical_store
self.index = index
if not isinstance(targets, Iterable) and targets is not None:
self.targets = [targets]
else:
self.targets = targets
for ind_list in [self.targets]:
if isinstance(ind_list, Iterable):
all_integer = all(
[isinstance(ind, np.int) for ind in ind_list])
if not all_integer:
raise ValueError("Index of a qubit must be an integer")
def measurement_comp_basis(self, state):
'''
Measures a particular qubit (determined by the target)
whose ket vector/ density matrix is specified in the
computational basis and returns collapsed_states and probabilities
(retains full dimension).
Parameters
----------
state : ket or oper
state to be measured on specified by
ket vector or density matrix
Returns
-------
collapsed_states : List of Qobjs
the collapsed state obtained after measuring the qubits
and obtaining the qubit specified by the target in the
state specified by the index.
probabilities : List of floats
the probability of measuring a state in a the state
specified by the index.
'''
n = int(np.log2(state.shape[0]))
target = self.targets[0]
if target < n:
op0 = basis(2, 0) * basis(2, 0).dag()
op1 = basis(2, 1) * basis(2, 1).dag()
measurement_ops = [op0, op1]
else:
raise ValueError("target is not valid")
return measurement_statistics(state, measurement_ops,
targets=self.targets)
def __str__(self):
str_name = (("Measurement(%s, target=%s, classical_store=%s)") %
(self.name, self.targets, self.classical_store))
return str_name
def __repr__(self):
return str(self)
def _repr_latex_(self):
return str(self)
class QubitCircuit:
"""
Representation of a quantum program/algorithm, maintaining a sequence
of gates.
Parameters
----------
N : int
Number of qubits in the system.
user_gates : dict
Define a dictionary of the custom gates. See examples for detail.
input_states : list
A list of string such as `0`,'+', "A", "Y". Only used for latex.
dims : list
A list of integer for the dimension of each composite system.
e.g [2,2,2,2,2] for 5 qubits system. If None, qubits system
will be the default option.
Examples
--------
>>> def user_gate():
... mat = np.array([[1., 0],
... [0., 1.j]])
... return Qobj(mat, dims=[[2], [2]])
>>> qubit_circuit.QubitCircuit(2, user_gates={"T":user_gate})
>>> qubit_circuit.add_gate("T", targets=[0])
"""
def __init__(self, N, input_states=None, output_states=None,
reverse_states=True, user_gates=None, dims=None, num_cbits=0):
# number of qubits in the register
self.N = N
self.reverse_states = reverse_states
self.gates = []
self.U_list = []
self.dims = dims
self.num_cbits = num_cbits
if input_states:
self.input_states = input_states
else:
self.input_states = [None for i in range(N+num_cbits)]
if output_states:
self.output_states = output_states
else:
self.output_states = [None for i in range(N+num_cbits)]
if user_gates is None:
self.user_gates = {}
else:
if isinstance(user_gates, dict):
self.user_gates = user_gates
else:
raise ValueError(
"`user_gate` takes a python dictionary of the form"
"{{str: gate_function}}, not {}".format(user_gates))
def add_state(self, state, targets=None, state_type="input"):
"""
Add an input or ouput state to the circuit. By default all the input
and output states will be initialized to `None`. A particular state can
be added by specifying the state and the qubit where it has to be added
along with the type as input or output.
Parameters
----------
state: str
The state that has to be added. It can be any string such as `0`,
'+', "A", "Y"
targets: list
A list of qubit positions where the given state has to be added.
state_type: str
One of either "input" or "output". This specifies whether the state
to be added is an input or output.
default: "input"
"""
if state_type == "input":
for i in targets:
self.input_states[i] = state
if state_type == "output":
for i in targets:
self.output_states[i] = state
def add_measurement(self, measurement, targets=None, index=None,
classical_store=None):
"""
Adds a measurement with specified parameters to the circuit.
Parameters
----------
name: string
Measurement name. If name is an instance of `Measuremnent`,
parameters are unpacked and added.
targets: list
Gate targets
index : list
Positions to add the gate.
classical_store : int
Classical register where result of measurement is stored.
"""
if isinstance(measurement, Measurement):
name = measurement.name
targets = measurement.targets
classical_store = measurement.classical_store
else:
name = measurement
if index is None:
self.gates.append(
Measurement(name, targets=targets,
classical_store=classical_store))
else:
for position in index:
self.gates.insert(
position,
Measurement(name, targets=targets,
classical_store=classical_store))
def add_gate(self, gate, targets=None, controls=None, arg_value=None,
arg_label=None, index=None,
classical_controls=None, control_value=None):
"""
Adds a gate with specified parameters to the circuit.
Parameters
----------
gate: string or `Gate`
Gate name. If gate is an instance of `Gate`, parameters are
unpacked and added.
targets: list
Gate targets.
controls: list
Gate controls.
arg_value: float
Argument value(phi).
arg_label: string
Label for gate representation.
index : list
Positions to add the gate.
classical_controls : int or list of int, optional
indices of classical bits to control gate on.
control_value : int, optional
value of classical bits to control on, the classical controls are
interpreted as an integer with lowest bit being the first one.
If not specified, then the value is interpreted to be
2 ** len(classical_controls) - 1
(i.e. all classical controls are 1).
"""
if isinstance(gate, Gate):
name = gate.name
targets = gate.targets
controls = gate.controls
arg_value = gate.arg_value
arg_label = gate.arg_label
classical_controls = gate.classical_controls
control_value = gate.control_value
else:
name = gate
if index is None:
gate = Gate(name, targets=targets, controls=controls,
arg_value=arg_value, arg_label=arg_label,
classical_controls=classical_controls,
control_value=control_value)
self.gates.append(gate)
else:
for position in index:
num_mes = (sum(isinstance(op, Measurement) for op
in self.gates[:position]))
gate = Gate(name, targets=targets, controls=controls,
arg_value=arg_value, arg_label=arg_label,
classical_controls=classical_controls,
control_value=control_value)
self.gates.insert(position, gate)
def add_1q_gate(self, name, start=0, end=None, qubits=None,
arg_value=None, arg_label=None,
classical_controls=None, control_value=None):
"""
Adds a single qubit gate with specified parameters on a variable
number of qubits in the circuit. By default, it applies the given gate
to all the qubits in the register.
Parameters
----------
name : string
Gate name.
start : int
Starting location of qubits.
end : int
Last qubit for the gate.
qubits : list
Specific qubits for applying gates.
arg_value : float
Argument value(phi).
arg_label : string
Label for gate representation.
"""
if name not in ["RX", "RY", "RZ", "SNOT", "SQRTNOT", "PHASEGATE",
"X", "Y", "Z", "S", "T", "QASMU"]:
raise ValueError("%s is not a single qubit gate" % name)
if qubits is not None:
for _, i in enumerate(qubits):
gate = Gate(name, targets=qubits[i], controls=None,
arg_value=arg_value, arg_label=arg_label,
classical_controls=classical_controls,
control_value=control_value)
self.gates.append(gate)
else:
if end is None:
end = self.N - 1
for i in range(start, end+1):
gate = Gate(name, targets=i, controls=None,
arg_value=arg_value, arg_label=arg_label,
classical_controls=classical_controls,
control_value=control_value)
self.gates.append(gate)
def add_circuit(self, qc, start=0):
"""
Adds a block of a qubit circuit to the main circuit.
Globalphase gates are not added.
Parameters
----------
qc : QubitCircuit
The circuit block to be added to the main circuit.
start : int
The qubit on which the first gate is applied.
"""
if self.N - start < qc.N:
raise NotImplementedError("Targets exceed number of qubits.")
for circuit_op in qc.gates:
if isinstance(circuit_op, Gate):
gate = circuit_op
if gate.name in ["RX", "RY", "RZ",
"SNOT", "SQRTNOT", "PHASEGATE", "QASMU"]:
self.add_gate(gate.name, gate.targets[0] + start, None,
gate.arg_value, gate.arg_label)
elif gate.name in ["X", "Y", "Z", "S", "T"]:
self.add_gate(gate.name, gate.targets[0] + start, None,
None, gate.arg_label)
elif gate.name in ["CPHASE", "CNOT", "CSIGN", "CRX", "CRY",
"CRZ", "CY", "CZ", "CS", "CT"]:
self.add_gate(gate.name, gate.targets[0] + start,
gate.controls[0] + start, gate.arg_value,
gate.arg_label)
elif gate.name in ["BERKELEY", "SWAPalpha", "SWAP", "ISWAP",
"SQRTSWAP", "SQRTISWAP"]:
self.add_gate(gate.name,
[gate.targets[0] + start,
gate.targets[1] + start])
elif gate.name in ["TOFFOLI"]:
self.add_gate(gate.name, gate.targets[0] + start,
[gate.controls[0] + start,
gate.controls[1] + start], None, None)
elif gate.name in ["FREDKIN"]:
self.add_gate(gate.name,
[gate.targets[0] + start,
gate.targets[1] + start],
gate.controls + start, None, None)
elif gate.name in self.user_gates:
self.add_gate(
gate.name, targets=gate.targets,
arg_value=gate.arg_value)
else:
measurement = circuit_op
self.add_measurement(
measurement.name,
targets=[measurement.targets[0] + start],
classical_store=measurement.classical_store)
def remove_gate_or_measurement(self, index=None, end=None,
name=None, remove="first"):
"""
Remove a gate from a specific index or between two indexes or the
first, last or all instances of a particular gate.
Parameters
----------
index : int
Location of gate or measurement to be removed.
name : string
Gate or Measurement name to be removed.
remove : string
If first or all gates/measurements are to be removed.
"""
if index is not None:
if index > len(self.gates):
raise ValueError("Index exceeds number \
of gates + measurements.")
if end is not None and end <= len(self.gates):
for i in range(end - index):
self.gates.pop(index + i)
elif end is not None and end > self.N:
raise ValueError("End target exceeds number \
of gates + measurements.")
else:
self.gates.pop(index)
elif name is not None and remove == "first":
for circuit_op in self.gates:
if name == circuit_op.name:
self.gates.remove(circuit_op)
break
elif name is not None and remove == "last":
for i in reversed(range(len(self.gates))):
if name == self.gates[i].name:
self.gates.pop(i)
break
elif name is not None and remove == "all":
for i in reversed(range(len(self.gates))):
if name == self.gates[i].name:
self.gates.pop(i)
else:
self.gates.pop()
def reverse_circuit(self):
"""
Reverse an entire circuit of unitary gates.
Returns
-------
qubit_circuit : QubitCircuit
Return QubitCircuit of resolved gates for the qubit circuit in the
reverse order.
"""
temp = QubitCircuit(self.N, reverse_states=self.reverse_states,
num_cbits=self.num_cbits,
input_states=self.input_states,
output_states=self.output_states)
for circuit_op in reversed(self.gates):
if isinstance(circuit_op, Gate):
temp.add_gate(circuit_op)
else:
temp.add_measurement(circuit_op)
return temp
def _resolve_to_universal(self, gate, temp_resolved, basis_1q, basis_2q):
"""A dispatch method"""
if gate.name in basis_2q:
method = getattr(self, '_gate_basis_2q')
else:
if gate.name == "SWAP" and "ISWAP" in basis_2q:
method = getattr(self, '_gate_IGNORED')
else:
method = getattr(self, '_gate_' + str(gate.name))
method(gate, temp_resolved)
def _gate_IGNORED(self, gate, temp_resolved):
temp_resolved.append(gate)
_gate_RY = _gate_RZ = _gate_basis_2q = _gate_IGNORED
_gate_CNOT = _gate_RX = _gate_IGNORED
def _gate_SQRTNOT(self, gate, temp_resolved):
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=np.pi / 4, arg_label=r"\pi/4"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi / 2, arg_label=r"\pi/2"))
def _gate_SNOT(self, gate, temp_resolved):
half_pi = np.pi / 2
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
def _gate_PHASEGATE(self, gate, temp_resolved):
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=gate.arg_value / 2,
arg_label=gate.arg_label))
temp_resolved.append(Gate("RZ", gate.targets, None,
gate.arg_value, gate.arg_label))
def _gate_NOTIMPLEMENTED(self, gate, temp_resolved):
raise NotImplementedError("Cannot be resolved in this basis")
_gate_PHASEGATE = _gate_BERKELEY = _gate_SWAPalpha = _gate_NOTIMPLEMENTED
_gate_SQRTSWAP = _gate_SQRTISWAP = _gate_NOTIMPLEMENTED
def _gate_CSIGN(self, gate, temp_resolved):
half_pi = np.pi / 2
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("CNOT", gate.targets, gate.controls))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=np.pi, arg_label=r"\pi"))
def _gate_SWAP(self, gate, temp_resolved):
temp_resolved.append(
Gate("CNOT", gate.targets[0], gate.targets[1]))
temp_resolved.append(
Gate("CNOT", gate.targets[1], gate.targets[0]))
temp_resolved.append(
Gate("CNOT", gate.targets[0], gate.targets[1]))
def _gate_ISWAP(self, gate, temp_resolved):
half_pi = np.pi / 2
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.targets[1]))
temp_resolved.append(Gate("CNOT", gate.targets[1],
gate.targets[0]))
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.targets[1]))
temp_resolved.append(Gate("RZ", gate.targets[0], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RZ", gate.targets[1], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets[0], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets[0], None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.targets[1]))
temp_resolved.append(Gate("RY", gate.targets[0], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets[0], None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
def _gate_FREDKIN(self, gate, temp_resolved):
half_pi = np.pi / 2
eigth_pi = np.pi / 8
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.targets[1]))
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.controls))
temp_resolved.append(Gate("RZ", gate.controls, None,
arg_value=eigth_pi,
arg_label=r"\pi/8"))
temp_resolved.append(Gate("RZ", [gate.targets[0]], None,
arg_value=-eigth_pi,
arg_label=r"-\pi/8"))
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.controls))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets[1], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RZ", gate.targets[0], None,
arg_value=eigth_pi,
arg_label=r"\pi/8"))
temp_resolved.append(Gate("RZ", gate.targets[1], None,
arg_value=eigth_pi,
arg_label=r"\pi/8"))
temp_resolved.append(Gate("CNOT", gate.targets[1],
gate.controls))
temp_resolved.append(Gate("RZ", gate.targets[1], None,
arg_value=-eigth_pi,
arg_label=r"-\pi/8"))
temp_resolved.append(Gate("CNOT", gate.targets[1],
gate.targets[0]))
temp_resolved.append(Gate("RZ", gate.targets[1], None,
arg_value=eigth_pi,
arg_label=r"\pi/8"))
temp_resolved.append(Gate("CNOT", gate.targets[1],
gate.controls))
temp_resolved.append(Gate("RZ", gate.targets[1], None,
arg_value=-eigth_pi,
arg_label=r"-\pi/8"))
temp_resolved.append(Gate("CNOT", gate.targets[1],
gate.targets[0]))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets[1], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("CNOT", gate.targets[0],
gate.targets[1]))
def _gate_TOFFOLI(self, gate, temp_resolved):
half_pi = np.pi / 2
quarter_pi = np.pi / 4
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=np.pi / 8,
arg_label=r"\pi/8"))
temp_resolved.append(Gate("RZ", gate.controls[1], None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RZ", gate.controls[0], None,
arg_value=quarter_pi,
arg_label=r"\pi/4"))
temp_resolved.append(Gate("CNOT", gate.controls[1],
gate.controls[0]))
temp_resolved.append(Gate("RZ", gate.controls[1], None,
arg_value=-quarter_pi,
arg_label=r"-\pi/4"))
temp_resolved.append(Gate("CNOT", gate.controls[1],
gate.controls[0]))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
temp_resolved.append(Gate("RZ", gate.controls[1], None,
arg_value=-quarter_pi,
arg_label=r"-\pi/4"))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=quarter_pi,
arg_label=r"\pi/4"))
temp_resolved.append(Gate("CNOT", gate.targets,
gate.controls[0]))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=-quarter_pi,
arg_label=r"-\pi/4"))
temp_resolved.append(Gate("CNOT", gate.targets,
gate.controls[1]))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=quarter_pi,
arg_label=r"\pi/4"))
temp_resolved.append(Gate("CNOT", gate.targets,
gate.controls[0]))
temp_resolved.append(Gate("RZ", gate.targets, None,
arg_value=-quarter_pi,
arg_label=r"-\pi/4"))
temp_resolved.append(Gate("CNOT", gate.targets,
gate.controls[1]))
temp_resolved.append(Gate("GLOBALPHASE", None, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
temp_resolved.append(Gate("RX", gate.targets, None,
arg_value=np.pi, arg_label=r"\pi"))
def _gate_GLOBALPHASE(self, gate, temp_resolved):
temp_resolved.append(Gate(gate.name, gate.targets,
gate.controls,
gate.arg_value, gate.arg_label))
def _resolve_2q_basis(self, basis, qc_temp, temp_resolved):
"""Dispatch method"""
method = getattr(self, '_basis_' + str(basis), temp_resolved)
method(qc_temp, temp_resolved)
def _basis_CSIGN(self, qc_temp, temp_resolved):
half_pi = np.pi / 2
for gate in temp_resolved:
if gate.name == "CNOT":
qc_temp.gates.append(Gate("RY", gate.targets, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("CSIGN", gate.targets,
gate.controls))
qc_temp.gates.append(Gate("RY", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
else:
qc_temp.gates.append(gate)
def _basis_ISWAP(self, qc_temp, temp_resolved):
half_pi = np.pi / 2
quarter_pi = np.pi / 4
for gate in temp_resolved:
if gate.name == "CNOT":
qc_temp.gates.append(Gate("GLOBALPHASE", None, None,
arg_value=quarter_pi,
arg_label=r"\pi/4"))
qc_temp.gates.append(Gate("ISWAP", [gate.controls[0],
gate.targets[0]],
None))
qc_temp.gates.append(Gate("RZ", gate.targets, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("RY", gate.controls, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("RZ", gate.controls, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
qc_temp.gates.append(Gate("ISWAP", [gate.controls[0],
gate.targets[0]], None))
qc_temp.gates.append(Gate("RY", gate.targets, None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("RZ", gate.targets, None,
arg_value=half_pi,
arg_label=r"\pi/2"))
elif gate.name == "SWAP":
qc_temp.gates.append(Gate("GLOBALPHASE", None, None,
arg_value=quarter_pi,
arg_label=r"\pi/4"))
qc_temp.gates.append(Gate("ISWAP", gate.targets, None))
qc_temp.gates.append(Gate("RX", gate.targets[0], None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("ISWAP", gate.targets, None))
qc_temp.gates.append(Gate("RX", gate.targets[1], None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
qc_temp.gates.append(Gate("ISWAP", [gate.targets[1],
gate.targets[0]], None))
qc_temp.gates.append(Gate("RX", gate.targets[0], None,
arg_value=-half_pi,
arg_label=r"-\pi/2"))
else:
qc_temp.gates.append(gate)
def _basis_SQRTSWAP(self, qc_temp, temp_resolved):
half_pi = np.pi / 2
for gate in temp_resolved:
if gate.name == "CNOT":
qc_temp.gates.append(Gate("RY", gate.targets, None,