-
Notifications
You must be signed in to change notification settings - Fork 23
/
Package.hpp
3708 lines (3339 loc) · 124 KB
/
Package.hpp
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
#pragma once
#include "dd/Complex.hpp"
#include "dd/ComplexNumbers.hpp"
#include "dd/ComplexValue.hpp"
#include "dd/ComputeTable.hpp"
#include "dd/DDDefinitions.hpp"
#include "dd/DensityNoiseTable.hpp"
#include "dd/Edge.hpp"
#include "dd/GateMatrixDefinitions.hpp"
#include "dd/Package_fwd.hpp"
#include "dd/StochasticNoiseOperationTable.hpp"
#include "dd/UnaryComputeTable.hpp"
#include "dd/UniqueTable.hpp"
#include "operations/Control.hpp"
#include <algorithm>
#include <array>
#include <bitset>
#include <cassert>
#include <cmath>
#include <complex>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <regex>
#include <set>
#include <stack>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace dd {
template <class Config> class Package {
static_assert(std::is_base_of_v<DDPackageConfig, Config>,
"Config must be derived from DDPackageConfig");
///
/// Construction, destruction, information and reset
///
public:
static constexpr std::size_t MAX_POSSIBLE_QUBITS =
static_cast<std::size_t>(std::numeric_limits<Qubit>::max()) + 1U;
static constexpr std::size_t DEFAULT_QUBITS = 32U;
explicit Package(std::size_t nq = DEFAULT_QUBITS) : nqubits(nq) {
resize(nq);
};
~Package() = default;
Package(const Package& package) = delete;
Package& operator=(const Package& package) = delete;
// resize the package instance
void resize(std::size_t nq) {
if (nq > MAX_POSSIBLE_QUBITS) {
throw std::invalid_argument("Requested too many qubits from package. "
"Qubit datatype only allows up to " +
std::to_string(MAX_POSSIBLE_QUBITS) +
" qubits, while " + std::to_string(nq) +
" were requested. Please recompile the "
"package with a wider Qubit type!");
}
nqubits = nq;
vUniqueTable.resize(nqubits);
mUniqueTable.resize(nqubits);
dUniqueTable.resize(nqubits);
stochasticNoiseOperationCache.resize(nqubits);
idTable.resize(nqubits);
}
// reset package state
void reset() {
clearUniqueTables();
resetMemoryManagers();
clearComputeTables();
}
/// Get the number of qubits
[[nodiscard]] auto qubits() const { return nqubits; }
private:
std::size_t nqubits;
public:
/// The memory manager for vector nodes
MemoryManager<vNode> vMemoryManager{Config::UT_VEC_INITIAL_ALLOCATION_SIZE};
/// The memory manager for matrix nodes
MemoryManager<mNode> mMemoryManager{Config::UT_MAT_INITIAL_ALLOCATION_SIZE};
/// The memory manager for density matrix nodes
MemoryManager<dNode> dMemoryManager{Config::UT_DM_INITIAL_ALLOCATION_SIZE};
/**
* @brief The memory manager for complex numbers
* @note The real and imaginary part of complex numbers are treated
* separately. Hence, it suffices for the manager to only manage real numbers.
*/
MemoryManager<RealNumber> cMemoryManager{};
/**
* @brief The cache manager for complex numbers
* @note Similar to the memory manager, the cache only maintains real entries,
* but typically gives them out in pairs to form complex numbers.
*/
MemoryManager<RealNumber> cCacheManager{};
/**
* @brief Get the memory manager for a given type
* @tparam T The type to get the manager for
* @return A reference to the manager
*/
template <class T> [[nodiscard]] auto& getMemoryManager() {
if constexpr (std::is_same_v<T, vNode>) {
return vMemoryManager;
} else if constexpr (std::is_same_v<T, mNode>) {
return mMemoryManager;
} else if constexpr (std::is_same_v<T, dNode>) {
return dMemoryManager;
} else if constexpr (std::is_same_v<T, RealNumber>) {
return cMemoryManager;
}
}
/**
* @brief Reset all memory managers
* @arg resizeToTotal If set to true, each manager allocates one chunk of
* memory as large as all chunks combined before the reset.
* @see MemoryManager::reset
*/
void resetMemoryManagers(const bool resizeToTotal = false) {
vMemoryManager.reset(resizeToTotal);
mMemoryManager.reset(resizeToTotal);
dMemoryManager.reset(resizeToTotal);
cMemoryManager.reset(resizeToTotal);
cCacheManager.reset(resizeToTotal);
}
/// The unique table used for vector nodes
UniqueTable<vNode, Config::UT_VEC_NBUCKET> vUniqueTable{0U, vMemoryManager};
/// The unique table used for matrix nodes
UniqueTable<mNode, Config::UT_MAT_NBUCKET> mUniqueTable{0U, mMemoryManager};
/// The unique table used for density matrix nodes
UniqueTable<dNode, Config::UT_DM_NBUCKET> dUniqueTable{0U, dMemoryManager};
/**
* @brief The unique table used for complex numbers
* @note The table actually only stores real numbers in the interval [0, 1],
* but is used to manages all complex numbers throughout the package.
* @see RealNumberUniqueTable
*/
RealNumberUniqueTable cUniqueTable{cMemoryManager};
ComplexNumbers cn{cUniqueTable, cCacheManager};
/**
* @brief Get the unique table for a given type
* @tparam T The type to get the unique table for
* @return A reference to the unique table
*/
template <class T> [[nodiscard]] auto& getUniqueTable() {
if constexpr (std::is_same_v<T, vNode>) {
return vUniqueTable;
} else if constexpr (std::is_same_v<T, mNode>) {
return mUniqueTable;
} else if constexpr (std::is_same_v<T, dNode>) {
return dUniqueTable;
} else if constexpr (std::is_same_v<T, RealNumber>) {
return cUniqueTable;
}
}
/**
* @brief Clear all unique tables
* @see UniqueTable::clear
* @see RealNumberUniqueTable::clear
*/
void clearUniqueTables() {
vUniqueTable.clear();
mUniqueTable.clear();
dUniqueTable.clear();
cUniqueTable.clear();
}
/**
* @brief Increment the reference count of an edge
* @details This is the main function for increasing reference counts within
* the DD package. It increases the reference count of the complex edge weight
* as well as the DD node itself. If the node newly becomes active, meaning
* that it had a reference count of zero beforehand, the reference count of
* all children is recursively increased.
* @tparam Node The node type of the edge.
* @param e The edge to increase the reference count of
*/
template <class Node> void incRef(const Edge<Node>& e) noexcept {
cn.incRef(e.w);
const auto& p = e.p;
const auto inc = getUniqueTable<Node>().incRef(p);
if (inc && p->ref == 1U) {
for (const auto& child : p->e) {
incRef(child);
}
}
}
/**
* @brief Decrement the reference count of an edge
* @details This is the main function for decreasing reference counts within
* the DD package. It decreases the reference count of the complex edge weight
* as well as the DD node itself. If the node newly becomes dead, meaning
* that its reference count hit zero, the reference count of all children is
* recursively decreased.
* @tparam Node The node type of the edge.
* @param e The edge to decrease the reference count of
*/
template <class Node> void decRef(const Edge<Node>& e) noexcept {
cn.decRef(e.w);
const auto& p = e.p;
const auto dec = getUniqueTable<Node>().decRef(p);
if (dec && p->ref == 0U) {
for (const auto& child : p->e) {
decRef(child);
}
}
}
bool garbageCollect(bool force = false) {
// return immediately if no table needs collection
if (!force && !vUniqueTable.possiblyNeedsCollection() &&
!mUniqueTable.possiblyNeedsCollection() &&
!dUniqueTable.possiblyNeedsCollection() &&
!cUniqueTable.possiblyNeedsCollection()) {
return false;
}
auto cCollect = cUniqueTable.garbageCollect(force);
if (cCollect > 0) {
// Collecting garbage in the complex numbers table requires collecting the
// node tables as well
force = true;
}
auto vCollect = vUniqueTable.garbageCollect(force);
auto mCollect = mUniqueTable.garbageCollect(force);
auto dCollect = dUniqueTable.garbageCollect(force);
// invalidate all compute tables involving vectors if any vector node has
// been collected
if (vCollect > 0) {
vectorAdd.clear();
vectorInnerProduct.clear();
vectorKronecker.clear();
matrixVectorMultiplication.clear();
}
// invalidate all compute tables involving matrices if any matrix node has
// been collected
if (mCollect > 0 || dCollect > 0) {
matrixAdd.clear();
matrixTranspose.clear();
conjugateMatrixTranspose.clear();
matrixKronecker.clear();
matrixVectorMultiplication.clear();
matrixMatrixMultiplication.clear();
clearIdentityTable();
stochasticNoiseOperationCache.clear();
densityAdd.clear();
densityDensityMultiplication.clear();
densityNoise.clear();
}
// invalidate all compute tables where any component of the entry contains
// numbers from the complex table if any complex numbers were collected
if (cCollect > 0) {
matrixVectorMultiplication.clear();
matrixMatrixMultiplication.clear();
matrixTranspose.clear();
conjugateMatrixTranspose.clear();
vectorInnerProduct.clear();
vectorKronecker.clear();
matrixKronecker.clear();
stochasticNoiseOperationCache.clear();
densityAdd.clear();
densityDensityMultiplication.clear();
densityNoise.clear();
}
return vCollect > 0 || mCollect > 0 || cCollect > 0;
}
///
/// Vector nodes, edges and quantum states
///
vEdge normalize(const vEdge& e, bool cached) {
auto zero = std::array{e.p->e[0].w.approximatelyZero(),
e.p->e[1].w.approximatelyZero()};
// make sure to release cached numbers approximately zero, but not exactly
// zero
if (cached) {
for (auto i = 0U; i < RADIX; i++) {
if (zero[i]) {
cn.returnToCache(e.p->e[i].w);
e.p->e[i] = vEdge::zero;
}
}
}
if (zero[0]) {
// all equal to zero
if (zero[1]) {
if (!cached && !e.isTerminal()) {
// If it is not a cached computation, the node has to be put back into
// the chain
vMemoryManager.returnEntry(e.p);
}
return vEdge::zero;
}
auto r = e;
auto& w = r.p->e[1].w;
if (cached) {
r.w = w;
} else {
r.w = cn.lookup(w);
}
w = Complex::one;
return r;
}
if (zero[1]) {
auto r = e;
auto& w = r.p->e[0].w;
if (cached) {
r.w = w;
} else {
r.w = cn.lookup(w);
}
w = Complex::one;
return r;
}
const auto mag0 = ComplexNumbers::mag2(e.p->e[0].w);
const auto mag1 = ComplexNumbers::mag2(e.p->e[1].w);
const auto norm2 = mag0 + mag1;
const auto mag2Max = (mag0 + RealNumber::eps >= mag1) ? mag0 : mag1;
const auto argMax = (mag0 + RealNumber::eps >= mag1) ? 0 : 1;
const auto norm = std::sqrt(norm2);
const auto magMax = std::sqrt(mag2Max);
const auto commonFactor = norm / magMax;
auto r = e;
auto& max = r.p->e[static_cast<std::size_t>(argMax)];
if (cached) {
if (max.w.exactlyOne()) {
r.w = cn.lookup(commonFactor, 0.);
} else {
r.w = max.w;
r.w.r->value *= commonFactor;
r.w.i->value *= commonFactor;
}
} else {
r.w = cn.lookup(RealNumber::val(max.w.r) * commonFactor,
RealNumber::val(max.w.i) * commonFactor);
if (r.w.approximatelyZero()) {
return vEdge::zero;
}
}
max.w = cn.lookup(magMax / norm, 0.);
if (max.w == Complex::zero) {
max = vEdge::zero;
}
const auto argMin = (argMax + 1) % 2;
auto& min = r.p->e[static_cast<std::size_t>(argMin)];
if (cached) {
ComplexNumbers::div(min.w, min.w, r.w);
min.w = cn.lookup(min.w, true);
} else {
min.w = cn.lookup(cn.divTemp(min.w, r.w));
}
if (min.w == Complex::zero) {
min = vEdge::zero;
}
return r;
}
dEdge makeZeroDensityOperator(const std::size_t n) {
auto f = dEdge::one;
for (std::size_t p = 0; p < n; p++) {
f = makeDDNode(static_cast<Qubit>(p),
std::array{f, dEdge::zero, dEdge::zero, dEdge::zero});
}
return f;
}
// generate |0...0> with n qubits
vEdge makeZeroState(const std::size_t n, const std::size_t start = 0) {
if (n + start > nqubits) {
throw std::runtime_error{
"Requested state with " + std::to_string(n + start) +
" qubits, but current package configuration only supports up to " +
std::to_string(nqubits) +
" qubits. Please allocate a larger package instance."};
}
auto f = vEdge::one;
for (std::size_t p = start; p < n + start; p++) {
f = makeDDNode(static_cast<Qubit>(p), std::array{f, vEdge::zero});
}
return f;
}
// generate computational basis state |i> with n qubits
vEdge makeBasisState(const std::size_t n, const std::vector<bool>& state,
const std::size_t start = 0) {
if (n + start > nqubits) {
throw std::runtime_error{
"Requested state with " + std::to_string(n + start) +
" qubits, but current package configuration only supports up to " +
std::to_string(nqubits) +
" qubits. Please allocate a larger package instance."};
}
auto f = vEdge::one;
for (std::size_t p = start; p < n + start; ++p) {
if (!state[p]) {
f = makeDDNode(static_cast<Qubit>(p), std::array{f, vEdge::zero});
} else {
f = makeDDNode(static_cast<Qubit>(p), std::array{vEdge::zero, f});
}
}
return f;
}
// generate general basis state with n qubits
vEdge makeBasisState(const std::size_t n,
const std::vector<BasisStates>& state,
const std::size_t start = 0) {
if (n + start > nqubits) {
throw std::runtime_error{
"Requested state with " + std::to_string(n + start) +
" qubits, but current package configuration only supports up to " +
std::to_string(nqubits) +
" qubits. Please allocate a larger package instance."};
}
if (state.size() < n) {
throw std::runtime_error(
"Insufficient qubit states provided. Requested " + std::to_string(n) +
", but received " + std::to_string(state.size()));
}
auto f = vEdge::one;
for (std::size_t p = start; p < n + start; ++p) {
switch (state[p]) {
case BasisStates::zero:
f = makeDDNode(static_cast<Qubit>(p), std::array{f, vEdge::zero});
break;
case BasisStates::one:
f = makeDDNode(static_cast<Qubit>(p), std::array{vEdge::zero, f});
break;
case BasisStates::plus:
f = makeDDNode(
static_cast<Qubit>(p),
std::array<vEdge, RADIX>{{{f.p, cn.lookup(dd::SQRT2_2, 0)},
{f.p, cn.lookup(dd::SQRT2_2, 0)}}});
break;
case BasisStates::minus:
f = makeDDNode(
static_cast<Qubit>(p),
std::array<vEdge, RADIX>{{{f.p, cn.lookup(dd::SQRT2_2, 0)},
{f.p, cn.lookup(-dd::SQRT2_2, 0)}}});
break;
case BasisStates::right:
f = makeDDNode(
static_cast<Qubit>(p),
std::array<vEdge, RADIX>{{{f.p, cn.lookup(dd::SQRT2_2, 0)},
{f.p, cn.lookup(0, dd::SQRT2_2)}}});
break;
case BasisStates::left:
f = makeDDNode(
static_cast<Qubit>(p),
std::array<vEdge, RADIX>{{{f.p, cn.lookup(dd::SQRT2_2, 0)},
{f.p, cn.lookup(0, -dd::SQRT2_2)}}});
break;
}
}
return f;
}
// generate the decision diagram from an arbitrary state vector
vEdge makeStateFromVector(const CVec& stateVector) {
if (stateVector.empty()) {
return vEdge::one;
}
const auto& length = stateVector.size();
if ((length & (length - 1)) != 0) {
throw std::invalid_argument(
"State vector must have a length of a power of two.");
}
if (length == 1) {
return vEdge::terminal(cn.lookup(stateVector[0]));
}
[[maybe_unused]] const auto before = cn.cacheCount();
const auto level = static_cast<Qubit>(std::log2(length) - 1);
auto state =
makeStateFromVector(stateVector.begin(), stateVector.end(), level);
// the recursive function makes use of the cache, so we have to clean it up
state.w = cn.lookup(state.w, true);
[[maybe_unused]] const auto after = cn.cacheCount();
assert(after == before);
return state;
}
/**
Converts a given matrix to a decision diagram
@param matrix A complex matrix to convert to a DD.
@return An mEdge that represents the DD.
@throws std::invalid_argument If the given matrix is not square or its
length is not a power of two.
**/
mEdge makeDDFromMatrix(const CMat& matrix) {
if (matrix.empty()) {
return mEdge::one;
}
const auto& length = matrix.size();
if ((length & (length - 1)) != 0) {
throw std::invalid_argument(
"Matrix must have a length of a power of two.");
}
const auto& width = matrix[0].size();
if (length != width) {
throw std::invalid_argument("Matrix must be square.");
}
if (length == 1) {
return mEdge::terminal(cn.lookup(matrix[0][0]));
}
[[maybe_unused]] const auto before = cn.cacheCount();
const auto level = static_cast<Qubit>(std::log2(length) - 1);
auto matrixDD = makeDDFromMatrix(matrix, level, 0, length, 0, width);
matrixDD.w = cn.lookup(matrixDD.w, true);
[[maybe_unused]] const auto after = cn.cacheCount();
assert(after == before);
return matrixDD;
}
///
/// Matrix nodes, edges and quantum gates
///
template <class Node> Edge<Node> normalize(const Edge<Node>& e, bool cached) {
if constexpr (std::is_same_v<Node, mNode> || std::is_same_v<Node, dNode>) {
auto argmax = -1;
auto zero = std::array{
e.p->e[0].w.approximatelyZero(), e.p->e[1].w.approximatelyZero(),
e.p->e[2].w.approximatelyZero(), e.p->e[3].w.approximatelyZero()};
// make sure to release cached numbers approximately zero, but not exactly
// zero
if (cached) {
for (auto i = 0U; i < NEDGE; i++) {
auto& successor = e.p->e[i];
if (zero[i]) {
cn.returnToCache(successor.w);
successor = Edge<Node>::zero;
}
}
}
fp max = 0;
auto maxc = Complex::one;
// determine max amplitude
for (auto i = 0U; i < NEDGE; ++i) {
if (zero[i]) {
continue;
}
const auto& w = e.p->e[i].w;
if (argmax == -1) {
argmax = static_cast<decltype(argmax)>(i);
max = ComplexNumbers::mag2(w);
maxc = w;
} else {
auto mag = ComplexNumbers::mag2(w);
if (mag - max > RealNumber::eps) {
argmax = static_cast<decltype(argmax)>(i);
max = mag;
maxc = w;
}
}
}
// all equal to zero
if (argmax == -1) {
if (!cached && !e.isTerminal()) {
// If it is not a cached computation, the node has to be put back into
// the chain
getMemoryManager<Node>().returnEntry(e.p);
}
return Edge<Node>::zero;
}
auto r = e;
// divide each entry by max
for (auto i = 0U; i < NEDGE; ++i) {
if (static_cast<decltype(argmax)>(i) == argmax) {
r.p->e[i].w = Complex::one;
if (r.w.exactlyOne()) {
r.w = maxc;
continue;
}
if (cached) {
ComplexNumbers::mul(r.w, r.w, maxc);
} else {
r.w = cn.lookup(cn.mulTemp(r.w, maxc));
}
} else {
auto& successor = r.p->e[i];
if (zero[i]) {
assert(successor.w.exactlyZero() &&
"Should have been set to zero at the start");
continue;
}
// TODO: it might be worth revisiting whether this check actually
// improves performance or rather causes more instability.
if (successor.w.approximatelyOne()) {
if (cached) {
cn.returnToCache(successor.w);
}
successor.w = Complex::one;
}
const auto c = cn.divTemp(successor.w, maxc);
if (cached) {
cn.returnToCache(successor.w);
}
successor.w = cn.lookup(c);
}
}
return r;
}
}
// build matrix representation for a single gate on an n-qubit circuit
mEdge makeGateDD(const std::array<ComplexValue, NEDGE>& mat,
const std::size_t n, const qc::Qubit target,
const std::size_t start = 0) {
return makeGateDD(mat, n, qc::Controls{}, target, start);
}
mEdge makeGateDD(const std::array<ComplexValue, NEDGE>& mat,
const std::size_t n, const qc::Control& control,
const qc::Qubit target, const std::size_t start = 0) {
return makeGateDD(mat, n, qc::Controls{control}, target, start);
}
mEdge makeGateDD(const std::array<ComplexValue, NEDGE>& mat,
const std::size_t n, const qc::Controls& controls,
const qc::Qubit target, const std::size_t start = 0) {
if (n + start > nqubits) {
throw std::runtime_error{
"Requested gate with " + std::to_string(n + start) +
" qubits, but current package configuration only supports up to " +
std::to_string(nqubits) +
" qubits. Please allocate a larger package instance."};
}
std::array<mEdge, NEDGE> em{};
auto it = controls.begin();
for (auto i = 0U; i < NEDGE; ++i) {
// NOLINTNEXTLINE(clang-diagnostic-float-equal) it has to be really zero
if (mat[i].r == 0 && mat[i].i == 0) {
em[i] = mEdge::zero;
} else {
em[i] = mEdge::terminal(cn.lookup(mat[i]));
}
}
// process lines below target
auto z = static_cast<Qubit>(start);
for (; z < static_cast<Qubit>(target); ++z) {
for (auto i1 = 0U; i1 < RADIX; ++i1) {
for (auto i2 = 0U; i2 < RADIX; ++i2) {
auto i = i1 * RADIX + i2;
if (it != controls.end() && it->qubit == z) {
auto edges =
std::array{mEdge::zero, mEdge::zero, mEdge::zero, mEdge::zero};
if (it->type == qc::Control::Type::Neg) { // neg. control
edges[0] = em[i];
if (i1 == i2) {
if (z == 0U) {
edges[3] = mEdge::one;
} else {
edges[3] = makeIdent(start, z - 1U);
}
}
} else { // pos. control
edges[3] = em[i];
if (i1 == i2) {
if (z == 0U) {
edges[0] = mEdge::one;
} else {
edges[0] = makeIdent(start, z - 1U);
}
}
}
em[i] = makeDDNode(z, edges);
} else { // not connected
em[i] = makeDDNode(
z, std::array{em[i], mEdge::zero, mEdge::zero, em[i]});
}
}
}
if (it != controls.end() && it->qubit == z) {
++it;
}
}
// target line
auto e = makeDDNode(z, em);
// process lines above target
for (; z < static_cast<Qubit>(n - 1 + start); z++) {
auto q = static_cast<Qubit>(z + 1);
if (it != controls.end() && it->qubit == static_cast<qc::Qubit>(q)) {
if (it->type == qc::Control::Type::Neg) { // neg. control
e = makeDDNode(q, std::array{e, mEdge::zero, mEdge::zero,
makeIdent(start, q - 1U)});
} else { // pos. control
e = makeDDNode(q, std::array{makeIdent(start, q - 1U), mEdge::zero,
mEdge::zero, e});
}
++it;
} else { // not connected
e = makeDDNode(q, std::array{e, mEdge::zero, mEdge::zero, e});
}
}
return e;
}
/**
Creates the DD for a two-qubit gate
@param mat Matrix representation of the gate
@param n Number of qubits in the circuit
@param target0 First target qubit
@param target1 Second target qubit
@param start Start index for the DD
@return DD representing the gate
@throws std::runtime_error if the number of qubits is larger than the package
configuration
**/
mEdge makeTwoQubitGateDD(
const std::array<std::array<ComplexValue, NEDGE>, NEDGE>& mat,
const std::size_t n, const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
// sanity check
if (n + start > nqubits) {
throw std::runtime_error{
"Requested gate with " + std::to_string(n + start) +
" qubits, but current package configuration only supports up to " +
std::to_string(nqubits) +
" qubits. Please allocate a larger package instance."};
}
// create terminal edge matrix
std::array<std::array<mEdge, NEDGE>, NEDGE> em{};
for (auto i1 = 0U; i1 < NEDGE; i1++) {
const auto& matRow = mat.at(i1);
auto& emRow = em.at(i1);
for (auto i2 = 0U; i2 < NEDGE; i2++) {
const auto& matEntry = matRow.at(i2);
auto& emEntry = emRow.at(i2);
// NOLINTNEXTLINE(clang-diagnostic-float-equal) it has to be really zero
if (matEntry.r == 0 && matEntry.i == 0) {
emEntry = mEdge::zero;
} else {
emEntry = mEdge::terminal(cn.lookup(matEntry));
}
}
}
// process lines below smaller target (by creating identity structures)
auto z = static_cast<Qubit>(start);
const auto smallerTarget = std::min(target0, target1);
for (; z < smallerTarget; ++z) {
for (auto& row : em) {
for (auto& entry : row) {
entry =
makeDDNode(z, std::array{entry, mEdge::zero, mEdge::zero, entry});
}
}
}
// process the smaller target by taking the 16 submatrices and appropriately
// combining them into four DDs.
std::array<mEdge, NEDGE> em0{};
for (std::size_t row = 0; row < RADIX; ++row) {
for (std::size_t col = 0; col < RADIX; ++col) {
std::array<mEdge, NEDGE> local{};
if (target0 > target1) {
for (std::size_t i = 0; i < RADIX; ++i) {
for (std::size_t j = 0; j < RADIX; ++j) {
local.at(i * RADIX + j) =
em.at(row * RADIX + i).at(col * RADIX + j);
}
}
} else {
for (std::size_t i = 0; i < RADIX; ++i) {
for (std::size_t j = 0; j < RADIX; ++j) {
local.at(i * RADIX + j) =
em.at(i * RADIX + row).at(j * RADIX + col);
}
}
}
em0.at(row * RADIX + col) = makeDDNode(z, local);
}
}
// process lines between the two targets (by creating identity structures)
for (++z; z < std::max(target0, target1); ++z) {
for (auto& entry : em0) {
entry =
makeDDNode(z, std::array{entry, mEdge::zero, mEdge::zero, entry});
}
}
// process the larger target by combining the four DDs from the smaller
// target
auto e = makeDDNode(z, em0);
// process lines above the larger target (by creating identity structures)
const auto end = static_cast<Qubit>(n + start);
for (++z; z < end; ++z) {
e = makeDDNode(z, std::array{e, mEdge::zero, mEdge::zero, e});
}
return e;
}
mEdge makeSWAPDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const std::size_t start = 0) {
return makeTwoQubitGateDD(SWAPmat, n, target0, target1, start);
}
mEdge makeSWAPDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
auto c = controls;
c.insert(qc::Control{target0});
mEdge e = makeGateDD(Xmat, n, c, target1, start);
c.erase(qc::Control{target0});
c.insert(qc::Control{target1});
e = multiply(e, multiply(makeGateDD(Xmat, n, c, target0, start), e));
return e;
}
mEdge makePeresDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
auto c = controls;
c.insert(qc::Control{target1});
mEdge e = makeGateDD(Xmat, n, c, target0, start);
e = multiply(makeGateDD(Xmat, n, controls, target1, start), e);
return e;
}
mEdge makePeresdagDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
mEdge e = makeGateDD(Xmat, n, controls, target1, start);
auto c = controls;
c.insert(qc::Control{target1});
e = multiply(makeGateDD(Xmat, n, c, target0, start), e);
return e;
}
mEdge makeiSWAPDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const std::size_t start = 0) {
return makeTwoQubitGateDD(iSWAPmat, n, target0, target1, start);
}
mEdge makeiSWAPDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
mEdge e = makeGateDD(Smat, n, controls, target1, start); // S q[1]
e = multiply(e, makeGateDD(Smat, n, controls, target0, start)); // S q[0]
e = multiply(e, makeGateDD(Hmat, n, controls, target0, start)); // H q[0]
auto c = controls;
c.insert(qc::Control{target0});
e = multiply(e, makeGateDD(Xmat, n, c, target1, start)); // CX q[0], q[1]
c.erase(qc::Control{target0});
c.insert(qc::Control{target1});
e = multiply(e, makeGateDD(Xmat, n, c, target0, start)); // CX q[1], q[0]
e = multiply(e, makeGateDD(Hmat, n, controls, target1, start)); // H q[1]
return e;
}
mEdge makeiSWAPinvDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const std::size_t start = 0) {
return makeTwoQubitGateDD(iSWAPinvmat, n, target0, target1, start);
}
mEdge makeiSWAPinvDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
mEdge e = makeGateDD(Hmat, n, controls, target1, start); // H q[1]
auto c = controls;
c.insert(qc::Control{target1});
e = multiply(e, makeGateDD(Xmat, n, c, target0, start)); // CX q[1], q[0]
c.erase(qc::Control{target1});
c.insert(qc::Control{target0});
e = multiply(e, makeGateDD(Xmat, n, c, target1, start)); // CX q[0], q[1]
e = multiply(e, makeGateDD(Hmat, n, controls, target0, start)); // H q[0]
e = multiply(e,
makeGateDD(Sdagmat, n, controls, target0, start)); // Sdag q[0]
e = multiply(e,
makeGateDD(Sdagmat, n, controls, target1, start)); // Sdag q[1]
return e;
}
mEdge makeDCXDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const std::size_t start = 0) {
return makeTwoQubitGateDD(DCXmat, n, target0, target1, start);
}
mEdge makeDCXDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const std::size_t start = 0) {
auto c = controls;
c.insert(qc::Control{target0});
mEdge e = makeGateDD(Xmat, n, c, target1, start);
c.erase(qc::Control{target0});
c.insert(qc::Control{target1});
e = multiply(e, makeGateDD(Xmat, n, c, target0, start));
return e;
}
mEdge makeRZZDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const fp theta,
const std::size_t start = 0) {
return makeTwoQubitGateDD(RZZmat(theta), n, target0, target1, start);
}
mEdge makeRZZDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const fp theta, const std::size_t start = 0) {
auto c = controls;
c.insert(qc::Control{target0});
auto e = makeGateDD(Xmat, n, c, target1, start);
c.erase(qc::Control{target0});
e = multiply(e, makeGateDD(RZmat(theta), n, c, target1, start));
c.insert(qc::Control{target0});
e = multiply(e, makeGateDD(Xmat, n, c, target1, start));
return e;
}
mEdge makeRYYDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const fp theta,
const std::size_t start = 0) {
return makeTwoQubitGateDD(RYYmat(theta), n, target0, target1, start);
}
mEdge makeRYYDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const fp theta, const std::size_t start = 0) {
// no controls are necessary on the RX gates since they cancel if the
// controls are 0.
auto e = makeGateDD(RXmat(PI_2), n, qc::Controls{}, target0, start);
e = multiply(e, makeGateDD(RXmat(PI_2), n, qc::Controls{}, target1, start));
e = multiply(e, makeRZZDD(n, controls, target0, target1, theta, start));
e = multiply(e,
makeGateDD(RXmat(-PI_2), n, qc::Controls{}, target1, start));
e = multiply(e,
makeGateDD(RXmat(-PI_2), n, qc::Controls{}, target0, start));
return e;
}
mEdge makeRXXDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const fp theta,
const std::size_t start = 0) {
return makeTwoQubitGateDD(RXXmat(theta), n, target0, target1, start);
}
mEdge makeRXXDD(const std::size_t n, const qc::Controls& controls,
const qc::Qubit target0, const qc::Qubit target1,
const fp theta, const std::size_t start = 0) {
// no controls are necessary on the H gates since they cancel if the
// controls are 0.
auto e = makeGateDD(Hmat, n, qc::Controls{}, target0, start);
e = multiply(e, makeGateDD(Hmat, n, qc::Controls{}, target1, start));
e = multiply(e, makeRZZDD(n, controls, target0, target1, theta, start));
e = multiply(e, makeGateDD(Hmat, n, qc::Controls{}, target1, start));
e = multiply(e, makeGateDD(Hmat, n, qc::Controls{}, target0, start));
return e;
}
mEdge makeRZXDD(const std::size_t n, const qc::Qubit target0,
const qc::Qubit target1, const fp theta,
const std::size_t start = 0) {
return makeTwoQubitGateDD(RZXmat(theta), n, target0, target1, start);