-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsf_modules.py
2732 lines (2675 loc) · 118 KB
/
sf_modules.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
#!/usr/bin/env python
"""
### Written by Matteo Guzzo ###
### A.D. MMXIV (2014) ###
Functions necessary to the main script for the calculation
of spectral functions.
"""
from __future__ import print_function
import numpy as np;
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy import optimize
import sys
from os.path import isfile, join, isdir
from os import getcwd, pardir, mkdir, chdir
#
def read_invar(infile='invar.in'):
"""
A small function that produces a list of the input variables
using a dictionary.
Returns a dictionary with keys and variables from the invar file.
List of variables with default values:
'sigmafile': None, # Name of file containing the self-energy
'minband': 1, Lowest band to be used in the calculation
'maxband': 1, Highest band to be used in the calculation
'minkpt': 1, Lowest kpt to be used in the calculation
'maxkpt': 1, Highest kpt to be used in the calculation
'nkpt': 1, Number of kpt (redundant, but useful to keep in mind the actual total)
'enmin': -20.0, Lowest energy to be used in the calculation for the sf output
'enmax': 20.0, Highest energy to be used in the calculation for the sf output
'sfactor': 1., Percentage of LH spectrum to be calculated [0.;1.]
'pfactor': 1., Percentage of LV spectrum to be calculated [0.;1.]
'penergy': 0.0, Photon energy
'npoles': 1, Number of poles for multipole fit
'calc_gw': 1, Enables output of GW spectral function
'calc_exp': 0, Enables output of cumulant spectral function
'calc_numeric': 0, Enables full numerical calculation of the cumulant A(w) at all orders
'calc_crc': 0, Enables output of constrained retarded cumulant spectral function
'np_crc': 1, Number of poles for B coefficient in constrained retarded cumulant spectral function
'extinf': 0, Includes extrinsic and interference effects (0, 1)
'efermi': 0.0, Fermi energy
'omega_p': 5.0, Arbitrary plasmon frequency (used only in the case npoles=999)
'max_range_integral': 10.0, Arbitrary integral range for Im(Sigma), relative to eqp (used only in the case npoles=999)
'enhartree': 0, Converts energies to eV in case they are given in Hartree (0, 1)
'gwcode': 'abinit', Name of code
'nspin': 0, Number of spin polarizations (0, 1, 2)
'spin': 0, Spin calculation (0, 1)
'is_sc': 0, Self-consistent calculation (0, 1)
'restart': 0, Will not calculate anything, but simply use the single spf files already calculated (0, 1)
'add_wtk': 1, Include k-point weights (0, 1)
'plot_fit': 0, Plot the fitted ImSigma as representation of poles (0, 1)
'ir_cut': 0.0, Puts to 0 the imaginary part of sigma in a [-ir_cut;ir_cut) range around eqp[ik,ib]
'coarse': 0, Use coarser grid for the spectral function (faster?) (0, 1)
'exact_sat1': 0, Use exact analytic formula from Ferdi's paper (0, 1)
'print_gt': 0, Print out G(t) from the numerical integration method (0, 1)
'fit_model': 'new', Choose what multipole fit model to use (old=Josh's, new=uniform binning) (old, new)
'test_lorentz_W': 0, Enables the use of a Lorentzian function (for code testing)
'calc_toc96': 0 or 1, calculate the toc96 but keep the spf renormalized to 1
'encut': 0, 1, 2 etc, the number of element arround w=0 that are removed
in the frequence list when integrating to avoid divergency at w=0.
'tfft_size': 1000, the number of elements enters in FFT.
"""
var_defaults = {
'sigmafile': None,
'calc_toc96': 0,
'encut': 0,
'tfft_size': 1000,
'minband': 1,
'maxband': 1,
'minkpt': 1,
'maxkpt': 1,
'nkpt': 1,
'enmin': -20.0,
'enmax': 20.0,
'sfactor': 1.,
'pfactor': 1.,
'penergy': 0.0,
'npoles': 1,
'calc_gw': 1,
'calc_exp': 0,
'calc_numeric': 0,
'calc_crc': 0,
'np_crc': 1,
'extinf': 0,
'efermi': 0.0,
'omega_p': 5.0,
'max_range_integral': 10.0,
'enhartree': 0,
'gwcode': 'abinit',
'nspin': 0,
'spin': 0,
'is_sc': 0,
'restart': 0,
'add_wtk': 1,
'plot_fit': 0,
'ir_cut': 0.0,
'coarse': 0,
'exact_sat1': 0,
'print_gt': 0,
'fit_model': 'new',
'test_lorentz_W': 0
}
# varlist = list((
# 'sigmafile','minband','maxnband','minkpt','maxkpt',
# 'nkpt','enmin','enmax','sfactor','pfactor','penergy',
# 'npoles','calc_gw','calc_exp','extinf','efermi',
# 'omega_p','enhartree'
# ))
varlist = var_defaults.keys()
invar_dict = var_defaults.copy()
print("read_invar :: reading file: ", infile)
with open(infile,'r') as f:
lines = [line.strip('\n') for line in f]
#print(varlist)
for var in varlist:
for line in lines:
last = line.split()[-1]
if var == last:
#print(var, last)
invar_dict[var] = line.split()[0]
return invar_dict
def imW(w,lbd=1.,w0=10.,G=1.):
"""
Imaginary part of model Lorentzian W.
"""
w = np.array(w)
return lbd*(G/((w+w0)**2+G**2)+G/((w-w0)**2+G**2))
def reW(w,lbd=1.,w0=10.,G=1.):
"""
Real part of model Lorentzian W.
"""
w = np.array(w)
return lbd*((w+w0)/((w+w0)**2+G**2)+(w-w0)/((w-w0)**2+G**2))
def model_W(w,lbd=1.,w0=10.,G=1.):
"""
Handy shorthand when needing both reW and imW.
"""
return reW(w,lbd,w0,G), imW(w,lbd,w0,G)
def read_hartree():
"""
This function takes the file 'hartree.dat'
(or alternatively the files 'Vxc.dat' and 'Elda.dat')
and creates a 'nkpt x nband' array containing the
values of the hartree energy for each state.
This array is returned.
All input files are supposed to be ordered in a
'nkpt x nband' fashion.
"""
# TODO: write a function to read the parameters from not ad-hoc files
if isfile("hartree.dat"):
print(" Reading file hartree.dat... ",end="")
hartreefile = open("hartree.dat");
hartree = [];
for line in hartreefile.readlines():
hartree.append(map(float,line.split()));
hartreefile.close()
print("Done.")
hartree = np.array(hartree);
elif isfile("E_lda.dat") and isfile("Vxc.dat"):
print("Auxiliary file (hartree.dat) not found.")
print("Reading files E_lda.dat and Vxc.dat... ",end="")
Eldafile = open("E_lda.dat");
Vxcfile = open("Vxc.dat");
elda = [];
vxc = [];
for line in Eldafile.readlines():
elda.append(map(float,line.split()));
Eldafile.close()
for line in Vxcfile.readlines():
vxc.append(map(float,line.split()));
Vxcfile.close()
print("Done.")
elda = np.array(elda);
vxc = np.array(vxc);
hartree = elda - vxc
else :
print("Auxiliary file not found (hartree/E_lda/Vxc). Impossible to continue.")
sys.exit(1)
return hartree
def read_wtk():
"""
This function takes the file 'wtk.dat'
and creates an array containing the
values of the k-point weights for each state.
This array is returned.
The input file is supposed to be a single column of
nkpt elements.
"""
if isfile("wtk.dat"):
wtkfile = open("wtk.dat");
else :
print("Auxiliary file not found (wtk.dat). Impossible to continue.")
sys.exit(1)
wtk = [];
for line in wtkfile.readlines():
wtk.append((float(line)));
wtkfile.close()
wtk = np.array(wtk);
return wtk
def read_occ(maxkpt,minband,maxband):
"""
This function takes the file 'occ.dat'
and creates an array containing the
occupation number for each state.
This array is returned.
All input files are supposed to be ordered in a
'nkpt x nband' fashion.
"""
if isfile("occ.dat"):
occfile = open("occ.dat");
occ = [];
for line in occfile.readlines():
occ.append(map(float,line.split()));
occfile.close()
occ = np.array(occ)
else :
print("Auxiliary file not found (occ.dat). ")
print("Setting all occupations to 2.0.")
occ = 2.0*np.ones((maxkpt,maxband-minband+1))
return occ
def strictly_increasing(L):
return all(x<y for x, y in zip(L, L[1:]))
def calc_nkpt_sigfile(insigfile, spin = False):
"""
Get number of kpt from a _SIG file
"""
print("calc_nkpt_sigfile ::",end='')
insigfile.seek(0)
lines = insigfile.readlines()
nkpt = 0
for line in lines:
if '#' in line:
nkpt += 1
nkpt = nkpt/2
if spin == 1:
nkpt = nkpt/2
print("nkpt= {}".format(nkpt))
return nkpt
def read_wtk_sigfile(insigfile, spin = 0):
"""
Get wtk (k-point weights) from a SelfXC.dat file (exciting)
"""
print("read_wtk_sigfile ::")
insigfile.seek(0)
lines = insigfile.readlines()
wtk = []
for line in lines:
if 'wkpt' in line:
wtk.append(float(line.split()[-1]))
if spin == 1:
wtk = wtk[::2]
print("wtk = {}".format(wtk))
print("read_wtk_sigfile :: Done.")
return wtk
def read_sigfile(invar_dict):
"""
A hopefully better version.
This has to deal with the fact that abinit does not write
all values of sigma for one enery on a single line, but
instead goes on a newline when a certain limit is reached.
also: SPIN!!! For the moment, it will skip every second kpt,
i.e. it will read only one spin channel.
"""
import glob
from time import sleep
print("read_sigfile :: ",end="")
# We put the content of the file (lines) in this array
sigfilename = invar_dict['sigmafile']
spin = int(invar_dict['spin'])
nspin = int(invar_dict['nspin'])
#en=[]
firstbd = 0
lastbd = 0
nbd = 0
#sngl_row = True # are data not split in more than 1 line?
if sigfilename is None:
print("File "+str(sigfilename)+" not defined.")
sigfilename = glob.glob('*_SIG')[0]
print("Looking automatically for a _SIG file... ",sigfilename)
with open(sigfilename) as insigfile:
filelines = insigfile.readlines()
nkpt = calc_nkpt_sigfile(insigfile,spin)
if invar_dict['gwcode'] == 'exciting':
invar_dict['wtk'] = read_wtk_sigfile(insigfile)
insigfile.seek(0)
insigfile.readline()
line = insigfile.readline()
firstbd = int(line.split()[-2])
lastbd = int(line.split()[-1])
nbd = lastbd - firstbd + 1
print("nbd:",nbd)
num_cols = len(insigfile.readline().split())
num_cols2 = len(insigfile.readline().split())
print("numcols:",num_cols)
print("numcols2:",num_cols2)
if num_cols != num_cols2:
print()
print(" WARNING: newlines in _SIG file.")
print(" Reshaping _SIG file structure...")
print(" _SIG file length (rows):", len(filelines))
new_list = []
nline = 0
a = []
b = []
for line in filelines:
#if line.split()[0] == "#":
if '#' in line:
print(line.strip('\n'))
continue
elif nline == 0:
a = line.strip('\n')
nline += 1
else:
b = line.strip('\n')
new_list.append(a + " " + b)
nline = 0
print("New shape for _SIG array:",np.asarray(new_list).shape)
tmplist = []
tmplist2 = []
for line in new_list:
tmplist.append(map(float,line.split())[0])
tmplist2.append(map(float,line.split())[1:])
for el1 in tmplist2:
for j in el1:
try:
float(j)
except:
print(j)
#tmplist = map(float,tmplist)
#tmplist2 = map(float,tmplist2)
xen = np.asarray(tmplist)
x = np.asarray(tmplist2)
else:
insigfile.seek(0)
xen = np.genfromtxt(sigfilename,usecols = 0)
insigfile.seek(0)
x = np.genfromtxt(sigfilename,usecols = range(1,num_cols), filling_values = 'myNaN')
#nkpt = int(invar_dict['nkpt'])
print("nkpt:",nkpt)
print("spin:",spin)
print("nspin:",nspin)
# From a long line to a proper 2D array, then only first row
#print(xen.shape)
print("x.shape", x.shape)
if spin == 1 and nspin == 0:
nspin = 2
else:
nspin = 1
print("nspin:",nspin)
print("size(xen):",xen.size)
print("The size of a single energy array should be",\
float(np.size(xen))/nkpt/nspin)
en = xen.reshape(nkpt*nspin,np.size(xen)/nkpt/nspin)[0]
#en = xen.reshape(nkpt,np.size(xen)/nkpt)[0]
print("New shape en:",np.shape(en))
print("First row of x:",x[0])
if invar_dict['gwcode'] == 'abinit':
nb_cols = 3
elif invar_dict['gwcode'] == 'exciting':
nb_cols = 2
#b = x.reshape(nkpt*nspin,np.size(x)/nkpt/nspin/nbd/3,3*nbd)
b = x.reshape(nkpt*nspin,np.size(x)/nkpt/nspin/nbd/nb_cols,nb_cols*nbd)
print("New shape x:",b.shape)
y = b[0::nspin,:,0::nb_cols]
z = b[0::nspin,:,1::nb_cols]
res = np.rollaxis(y,-1,1)
ims = np.rollaxis(z,-1,1)
print("New shape res, ims:", res.shape)
print("First and last band in _SIG file:", firstbd, lastbd)
print(" Done.")
return en, res, ims, (firstbd, lastbd)
def read_cross_sections(penergy):
"""
This function should read the values for the cross sections
given a photon energy 'penergy' from the file
"cs'penergy'.dat" and construct an array "cs"
containing the values.
For now only s and p are expected, but they can be added
seamlessly to the file. Only, the other part of the code
using the cs array would have to be changed accordingly.
cs array is returned.
"""
print(" ### Reading cross sections... ")
if int(penergy) == 0:
cs = np.array([0.1,0.1])
else:
csfilename = "cs"+str(int(penergy))+".dat"
if isfile(csfilename):
print(" Photon energy:", penergy,"eV")
else:
penergy = raw_input(" File "+csfilename+" not found. Photon energy (eV): ")
csfilename = "cs"+str(penergy)+".dat"
cs = []
print(" csfilename:",csfilename)
csfile = open(csfilename,'r')
for line in csfile.readlines():
cs.append((float(line)));
csfile.close()
cs = np.array(cs)
#print("cs:",cs.shape,cs)
#print("cs:",np.transpose(cs),cs.shape)
return cs
def calc_pdos(var_dct,res=None):
"""
Calculates projected DOS for all bands contained in the
sigma file.
"""
penergy = float(var_dct['penergy'])
sfac = float(var_dct['sfactor'])
pfac = float(var_dct['pfactor'])
#nband = int(var_dct['nband'])
nband = int(var_dct['sig_bdgw'][1]) - int(var_dct['sig_bdgw'][0]) + 1
#[print(x, var_dct[x]) for x in var_dct if ('band' in x) | ('bd' in x)]
if penergy != 0:
# ======== CROSS SECTIONS ======= #
cs = read_cross_sections(penergy)
# ====== BAND TYPE AND SYMMETRY ==== #
sp = read_band_type_sym(sfac,pfac,nband)
# ===== EFFECTIVE STATE-DEPENDENT PREFACTOR ==== #
pdos = 10000.*np.dot(cs,sp)
else:
pdos=np.ones((nband))
if res is not None:
tail = np.ones(shape=(res[0,:,0].size-pdos.size))*pdos[-1] # same weight as last item of pdos
pdos = np.concatenate((pdos,tail))
return pdos
def read_band_type_sym(sfac,pfac,nband):
"""
This function reads the s,p (TODO and d,f)
composition of bands, descerning between
s (mirror-even) and p (mirror-odd) symmetries
with respect to a plane normal to the surface
of the sample.
By consequence, the preparation of the input
files s.dat, p_even.dat and p_odd.dat is crucial
for a correct description of cross-section
and symmetry effects.
The function takes sfac and pfac as inputs, so that
one can simulate LH or LV light measurements.
A 'sp' symmetry-biased array is created, following the
number of band types that are considered (s and p for now).
sp numpy array is returned.
"""
print(" Reading s bands file... ",)
if isfile("s.dat"):
sfile = open("s.dat",'r')
s = map(float,sfile.read().split())
sfile.close()
s = np.array(s)
print("Done.")
else :
print()
print(" WARNING: File for orbital character not found (s.dat). S character will be 1 for all bands. ")
s = np.ones(nband)
print(" Reading p bands file... ",)
if isfile("p_even.dat") and isfile("p_odd.dat"):
# This file should contain the summed contribution of all even p orbitals
pevenfile = open("p_even.dat",'r')
# This file should contain the summed contribution of all odd p orbitals
poddfile = open("p_odd.dat",'r')
peven = map(float,pevenfile.read().split())
podd = map(float,poddfile.read().split())
pevenfile.close()
poddfile.close()
peven = np.array(peven)
podd = np.array(podd)
print("Done.")
else :
print()
print(" WARNING: File for orbital character not found (p_even.dat/p_odd.dat). P character will be 1 for all bands. ")
peven = np.ones(nband)
podd = np.ones(nband)
# TODO: Add d bands!!!
# Warning: in this section it is easy to confuse
# s and p symmetry with s and p electrons!
# Don't worry, it's normal.
s = sfac*s
peven = sfac*peven
podd = pfac*podd
p = peven+podd
sp = np.array([s,p])
#print("sp:",sp)
return sp
#def calc_spf_gw(minkpt,maxkpt,minband,maxband,wtk,pdos,en,enmin,enmax,res,ims,hartree):
def calc_sf_gw(vardct,hartree,pdos,en,res,ims):
"""
Macro-function calling instructions necessary to calculate
the GW spectral function.
For now it writes out the single state spectral functions
on ascii files. This should be moved to an external module
and just return spfkb as an output variable.
spf (GW spectral function) is returned.
"""
print("calc_sf_gw :: ")
wtk = np.array(vardct['wtk'])
hartree = np.array(hartree)
pdos = np.array(pdos)
#minkpt = int(vardct['minkpt'])
#maxkpt = int(vardct['maxkpt'])
nkpt = res[:,0,0].size
#maxkpt - minkpt + 1
#minband = int(vardct['minband'])
#maxband = int(vardct['maxband'])
nband = res[0,:,0].size
print("nkpt, nband ", nkpt, nband)
#bdgw = map(int, vardct['sig_bdgw'])
#bdrange = range(minband-bdgw[0],maxband-bdgw[0]+1)
#kptrange = range(minkpt - 1, maxkpt)
#maxband - minband + 1
coarse = int(vardct['coarse'])
if coarse == 1:
newdx = 0.2
else:
newdx = 0.005
enmin = float(vardct['enmin'])
enmax = float(vardct['enmax'])
if enmin < en[0] and enmax >= en[-1]:
newen = np.arange(en[0],en[-1],newdx)
elif enmin < en[0]:
newen = np.arange(en[0],enmax,newdx)
elif enmax >= en[-1] :
newen = np.arange(enmin,en[-1],newdx)
else :
newen = np.arange(enmin,enmax,newdx)
print(" ### Interpolation and calculation of A(\omega)_GW... ")
spftot = np.zeros((np.size(newen)));
# Here we interpolate re and im sigma
# for each band and k point
spfkb = np.zeros(shape=(res[:,0,0].size,res[0,:,0].size,np.size(newen)))
reskb = np.zeros(shape=(res[:,0,0].size,res[0,:,0].size,np.size(newen)))
imskb = np.zeros(shape=(res[:,0,0].size,res[0,:,0].size,np.size(newen)))
rdenkb = np.zeros(shape=(res[:,0,0].size,res[0,:,0].size,np.size(newen)))
#spfkb = np.zeros(shape=(nkpt,nband,np.size(newen)))
#reskb = np.zeros(shape=(nkpt,nband,np.size(newen)))
#imskb = np.zeros(shape=(nkpt,nband,np.size(newen)))
#rdenkb = np.zeros(shape=(nkpt,nband,np.size(newen)))
bdgw = map(int, vardct['sig_bdgw'])
bdrange = vardct['bdrange']
kptrange = vardct['kptrange']
#for ik in range(nkpt):
# #ikeff = minkpt+ik-1
# print(" k point, nband = %02d %02d" % (ik,nband))
# #print(" nband = %02d " % (nband))
# for ib in range(nband):
# #ibeff = minband+ib-1
for ik in kptrange:
#ikeff = ik + minkpt
ikeff = ik + 1
#for ib in range(nband):
for ib in bdrange:
#ibeff = ib + minband
ibeff = ib + bdgw[0]
print(ik, ib)
#plt.plot(en,ims[ik,ib])
interpres = interp1d(en, res[ik,ib], kind = 'linear', axis = -1)
interpims = interp1d(en, ims[ik,ib], kind = 'linear', axis = -1)
tmpres = interpres(newen)
reskb[ik,ib] = tmpres
#redenom = newen + efermi - hartree[ik,ib] - interpres(newen)
redenom = newen - hartree[ik,ib] - interpres(newen)
#plt.plot(hartree[ik,ib],'o')
rdenkb[ik,ib] = redenom
#print("ik ib minband maxband ibeff hartree[ik,ib]", ik, ib, minband, maxband, ibeff, hartree[ik,ib])
tmpim = interpims(newen)
imskb[ik,ib] = tmpim
#print("pdos ",pdos)
spfkb_tmp = wtk[ik] * pdos[ib] * abs(tmpim)/np.pi/(redenom**2 + tmpim**2)
#print(spfkb.shape, spfkb_tmp.shape)
spfkb[ik,ib] = spfkb_tmp
spftot += spfkb_tmp
allkb = [spfkb, reskb, rdenkb, imskb]
#plt.plot(newen,spftot)
print("reskb.shape:",reskb.shape)
return newen, spftot, allkb
#return newen, spftot, spfkb,reskb, rdemkb, imskb
def write_spfkb(vardct, newen, allkb):
"""
Does what it says. For the GW spectral function.
"""
print("write_spfkb :: ")
minkpt = int(vardct['minkpt'])
maxkpt = int(vardct['maxkpt'])
nkpt = maxkpt - minkpt + 1
minband = int(vardct['minband'])
maxband = int(vardct['maxband'])
nband = maxband - minband + 1
bdgw = map(int, vardct['sig_bdgw'])
#bdrange = range(minband - bdgw[0], maxband - bdgw[0] + 1)
#kptrange = range(minkpt - 1, maxkpt)
bdrange = vardct['bdrange']
kptrange = vardct['kptrange']
spfkb = allkb[0]
reskb = allkb[1]
rdenkb = allkb[2]
imskb = allkb[3]
#for ik in range(nkpt):
# #print(" k point = %02d " % (ikeff+1))
# ikeff = minkpt + ik
# for ib in range(nband):
for ik in kptrange:
#ikeff = ik + minkpt
ikeff = ik + 1
#for ib in range(nband):
for ib in bdrange:
#ibeff = ib + minband
ibeff = ib + bdgw[0]
outnamekb = "spf_gw-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+".dat"
outfilekb = open(outnamekb,'w')
for ien in xrange(np.size(newen)) :
outfilekb.write("%8.4f %12.8e %12.8e %12.8e %12.8e\n" % (newen[ien], spfkb[ik,ib,ien], rdenkb[ik,ib,ien], reskb[ik,ib,ien], imskb[ik,ib,ien]))
outfilekb.close()
print("write_spfkb :: Done.")
def find_eqp_resigma(en, resigma, efermi):
"""
This function is supposed to deal with the plasmaron problem
and calculate the quasiparticle energy once it is fed with
resigma = \omega - \epsilon_H - \Re\Sigma.
It expects an array of increasing values on the x axis
and it will return
the x value of the last resigma=0 detected.
It should return the value of eqp and the number of zeros
found (useful in case there are plasmarons or for debugging).
If no zeros are found, it will fit resigma with a line and
extrapolate a value.
"""
nzeros=0
zeros = []
tmpeqp = en[0]
for i in xrange(1,np.size(resigma)):
#print(resigma[i]*resigma[i-1] # DEBUG)
if resigma[i] == 0: # Yes, it can happen
tmpeqp = en[i]
zeros.append(en[i])
nzeros+=1
elif (resigma[i]*resigma[i-1] < 0):
tmpeqp = en[i-1] - resigma[i-1]*(en[i] - en[i-1])/(resigma[i] - resigma[i-1]) # High school formula
zeros.append(tmpeqp)
nzeros+=1
if tmpeqp>efermi:
tmpeqp=zeros[0]
if nzeros==0 :
print()
print(" WARNING: No eqp found! ")
def fit_func(x, a, b):
return a*x + b
from scipy.optimize import curve_fit
params = curve_fit(fit_func, en, resigma)
[a, b] = params[0]
if -b/a < en[-1]:
print("WTF!!! BYE!")
sys.exit()
tmpeqp = -b/a
zeros.append(tmpeqp)
elif nzeros>1 :
print(" WARNING: Plasmarons! ")
return tmpeqp, nzeros
def write_eqp_imeqp(eqp,imeqp):
"""
Does what it says.
"""
print("write_eqp_imeqp :: ")
outname = "eqp.dat"
outfile2 = open(outname,'w')
outname = "imeqp.dat"
outfile3 = open(outname,'w')
for ik in xrange(np.size(eqp[:,0])):
for ib in xrange(np.size(eqp[0,:])):
outfile2.write("%14.5f" % (eqp[ik,ib]))
outfile3.write("%14.5f" % (imeqp[ik,ib]))
outfile2.write("\n")
outfile3.write("\n")
outfile2.close()
outfile3.close()
print("write_eqp_imeqp :: Done.")
def calc_eqp_imeqp(en,res,ims,hartree,efermi):
"""
This function calculates qp energies and corresponding
values of the imaginary part of sigma for a set of
k points and bands.
The function find_eqp_resigma() is used here.
eqp and imeqp are returned.
"""
from scipy import interp
nkpt = np.size(res[:,0,0])
nband = np.size(res[0,:,0])
eqp = np.zeros((nkpt,nband))
imeqp = np.zeros((nkpt,nband))
hartree = np.array(hartree)
for ik in range(nkpt):
for ib in range(nband):
#temparray = np.array(en - hartree[ik,ib] - res[ik,ib])
temparray = np.array(en - hartree[ik,ib] - res[ik,ib])
interpims = interp1d(en, ims[ik,ib], kind = 'linear', axis = -1)
tempim = interpims(en)
# New method to overcome plasmaron problem
eqp[ik,ib], nzeros = find_eqp_resigma(en,temparray,efermi)
if nzeros==0:
print()
print(" WARNING: ik "+str(ik)+" ib "+str(ib)+". No eqp found!!!")
if (eqp[ik,ib] > en[0]) and (eqp[ik,ib] < en[-1]):
#print(en[0], eqp[ik,ib], en[-1])
imeqp[ik,ib] = interpims(eqp[ik,ib])
else:
imeqp[ik,ib] = interp(eqp[ik,ib], en, ims[ik,ib])
## Warning if imaginary part of sigma < 0 (Convergence problems?)
if imeqp[ik,ib] <= 0 :
print()
print(" WARNING: im(Sigma(eps_k)) <= 0 !!! ik ib eps_k im(Sigma(eps_k)) = ", ik, ib, eqp[ik,ib], imeqp[ik,ib])
return eqp, imeqp
def calc_extinf_corrections(origdir,extinfname,ampole,omegampole):
"""
# Here we add the extrinsic contribution.
# N.B.: It has to be renormalized to the number of poles!!!
# The data are interpolated linearly with a numerical function.
# The fit curve of ext+inf passes by the origin.
The file structure is expected to be:
# wp, aext, ainf, aint, width
"""
import multipole.getdata_file as getdata_file #, write_f_as_sum_of_poles
#extinfname = "a_wp.dat"
print(" Reading extrinsic and interference contribution from file "+str(extinfname)+"...")
en_ei, aext = getdata_file(origdir+"/"+str(extinfname))
en_ei, ainf = getdata_file(origdir+"/"+str(extinfname),2)
aextinf = aext+ainf
newen_ei = []
newen_ei.append(0.0)
for x in en_ei.tolist():
newen_ei.append(x)
newen_ei = np.array(newen_ei)
newa_ei = []
newa_ei.append(0.0)
for x in aextinf.tolist():
newa_ei.append(x)
newa_ei = np.array(newa_ei)
# a_int from the model is in the third column
en_ei, aint = getdata_file(origdir+"/"+str(extinfname),3)
newa_int = []
a_int_zero = aint[1] - en_ei[1]*(aint[0]-aint[1])/(en_ei[0]-en_ei[1])
newa_int.append(a_int_zero)
for x in aint.tolist():
newa_int.append(x)
newa_int = np.array(newa_int)
# broadening from the model is in the fourth column
en_ei, width = getdata_file(origdir+"/"+str(extinfname),4)
newwmod = []
w_zero = width[1] - en_ei[1]*(width[0]-width[1])/(en_ei[0]-en_ei[1])
newwmod.append(w_zero)
for x in width.tolist():
newwmod.append(x)
newwmod = np.array(newwmod)
interpwidth = interp1d(newen_ei, newwmod, kind = 'linear', axis = -1)
w_extinf = ampole.copy()
print("omega_p, a_extinf, a_int:")
print(newen_ei)
print(newa_ei)
print(newa_ei/newa_int)
#print(en_ei, newenexin)
#print(aextinf, newaexin)
interpextinf = interp1d(newen_ei, newa_ei/newa_int, kind = 'linear', axis = -1)
amp_exinf = ampole.copy()
#print("Type(amp_exinf, ampole):", type(amp_exinf), type(ampole))
# Mod following discussion with Josh
amp_mean = np.mean(ampole)
for ik in range(ampole[:,0,0].size):
for ib in range(ampole[0,:,0].size):
#tmpextinf = interpextinf(omegampole[ik,ib])/npoles # <-- Divided by the number of poles (normalization)!
try:
w_extinf[ik,ib] = interpwidth(omegampole[ik,ib]) # Numpy array
except ValueError:
print()
print(" WARNING: A value for omega_p is beyond what contained in a_wp.x.")
print(" The last available value is taken. ")
print("ik, ib, omegampole: ", ik, ib, omegampole[ik,ib])
w_extinf[ik,ib] = np.interp(omegampole[ik,ib],newen_ei,newwmod)
try:
tmpextinf = interpextinf(omegampole[ik,ib]) #
except ValueError:
print()
print(" WARNING: A value for omega_p is beyond what contained in a_wp.x.")
tmpextinf = np.interp(omegampole[ik,ib],newen_ei, newa_ei/newa_int)
# Mod following discussion with Josh
#amp_exinf[ik,ib] += ampole[ik,ib] * tmpextinf
amp_exinf[ik,ib] += amp_mean * tmpextinf
return amp_exinf, w_extinf
def read_sf(vardct, pdos, approx):
"""
This function reads the spectral functions from the files
spf_gw- or spf_exp- and returns their sum,
according to minband, maxband and minkpt, maxkpt.
"""
print("read_sf :: ")
minkpt = int(vardct['minkpt'])
maxkpt = int(vardct['maxkpt'])
nkpt = maxkpt - minkpt + 1
minband = int(vardct['minband'])
maxband = int(vardct['maxband'])
nband = maxband - minband + 1
extinf = int(vardct['extinf'])
npoles = int(vardct['npoles'])
penergy = int(vardct['penergy'])
#wtk = np.array(vardct['wtk'])
#hartree = np.array(hartree)
bdrange = vardct['bdrange']
print("bdrange", bdrange)
kptrange = vardct['kptrange']
print("kptrange", kptrange)
pdos = np.array(pdos)
if extinf == 1:
str_exi = "_extinf"
else:
str_exi = ""
if approx == 'exp':
end_fname = "_np"+str(npoles)+str_exi+"."+str(penergy)
elif approx == 'gw':
end_fname = ".dat"
# Initialize sf
ikeff = minkpt
ibeff = minband
fname = "spf_"+str(approx)+"-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+str_exi+end_fname
en = np.genfromtxt(fname, usecols = 0) # sigfilename,usecols = range(1,num_cols), filling_values = 'myNaN')
#sf = np.genfromtxt(fname, usecols = 1) # sigfilename,usecols = range(1,num_cols), filling_values = 'myNaN')
sf = np.zeros((en.size))
#bdgw = map(int, vardct['sig_bdgw'])
#for ik in range(nkpt):
for ik in kptrange:
#print(" k point = %02d " % (ikeff+1))
ikeff = ik + 1
#for ib in range(nband):
for ib in bdrange:
#ibeff = minband + ib
ibeff = ib + 1
print("ikeff, ibeff: ",ikeff,ibeff)
#outnamekb = "spf_gw-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+".dat"
#outnamekb = "spf_"+str(approx)+"-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+"_np"+str(npoles)+str_exi+"."+str(penergy)
fname = "spf_"+str(approx)+"-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+str_exi+end_fname
print("fname: ",fname)
tmp_sf = np.genfromtxt(fname, usecols = 1) # sigfilename,usecols = range(1,num_cols), filling_values = 'myNaN')
#en, tmp_sf = np.genfromtxt(fname) # sigfilename,usecols = range(1,num_cols), filling_values = 'myNaN')
sf += tmp_sf
#with open(fname,'r') as ifkb:
# for ien in range(en.size):
# ifkb.write("%8.4f %12.8f\n" % (en[ien], sfkb[ik,ib,ien]))
print("read_sf :: Done.")
return en, sf
def calc_spf_mpole(enexp,prefac,akb,omegakb,eqpkb,imkb,npoles,wkb=None):
"""
OBSOLETE???
This function calculates the exponential spectral function.
"""
nenexp=np.size(enexp)
ftot = np.zeros((np.size(enexp)))
tmpf1=np.zeros((nenexp))
tmpf2=np.zeros((nenexp))
tmpf3=np.zeros((nenexp))
if wkb is None:
wkb = np.zeros(npoles)
for ipole in xrange(npoles):
#print(" First order")
tmpf2=0.
for jpole in xrange(npoles):
#print(" Second order")
tmpf3=0.
for kpole in xrange(npoles):
## Fourth order
#tmpf4 = np.zeros((np.size(enexp)))
#for ipole4 in xrange(npoles):
#tmpf4[:] += 1./4. * ( abs( imeqp[ik,ib] ) / ( ( enexp[:] - eqp[ik,ib] + omegampole[ik,ib,ipole] + omegampole[ik,ib,jpole] + omegampole[ik,ib,kpole] + omegampole[ik,ib,ipole4] )**2 + ( imeqp[ik,ib] )**2 ) )
tmpomegap = omegakb[ipole]+omegakb[jpole]+omegakb[kpole]
tmpgamma = (wkb[ipole]+wkb[jpole]+wkb[kpole])/2
tmpf3+=1./3.*akb[kpole]/((enexp-eqpkb+tmpomegap)**2+(tmpgamma+imkb)**2 )
tmpomegap = omegakb[ipole]+omegakb[jpole]
tmpgamma = (wkb[ipole]+wkb[jpole])/2
tmpf2+=1./2.*akb[jpole]*(1./((enexp - eqp[ik,ib]+tmpomegap)**2+(tmpgamma+imkb)**2 ) + tmpf3 )
tmpomegap = omegakb[ipole]
tmpgamma = (wkb[ipole])/2
tmpf1+=1.*akb[ipole]*(1./((enexp-eqp[ik,ib]+tmpomegap)**2+(tmpgamma+imkb)**2)+tmpf2)
#f[ik,ib]=prefac*(1./((enexp-eqpkb)**2+(imkb)**2)+tmpf1)
#ftot += f[ik,ib]
f=prefac*(1./((enexp-eqpkb)**2+(imkb)**2)+tmpf1)
ftot += f
return ftot
def write_sfkb_c(vardct,en,sfkb):
"""
Does what it says. For the cumulant spectral function.
"""
sfkb = np.array(sfkb)
print("write_sfkb_c :: ")
minkpt = int(vardct['minkpt'])
maxkpt = int(vardct['maxkpt'])
nkpt = maxkpt - minkpt + 1
minband = int(vardct['minband'])
maxband = int(vardct['maxband'])
nband = maxband - minband + 1
bdgw = map(int, vardct['sig_bdgw'])
bdrange = range(minband-bdgw[0],maxband-bdgw[0]+1)
kptrange = range(minkpt - 1, maxkpt)
extinf = int(vardct['extinf'])
npoles = "_np"+vardct['npoles']
penergy = int(vardct['penergy'])
label = '_exp'
if int(vardct['calc_numeric']) == 1:
label += '_num'
npoles = ''
#plt.plot(en,sfkb[0,4])
#plt.show()
if extinf == 1:
str_exi = "_extinf"
else:
str_exi = ""
for ik in kptrange:
#print(" k point = %02d " % (ikeff+1))
#ikeff = minkpt + ik
ikeff = ik + 1
for ib in bdrange:
#ibeff = minband + ib
ibeff = ib + bdgw[0]
outnamekb = "spf"+str(label)+"-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+str(npoles)+str_exi+"."+str(penergy)
#outnamekb = "spf_exp-k"+str("%02d"%(ikeff))+"-b"+str("%02d"%(ibeff))+"_np"+str(npoles)+str_exi+"."+str(penergy)
print("ik,ib: ",ik,ib)
print(" Writing on file : ", outnamekb)
with open(outnamekb,'w') as ofkb:
for ien in range(en.size):
ofkb.write("%9.4f %15.8f\n" % (en[ien], sfkb[ik,ib,ien]))
print("write_sfkb_c :: Done.")
def calc_sf_c(vardct, hartree, pdos, eqp, imeqp, newen, allkb):
"""
Meta-function that calls serial or para version.
Still wishful thinking ATM, as it just calls the serial version.
"""
npoles = int(vardct['npoles'])
#if npoles == 0 or npoles == 1 or npoles == 999:
enexp, ftot, sfkb_c = \
calc_sf_c_serial(\
vardct, hartree, pdos, eqp, imeqp, newen, allkb)
#else:
# enexp, ftot, sfkb_c = \
# calc_sf_c_para(\
# vardct, hartree, pdos, eqp, imeqp, newen, allkb)
return enexp, ftot, sfkb_c
def calc_multipole(npoles, imskb, kptrange, bdrange, eqp, newen):
"""
Function that calculates frequencies and amplitudes
of ImSigma using the multipole model.
"""
from multipole import fit_multipole #, write_f_as_sum_of_poles
print(" ### ================== ###")
print(" ### Multipole fit ###")
print(" Number of poles:", npoles)
omegampole = np.zeros((imskb[:,0,0].size,imskb[0,:,0].size,npoles))
ampole = np.zeros((imskb[:,0,0].size,imskb[0,:,0].size,npoles))
for ik in kptrange:
for ib in bdrange:
if eqp[ik,ib] > newen[-npoles]:
omegampole[ik,ib] = omegampole[ik,ib-1]
ampole[ik,ib] = ampole[ik,ib-1]
print(" Eqp beyond available energy range. Values from lower band are taken.")
continue
else:
ibeff = bdrange[0] + ib - 1
print(" ik, ib", ik, ib)
# Here we take the curve starting from eqp and then we invert it
# so as to have it defined on the positive x axis
# and so that the positive direction is in the
# increasing direction of the array index
if eqp[ik,ib] <= 0:
en3 = newen[newen<=eqp[ik,ib]] # So as to avoid negative omegampole
im3 = abs(imskb[ik,ib][newen<=eqp[ik,ib]]/np.pi) # This is what should be fitted
else:
en3 = newen[newen>eqp[ik,ib]] # So as to avoid negative omegampole
im3 = abs(imskb[ik,ib][newen<=eqp[ik,ib]]/np.pi) # This is what should be fitted
if en3.size == 0:
print()
print(" WARNING: QP energy is outside of given energy range!\n"+\
" This state will be skipped!\n"+\
"You might want to modify enmin/enmax.")
print(" eqp[ik,ib], newen[-1]", eqp[ik,ib] , newen[-1])