-
Notifications
You must be signed in to change notification settings - Fork 985
/
_parser_test.py
1078 lines (809 loc) · 27 KB
/
_parser_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2021 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO(#6171): enable the check and fix pylint errors
# pylint: disable=consider-using-f-string
from typing import Callable
import numpy as np
import pytest
import sympy
import cirq
import cirq.testing as ct
from cirq import Circuit
from cirq.circuits.qasm_output import QasmUGate
from cirq.contrib.qasm_import import QasmException
from cirq.contrib.qasm_import._parser import QasmParser
def test_format_header_circuit():
parser = QasmParser()
parsed_qasm = parser.parse("OPENQASM 2.0;")
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, Circuit())
def test_unsupported_format():
qasm = "OPENQASM 2.1;"
parser = QasmParser()
with pytest.raises(QasmException, match="Unsupported.*2.1.*2.0.*supported.*"):
parser.parse(qasm)
def test_format_header_with_quelibinc_circuit():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
"""
parser = QasmParser()
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, Circuit())
@pytest.mark.parametrize('qasm', ["include \"qelib1.inc\";", "", "qreg q[3];"])
def test_error_not_starting_with_format(qasm: str):
parser = QasmParser()
with pytest.raises(QasmException, match="Missing 'OPENQASM 2.0;' statement"):
parser.parse(qasm)
def test_comments():
parser = QasmParser()
parsed_qasm = parser.parse(
"""
//this is the format
OPENQASM 2.0;
// this is some other comment
include "qelib1.inc";
// and something at the end of the file
// multiline
"""
)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, Circuit())
def test_multiple_qreg_declaration():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg a_quantum_register [ 1337 ];
qreg q[42];
"""
parser = QasmParser()
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, Circuit())
assert parsed_qasm.qregs == {'a_quantum_register': 1337, 'q': 42}
@pytest.mark.parametrize(
'qasm',
[
"""OPENQASM 2.0;
qreg q[2];
creg q[3];
""",
"""OPENQASM 2.0;
creg q[2];
qreg q[3];
""",
],
)
def test_already_defined_error(qasm: str):
parser = QasmParser()
with pytest.raises(QasmException, match=r"q.*already defined.* line 3"):
parser.parse(qasm)
@pytest.mark.parametrize(
'qasm',
[
"""OPENQASM 2.0;
qreg q[0];
""",
"""OPENQASM 2.0;
creg q[0];
""",
],
)
def test_zero_length_register(qasm: str):
parser = QasmParser()
with pytest.raises(QasmException, match=".* zero-length.*'q'.*line 2"):
parser.parse(qasm)
def test_unexpected_end_of_file():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
creg
"""
parser = QasmParser()
with pytest.raises(QasmException, match="Unexpected end of file"):
parser.parse(qasm)
def test_multiple_creg_declaration():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
creg a_classical_register [1337];
qreg a_quantum_register [1337];
creg c[42];
"""
parser = QasmParser()
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, Circuit())
assert parsed_qasm.qregs == {'a_quantum_register': 1337}
assert parsed_qasm.cregs == {'a_classical_register': 1337, 'c': 42}
def test_syntax_error():
qasm = """OPENQASM 2.0;
qreg q[2] bla;
foobar q[0];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Syntax error: 'bla'.*"""):
parser.parse(qasm)
def test_CX_gate():
qasm = """OPENQASM 2.0;
qreg q1[2];
qreg q2[2];
CX q1[0], q1[1];
CX q1, q2[0];
CX q2, q1;
"""
parser = QasmParser()
q1_0 = cirq.NamedQubit('q1_0')
q1_1 = cirq.NamedQubit('q1_1')
q2_0 = cirq.NamedQubit('q2_0')
q2_1 = cirq.NamedQubit('q2_1')
expected_circuit = Circuit()
# CX q1[0], q1[1];
expected_circuit.append(cirq.CNOT(q1_0, q1_1))
# CX q1, q2[0];
expected_circuit.append(cirq.CNOT(q1_0, q2_0))
expected_circuit.append(cirq.CNOT(q1_1, q2_0))
# CX q2, q1;
expected_circuit.append(cirq.CNOT(q2_0, q1_0))
expected_circuit.append(cirq.CNOT(q2_1, q1_1))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q1': 2, 'q2': 2}
def test_classical_control():
qasm = """OPENQASM 2.0;
qreg q[2];
creg a[1];
measure q[0] -> a[0];
if (a==1) CX q[0],q[1];
"""
parser = QasmParser()
q_0 = cirq.NamedQubit('q_0')
q_1 = cirq.NamedQubit('q_1')
expected_circuit = cirq.Circuit(
cirq.measure(q_0, key='a_0'),
cirq.CNOT(q_0, q_1).with_classical_controls(sympy.Eq(sympy.Symbol('a_0'), 1)),
)
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
# Note this cannot *exactly* round-trip because the way QASM and Cirq handle measurements
# into classical registers is different. Cirq parses QASM classical registers into m_a_i for i
# in 0..bit_count. Thus the generated key has an extra "_0" at the end.
expected_generated_qasm = f"""// Generated from Cirq v{cirq.__version__}
OPENQASM 2.0;
include "qelib1.inc";
// Qubits: [q_0, q_1]
qreg q[2];
creg m_a_0[1];
measure q[0] -> m_a_0[0];
if (m_a_0==1) cx q[0],q[1];
"""
assert cirq.qasm(parsed_qasm.circuit) == expected_generated_qasm
def test_classical_control_multi_bit():
qasm = """OPENQASM 2.0;
qreg q[2];
creg a[2];
measure q[0] -> a[0];
measure q[0] -> a[1];
if (a==1) CX q[0],q[1];
"""
parser = QasmParser()
q_0 = cirq.NamedQubit('q_0')
q_1 = cirq.NamedQubit('q_1')
# Since we split the measurement into two, we also need two conditions.
# m_a==1 corresponds to m_a[0]==1, m_a[1]==0
expected_circuit = cirq.Circuit(
cirq.measure(q_0, key='a_0'),
cirq.measure(q_0, key='a_1'),
cirq.CNOT(q_0, q_1).with_classical_controls(
sympy.Eq(sympy.Symbol('a_0'), 1), sympy.Eq(sympy.Symbol('a_1'), 0)
),
)
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
# Note that this will *not* round-trip, but there's no good way around that due to the
# difference in how Cirq and QASM do multi-bit measurements.
with pytest.raises(ValueError, match='QASM does not support multiple conditions'):
_ = cirq.qasm(parsed_qasm.circuit)
def test_CX_gate_not_enough_args():
qasm = """OPENQASM 2.0;
qreg q[2];
CX q[0];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"CX.*takes.*got.*1.*line 3"):
parser.parse(qasm)
def test_CX_gate_mismatched_registers():
qasm = """OPENQASM 2.0;
qreg q1[2];
qreg q2[3];
CX q1, q2;
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"Non matching.*length \[2 3\].*line 4"):
parser.parse(qasm)
def test_CX_gate_bounds():
qasm = """OPENQASM 2.0;
qreg q1[2];
qreg q2[3];
CX q1[4], q2[0];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"Out of bounds.*4.*q1.*2.*line 4"):
parser.parse(qasm)
def test_CX_gate_arg_overlap():
qasm = """OPENQASM 2.0;
qreg q1[2];
qreg q2[3];
CX q1[1], q1[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"Overlapping.*at line 4"):
parser.parse(qasm)
def test_U_gate():
qasm = """
OPENQASM 2.0;
qreg q[2];
U(pi, 2.3, 3) q[0];
U(+3.14, -pi, (8)) q;
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
q1 = cirq.NamedQubit('q_1')
expected_circuit = Circuit()
expected_circuit.append(
cirq.Moment(
[
QasmUGate(1.0, 2.3 / np.pi, 3 / np.pi)(q0),
QasmUGate(3.14 / np.pi, -1.0, 8 / np.pi)(q1),
]
)
)
expected_circuit.append(cirq.Moment([QasmUGate(3.14 / np.pi, -1.0, 8 / np.pi)(q0)]))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
def test_U_angles():
qasm = """
OPENQASM 2.0;
qreg q[1];
U(pi/2,0,pi) q[0];
"""
c = QasmParser().parse(qasm).circuit
cirq.testing.assert_allclose_up_to_global_phase(
cirq.unitary(c), cirq.unitary(cirq.H), atol=1e-7
)
def test_U_gate_zero_params_error():
qasm = """OPENQASM 2.0;
qreg q[2];
U q[1];"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"U takes 3.*got.*0.*line 3"):
parser.parse(qasm)
def test_U_gate_too_much_params_error():
qasm = """OPENQASM 2.0;
qreg q[2];
U(pi, pi, pi, pi) q[1];"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"U takes 3.*got.*4.*line 3"):
parser.parse(qasm)
@pytest.mark.parametrize(
'expr',
[
'.333 + 4',
'1.0 * 2',
'0.1 ^ pi',
'0.1 / pi',
'2.0e-05 ^ (1/2)',
'1.2E+05 * (3 + 2)',
'123123.2132312 * cos(pi)',
'123123.2132312 * sin(2 * pi)',
'3 - 4 * 2', # precedence of *
'3 * 4 + 2', # precedence of *
'3 * 4 ^ 2', # precedence of ^
'3 - 4 ^ 2', # precedence of ^
'3^2^(-2)', # right associativity of ^
'(-1) * pi',
'(+1) * pi',
'-3 * 5 + 2',
'(+4 * (-3) ^ 5 - 2)',
'tan(123123.2132312)',
'ln(pi)',
'exp(2*pi)',
'sqrt(4)',
'acos(1)',
'atan(0.2)',
],
)
def test_expressions(expr: str):
qasm = f"""OPENQASM 2.0;
qreg q[1];
U({expr}, 2 * pi, pi / 2.0) q[0];
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
expected_circuit = Circuit()
expected_circuit.append(QasmUGate(float(sympy.sympify(expr)) / np.pi, 2.0, 1 / 2.0)(q0))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert not parsed_qasm.qelib1Include
ct.assert_allclose_up_to_global_phase(
cirq.unitary(parsed_qasm.circuit), cirq.unitary(expected_circuit), atol=1e-10
)
assert parsed_qasm.qregs == {'q': 1}
def test_unknown_function():
qasm = """OPENQASM 2.0;
qreg q[1];
U(nonexistent(3), 2 * pi, pi / 3.0) q[0];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r".*not recognized.*'nonexistent'.*line 3"):
parser.parse(qasm)
rotation_gates = [('rx', cirq.rx), ('ry', cirq.ry), ('rz', cirq.rz)]
single_qubit_gates = [
('x', cirq.X),
('y', cirq.Y),
('z', cirq.Z),
('h', cirq.H),
('s', cirq.S),
('t', cirq.T),
('sdg', cirq.S**-1),
('tdg', cirq.T**-1),
('sx', cirq.XPowGate(exponent=0.5)),
]
@pytest.mark.parametrize('qasm_gate,cirq_gate', rotation_gates)
def test_rotation_gates(qasm_gate: str, cirq_gate: Callable[[float], cirq.Gate]):
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{0}(pi/2) q[0];
{0}(pi) q;
""".format(
qasm_gate
)
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
q1 = cirq.NamedQubit('q_1')
expected_circuit = Circuit()
expected_circuit.append(cirq.Moment([cirq_gate(np.pi / 2).on(q0), cirq_gate(np.pi).on(q1)]))
expected_circuit.append(cirq.Moment([cirq_gate(np.pi).on(q0)]))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
@pytest.mark.parametrize('qasm_gate', [g[0] for g in rotation_gates])
def test_rotation_gates_wrong_number_of_args(qasm_gate: str):
qasm = f"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate}(pi) q[0], q[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r".*{}.* takes 1.*got.*2.*line 5".format(qasm_gate)):
parser.parse(qasm)
@pytest.mark.parametrize('qasm_gate', [g[0] for g in rotation_gates])
def test_rotation_gates_zero_params_error(qasm_gate: str):
qasm = f"""OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate} q[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r".*{}.* takes 1.*got.*0.*line 4".format(qasm_gate)):
parser.parse(qasm)
def test_qelib_gate_without_include_statement():
qasm = """OPENQASM 2.0;
qreg q[2];
x q[0];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Unknown gate "x".* line 3.*forget.*\?"""):
parser.parse(qasm)
def test_undefined_register_from_qubit_arg():
qasm = """OPENQASM 2.0;
qreg q[2];
CX q[0], q2[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Undefined.*register.*q2.*"""):
parser.parse(qasm)
def test_undefined_register_from_register_arg():
qasm = """OPENQASM 2.0;
qreg q[2];
qreg q2[2];
CX q1, q2;
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Undefined.*register.*q.*"""):
parser.parse(qasm)
def test_measure_individual_bits():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q1[2];
creg c1[2];
measure q1[0] -> c1[0];
measure q1[1] -> c1[1];
"""
parser = QasmParser()
q1_0 = cirq.NamedQubit('q1_0')
q1_1 = cirq.NamedQubit('q1_1')
expected_circuit = Circuit()
expected_circuit.append(cirq.MeasurementGate(num_qubits=1, key='c1_0').on(q1_0))
expected_circuit.append(cirq.MeasurementGate(num_qubits=1, key='c1_1').on(q1_1))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q1': 2}
assert parsed_qasm.cregs == {'c1': 2}
def test_measure_registers():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q1[3];
creg c1[3];
measure q1 -> c1;
"""
parser = QasmParser()
q1_0 = cirq.NamedQubit('q1_0')
q1_1 = cirq.NamedQubit('q1_1')
q1_2 = cirq.NamedQubit('q1_2')
expected_circuit = Circuit()
expected_circuit.append(cirq.MeasurementGate(num_qubits=1, key='c1_0').on(q1_0))
expected_circuit.append(cirq.MeasurementGate(num_qubits=1, key='c1_1').on(q1_1))
expected_circuit.append(cirq.MeasurementGate(num_qubits=1, key='c1_2').on(q1_2))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q1': 3}
assert parsed_qasm.cregs == {'c1': 3}
def test_measure_mismatched_register_size():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q1[2];
creg c1[3];
measure q1 -> c1;
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r""".*mismatched .* 2 -> 3.*line 5"""):
parser.parse(qasm)
def test_measure_to_quantum_register():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q1[3];
qreg q2[3];
creg c1[3];
measure q2 -> q1;
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Undefined classical register.*q1.*line 6"""):
parser.parse(qasm)
def test_measure_undefined_classical_bit():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q1[3];
creg c1[3];
measure q1[1] -> c2[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Undefined classical register.*c2.*line 5"""):
parser.parse(qasm)
def test_measure_from_classical_register():
qasm = """OPENQASM 2.0;
include "qelib1.inc";
qreg q1[2];
creg c1[3];
creg c2[3];
measure c1 -> c2;
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"""Undefined quantum register.*c1.*line 6"""):
parser.parse(qasm)
def test_measurement_bounds():
qasm = """OPENQASM 2.0;
qreg q1[3];
creg c1[3];
measure q1[0] -> c1[4];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r"Out of bounds bit.*4.*c1.*size 3.*line 4"):
parser.parse(qasm)
def test_u1_gate():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
u1(pi / 3.0) q[0];
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
expected_circuit = Circuit()
expected_circuit.append(QasmUGate(0, 0, 1.0 / 3.0)(q0))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 1}
def test_u2_gate():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
u2(2 * pi, pi / 3.0) q[0];
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
expected_circuit = Circuit()
expected_circuit.append(QasmUGate(0.5, 2.0, 1.0 / 3.0)(q0))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 1}
def test_id_gate():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
id q;
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
q1 = cirq.NamedQubit('q_1')
expected_circuit = Circuit()
expected_circuit.append(cirq.IdentityGate(num_qubits=1)(q0))
expected_circuit.append(cirq.IdentityGate(num_qubits=1)(q1))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
def test_u3_gate():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
u3(pi, 2.3, 3) q[0];
u3(+3.14, -pi, (8)) q;
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
q1 = cirq.NamedQubit('q_1')
expected_circuit = Circuit()
expected_circuit.append(
cirq.Moment(
[
QasmUGate(1.0, 2.3 / np.pi, 3 / np.pi)(q0),
QasmUGate(3.14 / np.pi, -1.0, 8 / np.pi)(q1),
]
)
)
expected_circuit.append(cirq.Moment([QasmUGate(3.14 / np.pi, -1.0, 8 / np.pi)(q0)]))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 2}
def test_r_gate():
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
r(pi, pi / 2.0) q[0];
"""
parser = QasmParser()
q0 = cirq.NamedQubit('q_0')
expected_circuit = Circuit()
expected_circuit.append(QasmUGate(1.0, 0.0, 0.0)(q0))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q': 1}
@pytest.mark.parametrize(
'qasm_gate',
['id', 'u2', 'u3', 'r'] + [g[0] for g in rotation_gates] + [g[0] for g in single_qubit_gates],
)
def test_standard_single_qubit_gates_wrong_number_of_args(qasm_gate):
qasm = f"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate} q[0], q[1];
"""
parser = QasmParser()
with pytest.raises(QasmException, match=r".* takes 1.*got.*2.*line 5"):
parser.parse(qasm)
@pytest.mark.parametrize(
['qasm_gate', 'num_params'],
[['id', 0], ['u2', 2], ['u3', 3], ['rx', 1], ['ry', 1], ['rz', 1], ['r', 2]]
+ [[g[0], 0] for g in single_qubit_gates],
)
def test_standard_gates_wrong_params_error(qasm_gate: str, num_params: int):
qasm = f"""OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate}(pi, 2*pi, 3*pi, 4*pi, 5*pi) q[1];
"""
parser = QasmParser()
with pytest.raises(
QasmException, match=r".*{}.* takes {}.*got.*5.*line 4".format(qasm_gate, num_params)
):
parser.parse(qasm)
if num_params == 0:
return
qasm = f"""OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate} q[1];
"""
parser = QasmParser()
with pytest.raises(
QasmException, match=r".*{}.* takes {}.*got.*0.*line 4".format(qasm_gate, num_params)
):
parser.parse(qasm)
two_qubit_gates = [
('cx', cirq.CNOT),
('CX', cirq.CNOT),
('cz', cirq.CZ),
('cy', cirq.ControlledGate(cirq.Y)),
('swap', cirq.SWAP),
('ch', cirq.ControlledGate(cirq.H)),
]
@pytest.mark.parametrize('qasm_gate,cirq_gate', two_qubit_gates)
def test_two_qubit_gates(qasm_gate: str, cirq_gate: cirq.testing.TwoQubitGate):
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q1[2];
qreg q2[2];
{0} q1[0], q1[1];
{0} q1, q2[0];
{0} q2, q1;
""".format(
qasm_gate
)
parser = QasmParser()
q1_0 = cirq.NamedQubit('q1_0')
q1_1 = cirq.NamedQubit('q1_1')
q2_0 = cirq.NamedQubit('q2_0')
q2_1 = cirq.NamedQubit('q2_1')
expected_circuit = Circuit()
# CX q1[0], q1[1];
expected_circuit.append(cirq_gate(q1_0, q1_1))
# CX q1, q2[0];
expected_circuit.append(cirq_gate(q1_0, q2_0))
expected_circuit.append(cirq_gate(q1_1, q2_0))
# CX q2, q1;
expected_circuit.append(cirq_gate(q2_0, q1_0))
expected_circuit.append(cirq_gate(q2_1, q1_1))
parsed_qasm = parser.parse(qasm)
assert parsed_qasm.supportedFormat
assert parsed_qasm.qelib1Include
ct.assert_same_circuits(parsed_qasm.circuit, expected_circuit)
assert parsed_qasm.qregs == {'q1': 2, 'q2': 2}
@pytest.mark.parametrize('qasm_gate', [g[0] for g in two_qubit_gates])
def test_two_qubit_gates_not_enough_args(qasm_gate: str):
qasm = f"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate} q[0];
"""
parser = QasmParser()
with pytest.raises(
QasmException, match=r".*{}.* takes 2 arg\(s\).*got.*1.*line 5".format(qasm_gate)
):
parser.parse(qasm)
@pytest.mark.parametrize('qasm_gate', [g[0] for g in two_qubit_gates])
def test_two_qubit_gates_with_too_much_parameters(qasm_gate: str):
qasm = f"""
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
{qasm_gate}(pi) q[0],q[1];
"""
parser = QasmParser()
with pytest.raises(
QasmException, match=r".*{}.* takes 0 parameter\(s\).*got.*1.*line 5".format(qasm_gate)
):
parser.parse(qasm)
three_qubit_gates = [('ccx', cirq.TOFFOLI), ('cswap', cirq.CSWAP)]
@pytest.mark.parametrize('qasm_gate,cirq_gate', three_qubit_gates)
def test_three_qubit_gates(qasm_gate: str, cirq_gate: cirq.testing.TwoQubitGate):
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q1[2];
qreg q2[2];
qreg q3[2];
{0} q1[0], q1[1], q2[0];
{0} q1, q2[0], q3[0];
{0} q1, q2, q3;
""".format(
qasm_gate
)
parser = QasmParser()
q1_0 = cirq.NamedQubit('q1_0')
q1_1 = cirq.NamedQubit('q1_1')
q2_0 = cirq.NamedQubit('q2_0')