-
Notifications
You must be signed in to change notification settings - Fork 0
/
quf.py
executable file
·6849 lines (4940 loc) · 224 KB
/
quf.py
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
from quimb import *
from quimb.tensor import *
from quimb.tensor.tensor_core import *
import quimb as qu
import numpy as np
import quimb.tensor as qtn
import itertools
import functools
from operator import add
import operator
import matplotlib.pyplot as plt
import math
import cmath
from numpy.linalg import inv
from math import exp, pi, sin, cos, acos, log#, polar
import cotengra as ctg
import copy
import autoray
import time
from progress.bar import Bar
import tqdm
import warnings
from collections import Counter
from quimb.tensor.tensor_2d import *
from quimb.tensor.tensor_3d import *
import torch
import os, sys
import scipy.linalg
from autoray import astype
#from cotengra.parallel import RayExecutor
#from concurrent.futures import ProcessPoolExecutor
be_verbose = True
method_norm=load_from_disk("Store/method")
#import ray
def change_datatype(TN, dtype):
for t in TN:
if t.dtype != dtype:
t.modify(apply=lambda data: astype(data, dtype), left_inds=t.left_inds)
l_type=[ t.dtype for t in TN ]
print ( "TN_data_type=" , l_type[0],l_type[-1] )
def safe_inverse(x, epsilon=1E-12):
return x/(x**2 + epsilon)
class SVD(torch.autograd.Function):
@staticmethod
def forward(self, A):
try:
U, S, V = torch.svd(A)
except:
if be_verbose:
print('trouble in torch gesdd routine, falling back to gesvd')
U, S, V = scipy.linalg.svd(A.detach().numpy(), full_matrices=False, lapack_driver='gesvd')
U = torch.from_numpy(U)
S = torch.from_numpy(S)
V = torch.from_numpy(V.T)
# make SVD result sign-consistent across multiple runs
for idx in range(U.size()[1]):
if max(torch.max(U[:,idx]), torch.min(U[:,idx]), key=abs) < 0.0:
U[:,idx] *= -1.0
V[:,idx] *= -1.0
self.save_for_backward(U, S, V)
return U, S, V.t()
@staticmethod
def backward(self, dU, dS, dV):
U, S, V = self.saved_tensors
dV = dV.t()
Vt = V.t()
Ut = U.t()
M = U.size(0)
N = V.size(0)
NS = len(S)
F = (S - S[:, None])
F = safe_inverse(F)
F.diagonal().fill_(0)
G = (S + S[:, None])
#G.diagonal().fill_(np.inf)
#G = 1/G
G = safe_inverse(G)
G.diagonal().fill_(0)
UdU = Ut @ dU
VdV = Vt @ dV
Su = (F+G)*(UdU-UdU.t())/2
Sv = (F-G)*(VdV-VdV.t())/2
dA = U @ (Su + Sv + torch.diag(dS)) @ Vt
if (M>NS):
#dA = dA + (torch.eye(M, dtype=dU.dtype, device=dU.device) - U@Ut) @ (dU/S) @ Vt
dA = dA + (torch.eye(M, dtype=dU.dtype, device=dU.device) - U@Ut) @ (dU*safe_inverse(S)) @ Vt
if (N>NS):
#dA = dA + (U/S) @ dV.t() @ (torch.eye(N, dtype=dU.dtype, device=dU.device) - V@Vt)
dA = dA + (U*safe_inverse(S)) @ dV.t() @ (torch.eye(N, dtype=dU.dtype, device=dU.device) - V@Vt)
return dA
autoray.register_function('torch', 'linalg.svd', SVD.apply)
class TN2DUni(TensorNetwork2DVector,
TensorNetwork2D,
TensorNetwork):
_EXTRA_PROPS = (
'_site_tag_id',
'_Lx',
'_Ly',
'_row_tag_id',
'_col_tag_id',
'_site_ind_id',
'_layer_ind_id',
)
@classmethod
def empty(
cls,
Lx,
Ly,
phys_dim=2,
data_type='float64',
site_tag_id="I{},{}",
site_ind_id="k{},{}",
layer_ind_id="l{},{}",
):
self = object.__new__(cls)
self._Lx = Lx
self._Ly = Ly
self._site_tag_id = site_tag_id
self._site_ind_id = site_ind_id
self._layer_ind_id = layer_ind_id
self._row_tag_id = None
self._col_tag_id = None
ts = [
Tensor(data=do("eye", phys_dim,dtype=data_type),
inds=[self.site_ind(i, j),
self.layer_ind(i, j)],
tags=[self.site_tag(i, j), f"reg{i},{j}", "const", f"CP{i*Ly+j}"],
left_inds=(self.site_ind(i, j),))
for i, j in itertools.product(range(Lx), range(Ly))
]
super().__init__(self, ts)
return self
@property
def layer_ind_id(self):
return self._layer_ind_id
def layer_ind(self, i, j):
return self._layer_ind_id.format(i, j)
def reverse_gate(
self,
G,
where,
new_sites=None,
tags=None,
iso=True,
):
"""
Parameters
----------
G : array_like
where : tuple[tuple[int]]
new_sites : None or tuple[tuple[int]], optional
tags : str or sequence of str, optional
iso : bool, optional
"""
tags = tags_to_oset(tags)
if is_lone_coo(where):
where = (where,)
else:
where = tuple(where)
nbelow = len(where)
layer_ix = [self.layer_ind(i, j) for i, j in where]
bnds = [rand_uuid() for _ in range(nbelow)]
reindex_map = dict(zip(layer_ix, bnds))
##print ("reindex_map", reindex_map)
nabove = len(G.shape) - nbelow
if new_sites is None:
new_sites = where[:nabove]
new_layer_ix = [self.layer_ind(i, j) for i, j in new_sites]
##print ("new_sites", new_sites)
##print ("new_layer_ix", new_layer_ix)
##print ("layer_ix", new_layer_ix)
#get tag of any tensor that has index "layer_ix"=[self.layer_ind(i, j) for i, j in where]
old_tags = oset_union(t.tags for t in self._inds_get(*layer_ix))
##print ("old_tags", old_tags)
if iso and 'TREE' in old_tags:
raise ValueError("You can't place isometric tensors above tree tensors.")
rex = re.compile(self.site_tag_id.format(r"\d+", r"\d+"))
old_tags = oset(filter(rex.match, old_tags))
if not iso:
old_tags.add('TREE')
left_inds = bnds
else:
old_tags.add('ISO')
left_inds = bnds
TG = Tensor(G, inds=new_layer_ix + bnds, tags=tags | old_tags, left_inds=left_inds)
self.reindex_(reindex_map)
self |= TG
return self
class TN3DUni(TensorNetwork3DVector,
TensorNetwork3D,
TensorNetwork):
_EXTRA_PROPS = (
'_site_tag_id',
'_x_tag_id',
'_y_tag_id',
'_z_tag_id',
'_site_ind_id',
'_Lx',
'_Ly',
'_Lz'
)
@classmethod
def empty(
cls,
Lx,
Ly,
Lz,
phys_dim=2,
data_type='float64',
site_tag_id="I{},{},{}",
site_ind_id="k{},{},{}",
layer_ind_id="l{},{},{}",
):
self = object.__new__(cls)
self._Lx = Lx
self._Ly = Ly
self._Lz = Lz
self._site_tag_id = site_tag_id
self._site_ind_id = site_ind_id
self._layer_ind_id = layer_ind_id
self._x_tag_id = None
self._y_tag_id = None
self._z_tag_id = None
ts = [
Tensor(data=do("eye", phys_dim),
inds=[self.site_ind(i, j, k),
self.layer_ind(i, j, k)],
tags=[self.site_tag(i, j, k), f"reg{i},{j},{k}", "const",f"CP{k*Ly*Lx+i*Ly+j}"],
left_inds=(self.site_ind(i, j, k),))
for i, j, k in itertools.product(range(Lx), range(Ly), range(Lz))
]
super().__init__(self, ts)
return self
@property
def layer_ind_id(self):
return self._layer_ind_id
def layer_ind(self, i, j, k):
return self._layer_ind_id.format(i, j, k)
def reverse_gate(
self,
G,
where,
new_sites=None,
tags=None,
iso=True,
):
"""
Parameters
----------
G : array_like
where : tuple[tuple[int]]
new_sites : None or tuple[tuple[int]], optional
tags : str or sequence of str, optional
iso : bool, optional
"""
tags = tags_to_oset(tags)
if is_lone_coo(where):
where = (where,)
else:
where = tuple(where)
nbelow = len(where)
layer_ix = [self.layer_ind(i, j, k) for i, j, k in where]
bnds = [rand_uuid() for _ in range(nbelow)]
reindex_map = dict(zip(layer_ix, bnds))
##print ("reindex_map", reindex_map)
nabove = len(G.shape) - nbelow
if new_sites is None:
new_sites = where[:nabove]
new_layer_ix = [self.layer_ind(i, j, k) for i, j, k in new_sites]
#get tag of any tensor that has index "layer_ix"=[self.layer_ind(i, j) for i, j in where]
old_tags = oset_union(t.tags for t in self._inds_get(*layer_ix))
##print ("old_tags", old_tags)
if iso and 'TREE' in old_tags:
raise ValueError("You can't place isometric tensors above tree tensors.")
rex = re.compile(self.site_tag_id.format(r"\d+", r"\d+", r"\d+"))
old_tags = oset(filter(rex.match, old_tags))
if not iso:
old_tags.add('TREE')
left_inds = None
else:
old_tags.add('ISO')
left_inds = bnds
TG = Tensor(G, inds=new_layer_ix + bnds, tags=tags | old_tags, left_inds=left_inds)
self.reindex_(reindex_map)
self |= TG
return self
def iso_Tn( tn, chi, size_Iso_x, size_Iso_y,list_tags,shared_I,list_scale,layer=None, L_x=None,L_y=None,
Iso=True, shift_x=0, shift_y=0,
dis_x=1, dis_y=1,last_bond="off", cycle="on",data_type='float64',
seed_val=10,scale=0, label=0, dist_type="uniform"):
shared_I.append(f"SI{scale},I{label}")
list_scale.append(f"SI{scale}")
lx_up=L_x//size_Iso_x if size_Iso_x != 0 else L_x
ly_up=L_y//size_Iso_y if size_Iso_y != 0 else L_y
for i in range(shift_x, L_x,dis_x):
for j in range(shift_y, L_y, dis_y):
if cycle=="off":
if (i+size_Iso_x-1)>L_x-1 or (j+size_Iso_y-1)>L_y-1: break
where=[]
for i_x in range(size_Iso_x if size_Iso_x != 0 else 1):
for j_y in range(size_Iso_y if size_Iso_y != 0 else 1):
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y ) )
##print ( i, j, where, [(f"{ ( shift_x+( i//(size_Iso_x if size_Iso_x != 0 else 1) ) )%(lx_up) }",
#f"{ ( shift_y+( j//(size_Iso_y if size_Iso_y != 0 else 1 )) )%(ly_up) }")] )
dims = [tn.ind_size(tn.layer_ind(*coo)) for coo in where]
if last_bond=="off":
dims.insert(0, min(prod(dims), chi))
##print ("dim", dims)
list_tags.append(f"I{layer},I{i},{j}")
tn.reverse_gate(
G=qu.randn(dims, dtype=data_type, dist=dist_type, seed=seed_val+i+j ),
where=where,
iso=Iso,
tags=["I", f"I{layer}",f"I{layer},I{i},{j}",f"SI{scale}",f"SI{scale},I{label}"],
new_sites=[(f"{ ( shift_x+( i//(size_Iso_x if size_Iso_x != 0 else 1) ) )%(lx_up) }",
f"{ ( shift_y+( j//(size_Iso_y if size_Iso_y != 0 else 1 )) )%(ly_up) }")]
)
else:
list_tags.append(f"I{layer},I{i},{j}")
tn.reverse_gate(
G=qu.randn(dims,dtype=data_type,dist=dist_type, seed=seed_val+i+j),
where=where,
iso=Iso,
tags=["I",f"I{layer}", f"I{layer},I{i},{j}",f"SI{scale}",f"SI{scale},I{label}"],
)
index_map={}
for i in range((lx_up)):
for j in range((ly_up)):
index_map[f"l{i},{j}"] =f"l{ (i+lx_up-shift_x)%lx_up},{ (j+ly_up-shift_y)%ly_up}"
##print (index_map)
tn.reindex_(index_map)
def Uni_Tn( tn, chi, size_U_x, size_U_y,list_tags,shared_U,list_scale,layer=None, L_x=None,L_y=None, Iso_on=True, shift_x=0, shift_y=0,dis_x=1, dis_y=1,last_bond="off", cycle="on",data_type='float64', seed_val=10, scale=0,label=0, dist_type="uniform"):
Lx=tn.Lx
Ly=tn.Ly
dic_coding={ i*Ly+j: (i,j) for i, j in itertools.product(range(Lx), range(Ly)) }
shared_U.append(f"SU{scale},U{label}")
list_scale.append(f"SU{scale}")
for i in range(shift_x, L_x,dis_x):
for j in range(shift_y, L_y, dis_y):
where=[]
if isinstance(size_U_x, list) or isinstance(size_U_y, list):
for i_x,j_y in zip(size_U_x,size_U_y):
if cycle=="off" and i+i_x<=L_x-1 and j+j_y<=L_y-1:
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y ) )
elif cycle=="on":
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y ) )
else:
for i_x in range(size_U_x):
for j_y in range(size_U_y):
#print (i_x, j_y, i+i_x<=L_x-1, j+j_y<=L_y-1, cycle=="off")
if cycle=="off" and i+i_x<=L_x-1 and j+j_y<=L_y-1:
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y ) )
#print ("where",where)
elif cycle=="on":
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y ) )
#print (where)
#take_out trivial unitary
if len(where)==1: where = []
#print (scale,where)
if where:
dims = [tn.ind_size(tn.layer_ind(*coo)) for coo in where]*2
if seed_val==0:
G_v=qu.eye( int(prod(dims)**(1./2.)), dtype=data_type).reshape( dims )
G_r=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j)
G_v=G_v+G_r*(0.1)
else:
G_v=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j)
list_tags.append(f"U{layer},I{i},{j}")
tag1=[]
for i_counter in range(len(where)):
ipp,jpp=where[i_counter]
tag1.append(f"UP{ipp*Ly+jpp}")
#print (where)
tag_f=["U",f"U{layer}",
f"U{layer},I{i},{j}",
f"SU{scale}",f"SU{scale},U{label}"]+tag1
tn.reverse_gate(G=G_v,where=where,iso=Iso_on,
tags=tag_f
)
def Uni_Tn_3D( tn, chi, size_U_x, size_U_y,size_U_z,list_tags,list_scale,layer=None,
L_x=None,L_y=None,L_z=None, Iso_on=True, shift_x=0, shift_y=0,shift_z=0,dis_x=1,
dis_y=1,dis_z=1,last_bond="off", cycle="on",data_type='float64',
dist_type="uniform",seed_val=10, scale=0, label=0):
list_scale.append(f"SU{scale}")
for i in range(shift_x, L_x,dis_x):
for j in range(shift_y, L_y, dis_y):
for k in range(shift_z, L_z, dis_z):
where=[]
if isinstance(size_U_x, list) or isinstance(size_U_y, list) or isinstance(size_U_z, list):
for i_x, j_y, k_z in zip(size_U_x, size_U_y, size_U_z):
if cycle=="off" and i+i_x<=L_x-1 and j+j_y<=L_y-1 and k+k_z<=L_z-1:
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y, (k+k_z)%L_z) )
elif cycle=="on":
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y, (k+k_z)%L_z) )
else:
for i_x in range(size_U_x):
for j_y in range(size_U_y):
for k_z in range(size_U_z):
##print (i_x, j_y, i+i_x<=L_x-1, j+j_y<=L_y-1, cycle=="off")
if cycle=="off" and i+i_x<=L_x-1 and j+j_y<=L_y-1 and k+k_z<=L_z-1:
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y, (k+k_z)%L_z ) )
elif cycle=="on":
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y, (k+k_z)%L_z ) )
#print (i,j,k,where)
#take_out trivial unitary
if len(where)==1: where = []
if where:
dims = [tn.ind_size(tn.layer_ind(*coo)) for coo in where]*2
if seed_val==0:
G_v=qu.eye( int(prod(dims)**(1./2.)), dtype=data_type).reshape( dims )
G_r=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j)
G_v=G_v+G_r*(0.1)
else:
G_v=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j)
list_tags.append(f"U{layer},I{i},{j},{k}")
tag1=[]
for i_counter in range(len(where)):
ipp, jpp, kpp=where[i_counter]
tag1.append(f"UP{kpp*Ly*Lx+ipp*Ly+jpp}")
tag_f=["U",f"U{layer}",f"U{layer},I{i},{j},{k}",f"SU{scale}",f"SU{scale},U{label}"]+tag1
tn.reverse_gate(G=G_v,where=where,iso=Iso_on,tags=tag_f)
def iso_Tn_3D( tn, chi, size_Iso_x, size_Iso_y, size_Iso_z,list_tags,list_scale,layer=None,
L_x=None,L_y=None, L_z=None, Iso=True, shift_x=0, shift_y=0,shift_z=0,dis_x=1, dis_y=1, dis_z=1,
last_bond="off", cycle="on",data_type='float64', seed_val=10, scale=0,dist_type="uniform",label=0):
list_scale.append(f"SI{scale}")
lx_up=L_x//size_Iso_x if size_Iso_x != 0 else L_x
ly_up=L_y//size_Iso_y if size_Iso_y != 0 else L_y
lz_up=L_z//size_Iso_z if size_Iso_z != 0 else L_z
##print ("Hi","x",shift_x, L_x,dis_x, "y",shift_y, L_y, dis_y,"z" ,shift_z, L_z, dis_z)
for i in range(shift_x, L_x,dis_x):
for j in range(shift_y, L_y, dis_y):
for k in range(shift_z, L_z, dis_z):
##print (i,j)
if cycle=="off":
##print ((i+size_Iso_x-1)>L_x-1 , (j+size_Iso_y-1)>L_y-1)
if (i+size_Iso_x-1)>L_x-1 or (j+size_Iso_y-1)>L_y-1 or (k+size_Iso_z-1)>L_z-1: break
where=[]
for i_x in range(size_Iso_x if size_Iso_x != 0 else 1):
for j_y in range(size_Iso_y if size_Iso_y != 0 else 1):
for k_z in range(size_Iso_z if size_Iso_z != 0 else 1):
where.append( ( (i+i_x)%L_x, (j+j_y)%L_y, (k+k_z)%L_z ) )
dims = [tn.ind_size(tn.layer_ind(*coo)) for coo in where]
if last_bond=="off":
##print ( i, j,k, where, [(f"{ ( shift_x+( i//(size_Iso_x if size_Iso_x != 0 else 1) ) )%(lx_up) }",
# f"{ ( shift_y+( j//(size_Iso_y if size_Iso_y != 0 else 1 )) )%(ly_up) }",f"{ ( shift_z+( k//(size_Iso_z if size_Iso_z != 0 else 1 )) )%(lz_up) }")] )
dims.insert(0, min(prod(dims), chi))
##print ("dim", dims)
list_tags.append(f"I{layer},I{i},{j},{k}")
tn.reverse_gate(
G=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j ),
where=where,
iso=Iso,
tags=["I", f"I{layer}",f"I{layer},I{i},{j},{k}",f"SI{scale}",f"SI{scale},I{label}"],
new_sites=[(f"{ ( shift_x+( i//(size_Iso_x if size_Iso_x != 0 else 1) ) )%(lx_up) }",
f"{ ( shift_y+( j//(size_Iso_y if size_Iso_y != 0 else 1 )) )%(ly_up) }", f"{ ( shift_z+( k//(size_Iso_z if size_Iso_z != 0 else 1 )) )%(lz_up) }")]
)
else:
list_tags.append(f"I{layer},I{i},{j},{k}")
tn.reverse_gate(
G=qu.randn(dims,dtype=data_type, dist=dist_type, seed=seed_val+i+j),
where=where,
iso=Iso,
tags=["I",f"I{layer}",f"I{layer},I{i},{j},{k}",f"SI{scale}",f"SI{scale},I{label}"],
)
index_map={}
for i in range((lx_up)):
for j in range((ly_up)):
for k in range((lz_up)):
index_map[f"l{i},{j},{k}"] =f"l{ (i+lx_up-shift_x)%lx_up},{ (j+ly_up-shift_y)%ly_up},{ (k+lz_up-shift_z)%lz_up}"
##print (index_map)
tn.reindex_(index_map)
def Heis_local_Ham_open_tree(N_x,N_y,data_type="float64"):
Z = qu.pauli('Z',dtype=data_type) * (0.5)
X = qu.pauli('X',dtype=data_type) * (0.5)
Y=np.array([[0, -1],[1,0]]) * (0.5)
X=X.astype(data_type)
Z=Z.astype(data_type)
Y=Y.astype(data_type)
list_sites=[]
list_inter=[]
##print (qu.ham_heis(2))
for i in range(N_x-1):
for j in range(N_y):
list_sites.append( [ ( i,j), ((i+1),j) ] )
for i in range(N_x):
for j in range(N_y-1):
list_sites.append( [ ( i,j), (i, (j+1)) ] )
list_inter=[X,Z,Y]
return list_sites, list_inter
def Heis_local_Ham_open(N_x,N_y,data_type="float64",phys_dim=2):
list_sites=[]
list_inter=[]
##print (qu.ham_heis(2))
#H=qu.ham_heis(2).astype(data_type)
if phys_dim==2:
h_h=qu.ham_heis(2).astype(data_type)
else:
h_h=np.eye(phys_dim*phys_dim).astype(data_type)
h_h=qu.randn((phys_dim, phys_dim, phys_dim, phys_dim),dtype=data_type, dist="uniform", seed=10)
for i in range(N_x-1):
for j in range(N_y):
list_sites.append( [ ( i,j), ((i+1),j) ] )
list_inter.append( h_h )
for i in range(N_x):
for j in range(N_y-1):
list_sites.append( [ ( i,j), (i, (j+1)) ] )
list_inter.append( h_h )
return list_sites, list_inter
def Heis_local_Ham_open_long(N_x,N_y,data_type="float64",phys_dim=2, alpha=1, phi=0, theta=0, N_interval=500):
import ray
ray.shutdown()
ray.init()
# @ray.remote
# def f_val_p(n,i,i1,j,j1,alpha,N_x,N_y, theta,phi,N=500):
# sum=0
# for m in range(-N,N+1):
# if i != i1+n*N_x or j!=j1+m*N_y:
# r=(abs(i-i1-n*N_x)**2+abs(j-j1-m*N_y)**2)**(0.5)
# e_0=(sin(theta)*(cos(phi)*(i-i1-n*N_x)+sin(phi)*(j-j1-m*N_y)))/r
# e_1=(1.-3.*(e_0**2.))
# sum+=e_1/(r**alpha)
# return sum
print ("Ham_info=alpha, phi, theta", alpha, phi, theta)
list_sites=[]
list_inter=[]
if phys_dim==2:
h_h=qu.ham_heis(2).astype(data_type)
I=qu.pauli('I',dtype=data_type)
h_I= I & I
else:
h_h=np.eye(phys_dim*phys_dim).astype(data_type)
h_h=qu.randn((phys_dim, phys_dim, phys_dim, phys_dim),dtype=data_type, dist="uniform", seed=10)
for i, j in itertools.product(range(N_x), range(N_y)):
for i1, j1 in itertools.product(range(N_x), range(N_y)):
ii=i*N_y+j
ii_=i1*N_y+j1
if ii_<ii:
#start_time = time.time()
#r_modified=cal_r_parralel(i,i1,j,j1, alpha,N_x,N_y,theta,phi,ray,f_val_p,N_interval=N_interval)
r_modified=cal_r_parralel_A(i,i1,j,j1, alpha,N_x,N_y,theta,phi,ray,N_interval=N_interval)
#print ( "--- %s seconds ---" % (time.time() - start_time), r_modified )
#start_time = time.time()
#r_modified=cal_r(i,i1,j,j1, alpha,N_x,N_y,theta,phi,N_interval=N_interval)
#print ("--- %s seconds ---" % (time.time() - start_time), r_modified)
h_f=h_h*r_modified
#print (i,j,i1,j1,r_modified)
h_f=h_f.astype(data_type)
list_sites.append( [ ( i,j), (i1,j1) ] )
list_inter.append( h_f )
ray.shutdown()
return list_sites, list_inter
def cal_r(i,i1,j,j1,alpha,N_x,N_y, theta,phi, N_interval=500):
N=N_interval
def f_val(n,m):
r=(abs(i-i1-n*N_x)**2+abs(j-j1-m*N_y)**2)**(0.5)
e_0=(sin(theta)*(cos(phi)*(i-i1-n*N_x)+sin(phi)*(j-j1-m*N_y)))/r
e_1=(1.-3.*(e_0**2.))
#print (i != i1+n*N_x , j!=j1+m*N_y)
return e_1/(r**alpha)
return sum ( f_val(n,m) for n,m in itertools.product(range(-N,N+1), range(-N,N+1)) if i != i1+n*N_x or j!=j1+m*N_y )
def cal_r_parralel(i,i1,j,j1,alpha,N_x,N_y, theta,phi,ray,f_val_p,N_interval=500):
N=N_interval
# @ray.remote
# def f_val_ll(n):
# sum=0
# for m in range(-N,N+1):
# if i != i1+n*N_x or j!=j1+m*N_y:
# r=(abs(i-i1-n*N_x)**2+abs(j-j1-m*N_y)**2)**(0.5)
# e_0=(sin(theta)*(cos(phi)*(i-i1-n*N_x)+sin(phi)*(j-j1-m*N_y)))/r
# e_1=(1.-3.*(e_0**2.))
# sum+=e_1/(r**alpha)
# return sum
f_val_l = [ f_val_p.remote(n,i,i1,j,j1,alpha,N_x,N_y, theta,phi,N=N) for n in range(-N,N+1) ]
# f_val_l = [ f_val_ll.remote(n) for n in range(-N,N+1) ]
#print (ray.get(f_val_l))
return sum(ray.get(f_val_l))
def cal_r_parralel_A(i,i1,j,j1,alpha,N_x,N_y, theta,phi,ray,N_interval=500):
N=N_interval
@ray.remote
def f_val_ll(n):
sum=0
for m in range(-N,N+1):
if i != i1+n*N_x or j!=j1+m*N_y:
r=(abs(i-i1-n*N_x)**2+abs(j-j1-m*N_y)**2)**(0.5)
e_0=(sin(theta)*(cos(phi)*(i-i1-n*N_x)+sin(phi)*(j-j1-m*N_y)))/r
e_1=(1.-3.*(e_0**2.))
sum+=e_1/(r**alpha)
return sum
f_val_l = [ f_val_ll.remote(n) for n in range(-N,N+1) ]
# f_val_l = [ f_val_ll.remote(n) for n in range(-N,N+1) ]
#print (ray.get(f_val_l))
return sum(ray.get(f_val_l))
def Heis_local_Ham_cycle(N_x,N_y):
list_sites=[]
list_inter=[]
##print (qu.ham_heis(2))
for i in range(N_x):
for j in range(N_y):
list_sites.append( [ ( i,j), ((i+1)%N_x,j) ] )
list_inter.append( qu.ham_heis(2) )
for i in range(N_x):
for j in range(N_y):
list_sites.append( [ ( i,j), (i, (j+1)%N_y) ] )
list_inter.append( qu.ham_heis(2) )
return list_sites, list_inter
def mpo_2d_His(L_x,L_y,L_L, data_type="float64"):
Z=qu.pauli('Z',dtype=data_type) * 0.5
X=qu.pauli('X',dtype=data_type) * 0.5
Y= np.array([[0, -1],[1,0]]) * 0.5
I=qu.pauli('I',dtype=data_type)
Y=Y.astype(data_type)
X=X.astype(data_type)
Z=Z.astype(data_type)
Ham=[X, Y, Z]
MPO_I=MPO_identity(L_L, phys_dim=2)
MPO_result=MPO_identity(L_L, phys_dim=2)
MPO_result=MPO_result*0.0
MPO_f=MPO_result*0.0
max_bond_val=300
cutoff_val=1.0e-12
for count, elem in enumerate (Ham):
for i, j in itertools.product(range(L_x-1), range(L_y)):
ii=i*L_y+j
ii_=(i+1)*L_y+j
Wl = np.zeros([ 1, 2, 2], dtype=data_type)
W = np.zeros([1, 1, 2, 2], dtype=data_type)
Wr = np.zeros([ 1, 2, 2], dtype=data_type)
Wl[ 0,:,:]=elem
W[ 0,0,:,:]=elem
Wr[ 0,:,:]=elem
W_list=[Wl]+[W]*(L_L-2)+[Wr]
MPO_I=MPO_identity(L_L, phys_dim=2 )
if count!=1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_])
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
elif count==1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_]*-1.0)
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
for count, elem in enumerate (Ham):
for i, j in itertools.product(range(L_x), range(L_y-1)):
ii=i*L_y+j
ii_=i*L_y+j+1
Wl = np.zeros([ 1, 2, 2], dtype=data_type)
W = np.zeros([1, 1, 2, 2], dtype=data_type)
Wr = np.zeros([ 1, 2, 2], dtype=data_type)
Wl[ 0,:,:]=elem
W[ 0,0,:,:]=elem
Wr[ 0,:,:]=elem
W_list=[Wl]+[W]*(L_L-2)+[Wr]
MPO_I=MPO_identity(L_L, phys_dim=2 )
if count!=1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_])
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
elif count==1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_]*-1.)
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
MPO_f=MPO_result
MPO_f.compress( max_bond=max_bond_val, cutoff=cutoff_val )
print ( MPO_f.show() )
return MPO_f
def mpo_2d_His_long(L_x,L_y,L_L, data_type="float64",cutoff_val=1.0e-12, alpha=1, phi=0, theta=0,chi=300, N_interval=500):
import ray
ray.shutdown()
ray.init()
@ray.remote
def f_val_p(n,i,i1,j,j1,alpha,N_x,N_y, theta,phi,N=500):
sum=0
for m in range(-N,N+1):
if i != i1+n*N_x or j!=j1+m*N_y:
r=(abs(i-i1-n*N_x)**2+abs(j-j1-m*N_y)**2)**(0.5)
e_0=(sin(theta)*(cos(phi)*(i-i1-n*N_x)+sin(phi)*(j-j1-m*N_y)))/r
e_1=(1.-3.*(e_0**2.))
sum+=e_1/(r**alpha)
return sum
Z=qu.pauli('Z',dtype=data_type) * 0.5
X=qu.pauli('X',dtype=data_type) * 0.5
Y= np.array([[0, -1],[1,0]]) * 0.5
I=qu.pauli('I',dtype=data_type)
Y=Y.astype(data_type)
X=X.astype(data_type)
Z=Z.astype(data_type)
Ham=[X, Y, Z]
MPO_I=MPO_identity(L_L, phys_dim=2)
MPO_result=MPO_identity(L_L, phys_dim=2)
MPO_result=MPO_result*0.0
MPO_f=MPO_result*0.0
max_bond_val=chi
for count, elem in enumerate (Ham):
for i, j in itertools.product(range(L_x), range(L_y)):
for i1, j1 in itertools.product(range(L_x), range(L_y)):
ii=i*L_y+j
ii_=i1*L_y+j1
if ii_<ii:
Wl = np.zeros([ 1, 2, 2], dtype=data_type)
W = np.zeros([1, 1, 2, 2], dtype=data_type)
Wr = np.zeros([ 1, 2, 2], dtype=data_type)
Wl[ 0,:,:]=elem
W[ 0,0,:,:]=elem
Wr[ 0,:,:]=elem
W_list=[Wl]+[W]*(L_L-2)+[Wr]
MPO_I=MPO_identity(L_L, phys_dim=2 )
# r_modified=cal_r(i,i1,j,j1, alpha,L_x,L_y,theta,phi,N_interval=N_interval)
r_modified=cal_r_parralel(i,i1,j,j1, alpha,L_x,L_y,theta,phi,ray,f_val_p,N_interval=N_interval)
#print (i, j,i1, j1,r_modified)
if count!=1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_]*r_modified )
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
elif count==1:
MPO_I[ii].modify(data=W_list[ii])
MPO_I[ii_].modify(data=W_list[ii_]*-1.0*r_modified )
MPO_result=MPO_result+MPO_I
MPO_result.compress( max_bond=max_bond_val, cutoff=cutoff_val )
MPO_f=MPO_result
MPO_f.compress( max_bond=max_bond_val, cutoff=cutoff_val )
print ( MPO_f.show() )
return MPO_f
def mpo_3d_His(L_x,L_y,L_z,L_L, data_type="float64", chi=200,cutoff_val=1.0e-12):
Z=qu.pauli('Z',dtype=data_type) * 0.5
X=qu.pauli('X',dtype=data_type) * 0.5
Y= np.array([[0, -1],[1,0]]) * 0.5
I=qu.pauli('I',dtype=data_type)
Y=Y.astype(data_type)
X=X.astype(data_type)
Z=Z.astype(data_type)