-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathBlockUniTensor.cpp
More file actions
2091 lines (1859 loc) · 83.4 KB
/
BlockUniTensor.cpp
File metadata and controls
2091 lines (1859 loc) · 83.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
#include "UniTensor.hpp"
#include "Accessor.hpp"
#include "utils/utils.hpp"
#include "linalg.hpp"
#include "Generator.hpp"
#include <vector>
#include "utils/vec_clone.hpp"
#include "utils/vec_print.hpp"
#include "utils/vec_concatenate.hpp"
#include <map>
#include <boost/unordered_map.hpp>
#include <stack>
using namespace std;
#ifdef BACKEND_TORCH
#else
namespace cytnx {
typedef Accessor ac;
void BlockUniTensor::Init(const std::vector<Bond> &bonds, const std::vector<string> &in_labels,
const cytnx_int64 &rowrank, const unsigned int &dtype,
const int &device, const bool &is_diag, const bool &no_alloc,
const std::string &name) {
this->_name = name;
// the entering is already check all the bonds have symmetry.
// need to check:
// 1. the # of symmetry and their type across all bonds
// 2. check if all bonds are non regular:
// check Symmetry for all bonds
cytnx_uint32 N_symmetry = bonds[0].Nsym();
vector<Symmetry> tmpSyms = bonds[0].syms();
cytnx_uint32 N_ket = 0;
for (cytnx_uint64 i = 0; i < bonds.size(); i++) {
// check
cytnx_error_msg(
bonds[i].type() == BD_REG,
"[ERROR][BlockUniTensor] All bonds must be tagged for UniTensor with symmetries.%s", "\n");
cytnx_error_msg(
bonds[i]._impl->_degs.size() == 0,
"[ERROR][BlockUniTensor] All bonds must be in new format for BlockUniTensor!.%s", "\n");
// check rank-0 bond:
cytnx_error_msg(bonds[i].dim() == 0,
"[ERROR][BlockUniTensor] All bonds must have dimension >=1%s", "\n");
// check symmetry and type:
cytnx_error_msg(bonds[i].Nsym() != N_symmetry,
"[ERROR][BlockUniTensor] inconsistant # of symmetry at bond: %d. # of "
"symmetry should be %d\n",
i, N_symmetry);
for (cytnx_uint32 n = 0; n < N_symmetry; n++) {
cytnx_error_msg(bonds[i].syms()[n] != tmpSyms[n],
"[ERROR][BlockUniTensor] symmetry mismatch at bond: %d, %s != %s\n", n,
bonds[i].syms()[n].stype_str().c_str(), tmpSyms[n].stype_str().c_str());
}
N_ket += cytnx_uint32(bonds[i].type() == bondType::BD_KET);
}
// check rowrank:
// cytnx_error_msg((N_ket < 1) || (N_ket > bonds.size() - 1),
// "[ERROR][BlockUniTensor] must have at least one ket-bond and one
// bra-bond.%s",
// "\n");
if (rowrank == -1) {
this->_rowrank = N_ket;
// this->_inner_rowrank = N_ket;
} else {
if (is_diag) {
cytnx_error_msg(rowrank != 1,
"[ERROR][BlockUniTensor] rowrank must be = 1 when is_diag = true.%s", "\n");
} else {
cytnx_error_msg((rowrank < 0) || (rowrank > bonds.size()),
"[ERROR][BlockUniTensor] rowrank must be >=0 and <=rank.%s", "\n");
}
this->_rowrank = rowrank;
// this->_inner_rowrank = rowrank;
// update braket_form >>>
}
// check labels:
if (in_labels.size() == 0) {
for (cytnx_int64 i = 0; i < bonds.size(); i++) this->_labels.push_back(to_string(i));
} else {
// check bonds & labels dim
cytnx_error_msg(bonds.size() != in_labels.size(), "%s",
"[ERROR] labels must have same length as # of bonds.");
std::vector<string> tmp = vec_unique(in_labels);
cytnx_error_msg(tmp.size() != in_labels.size(),
"[ERROR] labels cannot contain duplicated elements.%s", "\n");
this->_labels = in_labels;
}
// cytnx_error_msg(is_diag,"[ERROR][BlockUniTensor] Cannot set is_diag=true when the UniTensor
// is with symmetry.%s","\n");
if (is_diag) {
cytnx_error_msg(bonds.size() != 2,
"[ERROR][BlockUniTensor] is_diag = true must be rank-2 with one in-bond and "
"one out-bond.%s",
"\n");
cytnx_error_msg(
bonds[0].type() == bonds[1].type(),
"[ERROR][BlockUniTensor] is_diag=true must have one in-bond and oue out-bond.%s", "\n");
if (rowrank != 1, "[ERROR][BlockUniTensor] is_diag = true must have rowrank=1.%s", "\n")
;
// checking basis!
cytnx_error_msg(
bonds[0].redirect() != bonds[1],
"[ERROR][BlockUniTensor] is_diag=true the in-bond and out-bond basis must match!%s", "\n");
}
this->_is_diag = is_diag;
// copy bonds, otherwise it will share objects:
this->_bonds = vec_clone(bonds);
this->_is_braket_form = this->_update_braket();
// vector<cytnx_uint64> blocklens;
// vector<vector<cytnx_uint64>> blocksizes;
// cytnx_uint64 totblocksize = 0;
if (this->_is_diag) {
for (int b = 0; b < this->_bonds[0].qnums().size(); b++) {
this->_inner_to_outer_idx.push_back({(cytnx_uint64)b, (cytnx_uint64)b});
if (!no_alloc) {
this->_blocks.push_back(zeros(this->_bonds[0]._impl->_degs[b], dtype, device));
} else {
this->_blocks.push_back(Tensor({this->_bonds[0]._impl->_degs[b]}, dtype, device, false));
}
}
} else {
// checking how many blocks are there, and the size:
std::vector<cytnx_uint64> Loc(this->_bonds.size(), 0);
std::vector<cytnx_int64> tot_qns(
this->_bonds[0].Nsym()); // use first bond to determine symmetry size
std::vector<cytnx_uint64> size(this->_bonds.size());
bool fin = false;
while (1) {
// get elem
// cout << "start!" << endl;
// cytnx::vec_print_simple(std::cout , Loc);
this->_fx_get_total_fluxs(Loc, this->_bonds[0].syms(), tot_qns);
// std::cout << "Loc: ";
// cytnx::vec_print_simple(std::cout, Loc);
// std::cout << "tot_flx: ";
// cytnx::vec_print_simple(std::cout, tot_qns);
// if exists:
if (std::all_of(tot_qns.begin(), tot_qns.end(), [](const int &i) { return i == 0; })) {
// get size & init block!
if (!no_alloc) {
// cytnx_uint64 blockNelem = 1;
for (cytnx_int32 i = 0; i < Loc.size(); i++) {
size[i] = this->_bonds[i]._impl->_degs[Loc[i]];
// blockNelem *= size[i];
}
this->_blocks.push_back(zeros(size, dtype, device));
// blocklens.push_back(blockNelem);
// blocksizes.push_back(size);
// totblocksize += blockNelem;
} else {
for (cytnx_int32 i = 0; i < Loc.size(); i++) {
size[i] = this->_bonds[i]._impl->_degs[Loc[i]];
}
this->_blocks.push_back(Tensor(size, dtype, device, false));
}
// push its loc
this->_inner_to_outer_idx.push_back(Loc);
}
while (Loc.size() != 0) {
if (Loc.back() == this->_bonds[Loc.size() - 1]._impl->_qnums.size() - 1) {
Loc.pop_back();
continue;
} else {
Loc.back() += 1;
// cout << "+1 at loc:" << Loc.size()-1 <<endl;
while (Loc.size() != this->_bonds.size()) {
Loc.push_back(0);
}
break;
}
}
if (Loc.size() == 0) break;
}
// if(!no_alloc){
// cytnx_uint64 offset=0;
// char* ptr = (char*)utils_internal::Calloc_cpu(
// totblocksize+blocklens.size()*STORAGE_DEFT_SZ,
// Type.typeSize(dtype));
// for(cytnx_int64 k=0;k<blocklens.size();k++){
// cytnx_uint64 cap=0;
// if (blocklens[k] % STORAGE_DEFT_SZ) {
// cap = ((unsigned long long)((blocklens[k]) / STORAGE_DEFT_SZ) + 1) * STORAGE_DEFT_SZ;
// } else {
// cap = blocklens[k];
// }
// this->_blocks.push_back(Tensor(Storage(ptr+(offset*Type.typeSize(dtype)),
// blocklens[k],dtype,device,true,cap),blocksizes[k],dtype,device));
// offset+=cap;
// }
// }
} // is_diag?
}
void beauty_print_block(std::ostream &os, const cytnx_uint64 &Nin, const cytnx_uint64 &Nout,
const std::vector<cytnx_uint64> &qn_indices,
const std::vector<Bond> &bonds, const Tensor &block) {
cytnx_uint64 Total_line = Nin < Nout ? Nout : Nin;
std::vector<std::string> Lside(Total_line);
std::vector<std::string> Rside(Total_line);
std::vector<std::string> MidL(Total_line);
std::vector<std::string> MidR(Total_line);
cytnx_uint64 Lmax = 0;
cytnx_uint64 mL = 0;
cytnx_uint64 mR = 0;
for (int i = 0; i < Total_line; i++) {
// Lside:
if (i < Nin) {
Lside[i] += "[" + to_string(qn_indices[i]) + "] ";
for (int s = 0; s < bonds[0].Nsym(); s++) {
Lside[i] += bonds[0]._impl->_syms[s].stype_str() + "(" +
to_string(bonds[i]._impl->_qnums[qn_indices[i]][s]) + ")";
}
if (Lmax < Lside[i].size()) Lmax = Lside[i].size();
MidL[i] += to_string(block.shape()[i]);
if (mL < MidL[i].size()) mL = MidL[i].size();
}
// Rside:
if (i < Nout) {
Rside[i] += "[" + to_string(qn_indices[Nin + i]) + "] ";
for (int s = 0; s < bonds[0].Nsym(); s++) {
Rside[i] += bonds[0]._impl->_syms[s].stype_str() + "(" +
to_string(bonds[Nin + i]._impl->_qnums[qn_indices[Nin + i]][s]) + ")";
}
// check if is_diag = true:
if (block.shape().size() == 1 && bonds.size() == 2)
MidR[i] += to_string(block.shape()[i]);
else
MidR[i] += to_string(block.shape()[Nin + i]);
if (mR < MidR[i].size()) mR = MidR[i].size();
}
}
// filling space:
for (int i = 0; i < Total_line; i++) {
if (Lside[i].size() < Lmax) {
Lside[i] += string(" ") * (Lmax - Lside[i].size());
}
if (MidL[i].size() < mL) {
MidL[i] += string(" ") * (mL - MidL[i].size());
}
if (MidR[i].size() < mR) {
MidR[i] += string(" ") * (mR - MidR[i].size());
}
}
// starting printing:
// 3spacing, Lmax , 5 for arrow
std::string empty_line =
(std::string(" ") * (3 + Lmax + 5)) + "| " + std::string(" ") * (mL + 5 + mR) + " |";
os << (std::string(" ") * (3 + Lmax + 5)) << std::string("-") * (4 + mL + mR + 5) << endl;
os << empty_line << endl;
std::string bks;
for (int i = 0; i < Total_line; i++) {
os << " " << Lside[i];
// arrow:
if (i < Nin) {
if (bonds[i].type() == bondType::BD_KET)
bks = " -->";
else
bks = " *<--";
} else {
bks = " ";
}
os << bks << "| " << MidL[i] << " " << MidR[i] << " |";
if (i < Nout) {
if (bonds[Nin + i].type() == bondType::BD_KET)
bks = "<--* ";
else
bks = "--> ";
} else {
bks = "";
}
os << bks << Rside[i] << endl;
os << empty_line << endl;
}
os << (std::string(" ") * (3 + Lmax + 5)) << std::string("-") * (4 + mL + mR + 5) << endl;
}
void BlockUniTensor::print_block(const cytnx_int64 &idx, const bool &full_info) const {
cytnx_error_msg(
(idx < 0) || (idx >= this->_blocks.size()),
"[ERROR] index [%d] out of bound. should be >0 and < number of available blocks %d\n", idx,
this->_blocks.size());
std::ostream &os = std::cout;
os << "========================\n";
if (this->_is_diag) os << " *is_diag: True\n";
os << "BLOCK [#" << idx << "]\n";
/*
os << " |-Qn indices for each axis:\n {\t";
for(int s=0;s<this->_inner_to_outer_idx[idx].size();s++){
os << this->_inner_to_outer_idx[idx][s] << "\t";
}
os << "}" << endl;
os << "\t";
for(int s=0;s<this->_bonds.size();s++){
os << ((this->_bonds[s].type()>0)?"OUT":"IN") << "\t";
}
os << endl;
os << " |-Qn for each axis:\n";
for(int s=0;s<this->_bonds[0].Nsym();s++){
os << " " <<this->_bonds[0]._impl->_syms[s].stype_str() << ":\t";
for(int l=0;l<this->_blocks[idx].shape().size();l++){
os << std::showpos <<
this->_bonds[l]._impl->_qnums[this->_inner_to_outer_idx[idx][l]][s] << "\t";
}
os << std::noshowpos << endl;
}
*/
os << " |- [] : Qn index \n";
os << " |- Sym(): Qnum of correspond symmetry\n";
beauty_print_block(os, this->_rowrank, this->_labels.size() - this->_rowrank,
this->_inner_to_outer_idx[idx], this->_bonds, this->_blocks[idx]);
if (full_info)
os << this->_blocks[idx];
else {
os << " |-dtype:\t" << Type.getname(this->_blocks[idx].dtype()) << endl;
os << " |-device:\t" << Device.getname(this->_blocks[idx].device()) << endl;
os << " |-contiguous:\t" << (this->_blocks[idx].is_contiguous() ? "True" : "False") << endl;
os << " |-shape:\t";
vec_print_simple(os, this->_blocks[idx].shape());
}
}
void BlockUniTensor::print_blocks(const bool &full_info) const {
std::ostream &os = std::cout;
os << "-------- start of print ---------\n";
char *buffer = (char *)malloc(sizeof(char) * 10240);
sprintf(buffer, "Tensor name: %s\n", this->_name.c_str());
os << std::string(buffer);
sprintf(buffer, "Tensor type: %s\n", this->uten_type_str().c_str());
os << std::string(buffer);
if (this->_is_tag)
sprintf(buffer, "braket_form : %s\n", this->_is_braket_form ? "True" : "False");
os << std::string(buffer);
sprintf(buffer, "is_diag : %s\n", this->_is_diag ? "True" : "False");
os << std::string(buffer);
sprintf(buffer, "[OVERALL] contiguous : %s\n", this->is_contiguous() ? "True" : "False");
os << std::string(buffer);
/*
os << "Symmetries: ";
for(int s=0;s<this->_bonds[0].Nsym();s++)
os << this->_bonds[0]._impl->_syms[s].stype_str() << " ";
os << endl;
*/
// print each blocks with its qnum!
for (int b = 0; b < this->_blocks.size(); b++) {
this->print_block(b, full_info);
}
/*
auto tmp_qnums = in.get_blocks_qnums();
std::vector<Tensor> tmp = in.get_blocks_(true);
sprintf(buffer, "BLOCKS:: %s", "\n");
os << std::string(buffer);
os << "=============\n";
if (!in.is_contiguous()) {
cytnx_warning_msg(
true,
"[WARNING][Symmetric] cout/print UniTensor on a non-contiguous UniTensor. the blocks "
"appears here could be different than the current shape of UniTensor.%s",
"\n");
}
for (cytnx_uint64 i = 0; i < tmp.size(); i++) {
os << "Qnum:" << tmp_qnums[i] << std::endl;
os << tmp[i] << std::endl;
os << "=============\n";
}
os << "-------- end of print ---------\n";
*/
free(buffer);
}
void BlockUniTensor::print_diagram(const bool &bond_info) const {
char *buffer = (char *)malloc(10240 * sizeof(char));
unsigned int BUFFsize = 100;
sprintf(buffer, "-----------------------%s", "\n");
std::cout << std::string(buffer);
sprintf(buffer, "tensor Name : %s\n", this->_name.c_str());
std::cout << std::string(buffer);
sprintf(buffer, "tensor Rank : %d\n", this->_labels.size());
std::cout << std::string(buffer);
// sprintf(buffer, "block_form : true%s", "\n");
// std::cout << std::string(buffer);
sprintf(buffer, "contiguous : %s\n", this->is_contiguous() ? "True" : "False");
std::cout << std::string(buffer);
sprintf(buffer, "valid blocks: %d\n", this->_blocks.size());
std::cout << std::string(buffer);
sprintf(buffer, "is diag : %s\n", this->is_diag() ? "True" : "False");
std::cout << std::string(buffer);
sprintf(buffer, "on device : %s\n", this->device_str().c_str());
std::cout << std::string(buffer);
cytnx_uint64 Nin = this->_rowrank;
cytnx_uint64 Nout = this->_labels.size() - this->_rowrank;
cytnx_uint64 vl;
if (Nin > Nout)
vl = Nin;
else
vl = Nout;
std::string bks;
char *l = (char *)malloc(BUFFsize * sizeof(char));
char *llbl = (char *)malloc(BUFFsize * sizeof(char));
char *r = (char *)malloc(BUFFsize * sizeof(char));
char *rlbl = (char *)malloc(BUFFsize * sizeof(char));
int Space_Llabel_max = 0, Space_Ldim_max = 0, Space_Rdim_max = 0;
// quickly checking the size for each line, only check the largest!
for (cytnx_uint64 i = 0; i < vl; i++) {
if (i < Nin) {
if (Space_Llabel_max < this->_labels[i].size()) Space_Llabel_max = this->_labels[i].size();
if (Space_Ldim_max < to_string(this->_bonds[i].dim()).size())
Space_Ldim_max = to_string(this->_bonds[i].dim()).size();
}
if (i < Nout) {
if (Space_Rdim_max < to_string(this->_bonds[Nin + i].dim()).size())
Space_Rdim_max = to_string(this->_bonds[Nin + i].dim()).size();
}
}
string LallSpace = (string(" ") * (Space_Llabel_max + 3 + 1));
string MallSpace = string(" ") * (1 + Space_Ldim_max + 5 + Space_Rdim_max + 1);
string M_dashes = string("-") * (1 + Space_Ldim_max + 5 + Space_Rdim_max + 1);
std::string tmpss;
sprintf(buffer, "%s row %s col %s", LallSpace.c_str(), MallSpace.c_str(), "\n");
std::cout << std::string(buffer);
sprintf(buffer, "%s -%s- %s", LallSpace.c_str(), M_dashes.c_str(), "\n");
std::cout << std::string(buffer);
for (cytnx_uint64 i = 0; i < vl; i++) {
sprintf(buffer, "%s |%s| %s", LallSpace.c_str(), MallSpace.c_str(), "\n");
std::cout << std::string(buffer);
if (i < Nin) {
if (this->_bonds[i].type() == bondType::BD_KET)
bks = " -->";
else
bks = "*<--";
memset(l, 0, sizeof(char) * BUFFsize);
memset(llbl, 0, sizeof(char) * BUFFsize);
tmpss = this->_labels[i] + std::string(" ") * (Space_Llabel_max - this->_labels[i].size());
sprintf(l, "%s %s", tmpss.c_str(), bks.c_str());
tmpss = to_string(this->_bonds[i].dim()) +
std::string(" ") * (Space_Ldim_max - to_string(this->_bonds[i].dim()).size());
sprintf(llbl, "%s", tmpss.c_str());
} else {
memset(l, 0, sizeof(char) * BUFFsize);
memset(llbl, 0, sizeof(char) * BUFFsize);
tmpss = std::string(" ") * (Space_Llabel_max + 5);
sprintf(l, "%s", tmpss.c_str());
tmpss = std::string(" ") * (Space_Ldim_max);
sprintf(llbl, "%s", tmpss.c_str());
}
if (i < Nout) {
if (this->_bonds[Nin + i].type() == bondType::BD_KET)
bks = "<--*";
else
bks = "--> ";
memset(r, 0, sizeof(char) * BUFFsize);
memset(rlbl, 0, sizeof(char) * BUFFsize);
sprintf(r, "%s %s", bks.c_str(), this->_labels[Nin + i].c_str());
tmpss = to_string(this->_bonds[Nin + i].dim()) +
std::string(" ") * (Space_Rdim_max - to_string(this->_bonds[Nin + i].dim()).size());
sprintf(rlbl, "%s", tmpss.c_str());
} else {
memset(r, 0, sizeof(char) * BUFFsize);
memset(rlbl, 0, sizeof(char) * BUFFsize);
sprintf(r, "%s", " ");
tmpss = std::string(" ") * Space_Rdim_max;
sprintf(rlbl, "%s", tmpss.c_str());
}
sprintf(buffer, " %s| %s %s |%s\n", l, llbl, rlbl, r);
std::cout << std::string(buffer);
}
sprintf(buffer, "%s |%s| %s", LallSpace.c_str(), MallSpace.c_str(), "\n");
std::cout << std::string(buffer);
sprintf(buffer, "%s -%s- %s", LallSpace.c_str(), M_dashes.c_str(), "\n");
std::cout << std::string(buffer);
sprintf(buffer, "%s", "\n");
std::cout << std::string(buffer);
if (bond_info) {
for (cytnx_uint64 i = 0; i < this->_bonds.size(); i++) {
// sprintf(buffer, "lbl:%d ", this->_labels[i]);
sprintf(buffer, "lbl:%s ", this->_labels[i].c_str());
std::cout << std::string(buffer);
std::cout << this->_bonds[i] << std::endl;
}
}
fflush(stdout);
free(l);
free(llbl);
free(r);
free(rlbl);
free(buffer);
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::contiguous() {
if (this->is_contiguous()) {
boost::intrusive_ptr<UniTensor_base> out(this);
return out;
} else {
BlockUniTensor *tmp = new BlockUniTensor();
tmp = this->clone_meta(true, true);
tmp->_blocks.resize(this->_blocks.size());
for (unsigned int b = 0; b < this->_blocks.size(); b++) {
if (this->_blocks[b].is_contiguous()) {
tmp->_blocks[b] = this->_blocks[b].clone();
} else {
tmp->_blocks[b] = this->_blocks[b].contiguous();
}
}
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
}
std::vector<Symmetry> BlockUniTensor::syms() const { return this->_bonds[0].syms(); }
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::permute(
const std::vector<cytnx_int64> &mapper, const cytnx_int64 &rowrank) {
BlockUniTensor *out_raw = this->clone_meta(true, true);
out_raw->_blocks.resize(this->_blocks.size());
std::vector<cytnx_uint64> mapper_u64 = std::vector<cytnx_uint64>(mapper.begin(), mapper.end());
// checking:
for (int i = 0; i < mapper_u64.size(); i++) {
cytnx_error_msg(mapper_u64[i] >= this->rank(), "[ERROR] index %d out of bound!\n",
mapper_u64[i]);
}
out_raw->_bonds = vec_map(vec_clone(out_raw->bonds()), mapper_u64); // this will check validity
out_raw->_labels = vec_map(out_raw->labels(), mapper_u64);
if (out_raw->_is_diag) {
// cytnx_error_msg(true,"[ERROR][BlockUniTensor] currently do not support permute for
// is_diag=true for BlockUniTensor!%s","\n");
if (rowrank >= 0)
cytnx_error_msg(rowrank != 1, "[ERROR][BlockUniTensor] is_diag=true must have rowrank=1.%s",
"\n");
out_raw->_is_braket_form = out_raw->_update_braket();
} else {
// inner_to_outer permute!
for (cytnx_int64 b = 0; b < this->_inner_to_outer_idx.size(); b++) {
out_raw->_inner_to_outer_idx[b] = vec_map(out_raw->_inner_to_outer_idx[b], mapper_u64);
out_raw->_blocks[b] = this->_blocks[b].permute(mapper_u64);
}
if (rowrank >= 0) {
cytnx_error_msg((rowrank > out_raw->_bonds.size()),
"[ERROR][BlockUniTensor] rowrank cannot exceed the rank of UniTensor.%s",
"\n");
out_raw->_rowrank = rowrank;
}
out_raw->_is_braket_form = out_raw->_update_braket();
}
boost::intrusive_ptr<UniTensor_base> out(out_raw);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::permute(
const std::vector<std::string> &mapper, const cytnx_int64 &rowrank) {
BlockUniTensor *out_raw = this->clone_meta(true, true);
out_raw->_blocks.resize(this->_blocks.size());
std::vector<cytnx_int64> mapper_i64;
// cytnx_error_msg(true,"[Developing!]%s","\n");
std::vector<string>::iterator it;
for (cytnx_int64 i = 0; i < mapper.size(); i++) {
it = std::find(out_raw->_labels.begin(), out_raw->_labels.end(), mapper[i]);
cytnx_error_msg(it == out_raw->_labels.end(),
"[ERROR] label %s does not exist in current UniTensor.\n", mapper[i].c_str());
mapper_i64.push_back(std::distance(out_raw->_labels.begin(), it));
}
return this->permute(mapper_i64, rowrank);
}
void BlockUniTensor::permute_(const std::vector<cytnx_int64> &mapper,
const cytnx_int64 &rowrank) {
std::vector<cytnx_uint64> mapper_u64;
mapper_u64 = std::vector<cytnx_uint64>(mapper.begin(), mapper.end());
// checking:
for (int i = 0; i < mapper_u64.size(); i++) {
cytnx_error_msg(mapper_u64[i] >= this->rank(), "[ERROR] index %d out of bound!\n",
mapper_u64[i]);
}
this->_bonds = vec_map(vec_clone(this->bonds()), mapper_u64); // this will check validity
this->_labels = vec_map(this->labels(), mapper_u64);
if (this->_is_diag) {
if (rowrank >= 0)
cytnx_error_msg(rowrank != 1, "[ERROR][BlockUniTensor] is_diag=true must have rowrank=1.%s",
"\n");
this->_is_braket_form = this->_update_braket();
} else {
// inner_to_outer permute!
for (cytnx_int64 b = 0; b < this->_inner_to_outer_idx.size(); b++) {
this->_inner_to_outer_idx[b] = vec_map(this->_inner_to_outer_idx[b], mapper_u64);
this->_blocks[b].permute_(mapper_u64);
}
if (rowrank >= 0) {
cytnx_error_msg((rowrank > this->_bonds.size()),
"[ERROR][BlockUniTensor] rowrank cannot exceed the rank of UniTensor.%s",
"\n");
this->_rowrank = rowrank;
}
this->_is_braket_form = this->_update_braket();
}
}
void BlockUniTensor::permute_(const std::vector<std::string> &mapper,
const cytnx_int64 &rowrank) {
std::vector<cytnx_int64> mapper_i64;
// cytnx_error_msg(true,"[Developing!]%s","\n");
std::vector<std::string>::iterator it;
for (cytnx_uint64 i = 0; i < mapper.size(); i++) {
it = std::find(this->_labels.begin(), this->_labels.end(), mapper[i]);
cytnx_error_msg(it == this->_labels.end(),
"[ERROR] label %d does not exist in current UniTensor.\n", mapper[i].c_str());
mapper_i64.push_back(std::distance(this->_labels.begin(), it));
}
this->permute_(mapper_i64, rowrank);
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabel(
const std::vector<string> &new_labels) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->set_labels(new_labels);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabel(
const std::vector<std::string> &old_labels, const std::vector<std::string> &new_labels) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->relabel_(old_labels, new_labels);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabels(
const std::vector<string> &new_labels) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->set_labels(new_labels);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabels(
const std::vector<std::string> &old_labels, const std::vector<std::string> &new_labels) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->relabels_(old_labels, new_labels);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabel(const cytnx_int64 &inx,
const string &new_label) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->set_label(inx, new_label);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::relabel(const string &inx,
const string &new_label) {
BlockUniTensor *tmp = this->clone_meta(true, true);
tmp->_blocks = this->_blocks;
tmp->set_label(inx, new_label);
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
}
boost::intrusive_ptr<UniTensor_base> BlockUniTensor::contract(
const boost::intrusive_ptr<UniTensor_base> &rhs, const bool &mv_elem_self,
const bool &mv_elem_rhs) {
// checking type
cytnx_error_msg(
rhs->uten_type() != UTenType.Block,
"[ERROR] cannot contract symmetry-block UniTensor with other type of UniTensor%s", "\n");
// checking symmetry:
cytnx_error_msg(this->syms() != rhs->syms(),
"[ERROR] two UniTensor have different symmetry type cannot contract.%s", "\n");
// get common labels:
std::vector<string> comm_labels;
std::vector<cytnx_uint64> comm_idx1, comm_idx2;
vec_intersect_(comm_labels, this->labels(), rhs->labels(), comm_idx1, comm_idx2);
if (comm_idx1.size() == 0) {
// output instance;
BlockUniTensor *tmp = new BlockUniTensor();
BlockUniTensor *Rtn = (BlockUniTensor *)rhs.get();
std::vector<string> out_labels;
std::vector<Bond> out_bonds;
cytnx_int64 out_rowrank;
// no-common label:
vec_concatenate_(out_labels, this->labels(), rhs->labels());
for (cytnx_uint64 i = 0; i < this->_bonds.size(); i++)
out_bonds.push_back(this->_bonds[i].clone());
for (cytnx_uint64 i = 0; i < rhs->_bonds.size(); i++)
out_bonds.push_back(rhs->_bonds[i].clone());
out_rowrank = this->rowrank() + rhs->rowrank();
vec_concatenate_(out_labels, this->_labels, rhs->_labels);
// cout << out_bonds;
tmp->Init(out_bonds, out_labels, out_rowrank, this->dtype(), this->device(), false);
// tmp->_name = this->_name + "+" + rhs->_name;
// check each valid block:
std::vector<cytnx_uint64> Lidx(this->_bonds.size()); // buffer
std::vector<cytnx_uint64> Ridx(rhs->_bonds.size()); // buffer
for (cytnx_int32 b = 0; b < tmp->_blocks.size(); b++) {
memcpy(&Lidx[0], &tmp->_inner_to_outer_idx[b][0],
sizeof(cytnx_uint64) * this->_bonds.size());
memcpy(&Ridx[0], &tmp->_inner_to_outer_idx[b][this->_bonds.size()],
sizeof(cytnx_uint64) * rhs->_bonds.size());
auto IDL = vec_argwhere(this->_inner_to_outer_idx, Lidx);
auto IDR = vec_argwhere(Rtn->_inner_to_outer_idx, Ridx);
if (User_debug) {
if (IDL.size() == IDR.size()) {
cytnx_error_msg(IDL.size() > 1,
"[ERROR][BlockUniTensor] IDL has more than two ambiguous location!%s",
"\n");
cytnx_error_msg(IDR.size() > 1,
"[ERROR][BlockUniTensor] IDL has more than two ambiguous location!%s",
"\n");
} else {
cytnx_error_msg(true, "[ERROR] duplication, something wrong!%s", "\n");
}
}
if (IDL.size()) {
auto tmpR = Rtn->is_diag() ? linalg::Diag(Rtn->_blocks[IDR[0]]) : Rtn->_blocks[IDR[0]];
auto tmpL = this->is_diag() ? linalg::Diag(this->_blocks[IDL[0]]) : this->_blocks[IDL[0]];
std::vector<cytnx_uint64> shape_L =
vec_concatenate(tmpL.shape(), std::vector<cytnx_uint64>(tmpR.shape().size(), 1));
tmpL = tmpL.reshape(shape_L);
auto Ott = linalg::Kron(tmpL, tmpR, false, true);
// checking:
cytnx_error_msg(Ott.shape() != tmp->_blocks[b].shape(), "[ERROR] mismatching shape!%s",
"\n");
tmp->_blocks[b] = Ott;
}
}
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
} else {
// first, get common index!
// check qnums & type:
for (int i = 0; i < comm_labels.size(); i++) {
if (User_debug) {
cytnx_error_msg(this->_bonds[comm_idx1[i]].qnums() != rhs->_bonds[comm_idx2[i]].qnums(),
"[ERROR] contract bond @ label %s have qnum mismatch.\n",
comm_labels[i].c_str());
cytnx_error_msg(this->_bonds[comm_idx1[i]].getDegeneracies() !=
rhs->_bonds[comm_idx2[i]].getDegeneracies(),
"[ERROR] contract bond @ label %s have degeneracies mismatch.\n",
comm_labels[i].c_str());
}
cytnx_error_msg(this->_bonds[comm_idx1[i]].type() + rhs->_bonds[comm_idx2[i]].type(),
"[ERROR] BRA can only contract with KET. invalid @ label: %s\n",
comm_labels[i].c_str());
}
// proc meta, labels:
std::vector<cytnx_uint64> non_comm_idx1 = vec_erase(vec_range(this->rank()), comm_idx1);
std::vector<cytnx_uint64> non_comm_idx2 = vec_erase(vec_range(rhs->rank()), comm_idx2);
if ((non_comm_idx1.size() == 0) && (non_comm_idx2.size() == 0)) {
std::vector<cytnx_int64> _shadow_comm_idx1(comm_idx1.size()),
_shadow_comm_idx2(comm_idx2.size());
memcpy(_shadow_comm_idx1.data(), comm_idx1.data(), sizeof(cytnx_int64) * comm_idx1.size());
memcpy(_shadow_comm_idx2.data(), comm_idx2.data(), sizeof(cytnx_int64) * comm_idx2.size());
// All the legs are contracted, the return will be a scalar
// output instance;
DenseUniTensor *tmp = new DenseUniTensor();
boost::intrusive_ptr<UniTensor_base> Lperm = this->permute(_shadow_comm_idx1);
boost::intrusive_ptr<UniTensor_base> Rperm = rhs->permute(_shadow_comm_idx2);
BlockUniTensor *Lperm_raw = (BlockUniTensor *)Lperm.get();
BlockUniTensor *Rperm_raw = (BlockUniTensor *)Rperm.get();
// pair the block and contract using vectordot!
// naive way!
for (unsigned int b = 0; b < Lperm_raw->_blocks.size(); b++) {
for (unsigned int a = 0; a < Rperm_raw->_blocks.size(); a++) {
if (Lperm_raw->_inner_to_outer_idx[b] == Rperm_raw->_inner_to_outer_idx[a]) {
if (tmp->_block.dtype() == Type.Void)
tmp->_block = linalg::Vectordot(Lperm_raw->_blocks[b].flatten(),
Rperm_raw->_blocks[a].flatten());
else
tmp->_block += linalg::Vectordot(Lperm_raw->_blocks[b].flatten(),
Rperm_raw->_blocks[a].flatten());
}
}
}
tmp->_rowrank = 0;
tmp->_is_tag = false;
/*
if(mv_elem_self){
// calculate reverse mapper:
std::vector<cytnx_uint64> inv_mapperL(comm_idx1.size());
for (int i = 0; i < comm_idx1.size(); i++) {
inv_mapperL[comm_idx1[i]] = i;
}
for(unsigned int b=0;b<this->_blocks.size();b++){
this->_blocks[b].permute_(comm_idx1);
this->_blocks[b].contiguous_();
this->_blocks[b].permute_(inv_mapperL);
}
}
if(mv_elem_rhs){
BlockUniTensor *Rtn = (BlockUniTensor*)rhs.get();
// calculate reverse mapper:
std::vector<cytnx_uint64> inv_mapperR(comm_idx2.size());
for (int i = 0; i < comm_idx2.size(); i++) {
inv_mapperR[comm_idx2[i]] = i;
}
for(unsigned int b=0;b<Rtn->_blocks.size();b++){
Rtn->_blocks[b].permute_(comm_idx2);
Rtn->_blocks[b].contiguous_();
Rtn->_blocks[b].permute_(inv_mapperR);
}
}
*/
boost::intrusive_ptr<UniTensor_base> out(tmp);
return out;
} else {
BlockUniTensor *tmp = new BlockUniTensor();
BlockUniTensor *Rtn = (BlockUniTensor *)rhs.get();
std::vector<string> out_labels;
std::vector<Bond> out_bonds;
cytnx_int64 out_rowrank;
for (cytnx_uint64 i = 0; i < non_comm_idx1.size(); i++)
out_bonds.push_back(this->_bonds[non_comm_idx1[i]].clone());
for (cytnx_uint64 i = 0; i < non_comm_idx2.size(); i++)
out_bonds.push_back(rhs->_bonds[non_comm_idx2[i]].clone());
vec_concatenate_(out_labels, vec_clone(this->_labels, non_comm_idx1),
vec_clone(rhs->_labels, non_comm_idx2));
out_rowrank = this->rowrank() + rhs->rowrank();
for (cytnx_uint64 i = 0; i < comm_idx1.size(); i++)
if (comm_idx1[i] < this->_rowrank) out_rowrank--;
for (cytnx_uint64 i = 0; i < comm_idx2.size(); i++)
if (comm_idx2[i] < rhs->_rowrank) out_rowrank--;
#ifdef UNI_MKL
// Initialize!!
if (true or
(this->dtype() != Type.Double and this->dtype() != Type.ComplexDouble) and
(this->dtype() != Type.Float and this->dtype() != Type.ComplexFloat) or
this->is_diag() or Rtn->is_diag()) {
tmp->Init(out_bonds, out_labels, out_rowrank, this->dtype(), this->device(), false,
false);
} else {
tmp->Init(out_bonds, out_labels, out_rowrank, this->dtype(), this->device(), false, true);
}
#else
tmp->Init(out_bonds, out_labels, out_rowrank, this->dtype(), this->device(), false, false);
#endif
// now, build the itoi table:
std::vector<std::vector<cytnx_uint64>> itoiL_common(this->_blocks.size()),
itoiR_common(Rtn->_blocks.size());
for (cytnx_int64 a = 0; a < this->_blocks.size(); a++) {
itoiL_common[a] = vec_clone(this->_inner_to_outer_idx[a], comm_idx1);
}
boost::unordered_map<std::vector<cytnx_uint64>, std::vector<cytnx_uint64>> mp;
boost::unordered_map<std::vector<cytnx_uint64>, cytnx_uint64> mpC;
for (cytnx_int64 b = 0; b < Rtn->_blocks.size(); b++) {
itoiR_common[b] = vec_clone(Rtn->_inner_to_outer_idx[b], comm_idx2);
if (!mp[itoiR_common[b]].size())
mp[itoiR_common[b]] = std::vector<cytnx_uint64>(1, b);
else
mp[itoiR_common[b]].push_back(b);
}
for (cytnx_int64 b = 0; b < tmp->_blocks.size(); b++) {
mpC[tmp->_inner_to_outer_idx[b]] = b;
}
std::vector<cytnx_uint64> Lgbuffer;
std::vector<cytnx_uint64> itoiR_idx;
std::vector<cytnx_uint64> oldshapeL;
std::vector<std::vector<cytnx_uint64>> oldshapeR(Rtn->_blocks.size(),
std::vector<cytnx_uint64>());
std::vector<std::vector<cytnx_uint64>> oldshapeC;
std::vector<bool> reshaped(tmp->_blocks.size(), false);
for (cytnx_int64 a = 0; a < tmp->_blocks.size(); a++) {
oldshapeC.push_back(tmp->_blocks[a].shape());
}
std::vector<cytnx_uint64> mapperL, inv_mapperL(this->rank());
std::vector<cytnx_uint64> mapperR, inv_mapperR(rhs->rank());
vec_concatenate_(mapperL, non_comm_idx1, comm_idx1);
vec_concatenate_(mapperR, comm_idx2, non_comm_idx2);
for (int aa = 0; aa < mapperL.size(); aa++) {
inv_mapperL[mapperL[aa]] = aa;
}
for (int aa = 0; aa < mapperR.size(); aa++) {
inv_mapperR[mapperR[aa]] = aa;
}
if (this->is_diag() != Rtn->is_diag()) {
for (cytnx_int64 a = 0; a < this->_blocks.size(); a++) {
cytnx_int64 comm_dim = 1;
itoiR_idx = mp[itoiL_common[a]];
for (cytnx_uint64 b : itoiR_idx) {
Lgbuffer.resize(non_comm_idx1.size() + non_comm_idx2.size());
for (cytnx_uint64 cc = 0; cc < non_comm_idx1.size(); cc++) {
Lgbuffer[cc] = this->_inner_to_outer_idx[a][non_comm_idx1[cc]];
}
for (cytnx_uint64 cc = non_comm_idx1.size();
cc < non_comm_idx1.size() + non_comm_idx2.size(); cc++) {
Lgbuffer[cc] =
Rtn->_inner_to_outer_idx[b][non_comm_idx2[cc - non_comm_idx1.size()]];
}
cytnx_int64 targ_b = mpC[Lgbuffer];
tmp->_blocks[targ_b] += linalg::Tensordot_dg(this->_blocks[a], Rtn->_blocks[b],
comm_idx1, comm_idx2, this->is_diag());
}
}
} else {
std::vector<char> transs(Rtn->_blocks.size(), 'N');
std::vector<blas_int> ms(Rtn->_blocks.size(), 0), ns(Rtn->_blocks.size(), 0),
ks(Rtn->_blocks.size(), 0);
std::vector<void *> LMems(Rtn->_blocks.size(), 0), RMems(Rtn->_blocks.size(), 0),
CMems(Rtn->_blocks.size(), 0);
std::vector<blas_int> group_size(Rtn->_blocks.size(), 1);