-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHofstadterThreeBody.py
1737 lines (1497 loc) · 75.8 KB
/
HofstadterThreeBody.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
import numpy as np
import scipy as sp
from scipy import special
from scipy.sparse import linalg
import sys
import getopt
import argparse
import time
import bisect
from functools import reduce
import GenericModule as gm
np.set_printoptions(threshold=sys.maxsize)
def TimePrint(start):
"""
Print the time elapsed in a readable way
"""
end = time.time()
dt = end - start
dtMin = dt/60.
print('-------- Time elapsed --------')
print(f'sec={dt}')
print(f'min={dtMin}')
print('------------------------------')
def GenFilename(hardcore, L, J, U, trapConf, gamma, nEigenstate, hamiltonian=False, spectrum=False, absSpectrum=False, localDensity=False, c4=False, U3=0.0, alpha=0.0, N=0):
"""
Returns the filename string the saved eigenstates will have
"""
tmpString = ""
fileName = f'bosons_'
if (hardcore == True):
tmpString = f'hardcore_'
fileName = fileName + tmpString
else:
tmpString = f'softcore_'
fileName = fileName + tmpString
if (c4 == True):
tmpString = f'c4_'
fileName = fileName + tmpString
tmpString = f'N_{N}_x_{L}_y_{L}_J_{J}_alpha_{alpha}_'
fileName = fileName + tmpString
if ((hardcore == False) and (U != 0.)):
tmpString = f'U_{U}_'
fileName = fileName + tmpString
if ((hardcore == False) and (U3 != 0.)):
tmpString = f'U3_{U3}_'
fileName = fileName + tmpString
if (trapConf != 0):
tmpString = f'c_{trapConf}_g_{gamma}_'
fileName = fileName + tmpString
if (hamiltonian == False) and (spectrum == False) and (absSpectrum == False):
tmpString = f'n_{nEigenstate}'
fileName = fileName + tmpString
if (hamiltonian == True):
tmpString = f'hamiltonian'
fileName = fileName + tmpString
if (spectrum == True):
tmpString = f'spectrum'
fileName = fileName + tmpString
if (absSpectrum == True):
tmpString = f'absorption'
fileName = fileName + tmpString
if (localDensity == True):
tmpString = f'density'
fileName = fileName + tmpString
return fileName
def SaveSpectrum(fileName, energies):
fileName = fileName + '.dat'
fileDesc = open(fileName,"a")
for E in energies:
fileDesc.write(f'{E}\n')
def SaveC4Spectrum(fileName, c4Sector, energies):
"""
Save the absorption spectrum {energy -- angular momentum -- matrix element} on a file
"""
fileName = fileName + '.dat'
c4Set = [c4Sector for i in np.arange(0,len(energies))]
dataStack = np.column_stack((c4Set, energies))
print(f'Saving the C4 energy spectrum for L={c4Sector} on file "{fileName}"...')
with open(fileName,"ab") as fileDesc:
np.savetxt(fileDesc, dataStack)
def SaveVector(fileName, eigenstate):
"""
Routine to save eigenstates in .npy format (binary files)
"""
np.save(fileName, eigenstate)
def LoadVector(fileName):
"""
Routine to load data of an eigenstate from a binary file
"""
fileName = fileName + '.npy'
vector = np.load(fileName)
return vector
def SaveMatrix(fileName, matrix):
"""
Save a sparse matrix into a file
"""
sp.sparse.save_npz(fileName,matrix)
def FindCenter(L):
"""
Return the center coordinate of a square lattice sized LxL
"""
return (L/2. - 0.5)
def Phase(ang):
"""
Return a complex phase factor e^{i*ang}
"""
return np.exp(complex(0.,ang))
def Radius(i, j, c):
"""
Return the value of radius related to the coordinates (i,j) on the lattice
"""
return np.sqrt((i-c)*(i-c) + (j-c)*(j-c))
def BitArrayToString(array):
"""
Transform an array of bits in a string of bits
"""
resString = ''
for b in array:
resString = resString + str(b)
return resString
def BitStringToArray(string):
"""
Transform a string of bit in an array
"""
return [int(bit) for bit in string]
def IntToBinary(intNum, Nb):
"""
Transform an integer into a binary string of Nb bits
"""
binary = '{0:0' + str(Nb) + 'b}'
return binary.format(intNum)
def IntToBinaryArray(intNum, Nb):
"""
Transform an integer into an array of bits
"""
bitString = IntToBinary(intNum, Nb)
return BitStringToArray(bitString)
def AssignTagToState(basis, n=0):
"""
It takes the basis vectors and assign a decimal number (a tag in general) to them
"""
if (n != 1):
arrayOfStrings = [BitArrayToString(vec) for vec in basis]
return [int(binString, 2) for binString in arrayOfStrings]
else:
binaryString = BitArrayToString(basis)
return int(binaryString, 2)
def RotVec(state, r=1):
"""
Rotate a state vector by pi/2
---- parameters
state = state vector to be rotated
r = number of rotations to be performed
---- return
rotVec = array rotated by 90 degrees
"""
L = int(np.sqrt(len(state)))
#print('Initial state:')
#print(state)
stateMat = np.array([[bit for bit in state[((i-1)*L):(i*L)]] for i in np.arange(L,0,-1)])
#print('Initial state mat:')
#print(stateMat)
rotMat = stateMat.copy()
for rot in range(r):
rotMat = np.rot90(rotMat)
#print('Rotated mat:')
#print(rotMat)
rotVec = [rotMat[-(idx//L + 1)][idx%L] for idx in np.arange(0,L*L)]
#print('Rotated vector:')
#print(rotVec)
return rotVec
def RotVecInt(stateTag, Ns, softcoreBasis=None, hardcore=True):
"""
Same as RotVec() but this function works with tags of the states, i.e. it takes an integer that
represents the state, rotates this latter and gives the integer tag of the rotated state.
---- parameters
stateTag = integer representative of the state
Ns = number of lattice sites
softcoreBasis = the basis vectors in the soft-core mode (set only if hardcore=False)
hardcore = hardcore bosons flag
--- returns
rotatedTag = integer representative of the 90-degrees rotated state
"""
if hardcore == True:
state = IntToBinaryArray(stateTag, Ns)
rotState = RotVec(state)
rotatedTag = AssignTagToState(rotState, n=1)
else:
state = softcoreBasis[stateTag-1]
rotState = RotVec(state)
rotatedTag = PomeranovTag([rotState])
return rotatedTag
def FindRotatedIndex(index, L, r=1):
"""
Take a spatial index and find the corresponding one after r rotation of the lattice
"""
stateMat = np.array([[bit for bit in state[((i-1)*L):(i*L)]] for i in np.arange(L,0,-1)])
#print('Initial state mat:')
#print(stateMat)
rotMat = stateMat.copy()
for rot in range(r):
rotMat = np.rot90(rotMat)
#print('Rotated mat:')
#print(rotMat)
return
def findIntRep(state, softcoreBasis=None, hardcore=True):
"""
Take a binary string and find the integer representative of the state under C4 rotation, i.e. apply
rotation at most 4 times (then the state comes back to itself) and find the minimum integer associated
---- parameters
state = binary array of the initial state for which we want to find the representative
---- returns
repIntState = integer representative of the C4 symmetric state
pIdx = number of rotations needed to reach the state passed as parameter, from the representative
"""
Ns = len(state)
if hardcore == True:
initStateInt = AssignTagToState(state, n=1)
rotState = state
rotStateInt = 0
repIntState = initStateInt
while (rotStateInt != initStateInt):
rotState = RotVec(rotState, r=1)
rotStateInt = AssignTagToState(rotState, n=1)
if (rotStateInt < repIntState):
repIntState = rotStateInt
pIdx = StateDistance(repIntState, initStateInt, Ns)
else:
initStateInt = PomeranovTag([state])
rotState = state
rotStateInt = 0
repIntState = initStateInt
while (rotStateInt != initStateInt):
rotState = RotVec(rotState, r=1)
rotStateInt = PomeranovTag([rotState])
if (rotStateInt < repIntState):
repIntState = rotStateInt
pIdx = StateDistance(repIntState, initStateInt, Ns, softcoreBasis=softcoreBasis, hardcore=False)
return repIntState, pIdx
def StateDistance(stateInt1, stateInt2, Ns, softcoreBasis=None, hardcore=True):
"""
Calculate how many C4 rotations are needed to move from state1 to state2
"""
dist = 0
if hardcore == True:
state1 = BitStringToArray(IntToBinary(stateInt1, Ns))
state2 = BitStringToArray(IntToBinary(stateInt2, Ns))
rotState = state1
rotStateInt = stateInt1
while (rotStateInt != stateInt2):
rotState = RotVec(rotState, r=1)
rotStateInt = AssignTagToState(rotState, n=1)
dist = dist + 1
else:
rotStateInt = stateInt1
while (rotStateInt != stateInt2):
rotStateInt = RotVecInt(rotStateInt, Ns, softcoreBasis=softcoreBasis, hardcore=False)
dist = dist + 1
return dist
def CalcHofstadterPhaseFromRotation(binState, L, phaseMatrix):
"""
Calculate the phases e^{i*phi*(x*y)} to attach to a MB state in order to make it C4 symmetric
in the Hofstadter model.
We take one generic state, find its rep, then act on the rep with rotations by attaching everytime
a phase e^{i*phi*(x*y)} (where x,y are the coordinate of the state we are acting on) for each particle,
until we reach the starting state. The final phase reached is the one of the state passed as parameter.
"""
totalPhase = 0
Ns = L*L
c = FindCenter(L)
binStateString = BitArrayToString(binState)
binStateInt = AssignTagToState(binState, n=1)
repStateInt, idx = findIntRep(binState)
repStateBinArray = IntToBinary(repStateInt, Ns)
repStateBinString = BitArrayToString(repStateBinArray)
#print(f'Representative={repStateBinString}')
nextStateInt=repStateInt
nextStateArray = repStateBinArray
nextStateString = repStateBinString
while (nextStateInt != binStateInt):
#print(f'Next state in the C4 sector={nextStateString}')
filledIndices = list(i for i, x in enumerate(nextStateString) if x != '0')
for idx in filledIndices:
#print(f'idx={idx}')
x = idx%L
y = idx//L
#totalPhase = totalPhase + (x*y)
totalPhase = totalPhase + phaseMatrix[x,y]
#print(f'Adding a phase={(x*y)}')
nextStateArray = RotVec(nextStateArray)
nextStateString = BitArrayToString(nextStateArray)
nextStateInt = AssignTagToState(nextStateArray, n=1)
print(f'Fase che forse sembra vera={totalPhase}')
return totalPhase
def EvaluateHofstadterPhaseShift(stateInt, normFactor, L):
"""
Take a state descriptor and find its phase shift with respect to the representative
"""
totalPhase = 0
c = FindCenter(L)
Ns = L*L
binState = IntToBinaryArray(stateInt, Ns)
repStateInt, nbrRotFromRep = findIntRep(binState)
repStateString = IntToBinary(repStateInt, Ns)
if (nbrRotFromRep != 0):
# Find the filled indices of the representative and the coordinates, then generate the total phase
filledIndices = list(i for i, x in enumerate(repStateString) if x != '0')
for idx in filledIndices:
x = (idx%L) - c
y = (idx//L) - c
totalPhase = totalPhase + ((normFactor - nbrRotFromRep) * x * y)
#totalPhase = totalPhase + (((Ns-2) - (nbrRotFromRep*L - 1)) * x * y)
return totalPhase
def HilbertDim(N,Ns):
"""
Calculate the Hilbert space dimension for N particles in Ns sites
"""
return sp.special.comb(N+Ns-1,N)
def MapToOccupations(state):
"""
Take a Fock state e.g. [3,2,0,0,1] and map it to an array of [m1,m2,...,mN] where
mi is the site occupied by the i-th particle, e.g. -> [1,1,1,2,2,5]
"""
occArray = []
N = np.sum(state)
filledIndices = list(i for i, x in enumerate(state) if x != '0')
for idx in filledIndices:
for n in np.arange(0,state[idx]):
occArray.append(idx+1)
return occArray
def PomeranovTag(arrayOfStates, hardcore=False):
"""
Assign a tag to a Fock state following Pomeranov algorithm
"""
N = np.sum(arrayOfStates[0])
Ns = len(arrayOfStates[0])
tagArray = []
if (hardcore == False):
maxOccupationPerSite = N
else:
maxOccupationPerSite = 1
for state in arrayOfStates:
tmpTag = 1
occMap = MapToOccupations(state)
occMap.sort(reverse=True)
for j in np.arange(1,maxOccupationPerSite+1):
tmpTag = tmpTag + HilbertDim(j, Ns-occMap[j-1])
tagArray.append(int(tmpTag))
if len(tagArray) > 1:
return tagArray
else:
return tagArray[0]
def GenerateBasis(N, Ns, array=[]):
"""
Build the MB basis made of strings of dimension Ns, whose sum is constant and equal to N
---- parameters
N = number of particles
Ns = number of sites
---- return
array of strings describing the MB basis
"""
if Ns == 0:
if N == 0:
yield ''.join(map(str, array))
elif N < 0:
return
else:
for i in range(N + 1):
yield from GenerateBasis(N - i, Ns - 1, array + [i])
def GenerateHardcoreBasis(N, Ns, array=[]):
"""
Build the Hardcore MB basis made of strings of dimension Ns, whose sum is constant and equal to N
---- parameters
N = number of particles
Ns = number of sites
---- return
array of strings describing the MB basis
"""
if Ns == 0:
if N == 0:
yield ''.join(map(str, array))
elif N < 0:
return
else:
for i in [0, 1]:
yield from GenerateHardcoreBasis(N - i, Ns - 1, array + [i])
def GenerateHardcoreC4Basis(binBasis, L):
"""
Build the MB reduced Hilbert space related to the C4 sector l
---- parameters
---- return
intC4Basis = array of the form [(tag1, n1),(tag2, n2),...] where tag is the min integer of the linear combination
and n is the relative normalization factor for the state.
pIdx is the phase index related to the Aharonov-Bohm phase, that is acquired in front of
the state at every rotation.
"""
Ns = L*L
intC4Basis = []
normFactorArray = []
pIdxArray = []
n=0
for state in binBasis:
#print(f'State n.{n}')
#n = n+1
p=0
normFactor = 0
initState = state.copy()
initStateInt = AssignTagToState(initState, n=1)
rotState = state.copy()
rotStateInt = 0
repIntState = initStateInt
# until it gets to the same state
while (rotStateInt != initStateInt):
# rotate and add binStrings to a tmpArray
rotState = RotVec(rotState, r=1)
rotStateInt = AssignTagToState(rotState, n=1)
if (rotStateInt < repIntState):
repIntState = rotStateInt
p = p+1
normFactor = normFactor + 1
# check if the integer is already inside intC4basis:
# no -> append the (integer,normFactor) inside intC4Basis
if repIntState not in intC4Basis:
intC4Basis.append(repIntState)
normFactorArray.append(normFactor)
pIdxArray.append(p)
#print('Array of representative states and their norm factors:')
#print(intC4Basis)
return [[x,y,z] for x,y,z in zip(intC4Basis, normFactorArray, pIdxArray)] # stack
def GenerateSoftcoreC4Basis(binBasis, L):
"""
Build the MB C4 basis in the soft-core case (i.e. includes Pomeranov indexing)
"""
Ns = L*L
intC4Basis = []
normFactorArray = []
n=0
for state in binBasis:
#print(f'State n.{n}')
#n = n+1
normFactor = 0
initState = state.copy()
initStateInt = PomeranovTag([initState])
rotState = state.copy()
rotStateInt = 0
repIntState = initStateInt
# until it gets to the same state
while (rotStateInt != initStateInt):
# rotate and add binStrings to a tmpArray
rotState = RotVec(rotState, r=1)
rotStateInt = PomeranovTag([rotState])
if (rotStateInt < repIntState):
repIntState = rotStateInt
normFactor = normFactor + 1
# check if the integer is already inside intC4basis:
# no -> append the (integer,normFactor) inside intC4Basis
if repIntState not in intC4Basis:
intC4Basis.append(repIntState)
normFactorArray.append(normFactor)
return [[x,y] for x,y in zip(intC4Basis, normFactorArray)]
def prodA(indices, state, hardcore = True):
"""
MB annihilation operator a_i1 a_i2 ... a_in acting from right to left
---- parameters
indices = array of indices (i1,i2,...,in) for the operators
state = string describing the state we have to act on
hardcore = flag for hardcore bosons
---- return
coefficient = multiplicative factor after the action of the operators
finalState = normalized state resulting from the action of the operators ([0,0,...,0] if null state)
"""
tmpState = state.copy()
coefficient = 1
for idx in indices:
if (hardcore == True):
if (tmpState[idx] == 0):
tmpState = [elem-elem for elem in tmpState]
coefficient = 0
return tmpState, coefficient
else:
tmpState[idx] = 0
else:
if (tmpState[idx] == 0):
tmpState = [elem-elem for elem in tmpState]
coefficient = 0
return tmpState, coefficient
else:
coefficient = coefficient * np.sqrt(tmpState[idx])
tmpState[idx] = tmpState[idx] - 1
finalState = tmpState
return finalState, coefficient
def prodAd(indices, state, N, hardcore = True):
"""
MB creation operator ad_i1 ad_i2 ... ad_in acting from right to left
---- parameters
indices = array of indices (i1,i2,...,in) for the operators
state = string describing the state we have to act on
hardcore = flag for hardcore bosons
---- return
coefficient = multiplicative factor after the action of the operators
finalState = normalized state resulting from the action of the operators ([0,0,...,0] if null state)
"""
tmpState = state.copy()
coefficient = 1
for idx in indices:
if (hardcore == True):
if (tmpState[idx] == 1):
tmpState = [elem-elem for elem in tmpState]
coefficient = 0
return tmpState, coefficient
else:
tmpState[idx] = 1
else:
if (np.sum(tmpState)+1 > N):
tmpState = [elem-elem for elem in tmpState]
coefficient = 0
return tmpState, coefficient
else:
coefficient = coefficient * np.sqrt(tmpState[idx] + 1)
tmpState[idx] = tmpState[idx] + 1
finalState = tmpState
return finalState, coefficient
def GenLatticeNNLinks(L):
"""
Generates an array containing the link indices for the nearest neighbors of every site on the lattice.
E.g. for a 4x4 lattice the bottom-left site is linked upward and on the right, so the first elements
of the array will be [[(0),1,4], [(1),0,2,5], ...]
"""
linksArrayVer = [[[] for j in range(L)] for i in range(L)]
linksArrayHor = [[[] for j in range(L)] for i in range(L)]
for i in range(L):
for j in range(L):
if i > 0:
linksArrayVer[i][j].append((i - 1)*L + j)
if i < L - 1:
linksArrayVer[i][j].append((i + 1)*L + j)
if j > 0:
linksArrayHor[i][j].append(i*L + (j-1))
if j < L - 1:
linksArrayHor[i][j].append(i*L + (j+1))
return linksArrayVer, linksArrayHor
def GenLatticeNNLinksOptimized(L):
"""
Optimized version of GenLatticeNNLinks()
---- optimization
It generates one array only, containing all the horizontal and vertical NN on the lattice.
It is useful to build the Hamiltonian faster.
"""
linksArray = [[[] for j in range(L)] for i in range(L)]
for i in range(L):
for j in range(L):
if i > 0:
linksArray[i][j].append((i - 1)*L + j)
if i < L - 1:
linksArray[i][j].append((i + 1)*L + j)
if j > 0:
linksArray[i][j].append(i*L + (j-1))
if j < L - 1:
linksArray[i][j].append(i*L + (j+1))
return linksArray
def GetTunnelingDirection(initialState, finalState):
"""
Take two states and returns the spatial indices related to the particle moving from
the initial state to the final state, e.g. [0,1,2,0],[1,1,1,0] --> (2,0)
"""
initialState = np.array(initialState)
finalState = np.array(finalState)
# where XOR op. gets zero means that nothing has changed
xorState = initialState^finalState
indices = np.nonzero(xorState)[0]
if (finalState[indices[0]] > initialState[indices[0]]):
destinationIdx = indices[0]
startingIdx = indices[1]
else:
destinationIdx = indices[1]
startingIdx = indices[0]
return startingIdx, destinationIdx
def BuildHOneBody(binBasis, intBasis, linksVer, linksHor, J, FluxDensity, confinement, gamma=2, debug=False):
"""
Calculate all the non-zero matrix elements for the hopping terms of the Hofstadter model
---- Parameters
binBasis =
intBasis =
"""
print("Building the Hamiltonian...")
L = len(linksVer)
D = len(intBasis)
c = FindCenter(L)
Hmat = sp.sparse.csc_array((D,D), dtype=complex)
n=0
goodState = False
timeStart = time.time()
timeStartStates = time.time()
for state in binBasis:
stateInt = AssignTagToState(state, n=1)
#timeFor = time.time()
for i in np.arange(0,L):
for j in np.arange(0,L):
idx = i*L + j
#print("Spanning in vertical links:")
#print(linksVer[i][j])
# Vertical hopping (complex conjugate is the same if no phase factor)
if(state[idx] != 1):
for nnIndex in linksVer[i][j]:
if (state[nnIndex] != 0):
aState = prodA([nnIndex], state)
if(state[idx] != 1):
adaState = prodAd([idx], aState)
adaStateInt = AssignTagToState(adaState, n=1)
rowH = intBasis.index(adaStateInt)
colH = intBasis.index(stateInt)
Hmat[rowH,colH] += -J
#print("Non-zero matrix element initial state (Vertical):")
#print(state)
#del adaState, adaStateInt
goodState = True
# Horizontal hopping
for nnIndex in linksHor[i][j]:
if (state[nnIndex] != 0):
aState = prodA([nnIndex], state)
if(state[idx] != 1):
adaState = prodAd([idx], aState)
adaStateInt = AssignTagToState(adaState, n=1)
rowH = intBasis.index(adaStateInt)
colH = intBasis.index(stateInt)
if (nnIndex > idx): # left-hopping
Hmat[rowH,colH] += -J*Phase(-2.*np.pi*FluxDensity*i)
else: # right-hopping (complex-conjugate)
Hmat[rowH,colH] += -J*Phase(2.*np.pi*FluxDensity*i)
#del adaState, adaStateInt
goodState = True
# Trap confinement
if (state[idx] != 0):
idxDiagH = intBasis.index(stateInt)
Hmat[idxDiagH,idxDiagH] += state[idx] * confinement * (Radius(i, j, c) ** gamma)
#endTimeFor = time.time()
#print(f'Time for the for loop over sites t={(endTimeFor-timeFor)}')
if (goodState == True):
n = n+1
if (n%1000 == 0):
timeEnd = time.time()
print("basis state n."+str(n)+"/"+str(D))
locTime = (timeEnd - timeStartStates)
print(f'time for 1000 states: {locTime/60.:.2f} mins , {locTime:.2f} sec')
totTime = (timeEnd - timeStart)
print(f'total time: {totTime/60.:.2f} mins , {totTime:.2f} sec')
print(f'Expected time for building H: {D/n * (totTime/60.):.2f} mins , {D/n * (totTime):.2f} sec')
timeStartStates = time.time()
print("-----")
goodState = False
if (debug == True):
print(Hmat.toarray())
print("Number of states (off-diag) contributing to the Hamiltonian: " + str(n))
return Hmat
def BuildHOneBodyOptimized(binBasis, intBasis, links, J, FluxDensity, confinement, gamma=2, hardcore=True):
"""
Optimized version of BuildHOneBody()
---- optimization
1) It takes the MB state and transform it into a string, such that we spot the indices
related to the presence of '1's in the string, that will be our variable 'idx'.
In this way we don't have to iterate the sites with the nested for loops.
2) Use the bisection to find the indices related to the integer tag of the states
3) Use only one array 'links' and distinguish the horizontal hopping by checking
if 'nnIndex = idx +- 1'
"""
print("Building the Hamiltonian (optimized)...")
L = len(links)
D = len(intBasis)
c = FindCenter(L)
N = np.sum(binBasis[0])
Hmat = sp.sparse.lil_matrix((D,D), dtype=complex)
n = 0
colH = 1
for state in binBasis:
#print(f'State n.{n}')
#n = n+1
stateInt = AssignTagToState(state, n=1)
# this is the ket of H|state>
stateString = BitArrayToString(state)
# find the sites (idx) in which we don't have a particle
indices = list(i for i, x in enumerate(stateString) if x == '0')
for idx in indices:
for nnIndex in links[idx//L][idx%L]:
if (state[nnIndex] != 0):
aState, coeffA = prodA([nnIndex], state)
if(state[idx] != 1):
adaState, coeffAdA = prodAd([idx], aState, N)
adaStateInt = AssignTagToState(adaState, n=1)
rowH = bisect.bisect_right(intBasis,adaStateInt)
if (nnIndex == (idx+1)): # left-hopping
Hmat[rowH-1,colH-1] += -J*Phase(-2.*np.pi*FluxDensity*(idx//L))
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J*Phase(-2.*np.pi*FluxDensity*(idx//L))}')
elif (nnIndex == (idx-1)): # right-hopping
Hmat[rowH-1,colH-1] += -J*Phase(2.*np.pi*FluxDensity*(idx//L))
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J*Phase(2.*np.pi*FluxDensity*(idx//L))}')
else:
Hmat[rowH-1,colH-1] += -J
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J}')
colH = colH + 1
# add the confinement trap
filledSites = list(i for i, x in enumerate(stateString) if x == '1')
for idx in filledSites:
idxDiagH = bisect.bisect_right(intBasis, stateInt)
i = idx//L
j = idx%L
Hmat[idxDiagH-1,idxDiagH-1] += state[idx] * confinement * (Radius(i, j, c) ** gamma)
return Hmat
def BuildHOneBodyOptimizedSoftCore(binBasis, intBasis, links, J, FluxDensity, confinement, gamma=2):
"""
Optimized version of BuildHOneBody() for soft-core bosons
"""
print("Building the soft-core Hamiltonian...")
L = len(links)
D = len(intBasis)
c = FindCenter(L)
N = np.sum(binBasis[0])
print(f'Number of bosons={N}')
Hmat = sp.sparse.lil_matrix((D,D), dtype=complex)
n = 0
colH = 1
for state in binBasis:
#print(f'State n.{n}')
#n = n+1
stateInt = PomeranovTag([state])
# this is the ket of H|state>
stateString = BitArrayToString(state)
# find the sites (idx) in which we don't have a particle
indices = list(i for i, x in enumerate(stateString) if x != '0')
for idx in indices:
aState, coeffA = prodA([idx], state, hardcore=False)
for nnIndex in links[idx//L][idx%L]:
if (state[nnIndex] < N):
adaState, coeffAdA = prodAd([nnIndex], aState, N, hardcore=False)
#adaStateInt = AssignTagToState(adaState, n=1)
#rowH = bisect.bisect_right(intBasis,adaStateInt)
rowH = PomeranovTag([adaState])
if (nnIndex == (idx+1)): # right-hopping
Hmat[rowH-1,colH-1] += -J*Phase(2.*np.pi*FluxDensity*(idx//L))*coeffA*coeffAdA
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J*Phase(-2.*np.pi*FluxDensity*(idx//L))}')
elif (nnIndex == (idx-1)): # left-hopping
Hmat[rowH-1,colH-1] += -J*Phase(-2.*np.pi*FluxDensity*(idx//L))*coeffA*coeffAdA
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J*Phase(2.*np.pi*FluxDensity*(idx//L))}')
else:
Hmat[rowH-1,colH-1] += -J*coeffA*coeffAdA
#print(f'Matrix element <{rowH-1}|H|{colH-1}> = {-J}')
colH = colH + 1
# add the confinement trap
filledSites = list(i for i, x in enumerate(stateString) if x != '0')
for idx in filledSites:
i = idx//L
j = idx%L
Hmat[stateInt-1,stateInt-1] += state[idx] * confinement * (Radius(i, j, c) ** gamma)
return Hmat
def BuildHOneBodyC4Symmetry(repStatesArray, binBasis, L, links, J, FluxDensity, confinement, gamma, l):
"""
It builds the hopping Hamiltonian blocks with the C4 symmetry
"""
print(f'Building the C4 Hamiltonian in sector l={l}')
Ns = L*L
D = len(repStatesArray)
c = FindCenter(L)
# number of particles
N = np.sum(binBasis[0])
print(f'Number of particles={N}')
Hmat = sp.sparse.lil_matrix((D,D), dtype=complex)
tmpMatElem = 0
# recall the repStatesArray integers are sorted, so colH=0,1,2,3... as long as we span repStatesArray
colH = 0
intRepArray = {subArray[0]: i for i, subArray in enumerate(repStatesArray)}
#n=0
for elem in repStatesArray:
#print(f'State n.{n}')
#n = n+1
repStateInt = elem[0]
normFactor = elem[1]
repStateBin = '{0:0' + str(Ns) + 'b}'
repStateBin = repStateBin.format(repStateInt)
repState = BitStringToArray(repStateBin)
# reconstruct the symmetric state from the representative
for i in np.arange(0,normFactor):
currSubState = RotVec(repState, r=i)
currSubStateString = BitArrayToString(currSubState)
currSubStateInt = AssignTagToState(currSubStateString, n=1)
#print(f'Acting with H on ket=|{currSubStateString}> (|{AssignTagToState(currSubStateString, n=1)}>)')
currSubStatePhase = Phase(2.*np.pi*l*i / 4.)
# here the procedure is more or less the same as in BuildHOneBodyOptimized()
# find the sites (idx) in which we have a particle
filledIndices = list(i for i, x in enumerate(currSubStateString) if x == '1')
for idx in filledIndices:
iCoord = idx//L
jCoord = idx%L
aState, coeffA = prodA([idx], currSubState)
for nnIndex in links[idx//L][idx%L]:
iNNCoord = nnIndex//L
jNNCoord = nnIndex%L
if (currSubState[nnIndex] == 0):
adaState, coeffAdA = prodAd([nnIndex], aState, N)
# find the representative of this state and the phase related
adaStateInt, phaseRowIdx = findIntRep(adaState)
if adaStateInt in intRepArray:
adaStateString = BitArrayToString(adaState)
adaInt = AssignTagToState(adaStateString, n=1)
rowH = intRepArray[adaStateInt]
normFactorRow = repStatesArray[rowH][1]
rowStatePhase = Phase(2.*np.pi*l*phaseRowIdx / 4.)
if (nnIndex == (idx+1)): # right-hopping
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(iCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(iCoord-c))}')
elif (nnIndex == (idx-1)): # left-hopping
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(iCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(iCoord-c))}')
elif (nnIndex > (idx+1)): # upward
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(jCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(jCoord-c))}')
elif (nnIndex < (idx-1)): #downward
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(jCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * currSubStatePhase * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(jCoord-c))}')
# add confinement
Hmat[colH,colH] += currSubState[idx] * confinement * (Radius(iCoord, jCoord, c) ** gamma) * (1./normFactor)
colH = colH + 1
return Hmat
def BuildHOneBodyC4SymmetryOptimized(repStatesArray, binBasis, L, links, J, FluxDensity, confinement, gamma, l):
"""
Optimized version of BuildHOneBodyC4Symmetry()
--- Optimization
Now we act ONLY on the representative state (so get rid of one FOR loop inside each C4 state) and then we build the other matrix elements by rotating the
resulting action on the representative, i.e. [R, a_d a] = 0 (rotation and hopping commute)
"""
print(f'Building the C4 Hamiltonian (optimized) in sector l={l}')
Ns = L*L
D = len(repStatesArray)
c = FindCenter(L)
# number of particles
N = np.sum(binBasis[0])
Hmat = sp.sparse.lil_matrix((D,D), dtype=complex)
tmpMatElem = 0
# recall the repStatesArray integers are sorted, so colH=0,1,2,3... as long as we span repStatesArray
colH = 0
intRepArray = {subArray[0]: i for i, subArray in enumerate(repStatesArray)}
#n=0
for elem in repStatesArray:
#print(f'State n.{n}')
#n = n+1
repStateInt = elem[0]
normFactor = elem[1]
repStateString = IntToBinary(repStateInt, Ns)
repState = BitStringToArray(repStateString)
#print(f'Rep state={repStateString}')
# here the procedure is more or less the same as in BuildHOneBodyOptimized()
# find the sites (idx) in which we have a particle
filledIndices = list(i for i, x in enumerate(repStateString) if x == '1')
for idx in filledIndices:
iCoord = idx//L
jCoord = idx%L
aState, coeffA = prodA([idx], repState)
for nnIndex in links[iCoord][jCoord]:
iNNCoord = nnIndex//L
jNNCoord = nnIndex%L
if (repState[nnIndex] == 0):
adaState, coeffAdA = prodAd([nnIndex], aState, N)
# find the representative of this state and the phase related
adaStateInt, phaseRowIdx = findIntRep(adaState)
if adaStateInt in intRepArray:
#adaStateString = BitArrayToString(adaState)
#adaInt = AssignTagToState(adaStateString, n=1)
#print(f'Row vector={BitArrayToString(adaState)}')
rowH = intRepArray[adaStateInt]
normFactorRow = repStatesArray[rowH][1]
rowStatePhase = Phase(2.*np.pi*l*phaseRowIdx / 4.)
if (nnIndex == (idx+1)): # right-hopping
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(iCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(iCoord-c))}')
elif (nnIndex == (idx-1)): # left-hopping
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(iCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(iCoord-c))}')
elif (nnIndex > (idx+1)): # upward
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(jCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(-2.*np.pi*FluxDensity*0.5*(jCoord-c))}')
elif (nnIndex < (idx-1)): #downward
Hmat[rowH,colH] += -J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(jCoord-c))
#print(f'({rowH},{colH})={-J * (1./np.sqrt(normFactor*normFactorRow)) * np.conj(rowStatePhase) * Phase(2.*np.pi*FluxDensity*0.5*(jCoord-c))}')
# Here we rotate the resulting AdA|ket> (and <bra| also) state (at most normFactorRow-phaseRowIdx-1 times) and find the other matrix elements (off-diagonal terms)
for nbrRot in np.arange(1,normFactorRow):
# The representative of this is still the representative of AdA|state>
rotatedAdAKet = RotVec(adaState, r=nbrRot)
#print(f'rotation-->{BitArrayToString(rotatedAdAKet)}')
rotatedAdAKetInt = AssignTagToState(rotatedAdAKet, n=1)
rotatedRowStatePhase = Phase(2.*np.pi*l*(phaseRowIdx+nbrRot) / 4.)
# The representative of this is still repState, so no need to rotate it accordingly
rotatedKet = RotVec(repState, r=nbrRot)
rotatedKetPhase = Phase(2.*np.pi*l*nbrRot / 4.)