-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathquantum_circuit.py
1257 lines (1068 loc) · 39.8 KB
/
quantum_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
# (C) Copyright 2023 Beijing Academy of Quantum Information Sciences
#
# 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
#
# http://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 circuit module."""
# pylint: disable=too-many-lines
import copy
from contextlib import contextmanager
from typing import Any, Iterable, List, Optional, Union
import numpy as np
from ..elements import (
Barrier,
Cif,
CircuitWrapper,
ControlledCircuitWrapper,
ControlledGate,
Delay,
Instruction,
KrausChannel,
Measure,
Parameter,
ParameterExpression,
ParameterType,
QuantumGate,
QuantumPulse,
Reset,
UnitaryChannel,
UnitaryDecomposer,
XYResonance,
)
from ..elements import element_gates as qeg
from ..exceptions import CircuitError
from .classical_register import ClassicalRegister
from .quantum_register import QuantumRegister
# pylint: disable=too-many-public-methods,too-many-instance-attributes
class QuantumCircuit:
"""
Representation of quantum circuit.
"""
def __init__(
self,
qnum: int,
cnum: Optional[int] = None,
name="",
**kwargs, # pylint: disable=unused-argument
):
"""
Initialize a QuantumCircuit object
Args:
qnum (int): Total qubit number used
cnum (int): Classical bit number, equals to qubit number in default
"""
self.name = name
self.qregs = [QuantumRegister(qnum)] if qnum > 0 else []
cnum = self.num if cnum is None else cnum
self.cregs = [ClassicalRegister(cnum)] if cnum > 0 else []
self._gates = []
self.instructions = []
self.openqasm = ""
self.circuit = []
self._measures = []
self.executable_on_backend = True
self._used_qubits = []
self._parameterized_gates = []
self._parameter_grads = {}
self._variables = []
self._has_wrap = False
self._def_para_name = "theta_inner" # default parameter name prefix
self._para_id = 0 # current parameter index
@property
def parameterized_gates(self):
"""Return the list of gates which the parameters are tunable"""
# FIXME: if we add parameterized gates after calling this function it will not work
if not self._parameterized_gates:
self._parameterized_gates = [g for g in self.gates if len(g.paras) != 0]
return self._parameterized_gates
@property
def num(self):
return sum(len(qreg) for qreg in self.qregs)
@num.setter
def num(self, num: int):
self.qregs = [QuantumRegister(num)] if num > 0 else []
self.cregs = [ClassicalRegister(num)] if num > 0 else []
@property
def cbits_num(self):
return sum(len(creg) for creg in self.cregs)
@property
def used_qubits(self) -> List:
self.layered_circuit()
return self._used_qubits
@property
def measures(self):
measures = {}
for meas in self._measures:
measures.update(dict(zip(meas.qbits, meas.cbits)))
return measures
@measures.setter
def measures(self, measures: dict):
self._measures = [Measure(measures)]
@property
def gates(self):
"""Deprecated warning: due to historical reason, ``gates`` contains not only instances of
QuantumGate, meanwhile not contains measurements. This attributes might be deprecated in
the future. Better to use ``instructions`` which contains all the instructions.
"""
return self._gates
@gates.setter
def gates(self, gates: list):
self._gates = gates
def __lshift__(self, operation: Instruction):
max_pos = max(operation.pos) if isinstance(operation.pos, Iterable) else operation.pos
if max_pos >= self.num:
raise CircuitError("Operation act on qubit that not allocated")
self.add_ins(operation)
if isinstance(operation, CircuitWrapper):
self._has_wrap = True
return self
# TODO(qtzhuang): add_gates is just a temporary call function to add gate from gate_list
def add_gates(self, gates: list):
for gate in gates:
self.add_ins(gate)
def add_gate(self, gate: QuantumGate):
"""
Add quantum gate to circuit, with some checking.
"""
pos = np.array(gate.pos)
if np.any(pos >= self.num):
raise CircuitError(f"Gate position out of range: {gate.pos}")
self.gates.append(gate)
def add_pulse(self, pulse: QuantumPulse, pos: int = None) -> "QuantumCircuit":
"""
Add quantum gate from pulse.
"""
if pos is not None:
pulse.set_pos(pos)
self.add_ins(pulse)
return self
def add_ins(self, ins: Instruction):
"""
Add instruction to circuit, with NO checking yet.
"""
if isinstance(ins, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel)):
# TODO: Delay, Barrier added by add_gate for backward compatibility.
# Figure out better handling in the future.
self.add_gate(ins)
self.instructions.append(ins)
# pylint: disable=too-many-branches,too-many-arguments,too-many-positional-arguments
def add_noise(
self,
channel: str,
channel_args,
qubits: Union[None, List[int]] = None,
gates: Union[None, List[str]] = None,
checkgates=True,
):
if qubits is None:
qubits = []
if gates is None:
gates = []
if channel not in ["bitflip", "dephasing", "depolarizing", "ampdamping"]:
raise ValueError("Invalid channel name")
if checkgates:
for g in gates:
if g not in QuantumGate.gate_classes:
raise ValueError("Invalid gate name")
newinstructions = []
newgates = []
for op in self.instructions:
newinstructions.append(op)
if isinstance(op, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel, UnitaryChannel)):
newgates.append(op)
if isinstance(op, QuantumGate):
add_q = False
add_g = False
if qubits:
for q in op.pos:
if q in qubits:
add_q = True
else:
add_q = True
if gates:
if op.name.lower() in gates:
add_g = True
else:
add_g = True
if add_q and add_g:
for q in op.pos:
if q in qubits:
newinstructions.append(Instruction.ins_classes[channel](q, *channel_args))
newgates.append(Instruction.ins_classes[channel](q, *channel_args))
self.instructions = newinstructions
self._gates = newgates
return self
@property
def noised(self):
if self._has_wrap:
self.unwrap()
for op in self.instructions:
if isinstance(op, KrausChannel):
return True
return False
def get_parameter_grads(self):
if self._has_wrap:
print("warning: The circuit has wrapped gates, it will unwarp automaticllay")
self.unwrap()
self._parameter_grads = {}
for i, op in enumerate(self.gates):
for j, para in enumerate(op.paras):
if isinstance(para, Parameter):
if para not in self._parameter_grads:
self._parameter_grads[para] = [[(i, j), 1.0]]
else:
self._parameter_grads[para].append([(i, j), 1.0])
elif isinstance(para, ParameterExpression):
para_grads = para.grad()
for var in para._variables:
if var not in self._parameter_grads:
self._parameter_grads[var] = [[(i, j), para_grads[para._variables[var]]]]
else:
self._parameter_grads[var].append([(i, j), para_grads[para._variables[var]]])
self._variables = list(self._parameter_grads)
return self._parameter_grads
def _calc_parameter_grads(self):
"""
Update parameter gradient value, not variables
"""
for var, grads in self._parameter_grads.items():
for item in grads:
i, j = item[0]
para = self.gates[i].paras[j]
if isinstance(para, ParameterExpression):
para_grads = para.grad()
item[1] = para_grads[para._variables[var]]
return self._parameter_grads
@property
def variables(self):
self._variables = list(self.get_parameter_grads().keys())
return self._variables
def _update_params(self, values, order: Union[None, List] = None, tunable_only: bool = False):
"""
Update variables' value, not variables
Args:
values: list of variables' value.
order: For transplied circuit that change the order of variables,
need pass the order to match untranspiled circuit's variable.
"""
if order is None:
order = []
if len(values) != len(self.variables):
raise CircuitError("The size of input values must be the same to the parameters")
for i, v in enumerate(values):
val = values[order[i]] if order else v
if tunable_only:
if self._variables[i].tunable:
# only update tunable parameters
self._variables[i].value = val
else:
self._variables[i].value = val
# TODO: delete after 0.4.1
def update_params(self, paras_list: List[Any]):
"""Update parameters of parameterized gates
Args:
paras_list (List[Any]): list of params
Raise:
CircuitError
"""
if len(paras_list) != len(self.parameterized_gates):
raise CircuitError("`params_list` must have the same size with parameterized gates")
# TODO(): Support updating part of params of a single gate
for gate, paras in zip(self.parameterized_gates, paras_list):
gate.update_params(paras)
def angles2parameters(self):
"""Transform all float value params to `Parameter`"""
for g in self.gates:
if all(isinstance(x, float) for x in g.paras):
for i, para in enumerate(g.paras):
g.paras[i] = Parameter(f"{self._def_para_name}_{self._para_id}", value=para)
self._para_id += 1
self.get_parameter_grads()
# pylint: disable=too-many-branches
def layered_circuit(self) -> np.ndarray:
"""
Make layered circuit from the gate sequence self.gates.
Returns:
A layered list with left justed circuit.
"""
num = self.num
gatelist = self.gates
gateQlist = [[] for i in range(num)]
used_qubits = []
for gate in gatelist:
if isinstance(gate, (Delay, QuantumPulse)):
gateQlist[gate.pos].append(gate)
if gate.pos not in used_qubits:
used_qubits.append(gate.pos)
else:
pos1 = min(gate.pos)
pos2 = max(gate.pos)
gateQlist[pos1].append(gate)
for j in range(pos1 + 1, pos2 + 1):
gateQlist[j].append(None)
for pos in gate.pos:
if pos not in used_qubits:
used_qubits.append(pos)
maxlayer = max(len(gateQlist[j]) for j in range(pos1, pos2 + 1))
for j in range(pos1, pos2 + 1):
layerj = len(gateQlist[j])
pos = layerj - 1
if not layerj == maxlayer:
for i in range(abs(layerj - maxlayer)):
gateQlist[j].insert(pos, None)
# Add support of used_qubits for Reset and Cif
def get_used_qubits(instructions):
used_q = []
for ins in instructions:
if isinstance(ins, Cif):
used_q_h = get_used_qubits(ins.instructions)
for pos in used_q_h:
if pos not in used_q:
used_q.append(pos)
elif isinstance(ins, Barrier):
continue
if isinstance(ins.pos, int):
if ins.pos not in used_q:
used_q.append(ins.pos)
elif isinstance(ins.pos, list):
for pos in ins.pos:
if pos not in used_q:
used_q.append(pos)
return used_q
# Only consider of reset and cif
for ins in self.instructions:
if isinstance(ins, (Reset, Cif)):
used_q = get_used_qubits([ins])
for pos in used_q:
if pos not in used_qubits:
used_qubits.append(pos)
maxdepth = max(len(gateQlist[i]) for i in range(num))
for gates in gateQlist:
gates.extend([None] * (maxdepth - len(gates)))
for m in self.measures.keys():
if m not in used_qubits:
used_qubits.append(m)
used_qubits = np.sort(used_qubits)
new_gateQlist = []
for old_qi, gates in enumerate(gateQlist):
if old_qi in used_qubits:
new_gateQlist.append(gates)
lc = np.array(new_gateQlist)
lc = np.vstack((used_qubits, lc.T)).T
self.circuit = lc
self._used_qubits = list(used_qubits)
return self.circuit
# pylint: disable=inconsistent-return-statements, too-many-branches
def draw_circuit(self, width: int = 4, return_str: bool = False):
"""
Draw layered circuit using ASCII, print in terminal.
Args:
width (int): The width of each gate.
return_str: Whether return the circuit string.
"""
# TODO: support draw other instructions
self.layered_circuit()
gateQlist = self.circuit
num = gateQlist.shape[0]
depth = gateQlist.shape[1] - 1
printlist = np.array([[""] * depth for i in range(2 * num)], dtype="<U30")
reduce_map = dict(zip(gateQlist[:, 0], range(num)))
reduce_map_inv = dict(zip(range(num), gateQlist[:, 0]))
# pylint: disable=too-many-nested-blocks
for l in range(depth):
layergates = gateQlist[:, l + 1]
maxlen = 1 + width
for i in range(num):
gate = layergates[i]
if isinstance(gate, Barrier):
pos = [i for i in gate.pos if i in reduce_map.keys()]
q1 = reduce_map[min(pos)]
q2 = reduce_map[max(pos)]
printlist[2 * q1 : 2 * q2 + 1, l] = "||"
maxlen = max(maxlen, len("||"))
elif isinstance(gate, Instruction) and len(gate.pos) == 1:
printlist[i * 2, l] = gate.symbol
maxlen = max(maxlen, len(gate.symbol) + width)
elif isinstance(gate, Instruction) and len(gate.pos) > 1:
q1 = reduce_map[min(gate.pos)]
q2 = reduce_map[max(gate.pos)]
printlist[2 * q1 + 1 : 2 * q2, l] = "|"
printlist[q1 * 2, l] = "#"
printlist[q2 * 2, l] = "#"
if isinstance(gate, ControlledGate): # Controlled-Multiqubit gate
for ctrl in gate.ctrls:
printlist[reduce_map[ctrl] * 2, l] = "*"
if gate._targ_name == "SWAP":
printlist[reduce_map[gate.targs[0]] * 2, l] = "x"
printlist[reduce_map[gate.targs[1]] * 2, l] = "x"
else:
tq1 = reduce_map[min(gate.targs)]
tq2 = reduce_map[max(gate.targs)]
printlist[tq1 * 2, l] = "#"
printlist[tq2 * 2, l] = "#"
if tq1 + tq2 in [reduce_map[ctrl] * 2 for ctrl in gate.ctrls]:
printlist[tq1 + tq2, l] = "*" + gate.symbol
else:
printlist[tq1 + tq2, l] = gate.symbol
maxlen = max(maxlen, len(gate.symbol) + width)
else: # Multiqubit gate
if gate.name == "SWAP":
printlist[q1 * 2, l] = "x"
printlist[q2 * 2, l] = "x"
else:
printlist[q1 + q2, l] = gate.symbol
maxlen = max(maxlen, len(gate.symbol) + width)
printlist[-1, l] = maxlen
circuitstr = []
for j in range(2 * num - 1):
if j % 2 == 0:
linestr = f'q[{reduce_map_inv[j // 2]}]'.ljust(6)
linestr += ''.join([printlist[j, l].center(int(printlist[-1, l]), "-") for l in range(depth)])
if reduce_map_inv[j // 2] in self.measures.keys():
linestr += f" M->c[{self.measures[reduce_map_inv[j // 2]]}]"
circuitstr.append(linestr)
else:
circuitstr.append(
"".ljust(6) + "".join([printlist[j, l].center(int(printlist[-1, l]), " ") for l in range(depth)])
)
circuitstr = "\n".join(circuitstr)
if return_str:
return circuitstr
print(circuitstr)
return # noqa:R502
def plot_circuit(self, *args, **kwargs):
# pylint: disable=import-outside-toplevel
from quafu.visualisation.circuit_plot import CircuitPlotManager
cmp = CircuitPlotManager(self)
return cmp(*args, **kwargs)
def from_openqasm(self, openqasm: str):
"""
Initialize the circuit from openqasm text.
Args:
openqasm: input openqasm str.
"""
# pylint: disable=import-outside-toplevel
from quafu.qfasm.qfasm_convertor import qasm2_to_quafu_qc
return qasm2_to_quafu_qc(self, openqasm)
def to_openqasm(self, with_para=False) -> str:
"""
Convert the circuit to openqasm text.
Returns:
openqasm text.
"""
valid_gates = list(QuantumGate.gate_classes.keys()) # TODO:include instruction futher
valid_gates.extend(["barrier", "delay", "reset"])
qasm = 'OPENQASM 2.0;\ninclude "qelib1.inc";\n'
qasm += f"qreg q[{self.num}];\n"
qasm += f"creg meas[{self.cbits_num}];\n"
if with_para:
for variable in self.variables:
qasm += f"{variable.latex} = {variable.value};\n"
for gate in self.gates:
if gate.name.lower() in valid_gates:
qasm += gate.to_qasm(with_para) + ";\n"
else:
# TODO: add decompose subroutine
raise NotImplementedError(
f"gate {gate.name} can not convert to qasm2 directly, you may decompose it manuallly"
)
for key in self.measures:
qasm += f"measure q[{key}] -> meas[{self.measures[key]}];\n"
self.openqasm = qasm
return qasm
def wrap_to_gate(self, name: str):
"""
Wrap the circuit to a subclass of QuantumGate, create by metaclass.
"""
# pylint: disable=import-outside-toplevel
from copy import deepcopy
from quafu.elements.oracle import customize_gate
# TODO: check validity of instructions
gate_structure = [deepcopy(ins) for ins in self.instructions]
return customize_gate(name, gate_structure, self.num)
def _reallocate(self, num, qbits: List[int]):
"""Remap the qubits and gates to new positions."""
assert self.num == len(qbits)
if max(qbits) > num:
raise CircuitError("Bad allocation")
self.num = num
qbits_map = dict(zip(range(len(qbits)), qbits))
gates = self.instructions
for op in gates:
for i, ops in enumerate(op.pos):
op.pos[i] = qbits_map[ops]
if isinstance(op, ControlledGate):
for i, ctrl in enumerate(op.ctrls):
op.ctrls[i] = qbits_map[ctrl]
for i, targ in enumerate(op.targs):
op.targs[i] = qbits_map[targ]
def add_controls(
self, ctrlnum, ctrls: Union[None, List[int]] = None, targs: Union[None, List[int]] = None, inplace=False
) -> "QuantumCircuit":
if ctrls is None:
ctrls = []
if targs is None:
targs = []
num = 0
instrs = []
if len(ctrls + targs) == 0:
ctrls = list(np.arange(ctrlnum) + self.num)
num = self.num + ctrlnum
instrs = self.instructions
else:
if len(ctrls) == 0 or len(targs) == 0:
raise ValueError("Must provide both ctrls and targs")
assert len(targs) == self.num
assert len(ctrls) == ctrlnum
num = max(ctrls + targs) + 1
if inplace:
self._reallocate(num, targs)
else:
temp = copy.deepcopy(self)
temp._reallocate(num, targs)
instrs = temp.instructions
if inplace:
for op in self.instructions:
if isinstance(op, QuantumGate):
op = op.ctrl_by(ctrls)
return self
qc = QuantumCircuit(num)
for op in instrs:
if isinstance(op, QuantumGate):
qc << op.ctrl_by(ctrls)
return qc
# pylint: disable=too-many-branches
def join(
self,
qc: Union["QuantumCircuit", CircuitWrapper, ControlledCircuitWrapper],
qbits: Union[None, List[int]] = None,
inplace=True,
) -> "QuantumCircuit":
if qbits is None:
qbits = []
num = self.num
rnum = 0
if isinstance(qc, QuantumCircuit):
rnum = qc.num
else:
rnum = qc.circuit.num
if len(qbits) == 0:
num = max(self.num, rnum)
else:
num = max(self.num - 1, max(qbits)) + 1 # pylint: disable=nested-min-max
nqc = QuantumCircuit(num)
if inplace:
self.num = num
nqc = self
else:
for op in self.instructions:
nqc << op
if isinstance(qc, QuantumCircuit):
if qbits:
newqc = copy.deepcopy(qc)
newqc._reallocate(num, qbits)
for op in newqc.instructions:
nqc << op
else:
for op in qc.instructions:
nqc << op
else:
if qbits:
qc._reallocate(qbits)
nqc << qc
return nqc
def power(self, n, inplace=False):
if inplace:
for _ in range(n - 1):
self.instructions += self.instructions
return self
nq = QuantumCircuit(self.num)
for _ in range(n):
for op in self.instructions:
nq << op
nq.measures = self.measures
return nq
def dagger(self, inplace=False):
if inplace:
self.instructions = self.instructions[::-1]
for op in self.instructions:
if isinstance(op, QuantumGate):
op = op.dagger()
return self
nq = QuantumCircuit(self.num)
for op in self.instructions[::-1]:
if isinstance(op, QuantumGate):
nq << op.dagger()
else:
nq << op
nq.measures = self.measures
return nq
def wrap(self, qbits=None):
if qbits is None:
qbits = []
name = self.name if self.name else "Oracle"
return CircuitWrapper(name, self, qbits)
def unwrap(self):
instructions = []
gates = []
for op in self.instructions:
if isinstance(op, CircuitWrapper):
circ = op.circuit.unwrap()
for op_ in circ.instructions:
instructions.append(op_)
if isinstance(op_, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel)):
gates.append(op_)
else:
instructions.append(op)
if isinstance(op, (QuantumGate, Delay, Barrier, XYResonance, KrausChannel)):
gates.append(op)
self.instructions = instructions
self._gates = gates
self._has_wrap = False
return self
# # # # # # # # # # # # # # helper functions # # # # # # # # # # # # # #
def id(self, pos: int) -> "QuantumCircuit": # noqa: A003
"""
Identity gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.IdGate(pos)
self.add_ins(gate)
return self
def h(self, pos: int) -> "QuantumCircuit":
"""
Hadamard gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.HGate(pos)
self.add_ins(gate)
return self
def x(self, pos: int) -> "QuantumCircuit":
"""
X gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.XGate(pos)
self.add_ins(gate)
return self
def y(self, pos: int) -> "QuantumCircuit":
"""
Y gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.YGate(pos)
self.add_ins(gate)
return self
def z(self, pos: int) -> "QuantumCircuit":
"""
Z gate.
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.ZGate(pos))
return self
def t(self, pos: int) -> "QuantumCircuit":
"""
T gate. (~Z^(1/4))
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.TGate(pos))
return self
def tdg(self, pos: int) -> "QuantumCircuit":
"""
Tdg gate. (Inverse of T gate)
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.TdgGate(pos))
return self
def s(self, pos: int) -> "QuantumCircuit":
"""
S gate. (~√Z)
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.SGate(pos))
return self
def sdg(self, pos: int) -> "QuantumCircuit":
"""
Sdg gate. (Inverse of S gate)
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.SdgGate(pos))
return self
def sx(self, pos: int) -> "QuantumCircuit":
"""
√X gate.
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.SXGate(pos))
return self
def sxdg(self, pos: int) -> "QuantumCircuit":
"""
Inverse of √X gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.SXdgGate(pos)
self.add_ins(gate)
return self
def sy(self, pos: int) -> "QuantumCircuit":
"""
√Y gate.
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.SYGate(pos))
return self
def sydg(self, pos: int) -> "QuantumCircuit":
"""
Inverse of √Y gate.
Args:
pos (int): qubit the gate act.
"""
gate = qeg.SYdgGate(pos)
self.add_ins(gate)
return self
def w(self, pos: int) -> "QuantumCircuit":
"""
W gate. (~(X + Y)/√2)
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.WGate(pos))
return self
def sw(self, pos: int) -> "QuantumCircuit":
"""
√W gate.
Args:
pos (int): qubit the gate act.
"""
self.add_ins(qeg.SWGate(pos))
return self
def rx(self, pos: int, para: ParameterType) -> "QuantumCircuit":
"""
Single qubit rotation Rx gate.
Args:
pos (int): qubit the gate act.
para (float): rotation angle
"""
self.add_ins(qeg.RXGate(pos, para))
return self
def ry(self, pos: int, para: ParameterType) -> "QuantumCircuit":
"""
Single qubit rotation Ry gate.
Args:
pos (int): qubit the gate act.
para (float): rotation angle
"""
self.add_ins(qeg.RYGate(pos, para))
return self
def rz(self, pos: int, para: ParameterType) -> "QuantumCircuit":
"""
Single qubit rotation Rz gate.
Args:
pos (int): qubit the gate act.
para (float): rotation angle
"""
self.add_ins(qeg.RZGate(pos, para))
return self
def p(self, pos: int, para: ParameterType) -> "QuantumCircuit":
"""
Phase gate
Args:
pos (int): qubit the gate act.
para (float): rotation angle
"""
self.add_ins(qeg.PhaseGate(pos, para))
return self
def cnot(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
CNOT gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
"""
self.add_ins(qeg.CXGate(ctrl, tar))
return self
def cx(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
Ally of cnot.
"""
return self.cnot(ctrl=ctrl, tar=tar)
def cy(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
Control-Y gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
"""
self.add_ins(qeg.CYGate(ctrl, tar))
return self
def cz(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
Control-Z gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
"""
self.add_ins(qeg.CZGate(ctrl, tar))
return self
def cs(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
Control-S gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
"""
self.add_ins(qeg.CSGate(ctrl, tar))
return self
def ct(self, ctrl: int, tar: int) -> "QuantumCircuit":
"""
Control-T gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
"""
self.add_ins(qeg.CTGate(ctrl, tar))
return self
def cp(self, ctrl: int, tar: int, para: ParameterType) -> "QuantumCircuit":
"""
Control-P gate.
Args:
ctrl (int): control qubit.
tar (int): target qubit.
para: theta
"""
self.add_ins(qeg.CPGate(ctrl, tar, para))
return self
def swap(self, q1: int, q2: int) -> "QuantumCircuit":
"""
SWAP gate
Args:
q1 (int): qubit the gate act.