-
Notifications
You must be signed in to change notification settings - Fork 11
/
gpawsolve.py
executable file
·1928 lines (1727 loc) · 106 KB
/
gpawsolve.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
'''
gpawsolve.py: High-level Interaction Script for GPAW
More information: $ gpawsolve.py -h
'''
Description = f'''
Usage:
$ mpirun -np <corenumbers> gpawsolve.py <args>
-------------------------------------------------------------
Calculation selector
-------------------------------------------------------------
| Method | XCs | Structure optim. | Spin | Ground | Elastic | DOS | DFT+U | Band | Density | Optical |
| ------ | --------------- | ---------------- | ---- | ------ | ------- | --- | ----- | ---- | ------- | ------- |
| PW | Local and LibXC | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
| PW | GLLBSC / M | No | Yes | Yes | Yes | Yes | No | Yes | Yes | Yes |
| PW | HSE03, HSE06 | No | Yes | Yes | n/a | Yes | No | No | No | No |
| PW-G0W0| Local and LibXC | No | No | Yes | No | No | No | Some | No | No |
| LCAO | Local and LibXC | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
*: Just some ground state energy calculations.
'''
import getopt, sys, os, time, shutil
import textwrap
import requests
import pickle
from argparse import ArgumentParser, HelpFormatter
from ase import *
from ase.spacegroup import get_spacegroup
from ase.dft.kpoints import get_special_points
from ase.parallel import paropen, world, parprint, broadcast
from gpaw import GPAW, PW, Davidson, FermiDirac, MixerSum, MixerDif, Mixer
from ase.optimize import QuasiNewton
from ase.io import read, write
from ase.eos import calculate_eos
from ase.units import Bohr, GPa, kJ
import matplotlib.pyplot as plt
from ase.constraints import FixSymmetry
from ase.filters import FrechetCellFilter
from ase.io.cif import write_cif
from pathlib import Path
from gpaw.response.df import DielectricFunction
from gpaw.response.bse import BSE
from gpaw.response.g0w0 import G0W0
from gpaw.response.gw_bands import GWBands
from gpaw.dos import DOSCalculator
from gpaw.utilities.dos import raw_orbital_LDOS
import numpy as np
from numpy import genfromtxt
from elastic import get_elastic_tensor, get_elementary_deformations
from phonopy import Phonopy
from phonopy.structure.atoms import PhonopyAtoms
from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections
import phonopy
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
class RawFormatter(HelpFormatter):
"""To print Description variable with argparse"""
def _fill_text(self, text, width, indent):
return "\n".join([textwrap.fill(line, width) for line in textwrap.indent(textwrap.dedent(text), indent).splitlines()])
def struct_from_file(inputfile, geometryfile):
"""Load variables from parse function"""
global bulk_configuration
# Works like from FILE import *
inputf = __import__(Path(inputfile).stem, globals(), locals(), ['*'])
for k in dir(inputf):
# Still can not get rid of global variable usage :(
globals()[k] = getattr(inputf, k)
# If there is a CIF input, use it. Otherwise use the bulk configuration provided above.
if geometryfile is None:
if Outdirname !='':
struct = Outdirname
else:
struct = 'results' # All files will get their names from this file
else:
struct = Path(geometryfile).stem
bulk_configuration = read(geometryfile, index='-1')
parprint("Number of atoms imported from CIF file:"+str(bulk_configuration.get_global_number_of_atoms()))
parprint("Spacegroup of CIF file:",get_spacegroup(bulk_configuration, symprec=1e-2))
parprint("Special Points usable for this spacegroup:",get_special_points(bulk_configuration.get_cell()))
# Output directory
if Outdirname != '':
structpath = os.path.join(os.getcwd(),Outdirname)
else:
structpath = os.path.join(os.getcwd(),struct)
if not os.path.isdir(structpath):
os.makedirs(structpath, exist_ok=True)
struct = os.path.join(structpath,struct)
return struct
def autoscale_y(ax,margin=0.1):
"""This function rescales the y-axis based on the data that is visible given the current xlim of the axis.
ax -- a matplotlib axes object
margin -- the fraction of the total height of the y-data to pad the upper and lower ylims"""
import numpy as np
def get_bottom_top(line):
xd = line.get_xdata()
yd = line.get_ydata()
lo,hi = ax.get_xlim()
y_displayed = yd[((xd>lo) & (xd<hi))]
h = np.max(y_displayed) - np.min(y_displayed)
bot = np.min(y_displayed)-margin*h
top = np.max(y_displayed)+margin*h
return bot,top
lines = ax.get_lines()
bot,top = np.inf, -np.inf
for line in lines:
new_bot, new_top = get_bottom_top(line)
if new_bot < bot: bot = new_bot
if new_top > top: top = new_top
ax.set_ylim(bot,top)
class gpawsolve:
"""
The gpawsolve class is a high-level interaction script for GPAW calculations.
It handles various types of calculations such as ground state, structure optimization,
elastic properties, density of states, band structure, density, and optical properties.
The class takes input parameters from a configuration file and performs the calculations
accordingly.
"""
def __init__(self, struct):
global np
self.Mode = Mode
self.Geo_optim = Geo_optim
self.Elastic_calc = Elastic_calc
self.DOS_calc = DOS_calc
self.Band_calc = Band_calc
self.Density_calc = Density_calc
self.Optical_calc = Optical_calc
self.Optimizer = Optimizer
self.Max_F_tolerance = Max_F_tolerance
self.Max_step = Max_step
self.Alpha = Alpha
self.Damping = Damping
self.Fix_symmetry = Fix_symmetry
self.Relax_cell = Relax_cell
self.Hydrostatic_pressure = Hydrostatic_pressure
self.Cut_off_energy = Cut_off_energy
self.Ground_kpts_density = Ground_kpts_density
self.Ground_kpts_x = Ground_kpts_x
self.Ground_kpts_y = Ground_kpts_y
self.Ground_kpts_z = Ground_kpts_z
self.Ground_gpts_density = Ground_gpts_density
self.Ground_gpts_x = Ground_gpts_x
self.Ground_gpts_y = Ground_gpts_y
self.Ground_gpts_z = Ground_gpts_z
self.Setup_params = Setup_params
self.XC_calc = XC_calc
self.Ground_convergence = Ground_convergence
self.Occupation = Occupation
self.Mixer_type = Mixer_type
self.Spin_calc = Spin_calc
self.Magmom_per_atom = Magmom_per_atom
self.Magmom_single_atom = Magmom_single_atom
self.DOS_npoints = DOS_npoints
self.DOS_width = DOS_width
self.DOS_convergence = DOS_convergence
self.Gamma = Gamma
self.Band_path = Band_path
self.Band_npoints = Band_npoints
self.Energy_max = Energy_max
self.Energy_min = Energy_min
self.Band_convergence = Band_convergence
self.Refine_grid = Refine_grid
self.Phonon_PW_cutoff = Phonon_PW_cutoff
self.Phonon_kpts_x = Phonon_kpts_x
self.Phonon_kpts_y = Phonon_kpts_y
self.Phonon_kpts_z = Phonon_kpts_z
self.Phonon_supercell = Phonon_supercell
self.Phonon_displacement = Phonon_displacement
self.Phonon_path = Phonon_path
self.Phonon_npoints = Phonon_npoints
self.Phonon_acoustic_sum_rule = Phonon_acoustic_sum_rule
self.GW_calc_type = GW_calc_type
self.GW_kpoints_list = GW_kpoints_list
self.GW_truncation = GW_truncation
self.GW_cut_off_energy = GW_cut_off_energy
self.GW_valence_band_no = GW_valence_band_no
self.GW_conduction_band_no = GW_conduction_band_no
self.GW_PPA = GW_PPA
self.GW_q0_correction = GW_q0_correction
self.GW_nblocks_max = GW_nblocks_max
self.GW_interpolate_band = GW_interpolate_band
self.Opt_calc_type = Opt_calc_type
self.Opt_shift_en = Opt_shift_en
self.Opt_BSE_valence = Opt_BSE_valence
self.Opt_BSE_conduction = Opt_BSE_conduction
self.Opt_BSE_min_en = Opt_BSE_min_en
self.Opt_BSE_max_en = Opt_BSE_max_en
self.Opt_BSE_num_of_data = Opt_BSE_num_of_data
self.Opt_num_of_bands = Opt_num_of_bands
self.Opt_FD_smearing = Opt_FD_smearing
self.Opt_eta = Opt_eta
self.Opt_domega0 = Opt_domega0
self.Opt_omega2 = Opt_omega2
self.Opt_cut_of_energy = Opt_cut_of_energy
self.Opt_nblocks = Opt_nblocks
self.MPI_cores = MPI_cores
self.Localisation = Localisation
self.bulk_configuration = bulk_configuration
self.struct = struct
self.dos_xlabel = dos_xlabel
self.dos_ylabel = dos_ylabel
self.band_ylabel = band_ylabel
def structurecalc(self):
"""
This method calculates and writes the spacegroup and special points of the given structure.
It reads the bulk configuration from the CIF file and prints the number of atoms, spacegroup,
and special points usable for the spacegroup to a text file.
"""
# -------------------------------------------------------------
# Step 0 - STRUCTURE
# -------------------------------------------------------------
with paropen(struct+'-0-Result-Spacegroup-and-SpecialPoints.txt', "w") as fd:
print("Number of atoms imported from CIF file:"+str(bulk_configuration.get_global_number_of_atoms()), file=fd)
print("Spacegroup of CIF file:",get_spacegroup(bulk_configuration, symprec=1e-2), file=fd)
print("Special Points usable for this spacegroup:",get_special_points(bulk_configuration.get_cell()), file=fd)
def groundcalc(self):
"""
This method performs ground state calculations for the given structure using various settings
and parameters specified in the configuration file. It handles different XC functionals,
spin calculations, and geometry optimizations. The results are saved in appropriate files,
including the final configuration as a CIF file and the ground state results in a GPW file.
"""
# -------------------------------------------------------------
# Step 1 - GROUND STATE
# -------------------------------------------------------------
# Start ground state timing
time11 = time.time()
if Mode == 'PW':
if Spin_calc == True:
if 'Magmom_single_atom' in globals() and Magmom_single_atom is not None:
numm = [0.0]*bulk_configuration.get_global_number_of_atoms()
numm[Magmom_single_atom[0]] = Magmom_single_atom[1]
else:
numm = [Magmom_per_atom]*bulk_configuration.get_global_number_of_atoms()
bulk_configuration.set_initial_magnetic_moments(numm)
if Ground_calc == True:
# PW Ground State Calculations
parprint("Starting PW ground state calculation...")
if True in Relax_cell:
if XC_calc in ['GLLBSC', 'GLLBSCM', 'HSE06', 'HSE03','B3LYP', 'PBE0','EXX']:
parprint("\033[91mERROR:\033[0m Structure optimization LBFGS can not be used with "+XC_calc+" xc.")
parprint("Do manual structure optimization, or do with PBE, then use its final CIF as input.")
parprint("Quiting...")
quit()
if XC_calc in ['HSE06', 'HSE03','B3LYP', 'PBE0','EXX']:
parprint('Starting Hybrid XC calculations...')
if 'Ground_kpts_density' in globals() and Ground_kpts_density is not None:
calc = GPAW(mode=PW(ecut=Cut_off_energy, force_complex_dtype=True), xc={'name': XC_calc, 'backend': 'pw'}, nbands='200%',
parallel={'band': 1, 'kpt': 1}, eigensolver=Davidson(niter=1), mixer=Mixer_type, charge=Total_charge,
spinpol=Spin_calc, kpts={'density': Ground_kpts_density, 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',
convergence = Ground_convergence, occupations = Occupation)
else:
calc = GPAW(mode=PW(ecut=Cut_off_energy, force_complex_dtype=True), xc={'name': XC_calc, 'backend': 'pw'}, nbands='200%',
parallel={'band': 1, 'kpt': 1}, eigensolver=Davidson(niter=1), mixer=Mixer_type, charge=Total_charge,
spinpol=Spin_calc, kpts={'size': (Ground_kpts_x, Ground_kpts_y, Ground_kpts_z), 'gamma': Gamma}, txt=struct+'-1-Log-Ground.txt',
convergence = Ground_convergence, occupations = Occupation)
else:
parprint('Starting calculations with '+XC_calc+'...')
# Fix the spacegroup in the geometric optimization if wanted
if Fix_symmetry == True:
bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))
if 'Ground_kpts_density' in globals() and Ground_kpts_density is not None:
calc = GPAW(mode=PW(ecut=Cut_off_energy, force_complex_dtype=True), xc=XC_calc, nbands='200%', setups= Setup_params,
parallel={'domain': world.size}, spinpol=Spin_calc, kpts={'density': Ground_kpts_density, 'gamma': Gamma},
mixer=Mixer_type, txt=struct+'-1-Log-Ground.txt', charge=Total_charge,
convergence = Ground_convergence, occupations = Occupation)
else:
calc = GPAW(mode=PW(ecut=Cut_off_energy, force_complex_dtype=True), xc=XC_calc, nbands='200%', setups= Setup_params,
parallel={'domain': world.size}, spinpol=Spin_calc, kpts={'size': (Ground_kpts_x, Ground_kpts_y, Ground_kpts_z), 'gamma': Gamma},
mixer=Mixer_type, txt=struct+'-1-Log-Ground.txt', charge=Total_charge,
convergence = Ground_convergence, occupations = Occupation)
bulk_configuration.calc = calc
if Geo_optim == True:
if True in Relax_cell:
if Hydrostatic_pressure > 0.0:
uf = FrechetCellFilter(bulk_configuration, mask=Relax_cell, hydrostatic_strain=True, scalar_pressure=Hydrostatic_pressure)
else:
uf = FrechetCellFilter(bulk_configuration, mask=Relax_cell)
# Optimizer Selection
if Optimizer == 'FIRE':
from ase.optimize.fire import FIRE
relax = FIRE(uf, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'LBFGS':
from ase.optimize.lbfgs import LBFGS
relax = LBFGS(uf, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'GPMin':
from ase.optimize import GPMin
relax = GPMin(uf, trajectory=struct+'-1-Result-Ground.traj')
else:
relax = QuasiNewton(uf, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
else:
# Optimizer Selection
if Optimizer == 'FIRE':
from ase.optimize.fire import FIRE
relax = FIRE(bulk_configuration, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'LBFGS':
from ase.optimize.lbfgs import LBFGS
relax = LBFGS(bulk_configuration, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'GPMin':
from ase.optimize import GPMin
relax = GPMin(bulk_configuration, trajectory=struct+'-1-Result-Ground.traj')
else:
relax = QuasiNewton(bulk_configuration, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
relax.run(fmax=Max_F_tolerance) # Consider tighter fmax!
else:
bulk_configuration.set_calculator(calc)
bulk_configuration.get_potential_energy()
if Density_calc == True:
#This line makes huge GPW files. Therefore it is better to use this if else
calc.write(struct+'-1-Result-Ground.gpw', mode="all")
else:
calc.write(struct+'-1-Result-Ground.gpw')
# Writes final configuration as CIF file
write_cif(struct+'-Final.cif', bulk_configuration)
else:
parprint("Passing PW ground state calculation...")
# Control the ground state GPW file
if not os.path.exists(struct+'-1-Result-Ground.gpw'):
parprint('\033[91mERROR:\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in other calculations. Firstly, finish the ground state calculation. You must have \033[95mGround_calc = True\033[0m line in your input file. Quiting.')
quit()
elif Mode == 'PW-GW':
if Ground_calc == True:
# PW Ground State Calculations
parprint("Starting PW only ground state calculation for GW calculation...")
# Fix the spacegroup in the geometric optimization if wanted
if Fix_symmetry == True:
bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))
if 'Ground_kpts_density' in globals() and Ground_kpts_density is not None:
calc = GPAW(mode=PW(Cut_off_energy), xc=XC_calc, parallel={'domain': 1}, kpts={'density': Ground_kpts_density, 'gamma': Gamma},
convergence = Ground_convergence, charge=Total_charge,
mixer=Mixer_type, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')
else:
calc = GPAW(mode=PW(Cut_off_energy), xc=XC_calc, parallel={'domain': 1}, kpts={'size':(Ground_kpts_x, Ground_kpts_y, Ground_kpts_z), 'gamma': Gamma},
convergence = Ground_convergence, charge=Total_charge,
mixer=Mixer_type, occupations = Occupation, txt=struct+'-1-Log-Ground.txt')
bulk_configuration.calc = calc
if Hydrostatic_pressure > 0.0:
uf = FrechetCellFilter(bulk_configuration, mask=Relax_cell, hydrostatic_strain=True, scalar_pressure=Hydrostatic_pressure)
else:
uf = FrechetCellFilter(bulk_configuration, mask=Relax_cell)
# Optimizer Selection
if Optimizer == 'FIRE':
from ase.optimize.fire import FIRE
relax = FIRE(uf, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'LBFGS':
from ase.optimize.lbfgs import LBFGS
relax = LBFGS(uf, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'GPMin':
from ase.optimize import GPMin
relax = GPMin(uf, trajectory=struct+'-1-Result-Ground.traj')
else:
relax = QuasiNewton(uf, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
relax.run(fmax=Max_F_tolerance) # Consider tighter fmax!
bulk_configuration.get_potential_energy()
calc.diagonalize_full_hamiltonian()
calc.write(struct+'-1-Result-Ground.gpw', mode="all")
# Writes final configuration as CIF file
write_cif(struct+'-Final.cif', bulk_configuration)
# Print final spacegroup information
parprint("Final Spacegroup:",get_spacegroup(bulk_configuration, symprec=1e-2))
else:
parprint("Passing ground state calculation for GW calculation...")
# Control the ground state GPW file
if not os.path.exists(struct+'-1-Result-Ground.gpw'):
parprint('\033[91mERROR:\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in other calculations. Firstly, finish the ground state calculation. You must have \033[95mGround_calc = True\033[0m line in your input file. Quiting.')
quit()
# We start by setting up a G0W0 calculator object
gw = G0W0(struct+'-1-Result-Ground.gpw', filename=struct+'-1-', bands=(GW_valence_band_no, GW_conduction_band_no),
method=GW_calc_type,truncation=GW_truncation, nblocksmax=GW_nblocks_max,
maxiter=5, q0_correction=GW_q0_correction, charge=Total_charge,
mixing=0.5,savepckl=True,
ecut=GW_cut_off_energy, ppa=GW_PPA)
parprint("Starting PW ground state calculation with G0W0 approximation...")
gw.calculate()
results = pickle.load(open(struct+'-1-_results.pckl', 'rb'))
with paropen(struct+'-1-BandGap.txt', "w") as fd:
print('Quasi particle (QP) energies in eV. Take CB-VB for the bandgap', file=fd)
print('To see other energy contributions, use python -mpickle <picklefile>', file=fd)
for x in zip(results['qp']):
print(*x, sep=", ", file=fd)
elif Mode == 'LCAO':
if Spin_calc == True:
if 'Magmom_single_atom' in globals() and Magmom_single_atom is not None:
numm = [0.0]*bulk_configuration.get_global_number_of_atoms()
numm[Magmom_single_atom[0]] = Magmom_single_atom[1]
else:
numm = [Magmom_per_atom]*bulk_configuration.get_global_number_of_atoms()
bulk_configuration.set_initial_magnetic_moments(numm)
if Ground_calc == True:
parprint("Starting LCAO ground state calculation...")
# Fix the spacegroup in the geometric optimization if wanted
if Fix_symmetry == True:
bulk_configuration.set_constraint(FixSymmetry(bulk_configuration))
if 'Ground_gpts_density' in globals() and Ground_gpts_density is not None:
if 'Ground_kpts_density' in globals() and Ground_kpts_density is not None:
calc = GPAW(mode='lcao', basis='dzp', setups= Setup_params, kpts={'density': Ground_kpts_density, 'gamma': Gamma},
convergence = Ground_convergence, h=Ground_gpts_density, spinpol=Spin_calc, txt=struct+'-1-Log-Ground.txt',
mixer=Mixer_type, occupations = Occupation, nbands='200%', parallel={'domain': world.size}, charge=Total_charge)
else:
calc = GPAW(mode='lcao', basis='dzp', setups= Setup_params, kpts={'size':(Ground_kpts_x, Ground_kpts_y, Ground_kpts_z), 'gamma': Gamma},
convergence = Ground_convergence, h=Ground_gpts_density, spinpol=Spin_calc, txt=struct+'-1-Log-Ground.txt',
mixer=Mixer_type, occupations = Occupation, nbands='200%', parallel={'domain': world.size}, charge=Total_charge)
else:
if 'Ground_kpts_density' in globals() and Ground_kpts_density is not None:
calc = GPAW(mode='lcao', basis='dzp', setups= Setup_params, kpts={'density': Ground_kpts_density, 'gamma': Gamma},
convergence = Ground_convergence, gpts=(Ground_gpts_x, Ground_gpts_y, Ground_gpts_z), spinpol=Spin_calc, txt=struct+'-1-Log-Ground.txt',
mixer=Mixer_type, occupations = Occupation, nbands='200%', parallel={'domain': world.size}, charge=Total_charge)
else:
calc = GPAW(mode='lcao', basis='dzp', setups= Setup_params, kpts={'size':(Ground_kpts_x, Ground_kpts_y, Ground_kpts_z), 'gamma': Gamma},
convergence = Ground_convergence, gpts=(Ground_gpts_x, Ground_gpts_y, Ground_gpts_z), spinpol=Spin_calc, txt=struct+'-1-Log-Ground.txt',
mixer=Mixer_type, occupations = Occupation, nbands='200%', parallel={'domain': world.size}, charge=Total_charge)
bulk_configuration.calc = calc
if Geo_optim == True:
if True in Relax_cell:
#uf = FrechetCellFilter(bulk_configuration, mask=Relax_cell)
#relax = LBFGS(uf, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
parprint('\033[91mERROR:\033[0mModifying supercell and atom positions with a filter (Relax_cell keyword) is not implemented in LCAO mode.')
quit()
else:
# Optimizer Selection
if Optimizer == 'FIRE':
from ase.optimize.fire import FIRE
relax = FIRE(bulk_configuration, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'LBFGS':
from ase.optimize.lbfgs import LBFGS
relax = LBFGS(bulk_configuration, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
elif Optimizer == 'GPMin':
from ase.optimize import GPMin
relax = GPMin(bulk_configuration, trajectory=struct+'-1-Result-Ground.traj')
else:
relax = QuasiNewton(bulk_configuration, maxstep=Max_step, trajectory=struct+'-1-Result-Ground.traj')
relax.run(fmax=Max_F_tolerance) # Consider tighter fmax!
else:
bulk_configuration.set_calculator(calc)
bulk_configuration.get_potential_energy()
#relax = LBFGS(bulk_configuration, maxstep=Max_step, alpha=Alpha, damping=Damping, trajectory=struct+'-1-Result-Ground.traj')
#relax.run(fmax=Max_F_tolerance) # Consider much tighter fmax!
#bulk_configuration.get_potential_energy()
if Density_calc == True:
#This line makes huge GPW files. Therefore it is better to use this if else
calc.write(struct+'-1-Result-Ground.gpw', mode="all")
else:
calc.write(struct+'-1-Result-Ground.gpw')
# Writes final configuration as CIF file
write_cif(struct+'-Final.cif', bulk_configuration)
# Print final spacegroup information
parprint("Final Spacegroup:",get_spacegroup(bulk_configuration, symprec=1e-2))
else:
parprint("Passing LCAO ground state calculation...")
# Control the ground state GPW file
if not os.path.exists(struct+'-1-Result-Ground.gpw'):
parprint('\033[91mERROR:\033[0m'+struct+'-1-Result-Ground.gpw file can not be found. It is needed in other calculations. Firstly, finish the ground state calculation. You must have \033[95mGround_calc = True\033[0m line in your input file. Quiting.')
quit()
elif Mode == 'FD':
parprint("\033[91mERROR:\033[0mFD mode is not implemented in gpaw-tools yet...")
quit()
else:
parprint("\033[91mERROR:\033[0mPlease enter correct mode information.")
quit()
# Finish ground state timing
time12 = time.time()
# Write timings of calculation
with paropen(struct+'-7-Result-Log-Timings.txt', 'a') as f1:
print('Ground state: ', round((time12-time11),2), end="\n", file=f1)
def elasticcalc(self, drawfigs = False):
"""
This method performs elastic property calculations for the given structure using the
ground state results. It computes the elastic constants, bulk modulus, shear modulus,
and other related properties. The results are saved in appropriate files for further
analysis and visualization.
"""
# -------------------------------------------------------------
# Step 1.5 - ELASTIC CALCULATION
# -------------------------------------------------------------
# Start elastic calc
time151 = time.time()
parprint('Starting elastic tensor calculations (\033[93mWARNING:\033[0mNOT TESTED FEATURE, PLEASE CONTROL THE RESULTS)...')
calc = GPAW(struct+'-1-Result-Ground.gpw').fixed_density(txt=struct+'-1.5-Log-Elastic.txt')
# Getting space group
parprint("Spacegroup:",get_spacegroup(bulk_configuration, symprec=1e-2))
# Calculating equation of state
parprint('Calculating equation of state...')
eos = calculate_eos(bulk_configuration, trajectory=struct+'-1.5-Result-Elastic.traj')
v, e, B = eos.fit()
# Calculating elastic tensor
parprint('Calculating elastic tensor...')
Cij, Bij=get_elastic_tensor(bulk_configuration,get_elementary_deformations(bulk_configuration, n=5, d=2))
with paropen(struct+'-1.5-Result-Elastic.txt', "w") as fd:
print("Elastic calculation results (NOT TESTED FEATURE, PLEASE CONTROL THE RESULTS):", file=fd)
print("EoS: Stabilized jellium equation of state (SJEOS)", file=fd)
print("Refs: Phys.Rev.B 63, 224115 (2001) and Phys.Rev.B 67, 026103 (2003)", file=fd)
print("Elastic constants: Standart elasticity theory calculated by -Elastic- library", file=fd)
print("Ref: European Physical Journal B; 15, 2 (2000) 265-268", file=fd)
print("-----------------------------------------------------------------------------", file=fd)
print("Spacegroup: "+str(get_spacegroup(bulk_configuration, symprec=1e-2)), file=fd)
print("B (GPa): "+str(B / kJ * 1.0e24), file=fd)
print("e (eV): "+str(e), file=fd)
print("v (Ang^3): "+str(v), file=fd)
print("Cij (GPa): ",Cij/GPa, file=fd)
print("The general ordering of Cij components is (except triclinic): C11,C22,C33,C12,C13,C23,C44,C55,C66,C16,C26,C36,C45.", file=fd)
# Finish elastic calc
time152 = time.time()
# Write timings of calculation
with paropen(struct+'-7-Result-Log-Timings.txt', 'a') as f1:
print('Elastic calculation: ', round((time152-time151),2), end="\n", file=f1)
# Draw or write the figure
if drawfigs == True:
# Draw graphs only on master node
if world.rank == 0:
# Elastic
eos.plot(struct+'-1.5-Graph-Elastic-EOS.png', show=True)
else:
# Draw graphs only on master node
if world.rank == 0:
# Elastic
eos.plot(struct+'-1.5-Result-Elastic-EOS.png')
def doscalc(self, drawfigs = False):
"""
This method performs density of states (DOS) calculations for the given structure using
the ground state results. It computes the DOS for various energy levels and saves the
results in appropriate files for further electronic analysis and visualization.
"""
# -------------------------------------------------------------
# Step 2 - DOS CALCULATION
# -------------------------------------------------------------
# Start DOS calc
time21 = time.time()
parprint("Starting DOS calculation...")
if XC_calc in ['HSE06', 'HSE03','B3LYP', 'PBE0','EXX']:
parprint('Passing DOS NSCF calculations...')
calc = GPAW().read(filename=struct+'-1-Result-Ground.gpw')
ef=0.0 # Can not find the use get_fermi_level()
else:
calc = GPAW(struct+'-1-Result-Ground.gpw').fixed_density(txt=struct+'-2-Log-DOS.txt', convergence = DOS_convergence, occupations = Occupation)
ef = calc.get_fermi_level()
chem_sym = bulk_configuration.get_chemical_symbols()
if Spin_calc == True:
#Spin down
# RAW PDOS for spin down
parprint("Calculating and saving Raw PDOS for spin down...")
if ef==0.0:
rawdos = DOSCalculator.from_calculator(filename=struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)
else:
rawdos = DOSCalculator.from_calculator(filename=struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=False)
energies = rawdos.get_energies(npoints=DOS_npoints)
# Weights
pdossweightsdown = [0.0] * DOS_npoints
pdospweightsdown = [0.0] * DOS_npoints
pdospxweightsdown = [0.0] * DOS_npoints
pdospyweightsdown = [0.0] * DOS_npoints
pdospzweightsdown = [0.0] * DOS_npoints
pdosdweightsdown = [0.0] * DOS_npoints
pdosdxyweightsdown = [0.0] * DOS_npoints
pdosdyzweightsdown = [0.0] * DOS_npoints
pdosd3z2_r2weightsdown = [0.0] * DOS_npoints
pdosdzxweightsdown = [0.0] * DOS_npoints
pdosdx2_y2weightsdown = [0.0] * DOS_npoints
pdosfweightsdown = [0.0] * DOS_npoints
totaldosweightsdown = [0.0] * DOS_npoints
# Writing RawPDOS
with paropen(struct+'-2-Result-RawPDOS-EachAtom-Down.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for j in range(0, bulk_configuration.get_global_number_of_atoms()):
print("Atom no: "+str(j+1)+", Atom Symbol: "+chem_sym[j]+" --------------------", file=fd)
pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=0, width=DOS_width)
pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=0, width=DOS_width)
pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=0, width=DOS_width)
pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=0, width=DOS_width)
pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=0, width=DOS_width)
pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=0, width=DOS_width)
pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=0, width=DOS_width)
pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=0, width=DOS_width)
pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=0, width=DOS_width)
pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=0, width=DOS_width)
pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=0, width=DOS_width)
pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=0, width=DOS_width)
dosspdf = pdoss + pdosp + pdosd + pdosf
# Weights
pdossweightsdown = pdossweightsdown + pdoss
pdospweightsdown = pdospweightsdown + pdosp
pdospxweightsdown = pdospxweightsdown + pdospx
pdospyweightsdown = pdospyweightsdown + pdospy
pdospzweightsdown = pdospzweightsdown + pdospz
pdosdweightsdown = pdosdweightsdown + pdosd
pdosdxyweightsdown = pdosdxyweightsdown + pdosd
pdosdyzweightsdown = pdosdyzweightsdown + pdosd
pdosd3z2_r2weightsdown = pdosd3z2_r2weightsdown + pdosd
pdosdzxweightsdown = pdosdzxweightsdown + pdosd
pdosdx2_y2weightsdown = pdosdx2_y2weightsdown + pdosd
pdosfweightsdown = pdosfweightsdown + pdosf
totaldosweightsdown = totaldosweightsdown + dosspdf
for x in zip(energies, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf, dosspdf):
print(*x, sep=", ", file=fd)
# Writing DOS
parprint("Saving DOS for spin down...")
with paropen(struct+'-2-Result-DOS-Down.csv', "w") as fd:
for x in zip(energies, totaldosweightsdown):
print(*x, sep=", ", file=fd)
# Writing PDOS
parprint("Saving PDOS for spin down...")
with paropen(struct+'-2-Result-PDOS-Down.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for x in zip(energies, pdossweightsdown, pdospweightsdown, pdospxweightsdown, pdospyweightsdown, pdospzweightsdown, pdosdweightsdown,
pdosdxyweightsdown, pdosdyzweightsdown, pdosd3z2_r2weightsdown, pdosdzxweightsdown, pdosdx2_y2weightsdown, pdosfweightsdown, totaldosweightsdown):
print(*x, sep=", ", file=fd)
#Spin up
# RAW PDOS for spin up
parprint("Calculating and saving Raw PDOS for spin up...")
rawdos = DOSCalculator.from_calculator(struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)
energies = rawdos.get_energies(npoints=DOS_npoints)
# Weights
pdossweightsup = [0.0] * DOS_npoints
pdospweightsup = [0.0] * DOS_npoints
pdospxweightsup = [0.0] * DOS_npoints
pdospyweightsup = [0.0] * DOS_npoints
pdospzweightsup = [0.0] * DOS_npoints
pdosdweightsup = [0.0] * DOS_npoints
pdosdxyweightsup = [0.0] * DOS_npoints
pdosdyzweightsup = [0.0] * DOS_npoints
pdosd3z2_r2weightsup = [0.0] * DOS_npoints
pdosdzxweightsup = [0.0] * DOS_npoints
pdosdx2_y2weightsup = [0.0] * DOS_npoints
pdosfweightsup = [0.0] * DOS_npoints
totaldosweightsup = [0.0] * DOS_npoints
#Writing RawPDOS
with paropen(struct+'-2-Result-RawPDOS-EachAtom-Up.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for j in range(0, bulk_configuration.get_global_number_of_atoms()):
print("Atom no: "+str(j+1)+", Atom Symbol: "+chem_sym[j]+" --------------------", file=fd)
pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=1, width=DOS_width)
pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=1, width=DOS_width)
pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=1, width=DOS_width)
pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=1, width=DOS_width)
pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=1, width=DOS_width)
pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=1, width=DOS_width)
pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=1, width=DOS_width)
pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=1, width=DOS_width)
pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=1, width=DOS_width)
pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=1, width=DOS_width)
pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=1, width=DOS_width)
pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=1, width=DOS_width)
dosspdf = pdoss + pdosp + pdosd + pdosf
# Weights
pdossweightsup = pdossweightsup + pdoss
pdospweightsup = pdospweightsup + pdosp
pdospxweightsup = pdospxweightsup + pdospx
pdospyweightsup = pdospyweightsup + pdospy
pdospzweightsup = pdospzweightsup + pdospz
pdosdweightsup = pdosdweightsup + pdosd
pdosdxyweightsup = pdosdxyweightsup + pdosd
pdosdyzweightsup = pdosdyzweightsup + pdosd
pdosd3z2_r2weightsup = pdosd3z2_r2weightsup + pdosd
pdosdzxweightsup = pdosdzxweightsup + pdosd
pdosdx2_y2weightsup = pdosdx2_y2weightsup + pdosd
pdosfweightsup = pdosfweightsup + pdosf
totaldosweightsup = totaldosweightsup + dosspdf
for x in zip(energies, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf, dosspdf):
print(*x, sep=", ", file=fd)
# Writing DOS
parprint("Saving DOS for spin up...")
with paropen(struct+'-2-Result-DOS-Up.csv', "w") as fd:
for x in zip(energies, totaldosweightsup):
print(*x, sep=", ", file=fd)
# Writing PDOS
parprint("Saving PDOS for spin up...")
with paropen(struct+'-2-Result-PDOS-Up.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for x in zip(energies, pdossweightsup, pdospweightsup, pdospxweightsup, pdospyweightsup, pdospzweightsup, pdosdweightsup, pdosdxyweightsup,
pdosdyzweightsup, pdosd3z2_r2weightsup, pdosdzxweightsup, pdosdx2_y2weightsup, pdosfweightsup, totaldosweightsup):
print(*x, sep=", ", file=fd)
else:
# RAW PDOS
parprint("Calculating and saving Raw PDOS...")
rawdos = DOSCalculator.from_calculator(struct+'-1-Result-Ground.gpw',soc=False, theta=0.0, phi=0.0, shift_fermi_level=True)
energies = rawdos.get_energies(npoints=DOS_npoints)
totaldosweights = [0.0] * DOS_npoints
pdossweights = [0.0] * DOS_npoints
pdospweights = [0.0] * DOS_npoints
pdospxweights = [0.0] * DOS_npoints
pdospyweights = [0.0] * DOS_npoints
pdospzweights = [0.0] * DOS_npoints
pdosdweights = [0.0] * DOS_npoints
pdosdxyweights = [0.0] * DOS_npoints
pdosdyzweights = [0.0] * DOS_npoints
pdosd3z2_r2weights = [0.0] * DOS_npoints
pdosdzxweights = [0.0] * DOS_npoints
pdosdx2_y2weights = [0.0] * DOS_npoints
pdosfweights = [0.0] * DOS_npoints
# Writing RawPDOS
with paropen(struct+'-2-Result-RawPDOS-EachAtom.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for j in range(0, bulk_configuration.get_global_number_of_atoms()):
print("Atom no: "+str(j+1)+", Atom Symbol: "+chem_sym[j]+" ----------------------------------------", file=fd)
pdoss = rawdos.raw_pdos(energies, a=j, l=0, m=None, spin=None, width=DOS_width)
pdosp = rawdos.raw_pdos(energies, a=j, l=1, m=None, spin=None, width=DOS_width)
pdospx = rawdos.raw_pdos(energies, a=j, l=1, m=2, spin=None, width=DOS_width)
pdospy = rawdos.raw_pdos(energies, a=j, l=1, m=0, spin=None, width=DOS_width)
pdospz = rawdos.raw_pdos(energies, a=j, l=1, m=1, spin=None, width=DOS_width)
pdosd = rawdos.raw_pdos(energies, a=j, l=2, m=None, spin=None, width=DOS_width)
pdosdxy = rawdos.raw_pdos(energies, a=j, l=2, m=0, spin=None, width=DOS_width)
pdosdyz = rawdos.raw_pdos(energies, a=j, l=2, m=1, spin=None, width=DOS_width)
pdosd3z2_r2 = rawdos.raw_pdos(energies, a=j, l=2, m=2, spin=None, width=DOS_width)
pdosdzx = rawdos.raw_pdos(energies, a=j, l=2, m=3, spin=None, width=DOS_width)
pdosdx2_y2 = rawdos.raw_pdos(energies, a=j, l=2, m=4, spin=None, width=DOS_width)
pdosf = rawdos.raw_pdos(energies, a=j, l=3, m=None, spin=None, width=DOS_width)
# Weights
dosspdf = pdoss + pdosp + pdosd + pdosf
pdossweights = pdossweights + pdoss
pdospweights = pdospweights + pdosp
pdospxweights = pdospxweights + pdospx
pdospyweights = pdospyweights + pdospy
pdospzweights = pdospzweights + pdospz
pdosdweights = pdosdweights + pdosd
pdosdxyweights = pdosdxyweights + pdosd
pdosdyzweights = pdosdyzweights + pdosd
pdosd3z2_r2weights = pdosd3z2_r2weights + pdosd
pdosdzxweights = pdosdzxweights + pdosd
pdosdx2_y2weights = pdosdx2_y2weights + pdosd
pdosfweights = pdosfweights + pdosf
totaldosweights = totaldosweights + dosspdf
for x in zip(energies, pdoss, pdosp, pdospx, pdospy, pdospz, pdosd, pdosdxy, pdosdyz, pdosd3z2_r2, pdosdzx, pdosdx2_y2, pdosf, dosspdf):
print(*x, sep=", ", file=fd)
# Writing DOS
parprint("Saving DOS...")
with paropen(struct+'-2-Result-DOS.csv', "w") as fd:
for x in zip(energies, totaldosweights):
print(*x, sep=", ", file=fd)
# Writing PDOS
parprint("Saving PDOS...")
with paropen(struct+'-2-Result-PDOS.csv', "w") as fd:
print("Energy, s-total, p-total, px, py, pz, d-total, dxy, dyz, d3z2_r2, dzx, dx2_y2, f-total, TOTAL", file=fd)
for x in zip(energies, pdossweights, pdospweights, pdospxweights, pdospyweights, pdospzweights, pdosdweights, pdosdxyweights, pdosdyzweights,
pdosd3z2_r2weights, pdosdzxweights, pdosdx2_y2weights, pdosfweights, totaldosweights):
print(*x, sep=", ", file=fd)
# Finish DOS calc
time22 = time.time()
# Write timings of calculation
with paropen(struct+'-7-Result-Log-Timings.txt', 'a') as f1:
print('DOS calculation: ', round((time22-time21),2), end="\n", file=f1)
# Write or draw figures
if drawfigs == True:
# Draw graphs only on master node
if world.rank == 0:
# DOS
if Spin_calc == True:
downf = pd.read_csv(struct+'-2-Result-DOS-Down.csv', header=None)
upf = pd.read_csv(struct+'-2-Result-DOS-Up.csv', header=None)
downf[0]=downf[0]+ef
upf[0]=upf[0]+ef
ax = plt.gca()
ax.plot(downf[0], -1.0*downf[1], 'y')
ax.plot(upf[0], upf[1], 'b')
ax.set_xlabel(dos_xlabel[Localisation])
ax.set_ylabel(dos_ylabel[Localisation])
else:
dosf = pd.read_csv(struct+'-2-Result-DOS.csv', header=None)
dosf[0]=dosf[0]+ef
ax = plt.gca()
ax.plot(dosf[0], dosf[1], 'b')
ax.set_xlabel(dos_xlabel[Localisation])
ax.set_ylabel(dos_ylabel[Localisation])
plt.xlim(Energy_min+ef, Energy_max+ef)
autoscale_y(ax)
plt.savefig(struct+'-2-Graph-DOS.png', dpi=300)
#plt.show()
else:
# Draw graphs only on master node
if world.rank == 0:
# DOS
if Spin_calc == True:
downf = pd.read_csv(struct+'-2-Result-DOS-Down.csv', header=None)
upf = pd.read_csv(struct+'-2-Result-DOS-Up.csv', header=None)
downf[0]=downf[0]+ef
upf[0]=upf[0]+ef
ax = plt.gca()
ax.plot(downf[0], -1.0*downf[1], 'y')
ax.plot(upf[0], upf[1], 'b')
ax.set_xlabel(dos_xlabel[Localisation])
ax.set_ylabel(dos_ylabel[Localisation])
else:
dosf = pd.read_csv(struct+'-2-Result-DOS.csv', header=None)
dosf[0]=dosf[0]+ef
ax = plt.gca()
ax.plot(dosf[0], dosf[1], 'b')
ax.set_xlabel(dos_xlabel[Localisation])
ax.set_ylabel(dos_ylabel[Localisation])
plt.xlim(Energy_min+ef, Energy_max+ef)
autoscale_y(ax)
plt.savefig(struct+'-2-Graph-DOS.png', dpi=300)
def bandcalc(self, drawfigs = False):
"""
This method performs band structure calculations for the given structure using the
ground state results. It computes the electronic band structure along specified
k-point paths and saves the results in appropriate files for further analysis
and visualization.
"""
# -------------------------------------------------------------
# Step 3 - BAND STRUCTURE CALCULATION
# -------------------------------------------------------------
# Start Band calc
time31 = time.time()
parprint("Starting band structure calculation...")
if Mode == 'PW-GW':
GW = GWBands(calc=struct+'-1-Result-Ground.gpw', fixdensity=True,
gw_file=struct+'-1-_results.pckl',kpoints=GW_kpoints_list)
# Getting results without spin-orbit
results = GW.get_gw_bands(SO=False, interpolate=GW_interpolate_band, vac=True)
# Extracting data
X = results['X']
ef = results['ef']
xdata = results['x_k']
banddata = results['e_kn']
np.savetxt(struct+'-3-Result-Band.dat', np.c_[xdata,banddata])
with open(struct+'-3-Result-Band.dat', 'a') as f:
print ('Symmetry points: ', X, end="\n", file=f)
print ('Fermi Level: ', ef, end="\n", file=f)
else:
if XC_calc in ['HSE06', 'HSE03','B3LYP', 'PBE0','EXX']:
calc = GPAW(struct+'-1-Result-Ground.gpw', symmetry='off',kpts={'path': Band_path, 'npoints': Band_npoints},
parallel={'band':1, 'kpt':1}, occupations = Occupation,
txt=struct+'-3-Log-Band.txt', convergence=Band_convergence)
ef=0.0
else:
calc = GPAW(struct+'-1-Result-Ground.gpw').fixed_density(kpts={'path': Band_path, 'npoints': Band_npoints},
txt=struct+'-3-Log-Band.txt', symmetry='off', occupations = Occupation, convergence=Band_convergence)
ef = calc.get_fermi_level()
calc.get_potential_energy()
bs = calc.band_structure()
Band_num_of_bands = calc.get_number_of_bands()
parprint('Num of bands:'+str(Band_num_of_bands))
# No need to write an additional gpaw file. Use json file to use with ase band-structure command
#calc.write(struct+'-3-Result-Band.gpw')
bs.write(struct+'-3-Result-Band.json')
if Spin_calc == True:
eps_skn = np.array([[calc.get_eigenvalues(k,s)
for k in range(Band_npoints)]
for s in range(2)]) - ef
parprint(eps_skn.shape)
with paropen(struct+'-3-Result-Band-Down.dat', 'w') as f1:
for n1 in range(Band_num_of_bands):
for k1 in range(Band_npoints):
print(k1, eps_skn[0, k1, n1], end="\n", file=f1)
print (end="\n", file=f1)
with paropen(struct+'-3-Result-Band-Up.dat', 'w') as f2:
for n2 in range(Band_num_of_bands):
for k2 in range(Band_npoints):
print(k2, eps_skn[1, k2, n2], end="\n", file=f2)
print (end="\n", file=f2)
# Thanks to Andrej Kesely (https://stackoverflow.com/users/10035985/andrej-kesely) for helping the problem of general XYYY writer
currentd, all_groupsd = [], []
with open(struct+'-3-Result-Band-Down.dat', 'r') as f_in1:
for line in map(str.strip, f_in1):
if line == "" and currentd:
all_groupsd.append(currentd)
currentd = []
else:
currentd.append(line.split(maxsplit=1))
if currentd:
all_groupsd.append(currentd)
try:
with paropen(struct+'-3-Result-Band-Down-XYYY.dat', 'w') as f1:
for g in zip(*all_groupsd):
print('{} {} {}'.format(g[0][0], g[0][1], ' '.join(v for _, v in g[1:])), file=f1)
except Exception as e:
print("\033[93mWARNING:\033[0m A problem occurred during writing XYYY formatted spin down Band file. Mostly, the file is created without any problem.")
print(e)
pass # Continue execution after encountering an exception
currentu, all_groupsu = [], []
with open(struct+'-3-Result-Band-Up.dat', 'r') as f_in2:
for line in map(str.strip, f_in2):
if line == "" and currentu:
all_groupsu.append(currentu)
currentu = []
else:
currentu.append(line.split(maxsplit=1))
if currentu:
all_groupsu.append(currentu)
try:
with paropen(struct+'-3-Result-Band-Up-XYYY.dat', 'w') as f2:
for g in zip(*all_groupsu):
print('{} {} {}'.format(g[0][0], g[0][1], ' '.join(v for _, v in g[1:])), file=f2)
except Exception as e:
print("\033[93mWARNING:\033[0m A problem occurred during writing XYYY formatted spin up Band file. Mostly, the file is created without any problem.")
print(e)
pass # Continue execution after encountering an exception
else:
eps_skn = np.array([[calc.get_eigenvalues(k,s)
for k in range(Band_npoints)]
for s in range(1)]) - ef
with paropen(struct+'-3-Result-Band.dat', 'w') as f:
for n in range(Band_num_of_bands):
for k in range(Band_npoints):
print(k, eps_skn[0, k, n], end="\n", file=f)
print (end="\n", file=f)
# Thanks to Andrej Kesely (https://stackoverflow.com/users/10035985/andrej-kesely) for helping the problem of general XYYY writer
current, all_groups = [], []
with open(struct+'-3-Result-Band.dat', 'r') as f_in:
for line in map(str.strip, f_in):
if line == "" and current:
all_groups.append(current)
current = []
else:
current.append(line.split(maxsplit=1))
if current:
all_groups.append(current)
try:
with paropen(struct+'-3-Result-Band-XYYY.dat', 'w') as f1:
for g in zip(*all_groups):
print('{} {} {}'.format(g[0][0], g[0][1], ' '.join(v for _, v in g[1:])), file=f1)
except Exception as e:
print("\033[93mWARNING:\033[0m A problem occurred during writing XYYY formatted Band file. Mostly, the file is created without any problem.")
print(e)
pass # Continue execution after encountering an exception
# Projected Band
Projected_band = False
if Projected_band == True:
with paropen(struct+'-3-Result-ProjectedBand.dat', 'w') as f3:
for i in range(len(sym_ang_mom_i)):
print('----------------------'+sym_ang_mom_i[i]+'---------------------------', end="\n", file=f3)
for n in range(Band_num_of_bands):
for k in range(Band_npoints):
print(k, projector_weight_skni[0, k, n, i], end="\n", file=f3)
print (end="\n", file=f3)
# Finish Band calc