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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
use crate::components::{
measurement::{MeasurementBasis, MeasurementResult},
operator::{
CNOT, Hadamard, Identity, Matchgate, Operator, Pauli, PhaseS, PhaseSdag, PhaseShift,
PhaseT, PhaseTdag, RotateX, RotateY, RotateZ, SWAP, Toffoli, Unitary2,
},
};
use crate::errors::Error;
use num_complex::Complex;
use once_cell::sync::Lazy;
use rand::Rng;
use rayon::prelude::*;
use std::f64::consts::FRAC_1_SQRT_2;
use std::ops::{Add, Mul, Sub};
// Helper function to calculate the adjoint (conjugate transpose) of a 2x2 matrix
fn calculate_adjoint(matrix: &[[Complex<f64>; 2]; 2]) -> [[Complex<f64>; 2]; 2] {
[
[matrix[0][0].conj(), matrix[1][0].conj()],
[matrix[0][1].conj(), matrix[1][1].conj()],
]
}
/// Bell state vectors
pub(crate) mod bell_vectors {
use super::*;
pub static PHI_PLUS: Lazy<Vec<Complex<f64>>> = Lazy::new(|| {
let amplitude = Complex::new(FRAC_1_SQRT_2, 0.0);
vec![
amplitude,
Complex::new(0.0, 0.0),
Complex::new(0.0, 0.0),
amplitude,
]
});
pub static PHI_MINUS: Lazy<Vec<Complex<f64>>> = Lazy::new(|| {
let amplitude = Complex::new(FRAC_1_SQRT_2, 0.0);
vec![
amplitude,
Complex::new(0.0, 0.0),
Complex::new(0.0, 0.0),
-amplitude,
]
});
pub static PSI_PLUS: Lazy<Vec<Complex<f64>>> = Lazy::new(|| {
let amplitude = Complex::new(FRAC_1_SQRT_2, 0.0);
vec![
Complex::new(0.0, 0.0),
amplitude,
amplitude,
Complex::new(0.0, 0.0),
]
});
pub static PSI_MINUS: Lazy<Vec<Complex<f64>>> = Lazy::new(|| {
let amplitude = Complex::new(FRAC_1_SQRT_2, 0.0);
vec![
Complex::new(0.0, 0.0),
amplitude,
-amplitude,
Complex::new(0.0, 0.0),
]
});
}
#[derive(Clone)]
/// Represents the state of a quantum register.
///
/// The state is represented as a complex vector, where each element corresponds to a probability amplitude for a particular basis state.
/// The number of qubits in the system is also stored, which determines the length of the state vector (2^num_qubits).
pub struct State {
/// The state vector of the system, represented as a complex vector.
/// Each element of the vector represents a probability amplitude for a particular state.
pub state_vector: Vec<Complex<f64>>,
/// The number of qubits in the system.
pub num_qubits: usize,
}
impl State {
/// Creates a new state object with the given state vector.
///
/// # Arguments
///
/// * `state_vector` - The state vector of the system, represented as a complex vector.
///
/// # Returns
///
/// * `state` - A result containing the state object if successful, or an error if the state vector is invalid.
///
/// # Errors
///
/// * Returns an error if the state vector is empty.
/// * Returns an error if the state vector is not normalised (i.e., the square norm is not 1).
/// * Returns an error if the number of qubits is invalid (i.e., the length of the state vector is not a power of 2).
pub fn new(state_vector: Vec<Complex<f64>>) -> Result<Self, Error> {
let len = state_vector.len();
if len == 0 {
return Err(Error::InvalidNumberOfQubits(0));
}
// Check if the length of the state vector is a power of 2
if !len.is_power_of_two() {
// For error reporting, num_qubits can be approximated or a specific error used.
return Err(Error::InvalidNumberOfQubits(
(len as f64).log2().floor() as usize
));
}
// num_qubits can be safely calculated as len is non-zero and a power of two.
let num_qubits = len.trailing_zeros() as usize;
// Check if the square norm (probability) of the state vector is 1
let norm: f64 = state_vector.par_iter().map(|x| x.norm_sqr()).sum();
let tol: f64 = f64::EPSILON * len as f64; // Using len directly
if (norm - 1.0).abs() > tol {
return Err(Error::StateVectorNotNormalised);
}
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new Hartree-Fock state object with the given number of electrons and orbitals.
///
/// # Arguments
///
/// * `num_electrons` - The number of electrons in the system.
///
/// * `num_orbitals` - The number of orbitals in the system.
///
/// # Returns
///
/// * `state` - A result containing the state object if successful, or an error if the input is invalid.
pub fn new_hartree_fock(num_electrons: usize, num_orbitals: usize) -> Result<Self, Error> {
// Validate input (num_orbitals must be > 0 and >= num_electrons)
if num_orbitals == 0 || num_orbitals < num_electrons {
return Err(Error::InvalidInputValue(num_orbitals));
}
let n = ((1_usize.wrapping_shl(num_electrons as u32)) - 1)
.wrapping_shl((num_orbitals - num_electrons) as u32);
State::new_basis_n(num_orbitals, n)
}
/// Creates a new state object with the given number of qubits initialised to the |0...0> state.
///
/// # Arguments
///
/// * `num_qubits` - The number of qubits in the system.
///
/// # Returns
///
/// * `state` - A result containing the state object if successful, or an error if the number of qubits is invalid.
///
/// # Errors
///
/// * Returns an error if the number of qubits is 0.
pub fn new_zero(num_qubits: usize) -> Result<Self, Error> {
if num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(num_qubits));
}
let dim: usize = 1 << num_qubits;
let mut state_vector: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); dim];
state_vector[0] = Complex::new(1.0, 0.0); // |0...0> state has amplitude 1.0 at index 0
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new state object with the given number of qubits initialised to the `n`-th basis state.
///
/// # Arguments
///
/// * `num_qubits` - The number of qubits in the system.
/// * `n` - The index of the basis state to initialise to.
///
/// # Returns
///
/// * `state` - A result containing a new state object with the specified number of qubits, initialised to the `n`-th basis state or an error if `n` is out of bounds or if the number of qubits is invalid.
///
/// # Errors
///
/// * Returns an error if the number of qubits is 0 or if `n` is out of bounds for the given number of qubits.
pub fn new_basis_n(num_qubits: usize, n: usize) -> Result<Self, Error> {
let dim: usize = 1 << num_qubits;
if n >= dim {
return Err(Error::InvalidQubitIndex(n, num_qubits));
}
if num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(num_qubits));
}
let mut state_vector: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); dim];
state_vector[n] = Complex::new(1.0, 0.0); // |n> state has amplitude 1.0 at index n
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new plus state object with the given number of qubits initialised to the |+...+> state.
///
/// # Arguments
///
/// * `num_qubits` - The number of qubits in the system.
///
/// # Returns
///
/// * `state` - A result containing a new state object with the specified number of qubits, initialised to the |+...+> state or an error if the number of qubits is invalid.
///
/// # Errors
///
/// * Returns an error if the number of qubits is 0.
pub fn new_plus(num_qubits: usize) -> Result<Self, Error> {
if num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(num_qubits));
}
let dim: usize = 1 << num_qubits;
let amplitude = Complex::new(1.0 / (dim as f64).sqrt(), 0.0);
let state_vector: Vec<Complex<f64>> = vec![amplitude; dim];
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new minus state object with the given number of qubits initialised to the |-...-> state.
///
/// # Arguments
///
/// * `num_qubits` - The number of qubits in the system.
///
/// # Returns
///
/// * `state` - A result containing a new state object with the specified number of qubits, initialised to the |-...-> state or an error if the number of qubits is invalid.
///
/// # Errors
///
/// * Returns an error if the number of qubits is 0.
pub fn new_minus(num_qubits: usize) -> Result<Self, Error> {
if num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(num_qubits));
}
let dim: usize = 1 << num_qubits;
let amplitude: Complex<f64> = Complex::new(1.0 / (dim as f64).sqrt(), 0.0);
const PARALLEL_THRESHOLD: usize = 1 << 6; // Threshold for parallelization
let state_vector: Vec<Complex<f64>> = if dim > PARALLEL_THRESHOLD {
(0..dim)
.into_par_iter()
.map(|i| {
let num_ones = i.count_ones() as usize;
if num_ones % 2 == 0 {
amplitude
} else {
-amplitude
}
})
.collect()
} else {
let mut sv = Vec::with_capacity(dim);
for i in 0..dim {
let num_ones = i.count_ones() as usize;
sv.push(if num_ones % 2 == 0 {
amplitude
} else {
-amplitude
});
}
sv
};
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new Greenberger–Horne–Zeilinger state object with the given number of qubits initialised to the |GHZ> state.
/// The GHZ state is the maximally entangled state 1/sqrt(2) * (|0...0> + |1...1>).
///
/// # Arguments
///
/// * `num_qubits` - The number of qubits in the system.
///
/// # Returns
///
/// * `state` - A result containing a new state object with the specified number of qubits, initialised to the |GHZ> state or an error if the number of qubits is invalid.
///
/// # Errors
///
/// * Returns an error if the number of qubits is 0.
pub fn new_ghz(num_qubits: usize) -> Result<Self, Error> {
if num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(num_qubits));
}
let dim: usize = 1 << num_qubits;
let amplitude: Complex<f64> = Complex::new(FRAC_1_SQRT_2, 0.0);
let state_vector: Vec<Complex<f64>> = (0..dim)
.map(|i| {
if i == 0 || i == dim - 1 {
amplitude
} else {
Complex::new(0.0, 0.0)
}
})
.collect();
Ok(Self {
state_vector,
num_qubits,
})
}
/// Creates a new two-qubit Phi plus Bell state |Φ+⟩.
///
/// # Returns
///
/// * `Self` - A new instance of the two-qubit Bell state |Φ+⟩.
pub fn new_phi_plus() -> Self {
Self {
state_vector: bell_vectors::PHI_PLUS.clone(),
num_qubits: 2,
}
}
/// Creates a new two-qubit Phi minus Bell state |Φ-⟩.
///
/// # Returns
///
/// * `Self` - A new instance of the two-qubit Bell state |Φ-⟩.
pub fn new_phi_minus() -> Self {
Self {
state_vector: bell_vectors::PHI_MINUS.clone(),
num_qubits: 2,
}
}
/// Creates a new two-qubit Psi plus Bell state |Ψ+⟩.
///
/// # Returns
///
/// * `Self` - A new instance of the two-qubit Bell state |Ψ+⟩.
pub fn new_psi_plus() -> Self {
Self {
state_vector: bell_vectors::PSI_PLUS.clone(),
num_qubits: 2,
}
}
/// Creates a new two-qubit Psi minus Bell state |Ψ-⟩.
///
/// # Returns
///
/// * `Self` - A new instance of the two-qubit Bell state |Ψ-⟩.
pub fn new_psi_minus() -> Self {
Self {
state_vector: bell_vectors::PSI_MINUS.clone(),
num_qubits: 2,
}
}
/// Checks the phase-independent equality of two states
///
/// # Arguments
///
/// * `other` - The other state to compare with.
///
/// # Returns
///
/// * `true` if the states are equal (ignoring phase), `false` otherwise.
pub fn equals_without_phase(&self, other: &Self) -> bool {
if self.num_qubits != other.num_qubits {
return false;
}
// Safe to unwrap since number of qubits is the same
(self.inner_product(other).unwrap().norm() - 1.0).abs() < f32::EPSILON.into()
}
/// Returns the Hermitian conjugate (<self|) of the state.
///
/// # Returns
///
/// * `Self` - The Hermitian conjugate of the state.
pub fn conj(&self) -> Self {
let state_vector = self.state_vector.iter().map(|amp| amp.conj()).collect();
Self {
state_vector,
num_qubits: self.num_qubits,
}
}
/// Returns the probability of a basis state at index `n` in the state vector.
///
/// # Arguments
///
/// * `n` - The index of the basis state to get the probability for.
///
/// # Returns
///
/// * `probability` - The probability of the basis state at index `n`.
///
/// # Errors
///
/// * Returns an error if `n` is out of bounds for the state vector.
pub fn probability(&self, n: usize) -> Result<f64, Error> {
if n >= self.state_vector.len() {
return Err(Error::InvalidQubitIndex(n, self.num_qubits));
}
let amplitude: Complex<f64> = self.state_vector[n];
Ok(amplitude.norm_sqr())
}
/// Returns the number of qubits in the state vector.
///
/// # Returns
///
/// * `num_qubits` - The number of qubits in the state vector.
pub fn num_qubits(&self) -> usize {
self.num_qubits
}
/// Returns the amplitude of the basis state at index `n` in the state vector.
///
/// # Arguments
///
/// * `n` - The index of the basis state to get the amplitude for.
///
/// # Returns
///
/// * `amplitude` - The amplitude of the basis state at index `n`.
///
/// # Errors
///
/// * Returns an error if `n` is out of bounds for the state vector.
pub fn amplitude(&self, n: usize) -> Result<Complex<f64>, Error> {
if n >= self.state_vector.len() {
return Err(Error::InvalidQubitIndex(n, self.num_qubits));
}
Ok(self.state_vector[n])
}
/// Returns the Fubini-Study metric distance between two normalised quantum states.
/// Expressed as `D = arccos(<Self|Other>) = arccos(F^0.5)`.
///
/// # Arguments
///
/// * `other` - The other quantum state to compare against.
///
/// # Returns
///
/// * `distance` - The Fubini-Study metric distance between the two states.
///
/// # Errors
///
/// Returns an error if the inner product calculation fails (ie. if one of the state vectors is empty, or if the dimensions do not match)
/// Returns an error is the normalisation of either of the states fails (ie. if one of the states has zero norm).
pub fn fs_dist(&self, other: &Self) -> Result<f64, Error> {
// Normalise states
let normalised_self = self.normalise()?;
let normalised_other = other.normalise()?;
Ok(normalised_self
.inner_product(&normalised_other)?
.norm()
.acos())
}
/// Returns the Fubini-Study fidelity metric between two quantum states.
/// Expressed as `F = |<Self|Other>|^2 = cos^2(D)`.
///
/// # Arguments
///
/// * `other` - The other quantum state to compare against.
///
/// # Errors
///
/// Returns an error if the inner product calculation fails (ie. if one of the state vectors is empty, or if the dimensions do not match)
/// Returns an error if the normalisation of either of the states fails (ie. if one of the states has zero norm).
pub fn fs_fidelity(&self, other: &Self) -> Result<f64, Error> {
// Normalise states
let normalised_self = self.normalise()?;
let normalised_other = other.normalise()?;
Ok(normalised_self.inner_product(&normalised_other)?.norm_sqr())
}
// ***** MEASUREMENT FUNCTIONS *****
fn _measure_computational(
&self,
measured_qubits: &[usize],
) -> Result<MeasurementResult, Error> {
self.measure(MeasurementBasis::Computational, measured_qubits)
}
/// Measures the state vector in the specified basis and returns the measurement result.
///
/// # Arguments
///
/// * `basis` - The basis to measure in.
/// * `indices` - The indices of the qubits to measure. If `indices` is empty, all qubits are measured.
///
/// # Returns
///
/// * `result` - A result containing the measurement result if successful, or an error if the measurement fails.
///
/// # Errors
///
/// * Returns an error if the measurement fails.
/// * Returns an error if the number of qubits is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn measure(
&self,
basis: MeasurementBasis,
measured_qubits: &[usize],
) -> Result<MeasurementResult, Error> {
// If no indices are provided, measure all qubits
let all_qubits: Vec<usize> = if measured_qubits.is_empty() {
(0..self.num_qubits).collect()
} else {
Vec::new()
};
let actual_measured_qubits: &[usize] = if measured_qubits.is_empty() {
&all_qubits
} else {
measured_qubits
};
// Check for valid indices
let num_measured: usize = actual_measured_qubits.len();
if num_measured > self.num_qubits {
return Err(Error::InvalidNumberOfQubits(self.num_qubits));
}
for &index in actual_measured_qubits {
if index >= self.num_qubits {
return Err(Error::InvalidQubitIndex(index, self.num_qubits));
}
}
match basis {
MeasurementBasis::Computational => {
let num_outcomes: usize = 1 << num_measured;
// Calculate probabilities for each outcome (outcome as a single integer 0..num_outcomes-1)
let probabilities: Vec<f64> = self
.state_vector
.par_iter()
.enumerate()
.fold(
|| vec![0.0; num_outcomes], // Thread-local accumulator
|mut acc_probs, (idx, amplitude)| {
let mut outcome_val_for_this_state = 0;
// Extract the bits corresponding to measured_qubits to form the outcome value
for (bit_idx, &qubit_pos) in actual_measured_qubits.iter().enumerate() {
if (idx >> qubit_pos) & 1 != 0 {
outcome_val_for_this_state |= 1 << bit_idx;
}
}
// Ensure outcome_val_for_this_state is within bounds (0 to num_outcomes-1)
if outcome_val_for_this_state < num_outcomes {
acc_probs[outcome_val_for_this_state] += amplitude.norm_sqr();
}
acc_probs
},
)
.reduce(
|| vec![0.0; num_outcomes], // Initialiser for combining thread-local results
|mut total_probs, local_probs| {
for i in 0..num_outcomes {
total_probs[i] += local_probs[i];
}
total_probs
},
);
// Normalise probabilities
let total_probability: f64 = probabilities.iter().sum();
if total_probability < f64::EPSILON {
return Err(Error::UnknownError);
}
let normalised_probabilities: Vec<f64> = probabilities
.iter()
.map(|&prob| prob / total_probability)
.collect();
// Sample an outcome based on the probabilities
let mut rng = rand::rng();
let random_value: f64 = rng.random_range(0.0..1.0);
let mut cumulative_probability: f64 = 0.0;
let mut sampled_outcome_int: usize = 0;
// Sample loop
for (i, &prob) in normalised_probabilities.iter().enumerate() {
cumulative_probability += prob;
// Sample if random_value falls into the cumulative probability bin
if random_value < cumulative_probability {
sampled_outcome_int = i;
break; // Found the outcome, exit loop
}
}
// If, due to floating point issues, no outcome was selected, select the last one.
if random_value >= cumulative_probability && !normalised_probabilities.is_empty() {
sampled_outcome_int = normalised_probabilities.len() - 1;
}
// Collapse the state vector into a new vector
let mut collapsed_state_data: Vec<Complex<f64>> =
vec![Complex::new(0.0, 0.0); self.state_vector.len()];
let normalisation_sq: f64 = collapsed_state_data
.par_iter_mut()
.enumerate()
.zip(self.state_vector.par_iter()) // Zip with original state vector amplitudes
.map(|((idx, collapsed_amp_ref), &original_amp)| {
let mut current_outcome_val_for_this_state = 0;
// Extract the bits corresponding to measured_qubits
for (bit_idx, &qubit_pos) in actual_measured_qubits.iter().enumerate() {
if (idx >> qubit_pos) & 1 != 0 {
current_outcome_val_for_this_state |= 1 << bit_idx;
}
}
if current_outcome_val_for_this_state == sampled_outcome_int {
*collapsed_amp_ref = original_amp;
original_amp.norm_sqr() // Contribution to normalisation_sq
} else {
// *collapsed_amp_ref remains Complex::new(0.0, 0.0)
0.0 // No contribution
}
})
.sum(); // Sums up all contributions to get total normalisation_sq
// Renormalise the new collapsed state vector
if normalisation_sq > f64::EPSILON {
let norm_factor: f64 = normalisation_sq.sqrt();
for amplitude in collapsed_state_data.iter_mut() {
*amplitude /= norm_factor;
}
}
// Convert the sampled integer outcome to a Vec<u8>
let mut outcome_binary_vec: Vec<u8> = vec![0; num_measured];
for (i, qubit_pos) in outcome_binary_vec.iter_mut().enumerate() {
*qubit_pos = ((sampled_outcome_int >> i) & 1) as u8;
}
// Create the measurement result
Ok(MeasurementResult {
basis,
indices: actual_measured_qubits.to_vec(),
outcomes: outcome_binary_vec,
new_state: State::new(collapsed_state_data)?,
})
}
MeasurementBasis::X => {
// Apply Hadamard to measured qubits
let transformed_state = self.h_multi(actual_measured_qubits)?;
// Measure in computational basis
let computational_measurement_result =
transformed_state._measure_computational(actual_measured_qubits)?;
// Transform the new state back by applying Hadamard again
let final_state = computational_measurement_result
.new_state
.h_multi(actual_measured_qubits)?;
Ok(MeasurementResult {
basis: MeasurementBasis::X,
indices: computational_measurement_result.indices,
outcomes: computational_measurement_result.outcomes,
new_state: final_state,
})
}
MeasurementBasis::Y => {
// Apply Sdg then H to measured qubits
let state_after_sdag = self.s_dag_multi(actual_measured_qubits)?;
let transformed_state = state_after_sdag.h_multi(actual_measured_qubits)?;
// Measure in computational basis
let computational_measurement_result =
transformed_state._measure_computational(actual_measured_qubits)?;
// Transform the new state back by applying H then S
let state_after_h = computational_measurement_result
.new_state
.h_multi(actual_measured_qubits)?;
let final_state = state_after_h.s_multi(actual_measured_qubits)?;
Ok(MeasurementResult {
basis: MeasurementBasis::Y,
indices: computational_measurement_result.indices,
outcomes: computational_measurement_result.outcomes,
new_state: final_state,
})
}
MeasurementBasis::Custom(u_matrix) => {
// Apply the custom unitary U to measured qubits
let transformed_state = self.unitary_multi(actual_measured_qubits, u_matrix)?;
// Measure in computational basis
let computational_measurement_result =
transformed_state._measure_computational(actual_measured_qubits)?;
// Calculate U_dagger (adjoint of u_matrix)
let u_dagger_matrix = calculate_adjoint(&u_matrix);
// Transform the new state back by applying U_dagger
let final_state = computational_measurement_result
.new_state
.unitary_multi(actual_measured_qubits, u_dagger_matrix)?;
Ok(MeasurementResult {
basis: MeasurementBasis::Custom(u_matrix),
indices: computational_measurement_result.indices,
outcomes: computational_measurement_result.outcomes,
new_state: final_state,
})
}
}
}
/// Measures the state vector `n` times in the specified basis and returns the measurement results.
///
/// # Arguments
///
/// * `basis` - The basis to measure in.
/// * `indices` - The indices of the qubits to measure. If `indices` is empty, all qubits are measured.
/// * `n` - The number of measurements to perform.
///
/// # Returns
///
/// * `results` - A result containing a vector of measurement results if successful, or an error if the measurement fails.
///
/// # Errors
///
/// * Returns an error if the measurement fails.
/// * Returns an error if the number of qubits is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if `n` is 0.
pub fn measure_n(
&self,
basis: MeasurementBasis,
measured_qubits: &[usize],
n: usize,
) -> Result<Vec<MeasurementResult>, Error> {
if n == 0 {
return Err(Error::InvalidNumberOfMeasurements(0));
}
// If no indices are provided, measure all qubits
let all_indices: Vec<usize> = (0..self.num_qubits).collect();
let actual_measured_qubits: &[usize] = if measured_qubits.is_empty() {
&all_indices
} else {
measured_qubits
};
// Check for valid indices
let num_measured: usize = actual_measured_qubits.len();
if num_measured > self.num_qubits {
return Err(Error::InvalidNumberOfQubits(self.num_qubits));
}
for &index in actual_measured_qubits {
if index >= self.num_qubits {
return Err(Error::InvalidQubitIndex(index, self.num_qubits));
}
}
let results: Vec<MeasurementResult> = (0..n)
.into_par_iter()
.map(|_| self.measure(basis, actual_measured_qubits))
.collect::<Result<Vec<MeasurementResult>, Error>>()?;
Ok(results)
}
/// Performs a tensor product of two state vectors and returns the resulting state.
/// Uses parallel computation if the resulting dimension is large enough.
///
/// # Arguments
///
/// * `other` - The other state vector to perform the tensor product with.
///
/// # Returns
///
/// * `result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if either state vector is empty.
/// * Returns an error if either state vector has an invalid number of qubits.
pub fn tensor_product(&self, other: &Self) -> Result<Self, Error> {
if self.num_qubits == 0 || other.num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(0));
}
let new_num_qubits: usize = self.num_qubits + other.num_qubits;
let new_dim: usize = 1 << new_num_qubits;
let other_dim: usize = 1 << other.num_qubits; // Cache dimension of other state
// Threshold for using parallel computation
const PARALLEL_THRESHOLD: usize = 1 << 6; // Parallelise when dimension is larger than 64
let new_state_vector: Vec<Complex<f64>> = if new_dim > PARALLEL_THRESHOLD {
// Parallel calculation for large states
(0..new_dim)
.into_par_iter()
.map(|new_index| {
let i: usize = new_index >> other.num_qubits; // Index for self.state_vector
let j: usize = new_index & (other_dim - 1); // Index for other.state_vector
self.state_vector[i] * other.state_vector[j]
})
.collect()
} else {
// Sequential calculation for smaller states
let mut temp_state_vector: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); new_dim];
for i in 0..self.state_vector.len() {
for j in 0..other.state_vector.len() {
temp_state_vector[(i * other_dim) + j] =
self.state_vector[i] * other.state_vector[j];
}
}
temp_state_vector
};
Self::new(new_state_vector) // For normalisation check
}
/// Performs a tensor product of two state vectors without checking for validity.
#[allow(dead_code)]
pub(crate) fn tensor_product_unchecked(&self, other: &Self) -> Self {
let new_num_qubits: usize = self.num_qubits + other.num_qubits;
let new_dim: usize = 1 << new_num_qubits;
let other_dim: usize = 1 << other.num_qubits; // Cache dimension of other state
// Threshold for using parallel computation
const PARALLEL_THRESHOLD: usize = 1 << 6; // Parallelise when dimension is larger than 64
let new_state_vector: Vec<Complex<f64>> = if new_dim > PARALLEL_THRESHOLD {
// Parallel calculation for large states
(0..new_dim)
.into_par_iter()
.map(|new_index| {
let i: usize = new_index >> other.num_qubits; // Index for self.state_vector
let j: usize = new_index & (other_dim - 1); // Index for other.state_vector
self.state_vector[i] * other.state_vector[j]
})
.collect()
} else {
// Sequential calculation for smaller states
let mut temp_state_vector: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); new_dim];
for i in 0..self.state_vector.len() {
for j in 0..other.state_vector.len() {
temp_state_vector[(i * other_dim) + j] =
self.state_vector[i] * other.state_vector[j];
}
}
temp_state_vector
};
Self {
state_vector: new_state_vector,
num_qubits: new_num_qubits,
}
}
/// Performs an inner product of two state vectors (<Self | Other>) and returns the resulting complex number.
///
/// # Arguments
///
/// * `other` - The other state vector to perform the inner product with.
///
/// # Returns
///
/// * `result` - A result containing the inner product as a complex number if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if either state vector is empty.
/// * Returns an error if the state vectors have different dimensions.
pub fn inner_product(&self, other: &Self) -> Result<Complex<f64>, Error> {
if self.num_qubits == 0 || other.num_qubits == 0 {
return Err(Error::InvalidNumberOfQubits(0));
}
if self.state_vector.len() != other.state_vector.len() {
return Err(Error::InvalidNumberOfQubits(self.num_qubits));
}
const PARALLEL_THRESHOLD: usize = 1 << 6; // Threshold for parallelisation
let len = self.state_vector.len();
let inner_product: Complex<f64> = if len > PARALLEL_THRESHOLD {
self.state_vector
.par_iter()
.zip(other.state_vector.par_iter())
.map(|(a, b)| a.conj() * b)
.sum()
} else {
self.state_vector
.iter()
.zip(other.state_vector.iter())
.map(|(a, b)| a.conj() * b)
.sum()
};
Ok(inner_product)
}
/// Normalises the state vector and returns the state.
///
/// # Returns
///
/// * `Result<State, Error>` - The resulting state after normalisation, or an error if the operation fails.
pub fn normalise(&self) -> Result<Self, Error> {
let norm = self
.state_vector
.iter()
.map(|x| x.norm_sqr())
.sum::<f64>()
.sqrt();
if norm == 0.0 {
return Err(Error::ZeroNorm);
}
if norm == 1.0 {
return Ok(self.clone());
}
let new_state_vector: Vec<Complex<f64>> =
self.state_vector.iter().map(|x| x / norm).collect();
Ok(Self {
state_vector: new_state_vector,
num_qubits: self.num_qubits,
})
}
// ***** OPERATION FUNCTIONS *****
/// Applies a unitary operation to the state vector.
///
/// # Arguments
///
/// * `unitary` - The unitary operation to apply, represented as an `Operator` trait object.
///
/// * target_qubits - The indices of the qubits to apply the unitary operation to.
///
/// * control_qubits - The indices of the control qubits for the unitary operation, if any.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the unitary operation is invalid.
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn operate(
&self,
unitary: impl Operator,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
// Check for valid indices
let num_target: usize = target_qubits.len();
let num_control: usize = control_qubits.len();
if unitary.base_qubits() != (num_target + num_control) {
return Err(Error::InvalidNumberOfQubits(unitary.base_qubits()));
}
if num_target > self.num_qubits {
return Err(Error::InvalidNumberOfQubits(self.num_qubits));
}
for &index in target_qubits {
if index >= self.num_qubits {
return Err(Error::InvalidQubitIndex(index, self.num_qubits));
}
}
for &index in control_qubits {
if index >= self.num_qubits {
return Err(Error::InvalidQubitIndex(index, self.num_qubits));
}
}
// Apply the unitary operation to the state vector and return the new state
unitary.apply(self, target_qubits, control_qubits)
}
// -- SINGLE-QUBIT GATES --
/// Applies the Hadamard gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Hadamard gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn h(&self, index: usize) -> Result<Self, Error> {
Hadamard {}.apply(self, &[index], &[])
}
/// Applies the Hadamard gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Hadamard gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// * # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn h_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let h: Hadamard = Hadamard {};
for &qubit in qubits {
new_state = h.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Hadamard gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Hadamard gate to.
///
/// * `control_qubits` - The indices of the control qubits for the controlled Hadamard gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// * # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
///
/// * Returns an error if the control qubits and target qubits overlap.
pub fn ch_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let h: Hadamard = Hadamard {};
for &qubit in target_qubits {
new_state = h.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Pauli-X (NOT) gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Pauli-X gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn x(&self, index: usize) -> Result<Self, Error> {
Pauli::X.apply(self, &[index], &[])
}
/// Applies the Pauli-X (NOT) gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Pauli-X gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn x_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let x: Pauli = Pauli::X;
for &qubit in qubits {
new_state = x.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Pauli-X (NOT) gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Pauli-X gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Pauli-X gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cx_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let x: Pauli = Pauli::X;
for &qubit in target_qubits {
new_state = x.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Pauli-Y gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Pauli-Y gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn y(&self, index: usize) -> Result<Self, Error> {
Pauli::Y.apply(self, &[index], &[])
}
/// Applies the Pauli-Y gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Pauli-Y gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn y_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let y: Pauli = Pauli::Y;
for &qubit in qubits {
new_state = y.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Pauli-Y gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Pauli-Y gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Pauli-Y gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cy_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let y: Pauli = Pauli::Y;
for &qubit in target_qubits {
new_state = y.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Pauli-Z gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Pauli-Z gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn z(&self, index: usize) -> Result<Self, Error> {
Pauli::Z.apply(self, &[index], &[])
}
/// Applies the Pauli-Z gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Pauli-Z gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn z_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let z: Pauli = Pauli::Z;
for &qubit in qubits {
new_state = z.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Pauli-Z gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Pauli-Z gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Pauli-Z gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cz_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let z: Pauli = Pauli::Z;
for &qubit in target_qubits {
new_state = z.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Identity gate to the state vector.
///
/// # Arguments
///
/// * `qubit` - The index of the qubit to apply the Identity gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn i(&self, qubit: usize) -> Result<Self, Error> {
Identity {}.apply(self, &[qubit], &[])
}
/// Applies the Identity gate to the state vector for multiple qubits in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Identity gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn i_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let i: Identity = Identity {};
for &qubit in qubits {
new_state = i.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Identity gate to the state vector for multiple qubits in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Identity gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Identity gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn ci_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let i: Identity = Identity {};
for &qubit in target_qubits {
new_state = i.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Phase S gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Phase S gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn s(&self, index: usize) -> Result<Self, Error> {
PhaseS {}.apply(self, &[index], &[])
}
/// Applies the Phase S gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Phase S gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn s_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let s_gate: PhaseS = PhaseS {};
for &qubit in qubits {
new_state = s_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Phase S gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Phase S gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Phase S gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cs_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let s_gate: PhaseS = PhaseS {};
for &qubit in target_qubits {
new_state = s_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Phase T gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Phase T gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn t(&self, index: usize) -> Result<Self, Error> {
PhaseT {}.apply(self, &[index], &[])
}
/// Applies the Phase T gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Phase T gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn t_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let t_gate: PhaseT = PhaseT {};
for &qubit in qubits {
new_state = t_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Phase T gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Phase T gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Phase T gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn ct_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let t_gate: PhaseT = PhaseT {};
for &qubit in target_qubits {
new_state = t_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Phase S dagger gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Phase S dagger gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn s_dag(&self, index: usize) -> Result<Self, Error> {
PhaseSdag {}.apply(self, &[index], &[])
}
/// Applies the Phase S dagger gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Phase S dagger gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn s_dag_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let sdag_gate: PhaseSdag = PhaseSdag {};
for &qubit in qubits {
new_state = sdag_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Phase S dagger gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Phase S dagger gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Phase S dagger gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cs_dag_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let sdag_gate: PhaseSdag = PhaseSdag {};
for &qubit in target_qubits {
new_state = sdag_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Phase T dagger gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Phase T dagger gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn t_dag(&self, index: usize) -> Result<Self, Error> {
PhaseTdag {}.apply(self, &[index], &[])
}
/// Applies the Phase T dagger gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Phase T dagger gate to.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn t_dag_multi(&self, qubits: &[usize]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let tdag_gate: PhaseTdag = PhaseTdag {};
for &qubit in qubits {
new_state = tdag_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Phase T dagger gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Phase T dagger gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Phase T dagger gate.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn ct_dag_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let tdag_gate: PhaseTdag = PhaseTdag {};
for &qubit in target_qubits {
new_state = tdag_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Phase Shift gate with the specified angle to the given qubit.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Phase Shift gate to.
/// * `angle` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn p(&self, index: usize, angle: f64) -> Result<Self, Error> {
PhaseShift::new(angle).apply(self, &[index], &[])
}
/// Applies the Phase Shift gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Phase Shift gate to.
///
/// * `angle` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn p_multi(&self, qubits: &[usize], angle: f64) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let phase_shift_gate: PhaseShift = PhaseShift::new(angle);
for &qubit in qubits {
new_state = phase_shift_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Phase Shift gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Phase Shift gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled Phase Shift gate.
/// * `angle` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cp_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let phase_shift_gate: PhaseShift = PhaseShift::new(angle);
for &qubit in target_qubits {
new_state = phase_shift_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the RotateX gate with the specified angle to the given qubit.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the RotateX gate to.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn rx(&self, index: usize, angle: f64) -> Result<Self, Error> {
RotateX::new(angle).apply(self, &[index], &[])
}
/// Applies the RotateX gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the RotateX gate to.
///
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn rx_multi(&self, qubits: &[usize], angle: f64) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_x_gate: RotateX = RotateX::new(angle);
for &qubit in qubits {
new_state = rotate_x_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled RotateX gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled RotateX gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled RotateX gate.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn crx_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_x_gate: RotateX = RotateX::new(angle);
for &qubit in target_qubits {
new_state = rotate_x_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the RotateY gate with the specified angle to the given qubit.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the RotateY gate to.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn ry(&self, index: usize, angle: f64) -> Result<Self, Error> {
RotateY::new(angle).apply(self, &[index], &[])
}
/// Applies the RotateY gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the RotateY gate to.
///
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn ry_multi(&self, qubits: &[usize], angle: f64) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_y_gate: RotateY = RotateY::new(angle);
for &qubit in qubits {
new_state = rotate_y_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled RotateY gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled RotateY gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled RotateY gate.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cry_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_y_gate: RotateY = RotateY::new(angle);
for &qubit in target_qubits {
new_state = rotate_y_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the RotateZ gate with the specified angle to the given qubit.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the RotateZ gate to.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn rz(&self, index: usize, angle: f64) -> Result<Self, Error> {
RotateZ::new(angle).apply(self, &[index], &[])
}
/// Applies the RotateZ gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the RotateZ gate to.
///
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn rz_multi(&self, qubits: &[usize], angle: f64) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_z_gate: RotateZ = RotateZ::new(angle);
for &qubit in qubits {
new_state = rotate_z_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled RotateZ gate with the specified angle to the given qubits in order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled RotateZ gate to.
/// * `control_qubits` - The indices of the control qubits for the controlled RotateZ gate.
/// * `angle` - The rotation angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
/// * Returns an error if the indices are out of bounds for the state vector.
/// * Returns an error if the control qubits and target qubits overlap.
pub fn crz_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let rotate_z_gate: RotateZ = RotateZ::new(angle);
for &qubit in target_qubits {
new_state = rotate_z_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the unitary gate to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the unitary gate to.
///
/// * `unitary` - The unitary matrix to apply.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
///
/// * Returns an error if the unitary matrix is not unitary.
pub fn unitary(&self, index: usize, unitary: [[Complex<f64>; 2]; 2]) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::new(unitary)?;
new_state = unitary_gate.apply(&new_state, &[index], &[])?;
Ok(new_state)
}
/// Applies the unitary gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the unitary gate to.
///
/// * `unitary` - The unitary matrix to apply.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
///
/// * Returns an error if the unitary matrix is not unitary.
pub fn unitary_multi(
&self,
qubits: &[usize],
unitary: [[Complex<f64>; 2]; 2],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::new(unitary)?;
for &qubit in qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled unitary gate to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled unitary gate to.
///
/// * `control_qubits` - The indices of the control qubits for the controlled unitary gate.
///
/// * `unitary` - The unitary matrix to apply.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
///
/// * Returns an error if the control qubits and target qubits overlap.
///
/// * Returns an error if the unitary matrix is not unitary.
pub fn cunitary_multi(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
unitary: [[Complex<f64>; 2]; 2],
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::new(unitary)?;
for &qubit in target_qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubit in the state vector.
///
/// # Arguments
///
/// * `index` - The index of the qubit to apply the Unitary gate to.
///
/// * `angle` - The rotation angle in radians.
///
/// * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the index is out of bounds for the state vector.
pub fn ry_phase(&self, index: usize, angle: f64, phase: f64) -> Result<Self, Error> {
Unitary2::from_ry_phase(angle, phase).apply(self, &[index], &[])
}
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the Unitary gate to.
///
/// * `angle` - The rotation angle in radians.
///
/// * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn ry_phase_multi(&self, qubits: &[usize], angle: f64, phase: f64) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::from_ry_phase(angle, phase);
for &qubit in qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
///
/// # Arguments
///
/// * `target_qubits` - The indices of the target qubits to apply the controlled Unitary gate to.
///
/// * `control_qubits` - The indices of the control qubits for the controlled Unitary gate.
///
/// * `angle` - The rotation angle in radians.
///
/// * * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
///
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cry_phase_gates(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
phase: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::from_ry_phase(angle, phase);
for &qubit in target_qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubit in the state vector.
/// This is the adjoint of the ry_phase operation.
///
/// # Arguments
///
/// * `qubit` - The index of the qubit to apply the adjoint operation to.
///
/// * `angle` - The rotation angle in radians.
///
/// * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the target qubit is out of bounds for the state vector
pub fn ry_phase_dag(&self, qubit: usize, angle: f64, phase: f64) -> Result<Self, Error> {
Unitary2::from_ry_phase_dagger(angle, phase).apply(self, &[qubit], &[])
}
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
/// This is the adjoint of the ry_phase operation.
///
/// # Arguments
///
/// * `qubits` - The indices of the qubits to apply the adjoint ry_phase operation to.
///
/// * `angle` - The rotation angle in radians.
///
/// * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
pub fn ry_phase_dag_multi(
&self,
qubits: &[usize],
angle: f64,
phase: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::from_ry_phase_dagger(angle, phase);
for &qubit in qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], &[])?;
}
Ok(new_state)
}
/// Applies the controlled Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
/// This is the controlled adjoint of the ry_phase operation.
///
/// # Arguments
///
/// * `target_qubits` - The index of the target qubit.
///
/// * `control_qubits` - The indices of the control qubits.
///
/// * `angle` - The rotation angle in radians.
///
/// * `phase` - The phase shift angle in radians.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if the number of qubits provided is invalid.
///
/// * Returns an error if the indices are out of bounds for the state vector.
///
/// * Returns an error if the control qubits and target qubits overlap.
pub fn cry_phase_dag_gates(
&self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
phase: f64,
) -> Result<Self, Error> {
let mut new_state: State = self.clone();
let unitary_gate: Unitary2 = Unitary2::from_ry_phase_dagger(angle, phase);
for &qubit in target_qubits {
new_state = unitary_gate.apply(&new_state, &[qubit], control_qubits)?;
}
Ok(new_state)
}
// -- MULTI-QUBIT GATES --
/// Applies the CNOT (Controlled-NOT) gate to the state vector.
///
/// # Arguments
///
/// * `control` - The index of the control qubit.
/// * `target` - The index of the target qubit.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
pub fn cnot(&self, control: usize, target: usize) -> Result<Self, Error> {
CNOT {}.apply(self, &[target], &[control])
}
/// Applies the SWAP gate to the state vector.
///
/// # Arguments
///
/// * `qubit1` - The index of the first qubit to swap.
/// * `qubit2` - The index of the second qubit to swap.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
pub fn swap(&self, qubit1: usize, qubit2: usize) -> Result<Self, Error> {
SWAP {}.apply(self, &[qubit1, qubit2], &[])
}
/// Applies the controlled SWAP gate to the state vector.
///
/// # Arguments
///
/// * `target1` - The index of the first target qubit to swap.
/// * `target2` - The index of the second target qubit to swap.
/// * `controls` - The indices of the control qubits.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
/// * Returns an error if target or control qubits overlap.
pub fn cswap(&self, target1: usize, target2: usize, controls: &[usize]) -> Result<Self, Error> {
SWAP {}.apply(self, &[target1, target2], controls)
}
/// Applies the Matchgate to the state vector
///
/// # Arguments
///
/// * `target` - The index of the first target qubit. The second target qubit is automatically determined to be the next qubit.
/// * `theta` - The rotation angle in radians
/// * `phi1` - The first phase angle in radians
/// * `phi2` - The second phase angle in radians
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
/// * Returns an error if target or control qubits overlap.
pub fn matchgate(
&self,
target: usize,
theta: f64,
phi1: f64,
phi2: f64,
) -> Result<State, Error> {
Matchgate { theta, phi1, phi2 }.apply(self, &[target], &[])
}
/// Applies the controlled Matchgate to the state vector
///
/// # Arguments
///
/// * `target` - The index of the first target qubit. The second target qubit is automatically determined to be the next qubit.
/// * `theta` - The rotation angle in radians
/// * `phi1` - The first phase angle in radians
/// * `phi2` - The second phase angle in radians
/// * `controls` - The indices of the control qubits
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
/// * Returns an error if target or control qubits overlap.
pub fn cmatchgate(
&self,
target: usize,
theta: f64,
phi1: f64,
phi2: f64,
controls: &[usize],
) -> Result<State, Error> {
Matchgate { theta, phi1, phi2 }.apply(self, &[target], controls)
}
/// Applies the Toffoli (Controlled-Controlled-NOT) gate to the state vector.
///
/// # Arguments
///
/// * `control1` - The index of the first control qubit.
/// * `control2` - The index of the second control qubit.
/// * `target` - The index of the target qubit.
///
/// # Returns
///
/// * `Result` - A result containing the new state object if successful, or an error if the operation fails.
///
/// # Errors
///
/// * Returns an error if any index is out of bounds for the state vector.
pub fn toffoli(&self, control1: usize, control2: usize, target: usize) -> Result<Self, Error> {
Toffoli {}.apply(self, &[target], &[control1, control2])
}
}
impl PartialEq for State {
fn eq(&self, other: &Self) -> bool {
// Check if the number of qubits is the same
if self.num_qubits != other.num_qubits {
return false;
}
// Check if the state vectors have the same length (should be redundant with num_qubits check)
if self.state_vector.len() != other.state_vector.len() {
return false;
}
// Check if each element in the state vectors is approximately equal within epsilon
for (a, b) in self.state_vector.iter().zip(other.state_vector.iter()) {
let real_diff = (a.re - b.re).abs();
let imag_diff = (a.im - b.im).abs();
if real_diff > f32::EPSILON.into() || imag_diff > f32::EPSILON.into() {
return false;
}
}
true
}
}
/// A trait to enable chainable operations on Result<State, Error>
pub trait ChainableState {
// -- SINGLE QUBIT GATES --
/// Applies the Hadamard gate to the specified qubit in the state vector.
fn h(self, index: usize) -> Result<State, Error>;
/// Applies the Hadamard gate to the specified qubits in the state vector in the given order.
fn h_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Hadamard gate to the specified qubits in the state vector in the given order.
fn ch_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Pauli-X (NOT) gate to the specified qubit in the state vector.
fn x(self, index: usize) -> Result<State, Error>;
/// Applies the Pauli-X (NOT) gate to the specified qubits in the state vector in the given order.
fn x_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Pauli-X (NOT) gate to the specified qubits in the state vector in the given order.
fn cx_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Pauli-Y gate to the specified qubit in the state vector.
fn y(self, index: usize) -> Result<State, Error>;
/// Applies the Pauli-Y gate to the specified qubits in the state vector in the given order.
fn y_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Pauli-Y gate to the specified qubits in the state vector in the given order.
fn cy_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Pauli-Z gate to the specified qubit in the state vector.
fn z(self, index: usize) -> Result<State, Error>;
/// Applies the Pauli-Z gate to the specified qubits in the state vector in the given order.
fn z_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Pauli-Z gate to the specified qubits in the state vector in the given order.
fn cz_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Identity gate to the state vector.
fn i(self, qubit: usize) -> Result<State, Error>;
/// Applies the Identity gate to the state vector for multiple qubits in the given order.
fn i_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Identity gate to the state vector for multiple qubits in the given order.
fn ci_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Phase S gate to the specified qubit in the state vector.
fn s(self, index: usize) -> Result<State, Error>;
/// Applies the Phase S gate to the specified qubits in the state vector in the given order.
fn s_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Phase S gate to the specified qubits in the state vector in the given order.
fn cs_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Phase T gate to the specified qubit in the state vector.
fn t(self, index: usize) -> Result<State, Error>;
/// Applies the Phase T gate to the specified qubits in the state vector in the given order.
fn t_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Phase T gate to the specified qubits in the state vector in the given order.
fn ct_multi(self, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
/// Applies the Phase S dagger gate to the specified qubit in the state vector.
fn s_dag(self, index: usize) -> Result<State, Error>;
/// Applies the Phase S dagger gate to the specified qubits in the state vector in the given order.
fn s_dag_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Phase S dagger gate to the specified qubits in the state vector in the given order.
fn cs_dag_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<State, Error>;
/// Applies the Phase T dagger gate to the specified qubit in the state vector.
fn t_dag(self, index: usize) -> Result<State, Error>;
/// Applies the Phase T dagger gate to the specified qubits in the state vector in the given order.
fn t_dag_multi(self, qubits: &[usize]) -> Result<State, Error>;
/// Applies the controlled Phase T dagger gate to the specified qubits in the state vector in the given order.
fn ct_dag_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<State, Error>;
/// Applies the Phase Shift gate with the specified angle to the given qubit.
fn p(self, index: usize, angle: f64) -> Result<State, Error>;
/// Applies the Phase Shift gate with the specified angle to the given qubits in order.
fn p_multi(self, qubits: &[usize], angle: f64) -> Result<State, Error>;
/// Applies the controlled Phase Shift gate with the specified angle to the given qubits in order.
fn cp_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<State, Error>;
/// Applies the RotateX gate with the specified angle to the given qubit.
fn rx(self, index: usize, angle: f64) -> Result<State, Error>;
/// Applies the RotateX gate with the specified angle to the given qubits in order.
fn rx_multi(self, qubits: &[usize], angle: f64) -> Result<State, Error>;
/// Applies the controlled RotateX gate with the specified angle to the given qubits in order.
fn crx_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<State, Error>;
/// Applies the RotateY gate with the specified angle to the given qubit.
fn ry(self, index: usize, angle: f64) -> Result<State, Error>;
/// Applies the RotateY gate with the specified angle to the given qubits in order.
fn ry_multi(self, qubits: &[usize], angle: f64) -> Result<State, Error>;
/// Applies the controlled RotateY gate with the specified angle to the given qubits in order.
fn cry_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<State, Error>;
/// Applies the RotateZ gate with the specified angle to the given qubit.
fn rz(self, index: usize, angle: f64) -> Result<State, Error>;
/// Applies the RotateZ gate with the specified angle to the given qubits in order.
fn rz_multi(self, qubits: &[usize], angle: f64) -> Result<State, Error>;
/// Applies the controlled RotateZ gate with the specified angle to the given qubits in order.
fn crz_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
) -> Result<State, Error>;
/// Applies the unitary gate to the specified qubit in the state vector.
fn unitary(self, index: usize, unitary: [[Complex<f64>; 2]; 2]) -> Result<State, Error>;
/// Applies the unitary gate to the specified qubits in the state vector in the given order.
fn unitary_multi(
self,
qubits: &[usize],
unitary: [[Complex<f64>; 2]; 2],
) -> Result<State, Error>;
/// Applies the controlled unitary gate to the specified qubits in the state vector in the given order.
fn cunitary_multi(
self,
target_qubits: &[usize],
control_qubits: &[usize],
unitary: [[Complex<f64>; 2]; 2],
) -> Result<State, Error>;
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubit in the state vector.
fn ry_phase(self, index: usize, angle: f64, phase: f64) -> Result<State, Error>;
/// Applies the Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
fn ry_phase_multi(self, qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
/// Applies the controlled Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
fn cry_phase_gates(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
phase: f64,
) -> Result<State, Error>;
/// Applies the adjoint of the Unitary (constructed from rotation angle and phase shift) to the specified qubit in the state vector.
fn ry_phase_dag(self, index: usize, angle: f64, phase: f64) -> Result<State, Error>;
/// Applies the adjoint of the Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
fn ry_phase_dag_multi(self, qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
/// Applies the controlled adjoint of the Unitary (constructed from rotation angle and phase shift) to the specified qubits in the state vector in the given order.
fn cry_phase_dag_gates(
self,
target_qubits: &[usize],
control_qubits: &[usize],
angle: f64,
phase: f64,
) -> Result<State, Error>;
// -- MULTI-QUBIT GATES --
/// Applies the CNOT (Controlled-NOT) gate to the state vector.
fn cnot(self, control: usize, target: usize) -> Result<State, Error>;
/// Applies the SWAP gate to the state vector.
fn swap(self, qubit1: usize, qubit2: usize) -> Result<State, Error>;
/// Applies the controlled SWAP gate to the state vector.
fn cswap(self, target1: usize, target2: usize, controls: &[usize]) -> Result<State, Error>;
/// Applies the Toffoli (Controlled-Controlled-NOT) gate to the state vector.
fn toffoli(self, control1: usize, control2: usize, target: usize) -> Result<State, Error>;
/// Applies the Matchgate to the state vector.
fn matchgate(self, target: usize, theta: f64, phi1: f64, phi2: f64) -> Result<State, Error>;
/// Applies the controlled Matchgate to the state vector.
fn cmatchgate(
self,
target: usize,
theta: f64,
phi1: f64,
phi2: f64,
controls: &[usize],
) -> Result<State, Error>;
/// Applies a unitary operation to the state vector.
fn operate(
self,
unitary: impl Operator,
target_qubits: &[usize],
control_qubits: &[usize],
) -> Result<State, Error>;
// -- MEASUREMENT --
/// Measures the state vector in the specified basis and returns the measurement result.
fn measure(
self,
basis: MeasurementBasis,
measured_qubits: &[usize],
) -> Result<MeasurementResult, Error>;
/// Measures the state vector `n` times in the specified basis and returns the measurement results.
fn measure_n(
self,
basis: MeasurementBasis,
measured_qubits: &[usize],
n: usize,
) -> Result<Vec<MeasurementResult>, Error>;
}
macro_rules! impl_chainable_state {
($($method:ident($($arg:ident: $arg_type:ty),*) -> $return_type:ty);* $(;)?) => {
impl ChainableState for Result<State, Error> {
$(
fn $method(self, $($arg: $arg_type),*) -> $return_type {
self.and_then(|state| state.$method($($arg),*))
}
)*
}
};
}
impl_chainable_state! {
// -- SINGLE QUBIT GATES --
h(index: usize) -> Result<State, Error>;
h_multi(qubits: &[usize]) -> Result<State, Error>;
ch_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
x(index: usize) -> Result<State, Error>;
x_multi(qubits: &[usize]) -> Result<State, Error>;
cx_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
y(index: usize) -> Result<State, Error>;
y_multi(qubits: &[usize]) -> Result<State, Error>;
cy_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
z(index: usize) -> Result<State, Error>;
z_multi(qubits: &[usize]) -> Result<State, Error>;
cz_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
i(qubit: usize) -> Result<State, Error>;
i_multi(qubits: &[usize]) -> Result<State, Error>;
ci_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
s(index: usize) -> Result<State, Error>;
s_multi(qubits: &[usize]) -> Result<State, Error>;
cs_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
t(index: usize) -> Result<State, Error>;
t_multi(qubits: &[usize]) -> Result<State, Error>;
ct_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
s_dag(index: usize) -> Result<State, Error>;
s_dag_multi(qubits: &[usize]) -> Result<State, Error>;
cs_dag_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
t_dag(index: usize) -> Result<State, Error>;
t_dag_multi(qubits: &[usize]) -> Result<State, Error>;
ct_dag_multi(target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
p(index: usize, angle: f64) -> Result<State, Error>;
p_multi(qubits: &[usize], angle: f64) -> Result<State, Error>;
cp_multi(target_qubits: &[usize], control_qubits: &[usize], angle: f64) -> Result<State, Error>;
rx(index: usize, angle: f64) -> Result<State, Error>;
rx_multi(qubits: &[usize], angle: f64) -> Result<State, Error>;
crx_multi(target_qubits: &[usize], control_qubits: &[usize], angle: f64) -> Result<State, Error>;
ry(index: usize, angle: f64) -> Result<State, Error>;
ry_multi(qubits: &[usize], angle: f64) -> Result<State, Error>;
cry_multi(target_qubits: &[usize], control_qubits: &[usize], angle: f64) -> Result<State, Error>;
rz(index: usize, angle: f64) -> Result<State, Error>;
rz_multi(qubits: &[usize], angle: f64) -> Result<State, Error>;
crz_multi(target_qubits: &[usize], control_qubits: &[usize], angle: f64) -> Result<State, Error>;
unitary(index: usize, unitary: [[Complex<f64>; 2]; 2]) -> Result<State, Error>;
unitary_multi(qubits: &[usize], unitary: [[Complex<f64>; 2]; 2]) -> Result<State, Error>;
cunitary_multi(target_qubits: &[usize], control_qubits: &[usize], unitary: [[Complex<f64>; 2]; 2]) -> Result<State, Error>;
ry_phase(index: usize, angle: f64, phase: f64) -> Result<State, Error>;
ry_phase_multi(qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
cry_phase_gates(target_qubits: &[usize], control_qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
ry_phase_dag(index: usize, angle: f64, phase: f64) -> Result<State, Error>;
ry_phase_dag_multi(qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
cry_phase_dag_gates(target_qubits: &[usize], control_qubits: &[usize], angle: f64, phase: f64) -> Result<State, Error>;
// -- MULTI-QUBIT GATES --
cnot(control: usize, target: usize) -> Result<State, Error>;
swap(qubit1: usize, qubit2: usize) -> Result<State, Error>;
cswap(target1: usize, target2: usize, controls: &[usize]) -> Result<State, Error>;
toffoli(control1: usize, control2: usize, target: usize) -> Result<State, Error>;
matchgate(target: usize, theta: f64, phi1: f64, phi2: f64) -> Result<State, Error>;
cmatchgate(target: usize, theta: f64, phi1: f64, phi2: f64, controls: &[usize]) -> Result<State, Error>;
operate(unitary: impl Operator, target_qubits: &[usize], control_qubits: &[usize]) -> Result<State, Error>;
measure(basis: MeasurementBasis, measured_qubits: &[usize]) -> Result<MeasurementResult, Error>;
measure_n(basis: MeasurementBasis, measured_qubits: &[usize], n: usize) -> Result<Vec<MeasurementResult>, Error>;
}
// Implement multiplication by Complex<f64>
impl Mul<Complex<f64>> for State {
type Output = Self;
/// Multiplies each amplitude in the state vector by a complex scalar.
/// Note: This operation typically results in an unnormalised state.
fn mul(self, rhs: Complex<f64>) -> Self::Output {
let new_state_vector: Vec<Complex<f64>> = self
.state_vector
.into_par_iter() // Use parallel iterator for potential performance gain
.map(|amplitude| amplitude * rhs)
.collect();
// Create a new State directly, bypassing the normalization check in `new`
State {
state_vector: new_state_vector,
num_qubits: self.num_qubits,
}
}
}
// Implement multiplication by f64
impl Mul<f64> for State {
type Output = Self;
/// Multiplies each amplitude in the state vector by a real scalar.
/// Note: This operation typically results in an unnormalised state.
fn mul(self, rhs: f64) -> Self::Output {
let complex_rhs = Complex::new(rhs, 0.0); // Convert f64 to Complex<f64>
let new_state_vector: Vec<Complex<f64>> = self
.state_vector
.into_par_iter() // Use parallel iterator
.map(|amplitude| amplitude * complex_rhs)
.collect();
// Create a new State directly
State {
state_vector: new_state_vector,
num_qubits: self.num_qubits,
}
}
}
// Implement multiplication State = f64 * State
impl Mul<State> for f64 {
type Output = State;
/// Multiplies each amplitude in the state vector by a real scalar from the left.
/// Note: This operation typically results in an unnormalised state.
fn mul(self, rhs: State) -> Self::Output {
let complex_lhs = Complex::new(self, 0.0); // Convert f64 to Complex<f64>
let new_state_vector: Vec<Complex<f64>> = rhs
.state_vector
.into_par_iter() // Use parallel iterator
.map(|amplitude| complex_lhs * amplitude)
.collect();
// Create a new State directly
State {
state_vector: new_state_vector,
num_qubits: rhs.num_qubits,
}
}
}
// Implement multiplication State = Complex<f64> * State
impl Mul<State> for Complex<f64> {
type Output = State;
/// Multiplies each amplitude in the state vector by a complex scalar from the left.
/// Note: This operation typically results in an unnormalised state.
fn mul(self, rhs: State) -> Self::Output {
let new_state_vector: Vec<Complex<f64>> = rhs
.state_vector
.into_par_iter() // Use parallel iterator
.map(|amplitude| self * amplitude)
.collect();
// Create a new State directly
State {
state_vector: new_state_vector,
num_qubits: rhs.num_qubits,
}
}
}
// Implement addition for State + State
impl Add<State> for State {
type Output = Self;
/// Adds two state vectors element-wise.
/// Panics if the states do not have the same number of qubits.
/// Note: This operation typically results in an unnormalised state.
fn add(self, rhs: State) -> Self::Output {
if self.num_qubits != rhs.num_qubits {
panic!(
"Cannot add states with different numbers of qubits: {} != {}",
self.num_qubits, rhs.num_qubits
);
}
let new_state_vector: Vec<Complex<f64>> = self
.state_vector
.into_par_iter()
.zip(rhs.state_vector.into_par_iter())
.map(|(a, b)| a + b)
.collect();
// Create a new State directly
State {
state_vector: new_state_vector,
num_qubits: self.num_qubits,
}
}
}
// Implement sum for State
impl std::iter::Sum for State {
fn sum<I>(mut iter: I) -> Self
where
I: Iterator<Item = Self>,
{
// Take the first state as the initial accumulator.
let mut accumulator = match iter.next() {
Some(first_state) => first_state,
None => {
panic!(
"Cannot sum an empty iterator of State objects: num_qubits for the sum is undefined."
);
}
};
// Fold the rest of the states into the accumulator.
// The `Add` impl for `State` handles element-wise addition and
// panics if `num_qubits` do not match.
for state in iter {
if accumulator.num_qubits != state.num_qubits {
panic!(
"Cannot sum states with different numbers of qubits: {} != {}",
accumulator.num_qubits, state.num_qubits
);
}
accumulator = accumulator + state; // Uses the implemented Add for State
}
accumulator
}
}
// Implement subtraction for State - State
impl Sub<State> for State {
type Output = Self;
/// Subtracts the right-hand state vector from the left-hand state vector element-wise.
/// Panics if the states do not have the same number of qubits.
/// Note: This operation typically results in an unnormalised state.
fn sub(self, rhs: State) -> Self::Output {
if self.num_qubits != rhs.num_qubits {
panic!(
"Cannot subtract states with different numbers of qubits: {} != {}",
self.num_qubits, rhs.num_qubits
);
}
let new_state_vector: Vec<Complex<f64>> = self
.state_vector
.into_par_iter()
.zip(rhs.state_vector.into_par_iter())
.map(|(a, b)| a - b)
.collect();
// Create a new State directly
State {
state_vector: new_state_vector,
num_qubits: self.num_qubits,
}
}
}
impl std::fmt::Debug for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut state_str = String::new();
state_str.push_str(format!("State with {} qubits:\n[", self.num_qubits).as_str());
for amplitude in &self.state_vector {
let amplitude_string: String = if amplitude.im == 0.0 {
format!("{:.2}", amplitude.re)
} else if amplitude.re == 0.0 {
format!("{:.2}i", amplitude.im)
} else {
format!("{:.2} + {:.2}i", amplitude.re, amplitude.im)
};
// Add the amplitude to the string representations
state_str.push_str(format!("{}, ", amplitude_string).as_str());
}
state_str.pop(); // Remove the last comma
state_str.pop(); // Remove the last space
state_str.push(']');
write!(f, "{}", state_str)
}
}