forked from Qiskit/qiskit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_compose.py
885 lines (738 loc) · 39.7 KB
/
test_compose.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
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# 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.
# pylint: disable=invalid-name
"""Test QuantumCircuit.compose()."""
import unittest
import numpy as np
from qiskit import transpile
from qiskit.pulse import Schedule
from qiskit.circuit import (
QuantumRegister,
ClassicalRegister,
Clbit,
QuantumCircuit,
Qubit,
Parameter,
Gate,
Instruction,
CASE_DEFAULT,
SwitchCaseOp,
)
from qiskit.circuit.library import HGate, RZGate, CXGate, CCXGate, TwoLocal
from qiskit.circuit.classical import expr
from qiskit.test import QiskitTestCase
class TestCircuitCompose(QiskitTestCase):
"""Test composition of two circuits."""
def setUp(self):
super().setUp()
qreg1 = QuantumRegister(3, "lqr_1")
qreg2 = QuantumRegister(2, "lqr_2")
creg = ClassicalRegister(2, "lcr")
self.circuit_left = QuantumCircuit(qreg1, qreg2, creg)
self.circuit_left.h(qreg1[0])
self.circuit_left.x(qreg1[1])
self.circuit_left.p(0.1, qreg1[2])
self.circuit_left.cx(qreg2[0], qreg2[1])
self.left_qubit0 = qreg1[0]
self.left_qubit1 = qreg1[1]
self.left_qubit2 = qreg1[2]
self.left_qubit3 = qreg2[0]
self.left_qubit4 = qreg2[1]
self.left_clbit0 = creg[0]
self.left_clbit1 = creg[1]
self.condition = (creg, 3)
def test_compose_inorder(self):
"""Composing two circuits of the same width, default order.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ =
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── rqr_3: |0>┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════
lcr_1: 0 ═══════════
┌───┐
lqr_1_0: |0>──┤ H ├─────■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─────┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├──┼──┤ Y ├
└────────┘┌─┴─┐└───┘
lqr_2_0: |0>────■─────┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├────────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════════════════
lcr_1: 0 ═══════════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
circuit_composed = self.circuit_left.compose(circuit_right, inplace=False)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_inorder_unusual_types(self):
"""Test that composition works in order, using Numpy integer types as well as regular
integer types. In general, it should be permissible to use any of the same `QubitSpecifier`
types (or similar for `Clbit`) that `QuantumCircuit.append` uses."""
qreg = QuantumRegister(5, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_right.measure([0, 1], [0, 1])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
circuit_expected.measure(self.left_qubit0, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
circuit_composed = self.circuit_left.compose(circuit_right, np.arange(5), slice(0, 2))
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_inorder_inplace(self):
"""Composing two circuits of the same width, default order, inplace.
┌───┐
lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>───┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌──┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ U1(0.1) ├ + rqr_2: |0>──┼──┤ Y ├ =
└─────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>─────■───── rqr_3: |0>┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>───┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ═══════════
lcr_1: 0 ═══════════
┌───┐
lqr_1_0: |0>───┤ H ├─────■───────
├───┤ │ ┌───┐
lqr_1_1: |0>───┤ X ├─────┼──┤ X ├
┌──┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ U1(0.1) ├──┼──┤ Y ├
└─────────┘┌─┴─┐└───┘
lqr_2_0: |0>─────■─────┤ X ├─────
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>───┤ X ├────────┤ Z ├
└───┘ └───┘
lcr_0: 0 ════════════════════════
lcr_1: 0 ════════════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit3)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.z(self.left_qubit4)
# inplace
circuit_left = self.circuit_left.copy()
circuit_left.compose(circuit_right, inplace=True)
self.assertEqual(circuit_left, circuit_expected)
def test_compose_inorder_smaller(self):
"""Composing with a smaller RHS dag, default order.
┌───┐ ┌─────┐
lqr_1_0: |0>───┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>───┤ X ├─── rqr_1: |0>┤ X ├───────
┌──┴───┴──┐ └───┘
lqr_1_2: |0>┤ U1(0.1) ├ + =
└─────────┘
lqr_2_0: |0>─────■─────
┌─┴─┐
lqr_2_1: |0>───┤ X ├───
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐ ┌─────┐
lqr_1_0: |0>───┤ H ├─────■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>───┤ X ├───┤ X ├───────
┌──┴───┴──┐└───┘
lqr_1_2: |0>┤ U1(0.1) ├────────────
└─────────┘
lqr_2_0: |0>─────■─────────────────
┌─┴─┐
lqr_2_1: |0>───┤ X ├───────────────
└───┘
lcr_0: 0 ══════════════════════════
lcr_1: 0 ══════════════════════════
"""
qreg = QuantumRegister(2, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit0, self.left_qubit1)
circuit_expected.tdg(self.left_qubit0)
circuit_composed = self.circuit_left.compose(circuit_right)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted(self):
"""Composing two dags of the same width, permuted wires.
┌───┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■───────
├───┤ │ ┌───┐
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>──┼──┤ X ├
┌─┴───┴──┐ │ ├───┤
lqr_1_2: |0>┤ P(0.1) ├ rqr_2: |0>──┼──┤ Y ├
└────────┘ ┌─┴─┐└───┘
lqr_2_0: |0>────■───── + rqr_3: |0>┤ X ├───── =
┌─┴─┐ └───┘┌───┐
lqr_2_1: |0>──┤ X ├─── rqr_4: |0>─────┤ Z ├
└───┘ └───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐ ┌───┐
lqr_1_0: |0>──┤ H ├───┤ Z ├
├───┤ ├───┤
lqr_1_1: |0>──┤ X ├───┤ X ├
┌─┴───┴──┐├───┤
lqr_1_2: |0>┤ P(0.1) ├┤ Y ├
└────────┘└───┘
lqr_2_0: |0>────■───────■──
┌─┴─┐ ┌─┴─┐
lqr_2_1: |0>──┤ X ├───┤ X ├
└───┘ └───┘
lcr_0: 0 ══════════════════
lcr_1: 0 ══════════════════
"""
qreg = QuantumRegister(5, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[3])
circuit_right.x(qreg[1])
circuit_right.y(qreg[2])
circuit_right.z(qreg[4])
circuit_expected = self.circuit_left.copy()
circuit_expected.z(self.left_qubit0)
circuit_expected.x(self.left_qubit1)
circuit_expected.y(self.left_qubit2)
circuit_expected.cx(self.left_qubit3, self.left_qubit4)
# permuted wiring
circuit_composed = self.circuit_left.compose(
circuit_right,
qubits=[
self.left_qubit3,
self.left_qubit1,
self.left_qubit2,
self.left_qubit4,
self.left_qubit0,
],
inplace=False,
)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_permuted_smaller(self):
"""Composing with a smaller RHS dag, and permuted wires.
Compose using indices.
┌───┐ ┌─────┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├
├───┤ ┌─┴─┐└─────┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├───────
┌─┴───┴──┐ └───┘
lqr_1_2: |0>┤ P(0.1) ├ + =
└────────┘
lqr_2_0: |0>────■─────
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ═════════════
lcr_1: 0 ═════════════
┌───┐
lqr_1_0: |0>──┤ H ├───────────────
├───┤
lqr_1_1: |0>──┤ X ├───────────────
┌─┴───┴──┐┌───┐
lqr_1_2: |0>┤ P(0.1) ├┤ X ├───────
└────────┘└─┬─┘┌─────┐
lqr_2_0: |0>────■───────■──┤ Tdg ├
┌─┴─┐ └─────┘
lqr_2_1: |0>──┤ X ├───────────────
└───┘
lcr_0: 0 ═════════════════════════
lcr_1: 0 ═════════════════════════
"""
qreg = QuantumRegister(2, "rqr")
circuit_right = QuantumCircuit(qreg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
# permuted wiring of subset
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[3, 2])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit3, self.left_qubit2)
circuit_expected.tdg(self.left_qubit3)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_classical(self):
"""Composing on classical bits.
┌───┐ ┌─────┐┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: |0>──■──┤ Tdg ├┤M├
├───┤ ┌─┴─┐└─┬─┬─┘└╥┘
lqr_1_1: |0>──┤ X ├─── rqr_1: |0>┤ X ├──┤M├───╫─
┌─┴───┴──┐ └───┘ └╥┘ ║
lqr_1_2: |0>┤ P(0.1) ├ + rcr_0: 0 ════════╬════╩═ =
└────────┘ ║
lqr_2_0: |0>────■───── rcr_1: 0 ════════╩══════
┌─┴─┐
lqr_2_1: |0>──┤ X ├───
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐
lqr_1_0: |0>──┤ H ├──────────────────
├───┤ ┌─────┐┌─┐
lqr_1_1: |0>──┤ X ├─────■──┤ Tdg ├┤M├
┌─┴───┴──┐ │ └─────┘└╥┘
lqr_1_2: |0>┤ P(0.1) ├──┼──────────╫─
└────────┘ │ ║
lqr_2_0: |0>────■───────┼──────────╫─
┌─┴─┐ ┌─┴─┐ ┌─┐ ║
lqr_2_1: |0>──┤ X ├───┤ X ├──┤M├───╫─
└───┘ └───┘ └╥┘ ║
lcr_0: 0 ══════════════════╩════╬═
║
lcr_1: 0 ═══════════════════════╩═
"""
qreg = QuantumRegister(2, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.cx(qreg[0], qreg[1])
circuit_right.tdg(qreg[0])
circuit_right.measure(qreg, creg)
# permuted subset of qubits and clbits
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[1, 0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit1, self.left_qubit4)
circuit_expected.tdg(self.left_qubit1)
circuit_expected.measure(self.left_qubit4, self.left_clbit0)
circuit_expected.measure(self.left_qubit1, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_conditional(self):
"""Composing on classical bits.
┌───┐ ┌───┐ ┌─┐
lqr_1_0: |0>──┤ H ├─── rqr_0: ────────┤ H ├─┤M├───
├───┤ ┌───┐ └─┬─┘ └╥┘┌─┐
lqr_1_1: |0>──┤ X ├─── rqr_1: ─┤ X ├────┼────╫─┤M├
┌─┴───┴──┐ └─┬─┘ │ ║ └╥┘
lqr_1_2: |0>┤ P(0.1) ├ + ┌──┴──┐┌──┴──┐ ║ ║
└────────┘ rcr_0: ╡ ╞╡ ╞═╩══╬═
lqr_2_0: |0>────■───── │ = 3 ││ = 3 │ ║
┌─┴─┐ rcr_1: ╡ ╞╡ ╞════╩═
lqr_2_1: |0>──┤ X ├─── └─────┘└─────┘
└───┘
lcr_0: 0 ══════════════
lcr_1: 0 ══════════════
┌───┐
lqr_1_0: ──┤ H ├───────────────────────
├───┤ ┌───┐ ┌─┐
lqr_1_1: ──┤ X ├───────────┤ H ├────┤M├
┌─┴───┴──┐ └─┬─┘ └╥┘
lqr_1_2: ┤ P(0.1) ├──────────┼───────╫─
└────────┘ │ ║
lqr_2_0: ────■───────────────┼───────╫─
┌─┴─┐ ┌───┐ │ ┌─┐ ║
lqr_2_1: ──┤ X ├────┤ X ├────┼───┤M├─╫─
└───┘ └─┬─┘ │ └╥┘ ║
┌──┴──┐┌──┴──┐ ║ ║
lcr_0: ════════════╡ ╞╡ ╞═╬══╩═
│ = 3 ││ = 3 │ ║
lcr_1: ════════════╡ ╞╡ ╞═╩════
└─────┘└─────┘
"""
qreg = QuantumRegister(2, "rqr")
creg = ClassicalRegister(2, "rcr")
circuit_right = QuantumCircuit(qreg, creg)
circuit_right.x(qreg[1]).c_if(creg, 3)
circuit_right.h(qreg[0]).c_if(creg, 3)
circuit_right.measure(qreg, creg)
# permuted subset of qubits and clbits
circuit_composed = self.circuit_left.compose(circuit_right, qubits=[1, 4], clbits=[0, 1])
circuit_expected = self.circuit_left.copy()
circuit_expected.x(self.left_qubit4).c_if(*self.condition)
circuit_expected.h(self.left_qubit1).c_if(*self.condition)
circuit_expected.measure(self.left_qubit1, self.left_clbit0)
circuit_expected.measure(self.left_qubit4, self.left_clbit1)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_conditional_no_match(self):
"""Test that compose correctly maps registers in conditions to the new circuit, even when
there are no matching registers in the destination circuit.
Regression test of gh-6583 and gh-6584."""
right = QuantumCircuit(QuantumRegister(3), ClassicalRegister(1), ClassicalRegister(1))
right.h(1)
right.cx(1, 2)
right.cx(0, 1)
right.h(0)
right.measure([0, 1], [0, 1])
right.z(2).c_if(right.cregs[0], 1)
right.x(2).c_if(right.cregs[1], 1)
test = QuantumCircuit(3, 3).compose(right, range(3), range(2))
z = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "z")
x = next(ins.operation for ins in test.data[::-1] if ins.operation.name == "x")
# The registers should have been mapped, including the bits inside them. Unlike the
# previous test, there are no matching registers in the destination circuit, so the
# composition needs to add new registers (bit groupings) over the existing mapped bits.
self.assertIsNot(z.condition, None)
self.assertIsInstance(z.condition[0], ClassicalRegister)
self.assertEqual(len(z.condition[0]), len(right.cregs[0]))
self.assertIs(z.condition[0][0], test.clbits[0])
self.assertEqual(z.condition[1], 1)
self.assertIsNot(x.condition, None)
self.assertIsInstance(x.condition[0], ClassicalRegister)
self.assertEqual(len(x.condition[0]), len(right.cregs[1]))
self.assertEqual(z.condition[1], 1)
self.assertIs(x.condition[0][0], test.clbits[1])
def test_compose_switch_match(self):
"""Test that composition containing a `switch` with a register that matches proceeds
correctly."""
case_0 = QuantumCircuit(1, 2)
case_0.x(0)
case_1 = QuantumCircuit(1, 2)
case_1.z(0)
case_default = QuantumCircuit(1, 2)
cr = ClassicalRegister(2, "target")
right = QuantumCircuit(QuantumRegister(1), cr)
right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1])
test = QuantumCircuit(QuantumRegister(3), cr, ClassicalRegister(2)).compose(
right, [1], [0, 1]
)
expected = test.copy_empty_like()
expected.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [1], [0, 1])
self.assertEqual(test, expected)
def test_compose_switch_no_match(self):
"""Test that composition containing a `switch` with a register that matches proceeds
correctly."""
case_0 = QuantumCircuit(1, 2)
case_0.x(0)
case_1 = QuantumCircuit(1, 2)
case_1.z(0)
case_default = QuantumCircuit(1, 2)
cr = ClassicalRegister(2, "target")
right = QuantumCircuit(QuantumRegister(1), cr)
right.switch(cr, [(0, case_0), (1, case_1), (CASE_DEFAULT, case_default)], [0], [0, 1])
test = QuantumCircuit(3, 3).compose(right, [1], [0, 1])
self.assertEqual(len(test.data), 1)
self.assertIsInstance(test.data[0].operation, SwitchCaseOp)
target = test.data[0].operation.target
self.assertIn(target, test.cregs)
self.assertEqual(list(target), test.clbits[0:2])
def test_compose_gate(self):
"""Composing with a gate.
┌───┐ ┌───┐ ┌───┐
lqr_1_0: ──┤ H ├─── lqr_1_0: ──┤ H ├────┤ X ├
├───┤ ├───┤ └─┬─┘
lqr_1_1: ──┤ X ├─── lqr_1_1: ──┤ X ├──────┼───
┌─┴───┴──┐ ───■─── ┌─┴───┴──┐ │
lqr_1_2: ┤ P(0.1) ├ + ┌─┴─┐ = lqr_1_2: ┤ P(0.1) ├───┼───
└────────┘ ─┤ X ├─ └────────┘ │
lqr_2_0: ────■───── └───┘ lqr_2_0: ────■────────┼──
┌─┴─┐ ┌─┴─┐ │
lqr_2_1: ──┤ X ├─── lqr_2_1: ──┤ X ├──────■───
└───┘ └───┘
lcr_0: 0 ══════════ lcr_0: 0 ═════════════════
lcr_1: 0 ══════════ lcr_1: 0 ═════════════════
"""
circuit_composed = self.circuit_left.compose(CXGate(), qubits=[4, 0])
circuit_expected = self.circuit_left.copy()
circuit_expected.cx(self.left_qubit4, self.left_qubit0)
self.assertEqual(circuit_composed, circuit_expected)
def test_compose_calibrations(self):
"""Test that composing two circuits updates calibrations."""
circ_left = QuantumCircuit(1)
circ_left.add_calibration("h", [0], None)
circ_right = QuantumCircuit(1)
circ_right.add_calibration("rx", [0], None)
circ = circ_left.compose(circ_right)
self.assertEqual(len(circ.calibrations), 2)
self.assertEqual(len(circ_left.calibrations), 1)
circ_left = QuantumCircuit(1)
circ_left.add_calibration("h", [0], None)
circ_right = QuantumCircuit(1)
circ_right.add_calibration("h", [1], None)
circ = circ_left.compose(circ_right)
self.assertEqual(len(circ.calibrations), 1)
self.assertEqual(len(circ.calibrations["h"]), 2)
self.assertEqual(len(circ_left.calibrations), 1)
# Ensure that transpiled _calibration is defaultdict
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure(0, 0)
qc = transpile(qc, None, basis_gates=["h", "cx"], coupling_map=[[0, 1], [1, 0]])
qc.add_calibration("cx", [0, 1], Schedule())
def test_compose_one_liner(self):
"""Test building a circuit in one line, for fun."""
circ = QuantumCircuit(3)
h = HGate()
rz = RZGate(0.1)
cx = CXGate()
ccx = CCXGate()
circ = circ.compose(h, [0]).compose(cx, [0, 2]).compose(ccx, [2, 1, 0]).compose(rz, [1])
expected = QuantumCircuit(3)
expected.h(0)
expected.cx(0, 2)
expected.ccx(2, 1, 0)
expected.rz(0.1, 1)
self.assertEqual(circ, expected)
def test_compose_global_phase(self):
"""Composing with global phase."""
circ1 = QuantumCircuit(1, global_phase=1)
circ1.rz(0.5, 0)
circ2 = QuantumCircuit(1, global_phase=2)
circ3 = QuantumCircuit(1, global_phase=3)
circ4 = circ1.compose(circ2).compose(circ3)
self.assertEqual(
circ4.global_phase, circ1.global_phase + circ2.global_phase + circ3.global_phase
)
def test_compose_front_circuit(self):
"""Test composing a circuit at the front of a circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
other = QuantumCircuit(2)
other.cz(1, 0)
other.z(1)
output = qc.compose(other, front=True)
expected = QuantumCircuit(2)
expected.cz(1, 0)
expected.z(1)
expected.h(0)
expected.cx(0, 1)
self.assertEqual(output, expected)
def test_compose_front_gate(self):
"""Test composing a gate at the front of a circuit."""
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
output = qc.compose(CXGate(), [1, 0], front=True)
expected = QuantumCircuit(2)
expected.cx(1, 0)
expected.h(0)
expected.cx(0, 1)
self.assertEqual(output, expected)
def test_compose_adds_parameters(self):
"""Test the composed circuit contains all parameters."""
a, b = Parameter("a"), Parameter("b")
qc_a = QuantumCircuit(1)
qc_a.rx(a, 0)
qc_b = QuantumCircuit(1)
qc_b.rx(b, 0)
with self.subTest("compose with other circuit out-of-place"):
qc_1 = qc_a.compose(qc_b)
self.assertEqual(qc_1.parameters, {a, b})
with self.subTest("compose with other instruction out-of-place"):
instr_b = qc_b.to_instruction()
qc_2 = qc_a.compose(instr_b, [0])
self.assertEqual(qc_2.parameters, {a, b})
with self.subTest("compose with other circuit in-place"):
qc_a.compose(qc_b, inplace=True)
self.assertEqual(qc_a.parameters, {a, b})
def test_wrapped_compose(self):
"""Test wrapping the circuit upon composition works."""
qc_a = QuantumCircuit(1)
qc_a.x(0)
qc_b = QuantumCircuit(1, name="B")
qc_b.h(0)
qc_a.compose(qc_b, wrap=True, inplace=True)
self.assertDictEqual(qc_a.count_ops(), {"B": 1, "x": 1})
self.assertDictEqual(qc_a.decompose().count_ops(), {"h": 1, "u3": 1})
def test_wrapping_unitary_circuit(self):
"""Test a unitary circuit will be wrapped as Gate, else as Instruction."""
qc_init = QuantumCircuit(1)
qc_init.x(0)
qc_unitary = QuantumCircuit(1, name="a")
qc_unitary.ry(0.23, 0)
qc_nonunitary = QuantumCircuit(1)
qc_nonunitary.reset(0)
with self.subTest("wrapping a unitary circuit"):
qc = qc_init.compose(qc_unitary, wrap=True)
self.assertIsInstance(qc.data[1].operation, Gate)
with self.subTest("wrapping a non-unitary circuit"):
qc = qc_init.compose(qc_nonunitary, wrap=True)
self.assertIsInstance(qc.data[1].operation, Instruction)
def test_single_bit_condition(self):
"""Test that compose can correctly handle circuits that contain conditions on single
bits. This is a regression test of the bug that broke qiskit-experiments in gh-7653."""
base = QuantumCircuit(1, 1)
base.x(0).c_if(0, True)
test = QuantumCircuit(1, 1).compose(base)
self.assertIsNot(base.clbits[0], test.clbits[0])
self.assertEqual(base, test)
self.assertIs(test.data[0].operation.condition[0], test.clbits[0])
def test_condition_mapping_ifelseop(self):
"""Test that the condition in an `IfElseOp` is correctly mapped to a new set of bits and
registers."""
base_loose = Clbit()
base_creg = ClassicalRegister(2)
base_qreg = QuantumRegister(1)
base = QuantumCircuit(base_qreg, [base_loose], base_creg)
with base.if_test((base_loose, True)):
base.x(0)
with base.if_test((base_creg, 3)):
base.x(0)
test_loose = Clbit()
test_creg = ClassicalRegister(2)
test_qreg = QuantumRegister(1)
test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base)
bit_instruction = test.data[0].operation
reg_instruction = test.data[1].operation
self.assertIs(bit_instruction.condition[0], test_loose)
self.assertEqual(bit_instruction.condition, (test_loose, True))
self.assertIs(reg_instruction.condition[0], test_creg)
self.assertEqual(reg_instruction.condition, (test_creg, 3))
def test_condition_mapping_whileloopop(self):
"""Test that the condition in a `WhileLoopOp` is correctly mapped to a new set of bits and
registers."""
base_loose = Clbit()
base_creg = ClassicalRegister(2)
base_qreg = QuantumRegister(1)
base = QuantumCircuit(base_qreg, [base_loose], base_creg)
with base.while_loop((base_loose, True)):
base.x(0)
with base.while_loop((base_creg, 3)):
base.x(0)
test_loose = Clbit()
test_creg = ClassicalRegister(2)
test_qreg = QuantumRegister(1)
test = QuantumCircuit(test_qreg, [test_loose], test_creg).compose(base)
bit_instruction = test.data[0].operation
reg_instruction = test.data[1].operation
self.assertIs(bit_instruction.condition[0], test_loose)
self.assertEqual(bit_instruction.condition, (test_loose, True))
self.assertIs(reg_instruction.condition[0], test_creg)
self.assertEqual(reg_instruction.condition, (test_creg, 3))
def test_compose_no_clbits_in_one(self):
"""Test combining a circuit with cregs to one without"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qc = QuantumCircuit(2)
qc.measure_all()
out = ansatz.compose(qc)
self.assertEqual(out.clbits, qc.clbits)
def test_compose_no_clbits_in_one_inplace(self):
"""Test combining a circuit with cregs to one without inplace"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qc = QuantumCircuit(2)
qc.measure_all()
ansatz.compose(qc, inplace=True)
self.assertEqual(ansatz.clbits, qc.clbits)
def test_compose_no_clbits_in_one_multireg(self):
"""Test combining a circuit with cregs to one without, multi cregs"""
ansatz = TwoLocal(2, rotation_blocks="ry", entanglement_blocks="cx")
qa = QuantumRegister(2, "q")
ca = ClassicalRegister(2, "a")
cb = ClassicalRegister(2, "b")
qc = QuantumCircuit(qa, ca, cb)
qc.measure(0, cb[1])
out = ansatz.compose(qc)
self.assertEqual(out.clbits, qc.clbits)
self.assertEqual(out.cregs, qc.cregs)
def test_compose_noclbits_registerless(self):
"""Combining a circuit with cregs to one without, registerless case"""
inner = QuantumCircuit([Qubit(), Qubit()], [Clbit(), Clbit()])
inner.measure([0, 1], [0, 1])
outer = QuantumCircuit(2)
outer.compose(inner, inplace=True)
self.assertEqual(outer.clbits, inner.clbits)
self.assertEqual(outer.cregs, [])
def test_expr_condition_is_mapped(self):
"""Test that an expression in a condition involving several registers is mapped correctly to
the destination circuit."""
inner = QuantumCircuit(1)
inner.x(0)
a_src = ClassicalRegister(2, "a_src")
b_src = ClassicalRegister(2, "b_src")
c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src))
source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src)
test_1 = lambda: expr.lift(a_src[0])
test_2 = lambda: expr.logic_not(b_src[1])
test_3 = lambda: expr.logic_and(expr.bit_and(b_src, 2), expr.less(c_src, 7))
source.if_test(test_1(), inner.copy(), [0], [])
source.if_else(test_2(), inner.copy(), inner.copy(), [0], [])
source.while_loop(test_3(), inner.copy(), [0], [])
a_dest = ClassicalRegister(2, "a_dest")
b_dest = ClassicalRegister(2, "b_dest")
dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source)
# Check that the input conditions weren't mutated.
for in_condition, instruction in zip((test_1, test_2, test_3), source.data):
self.assertEqual(in_condition(), instruction.operation.condition)
# Should be `a_dest`, `b_dest` and an added one to account for `c_src`.
self.assertEqual(len(dest.cregs), 3)
mapped_reg = dest.cregs[-1]
expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg)
expected.if_test(expr.lift(a_dest[0]), inner.copy(), [0], [])
expected.if_else(expr.logic_not(b_dest[1]), inner.copy(), inner.copy(), [0], [])
expected.while_loop(
expr.logic_and(expr.bit_and(b_dest, 2), expr.less(mapped_reg, 7)), inner.copy(), [0], []
)
self.assertEqual(dest, expected)
def test_expr_target_is_mapped(self):
"""Test that an expression in a switch statement's target is mapping correctly to the
destination circuit."""
inner1 = QuantumCircuit(1)
inner1.x(0)
inner2 = QuantumCircuit(1)
inner2.z(0)
a_src = ClassicalRegister(2, "a_src")
b_src = ClassicalRegister(2, "b_src")
c_src = ClassicalRegister(name="c_src", bits=list(a_src) + list(b_src))
source = QuantumCircuit(QuantumRegister(1), a_src, b_src, c_src)
test_1 = lambda: expr.lift(a_src[0])
test_2 = lambda: expr.logic_not(b_src[1])
test_3 = lambda: expr.lift(b_src)
test_4 = lambda: expr.bit_and(c_src, 7)
source.switch(test_1(), [(False, inner1.copy()), (True, inner2.copy())], [0], [])
source.switch(test_2(), [(False, inner1.copy()), (True, inner2.copy())], [0], [])
source.switch(test_3(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [])
source.switch(test_4(), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], [])
a_dest = ClassicalRegister(2, "a_dest")
b_dest = ClassicalRegister(2, "b_dest")
dest = QuantumCircuit(QuantumRegister(1), a_dest, b_dest).compose(source)
# Check that the input expressions weren't mutated.
for in_target, instruction in zip((test_1, test_2, test_3, test_4), source.data):
self.assertEqual(in_target(), instruction.operation.target)
# Should be `a_dest`, `b_dest` and an added one to account for `c_src`.
self.assertEqual(len(dest.cregs), 3)
mapped_reg = dest.cregs[-1]
expected = QuantumCircuit(dest.qregs[0], a_dest, b_dest, mapped_reg)
expected.switch(
expr.lift(a_dest[0]), [(False, inner1.copy()), (True, inner2.copy())], [0], []
)
expected.switch(
expr.logic_not(b_dest[1]), [(False, inner1.copy()), (True, inner2.copy())], [0], []
)
expected.switch(
expr.lift(b_dest), [(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())], [0], []
)
expected.switch(
expr.bit_and(mapped_reg, 7),
[(0, inner1.copy()), (CASE_DEFAULT, inner2.copy())],
[0],
[],
)
self.assertEqual(dest, expected)
if __name__ == "__main__":
unittest.main()