-
Notifications
You must be signed in to change notification settings - Fork 558
/
test_default_qubit_legacy_broadcasting.py
2019 lines (1651 loc) · 73 KB
/
test_default_qubit_legacy_broadcasting.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 2018-2020 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit tests for the :class:`pennylane.devices.DefaultQubitLegacy` device when using broadcasting.
"""
from itertools import product
# pylint: disable=protected-access,cell-var-from-loop,too-many-arguments
import math
import pytest
from gate_data import (
X,
Y,
Z,
S,
T,
H,
CNOT,
SWAP,
CZ,
ISWAP,
SISWAP,
CSWAP,
Rphi,
Rotx,
Roty,
Rotz,
MultiRZ1,
Rot3,
CRotx,
CRoty,
CRotz,
MultiRZ2,
IsingXX,
IsingYY,
IsingZZ,
CRot3,
I,
Toffoli,
)
import pennylane as qml
from pennylane import numpy as np, DeviceError
from pennylane.devices.default_qubit_legacy import DefaultQubitLegacy
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
INVSQ2 = 1 / math.sqrt(2)
T_PHASE = np.exp(1j * np.pi / 4)
T_PHASE_C = np.exp(-1j * np.pi / 4)
# Variant of diag that does not take the diagonal of a 2d array, but broadcasts diag.
diag = lambda x: np.array([np.diag(_x) for _x in x]) if np.ndim(x) == 2 else np.diag(x)
def mat_vec(mat, vec, par=None, inv=False):
if par is not None:
scalar = [np.isscalar(p) for p in par]
if not all(scalar):
batch_size = len(par[scalar.index(False)])
par = [tuple(p if s else p[i] for p, s in zip(par, scalar)) for i in range(batch_size)]
mat = np.array([mat(*_par) for _par in par])
else:
mat = mat(*par)
if inv:
mat = np.moveaxis(mat.conj(), -2, -1)
return np.einsum("...ij,...j->...i", mat, vec)
class TestApplyBroadcasted:
"""Tests that operations and inverses of certain operations are applied to a broadcasted
state/with broadcasted parameters (or both) correctly, or that the proper errors are raised.
"""
triple_state = np.array([[1, 0], [INVSQ2, INVSQ2], [0, 1]])
test_data_no_parameters = [
(qml.PauliX, triple_state, mat_vec(X, triple_state)),
(qml.PauliY, triple_state, mat_vec(Y, triple_state)),
(qml.PauliZ, triple_state, mat_vec(Z, triple_state)),
(qml.S, triple_state, mat_vec(S, triple_state)),
(qml.T, triple_state, mat_vec(T, triple_state)),
(qml.Hadamard, triple_state, mat_vec(H, triple_state)),
(qml.Identity, triple_state, triple_state),
]
@pytest.mark.parametrize("operation,input,expected_output", test_data_no_parameters)
def test_apply_operation_single_wire_no_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output
):
"""Tests that applying an operation yields the expected output state for single wire
operations that have no parameters."""
qubit_device_1_wire._state = np.array(input, dtype=qubit_device_1_wire.C_DTYPE)
qubit_device_1_wire.apply([operation(wires=[0])])
assert np.allclose(qubit_device_1_wire._state, np.array(expected_output), atol=tol, rtol=0)
assert qubit_device_1_wire._state.dtype == qubit_device_1_wire.C_DTYPE
single_state = np.array([[0, 0.6, 0, 0.8]])
triple_state = np.array([[1, 0, 0, 0], [0, 0, INVSQ2, -INVSQ2], [0, 0.6, 0, 0.8]])
test_data_two_wires_no_param = [
(qml_op, state, mat_vec(mat_op, state))
for (qml_op, mat_op), state in product(
zip(
[qml.CNOT, qml.SWAP, qml.CZ, qml.ISWAP, qml.SISWAP, qml.SQISW],
[CNOT, SWAP, CZ, ISWAP, SISWAP, SISWAP],
),
[single_state, triple_state],
)
]
@pytest.mark.parametrize("operation,input,expected_output", test_data_two_wires_no_param)
def test_apply_operation_two_wires_no_parameters_broadcasted(
self, qubit_device_2_wires, tol, operation, input, expected_output
):
"""Tests that applying an operation yields the expected output state for two wire
operations that have no parameters."""
qubit_device_2_wires._state = np.array(input, dtype=qubit_device_2_wires.C_DTYPE).reshape(
(-1, 2, 2)
)
qubit_device_2_wires.apply([operation(wires=[0, 1])])
assert np.allclose(
qubit_device_2_wires._state.reshape((-1, 4)),
np.array(expected_output),
atol=tol,
rtol=0,
)
assert qubit_device_2_wires._state.dtype == qubit_device_2_wires.C_DTYPE
quad_state = np.array(
[
[0.6, 0, 0, 0, 0, 0, 0.8, 0],
[-INVSQ2, INVSQ2, 0, 0, 0, 0, 0, 0],
[0, 0, 0.5, 0.5, 0.5, -0.5, 0, 0],
[0, 0, 0.5, 0, 0.5, -0.5, 0, 0.5],
]
)
test_data_three_wires_no_parameters = [(qml.CSWAP, quad_state, mat_vec(CSWAP, quad_state))]
@pytest.mark.parametrize("operation,input,expected_output", test_data_three_wires_no_parameters)
def test_apply_operation_three_wires_no_parameters_broadcasted(
self, qubit_device_3_wires, tol, operation, input, expected_output
):
"""Tests that applying an operation yields the expected output state for three wire
operations that have no parameters."""
qubit_device_3_wires._state = np.array(input, dtype=qubit_device_3_wires.C_DTYPE).reshape(
(-1, 2, 2, 2)
)
qubit_device_3_wires.apply([operation(wires=[0, 1, 2])])
assert np.allclose(
qubit_device_3_wires._state.reshape((-1, 8)),
np.array(expected_output),
atol=tol,
rtol=0,
)
assert qubit_device_3_wires._state.dtype == qubit_device_3_wires.C_DTYPE
single_state = np.array([[0, 0, 1, 0]])
triple_state = np.array(
[
[0, 0, 1, 0],
[1 / math.sqrt(3), 0, 1 / math.sqrt(3), 1 / math.sqrt(3)],
[0.5, -0.5, 0.5j, -0.5j],
]
)
# TODO[dwierichs]: add tests with qml.BaisState once `_apply_basis_state` supports broadcasting
@pytest.mark.parametrize(
"operation,expected_output,par",
[(qml.StatePrep, s, s) for s in [single_state, triple_state]],
)
def test_apply_operation_state_preparation_broadcasted(
self, qubit_device_2_wires, tol, operation, expected_output, par
):
"""Tests that applying an operation yields the expected output state for single wire
operations that have no parameters."""
par = np.array(par)
qubit_device_2_wires.reset()
qubit_device_2_wires.apply([operation(par, wires=[0, 1])])
assert np.allclose(
qubit_device_2_wires._state.reshape((-1, 4)),
np.array(expected_output),
atol=tol,
rtol=0,
)
# Collect test cases for single-scalar-parameter single-wire operations and their inverses
# For each operation, we choose broadcasted state, broadcasted params, or both
state_1 = np.array([0.6, 0.8j])
state_5 = np.array([[INVSQ2, INVSQ2], [0.6, 0.8], [0, 1j], [-1, 0], [-INVSQ2, INVSQ2]])
scalar_par_1 = [np.pi / 2]
scalar_par_5 = [[np.pi / 3, np.pi, 0.5, -1.2, -3 * np.pi / 2]]
test_data_single_wire_with_parameters = [
(qml_op, state, mat_vec(mat_op, state, par=par), par)
for (qml_op, mat_op), (state, par) in product(
zip(
[qml.PhaseShift, qml.RX, qml.RY, qml.RZ, qml.MultiRZ],
[Rphi, Rotx, Roty, Rotz, MultiRZ1],
),
[(state_1, scalar_par_5), (state_5, scalar_par_1), (state_5, scalar_par_5)],
)
]
# Add qml.QubitUnitary test cases
matrix_1_par_1 = [np.array([[1, 1j], [1j, 1]]) * INVSQ2]
matrix_1_par_5 = [
np.array(
[
np.array([[1, -1j], [-1j, 1]]) * INVSQ2,
np.array([[1, -1], [1, 1]]) * INVSQ2,
np.array([[T_PHASE_C, 0], [0, T_PHASE]]),
np.array([[1, 0], [0, -1]]),
T,
]
)
]
test_data_single_wire_with_parameters += [
(qml.QubitUnitary, s, mat_vec(par[0], s), par)
for s, par in [
(state_1, matrix_1_par_5),
(state_5, matrix_1_par_1),
(state_5, matrix_1_par_5),
]
]
# Add qml.DiagonalQubitUnitary test cases
diag_par_1 = [[np.exp(1j * 0.1), np.exp(1j * np.pi)]]
diag_par_5 = [
np.array(
[
[1, -1j],
[np.exp(1j * 0.4), np.exp(1j * -0.4)],
[np.exp(1j * 0.1), np.exp(1j * np.pi)],
[1.0, np.exp(1j * np.pi / 2)],
[1, 1],
]
)
]
test_data_single_wire_with_parameters += [
(qml.DiagonalQubitUnitary, s, mat_vec(diag(par[0]), s), par)
for s, par in [(state_1, diag_par_5), (state_5, diag_par_1), (state_5, diag_par_5)]
]
# Add qml.SpecialUnitary test cases
theta_1_par_1 = [np.array([np.pi / 2, 0, 0])]
theta_1_par_5 = [
np.array(
[[np.pi / 2, 0, 0], [0, np.pi / 2, 0], [0, 0, np.pi / 2], [0.3, 0, 0], [0.4, 0.2, 1.2]]
)
]
test_data_single_wire_with_parameters += [
(qml.SpecialUnitary, s, mat_vec(qml.SpecialUnitary.compute_matrix(par[0], 1), s), par)
for s, par in [(state_1, theta_1_par_5), (state_5, theta_1_par_1), (state_5, theta_1_par_5)]
]
# Add qml.Rot test cases
multi_par_1 = {
"rz_0": [0.632, 0, 0],
"ry": [0, 0.632, 0],
"rz_1": [0, 0, 0.632],
"mixed": [0.12, -2.468, 0.812],
}
multi_par_5 = {
"rz_0": [[np.pi / 2 * i for i in range(5)], 0, 0],
"ry": [0, [np.pi / 2 * i for i in range(5)], 0],
"rz_1": [0, 0, [np.pi / 2 * i for i in range(5)]],
"mixed": [[np.pi / 2 * i for i in range(5)], [np.pi / 2 * i for i in range(5)], np.pi],
}
for like in ["rz_0", "ry", "rz_1", "mixed"]:
states_and_pars = [
(state_1, multi_par_5[like]),
(state_5, multi_par_1[like]),
(state_5, multi_par_5[like]),
]
test_data_single_wire_with_parameters += [
(qml.Rot, s, mat_vec(Rot3, s, par=par), par) for s, par in states_and_pars
]
@pytest.mark.parametrize(
"operation,input,expected_output,par", test_data_single_wire_with_parameters
)
def test_apply_operation_single_wire_with_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output, par
):
"""Tests that applying an operation yields the expected output state for single wire
operations that have parameters."""
qubit_device_1_wire._state = np.array(input, dtype=qubit_device_1_wire.C_DTYPE)
par = tuple(np.array(p) for p in par)
qubit_device_1_wire.apply([operation(*par, wires=[0])])
assert np.allclose(qubit_device_1_wire._state, np.array(expected_output), atol=tol, rtol=0)
assert qubit_device_1_wire._state.dtype == qubit_device_1_wire.C_DTYPE
# Collect test cases for single-scalar-parameter two-wires operations and their inverses
# For each operation, we choose broadcasted state, broadcasted params, or both
state_1 = np.array([0.6, 0.8j, -0.6, -0.8j]) * INVSQ2
state_5 = np.array(
[
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, INVSQ2, INVSQ2, 0],
[0.5, 0.5j, -0.5, 0.5],
[0.6, 0, -0.8j, 0],
]
)
scalar_par_1 = [np.pi / 2]
scalar_par_5 = [[np.pi / 3, np.pi, 0.5, -1.2, -3 * np.pi / 2]]
two_wires_scalar_par_ops = [
qml.CRX,
qml.CRY,
qml.CRZ,
qml.MultiRZ,
qml.IsingXX,
qml.IsingYY,
qml.IsingZZ,
]
two_wires_scalar_par_mats = [CRotx, CRoty, CRotz, MultiRZ2, IsingXX, IsingYY, IsingZZ]
test_data_two_wires_with_parameters = [
(qml_op, state, mat_vec(mat_op, state, par=par), par)
for (qml_op, mat_op), (state, par) in product(
zip(two_wires_scalar_par_ops, two_wires_scalar_par_mats),
[(state_1, scalar_par_5), (state_5, scalar_par_1), (state_5, scalar_par_5)],
)
]
# Add qml.CRot test cases
multi_par_1 = {
"rz_0": [0.632, 0, 0],
"ry": [0, 0.632, 0],
"rz_1": [0, 0, 0.632],
"mixed": [0.12, -2.468, 0.812],
}
multi_par_5 = {
"rz_0": [[np.pi / 2 * i for i in range(5)], 0, 0],
"ry": [0, [np.pi / 2 * i for i in range(5)], 0],
"rz_1": [0, 0, [np.pi / 2 * i for i in range(5)]],
"mixed": [[np.pi / 2 * i for i in range(5)], [np.pi / 2 * i for i in range(5)], np.pi],
}
for like in ["rz_0", "ry", "rz_1", "mixed"]:
states_and_pars = [
(state_1, multi_par_5[like]),
(state_5, multi_par_1[like]),
(state_5, multi_par_5[like]),
]
test_data_two_wires_with_parameters += [
(qml.CRot, s, mat_vec(CRot3, s, par=par), par) for s, par in states_and_pars
]
# Add qml.QubitUnitary test cases
matrix_2_par_1 = [SISWAP]
matrix_2_par_5 = [
np.array(
[
np.eye(4),
np.array([[1, -1j, 0, 0], [-1j, 1, 0, 0], [0, 0, 1, -1j], [0, 0, -1j, 1]]) * INVSQ2,
np.array([[1, -1, 0, 0], [1, 1, 0, 0], [0, 0, 1, -1j], [0, 0, 1j, -1]]) * INVSQ2,
np.array([[T_PHASE_C, 0, 0, 0], [0, T_PHASE, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1j]]),
SISWAP,
]
)
]
test_data_two_wires_with_parameters += [
(qml.QubitUnitary, s, mat_vec(par[0], s), par)
for s, par in [
(state_1, matrix_2_par_5),
(state_5, matrix_2_par_1),
(state_5, matrix_2_par_5),
]
]
# Add qml.DiagonalQubitUnitary test cases
diag_par_1 = [np.exp(1j * np.array([0.1, np.pi, 0.2, -2.4]))]
diag_par_5 = [
np.array(
[
np.ones(4),
[1, -1j, 1, 1j],
[np.exp(1j * 0.4), np.exp(1j * -0.4), 1j, 1],
[np.exp(1j * 0.1), np.exp(1j * np.pi), INVSQ2 * (1 + 1j), INVSQ2 * (1 - 1j)],
[1.0, np.exp(1j * np.pi / 2), 1, 1],
]
)
]
test_data_two_wires_with_parameters += [
(qml.DiagonalQubitUnitary, s, mat_vec(diag(par[0]), s), par)
for s, par in [(state_1, diag_par_5), (state_5, diag_par_1), (state_5, diag_par_5)]
]
# Add qml.SpecialUnitary test cases
theta_2_par_1 = [np.linspace(0.1, 3, 15)]
theta_2_par_5 = [np.array([0.4, -0.2, 1.2, -0.5, 2.2])[:, np.newaxis] * np.eye(15)[2::3]]
test_data_two_wires_with_parameters += [
(qml.SpecialUnitary, s, mat_vec(qml.SpecialUnitary.compute_matrix(par[0], 2), s), par)
for s, par in [(state_1, theta_2_par_5), (state_5, theta_2_par_1), (state_5, theta_2_par_5)]
]
@pytest.mark.parametrize(
"operation,input,expected_output,par", test_data_two_wires_with_parameters
)
def test_apply_operation_two_wires_with_parameters_broadcasted(
self, qubit_device_2_wires, tol, operation, input, expected_output, par
):
"""Tests that applying an operation yields the expected output state for two wire
operations that have parameters."""
shape = (5, 2, 2) if np.array(input).size == 20 else (2, 2)
dtype = qubit_device_2_wires.C_DTYPE
qubit_device_2_wires._state = np.array(input, dtype=dtype).reshape(shape)
par = tuple(np.array(p) for p in par)
qubit_device_2_wires.apply([operation(*par, wires=[0, 1])])
assert np.allclose(
qubit_device_2_wires._state.reshape((5, 4)), expected_output, atol=tol, rtol=0
)
assert qubit_device_2_wires._state.dtype == qubit_device_2_wires.C_DTYPE
def test_apply_errors_qubit_state_vector_broadcasted(self, qubit_device_2_wires):
"""Test that apply fails for incorrect state preparation, and > 2 qubit gates"""
with pytest.raises(ValueError, match="Sum of amplitudes-squared does not equal one."):
qubit_device_2_wires.apply([qml.StatePrep(np.array([[1, -1], [0, 2]]), wires=[0])])
# Also test that the sum-check is *not* performed along the broadcasting dimension
qubit_device_2_wires.apply([qml.StatePrep(np.array([[0.6, 0.8], [0.6, 0.8]]), wires=[0])])
with pytest.raises(ValueError, match=r"State vector must have shape \(2\*\*wires,\)."):
# Second dimension does not match 2**num_wires
p = np.array([[1, 0, 1, 1, 0], [0, 1, 1, 0, 1]]) / np.sqrt(3)
qubit_device_2_wires.apply([qml.StatePrep(p, wires=[0, 1])])
with pytest.raises(ValueError, match=r"State vector must have shape \(2\*\*wires,\)."):
# Broadcasting dimension is not first dimension
p = np.array([[1, 1, 0], [0, 1, 1], [1, 0, 1], [0, 1, 1]]) / np.sqrt(2)
qubit_device_2_wires.apply([qml.StatePrep(p, wires=[0, 1])])
qubit_device_2_wires.reset()
vec = qml.StatePrep(np.array([[0, 1, 0, 0], [0, 0, 1, 0]]), wires=[0, 1])
with pytest.raises(
DeviceError,
match="Operation StatePrep cannot be used after other Operations have already been applied "
"on a default.qubit.legacy device.",
):
qubit_device_2_wires.apply([qml.RZ(0.5, wires=[0]), vec])
@pytest.mark.skip("Applying a BasisState does not support broadcasting yet")
def test_apply_errors_basis_state_broadcasted(self, qubit_device_2_wires):
"""Test that applying the BasisState operation raises the correct errors."""
with pytest.raises(
ValueError, match="BasisState parameter must consist of 0 or 1 integers."
):
op = qml.BasisState(np.array([[-0.2, 4.2], [0.5, 1.2]]), wires=[0, 1])
qubit_device_2_wires.apply([op])
with pytest.raises(
ValueError, match="BasisState parameter and wires must be of equal length."
):
# Test that the error is raised
qubit_device_2_wires.apply(
[qml.BasisState(np.array([[0, 1], [1, 1], [1, 0]]), wires=[0])]
)
# Test that the broadcasting dimension is allowed to mismatch the length of the wires
qubit_device_2_wires.apply([qml.BasisState(np.array([[0], [1], [0]]), wires=[0])])
qubit_device_2_wires.reset()
qubit_device_2_wires.apply([qml.RZ(0.5, wires=[0])])
vec = qml.BasisState(np.array([[0, 0], [1, 0], [1, 1]]), wires=[0, 1])
with pytest.raises(
DeviceError,
match="Operation BasisState cannot be used after other Operations have already been applied "
"on a default.qubit.legacy device.",
):
qubit_device_2_wires.apply([vec])
zero = [1, 0]
one = [0, 1]
plus = [INVSQ2, INVSQ2]
minus = [INVSQ2, -INVSQ2]
y_plus = [INVSQ2, 1j * INVSQ2]
y_minus = [INVSQ2, -1j * INVSQ2]
class TestExpvalBroadcasted:
"""Tests that expectation values are properly calculated for broadcasted states
or that the proper errors are raised."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, np.array([plus, zero, minus]), [1, 0, -1]),
(qml.PauliY, np.array([y_plus, zero, y_minus]), [1, 0, -1]),
(qml.PauliZ, np.array([plus, zero, one]), [0, 1, -1]),
(qml.Hadamard, np.array([plus, zero, one]), [INVSQ2, INVSQ2, -INVSQ2]),
(qml.Identity, np.array([minus, zero, one]), [1, 1, 1]),
],
)
def test_expval_single_wire_no_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output
):
"""Tests that expectation values are properly calculated for single-wire observables without parameters."""
obs = operation(wires=[0])
qubit_device_1_wire.reset()
qubit_device_1_wire.apply(
[qml.StatePrep(np.array(input), wires=[0])], obs.diagonalizing_gates()
)
res = qubit_device_1_wire.expval(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"operation,input,expected_output,par",
[(qml.Hermitian, [zero, one, minus, y_plus], [1, 1, 1, 0], I - Y)],
)
def test_expval_single_wire_with_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output, par
):
"""Tests that expectation values are properly calculated for single-wire observables with parameters."""
obs = operation(np.array(par), wires=[0])
qubit_device_1_wire.reset()
qubit_device_1_wire.apply(
[qml.StatePrep(np.array(input), wires=[0])], obs.diagonalizing_gates()
)
res = qubit_device_1_wire.expval(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"operation,input,expected_output,par",
[
(
qml.Hermitian,
[
[1 / math.sqrt(3), 0, 1 / math.sqrt(3), 1 / math.sqrt(3)],
[0, 0, 0, 1],
[1 / math.sqrt(2), 0, -1 / math.sqrt(2), 0],
],
[4 / 3, 0, 1],
[[1, 1j, 0, 1], [-1j, 1, 0, 0], [0, 0, 1, -1j], [1, 0, 1j, 0]],
),
(
qml.Hermitian,
[[INVSQ2, 0, 0, INVSQ2], [0, INVSQ2, -INVSQ2, 0]],
[1, -1],
[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
),
],
)
def test_expval_two_wires_with_parameters_broadcasted(
self, qubit_device_2_wires, tol, operation, input, expected_output, par
):
"""Tests that expectation values are properly calculated for two-wire observables with parameters."""
obs = operation(np.array(par), wires=[0, 1])
qubit_device_2_wires.reset()
qubit_device_2_wires.apply(
[qml.StatePrep(np.array(input), wires=[0, 1])], obs.diagonalizing_gates()
)
res = qubit_device_2_wires.expval(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
def test_expval_estimate_broadcasted(self):
"""Test that the expectation value is not analytically calculated"""
dev = qml.device("default.qubit.legacy", wires=1, shots=3)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit():
qml.RX(np.zeros(5), wires=0) # Broadcast the tape without applying an op
return qml.expval(qml.PauliX(0))
expval = circuit()
# With 3 samples we are guaranteed to see a difference between
# an estimated variance an an analytically calculated one
assert np.all(expval != 0.0)
class TestVarBroadcasted:
"""Tests that variances are properly calculated for broadcasted states."""
@pytest.mark.parametrize(
"operation,input,expected_output",
[
(qml.PauliX, [plus, zero, minus], [0, 1, 0]),
(qml.PauliY, [y_plus, zero, y_minus], [0, 1, 0]),
(qml.PauliZ, [plus, zero, one], [1, 0, 0]),
(qml.Hadamard, [plus, zero, one], [0.5, 0.5, 0.5]),
(qml.Identity, [minus, zero, one], [0, 0, 0]),
],
)
def test_var_single_wire_no_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output
):
"""Tests that variances are properly calculated for single-wire observables without parameters."""
obs = operation(wires=[0])
qubit_device_1_wire.reset()
qubit_device_1_wire.apply(
[qml.StatePrep(np.array(input), wires=[0])], obs.diagonalizing_gates()
)
res = qubit_device_1_wire.var(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"operation,input,expected_output,par",
[(qml.Hermitian, [zero, one, minus, y_plus], [1, 1, 1, 0], I - Y)],
)
def test_var_single_wire_with_parameters_broadcasted(
self, qubit_device_1_wire, tol, operation, input, expected_output, par
):
"""Tests that variances are properly calculated for single-wire observables with parameters."""
obs = operation(np.array(par), wires=[0])
qubit_device_1_wire.reset()
qubit_device_1_wire.apply(
[qml.StatePrep(np.array(input), wires=[0])], obs.diagonalizing_gates()
)
res = qubit_device_1_wire.var(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"operation,input,expected_output,par",
[
(
qml.Hermitian,
[
[1 / math.sqrt(3), 0, 1 / math.sqrt(3), 1 / math.sqrt(3)],
[0, 0, 0, 1],
[1 / math.sqrt(2), 0, -1 / math.sqrt(2), 0],
],
[11 / 9, 2, 3 / 2],
[[1, 1j, 0, 1], [-1j, 1, 0, 0], [0, 0, 1, -1j], [1, 0, 1j, 1]],
),
(
qml.Hermitian,
[[INVSQ2, 0, 0, INVSQ2], [0, INVSQ2, -INVSQ2, 0]],
[0, 0],
[[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],
),
],
)
def test_var_two_wires_with_parameters_broadcasted(
self, qubit_device_2_wires, tol, operation, input, expected_output, par
):
"""Tests that variances are properly calculated for two-wire observables with parameters."""
obs = operation(np.array(par), wires=[0, 1])
qubit_device_2_wires.reset()
qubit_device_2_wires.apply(
[qml.StatePrep(np.array(input), wires=[0, 1])], obs.diagonalizing_gates()
)
res = qubit_device_2_wires.var(obs)
assert np.allclose(res, expected_output, atol=tol, rtol=0)
def test_var_estimate_broadcasted(self):
"""Test that the variance is not analytically calculated"""
dev = qml.device("default.qubit.legacy", wires=1, shots=3)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit():
qml.RX(np.zeros(5), wires=0) # Broadcast the tape without applying an op
return qml.var(qml.PauliX(0))
var = circuit()
# With 3 samples we are guaranteed to see a difference between
# an estimated variance and an analytically calculated one
assert np.all(var != 1.0)
class TestSampleBroadcasted:
"""Tests that samples are properly calculated for broadcasted states."""
def test_sample_dimensions_broadcasted(self):
"""Tests if the samples returned by the sample function have
the correct dimensions
"""
# Explicitly resetting is necessary as the internal
# state is set to None in __init__ and only properly
# initialized during reset
dev = qml.device("default.qubit.legacy", wires=2, shots=1000)
dev.apply([qml.RX(np.array([np.pi / 2, 0.0]), 0), qml.RX(np.array([np.pi / 2, 0.0]), 1)])
dev.shots = 10
dev._wires_measured = {0}
dev._samples = dev.generate_samples()
s1 = dev.sample(qml.PauliZ(0))
assert s1.shape == (
2,
10,
)
dev.reset()
dev.shots = 12
dev._wires_measured = {1}
dev._samples = dev.generate_samples()
s2 = dev.sample(qml.PauliZ(wires=[1]))
assert s2.shape == (12,)
dev.reset()
dev.apply([qml.RX(np.ones(5), 0), qml.RX(np.ones(5), 1)])
dev.shots = 17
dev._wires_measured = {0, 1}
dev._samples = dev.generate_samples()
s3 = dev.sample(qml.PauliX(0) @ qml.PauliZ(1))
assert s3.shape == (5, 17)
def test_sample_values_broadcasted(self, tol):
"""Tests if the samples returned by sample have
the correct values
"""
# Explicitly resetting is necessary as the internal
# state is set to None in __init__ and only properly
# initialized during reset
dev = qml.device("default.qubit.legacy", wires=2, shots=1000)
dev.apply([qml.RX(np.ones(3), wires=[0])])
dev._wires_measured = {0}
dev._samples = dev.generate_samples()
s1 = dev.sample(qml.PauliZ(0))
# s1 should only contain 1 and -1, which is guaranteed if
# they square to 1
assert np.allclose(s1**2, 1, atol=tol, rtol=0)
class TestDefaultQubitIntegrationBroadcasted:
"""Integration tests for default.qubit.legacy. This test ensures it integrates
properly with the PennyLane interface, in particular QNode."""
@pytest.mark.parametrize("r_dtype", [np.float32, np.float64])
def test_qubit_circuit_broadcasted(self, qubit_device_1_wire, r_dtype, tol):
"""Test that the default qubit plugin provides correct result for a simple circuit"""
p = np.array([0.543, np.pi / 2, 0.0, 1.0])
dev = qubit_device_1_wire
dev.R_DTYPE = r_dtype
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(x):
qml.RX(x, wires=0)
return qml.expval(qml.PauliY(0))
expected = -np.sin(p)
res = circuit(p)
assert np.allclose(res, expected, atol=tol, rtol=0)
assert res.dtype == r_dtype # pylint:disable=no-member
def test_qubit_identity_broadcasted(self, qubit_device_1_wire, tol):
"""Test that the default qubit plugin provides correct result for the Identity expectation"""
p = np.array([0.543, np.pi / 2, 0.0, 1.0])
@qml.qnode(qubit_device_1_wire)
def circuit(x):
"""Test quantum function"""
qml.RX(x, wires=0)
return qml.expval(qml.Identity(0))
assert np.allclose(circuit(p), 1, atol=tol, rtol=0)
def test_nonzero_shots_broadcasted(self, tol):
"""Test that the default qubit plugin provides correct result for high shot number"""
shots = 10**5
dev = qml.device("default.qubit.legacy", wires=1, shots=shots)
p = np.array([0.543, np.pi / 2, 0.0, 1.0])
@qml.qnode(dev, diff_method="parameter-shift")
def circuit(x):
"""Test quantum function"""
qml.RX(x, wires=0)
return qml.expval(qml.PauliY(0))
runs = []
for _ in range(100):
runs.append(circuit(p))
assert np.allclose(np.mean(runs, axis=0), -np.sin(p), atol=tol, rtol=0)
@pytest.mark.parametrize(
"name,state,expected_output",
[
("PauliX", [plus, minus, zero], [1, -1, 0]),
("PauliY", [y_plus, y_minus, zero], [1, -1, 0]),
("PauliZ", [plus, one, zero], [0, -1, 1]),
("Hadamard", [plus, one, zero], [INVSQ2, -INVSQ2, INVSQ2]),
],
)
def test_supported_observable_single_wire_no_parameters_broadcasted(
self, qubit_device_1_wire, tol, name, state, expected_output
):
"""Tests supported observables on single wires without parameters."""
obs = getattr(qml.ops, name)
assert qubit_device_1_wire.supports_observable(name)
@qml.qnode(qubit_device_1_wire)
def circuit():
qml.StatePrep(np.array(state), wires=[0])
return qml.expval(obs(wires=[0]))
assert np.allclose(circuit(), expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"name,state,expected_output,par",
[
("Identity", [zero, one, plus], [1, 1, 1], []),
("Hermitian", [zero, one, minus], [1, 1, 1], [I - Y]),
],
)
def test_supported_observable_single_wire_with_parameters_broadcasted(
self, qubit_device_1_wire, tol, name, state, expected_output, par
):
"""Tests supported observables on single wires with parameters."""
obs = getattr(qml.ops, name)
assert qubit_device_1_wire.supports_observable(name)
@qml.qnode(qubit_device_1_wire)
def circuit():
qml.StatePrep(np.array(state), wires=[0])
return qml.expval(obs(*par, wires=[0]))
assert np.allclose(circuit(), expected_output, atol=tol, rtol=0)
@pytest.mark.parametrize(
"name,state,expected_output,par",
[
(
"Hermitian",
[
[1 / math.sqrt(3), 0, 1 / math.sqrt(3), 1 / math.sqrt(3)],
[0, 0, 0, 1],
[1 / math.sqrt(2), 0, -1 / math.sqrt(2), 0],
],
[4 / 3, 0, 1],
([[1, 1j, 0, 1], [-1j, 1, 0, 0], [0, 0, 1, -1j], [1, 0, 1j, 0]],),
),
(
"Hermitian",
[[INVSQ2, 0, 0, INVSQ2], [0, INVSQ2, -INVSQ2, 0]],
[1, -1],
([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]],),
),
],
)
def test_supported_observable_two_wires_with_parameters_broadcasted(
self, qubit_device_2_wires, tol, name, state, expected_output, par
):
"""Tests supported observables on two wires with parameters."""
obs = getattr(qml.ops, name)
assert qubit_device_2_wires.supports_observable(name)
@qml.qnode(qubit_device_2_wires)
def circuit():
qml.StatePrep(np.array(state), wires=[0, 1])
return qml.expval(obs(*par, wires=[0, 1]))
assert np.allclose(circuit(), expected_output, atol=tol, rtol=0)
def test_multi_samples_return_correlated_results_broadcasted(self):
"""Tests if the samples returned by the sample function are correlated
correctly for correlated observables.
"""
dev = qml.device("default.qubit.legacy", wires=2, shots=1000)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit():
qml.Hadamard(0)
qml.RX(np.zeros(5), 0)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1))
outcomes = circuit()
assert np.array_equal(outcomes[0], outcomes[1])
@pytest.mark.parametrize("num_wires", [3, 4, 5, 6, 7, 8])
def test_multi_samples_correlated_results_more_wires_than_observable_broadcasted(
self, num_wires
):
"""Tests if the samples returned by the sample function are correlated
correctly for correlated observables on larger devices than the observables
"""
dev = qml.device("default.qubit.legacy", wires=num_wires, shots=1000)
@qml.qnode(dev, diff_method="parameter-shift")
def circuit():
qml.Hadamard(0)
qml.RX(np.zeros(5), 0)
qml.CNOT(wires=[0, 1])
return qml.sample(qml.PauliZ(0)), qml.sample(qml.PauliZ(1))
outcomes = circuit()
assert np.array_equal(outcomes[0], outcomes[1])
# pylint: disable=unused-argument
@pytest.mark.parametrize(
"theta,phi,varphi", [(THETA, PHI, VARPHI), (THETA, PHI[0], VARPHI), (THETA[0], PHI, VARPHI[1])]
)
class TestTensorExpvalBroadcasted:
"""Test tensor expectation values for broadcasted states"""
def test_paulix_pauliy_broadcasted(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliX and PauliY works correctly"""
dev = qml.device("default.qubit.legacy", wires=3)
dev.reset()
obs = qml.PauliX(0) @ qml.PauliY(2)
dev.apply(
[
qml.RX(theta, wires=[0]),
qml.RX(phi, wires=[1]),
qml.RX(varphi, wires=[2]),
qml.CNOT(wires=[0, 1]),
qml.CNOT(wires=[1, 2]),
],
obs.diagonalizing_gates(),
)
res = dev.expval(obs)
expected = np.sin(theta) * np.sin(phi) * np.sin(varphi)
assert np.allclose(res, expected, atol=tol, rtol=0)
def test_pauliz_identity_broadcasted(self, theta, phi, varphi, tol):
"""Test that a tensor product involving PauliZ and Identity works correctly"""
dev = qml.device("default.qubit.legacy", wires=3)
dev.reset()
obs = qml.PauliZ(0) @ qml.Identity(1) @ qml.PauliZ(2)
dev.apply(
[
qml.RX(theta, wires=[0]),
qml.RX(phi, wires=[1]),
qml.RX(varphi, wires=[2]),
qml.CNOT(wires=[0, 1]),
qml.CNOT(wires=[1, 2]),
],
obs.diagonalizing_gates(),
)
res = dev.expval(obs)