-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExecutor.py
executable file
·298 lines (282 loc) · 13.1 KB
/
Executor.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
#!/usr/bin/env python3
import os
import subprocess
import argparse
import time
import re
import numpy as np
import math
import pychemia
import pymatgen.io.vasp as vasp
def create_kpoints(length):
length = str(length)+'\n'
comment = 'Automatic mesh'+'\n'
nkp = str(0)+'\n'
method = 'Auto'+'\n'
wf = open("KPOINTS",'w')
wf.write(comment)
wf.write(nkp )
wf.write(method )
wf.write(length )
wf.close()
return
def kpoint_manual(e_threshold,start,end,step,executable,nparal,ncore):
# manual kmesh generation
# in this case start = total number of kpoints to start with
# end = maximum number of kpoints
# step = jumps from
address = os.getcwd()
# I am adding this section as selective dynamics is still not implemented in pychemia
try :
structure = pychemia.code.vasp.read_poscar("POSCAR")
cell = structure.cell
except :
structure = vasp.Poscar.from_file("POSCAR").structure
cell = structure.lattice.matrix
rec_cell = np.linalg.inv(cell).T * 2*np.pi
b1 = np.linalg.norm(rec_cell[0,:])
b2 = np.linalg.norm(rec_cell[1,:])
b3 = np.linalg.norm(rec_cell[2,:])
# rlv = Reciprocal Lattice Vector
rlv = np.array([b1,b2,b3])
kpnts = []
toten= []
for i in range(start,end,step):
j = np.arange(0,200,1e-3)
counter = 0
while math.ceil(rlv[np.argmax(rlv)]*j[counter]) != i :
counter += 1
kpnts.append([math.ceil(b1*j[counter]),math.ceil(b2*j[counter]),math.ceil(b3*j[counter])])
for ikpoint in kpnts:
print("===================================================================================")
print("===================================================================================")
print("===================================================================================")
print('Running VASP for kmesh %i %i %i'% (tuple(ikpoint)))
kp = pychemia.crystal.KPoints(kmode='Monkhorst-pack')
kp.set_grid(ikpoint)
pychemia.code.vasp.kpoints.write_kpoints(kp=kp,filepath='KPOINTS')
if not os.path.exists('INCAR'):
incar = pychemia.code.vasp.VaspInput()
incar.set_encut(1.4,POTCAR='POTCAR')
incar['EDIFF' ] = 1e-4
incar['NWRITE'] = 2
incar['PREC' ] = 'Accurate'
incar['NCORE' ] = ncore
incar['SYSTEM'] = '-'.join(address.split('/')[-2:])
incar.write("INCAR")
runtime = execute(nparal,address,executable)
rf = open("OUTCAR",'r')
data = rf.read()
rf.close()
toten.append(float(re.findall("TOTEN\s*=\s*([-+0-9.]*)\s*eV",data)[-1]))
wf = open("kpoint_convergence",'a')
wf.write("kmesh = %i %i %i , TOTEN =%f \n" %(ikpoint[0],ikpoint[1],ikpoint[2],toten[-1]))
wf.close()
kpnts = np.array(kpnts)
toten = np.array(toten)
kpnt_idx = abs(toten - toten[-1]) < e_threshold
best_kpnt = list(kpnts[kpnt_idx][0])
wf = open('best_kpnt','w')
wf.write('kpnt_cut = %i %i %i ' % tuple(best_kpnt))
wf.close()
return
def kpoint_convergence(e_threshold,start,end,step,executable,nparal,ncore):
address = os.getcwd()
toten = []
kmesh = []
if not os.path.exists('INCAR'):
incar = pychemia.code.vasp.VaspInput()
incar.set_encut(1.4,POTCAR='POTCAR')
incar['EDIFF' ] = 1e-4
incar['NWRITE'] = 2
incar['PREC' ] = 'Accurate'
incar['NCORE' ] = ncore
incar['SYSTEM'] = '-'.join(address.split('/')[-2:])
incar.write("INCAR")
# create potcar here
klengths = np.arange(start,end,step)
for klength in klengths:
create_kpoints(klength)
print("===================================================================================")
print("===================================================================================")
print("===================================================================================")
runtime = execute(nparal,address,executable)
rf = open("OUTCAR",'r')
data = rf.read()
rf.close()
toten.append(float(re.findall("TOTEN\s*=\s*([-+0-9.]*)\s*eV",data)[-1]))
kmesh.append(re.findall("generate k-points for.*",data)[0])
wf = open("kpoint_convergence",'a')
wf.write("kpoint length = %i ,kmesh = %s, TOTEN =%f \n" %(klength,kmesh[-1],toten[-1]))
wf.close()
if klength != start : # this is to check if it's not doing the calculation for the first time
change = abs(toten[-2]-toten[-1])
if change < e_threshold : # need to add more comparision here
print("VASP calculations converged with k points length %i and kmesh %s " % (klength,kmesh[-1]))
break
print("VASP calculations converged with k points length %i and kmesh %s " % (klengths[conv_idx],kmesh[conv_idx]))
return
def encut_convergence(e_threshold,start,end,step,executable,nparal,ncore):
address = os.getcwd()
toten = []
if not os.path.exists('KPOINTS'):
create_kpoints(10)
rf = open('POTCAR')
potcar = rf.read()
rf.close()
encut_init = round(max([float(x) for x in re.findall('ENMAX\s*=\s*([0-9.]*);',potcar)])*1.3)
if start < encut_init :
print('Initial value provided for ENUCT is less than 1.3*ENMAX pseudo potential, replacing Estart with %f'% encut_init)
start = round(encut_init,-2)
encuts = np.arange(start,end,step)
for iencut in encuts:
incar = pychemia.code.vasp.VaspInput()
incar['ENCUT'] = iencut
incar['SYSTEM'] = '-'.join(address.split('/')[-2:])
incar['EDIFF' ] = 1e-5
incar['NWRITE'] = 2
incar['PREC' ] = 'Accurate'
incar['NCORE' ] = ncore
incar.write("INCAR")
print("===================================================================================")
print("===================================================================================")
print("===================================================================================")
print('Running vasp with ENCUT = {}'.format(iencut))
runtime = execute(nparal,address,executable)
rf = open("OUTCAR",'r')
data = rf.read()
rf.close()
toten.append(float(re.findall("TOTEN\s*=\s*([-+0-9.]*)\s*eV",data)[-1]))
wf = open("encut_convergence",'a')
wf.write("encut = %i , TOTEN =%f \n" %(iencut,toten[-1]))
wf.close()
toten = np.array(toten)
encut_idx = abs(toten - toten[-1]) < e_threshold
best_encut = encuts[encut_idx][0]
wf = open('best_encut','w')
wf.write('best_cut = {}'.format(best_encut))
wf.close()
return
def relax_structure(encut,kgrid,kmode,ismear,executable,nparal,ncore):
address = os.getcwd()
if not os.path.exists('INCAR'):
incar = pychemia.code.vasp.VaspInput()
if encut == None:
incar.set_encut(1.4,POTCAR='POTCAR')
else :
incar.set_encut(encut)
incar['SYSTEM'] = '-'.join(address.split('/')[-2:])
incar['NWRITE'] = 3 # how much info to write in outcar, long MD 0,1 short MD 2,3 debug 4
incar['PREC'] = 'Accurate'
incar['ADDGRID'] = True # additional support grid for augmentation charges
incar['ISMEAR'] = ismear # tetrahedron method with Blöchl corrections
incar['EDIFF'] = 1e-08
# incar['LREAL'] = 'a' # projection in real space or reciprocal, a is automatic
incar['NELMIN'] = 6 # minimum number of electronic steps
incar['EDIFFG'] = -1E-03
incar['NSW'] = 100
incar['IBRION'] = 2 # how atoms are updated to move
incar['ISIF'] = 3
incar['ISYM'] = 2
incar['SIGMA'] = 0.05
incar['NCORE' ] = ncore
incar.write("INCAR")
if kmode == None and kgrid == None:
create_kpoints(30)
else :
kp = pychemia.crystal.KPoints(kmode=kmode)
kp.set_grid(kgrid)
pychemia.code.vasp.kpoints.write_kpoints(kp=kp,filepath='KPOINTS')
runtime = execute(nparal,address,executable)
return
def SCF(encut,kgrid,kmode,ismear,executable,nparal,ncore):
address = os.getcwd()
magmom = ''
try :
structure = pychemia.code.vasp.read_poscar("POSCAR")
comp = structure.get_composition()
except :
structure = vasp.Poscar.from_file("POSCAR").structure
comp = structure.composition
for x in comp:
magmom += '%i*0.5 ' % comp[x]
incar = pychemia.code.vasp.VaspInput()
if encut == None:
incar.set_encut(1.4,POTCAR='POTCAR')
else :
incar.set_encut(encut)
incar['SYSTEM'] = '-'.join(address.split('/')[-2:])
incar['ISMEAR'] = ismear # tetrahedron method with Blöchl corrections
incar['ISTART'] = 0 # does not read WAVECAR
incar['EDIFF'] = 1e-06
incar['LREAL'] = 'a' # projection in real space or reciprocal, a is automatic
incar['NELMIN'] = 6 # minimum number of electronic steps
incar['IBRION'] = -1 # how atoms are updated to move
incar['ISPIN'] = 2
incar['NCORE' ] = ncore
incar['MAGMOM'] = magmom
incar['SIGMA'] = 0.05
incar.write("INCAR")
if kmode == None and kgrid == None:
create_kpoints(30)
else :
kp = pychemia.crystal.KPoints(kmode=kmode)
kp.set_grid(kgrid)
pychemia.code.vasp.kpoints.write_kpoints(kp=kp,filepath='KPOINTS')
runtime = execute(nparal,address,executable)
return
def execute(nparal,work_dir,vasp_exe):
wf=open(work_dir+os.sep+'RUNNING','w')
wf.write(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime()))
wf.close()
start_time=time.time()
status = subprocess.call("mpirun -np {} {}".format(nparal,vasp_exe),cwd=work_dir ,shell=True)
status = 0
end_time=time.time()
runtime=end_time-start_time
if status== 0:
print("VASP execution completed with returcode: %d runtime: %d secs" % (status, runtime))
else:
print("VASP execution failed with returcode: %d runtime: %d secs" % (status, runtime))
os.remove(work_dir+os.sep+'RUNNING')
return runtime
if __name__ == "__main__" :
parser = argparse.ArgumentParser()
parser.add_argument("--structure",dest="structure",type=str,help='poscar structure that you want to run',default = 'POSCAR')
parser.add_argument("-np" ,dest="np",type=int ,action="store", help="Number of MPI processes for the code",default = '1')
parser.add_argument("--ncore" ,dest="ncore",type=int ,action="store", help="NCORE value to be set in INCAR",default = '4')
subparsers = parser.add_subparsers(dest='calc')
parser_kpnt = subparsers.add_parser('kpoint_convergence')
parser_kpnt.add_argument('--mode',type=str,default='auto')
parser_kpnt.add_argument('--Kstart',type=int,default=10)
parser_kpnt.add_argument('--Kend',type=int,default=100)
parser_kpnt.add_argument('--Kstep',type=int,default=10)
parser_kpnt.add_argument('--Ethreshold',type=float,default=1e-3)
parser_encut = subparsers.add_parser('encut_convergence')
parser_encut.add_argument('--Estart',type=float,default=100)
parser_encut.add_argument('--Eend',type=float,default=900)
parser_encut.add_argument('--Estep',type=float,default=50)
parser_encut.add_argument('--Ethreshold',type=float,default=1e-3)
parser.add_argument("--executable",dest="executable",type=str,action="store",help="vasp executable",default="vasp_std")
parser_rlx = subparsers.add_parser('structure_relax')
parser_rlx.add_argument('--Kmode',type=str,default='Monkhorst-pack')
parser_rlx.add_argument('--Kgrid',type=int,nargs=3)
parser_rlx.add_argument('--encut',type=float)
parser_rlx.add_argument('--ismear',type=int,default=0)
parser_scf = subparsers.add_parser('scf')
parser_scf.add_argument('--Kmode',type=str,default='Monkhorst-pack')
parser_scf.add_argument('--Kgrid',type=int,nargs=3)
parser_scf.add_argument('--encut',type=float)
parser_scf.add_argument('--ismear',type=int,default=0)
args = parser.parse_args()
if args.calc == 'kpoint_convergence':
if args.mode == 'auto':
kpoint_convergence(e_threshold=args.Ethreshold,start=args.Kstart,end=args.Kend,step=args.Kstep,executable=args.executable,nparal=args.np,ncore=args.ncore)
elif args.mode == 'manual':
kpoint_manual(e_threshold=args.Ethreshold,start=args.Kstart,end=args.Kend,step=args.Kstep,executable=args.executable,nparal=args.np,ncore=args.ncore)
elif args.calc == 'encut_convergence':
encut_convergence(e_threshold=args.Ethreshold,start=args.Estart,end=args.Eend,step=args.Estep,executable=args.executable,nparal=args.np,ncore=args.ncore)
elif args.calc == 'structure_relax' :
relax_structure(encut=args.encut,kgrid=args.Kgrid,kmode=args.Kmode,ismear=args.ismear,executable=args.executable,nparal=args.np,ncore=args.ncore)
elif args.calc == 'scf':
SCF(encut=args.encut,kgrid=args.Kgrid,kmode=args.Kmode,ismear=args.ismear,executable=args.executable,nparal=args.np,ncore=args.ncore)