-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathprinter.cpp
More file actions
1456 lines (1050 loc) · 46.7 KB
/
printer.cpp
File metadata and controls
1456 lines (1050 loc) · 46.7 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
* Functions for formatting and outputting strings, used
* primarily by reporters (e.g. reportQureg). A substantial
* amount of logic is dedicated to making outputs look
* extra pretty, managing distributed objects, and
* aesthetically truncating large matrices.
*
* @author Tyson Jones
* @author Erich Essmann (improved OS agnosticism, patched mem-leak)
*/
#include "quest/include/qureg.h"
#include "quest/include/types.h"
#include "quest/include/matrices.h"
#include "quest/include/channels.h"
#include "quest/include/paulis.h"
#include "quest/src/core/printer.hpp"
#include "quest/src/core/errors.hpp"
#include "quest/src/core/memory.hpp"
#include "quest/src/core/bitwise.hpp"
#include "quest/src/core/localiser.hpp"
#include "quest/src/core/utilities.hpp"
#include "quest/src/comm/comm_config.hpp"
#include "quest/src/comm/comm_routines.hpp"
#include "quest/src/gpu/gpu_config.hpp"
#include <type_traits>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <memory>
#include <vector>
#include <tuple>
#include <string>
#include <new>
using std::cout;
using std::endl;
using std::left;
using std::setw;
using std::tuple;
using std::string;
using std::vector;
using std::setfill;
using std::complex;
/*
* PRIVATE AESTHETIC CONSTANTS
*/
const int MIN_SPACE_BETWEEN_DENSE_MATRIX_COLS = 2;
const int SET_SPACE_BETWEEN_DIAG_MATRIX_COLS = 2;
const int MIN_SPACE_BETWEEN_TABLE_COLS = 5;
const int SET_SPACE_BETWEEN_KET_AND_RANK = 2;
// must be kept as single char; use numbers above to change spacing
const char TABLE_SPACE_CHAR = '.';
const char MATRIX_SPACE_CHAR = ' ';
// should not contain newline
const string LABEL_SUFFIX = ":";
const string VDOTS_CHAR = "⋮"; // unicode too wide for char literal
const string DDOTS_CHAR = "⋱";
const string HDOTS_CHAR = "…";
const string HEADER_OPEN_BRACKET = " (";
const string HEADER_CLOSE_BRACKET = "):";
const string HEADER_DELIMITER = ", ";
const string IMAGINARY_UNIT = "i";
/*
* PUBLIC AESTHETIC CONSTATNS
*/
namespace printer_substrings {
string eq = " = ";
string pn = " per node";
string pg = " per gpu";
string ig = " in gpu";
string pm = " per machine";
string bt = "2^";
string na = "N/A";
string un = "unknown";
}
/*
* USER-CONFIGURABLE GLOBALS
*/
// user truncation of printed quregs, matrices, pauli-strings, etc
qindex global_maxNumPrintedRows = (1 << 5);
qindex global_maxNumPrintedCols = 4;
void printer_setMaxNumPrintedScalars(qindex numRows, qindex numCols) {
global_maxNumPrintedRows = numRows;
global_maxNumPrintedCols = numCols;
}
// user configuration of printed scalars
int global_maxNumPrintedSigFigs = 5;
void printer_setMaxNumPrintedSigFig(int numSigFigs) {
global_maxNumPrintedSigFigs = numSigFigs;
}
// user configuration of trailing newlines after reporters
int global_numTrailingNewlines = 2;
void printer_setNumTrailingNewlines(int numNewlines) {
global_numTrailingNewlines = numNewlines;
}
int printer_getNumTrailingNewlines() {
return global_numTrailingNewlines;
}
/*
* TYPE NAME STRINGS
*/
// try safely check for de-mangler library
#if defined __has_include
#if __has_include (<cxxabi.h>)
#include <cxxabi.h>
#define DEMANGLE_TYPE true
#else
#define DEMANGLE_TYPE false
#endif
// fall-back to dangerous compiler-specific check (we know MSVC doesn't mangle)
#elif ! defined _MSC_VER
// #warning command safe in non-MSVC compiler
#warning "Attempting to include compiler-specific library <cxxabi.h>"
#include <cxxabi.h>
#define DEMANGLE_TYPE true
// otherwise just give up; reporters might print mangled types
#else
#define DEMANGLE_TYPE false
#endif
// macros for printing multi-word macros (necessary indirection)
#define GET_STR_INTERNAL(x) #x
#define GET_STR(x) GET_STR_INTERNAL(x)
inline std::string demangleTypeName(const char* mangledName) {
#if defined(__GNUC__) || defined(__clang__)
int status = 0;
// __cxa_demangle returns a malloc'd string, so we wrap it in a unique_ptr
// for automatic cleanup. (The custom deleter calls free().)
std::unique_ptr<char, void(*)(void*)> demangled(
abi::__cxa_demangle(mangledName, nullptr, nullptr, &status),
std::free
);
if (status == 0 && demangled) {
return demangled.get();
} else {
// fall back to the mangled name
return mangledName;
}
#else
// e.g. MSVC or unknown compiler: no standard demangler
return mangledName;
#endif
}
// type T can be anything in principle, although it's currently only used for qcomp
template <typename T>
std::string getTypeName(T _unused) {
// For MSVC, typeid(T).name() typically returns something like "class Foo"
// or "struct Foo", but it's still not exactly "Foo".
// For GCC/Clang, you get a raw "mangled" name, e.g. "N3FooE".
const char* rawName = typeid(T).name();
// We'll try to demangle if we can:
return demangleTypeName(rawName);
}
string printer_getQcompType() {
qcomp x;
return getTypeName(x);
}
string printer_getQrealType() {
// more portable than getTypeName
return GET_STR( FLOAT_TYPE );
}
string printer_getQindexType() {
// more portable than getTypeName
return GET_STR( INDEX_TYPE );
}
string printer_getFloatPrecisionFlag() {
return GET_STR( FLOAT_PRECISION );
}
/*
* NUMBER STRINGIFYING
*
* which is precision and type agnostic - i.e. we can stringify non-qcomp
* and non-qreal numbers given by users or the backend
*/
// type T can be any number, e.g. int, qindex, float, double, long double
template <typename T>
string floatToStr(T num, bool hideSign=false, int overrideSigFigs=-1) {
// write to stream (instead of calling to_string()) to auto-use scientific notation
std::stringstream buffer;
// ensure +- is not shown if forced hidden
if (hideSign) {
buffer << std::noshowpos;
if (num < 0)
num *= -1;
}
// impose user-set significant figures, unless caller overrode
int sigFigs = (overrideSigFigs != -1)? overrideSigFigs : global_maxNumPrintedSigFigs;
buffer << std::setprecision(sigFigs);
// get string of e.g. 0, 1, 0.1, 1.2e-05, -1e+05
buffer << num;
string out = buffer.str();
// remove superflous 0 prefix in scientific notation exponent
size_t ePos = out.find('e');
if (ePos != string::npos && (out[ePos + 2] == '0'))
out.erase(ePos + 2, 1);
// permit superflous + prefix of scientific notatio exponent, e.g. 2e+6
return out;
}
// type T can be precision decimal (independent of qreal) i.e. float, double, long double
template <typename T>
string printer_toStr(complex<T> num) {
// precise 0 is rendered as a real integer
if (std::real(num) == 0 && std::imag(num) == 0)
return "0";
// real complex-floats neglect imag component
if (std::imag(num) == 0)
return floatToStr(std::real(num));
// imaginary complex-floats neglect real component entirely (instead of 0+3i)
string realStr = (std::real(num) == 0)? "" : floatToStr(std::real(num));
// scientific-notation real component (when followed by any imaginary component) gets brackets
if (realStr.find('e') != string::npos)
realStr = '(' + realStr + ')';
// -1i is abbreviated to -i
if constexpr (std::is_signed_v<T>)
if (std::imag(num) == -1)
return realStr + "-" + IMAGINARY_UNIT;
// +1i is abbreviated to +i, although the sign is dropped if there's no preceeding real component
if (std::imag(num) == 1)
return realStr + ((std::real(num) == 0)? IMAGINARY_UNIT : ("+" + IMAGINARY_UNIT));
// get imag component string but without sign
string imagStr = floatToStr(std::imag(num), true);
// scientific-notation components always get wrapped in paranthesis
if (imagStr.find('e') != string::npos)
imagStr = '(' + imagStr + ')';
// negative imag components always get - sign prefix
if (std::imag(num) < 0)
imagStr = '-' + imagStr;
// positive imag components only get + sign prefix if they follow a real component
if (std::imag(num) > 0 && std::real(num) != 0)
imagStr = '+' + imagStr;
// all imag components end in 'i'
imagStr += IMAGINARY_UNIT;
return realStr + imagStr;
}
// explicitly instantiate all publicly passable types
template string printer_toStr<int>(complex<int> num);
template string printer_toStr<long int>(complex<long int> num);
template string printer_toStr<long long int>(complex<long long int> num);
template string printer_toStr<unsigned>(complex<unsigned> num);
template string printer_toStr<long unsigned>(complex<long unsigned> num);
template string printer_toStr<long long unsigned>(complex<long long unsigned> num);
template string printer_toStr<float>(complex<float> num);
template string printer_toStr<double>(complex<double> num);
template string printer_toStr<long double>(complex<long double> num);
// alias as toStr() just for internal brevity
// (this seems backward; ordinarily we would define toStr() as
// the templated inner-function and define concretely-typed public
// printer_toStr() overloads. This current implementation, where
// we expose the templated printer_toStr() in the header, avoids
// polluting the header with the above precision-agnostic
// instantiations (which would become overloads). Stinky!)
template <class T> string toStr(T num) {
return printer_toStr(num);
}
/*
* PRIMITIVE PRINTING
*
* used by other files which need to directly print
* unformatted strings (from root node only)
*/
void print(const char* str) {
if (!comm_isRootNode())
return;
// never prints a trailing newline
cout << str;
}
void print(string str) {
print(str.data());
}
void print(qcomp num) {
print(toStr(num));
}
/*
* NEWLINE PRINTING
*/
void print_newlines() {
assert_printerGivenNonNegativeNumNewlines();
print(string(global_numTrailingNewlines, '\n'));
}
void print_oneFewerNewlines() {
assert_printerGivenPositiveNumNewlines();
print(string(global_numTrailingNewlines - 1, '\n'));
}
/*
* STRINGIFYING FUNCTIONS
*
* some of which are exposed to other files, while others
* are private convenience functions to prepare substrings
*/
string printer_getMemoryWithUnitStr(size_t numBytes) {
// retain "bytes" instead of "B" since more recognisable
vector<string> units = {"bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"};
// unit sizes (in bytes) may overflow; but then so too will numBytes
vector<size_t> sizes(units.size());
for (size_t i=0; i<units.size(); i++)
sizes[i] = powerOf2(10 * i); // = 1024^i
// find the biggest unit for which numBytes/sizes[ind] > 1
int ind = 1;
while (numBytes > sizes[ind])
ind++;
ind--;
// express numBytes in terms of new unit, forcefully rounding to 3 sig-figs max,
// except when the chosen unit is bytes (then we permit all 4 digits)
qreal frac = numBytes / static_cast<qreal>(sizes[ind]);
return floatToStr(frac, false, (ind==0)? 4 : 3) + " " + units[ind];
}
string getTableTitleStr(string title) {
return "[" + title + "]";
}
string getRankStr(int rank) {
return "[node " + toStr(rank) + "]";
}
string getKrausOperatorIndStr(qindex ind) {
return "[matrix " + toStr(ind) + "]";
}
vector<string> getBasisKets(qindex startInd, qindex numInds) {
vector<string> kets(numInds);
for (qindex i=0; i<numInds; i++)
kets[i] = std::string("|") + toStr(i+startInd) + std::string("⟩");
return kets;
}
string getNumQubitsStr(int numQubits) {
// e.g. "1 qubit" or "2 qubits"
return toStr(numQubits) + " qubit" + (numQubits>1? "s":"");
}
string getQuregTypeStr(Qureg qureg) {
// never pluralise qubit here because of following word
return toStr(qureg.numQubits) + " qubit " + (qureg.isDensityMatrix? "density matrix" : "statevector");
}
string getProductStr(qindex a, qindex b) {
// e.g. "4x3"
return toStr(a) + "x" + toStr(b);
}
string getNumMatrixElemsStr(qindex dim, bool isDiag, int numNodes) {
// we do not bother handling the dim=1 non-plural case, because it
// never occurs! We always receive power-of-2 dimension matrices
// e.g. "2 qcomps" or "2x2 qcomps"
string out = (isDiag? toStr(dim) : getProductStr(dim, dim)) + " qcomps"; // never non-plural
// FullStateDiagMatr may be distributed over >1 numNodes (for other matrix types, numNodes=1 always)
if (numNodes > 1)
out += " over " + toStr(numNodes) + " nodes";
return out;
}
string getMemoryCostsStr(size_t numBytesPerNode, bool isDistrib, bool isGpu) {
using namespace printer_substrings;
// when data is GPU-accelerated, we report all memory as being
// in the GPU; this isn't exactly true, since the GPU VRAM will
// not contain struct fields nor KrausMap matrices. However,
// the difference is tiny and unimportant, and shrinks exponentially
// (or quadratically, for KrausMap) with increasing number of qubits
string mem = printer_getMemoryWithUnitStr(numBytesPerNode);
if (isDistrib && isGpu)
return mem + pg;
if (isDistrib)
return mem + pn;
if (isGpu)
return mem + ig;
return mem;
}
/*
* INTERNAL CONVENIENCE TYPES
*
* used for compactly passing arguments to internal
* functions which format and print 1D and 2D matrices
*/
using qcompmatr = vector<vector<qcomp>>;
using stringmatr = vector<vector<string>>;
stringmatr getMatrixOfQcompStrings(qcompmatr in) {
if (in.empty())
return stringmatr(0);
size_t numRows = in.size();
size_t numCols = in[0].size();
stringmatr out(numRows, vector<string>(numCols));
for (size_t r=0; r<numRows; r++)
for (size_t c=0; c<numCols; c++)
out[r][c] = toStr(in[r][c]);
return out;
}
/*
* PRINTING MATRICES DIVIDED INTO QUADRANTS
*
* where the quadrants are those resulting
* from horizontally and vertically truncating
* the matrices. The functions in this section
* are compatible with both 1D and 2D data
* (vectors become single-column matrices)
*/
size_t getMaxWidthOfColumn(stringmatr matr, size_t col) {
size_t maxWidth = 0;
for (size_t r=0; r<matr.size(); r++) {
size_t width = matr[r][col].size();
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
vector<size_t> getMaxWidthOfColumns(stringmatr upper, stringmatr lower) {
if (upper.empty())
return {};
size_t numCols = upper[0].size(); // matches lower, unless lower empty
vector<size_t> maxWidths(numCols, 0);
for (size_t c=0; c<numCols; c++)
maxWidths[c] = std::max(
getMaxWidthOfColumn(upper, c),
getMaxWidthOfColumn(lower, c)); // 0 if lower empty
return maxWidths;
}
void expandMaxWidthsAccordingToLabels(vector<size_t> &widths, vector<string> &labels) {
if (labels.empty())
return;
for (size_t c=0; c<widths.size(); c++) {
size_t labelWidth = labels[c].size();
if (labelWidth > widths[c])
widths[c] = labelWidth;
}
}
void printPerRowIndent(string baseIndent, size_t row, string indentPerRow) {
cout << baseIndent;
// K. I. S. S.
for (size_t r=0; r<row; r++)
cout << indentPerRow;
}
void printRowInTwoQuadrants(
vector<string> leftRow, vector<size_t> leftColWidths,
vector<string> rightRow, vector<size_t> rightColWidths
) {
// print left portion of row
for (size_t c=0; c<leftRow.size(); c++)
cout << left << setw(leftColWidths[c] + MIN_SPACE_BETWEEN_DENSE_MATRIX_COLS) << setfill(MATRIX_SPACE_CHAR)
<< leftRow[c];
// finish without printing trailing newline if there is no right portion
if (rightRow.empty())
return;
// draw ellipsis; left-spacer already applied by previous amp
string spacer = string(MIN_SPACE_BETWEEN_DENSE_MATRIX_COLS, MATRIX_SPACE_CHAR);
cout << HDOTS_CHAR << spacer;
// print right portion
for (size_t c=0; c<rightRow.size(); c++)
cout << left << setw(rightColWidths[c] + MIN_SPACE_BETWEEN_DENSE_MATRIX_COLS) << setfill(MATRIX_SPACE_CHAR)
<< rightRow[c];
// do not print a trailing new line; caller may wish to append more characters
}
void printContiguousRowsInTwoQuadrants(
stringmatr left, vector<size_t> leftColWidths,
stringmatr right, vector<size_t> rightColWidths,
vector<string> rowLabels,
string indent, string indentPerRow, size_t rowOffsetForIndent
) {
for (size_t r=0; r<left.size(); r++) {
printPerRowIndent(indent, r + rowOffsetForIndent, indentPerRow);
auto rightRow = (right.empty())? vector<string>{} : right[r];
printRowInTwoQuadrants(left[r], leftColWidths, rightRow, rightColWidths);
// print optional row label, using trailing space left by above row print
cout << (rowLabels.empty()? "" : rowLabels[r]);
cout << endl;
}
}
void printMatrixInFourQuadrants(
qcompmatr upperLeft, qcompmatr upperRight,
qcompmatr lowerLeft, qcompmatr lowerRight,
vector<string> leftColLabels, vector<string> rightColLabels, // shown above the first row
vector<string> upperRowLabels, vector<string> lowerRowLabels, // shown right of the last column
string baseIndent, string indentPerRow, string verticalEllipsis
) {
// this function prints a matrix which has been prior divided into one, two or four
// quadrants, resulting from reporter truncation of the original matrix. It can be
// used to print truncated (or non-truncated) non-square matrices, horizontal and
// vertical vectors, diagonal matrices, and lists of scalars (e.g. Pauli coefficients)
// the below preconditions are assumed but not enforced:
// - it is valid for lowerLeft to be empty, implying upperLeft contains entire columns;
// in that scenario, lowerRight must also be empty
// - it is valid for upperRight to be empty, implying upperLeft contains entire rows;
// in that scenario, lowerRight must also be empty
// - it is valid for upperRight=lowerLeft=lowerRight to be empty, implying upperLeft
// contains the entire matrix
// - it is valid for qcompmatr={} (empty), but it is INVALID to be {{}} (reported non-empty)
// - it is INVALID for any qcompmatr to have an inconsistent number of columns across its rows
// - it is INVALID for upperLeft and lowerLeft to differ in #columns, though #rows can vary;
// the same applies to upperRight and lowerRight
// - it is INVALID for upperLeft and upperRight to differ in #rows, though #columns can vary;
// the same applies to lowerLeft and lowerRight
// - it is INVALID for upperLeft to ever be empty
// - it is valid for leftColLabels=rightColLabels to be empty, but otherwise...
// - leftColLabels must match the #cols in upperLeft (can contain empty strings)
// - rightColLabels must similarly match the #cols in upperRight
// - it is valid for upperRight=lowerRight to be empty, while lowerLeft is not empty;
// this would be the case when printing a vector. Non-distributed vectors like this
// are fine, although distributed vectors should use a separate, bespoke routine since
// this function cannot display labeled ranks spanning vertically
if (!comm_isRootNode())
return;
// prepare element strings
stringmatr upperLeftStrings = getMatrixOfQcompStrings(upperLeft);
stringmatr upperRightStrings = getMatrixOfQcompStrings(upperRight);
stringmatr lowerLeftStrings = getMatrixOfQcompStrings(lowerLeft);
stringmatr lowerRightStrings = getMatrixOfQcompStrings(lowerRight);
// decide column widths
vector<size_t> leftColWidths = getMaxWidthOfColumns(upperLeftStrings, lowerLeftStrings);
vector<size_t> rightColWidths = getMaxWidthOfColumns(upperRightStrings, lowerRightStrings);
// including consideration of column labels
expandMaxWidthsAccordingToLabels(leftColWidths, leftColLabels);
expandMaxWidthsAccordingToLabels(rightColWidths, rightColLabels);
// optionally print all column labels
if (!leftColLabels.empty()) {
cout << baseIndent;
printRowInTwoQuadrants(leftColLabels, leftColWidths, rightColLabels, rightColWidths);
cout << endl;
}
// print the upper rows
printContiguousRowsInTwoQuadrants(
upperLeftStrings, leftColWidths,
upperRightStrings, rightColWidths,
upperRowLabels,
baseIndent, indentPerRow, 0);
// finish immediately if there are no lower rows (matrix wasn't vertically truncated)
if (lowerLeftStrings.empty())
return;
// otherwise, draw ellipsis, aligned (approx) in the midpoint of leftmost column (which may be indented)
printPerRowIndent(baseIndent, upperLeft.size(), indentPerRow);
cout << string(leftColWidths[0]/2, MATRIX_SPACE_CHAR) << verticalEllipsis << endl;
// print the lower rows (continuing indentation from upper)
printContiguousRowsInTwoQuadrants(
lowerLeftStrings, leftColWidths,
lowerRightStrings, rightColWidths,
lowerRowLabels,
baseIndent, indentPerRow, upperLeft.size() + 1); // +1 for ellipsis
}
/*
* FUNCTIONS TO DIVIDE A MATRIX INTO QUADRANTS
*
* as per the user's printing truncation thresholds.
* These functions decide how to divide a matrix or
* vector into one, two or four quadrants (or for
* vectors, at most two quadrants) for subsequent
* pretty printing
*/
struct MatrixQuadrantInds {
qindex numUpperLeftRows=0, numUpperRightRows=0;
qindex numLowerLeftRows=0, numLowerRightRows=0;
qindex numUpperLeftCols=0, numUpperRightCols=0;
qindex numLowerLeftCols=0, numLowerRightCols=0;
qindex rightStartCol=0;
qindex lowerStartRow=0;
// these are always fixed at 0, but included for clarity
qindex leftStartCol = 0;
qindex upperStartRow = 0;
};
MatrixQuadrantInds getTruncatedMatrixQuadrantInds(qindex numRows, qindex numCols) {
MatrixQuadrantInds inds;
// according to the user-set truncations
qindex maxNumLeftCols = global_maxNumPrintedCols / 2; // floors
qindex maxNumRightCols = global_maxNumPrintedCols - maxNumLeftCols;
qindex maxNumUpperRows = global_maxNumPrintedRows / 2; // floors
qindex maxNumLowerRows = global_maxNumPrintedRows - maxNumUpperRows;
// may be ignored (and will unimportantly underflow when not truncating)
inds.rightStartCol = numCols - maxNumRightCols;
inds.lowerStartRow = numRows - maxNumLowerRows;
// decide among four possible quadrant population configurations;
// this code can be significantly shortened but we leave it explicit
// for clarity, and so that *NumRows=0 <=> *NumCols=0
if (numRows <= global_maxNumPrintedRows && numCols <= global_maxNumPrintedCols) {
// upper left contains entire matrix
inds.numUpperLeftRows = numRows; inds.numUpperLeftCols = numCols;
} else if (numRows <= global_maxNumPrintedRows) {
// matrix divided into upper left and upper right (bottoms empty)
inds.numUpperLeftRows = numRows; inds.numUpperLeftCols = maxNumLeftCols;
inds.numUpperRightRows = numRows; inds.numUpperRightCols = maxNumRightCols;
} else if (numCols <= global_maxNumPrintedCols) {
// matrix divided into upper left and lower left (rights empty)
inds.numUpperLeftRows = maxNumUpperRows; inds.numUpperLeftCols = numCols;
inds.numLowerLeftRows = maxNumLowerRows; inds.numLowerLeftCols = numCols;
} else {
// matrix divided into into four quadrants
inds.numUpperLeftRows = maxNumUpperRows; inds.numUpperLeftCols = maxNumLeftCols;
inds.numUpperRightRows = maxNumUpperRows; inds.numUpperRightCols = maxNumRightCols;
inds.numLowerLeftRows = maxNumLowerRows; inds.numLowerLeftCols = maxNumLeftCols;
inds.numLowerRightRows = maxNumLowerRows; inds.numLowerRightCols = maxNumRightCols;
}
return inds;
}
/*
* FUNCTIONS TO POPULATE THE QUADRANTS
*
* the sizes of which are decided by the above functions.
* The below functions invoke communication and GPU-to-CPU
* copying as necessary to populate the quadrants on the
* root node (that which subsequently prints them)
*/
void allocateMatrixQuadrants(MatrixQuadrantInds inds, qcompmatr &ul, qcompmatr &ur, qcompmatr &ll, qcompmatr &lr) {
util_tryAllocMatrix(ul, inds.numUpperLeftRows, inds.numUpperLeftCols, error_printerFailedToAllocTempMemory);
util_tryAllocMatrix(ur, inds.numUpperRightRows, inds.numUpperRightCols, error_printerFailedToAllocTempMemory); // may be zero-size
util_tryAllocMatrix(ll, inds.numLowerLeftRows, inds.numLowerLeftCols, error_printerFailedToAllocTempMemory); // may be zero-size
util_tryAllocMatrix(lr, inds.numLowerRightRows, inds.numLowerRightCols, error_printerFailedToAllocTempMemory); // may be zero-size
}
void populateSingleColumnQcompmatr(qcompmatr &matr, qindex startInd, PauliStrSum sum) {
// matr is single-column, and has been prior resized such that
// even before population, matr.size() is non-zero unless it is
// intended to stay empty
size_t numCoeffs = matr.size(); // numRows
if (numCoeffs == 0)
return;
// serially copy the CPU-only, non-distributed coefficients
for (size_t i=0; i<numCoeffs; i++)
matr[i][0] = sum.coeffs[startInd + i];
}
// T can be any 1D type, i.e. Qureg (.isDensity=0), FullStateDiagMatr, DiagMatr1, DiagMatr2, DiagMatr
template <class T>
void populateSingleColumnQcompmatr(qcompmatr &matr, qindex startInd, T obj) {
// matr is single-column, and has been prior resized such that
// even before population, matr.size() is non-zero unless it is
// intended to stay empty
size_t numAmps = matr.size(); // numRows
if (numAmps == 0)
return;
// prepare temp memory where adjacent columns are adjacent elems (unlike matr)
vector<qcomp> column;
util_tryAllocVector(column, numAmps, error_printerFailedToAllocTempMemory);
// populate temp memory, potentially invoking CPU-GPU copying and communication...
if constexpr (util_isFullStateDiagMatr<T>()) {
localiser_fullstatediagmatr_getElems(column.data(), obj, startInd, numAmps);
} else if constexpr (util_isQuregType<T>()) {
localiser_statevec_getAmps(column.data(), obj, startInd, numAmps);
// or invoking nothing...
} else if constexpr (util_isFixedSizeMatrixType<T>()) {
column = vector<qcomp>(obj.elems, obj.elems + numAmps);
// or invoking merely a GPU-CPU copy
} else {
column = vector<qcomp>(obj.cpuElems, obj.cpuElems + numAmps);
auto gpuPtr = util_getGpuMemPtr(obj);
if (mem_isAllocated(gpuPtr))
gpu_copyGpuToCpu(gpuPtr, column.data(), numAmps);
}
// overwrite matr; serial iteration is fine since we assume few elems printed
for (size_t i=0; i<numAmps; i++)
matr[i][0] = column[i];
}
void populateManyColumnQcompmatr(qcompmatr &matr, qindex startRow, qindex startCol, Qureg qureg) {
// matr has been prior resized such that even before
// population, matr.size() is non-zero unless it is
// intended to stay empty
if (matr.size() == 0)
return;
// prepare list of pointers to matr rows, compatible with localiser 2D input format
vector<qcomp*> ptrs;
util_tryAllocVector(ptrs, matr.size(), error_printerFailedToAllocTempMemory);
for (size_t r=0; r<matr.size(); r++)
ptrs[r] = matr[r].data();
// overwrite matr (throug ptrs), which may trigger communication and GPU-to-CPU copying.
// note this achieves node consensus; every node populates their matr, which is much more
// demanding than only the root note, however we expect this is not a big deal; live printing
// in distributed settings is exceptionally rare and will print small, tractable subsets
localiser_densmatr_getAmps(ptrs.data(), qureg, startRow, startCol, matr.size(), matr[0].capacity());
}
// T can be qcomp** or qcomp(*)[]
template <typename T>
void populateManyColumnQcompmatrFromPtr(qcompmatr &matr, qindex startRow, qindex startCol, T elems) {
if (matr.size() == 0)
return;
// serially copy elements; performance is no issue here
for (size_t r=0; r<matr.size(); r++)
for (size_t c=0; c<matr[r].size(); c++)
matr[r][c] = elems[r+startRow][c+startCol];
}
// T can be 2D matrix type, i.e CompMatr, CompMatr1, CompMatr2, SuperOp
template <typename T>
void populateManyColumnQcompmatr(qcompmatr &matr, qindex startRow, qindex startCol, T obj) {
if constexpr (util_isFixedSizeMatrixType<T>())
populateManyColumnQcompmatrFromPtr(matr, startRow, startCol, obj.elems);
else {
// even though matrix GPU memory should be unchanged, we copy it
// over to CPU to overwrite any changes the user may have done
// to the CPU matrix; this is so that the displayed matrix is
// definitely consistent with the simulated backend. Because
// we expect square matrices to be small, we do not bother copying
// the specifically displayed sub-matrix (like we do for Qureg and
// FullStateDiagMatr); instead, we just copy over the whole matrix.
if constexpr (util_isHeapMatrixType<T>()) {
auto gpuPtr = util_getGpuMemPtr(obj);
if (mem_isAllocated(gpuPtr))
gpu_copyGpuToCpu(obj);
}
populateManyColumnQcompmatrFromPtr(matr, startRow, startCol, obj.cpuElems);
}
}
void populateMatrixQuadrants(MatrixQuadrantInds inds, qcompmatr &ul, qcompmatr &ur, qcompmatr &ll, qcompmatr &lr, Qureg obj) {
// dense matrices can populate as many as 4 quadrants
if (obj.isDensityMatrix) {
populateManyColumnQcompmatr(ul, inds.upperStartRow, inds.leftStartCol, obj);
populateManyColumnQcompmatr(ur, inds.upperStartRow, inds.rightStartCol, obj);
populateManyColumnQcompmatr(ll, inds.lowerStartRow, inds.leftStartCol, obj);
populateManyColumnQcompmatr(lr, inds.lowerStartRow, inds.rightStartCol, obj);
// but vectors always become 1 or 2 quadrants (the left, as a potentially split column)
} else {
populateSingleColumnQcompmatr(ul, inds.upperStartRow, obj);
populateSingleColumnQcompmatr(ll, inds.lowerStartRow, obj);
}
}
// T can be all 1D and 2D types, i.e. CompMatr/1/2, DiagMatr1/2, FullStateDiagMatr, SuperOp,
// and can furthermore be PauliStrSum (in order to print the real coefficients).
// Importantly, this excludes KrausMap which is handled explicitly, and annoyingly, Qureg,
// which must be handled seperately above (because it must runtime branch, not compile-time)
template <class T>
void populateMatrixQuadrants(MatrixQuadrantInds inds, qcompmatr &ul, qcompmatr &ur, qcompmatr &ll, qcompmatr &lr, T obj) {
// dense matrices can populate as many as 4 quadrants
if constexpr (util_isDenseMatrixType<T>()) {
populateManyColumnQcompmatr(ul, inds.upperStartRow, inds.leftStartCol, obj);
populateManyColumnQcompmatr(ur, inds.upperStartRow, inds.rightStartCol, obj);
populateManyColumnQcompmatr(ll, inds.lowerStartRow, inds.leftStartCol, obj);
populateManyColumnQcompmatr(lr, inds.lowerStartRow, inds.rightStartCol, obj);
// but vectors always become 1 or 2 quadrants (the left, as a potentially split column)
} else {
populateSingleColumnQcompmatr(ul, inds.upperStartRow, obj);
populateSingleColumnQcompmatr(ll, inds.lowerStartRow, obj);
}
}
/*
* PRINTING DENSE MATRICES