-
Notifications
You must be signed in to change notification settings - Fork 0
/
input_module.py
243 lines (213 loc) · 8.54 KB
/
input_module.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
# NOTES: Since all the structures we use in this is tetragonal, we're not changing the
# atomic lattice positions from (0, 0, 0) to (0.25, 0.25, 0.25).
# Start with decent upper and lower limits for k_points and ecut.
# if error "Cannot read output" appears, it means that the scf.in file has failed.
# k_cut must be in integer format(9 instead of 9.0) or else the scf.in file will fail.
import subprocess as sp
import os
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#===============================================================================
# Change whatever you want here
# Directories, don't change unnecessarily
raw_input_directory = "./Raw_Inputs/"
raw_data_directory = "./Raw_data/"
raw_output_directory = "./Raw_Outputs/"
# UPF files
# Used limits
# Sn = 4 15 10 120 5. 15. 3
# C = 4 32 10 120 4. 20. 3
# Ge = 4 32 10 120 4. 20. 3
# Change this to your UPF file
# upf = "Sn.pbe-dn-rrkjus_psl.1.0.0.UPF"
# upf = "C.pbe-n-rrkjus_psl.1.0.0.UPF"
upf = "Ge.pbe-dn-kjpaw_psl.1.0.0.UPF"
# Set K points limits (integers ONLY)
K_POINT_LOWER_LIMIT = 4
K_POINT_UPPER_LIMIT = 32
# Set ecutwfc limits
ECUT_LOWER_LIMIT = 10
ECUT_UPPER_LIMIT = 120
# Set lattice_parameter limits
LATT_K_LOWER_LIMIT = 4.
LATT_K_UPPER_LIMIT = 20.
# Set accuracy level
ACCURACY_LEVEL = 3
# Clean Flag
CLEAN_FLAG = False
# Device specific
# ESPRESSO_path = "~/espresso-5.0.2/build_ompi/bin/"
# default
ESPRESSO_path = "pw.x"
# Don't change anything below this line
#===============================================================================
cwd = os.getcwd()
cl_ele = upf.split(".")[0]
element = "\'"+upf.split(".")[0]+"\'"
mass = 0
table = json.loads(open('Table.json').read())
# Element finder from a periodic table json
for elem in table['elements']:
if str(elem['symbol']).lower() == cl_ele.lower():
name = elem['name']
mass = float(elem['atomic_mass'])
ec = elem['shells']
print(f"Element: {name}")
print(f"Atomic mass: {mass}")
print(f"Shells: {ec}")
print("\n________________________________________________________________________________\n\n")
break
# This function is used to clean the raw data directory as well as the default directory
def clean():
print("Cleaning... in/out files")
os.system("rm *.in *.out")
print("Done")
print("Cleaning... raw data")
os.chdir(path=raw_data_directory)
os.system("rm -rf *")
print("Clean complete\n")
os.chdir(path=cwd)
# This function is used to create the .in/.out files for the calculation
def SCF_INPUT(upf, latt_k, ecut, k_pts):
element = upf.split(".")[0]
fname = element + "_" + str(latt_k) + "_" + str(ecut) + "_" + str(k_pts) + "_" + "scf.in"
oname = element + "_" + str(latt_k) + "_" + str(ecut) + "_" + str(k_pts) + "_" + "scf.out"
infile = open(fname, "w")
automatic = "{automatic}"
blocktext = f"""\
&control
calculation = 'scf',
restart_mode = 'from_scratch',
pseudo_dir = './Raw_Inputs/',
outdir = './Raw_data/',
prefix = '{element}'
/
&system
ibrav=2, celldm(1)={latt_k}, nat=2, ntyp=1,
ecutwfc ={ecut}
/
&electrons
conv_thr = 1.0d-8
mixing_beta = 0.7
diagonalization = 'david'
/
ATOMIC_SPECIES
{element} {mass} {upf}
ATOMIC_POSITIONS
{element} 0.00 0.00 0.00
{element} 0.25 0.25 0.25
K_POINTS {automatic}
{k_pts} {k_pts} {k_pts} 0 0 0"""
infile.write(blocktext)
infile.close()
print("{fname} created".format(fname=fname))
cmd = ESPRESSO_path + " < " + fname + " > " + oname
os.system(cmd)
cmd2 = "grep ! " + oname
a = os.popen(cmd2).read()
a = a.split(" ")
# return in format latt_k, ecut, k_pts, energy
# note that this will give an error in case it encounters absurd values.
return [float(latt_k), float(ecut), float(k_pts), float(a[-2])]
# K Point optimizer
def k_pt_opt(lower_lt=K_POINT_LOWER_LIMIT, upper_lt=K_POINT_UPPER_LIMIT):
data = np.array([])
for k_points in range(lower_lt, upper_lt):
data = np.append(data, SCF_INPUT(upf, 10.0, 20, k_points))
print(f"K_POINTS: {k_points} = DONE")
data = data.reshape(-1, 4)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title("Energy vs K points")
ax.set_xlabel("K point")
ax.set_ylabel("Energy (eV)")
ax = plt.plot(data[:,2], data[:,3])
ind = np.argmin(data[:,3])
k_point_min = int(data[:,2][ind])
plt.savefig(raw_output_directory + name + "_k-points.png")
print(data)
print(f"\n\nK-point optimized = {k_point_min}\n")
KPT = pd.DataFrame(data, columns=["Lattice Parameter", "Ecutwfc", "K points", "Energy"])
KPT = KPT[["K points", "Energy"]]
KPT.to_csv(raw_output_directory + name + "_k points.csv",index=False,sep=" ",header=False)
print("\nData written to csv\n")
return k_point_min
# ecutwfc optimizer
def ecut_opt(lower_ecut=ECUT_LOWER_LIMIT, upper_ecut=ECUT_UPPER_LIMIT):
data = np.array([0,lower_ecut,res_k_pt,0])
ec_prev = 0
for ecut in range(lower_ecut, upper_ecut, 10):
data = np.append(data, SCF_INPUT(upf, 10.0, ecut, int(res_k_pt)))
data = data.reshape(-1, 4)
ec_next = float(data[-1,3])
if (np.abs(ec_prev - ec_next) / np.abs(ec_next)) < 0.0001:
print("Next value within 0.01 of previous value")
print(f"terminate ECUT = {ecut}")
break
print(f"Ecut: {ecut} = DONE")
ec_prev = ec_next
data = data.reshape(-1, 4)
fig = plt.figure()
ax = fig.add_subplot(111)
plt.title("Energy vs Ecut")
ax.set_xlabel("Ecut")
ax.set_ylabel("Energy (eV)")
ax = plt.plot(data[1:,1], data[1:,3])
ind = np.argmin(data[1:,3])
ecut_min = data[1:,1][ind]
plt.savefig(raw_output_directory + name + "_ecut.png")
print(data)
print(f"\n\nEcut optimized = {ecut_min}\n")
ECUT = pd.DataFrame(data, columns=[
"Lattice Parameter", "Ecutwfc", "K points", "Energy"])
ECUT = ECUT[["Ecutwfc", "Energy"]]
ECUT.to_csv(raw_output_directory + name + "_ecut.csv",index=False,sep=" ",header=False)
print("\nData written to csv\n")
return ecut_min
# lattice parameter optimizer
def latt_opt(lower_lt=LATT_K_LOWER_LIMIT, upper_lt=LATT_K_UPPER_LIMIT,LEVEL=ACCURACY_LEVEL):
#data = np.array([])
fig = plt.figure(figsize=((LEVEL+1)*10,10))
for level in range(LEVEL):
data = np.array([])
print(f"\nBeginning lattice optimization level {level}\n")
for latt in np.arange(lower_lt, upper_lt,(2*0.1**level)):
latt = round(latt, level)
data = np.append(data, SCF_INPUT(upf, latt, int(res_ecut), int(res_k_pt)))
print(f"Latt: {latt} = DONE")
data = data.reshape(-1, 4)
ind = np.argmin(data[1:,3])
latt_min = data[1:,0][ind]
print(f"\n\nLattice minimum at level {level} = {latt_min}\n")
lower_lt = latt_min - (0.1**level)
upper_lt = latt_min + (0.1**level)
ax = fig.add_subplot(1 ,LEVEL ,level+1)
plt.title(label=f"Lattice optimization level {level}")
ax.set_xlabel("Lattice parameter")
ax.set_ylabel("Energy (eV)")
ax = plt.plot(data[1:,0], data[1:,3])
plt.savefig(raw_output_directory + name + "_lattice.png")
LATT = pd.DataFrame(data, columns=["Lattice Parameter", "Ecutwfc", "K points", "Energy"])
LATT = LATT[["Lattice Parameter", "Energy"]]
LATT.to_csv(raw_output_directory + name + "_lattice_level_{level}.csv",index=False,sep=" ",header=False)
print("\nData written to csv\n")
return latt_min
# Optimize all parameters
res_k_pt = k_pt_opt()
res_ecut = ecut_opt()
res_latt = latt_opt()
print("\nCreate final .in file with optimized parameters\n")
# Create final .in file with optimized parameters
SCF_INPUT(upf, res_latt, res_ecut, res_k_pt)
fname = element + "_" + str(res_latt) + "_" + str(res_ecut) + "_" + str(res_k_pt) + "_" + "scf.in"
# Move final .in file to output directory
cmd2 = "mv " + fname + " " + raw_output_directory
os.system(cmd2)
print("Final .in file created with optimized parameters\n")
# In some cases (for band structure calculation for ex, we need the .save folder as well as the .xml file)
# In those cases, leave CLEAN_FLAG = False
# If you want to cleanup the .save folder, set CLEAN_FLAG = True
if CLEAN_FLAG:
clean()