-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathutilities.cpp
More file actions
1061 lines (767 loc) · 30.4 KB
/
utilities.cpp
File metadata and controls
1061 lines (767 loc) · 30.4 KB
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
/** @file
* Miscellaneous utility functions needed internally,
* which are not performance critical (i.e. not used
* in hot loops). These include qubit and state index
* logic, matrix algebra, and channel parameters.
*
* @author Tyson Jones
*/
#include "quest/include/types.h"
#include "quest/include/qureg.h"
#include "quest/include/paulis.h"
#include "quest/include/matrices.h"
#include "quest/include/channels.h"
#include "quest/include/precision.h"
#include "quest/src/core/errors.hpp"
#include "quest/src/core/bitwise.hpp"
#include "quest/src/core/memory.hpp"
#include "quest/src/core/utilities.hpp"
#include "quest/src/core/validation.hpp"
#include "quest/src/cpu/cpu_config.hpp"
#include "quest/src/comm/comm_config.hpp"
#include "quest/src/comm/comm_routines.hpp"
#include <functional>
#include <algorithm>
#include <complex>
#include <cmath>
#include <vector>
#include <array>
#include <list>
#include <new>
using std::vector;
/*
* QUBIT PROCESSING
*/
int util_getPrefixInd(int qubit, Qureg qureg) {
if (qubit < qureg.logNumAmpsPerNode)
error_utilsGetPrefixIndGivenSuffixQubit();
return qubit - qureg.logNumAmpsPerNode;
}
int util_getBraQubit(int ketQubit, Qureg qureg) {
if (!qureg.isDensityMatrix)
error_utilsGetBraIndGivenNonDensMatr();
return ketQubit + qureg.numQubits;
}
int util_getPrefixBraInd(int ketQubit, Qureg qureg) {
if (!qureg.isDensityMatrix)
error_utilsGetPrefixBraIndGivenNonDensMatr();
if (ketQubit < qureg.logNumColsPerNode)
error_utilsGetPrefixBraIndGivenSuffixQubit();
// equivalent to util_getPrefixInd of util_getBraQubit
return ketQubit - qureg.logNumColsPerNode;
}
bool util_isQubitInSuffix(int qubit, Qureg qureg) {
return qubit < qureg.logNumAmpsPerNode;
}
bool util_areAllQubitsInSuffix(vector<int> qubits, Qureg qureg) {
for (int q : qubits)
if (!util_isQubitInSuffix(q, qureg))
return false;
return true;
}
bool util_isBraQubitInSuffix(int ketQubit, Qureg qureg) {
if (!qureg.isDensityMatrix)
error_utilsIsBraQubitInSuffixGivenNonDensMatr();
return ketQubit < qureg.logNumColsPerNode;
}
vector<int> getPrefixOrSuffixQubits(vector<int> qubits, Qureg qureg, bool getSuffix) {
// note that when the qureg is local/duplicated,
// all qubits will be suffix, none will be prefix
vector<int> subQubits(0);
subQubits.reserve(qubits.size());
for (int qubit : qubits)
if (util_isQubitInSuffix(qubit, qureg) == getSuffix)
subQubits.push_back(qubit);
return subQubits;
}
std::array<vector<int>,2> util_getPrefixAndSuffixQubits(vector<int> qubits, Qureg qureg) {
return {
getPrefixOrSuffixQubits(qubits, qureg, false),
getPrefixOrSuffixQubits(qubits, qureg, true)
};
}
int util_getRankBitOfQubit(int ketQubit, Qureg qureg) {
int rankInd = util_getPrefixInd(ketQubit, qureg);
int rankBit = getBit(qureg.rank, rankInd);
return rankBit;
}
int util_getRankBitOfBraQubit(int ketQubit, Qureg qureg) {
int rankInd = util_getPrefixBraInd(ketQubit, qureg);
int rankBit = getBit(qureg.rank, rankInd);
return rankBit;
}
int util_getRankWithQubitFlipped(int prefixKetQubit, Qureg qureg) {
int rankInd = util_getPrefixInd(prefixKetQubit, qureg);
int rankFlip = flipBit(qureg.rank, rankInd);
return rankFlip;
}
int util_getRankWithQubitsFlipped(vector<int> prefixQubits, Qureg qureg) {
int rank = qureg.rank;
for (int qubit : prefixQubits)
rank = flipBit(rank, util_getPrefixInd(qubit, qureg));
return rank;
}
int util_getRankWithBraQubitFlipped(int ketQubit, Qureg qureg) {
int rankInd = util_getPrefixBraInd(ketQubit, qureg);
int rankFlip = flipBit(qureg.rank, rankInd);
return rankFlip;
}
int util_getRankWithBraQubitsFlipped(vector<int> ketQubits, Qureg qureg) {
int rank = qureg.rank;
for (int qubit : ketQubits)
rank = flipBit(rank, util_getPrefixBraInd(qubit, qureg));
return rank;
}
vector<int> util_getBraQubits(vector<int> ketQubits, Qureg qureg) {
vector<int> braInds(0);
braInds.reserve(ketQubits.size());
for (int qubit : ketQubits)
braInds.push_back(util_getBraQubit(qubit, qureg));
return braInds;
}
vector<int> util_getNonTargetedQubits(int* targets, int numTargets, int numQubits) {
qindex mask = getBitMask(targets, numTargets);
vector<int> nonTargets;
nonTargets.reserve(numQubits - numTargets);
for (int i=0; i<numQubits; i++)
if (getBit(mask, i) == 0)
nonTargets.push_back(i);
return nonTargets;
}
vector<int> util_getConcatenated(vector<int> list1, vector<int> list2) {
// modify the copy of list1
list1.insert(list1.end(), list2.begin(), list2.end());
return list1;
}
vector<int> util_getSorted(vector<int> qubits) {
vector<int> copy = qubits;
std::sort(copy.begin(), copy.end());
return copy;
}
vector<int> util_getSorted(vector<int> ctrls, vector<int> targs) {
return util_getSorted(util_getConcatenated(ctrls, targs));
}
qindex util_getBitMask(vector<int> qubits) {
// inserts qubits in state 1
return getBitMask(qubits.data(), qubits.size());
}
qindex util_getBitMask(vector<int> qubits, vector<int> states) {
return getBitMask(qubits.data(), states.data(), states.size());
}
qindex util_getBitMask(vector<int> ctrls, vector<int> ctrlStates, vector<int> targs, vector<int> targStates) {
auto qubits = util_getConcatenated(ctrls, targs);
auto states = util_getConcatenated(ctrlStates, targStates);
return util_getBitMask(qubits, states);
}
vector<int> util_getVector(int* qubits, int numQubits) {
// permit qubits=nullptr, overriding numQubits (might be non-zero)
if (qubits == nullptr)
return {};
return vector<int> (qubits, qubits + numQubits);
}
/*
* INDEX ALGEBRA
*/
qindex util_getGlobalIndexOfFirstLocalAmp(Qureg qureg) {
return qureg.rank * qureg.numAmpsPerNode;
}
qindex util_getGlobalColumnOfFirstLocalAmp(Qureg qureg) {
assert_utilsGivenDensMatr(qureg);
return qureg.rank * powerOf2(qureg.logNumColsPerNode);
}
qindex util_getLocalIndexOfGlobalIndex(Qureg qureg, qindex globalInd) {
// equivalent to below, but clearer
if (!qureg.isDistributed)
return globalInd;
// defensive-design integrity check
qindex globalStart = util_getGlobalIndexOfFirstLocalAmp(qureg);
qindex globalEnd = globalStart + qureg.numAmpsPerNode;
if (globalInd < globalStart || globalInd >= globalEnd)
error_utilsGivenGlobalIndexOutsideNode();
return globalInd % qureg.numAmpsPerNode;
}
qindex util_getLocalIndexOfFirstDiagonalAmp(Qureg qureg) {
assert_utilsGivenDensMatr(qureg);
return qureg.rank * powerOf2(qureg.logNumColsPerNode);
}
qindex util_getGlobalFlatIndex(Qureg qureg, qindex globalRow, qindex globalCol) {
assert_utilsGivenDensMatr(qureg);
qindex numAmpsPerCol = powerOf2(qureg.numQubits);
return (globalCol * numAmpsPerCol) + globalRow;
}
int util_getRankContainingIndex(Qureg qureg, qindex globalInd) {
// when not distributed, root contains the index (as incidentally do all nodes)
if (!qureg.isDistributed)
return ROOT_RANK;
// accepts flat density matrix index too
return globalInd / qureg.numAmpsPerNode; // floors
}
int util_getRankContainingIndex(FullStateDiagMatr matr, qindex globalInd) {
// when not distributed, root contains the index (as incidentally do all nodes)
if (!matr.isDistributed)
return ROOT_RANK;
return globalInd / matr.numElemsPerNode; // floors
}
int util_getRankContainingColumn(Qureg qureg, qindex globalCol) {
assert_utilsGivenDensMatr(qureg);
/// when not distributed, root contains the column (as incidentally do all nodes)
if (!qureg.isDistributed)
return ROOT_RANK;
qindex numColsPerNode = powerOf2(qureg.logNumColsPerNode);
return globalCol / numColsPerNode; // floors
}
qindex util_getNextPowerOf2(qindex number) {
int nextExponent = static_cast<int>(std::ceil(std::log2(number)));
return powerOf2(nextExponent);
}
qcomp util_getElemFromNestedPtrs(void* in, qindex* inds, int numInds) {
qindex ind = inds[0];
if (numInds == 1)
return ((qcomp*) in)[ind];
qcomp* ptr = ((qcomp**) in)[ind];
return util_getElemFromNestedPtrs(ptr, &inds[1], numInds-1); // compiler may optimise tail-recursion
}
/*
* SCALAR ALGEBRA
*/
bool util_isStrictlyInteger(qreal num) {
return std::trunc(num) == num;
}
bool util_isApproxReal(qcomp num, qreal eps) {
return std::abs(std::imag(num)) <= eps;
}
qcomp util_getPowerOfI(size_t exponent) {
// seems silly, but at least it's precision agnostic!
qcomp values[] = {1, 1_i, -1, -1_i};
return values[exponent % 4];
}
/*
* VECTOR REDUCTION
*/
qreal util_getSum(vector<qreal> list) {
qreal sum = 0;
qreal y, t, c=0;
// complex Kahan summation
for (auto& x : list) {
y = x - c;
t = sum + y;
c = ( t - sum ) - y;
sum = t;
}
return sum;
}
/*
* MATRIX CONJUGATION
*/
// type T can be qcomp** or qcomp*[]
template <typename T>
void setDenseElemsConj(T elems, qindex dim) {
for (qindex i=0; i<dim; i++)
for (qindex j=0; j<dim; j++)
elems[i][j] = std::conj(elems[i][j]);
}
// diagonals don't need templating because arrays decay to pointers, yay!
void setDiagElemsConj(qcomp* elems, qindex dim) {
for (qindex i=0; i<dim; i++)
elems[i] = std::conj(elems[i]);
}
CompMatr1 util_getConj(CompMatr1 matrix) {
CompMatr1 conj = matrix;
setDenseElemsConj(conj.elems, matrix.numRows);
return conj;
}
CompMatr2 util_getConj(CompMatr2 matrix) {
CompMatr2 conj = matrix;
setDenseElemsConj(conj.elems, matrix.numRows);
return conj;
}
DiagMatr1 util_getConj(DiagMatr1 matrix) {
DiagMatr1 conj = matrix;
setDiagElemsConj(conj.elems, matrix.numElems);
return conj;
}
DiagMatr2 util_getConj(DiagMatr2 matrix) {
DiagMatr2 conj = matrix;
setDiagElemsConj(conj.elems, matrix.numElems);
return conj;
}
void util_setConj(CompMatr matrix) {
setDenseElemsConj(matrix.cpuElems, matrix.numRows);
}
void util_setConj(DiagMatr matrix) {
setDiagElemsConj(matrix.cpuElems, matrix.numElems);
}
/*
* MATRIX UNITARITY
*/
bool isApprox(qreal a, qreal b, qreal eps) {
return std::abs(a-b) <= eps;
}
bool isApprox(qcomp a, qcomp b, qreal eps) {
return std::norm(a-b) <= eps;
}
// type T can be qcomp** or qcomp*[]
template <typename T>
bool getUnitarity(T elems, qindex dim, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
// check m * dagger(m) == identity
for (qindex r=0; r<dim; r++) {
for (qindex c=0; c<dim; c++) {
// compute m[r,...] * dagger(m)[...,c]
qcomp elem = 0;
for (qindex i=0; i<dim; i++)
elem += elems[r][i] * std::conj(elems[c][i]);
// check if further than epsilon from identity[r,c]
if (!isApprox(elem, qcomp(r==c,0), eps))
return false;
}
}
return true;
}
// diagonal version doesn't need templating because array decays to pointer, yay!
bool getUnitarity(qcomp* diags, qindex dim, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
// check every element has unit magnitude
for (qindex i=0; i<dim; i++)
if (!isApprox(std::abs(diags[i]), 1, eps))
return false;
return true;
}
// unitarity of fixed-size matrices is always computed afresh
bool util_isUnitary(CompMatr1 m, qreal eps) { return getUnitarity(m.elems, m.numRows, eps); }
bool util_isUnitary(CompMatr2 m, qreal eps) { return getUnitarity(m.elems, m.numRows, eps); }
bool util_isUnitary(DiagMatr1 m, qreal eps) { return getUnitarity(m.elems, m.numElems, eps); }
bool util_isUnitary(DiagMatr2 m, qreal eps) { return getUnitarity(m.elems, m.numElems, eps); }
// unitarity of heap matrices is cached
bool util_isUnitary(CompMatr m, qreal eps) {
// compute and record unitarity if not already known
if (*(m.isApproxUnitary) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxUnitary) = getUnitarity(m.cpuElems, m.numRows, eps);
// eps may have been ignored
return *(m.isApproxUnitary);
}
bool util_isUnitary(DiagMatr m, qreal eps) {
// compute and record unitarity if not already known
if (*(m.isApproxUnitary) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxUnitary) = getUnitarity(m.cpuElems, m.numElems, eps);
// eps may have been ignored
return *(m.isApproxUnitary);
}
bool util_isUnitary(FullStateDiagMatr m, qreal eps) {
// compute and record unitarity if not already known
if (*(m.isApproxUnitary) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxUnitary) = getUnitarity(m.cpuElems, m.numElemsPerNode, eps);
// communication may be necessary
if (m.isDistributed)
*(m.isApproxUnitary) = comm_isTrueOnAllNodes(*(m.isApproxUnitary));
// eps may have been ignored
return *(m.isApproxUnitary);
}
/*
* MATRIX HERMITICITY
*/
// type T can be qcomp** or qcomp*[]
template <typename T>
bool getHermiticity(T elems, qindex dim, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
// check adjoint(elems) == elems
for (qindex r=0; r<dim; r++)
for (qindex c=0; c<r; c++)
if (!isApprox(elems[r][c], std::conj(elems[c][r]), eps))
return false;
return true;
}
// diagonal version doesn't need templating because array decays to pointer, yay!
bool getHermiticity(qcomp* diags, qindex dim, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
// check every element has a zero (or <eps) imaginary component
for (qindex i=0; i<dim; i++)
if (!isApprox(std::imag(diags[i]), 0, eps))
return false;
return true;
}
// hermiticity of fixed-size matrices is always computed afresh
bool util_isHermitian(CompMatr1 m, qreal eps) { return getHermiticity(m.elems, m.numRows, eps); }
bool util_isHermitian(CompMatr2 m, qreal eps) { return getHermiticity(m.elems, m.numRows, eps); }
bool util_isHermitian(DiagMatr1 m, qreal eps) { return getHermiticity(m.elems, m.numElems, eps); }
bool util_isHermitian(DiagMatr2 m, qreal eps) { return getHermiticity(m.elems, m.numElems, eps); }
// hermiticity of heap matrices is cached
bool util_isHermitian(CompMatr m, qreal eps) {
// compute and record hermiticity if not already known
if (*(m.isApproxHermitian) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxHermitian) = getHermiticity(m.cpuElems, m.numRows, eps);
// eps may have been ignored
return *(m.isApproxHermitian);
}
bool util_isHermitian(DiagMatr m, qreal eps) {
// compute and record hermiticity if not already known
if (*(m.isApproxHermitian) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxHermitian) = getHermiticity(m.cpuElems, m.numElems, eps);
// eps may have been ignored
return *(m.isApproxHermitian);
}
bool util_isHermitian(FullStateDiagMatr m, qreal eps) {
// compute and record hermiticity if not already known
if (*(m.isApproxHermitian) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isApproxHermitian) = getHermiticity(m.cpuElems, m.numElemsPerNode, eps);
// communication may be necessary
if (m.isDistributed)
*(m.isApproxHermitian) = comm_isTrueOnAllNodes(*(m.isApproxHermitian));
// eps may have been ignored
return *(m.isApproxHermitian);
}
/*
* EXPONENTIABLE MATRIX IS NON-ZERO
*/
bool getWhetherNonZero(qcomp* diags, qindex dim, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
for (qindex i=0; i<dim; i++) {
// check each complex element has non-zero abs
if (isApprox(std::abs(diags[i]), 0, eps))
return false;
// note that calc-expec functions which assume
// hermiticity will only consult the real component,
// so its magnitude alone should determine divergence.
// But alas an elem = eps*i will pass the above validation
// yet also be validly Hermitian (imag <= eps), and cause
// real(elem)=0 to be accepted within the matrix. This
// will cause a divergence or divison-by-zero error when
// the matrix is raised to a negative exponent; as this
// function was supposed to detect and prevent! Fixing
// this thoroughly would necessitate creating another
// matrix field, separating when .absIsApproxNonZero and
// .realIsApproxNonZero. But this is revolting and we
// simply accept the above strange scenario as a
// non-validated dge-case.
}
return true;
}
// non-zeroness of fixed-size matrices is always computed afresh
bool util_isApproxNonZero(DiagMatr1 m, qreal eps) { return getWhetherNonZero(m.elems, m.numElems, eps); }
bool util_isApproxNonZero(DiagMatr2 m, qreal eps) { return getWhetherNonZero(m.elems, m.numElems, eps); }
// non-zeroness of heap matrices is cached
bool util_isApproxNonZero(DiagMatr matrix, qreal eps) {
// compute and record whether matrix >= 0 if not already known
if (*(matrix.isApproxNonZero) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(matrix.isApproxNonZero) = getWhetherNonZero(matrix.cpuElems, matrix.numElems, eps);
// eps may be ignored
return *(matrix.isApproxNonZero);
}
bool util_isApproxNonZero(FullStateDiagMatr matrix, qreal eps) {
// compute and record whether matrix >= 0 if not already known
if (*(matrix.isApproxNonZero) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(matrix.isApproxNonZero) = getWhetherNonZero(matrix.cpuElems, matrix.numElemsPerNode, eps);
// communication may be necessary
if (matrix.isDistributed)
*(matrix.isApproxNonZero) = comm_isTrueOnAllNodes(*(matrix.isApproxNonZero));
return *(matrix.isApproxNonZero);
}
/*
* EXPONENTIABLE MATRIX IS NON-NEGATIVE
*/
bool getWhetherRealsAreStrictlyNonNegative(qcomp* diags, qindex dim) {
/// @todo
/// consider multithreading or GPU-accelerating this
/// when caller is big and e.g. has GPU memory
// it may seem like this function should be combined with
// getWhetherRealsAreApproxNonZero() above, or indeed with
// getHermiticity(), since all three are relevant to vali-
// dation of diagonl matrices which can be exponentiated.
// Alas, such as design is complicated by this particular
// property (non-negativeness) being independent of the
// validation epsilon. For example, sometimes it needs to
// be computed even when numerical validation is disabled,
// and does not need recomputing with the epsilon changes.
// check every real component is strictly >= 0
for (qindex i=0; i<dim; i++)
if (std::real(diags[i]) < 0)
return false;
return true;
}
// non-negativity of fixed-size matrices is always computed afresh
bool util_isStrictlyNonNegative(DiagMatr1 m) { return getWhetherRealsAreStrictlyNonNegative(m.elems, m.numElems); }
bool util_isStrictlyNonNegative(DiagMatr2 m) { return getWhetherRealsAreStrictlyNonNegative(m.elems, m.numElems); }
bool util_isStrictlyNonNegative(DiagMatr m) {
// compute and record whether m >= 0 if not already known
if (*(m.isStrictlyNonNegative) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isStrictlyNonNegative) = getWhetherRealsAreStrictlyNonNegative(m.cpuElems, m.numElems);
// eps may be ignored
return *(m.isStrictlyNonNegative);
}
bool util_isStrictlyNonNegative(FullStateDiagMatr m) {
// compute and record whether m >= 0 if not already known
if (*(m.isStrictlyNonNegative) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(m.isStrictlyNonNegative) = getWhetherRealsAreStrictlyNonNegative(m.cpuElems, m.numElemsPerNode);
// communication may be necessary
if (m.isDistributed)
*(m.isStrictlyNonNegative) = comm_isTrueOnAllNodes(*(m.isStrictlyNonNegative));
return *(m.isStrictlyNonNegative);
}
/*
* PAULI STR SUM HERMITICITY
*/
bool util_isHermitian(PauliStrSum sum, qreal eps) {
// check whether all coefficients are real (just like a diagonal matrix)
if (*(sum.isApproxHermitian) == validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
*(sum.isApproxHermitian) = getHermiticity(sum.coeffs, sum.numTerms, eps);
// eps may have been ignored
return *(sum.isApproxHermitian);
}
/*
* KRAUS MAPS
*/
bool util_isCPTP(KrausMap map, qreal eps) {
assert_utilsGivenNonZeroEpsilon(eps);
// use pre-computed CPTP if it exists
if (*(map.isApproxCPTP) != validate_STRUCT_PROPERTY_UNKNOWN_FLAG)
return *(map.isApproxCPTP);
/// @todo
/// if KrausMap is GPU-accelerated, we should maybe
/// instead perform this calculation using the GPU.
/// otherwise, if matrix is large, we should potentially
/// use a multithreaded routine
*(map.isApproxCPTP) = 1;
// check whether each element satisfies Identity = sum dagger(m)*m
for (qindex r=0; r<map.numRows; r++) {
for (qindex c=0; c<map.numRows; c++) {
// calculate (r,c)-th element of sum dagger(m)*m
qcomp elem = 0;
for (int n=0; n<map.numMatrices; n++)
for (qindex k=0; k<map.numRows; k++)
elem += std::conj(map.matrices[n][k][r]) * map.matrices[n][k][c];
// fail if too distant from Identity element...
qreal distSquared = std::norm(elem - (r==c));
if (distSquared > eps) {
// by recording the result and returning immediately
*(map.isApproxCPTP) = 0;
return *(map.isApproxCPTP);
}
}
}
// always true by this point
return *(map.isApproxCPTP);
}
// T can be qcomp*** or vector<vector<vector<qcomp>>>
template <typename T>
void setSuperoperator(qcomp** superop, T matrices, int numMatrices, qindex logMatrixDim) {
/// @todo
/// we initialise the superoperator completely serially, under the assumption that the
/// superoperator will be small in size and initialised infrequently. Still, it would
/// be better to provide backend initialisation functions (OpenMP and CUDA accelerated),
/// called when the superoperator size is above some threshold!
qindex matrixDim = powerOf2(logMatrixDim);
qindex superopDim = matrixDim * matrixDim;
// clear superoperator
for (qindex r=0; r<superopDim; r++)
for (qindex c=0; c<superopDim; c++)
superop[r][c] = 0;
// add each matrix's contribution to the superoperator
for (int n=0; n<numMatrices; n++) {
auto matrix = matrices[n];
// superop += conj(matrix) (tensor) matrix
for (qindex i=0; i<matrixDim; i++)
for (qindex j=0; j<matrixDim; j++)
for (qindex k=0; k<matrixDim; k++)
for (qindex l=0; l<matrixDim; l++) {
qindex r = i*matrixDim + k;
qindex c = j*matrixDim + l;
superop[r][c] += std::conj(matrix[i][j]) * matrix[k][l];
}
}
}
void util_setSuperoperator(qcomp** superop, vector<vector<vector<qcomp>>> matrices, int numMatrices, int numQubits) {
setSuperoperator(superop, matrices, numMatrices, numQubits);
}
void util_setSuperoperator(qcomp** superop, qcomp*** matrices, int numMatrices, int numQubits) {
setSuperoperator(superop, matrices, numMatrices, numQubits);
}
/*
* STRUCT PROPERTY CACHING
*/
std::list<int*> globalStructFieldPtrs(0);
void util_setFlagToUnknown(int* ptr) {
*ptr = validate_STRUCT_PROPERTY_UNKNOWN_FLAG;
}
int* util_allocEpsilonSensitiveHeapFlag() {
int* ptr = cpu_allocHeapFlag(); // may be nullptr
// if failed to alloc, do not add to global list;
// caller will handle validation/error messaging
if (!mem_isAllocated(ptr))
return ptr;
// caller should set ptr to the default "unknown"
// value, but we do so here too just to be safe
util_setFlagToUnknown(ptr);
// store the pointer so that we can reset the
// value to "unknown" when epsilon is changed
globalStructFieldPtrs.push_back(ptr);
return ptr;
}
void util_deallocEpsilonSensitiveHeapFlag(int* ptr) {
// nothing to do if the heap flag wasn't allocated;
// it was never added to the list nor needs freeing
if (!mem_isAllocated(ptr))
return;
globalStructFieldPtrs.remove(ptr);
cpu_deallocHeapFlag(ptr);
}
void util_setEpsilonSensitiveHeapFlagsToUnknown() {
for (auto ptr : globalStructFieldPtrs)
util_setFlagToUnknown(ptr);
}
/*
* DISTRIBUTED ELEMENTS INDEXING
*/
bool util_areAnyVectorElemsWithinNode(int rank, qindex numElemsPerNode, qindex elemStartInd, qindex numInds) {
qindex elemEndIndExcl = elemStartInd + numInds;
qindex nodeStartInd = numElemsPerNode * rank;
qindex nodeEndIndExcl = nodeStartInd + numElemsPerNode;
// 'no' if all targeted elems occur after this node
if (elemStartInd >= nodeEndIndExcl)
return false;
// 'no' if all targeted elems occur before this node
if (elemEndIndExcl <= nodeStartInd)
return false;
// otherwise yes; this node MUST contain one or more targeted elems
return true;
}
util_VectorIndexRange util_getLocalIndRangeOfVectorElemsWithinNode(int rank, qindex numElemsPerNode, qindex elemStartInd, qindex numInds) {
if (!util_areAnyVectorElemsWithinNode(rank, numElemsPerNode, elemStartInd, numInds))
error_nodeUnexpectedlyContainedNoElems();
// global indices of the user's targeted elements
qindex elemEndInd = elemStartInd + numInds;
// global indices of all elements contained in the node
qindex nodeStartInd = numElemsPerNode * rank;
qindex nodeEndInd = nodeStartInd + numElemsPerNode;
// global indices of user's targeted elements which are contained within node
qindex globalRangeStartInd = std::max(elemStartInd, nodeStartInd);
qindex globalRangeEndInd = std::min(elemEndInd, nodeEndInd);
qindex numLocalElems = globalRangeEndInd - globalRangeStartInd;
// local indices of user's targeted elements to overwrite
qindex localRangeStartInd = globalRangeStartInd % numElemsPerNode;
// local indices of user's passed elements that correspond to above
qindex localOffsetInd = globalRangeStartInd - elemStartInd;
return {
.localDistribStartInd = localRangeStartInd,
.localDuplicStartInd = localOffsetInd,
.numElems = numLocalElems
};
}
/*
* GATE PARAMETERS
*/
qreal util_getPhaseFromGateAngle(qreal angle) {
return - angle / 2;
}
/*
* DECOHERENCE FACTORS
*/
qreal util_getOneQubitDephasingFactor(qreal prob) {
return 1 - (2 * prob);
}
qreal util_getTwoQubitDephasingTerm(qreal prob) {
return - 4 * prob / 3;
}
util_Scalars util_getOneQubitDepolarisingFactors(qreal prob) {
// effected where braQubit == ketQubit
qreal facAA = 1 - (2 * prob / 3);
qreal facBB = 2 * prob / 3;
// effected where braQubit != ketQubit
qreal facAB = 1 - (4 * prob / 3);
return {.c1=facAA, .c2=facBB, .c3=facAB, .c4=0}; // c4 ignored
}
util_Scalars util_getTwoQubitDepolarisingFactors(qreal prob) {
return {
.c1 = 1 - (4 * prob / 5),
.c2 = 4 * prob / 15,
.c3 = - (16 * prob / 15),
.c4 = 0 // ignored
};
}
util_Scalars util_getOneQubitPauliChannelFactors(qreal pI, qreal pX, qreal pY, qreal pZ) {
// effected where braQubit == ketQubit
qreal facAA = pI + pZ;
qreal facBB = pX + pY;
// effected where braQubit != ketQubit
qreal facAB = pI - pZ;
qreal facBA = pX - pY;
return {.c1=facAA, .c2=facBB, .c3=facAB, .c4=facBA};
}
util_Scalars util_getOneQubitDampingFactors(qreal prob) {
// we assume 0 < prob < 1 (true even of the inverse channel), so c1 is always real
qreal c1 = std::sqrt(1 - prob);
qreal c2 = 1 - prob;
return {.c1=c1, .c2=c2, .c3=0, .c4=0}; //c3 and c4 ignored
}
qreal util_getMaxProbOfOneQubitDephasing() {
return 1/2.;
}
qreal util_getMaxProbOfTwoQubitDephasing() {
return 3/4.;
}
qreal util_getMaxProbOfOneQubitDepolarising() {
return 3/4.;
}
qreal util_getMaxProbOfTwoQubitDepolarising() {
return 15/16.;
}
// no equivalent function for oneQubitDamping, which
// can accept any valid probability, because we permit