-
Notifications
You must be signed in to change notification settings - Fork 342
/
test_quilbase.py
1833 lines (1527 loc) · 69.7 KB
/
test_quilbase.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
import copy
import pickle
from collections.abc import Iterable
from math import pi
from numbers import Complex, Number
from typing import Any, List, Optional, Tuple, Union
import numpy as np
import pytest
from syrupy.assertion import SnapshotAssertion
from pyquil.api._compiler import QPUCompiler
from pyquil.gates import X
from pyquil.paulis import PauliSum, PauliTerm
from pyquil.quil import Program
from pyquil.quilatom import (
BinaryExp,
Expression,
Frame,
Mul,
Qubit,
TemplateWaveform,
Waveform,
WaveformReference,
quil_cos,
quil_sin,
)
from pyquil.quilbase import (
AbstractInstruction,
ArithmeticBinaryOp,
Capture,
ClassicalAdd,
ClassicalAnd,
ClassicalComparison,
ClassicalConvert,
ClassicalDiv,
ClassicalEqual,
ClassicalExchange,
ClassicalExclusiveOr,
ClassicalGreaterEqual,
ClassicalGreaterThan,
ClassicalInclusiveOr,
ClassicalLessEqual,
ClassicalLessThan,
ClassicalLoad,
ClassicalMove,
ClassicalMul,
ClassicalNeg,
ClassicalNot,
ClassicalStore,
ClassicalSub,
Declare,
DefCalibration,
DefCircuit,
DefFrame,
DefGate,
DefGateByPaulis,
DefMeasureCalibration,
DefPermutationGate,
DefWaveform,
DelayFrames,
DelayQubits,
Fence,
FenceAll,
FormalArgument,
Gate,
Halt,
Include,
LogicalBinaryOp,
Measurement,
MemoryReference,
Nop,
Parameter,
ParameterDesignator,
Pragma,
Pulse,
QubitDesignator,
RawCapture,
Reset,
ResetQubit,
SetFrequency,
SetPhase,
SetScale,
ShiftFrequency,
ShiftPhase,
SwapPhases,
UnaryClassicalInstruction,
Wait,
_convert_to_py_instruction,
_convert_to_rs_instruction,
)
from pyquil.quiltwaveforms import (
BoxcarAveragerKernel,
DragGaussianWaveform,
ErfSquareWaveform,
FlatWaveform,
GaussianWaveform,
HrmGaussianWaveform,
)
@pytest.mark.parametrize(
("name", "params", "qubits"),
[
("X", [], [Qubit(0)]),
("CPHASE", [pi / 2], [Qubit(0), Qubit(1)]),
("RZ", [MemoryReference("theta", 0, 1)], [Qubit(0)]),
("RZ", [MemoryReference("alpha", 0) - MemoryReference("beta")], [Qubit(0)]),
],
ids=("X-Gate", "CPHASE-Expression", "RZ-MemoryReference", "RZ-MemoryReference-Expression"),
)
class TestGate:
@pytest.fixture
def gate(self, name: str, params: List[ParameterDesignator], qubits: List[Qubit]) -> Gate:
return Gate(name, params, qubits)
@pytest.fixture
def program(self, params: List[ParameterDesignator], gate: Gate) -> Program:
"""Creates a valid quil program using the gate and declaring memory regions for any of it's parameters"""
program = Program(gate)
for param in params:
if isinstance(param, MemoryReference):
program.declare(param.name, "REAL", param.declared_size or 1)
if isinstance(param, BinaryExp):
if isinstance(param.op1, MemoryReference):
program.declare(param.op1.name, "REAL", param.op1.declared_size or 1)
if isinstance(param.op2, MemoryReference):
program.declare(param.op2.name, "REAL", param.op2.declared_size or 1)
return program
def test_str(self, gate: Gate, snapshot: SnapshotAssertion):
assert str(gate) == snapshot
def test_name(self, gate: Gate, name: str):
assert gate.name == name
def test_params(self, gate: Gate, params: List[ParameterDesignator]):
assert gate.params == params
gate.params = [pi / 2]
assert gate.params == [pi / 2]
def test_qubits(self, gate: Gate, qubits: List[Qubit]):
assert gate.qubits == qubits
gate.qubits = [Qubit(123)]
assert gate.qubits == [Qubit(123)]
def test_get_qubits(self, gate: Gate, qubits: List[Qubit]):
assert gate.get_qubit_indices() == [q.index for q in qubits]
assert gate.get_qubits(indices=False) == qubits
def test_controlled_modifier(self, gate: Gate, snapshot: SnapshotAssertion):
assert str(gate.controlled([Qubit(5)])) == snapshot
def test_dagger_modifier(self, gate: Gate, snapshot: SnapshotAssertion):
assert str(gate.dagger()) == snapshot
def test_forked_modifier(self, gate: Gate, params: List[ParameterDesignator], snapshot: SnapshotAssertion):
alt_params: List[ParameterDesignator] = [n for n in range(len(params))]
assert str(gate.forked(Qubit(5), alt_params)) == snapshot
def test_modifiers(self, gate: Gate):
assert gate.modifiers == []
gate.modifiers = ["CONTROLLED"]
assert gate.modifiers == ["CONTROLLED"]
def test_repr(self, gate: Gate, snapshot: SnapshotAssertion):
assert repr(gate) == snapshot
def test_eq(self, gate: Gate, name: str, params: List[ParameterDesignator], qubits: List[Qubit]):
assert gate == Gate(name, params, qubits)
assert not gate != Gate(name, params, qubits)
not_eq_gate = Gate(f"not-{name}", params, qubits)
assert not (gate == not_eq_gate)
assert gate != not_eq_gate
def test_convert(self, gate: Gate):
rs_gate = _convert_to_rs_instruction(gate)
assert gate == _convert_to_py_instruction(rs_gate)
def test_copy(self, gate: Gate):
assert isinstance(copy.copy(gate), Gate)
assert isinstance(copy.deepcopy(gate), Gate)
def test_compile(self, program: Program, compiler: QPUCompiler):
try:
compiler.quil_to_native_quil(program)
except Exception as e:
raise AssertionError(f"Failed to compile the program: \n{program}") from e
def test_pickle(self, gate: Gate):
pickled = pickle.dumps(gate)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, Gate)
assert unpickled == gate
@pytest.mark.parametrize(
("name", "matrix", "parameters"),
[
("NoParamGate", np.eye(4), []),
("ParameterizedGate", np.diag([quil_cos(Parameter("X"))] * 4), [Parameter("X")]),
(
"MixedTypes",
np.array(
[
[0, quil_sin(Parameter("X"))],
[0, 0],
]
),
[Parameter("X")],
),
(
"ParameterlessExpressions",
np.array(
[
[-quil_cos(np.pi), quil_sin(np.pi)],
[quil_sin(np.pi), quil_cos(np.pi)],
]
),
[],
),
],
ids=("No-Params", "Params", "MixedTypes", "ParameterlessExpression"),
)
class TestDefGate:
@pytest.fixture
def def_gate(
self, name: str, matrix: Union[List[List[Any]], np.ndarray, np.matrix], parameters: Optional[List[Parameter]]
) -> DefGate:
return DefGate(name, matrix, parameters)
def test_out(self, def_gate: DefGate, snapshot: SnapshotAssertion):
assert def_gate.out() == snapshot
def test_str(self, def_gate: DefGate, snapshot: SnapshotAssertion):
assert str(def_gate) == snapshot
def test_get_constructor(self, def_gate: DefGate, snapshot: SnapshotAssertion):
constructor = def_gate.get_constructor()
if def_gate.parameters:
g = constructor(Parameter("theta"))(Qubit(123)) # type: ignore
assert g.out() == snapshot
else:
g = constructor(Qubit(123))
assert g.out() == snapshot
def test_num_args(self, def_gate: DefGate, matrix: Union[List[List[Any]], np.ndarray, np.matrix]):
assert def_gate.num_args() == np.log2(len(matrix))
def test_name(self, def_gate: DefGate, name: str):
assert def_gate.name == name
def_gate.name = "new_name"
assert def_gate.name == "new_name"
def test_matrix(self, def_gate: DefGate, matrix: Union[List[List[Any]], np.ndarray, np.matrix]):
assert np.array_equal(def_gate.matrix, matrix)
new_matrix = np.asarray([[0, 1, 2, 3], [3, 2, 1, 0]])
def_gate.matrix = new_matrix
assert np.array_equal(def_gate.matrix, new_matrix)
def test_parameters(self, def_gate: DefGate, parameters: Optional[List[Parameter]]):
assert def_gate.parameters == parameters
def_gate.parameters = [Parameter("brand_new_param")]
assert def_gate.parameters == [Parameter("brand_new_param")]
def test_copy(self, def_gate: DefGate):
assert isinstance(copy.copy(def_gate), DefGate)
assert isinstance(copy.deepcopy(def_gate), DefGate)
def test_pickle(self, def_gate: DefGate, snapshot: SnapshotAssertion):
pickled = pickle.dumps(def_gate)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DefGate)
assert unpickled == snapshot
@pytest.mark.parametrize(
("name", "permutation"),
[
("PermGate", np.asarray([4, 3, 2, 1])),
],
)
class TestDefPermutationGate:
@pytest.fixture
def def_permutation_gate(self, name: str, permutation: np.ndarray) -> DefPermutationGate:
return DefPermutationGate(name, permutation)
def test_out(self, def_permutation_gate: DefPermutationGate, snapshot: SnapshotAssertion):
assert def_permutation_gate.out() == snapshot
def test_str(self, def_permutation_gate: DefPermutationGate, snapshot: SnapshotAssertion):
assert str(def_permutation_gate) == snapshot
def test_get_constructor(self, def_permutation_gate: DefPermutationGate, snapshot: SnapshotAssertion):
constructor = def_permutation_gate.get_constructor()
g = constructor(Qubit(123))
assert g.out() == snapshot
def test_num_args(
self, def_permutation_gate: DefPermutationGate, permutation: Union[List[List[Any]], np.ndarray, np.matrix]
):
assert def_permutation_gate.num_args() == np.log2(len(permutation))
def test_name(self, def_permutation_gate: DefPermutationGate, name: str):
assert def_permutation_gate.name == name
def_permutation_gate.name = "new_name"
assert def_permutation_gate.name == "new_name"
def test_permutation(
self, def_permutation_gate: DefPermutationGate, permutation: Union[List[List[Any]], np.ndarray, np.matrix]
):
assert np.array_equal(def_permutation_gate.permutation, permutation)
new_permutation = [1, 2, 3, 4]
def_permutation_gate.permutation = new_permutation
assert np.array_equal(def_permutation_gate.permutation, new_permutation)
def test_parameters(self, def_permutation_gate: DefPermutationGate):
assert not def_permutation_gate.parameters
@pytest.mark.parametrize(
("gate_name", "parameters", "arguments", "body"),
[
("PauliGate", [], [FormalArgument("p")], PauliSum([])),
("PauliGate", [Parameter("theta")], [FormalArgument("p")], PauliSum([])),
("PauliGate", [], [FormalArgument("p")], PauliSum([PauliTerm("Y", FormalArgument("p"), 2.0)])),
(
"PauliGate",
[Parameter("theta")],
[FormalArgument("p"), FormalArgument("q")],
PauliSum(
[
PauliTerm("Z", FormalArgument("p"), Mul(1.0, Parameter("theta"))),
PauliTerm("Y", FormalArgument("p"), 2.0),
PauliTerm("X", FormalArgument("q"), 3.0),
PauliTerm("I", None, 3.0),
]
),
),
],
ids=("Default", "DefaultWithParams", "WithSum", "WithSumAndParams"),
)
class TestDefGateByPaulis:
@pytest.fixture
def def_gate_pauli(
self, gate_name: str, parameters: List[Parameter], arguments: List[QubitDesignator], body: PauliSum
) -> DefGateByPaulis:
return DefGateByPaulis(gate_name, parameters, arguments, body)
def test_out(self, def_gate_pauli: DefGateByPaulis, snapshot: SnapshotAssertion):
assert def_gate_pauli.out() == snapshot
def test_str(self, def_gate_pauli: DefGateByPaulis, snapshot: SnapshotAssertion):
assert str(def_gate_pauli) == snapshot
def test_get_constructor(self, def_gate_pauli: DefGateByPaulis, snapshot: SnapshotAssertion):
constructor = def_gate_pauli.get_constructor()
if def_gate_pauli.parameters:
g = constructor(Parameter("theta"))(Qubit(123)) # type: ignore
assert g.out() == snapshot
else:
g = constructor(Qubit(123))
assert g.out() == snapshot
def test_num_args(
self,
def_gate_pauli: DefGateByPaulis,
arguments: List[QubitDesignator],
):
assert def_gate_pauli.num_args() == len(arguments)
def test_name(self, def_gate_pauli: DefGateByPaulis, gate_name: str):
assert def_gate_pauli.name == gate_name
def_gate_pauli.name = "new_name"
assert def_gate_pauli.name == "new_name"
def test_parameters(self, def_gate_pauli: DefGate, parameters: Optional[List[Parameter]]):
assert def_gate_pauli.parameters == parameters
def_gate_pauli.parameters = [Parameter("brand_new_param")]
assert def_gate_pauli.parameters == [Parameter("brand_new_param")]
def test_arguments(self, def_gate_pauli: DefGateByPaulis, arguments: List[QubitDesignator]):
assert def_gate_pauli.arguments == arguments
def_gate_pauli.arguments = [FormalArgument("NewArgument")] # type: ignore
assert def_gate_pauli.arguments == [FormalArgument("NewArgument")]
def test_body(self, def_gate_pauli: DefGateByPaulis, body: PauliSum):
if all([isinstance(term.coefficient, Number) for term in body.terms]):
# PauliTerm equality is only defined for terms with Numbered coefficients
assert def_gate_pauli.body == body
new_body = PauliSum([PauliTerm("X", FormalArgument("a"), 5.0)])
def_gate_pauli.body = new_body
assert def_gate_pauli.body == new_body
@pytest.mark.parametrize(
("name", "parameters", "qubits", "instrs"),
[
("Calibrate", [], [Qubit(0)], [X(0)]),
("Calibrate", [Parameter("X")], [Qubit(0)], [X(0)]),
],
ids=("No-Params", "Params"),
)
class TestDefCalibration:
@pytest.fixture
def calibration(
self, name: str, parameters: List[ParameterDesignator], qubits: List[Qubit], instrs: List[AbstractInstruction]
) -> DefCalibration:
return DefCalibration(name, parameters, qubits, instrs)
def test_str(self, calibration: DefCalibration, snapshot: SnapshotAssertion):
assert str(calibration) == snapshot
def test_out(self, calibration: DefCalibration, snapshot: SnapshotAssertion):
assert calibration.out() == snapshot
def test_name(self, calibration: DefCalibration, name: str):
assert calibration.name == name
calibration.name = "new_name"
assert calibration.name == "new_name"
def test_parameters(self, calibration: DefCalibration, parameters: List[ParameterDesignator]):
assert calibration.parameters == parameters
calibration.parameters = [pi / 2]
assert calibration.parameters == [pi / 2]
def test_qubits(self, calibration: DefCalibration, qubits: List[QubitDesignator]):
assert calibration.qubits == qubits
calibration.qubits = [Qubit(123)]
assert calibration.qubits == [Qubit(123)]
def test_instrs(self, calibration: DefCalibration, instrs: List[AbstractInstruction]):
assert calibration.instrs == instrs
calibration.instrs = [Gate("SomeGate", [], [Qubit(0)], [])]
assert calibration.instrs == [Gate("SomeGate", [], [Qubit(0)], [])]
def test_copy(self, calibration: DefCalibration):
assert isinstance(copy.copy(calibration), DefCalibration)
assert isinstance(copy.deepcopy(calibration), DefCalibration)
def test_convert(self, calibration: DefCalibration):
rs_calibration = _convert_to_rs_instruction(calibration)
assert calibration == _convert_to_py_instruction(rs_calibration)
def test_pickle(self, calibration: DefCalibration):
pickled = pickle.dumps(calibration)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DefCalibration)
assert unpickled == calibration
@pytest.mark.parametrize(
("qubit", "memory_reference", "instrs"),
[(Qubit(0), MemoryReference("theta", 0, 1), [X(0)])],
)
class TestDefMeasureCalibration:
@pytest.fixture
def measure_calibration(
self, qubit: Qubit, memory_reference: MemoryReference, instrs: List[AbstractInstruction]
) -> DefMeasureCalibration:
return DefMeasureCalibration(qubit, memory_reference, instrs)
def test_out(self, measure_calibration: DefMeasureCalibration, snapshot: SnapshotAssertion):
assert measure_calibration.out() == snapshot
def test_qubit(self, measure_calibration: DefMeasureCalibration, qubit: Qubit):
assert measure_calibration.qubit == qubit
measure_calibration.qubit = Qubit(123)
assert measure_calibration.qubit == Qubit(123)
def test_memory_reference(self, measure_calibration: DefMeasureCalibration, memory_reference: MemoryReference):
assert measure_calibration.memory_reference == memory_reference
measure_calibration.memory_reference = MemoryReference("new_mem_ref")
assert measure_calibration.memory_reference == MemoryReference("new_mem_ref")
def test_instrs(self, measure_calibration: DefMeasureCalibration, instrs: List[AbstractInstruction]):
assert measure_calibration.instrs == instrs
measure_calibration.instrs = [Gate("SomeGate", [], [Qubit(0)], []), Fence([0])]
assert isinstance(measure_calibration.instrs[0], Gate)
assert not isinstance(measure_calibration.instrs[0], Fence)
assert isinstance(measure_calibration.instrs[1], Fence)
assert not isinstance(measure_calibration.instrs[1], Gate)
assert measure_calibration.instrs == [Gate("SomeGate", [], [Qubit(0)], []), Fence([0])]
def test_instructions(self, measure_calibration: DefMeasureCalibration, instrs: List[AbstractInstruction]):
assert measure_calibration.instructions == instrs
measure_calibration.instrs = [Gate("SomeGate", [], [Qubit(0)], []), Fence([0])]
assert isinstance(measure_calibration.instrs[0], Gate)
assert not isinstance(measure_calibration.instrs[0], Fence)
assert isinstance(measure_calibration.instrs[1], Fence)
assert not isinstance(measure_calibration.instrs[1], Gate)
assert measure_calibration.instrs == [Gate("SomeGate", [], [Qubit(0)], []), Fence([0])]
def test_copy(self, measure_calibration: DefMeasureCalibration):
assert isinstance(copy.copy(measure_calibration), DefMeasureCalibration)
assert isinstance(copy.deepcopy(measure_calibration), DefMeasureCalibration)
def test_convert(self, measure_calibration: DefMeasureCalibration):
rs_measure_calibration = _convert_to_rs_instruction(measure_calibration)
assert measure_calibration == _convert_to_py_instruction(rs_measure_calibration)
def test_pickle(self, measure_calibration: DefMeasureCalibration):
pickled = pickle.dumps(measure_calibration)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DefMeasureCalibration)
assert unpickled == measure_calibration
@pytest.mark.parametrize(
("qubit", "classical_reg"),
[
(Qubit(0), None),
(Qubit(1), MemoryReference("theta", 0, 1)),
],
ids=("No-MemoryReference", "MemoryReference"),
)
class TestMeasurement:
@pytest.fixture
def measurement(self, qubit: Qubit, classical_reg: Optional[MemoryReference]):
return Measurement(qubit, classical_reg)
def test_out(self, measurement: Measurement, snapshot: SnapshotAssertion):
assert measurement.out() == snapshot
def test_str(self, measurement: Measurement, snapshot: SnapshotAssertion):
assert str(measurement) == snapshot
def test_qubit(self, measurement: Measurement, qubit: Qubit):
assert measurement.qubit == qubit
measurement.qubit = Qubit(123)
assert measurement.qubit == Qubit(123)
def test_get_qubits(self, measurement: Measurement, qubit: Qubit):
assert measurement.get_qubits(False) == set([qubit])
if isinstance(qubit, Qubit):
assert measurement.get_qubits(True) == set([qubit.index])
def test_classical_reg(self, measurement: Measurement, classical_reg: MemoryReference):
assert measurement.classical_reg == classical_reg
measurement.classical_reg = MemoryReference("new_mem_ref")
assert measurement.classical_reg == MemoryReference("new_mem_ref")
def test_copy(self, measurement: Measurement):
assert isinstance(copy.copy(measurement), Measurement)
assert isinstance(copy.deepcopy(measurement), Measurement)
def test_convert(self, measurement: Measurement):
rs_measurement = _convert_to_rs_instruction(measurement)
assert measurement == _convert_to_py_instruction(rs_measurement)
def test_pickle(self, measurement: Measurement):
pickled = pickle.dumps(measurement)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, Measurement)
assert unpickled == measurement
@pytest.mark.parametrize(
("frame", "direction", "initial_frequency", "hardware_object", "sample_rate", "center_frequency", "channel_delay"),
[
(Frame([Qubit(0)], "frame"), "direction", 0.0, None, None, None, None),
(Frame([Qubit(1)], "frame"), "direction", 1.39, "hardware_object", 44.1, 440.0, 0.0),
],
ids=("Frame-Only", "With-Optionals"),
)
class TestDefFrame:
@pytest.fixture
def def_frame(
self,
frame: Frame,
direction: Optional[str],
initial_frequency: Optional[float],
hardware_object: Optional[str],
sample_rate: Optional[float],
center_frequency: Optional[float],
channel_delay: Optional[float],
) -> DefFrame:
args = dict(
direction=direction,
initial_frequency=initial_frequency,
hardware_object=hardware_object,
sample_rate=sample_rate,
center_frequency=center_frequency,
channel_delay=channel_delay,
)
return DefFrame(frame, **{k: v for k, v in args.items() if v is not None})
def test_out(self, def_frame: DefFrame, snapshot: SnapshotAssertion):
# The ordering of attributes isn't stable and can be printed in different orders across calls.
# We assert that the first line is definitely the `DEFFRAME` line, and that the following
# attributes are the same, regardless of their order.
quil_lines = def_frame.out().splitlines()
assert quil_lines[0] == snapshot
assert set(quil_lines[1:]) == snapshot
def test_str(self, def_frame: DefFrame, snapshot: SnapshotAssertion):
quil_lines = str(def_frame).splitlines()
assert quil_lines[0] == snapshot
assert set(quil_lines[1:]) == snapshot
def test_frame(self, def_frame: DefFrame, frame: Frame):
assert def_frame.frame == frame
def_frame.frame = Frame([Qubit(123)], "new_frame")
assert def_frame.frame == Frame([Qubit(123)], "new_frame")
def test_direction(self, def_frame: DefFrame, direction: Optional[str]):
assert def_frame.direction == direction
def_frame.direction = "tx"
assert def_frame.direction == "tx"
def test_initial_frequency(self, def_frame: DefFrame, initial_frequency: Optional[float]):
assert def_frame.initial_frequency == initial_frequency
def_frame.initial_frequency = 3.14
assert def_frame.initial_frequency == 3.14
def test_hardware_object(self, def_frame: DefFrame, hardware_object: Optional[str]):
assert def_frame.hardware_object == hardware_object
def_frame.hardware_object = "bfg"
assert def_frame.hardware_object == "bfg"
def test_hardware_object_json(self, def_frame: DefFrame, hardware_object: Optional[str]):
assert def_frame.hardware_object == hardware_object
def_frame.hardware_object = '{"string": "str", "int": 1, "float": 3.14}'
assert def_frame.hardware_object == '{"string": "str", "int": 1, "float": 3.14}'
def test_sample_rate(self, def_frame: DefFrame, sample_rate: Optional[float]):
assert def_frame.sample_rate == sample_rate
def_frame.sample_rate = 96.0
assert def_frame.sample_rate == 96.0
def test_center_frequency(self, def_frame: DefFrame, center_frequency: Optional[float]):
assert def_frame.center_frequency == center_frequency
def_frame.center_frequency = 432.0
assert def_frame.center_frequency == 432.0
def test_channel_delay(self, def_frame: DefFrame, channel_delay: Optional[float]):
assert def_frame.channel_delay == channel_delay
def_frame.channel_delay = 571.0
assert def_frame.channel_delay == 571.0
def test_copy(self, def_frame: DefFrame):
assert isinstance(copy.copy(def_frame), DefFrame)
assert isinstance(copy.deepcopy(def_frame), DefFrame)
def test_convert(self, def_frame: DefFrame):
rs_def_frame = _convert_to_rs_instruction(def_frame)
assert def_frame == _convert_to_py_instruction(rs_def_frame)
def test_pickle(self, def_frame: DefFrame):
pickled = pickle.dumps(def_frame)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DefFrame)
assert unpickled == def_frame
@pytest.mark.parametrize(
("name", "memory_type", "memory_size", "shared_region", "offsets"),
[
("ro", "BIT", 1, None, None),
("ro", "OCTET", 5, None, None),
("ro", "INTEGER", 5, "theta", None),
("ro", "BIT", 5, "theta", [(2, "OCTET")]),
],
ids=("Defaults", "With-Size", "With-Shared", "With-Offsets"),
)
class TestDeclare:
@pytest.fixture
def declare(
self,
name: str,
memory_type: str,
memory_size: int,
shared_region: Optional[str],
offsets: Optional[Iterable[Tuple[int, str]]],
) -> Declare:
return Declare(name, memory_type, memory_size, shared_region, offsets)
def test_out(self, declare: Declare, snapshot: SnapshotAssertion):
assert declare.out() == snapshot
def test_str(self, declare: Declare, snapshot: SnapshotAssertion):
assert str(declare) == snapshot
def test_asdict(self, declare: Declare, snapshot: SnapshotAssertion):
assert declare.asdict() == snapshot
def test_name(self, declare: Declare, name: str):
assert declare.name == name
declare.name = "new_name"
assert declare.name == "new_name"
def test_memory_type(self, declare: Declare, memory_type: Optional[str]):
assert declare.memory_type == memory_type
declare.memory_type = "REAL"
assert declare.memory_type == "REAL"
def test_memory_size(self, declare: Declare, memory_size: Optional[int]):
assert declare.memory_size == memory_size
declare.memory_size = 100
assert declare.memory_size == 100
def test_shared_region(self, declare: Declare, shared_region: Optional[str]):
assert declare.shared_region == shared_region
declare.shared_region = "new_shared"
assert declare.shared_region == "new_shared"
def test_offsets(self, declare: Declare, offsets: Optional[Iterable[Tuple[int, str]]]):
expected_offsets = offsets or []
assert declare.offsets == expected_offsets
if declare.shared_region is None:
with pytest.raises(ValueError):
declare.offsets = [(1, "BIT"), (2, "INTEGER")]
else:
declare.offsets = [(1, "BIT"), (2, "INTEGER")]
assert declare.offsets == [(1, "BIT"), (2, "INTEGER")]
def test_copy(self, declare: Declare):
assert isinstance(copy.copy(declare), Declare)
assert isinstance(copy.deepcopy(declare), Declare)
def test_convert(self, declare: Declare):
rs_declare = _convert_to_rs_instruction(declare)
assert declare == _convert_to_py_instruction(rs_declare)
def test_pickle(self, declare: Declare):
pickled = pickle.dumps(declare)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, Declare)
assert unpickled == declare
@pytest.mark.parametrize(
("command", "args", "freeform_string"),
[
("NO-NOISE", [], ""),
("DOES-A-THING", [Qubit(0), FormalArgument("b")], ""),
("INITIAL_REWIRING", [], "GREEDY"),
("READOUT-POVM", [Qubit(1)], "(0.9 0.19999999999999996 0.09999999999999998 0.8)"),
],
ids=("Command-Only", "With-Arg", "With-String", "With-Arg-And-String"),
)
class TestPragma:
@pytest.fixture
def pragma(self, command: str, args: List[Union[QubitDesignator, str]], freeform_string: str) -> Pragma:
return Pragma(command, args, freeform_string)
def test_out(self, pragma: Pragma, snapshot: SnapshotAssertion):
assert pragma.out() == snapshot
def test_str(self, pragma: Pragma, snapshot: SnapshotAssertion):
assert str(pragma) == snapshot
def test_command(self, pragma: Pragma, command: str):
assert pragma.command == command
pragma.command = "NEW_COMMAND"
assert pragma.command == "NEW_COMMAND"
def test_args(self, pragma: Pragma, args: List[Union[QubitDesignator, str]]):
assert pragma.args == tuple(args)
pragma.args = (Qubit(123),)
assert pragma.args == (Qubit(123),)
def test_freeform_string(self, pragma: Pragma, freeform_string: str):
assert pragma.freeform_string == freeform_string
pragma.freeform_string = "new string"
assert pragma.freeform_string == "new string"
def test_copy(self, pragma: Pragma):
assert isinstance(copy.copy(pragma), Pragma)
assert isinstance(copy.deepcopy(pragma), Pragma)
def test_convert(self, pragma: Pragma):
rs_pragma = _convert_to_rs_instruction(pragma)
assert pragma == _convert_to_py_instruction(rs_pragma)
def test_pickle(self, pragma: Pragma):
pickled = pickle.dumps(pragma)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, Pragma)
assert unpickled == pragma
@pytest.mark.parametrize(
("qubit"),
[
(Qubit(0)),
(FormalArgument("a")),
(None),
],
ids=("Qubit", "FormalArgument", "None"),
)
class TestReset:
@pytest.fixture
def reset_qubit(self, qubit: Qubit) -> Union[Reset, ResetQubit]:
if qubit is None:
with pytest.raises(TypeError):
ResetQubit(qubit)
return Reset(None)
return ResetQubit(qubit)
def test_out(self, reset_qubit: ResetQubit, snapshot: SnapshotAssertion):
assert reset_qubit.out() == snapshot
def test_str(self, reset_qubit: ResetQubit, snapshot: SnapshotAssertion):
assert str(reset_qubit) == snapshot
def test_qubit(self, reset_qubit: ResetQubit, qubit: Qubit):
assert reset_qubit.qubit == qubit
reset_qubit.qubit = FormalArgument("a")
assert reset_qubit.qubit == FormalArgument("a")
def test_get_qubits(self, reset_qubit: ResetQubit, qubit: Qubit):
if qubit is None:
assert reset_qubit.get_qubits(False) is None
assert reset_qubit.get_qubit_indices() is None
else:
assert reset_qubit.get_qubits(False) == {qubit}
if isinstance(qubit, Qubit):
assert reset_qubit.get_qubit_indices() == {qubit.index}
def test_copy(self, reset_qubit: Union[Reset, ResetQubit]):
assert isinstance(copy.copy(reset_qubit), type(reset_qubit))
assert isinstance(copy.deepcopy(reset_qubit), type(reset_qubit))
def test_convert(self, reset_qubit: Reset):
rs_reset_qubit = _convert_to_rs_instruction(reset_qubit)
assert reset_qubit == _convert_to_py_instruction(rs_reset_qubit)
def test_pickle(self, reset_qubit: Reset):
pickled = pickle.dumps(reset_qubit)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, (Reset, ResetQubit))
assert unpickled == reset_qubit
@pytest.mark.parametrize(
("frames", "duration"),
[
([Frame([Qubit(0)], "frame")], 5.0),
],
)
class TestDelayFrames:
@pytest.fixture
def delay_frames(self, frames: List[Frame], duration: float) -> DelayFrames:
return DelayFrames(frames, duration)
def test_out(self, delay_frames: DelayFrames, snapshot: SnapshotAssertion):
assert delay_frames.out() == snapshot
def test_frames(self, delay_frames: DelayFrames, frames: List[Frame]):
assert delay_frames.frames == frames
delay_frames.frames = [Frame([Qubit(123)], "new_frame")]
assert delay_frames.frames == [Frame([Qubit(123)], "new_frame")]
def test_duration(self, delay_frames: DelayFrames, duration: float):
assert delay_frames.duration == duration
delay_frames.duration = 3.14
assert delay_frames.duration == 3.14
def test_copy(self, delay_frames: DelayFrames):
assert isinstance(copy.copy(delay_frames), DelayFrames)
assert isinstance(copy.deepcopy(delay_frames), DelayFrames)
def test_convert(self, delay_frames: DelayFrames):
rs_delay_frames = _convert_to_rs_instruction(delay_frames)
assert delay_frames == _convert_to_py_instruction(rs_delay_frames)
def test_pickle(self, delay_frames: DelayFrames):
pickled = pickle.dumps(delay_frames)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DelayFrames)
assert unpickled == delay_frames
@pytest.mark.parametrize(
("qubits", "duration"),
[
([Qubit(0)], 5.0),
([FormalArgument("a")], 2.5),
],
ids=("Qubit", "FormalArgument"),
)
class TestDelayQubits:
@pytest.fixture
def delay_qubits(self, qubits: List[Union[Qubit, FormalArgument]], duration: float) -> DelayQubits:
return DelayQubits(qubits, duration)
def test_out(self, delay_qubits: DelayQubits, snapshot: SnapshotAssertion):
assert delay_qubits.out() == snapshot
def test_qubits(self, delay_qubits: DelayQubits, qubits: List[Qubit]):
assert delay_qubits.qubits == qubits
delay_qubits.qubits = [Qubit(123)] # type: ignore
assert delay_qubits.qubits == [Qubit(123)]
def test_duration(self, delay_qubits: DelayQubits, duration: float):
assert delay_qubits.duration == duration
delay_qubits.duration = 3.14
assert delay_qubits.duration == 3.14
def test_copy(self, delay_qubits: DelayQubits):
assert isinstance(copy.copy(delay_qubits), DelayQubits)
assert isinstance(copy.deepcopy(delay_qubits), DelayQubits)
def test_convert(self, delay_qubits: DelayQubits):
rs_delay_qubits = _convert_to_rs_instruction(delay_qubits)
assert delay_qubits == _convert_to_py_instruction(rs_delay_qubits)
def test_pickle(self, delay_qubits: DelayQubits):
pickled = pickle.dumps(delay_qubits)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, DelayQubits)
assert unpickled == delay_qubits
@pytest.mark.parametrize(
("qubits"),
[
([Qubit(0)]),
([FormalArgument("a")]),
],
ids=("Qubit", "FormalArgument"),
)
class TestFence:
@pytest.fixture
def fence(self, qubits: List[Union[Qubit, FormalArgument]]) -> Fence:
return Fence(qubits)
def test_out(self, fence: Fence, snapshot: SnapshotAssertion):
assert fence.out() == snapshot
def test_qubits(self, fence: Fence, qubits: List[Union[Qubit, FormalArgument]]):
assert fence.qubits == qubits
fence.qubits = [Qubit(123)] # type: ignore
assert fence.qubits == [Qubit(123)]
def test_copy(self, fence: Fence):
assert isinstance(copy.copy(fence), Fence)
assert isinstance(copy.deepcopy(fence), Fence)
def test_convert(self, fence: Fence):
rs_fence = _convert_to_rs_instruction(fence)
assert fence == _convert_to_py_instruction(rs_fence)
def test_pickle(self, fence: Fence):
pickled = pickle.dumps(fence)
unpickled = pickle.loads(pickled)
assert isinstance(unpickled, Fence)
assert unpickled == fence
def test_fence_all():
fa = FenceAll()
assert fa.out() == "FENCE"
assert fa.qubits == []
@pytest.mark.parametrize(
("name", "parameters", "entries"),
[
("Wavey", [Parameter("x")], [Parameter("x")]),
(
"Wavey",
[Parameter("x"), Parameter("y")],
[complex(1.0, 2.0), Parameter("x"), Mul(complex(3.0, 0.0), Parameter("y"))],
),
],
ids=("With-Param", "With-Params-Complex"),
)
class TestDefWaveform:
@pytest.fixture
def def_waveform(self, name: str, parameters: List[Parameter], entries: List[Union[complex, Expression]]):
return DefWaveform(name, parameters, entries)
def test_out(self, def_waveform: DefWaveform, snapshot: SnapshotAssertion):
assert def_waveform.out() == snapshot
def test_name(self, def_waveform: DefWaveform, name: str):
assert def_waveform.name == name
def_waveform.name = "new_name"
assert def_waveform.name == "new_name"
def test_parameters(self, def_waveform: DefWaveform, parameters: List[Parameter]):
assert def_waveform.parameters == parameters
def_waveform.parameters = [Parameter("z")]
assert def_waveform.parameters == [Parameter("z")]
def test_entries(self, def_waveform: DefWaveform, entries: List[Union[Complex, Expression]]):
assert def_waveform.entries == entries
def_waveform.entries = [Parameter("z")] # type: ignore
assert def_waveform.entries == [Parameter("z")]
def test_copy(self, def_waveform: DefWaveform):
assert isinstance(copy.copy(def_waveform), DefWaveform)
assert isinstance(copy.deepcopy(def_waveform), DefWaveform)
def test_convert(self, def_waveform: DefWaveform):
rs_def_waveform = _convert_to_rs_instruction(def_waveform)
assert def_waveform == _convert_to_py_instruction(rs_def_waveform)