-
Notifications
You must be signed in to change notification settings - Fork 104
/
Gaussian.py
executable file
·607 lines (414 loc) · 16 KB
/
Gaussian.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 19 15:56:54 2014
Rewritten during April 2019
@author: ke291
Contains all of the Gaussian specific code for input generation and calculation
execution. Called by PyDP4.py.
"""
import subprocess
import os
import time
import glob
import shutil
def SetupNMRCalcs(Isomers, settings):
jobdir = os.getcwd()
if not os.path.exists('nmr'):
os.mkdir('nmr')
os.chdir('nmr')
for iso in Isomers:
if iso.ExtCharge > -10:
charge = iso.ExtCharge
else:
charge = iso.MMCharge
if iso.DFTConformers == []:
conformers = iso.Conformers
else:
conformers = iso.DFTConformers
for num in range(0, len(conformers)):
filename = iso.BaseName + 'ginp' + str(num + 1).zfill(3)
if os.path.exists(filename + '.out'):
if IsGausCompleted(filename + '.out'):
iso.NMROutputFiles.append(filename + '.out')
continue
else:
os.remove(filename + '.out')
WriteGausFile(filename, conformers[num], iso.Atoms, charge, settings, 'nmr')
iso.NMRInputFiles.append(filename + '.com')
os.chdir(jobdir)
return Isomers
def SetupECalcs(Isomers, settings):
jobdir = os.getcwd()
if not os.path.exists('e'):
os.mkdir('e')
os.chdir('e')
for iso in Isomers:
if iso.ExtCharge > -10:
charge = iso.ExtCharge
else:
charge = iso.MMCharge
if iso.DFTConformers == []:
conformers = iso.Conformers
else:
conformers = iso.DFTConformers
for num in range(0, len(conformers)):
filename = iso.BaseName + 'ginp' + str(num + 1).zfill(3)
if os.path.exists(filename + '.out'):
if IsGausCompleted(filename + '.out'):
iso.EOutputFiles.append(filename + '.out')
continue
else:
os.remove(filename + '.out')
WriteGausFile(filename, conformers[num], iso.Atoms, charge, settings, 'e')
iso.EInputFiles.append(filename + '.com')
os.chdir(jobdir)
return Isomers
def SetupOptCalcs(Isomers, settings):
jobdir = os.getcwd()
if not os.path.exists('opt'):
os.mkdir('opt')
os.chdir('opt')
for iso in Isomers:
if iso.ExtCharge > -10:
charge = iso.ExtCharge
else:
charge = iso.MMCharge
for num in range(0, len(iso.Conformers)):
filename = iso.BaseName + 'ginp' + str(num + 1).zfill(3)
if os.path.exists(filename + '.out'):
if IsGausCompleted(filename + '.out'):
if IsGausConverged(filename + '.out') or (settings.AssumeConverged == True):
iso.OptOutputFiles.append(filename + '.out')
continue
else:
# If calculation completed, but didn't converge, reuse geometry and resubmit
atoms, coords = ReadGeometry(filename + '.out')
if coords != []:
print('Partially optimised structure found for ' + filename + ', reusing')
iso.Conformers[num] = coords
os.remove(filename + '.out')
else:
os.remove(filename + '.out')
WriteGausFile(filename, iso.Conformers[num], iso.Atoms, charge, settings, 'opt')
iso.OptInputFiles.append(filename + '.com')
os.chdir(jobdir)
return Isomers
def Converged(Isomers):
jobdir = os.getcwd()
if not os.path.exists('opt'):
os.chdir(jobdir)
return False
os.chdir('opt')
for iso in Isomers:
for num in range(0, len(iso.Conformers)):
filename = iso.BaseName + 'ginp' + str(num + 1).zfill(3)
if os.path.exists(filename + '.out'):
if IsGausConverged(filename + '.out') == False:
os.chdir(jobdir)
return False
else:
os.chdir(jobdir)
return False
os.chdir(jobdir)
return True
def RunNMRCalcs(Isomers, settings):
print('\nRunning Gaussian DFT NMR calculations locally...')
jobdir = os.getcwd()
os.chdir('nmr')
GausJobs = []
for iso in Isomers:
GausJobs.extend([x for x in iso.NMRInputFiles if (x[:-4] + '.out') not in iso.NMROutputFiles])
Completed = RunCalcs(GausJobs, settings)
for iso in Isomers:
iso.NMROutputFiles.extend([x[:-4] + '.out' for x in iso.NMRInputFiles if (x[:-4] + '.out') in Completed])
os.chdir(jobdir)
return Isomers
def GetPrerunNMRCalcs(Isomers):
print('\nLooking for prerun Gaussian DFT NMR files...')
jobdir = os.getcwd()
os.chdir('nmr')
for iso in Isomers:
iso.NMRInputFiles = glob.glob(iso.BaseName + 'ginp*com')
iso.NMROutputFiles.extend([x[:-4] + '.out' for x in iso.NMRInputFiles if IsGausCompleted(x[:-4] + '.out')])
print('NMR calc files:')
print(', '.join([', '.join(x.NMROutputFiles) for x in Isomers]))
os.chdir(jobdir)
return Isomers
def RunECalcs(Isomers, settings):
print('\nRunning Gaussian DFT energy calculations locally...')
jobdir = os.getcwd()
os.chdir('e')
GausJobs = []
for iso in Isomers:
GausJobs.extend([x for x in iso.EInputFiles if (x[:-4] + '.out') not in iso.EOutputFiles])
Completed = RunCalcs(GausJobs, settings)
for iso in Isomers:
iso.EOutputFiles.extend([x[:-4] + '.out' for x in iso.EInputFiles if (x[:-4] + '.out') in Completed])
os.chdir(jobdir)
return Isomers
def GetPrerunECalcs(Isomers):
print('\nLooking for prerun Gaussian DFT energy calculation files...')
jobdir = os.getcwd()
os.chdir('e')
for iso in Isomers:
iso.EInputFiles = glob.glob(iso.BaseName + 'ginp*com')
iso.EOutputFiles.extend([x[:-4] + '.out' for x in iso.EInputFiles if IsGausCompleted(x[:-4] + '.out')])
print('Energy files:')
print(', '.join([', '.join(x.EOutputFiles) for x in Isomers]))
os.chdir(jobdir)
return Isomers
def RunOptCalcs(Isomers, settings):
print('\nRunning Gaussian DFT geometry optimizations locally...')
jobdir = os.getcwd()
os.chdir('opt')
GausJobs = []
for iso in Isomers:
GausJobs.extend([x for x in iso.OptInputFiles if (x[:-4] + '.out') not in iso.OptOutputFiles])
Completed = RunCalcs(GausJobs, settings)
for iso in Isomers:
iso.OptOutputFiles.extend([x[:-4] + '.out' for x in iso.OptInputFiles if (x[:-4] + '.out') in Completed])
os.chdir(jobdir)
return Isomers
def GetPrerunOptCalcs(Isomers):
print('\nLooking for prerun Gaussian DFT optimization files...')
jobdir = os.getcwd()
os.chdir('opt')
for iso in Isomers:
iso.OptInputFiles = glob.glob(iso.BaseName + 'ginp*com')
iso.OptOutputFiles.extend([x[:-4] + '.out' for x in iso.OptInputFiles if IsGausCompleted(x[:-4] + '.out')])
print('Opt files:')
print(', '.join([', '.join(x.OptOutputFiles) for x in Isomers]))
os.chdir(jobdir)
return Isomers
def RunCalcs(GausJobs, settings):
NCompleted = 0
Completed = []
if len(GausJobs) == 0:
print("There were no jobs to run.")
return Completed
if ('GAUS_EXEDIR' in os.environ):
gausdir = os.environ['GAUSS_EXEDIR']
if shutil.which(os.path.join(gausdir, 'g09')) is None:
GausPrefix = os.path.join(gausdir, "g16")
else:
GausPrefix = os.path.join(gausdir, "g09")
else:
GausPrefix = settings.GausPath
if shutil.which(GausPrefix) is None:
print('Gaussian.py, RunCalcs:\n Could not find Gaussian executable at ' + GausPrefix)
quit()
for f in GausJobs:
time.sleep(3)
print(GausPrefix + " < " + f + ' > ' + f[:-3] + 'out')
outp = subprocess.check_output(GausPrefix + " < " + f + ' > ' + f[:-3] + 'out', shell=True,timeout= 86400)
NCompleted += 1
if IsGausCompleted(f[:-4] + '.out'):
Completed.append(f[:-4] + '.out')
print("Gaussian job " + str(NCompleted) + " of " + str(len(GausJobs)) + \
" completed.")
else:
print("Gaussian job terminated with an error. Continuing.")
if NCompleted > 0:
print(str(NCompleted) + " Gaussian jobs completed successfully.")
return Completed
def WriteGausFile(Gausinp, conformer, atoms, charge, settings, type):
f = open(Gausinp + '.com', 'w')
if(settings.nProc > 1):
f.write('%nprocshared=' + str(settings.nProc) + '\n')
if settings.DFT == 'g':
f.write('%mem=2000MB\n%chk='+Gausinp + '.chk\n')
elif settings.DFT == 'z':
f.write('%mem=1000MB\n%chk=' + Gausinp + '.chk\n')
else:
f.write('%mem=6000MB\n%chk='+Gausinp + '.chk\n')
if type == 'nmr':
f.write(NMRRoute(settings))
elif type == 'e':
f.write(ERoute(settings))
elif type == 'opt':
f.write(OptRoute(settings))
f.write('\n'+Gausinp+'\n\n')
f.write(str(charge) + ' 1\n')
natom = 0
for atom in conformer:
f.write(atoms[natom] + ' ' + atom[0] + ' ' + atom[1] + ' ' +
atom[2] + '\n')
natom = natom + 1
f.write('\n')
f.close()
def NMRRoute(settings):
route = '# ' + settings.nFunctional + '/' + settings.nBasisSet
if (settings.nFunctional).lower() == 'm062x':
route += ' int=ultrafine'
route += ' nmr=giao'
if settings.Solvent != '':
route += ' scrf=(solvent=' + settings.Solvent + ')'
route += '\n'
return route
def ERoute(settings):
route = '# ' + settings.eFunctional + '/' + settings.eBasisSet
if (settings.eFunctional).lower() == 'm062x':
route += ' int=ultrafine'
if settings.Solvent != '':
route += ' scrf=(solvent=' + settings.Solvent + ')'
route += '\n'
return route
def OptRoute(settings):
route = '# ' + settings.oFunctional + '/' + settings.oBasisSet
if (settings.oFunctional).lower() == 'm062x':
route += ' int=ultrafine'
route += ' Opt=(maxcycles=' + str(settings.MaxDFTOptCycles)
if settings.CalcFC == True:
route += ',CalcFC'
if (settings.OptStepSize != 30):
route += ',MaxStep=' + str(settings.OptStepSize)
route += ')'
if settings.Solvent != '':
route += ' scrf=(solvent=' + settings.Solvent + ')'
route += '\n'
return route
def IsGausCompleted(f):
Gfile = open(f, 'r')
outp = Gfile.readlines()
Gfile.close()
if len(outp) < 10:
return False
if ("Normal termination" in outp[-1]) or (('termination' in '\n'.join(outp[-3:])) and ('l9999.exe' in '\n'.join(outp[-3:]))):
return True
else:
return False
def IsGausConverged(f):
Gfile = open(f, 'r')
outp = Gfile.readlines()
Gfile.close()
ginp = '\n'.join(outp)
if 'Stationary point found' in ginp:
return True
else:
return False
#Read energy from e, if not present, then o, if not present, then nmr
def ReadEnergies(Isomers, settings):
jobdir = os.getcwd()
if 'e' in settings.Workflow:
os.chdir('e')
elif 'o' in settings.Workflow:
os.chdir('opt')
else:
os.chdir('nmr')
for i, iso in enumerate(Isomers):
if 'e' in settings.Workflow:
GOutpFiles = iso.EOutputFiles
elif 'o' in settings.Workflow:
GOutpFiles = iso.OptOutputFiles
else:
GOutpFiles = iso.NMROutputFiles
DFTEnergies = []
for GOutpFile in GOutpFiles:
gausfile = open(GOutpFile, 'r')
GOutp = gausfile.readlines()
gausfile.close()
for line in GOutp:
if 'SCF Done:' in line:
start = line.index(') =')
end = line.index('A.U.')
energy = float(line[start + 4:end])
DFTEnergies.append(energy)
Isomers[i].DFTEnergies = DFTEnergies
os.chdir(jobdir)
return Isomers
def ReadShieldings(Isomers):
jobdir = os.getcwd()
os.chdir('nmr')
for iso in Isomers:
if len(iso.NMROutputFiles) < 1:
print("Gaussian.py, ReadShieldings: No NMR DFT output" +
" files found, NMR data could not be read. Quitting.")
quit()
for GOutpFile in iso.NMROutputFiles:
gausfile = open(GOutpFile, 'r')
GOutp = gausfile.readlines()
gausfile.close()
index = 0
shieldings = []
labels = []
# Find the NMR shielding calculation section
while not 'Magnetic shielding' in GOutp[index]:
index = index + 1
# Read shielding constants and labels
for line in GOutp[index:]:
if 'Isotropic' in line:
data = [_f for _f in line.split(' ') if _f]
shieldings.append(float(data[4]))
labels.append(data[1] + data[0])
print(GOutpFile,len(shieldings))
iso.ConformerShieldings.append(shieldings)
iso.ShieldingLabels = labels
os.chdir(jobdir)
return Isomers
def ReadGeometry(GOutpFile):
gausfile = open(GOutpFile, 'r')
GOutp = gausfile.readlines()
gausfile.close()
atoms = []
coords = []
gindex = -1
#Find the last geometry section
for index in range(len(GOutp)):
if ('Input orientation:' in GOutp[index]) or ("Standard orientation:" in GOutp[index]):
gindex = index + 5
if gindex < 0:
print('Error: No geometry found in file ' + GOutpFile)
quit()
#Read geometry
for line in GOutp[gindex:]:
if '--------------' in line:
break
else:
data = [_f for _f in line[:-1].split(' ') if _f]
atoms.append(GetAtomSymbol(int(data[1])))
coords.append(data[3:])
#return atoms, coords, charge
return atoms, coords
def ReadGeometries(Isomers, settings):
jobdir = os.getcwd()
if ('o' in settings.Workflow):
os.chdir('opt')
for iso in Isomers:
iso.DFTConformers = [[] for x in iso.OptOutputFiles]
if len(iso.OptOutputFiles) < 1:
print("Gaussian.py, ReadGeometries: No geometry optimisation output" +
" files found, geometries could not be read. Quitting.")
quit()
for num, GOutpFile in enumerate(iso.OptOutputFiles):
atoms, coords = ReadGeometry(GOutpFile)
iso.DFTConformers[num] = coords
iso.Atoms = atoms
else:
os.chdir('nmr')
for iso in Isomers:
iso.DFTConformers = [[] for x in iso.NMROutputFiles]
if len(iso.NMROutputFiles) < 1:
print("Gaussian.py, ReadGeometries: No NMR DFT output" +
" files found, geometries could not be read. Quitting.")
quit()
for num, GOutpFile in enumerate(iso.NMROutputFiles):
atoms, coords = ReadGeometry(GOutpFile)
iso.DFTConformers[num] = coords
iso.Atoms = atoms
#return atoms, coords, charge
os.chdir(jobdir)
return Isomers
def GetAtomSymbol(AtomNum):
Lookup = ['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', \
'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', \
'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', \
'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', \
'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', \
'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', \
'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn']
if AtomNum > 0 and AtomNum < len(Lookup):
return Lookup[AtomNum-1]
else:
print("No such element with atomic number " + str(AtomNum))
return 0