-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainTernary.py
311 lines (249 loc) · 12.3 KB
/
MainTernary.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
'''
Created on Aug 26, 2014
@author: eswens13
'''
import os, subprocess
from random import seed
from numpy import zeros
from copy import deepcopy
import Enumerator, Extractor, Structs2Poscar, JobManager, MakeUncleFiles, Fitter, GSS, Analyzer, DistanceInfo
def readSettingsFile():
currDir = os.getcwd()
infile = open(currDir + '/needed_files/settings.in', 'r')
inlines = []
for line in infile:
firstPart = line.strip().split()[0]
firstChar = list(firstPart)[0]
if firstChar != '#':
inlines.append(line.strip())
infile.close()
atoms = []
volRange = []
clusterNums = []
trainStructs = 0
fitStructs = 0
fitSubsets = 0
plotTitle = "title"
xlabel = "xlabel"
ylabel = "ylabel"
case = 3
for line in inlines:
if line.split()[0] == 'ATOMS:':
while len(line) > 0:
low = line.find('[')
high = line.find(']')
if low == -1 or high == -1:
break
atoms.append(line[low+1:high].translate(None, " []"))
line = line[high+1:]
if len(atoms) == 0:
atoms = [line[line.find(':')+1:line.find('#')].strip().replace(' ', ',')]
elif line.split()[0] == 'CASE:':
case = int(line.split()[1])
elif line.split()[0] == 'VOL_RANGE:':
low = int(line.split()[1])
high = int(line.split()[2])
volRange = [low, high]
elif line.split()[0] == 'CLUSTER_NUMS:':
parts = line.split()
for i in xrange(1, 11):
clusterNums.append(int(parts[i]))
elif line.split()[0] == 'TRAINING_STRUCTS:':
trainStructs = int(line.split()[1])
elif line.split()[0] == 'FITTING_STRUCTS:':
fitStructs = int(line.split()[1])
elif line.split()[0] == 'STRUCT_SUBSETS:':
fitSubsets = int(line.split()[1])
elif line.split()[0] == 'PLOT_TITLE:':
plotTitle = line.split('\'')[1]
elif line.split()[0] == 'XLAB:':
xlabel = line.split('\'')[1]
elif line.split()[0] == 'YLAB:':
ylabel = line.split('\'')[1]
if len(atoms[0].split(',')) != case:
print "\nERROR: Number of atoms does not match case. Check settings.in\n"
print "Setting case to " + str(len(atoms[0].split(','))) + "-nary. . .\n"
case = len(atoms[0].split(','))
return [atoms, volRange, clusterNums, trainStructs, fitStructs, fitSubsets, plotTitle, xlabel, ylabel, case]
def contains(struct, alist):
for i in xrange(len(alist)):
if str(struct) == str(alist[i]):
return True
return False
def equals(alist, blist):
clist = deepcopy(alist)
dlist = deepcopy(blist)
while len(clist) > 0:
if len(dlist) == 0:
return False
if not contains(clist[0], dlist):
return False
else:
clist.remove(clist[0])
dlist.remove(clist[0])
if len(dlist) > 0:
return False
else:
return True
if __name__ == '__main__':
seed()
[atomList, volRange, clusterNums, trainingStructs, fitStructs, fitSubsets, plotTitle, xlabel, ylabel,case] = readSettingsFile()
uncleOutput = open('uncle_output.txt','w') # All output from UNCLE will be written to this file.
enumerator = Enumerator.Enumerator(atomList, volRange, clusterNums, trainingStructs, uncleOutput, case)
subprocess.call(['echo','\nEnumerating symmetrically unique structures. . .\n'])
enumerator.enumerate()
changed = True
iteration = 1
newStructs = []
gssStructs = []
lowestStructsFile = open('lowest_vasp.txt','w')
lowestGssFile = open('lowest_gss.txt','w')
failedFile = open('failed_vasp.txt','w')
while changed:
changed = False
subprocess.call(['echo','\n========================================================'])
subprocess.call(['echo','\t\tIteration ' + str(iteration)])
subprocess.call(['echo','========================================================\n'])
# Extract the pseudo-POSCARs from struct_enum.out
extractor = Extractor.Extractor(atomList, uncleOutput,case)
if iteration == 1:
extractor.setTrainingStructs()
elif iteration > 1:
extractor.setStructList(newStructs)
toCalculate = extractor.getStructList()
extractor.extract()
# Convert the extracted pseudo-POSCARs to VASP POSCAR files, make directories for them
# and put the POSCARs in their corresponding directories.
subprocess.call(['echo','\nConverting outputs to VASP inputs. . .\n'])
toPoscar = Structs2Poscar.Structs2Poscar(atomList, toCalculate)
toPoscar.convertOutputsToPoscar()
# Start VASP jobs and wait until they all complete or time out.
manager = JobManager.JobManager(atomList)
manager.runLowJobs(toCalculate)
manager.runNormalJobs(toCalculate)
manager.runDOSJobs(toCalculate)
# Create structures.in and structures.holdout files for each atom.
uncleFileMaker = MakeUncleFiles.MakeUncleFiles(atomList)
uncleFileMaker.makeUncleFiles()
# Get all the structs that have been through VASP calculations for each atom. These
# should be sorted by formation energy during the work done by makeUncleFiles()
[vaspStructs, failedStructs] = uncleFileMaker.getStructureList()
structuresInLengths = uncleFileMaker.getStructuresInLengths()
# Perform a fit to the VASP data in structures.in for each atom.
fitter = Fitter.Fitter(atomList, fitStructs, fitSubsets, structuresInLengths, uncleOutput)
fitter.makeFitDirectories()
fitter.fitVASPData(iteration)
# Perform a ground state search on the fit for each atom.
gss = GSS.GSS(atomList, volRange, plotTitle, xlabel, ylabel, uncleOutput)
gss.makeGSSDirectories()
gss.performGroundStateSearch(iteration)
gss.makePlots(iteration)
gssStructs = gss.getAllGSSStructures(iteration, failedStructs)
# Check the lowest 100 hundred structs from VASP against the lowest 100 structs from UNCLE
# for each atom. If they match, then that atom has converged and we remove it from the
# lists.
removeAtoms = []
removeGss = []
removeVasp = []
for i in xrange(len(vaspStructs)):
atomLength = len(vaspStructs[i])
if atomLength >= 100:
if equals(vaspStructs[i][:100], gssStructs[i][:100]):
removeAtoms.append(atomList[i])
removeGss.append(gssStructs[i])
removeVasp.append(vaspStructs[i])
else:
# If there are not yet 100 structs that have converged in VASP.
if equals(vaspStructs[i][:atomLength], gssStructs[i][:atomLength]):
removeAtoms.append(atomList[i])
removeGss.append(gssStructs[i])
removeVasp.append(vaspStructs[i])
for i in xrange(len(removeAtoms)):
atomList.remove(removeAtoms[i])
for i in xrange(len(removeGss)):
gssStructs.remove(removeGss[i])
for i in xrange(len(removeVasp)):
vaspStructs.remove(removeVasp[i])
# If all of the atoms have converged, exit the loop. Else, keep going.
if len(atomList) > 0:
changed = True
if not changed:
subprocess.call(['echo','\n----------------- The loop has converged! ---------------'])
# Print the lowest energy structures that have been through VASP calculations to a file.
try:
lowestStructsFile.write('==============================================================\n')
lowestStructsFile.write('\tIteration: ' + str(iteration) + '\n')
lowestStructsFile.write('==============================================================\n')
for i in xrange(len(vaspStructs)):
lowestStructsFile.write('\n******************** ' + atomList[i] + ' ********************\n')
atomLength = len(vaspStructs[i])
if atomLength >= 100:
for j in xrange(len(vaspStructs[i][:100])):
if (j + 1) % 20 == 0 or j == 99:
lowestStructsFile.write(str(vaspStructs[i][j]) + '\n')
else:
lowestStructsFile.write(str(vaspStructs[i][j]) + ', ')
else:
for j in xrange(len(vaspStructs[i][:atomLength])):
if (j + 1) % 20 == 0 or j == atomLength - 1:
lowestStructsFile.write(str(vaspStructs[i][j]) + '\n')
else:
lowestStructsFile.write(str(vaspStructs[i][j]) + ', ')
lowestStructsFile.flush()
os.fsync(lowestStructsFile.fileno())
except IOError:
subprocess.call(['echo','\n~~~~~~~~~~ Couldn\'t write to lowest_vasp file. ~~~~~~~~~~\n'])
# Write the all the structures that have failed VASP calculations to a file.
# TODO: Only write the failed structures that are unique to this iteration to the file.
try:
failedFile.write('==============================================================\n')
failedFile.write('\tIteration: ' + str(iteration) + '\n')
failedFile.write('==============================================================\n')
for i in xrange(len(failedStructs)):
failedFile.write('\n******************** ' + atomList[i] + ' ********************\n')
for j in xrange(len(failedStructs[i])):
if (j + 1) % 20 == 0 or j == len(failedStructs[i]) - 1:
failedFile.write(str(failedStructs[i][j]) + '\n')
else:
failedFile.write(str(failedStructs[i][j]) + ', ')
failedFile.flush()
os.fsync(failedFile.fileno())
except IOError:
subprocess.call(['echo','\n~~~~~~~~~~ Couldn\'t write to failed_vasp file. ~~~~~~~~~~\n'])
# Add the 100 structures with the lowest formation energy that have not been through VASP
# calculations (converged or failed) to the newStructs list for each remaining atom.
newStructs = []
added = zeros(len(atomList))
for i in xrange(len(gssStructs)):
atomStructs = []
for j in xrange(len(gssStructs[i])):
if added[i] >= 100:
break
elif not contains(gssStructs[i][j], vaspStructs[i]):
atomStructs.append(str(gssStructs[i][j]))
added[i] += 1
newStructs.append(atomStructs)
# Print the new GSS structures to a file.
try:
lowestGssFile.write('==================================================================\n')
lowestGssFile.write('\tIteration: ' + str(iteration) + '\n')
lowestGssFile.write('==================================================================\n')
for i in xrange(len(newStructs)):
lowestGssFile.write('\n***************** ' + atomList[i] + ' *******************\n')
atomLength = len(newStructs[i])
if atomLength >= 100:
for j in xrange(len(newStructs[i])):
if (j + 1) % 20 == 0 or j == 99:
lowestGssFile.write(str(newStructs[i][j]) + '\n')
else:
lowestGssFile.write(str(newStructs[i][j]) + ', ')
lowestGssFile.flush()
os.fsync(lowestGssFile.fileno())
except IOError:
subprocess.call(['echo','\n~~~~~~~~~~ Couldn\'t write to lowest_gss file. ~~~~~~~~~~\n'])
# Keep track of which iteration we're on.
iteration += 1
uncleOutput.close()
lowestStructsFile.close()
lowestGssFile.close()
# Should do some analysis after the loop has finished as well.