-
Notifications
You must be signed in to change notification settings - Fork 3
/
RotMol
executable file
·334 lines (294 loc) · 18.2 KB
/
RotMol
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
#!/usr/bin/python
from __future__ import print_function, absolute_import
# Python Libraries ############################################
import subprocess, sys, os, commands, math, time, tarfile, random
from decimal import Decimal
from glob import glob
from optparse import OptionParser
# Some useful arrays ##########################################
periodictable = ["","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","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Uub","Uut","Uuq","Uup","Uuh","Uus","Uuo"]
atomicmass = [0.0,1.008, 4.003, 6.941, 9.012, 10.81, 12.01, 14.01, 16.00, 19.00, 20.18, 22.99, 24.31, 26.98, 28.09, 30.97, 32.07, 35.45, 39.95, 39.10, 40.08, 44.96, 47.87, 50.94, 52.00, 54.94, 55.84, 58.93, 58.69,
63.55, 65.39, 69.72, 72.61, 74.92, 78.96, 79.90, 83.80, 85.47, 87.62, 88.91, 91.22, 92.91, 95.94, 99.0, 101.07, 102.91, 106.42, 107.87, 112.41, 114.82, 118.71, 121.76, 127.60, 126.90, 131.29]
def elementID(massno):
if massno < len(periodictable): return periodictable[massno]
else: return "XX"
def atomicnumber(element):
atomicno = 0
for i in range(0,len(periodictable)):
if element == periodictable[i]: atomicno = i
return atomicno
#Read molecule data from a compchem output file
class getoutData:
def __init__(self, file):
if not os.path.exists(file):
print(("\nFATAL ERROR: Output file [ %s ] does not exist"%file))
def getFORMAT(self, outlines):
for i in range(0,len(outlines)):
if outlines[i].find("Gaussian") > -1: self.FORMAT = "Gaussian"; break
if outlines[i].find("MOPAC") > -1: self.FORMAT = "Mopac"; break
def getSPIN(self, outlines, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("<Sx>") > -1:
self.S2 = (float(outlines[i].split()[7]))
def getJOBTYPE(self, outlines, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find(" # ") > -1:
self.JOBTYPE = outlines[i].lstrip(" #").rstrip("\n")
break
def getTERMINATION(self, outlines,format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("Normal termination") > -1: self.TERMINATION = "normal"
def getCHARGE(self, outlines, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("Charge = ") > -1:
self.CHARGE = int(outlines[i].split()[2])
self.MULT = int(outlines[i].split()[5].rstrip("\n"))
break
if format == "Mopac":
self.CHARGE = 0
#ideally add up all the atomic charges here?
self.MULT = 1
def getATOMTYPES(self, outlines, format):
self.ATOMTYPES = []
self.CARTESIANS = []
self.ATOMICTYPES = []
if format == "Gaussian":
anharmonic_geom=0
for i in range(0,len(outlines)):
if outlines[i].find("Input orientation") > -1:
standor = i #; print("standor", standor)
if outlines[i].find("Standard orientation") > -1:
standor = i #; print("standor", standor)
if outlines[i].find("Vib.Av.Geom.") > -1:
standor = i #; print("standor", standor)
anharmonic_geom=1
if outlines[i].find("Distance matrix") > -1 or outlines[i].find("Rotational constants") >-1:
if outlines[i-1].find("-------") > -1:
self.NATOMS = i-standor-6
#print("NATOMS", self.NATOMS)
try: standor
except NameError: pass
else:
for i in range (standor+5,standor+5+self.NATOMS):
self.ATOMTYPES.append(elementID(int(outlines[i].split()[1])))
self.ATOMICTYPES.append(int(outlines[i].split()[2]))
if anharmonic_geom==0:
if len(outlines[i].split()) > 5: self.CARTESIANS.append([float(outlines[i].split()[3]),float(outlines[i].split()[4]),float(outlines[i].split()[5])])
else: self.CARTESIANS.append([float(outlines[i].split()[2]),float(outlines[i].split()[3]),float(outlines[i].split()[4])])
if anharmonic_geom==1:self.CARTESIANS.append([float(outlines[i].split()[2]),float(outlines[i].split()[3]),float(outlines[i].split()[4])])
if format == "Mopac":
for i in range(0,len(outlines)):
#if outlines[i].find("TOTAL ENERGY") > -1: #Get the energy (convert from eV to Hartree)
# energy=(float(line.split()[3]))
# energy=energy*0.036749309
if outlines[i].find("CARTESIAN COORDINATES") > -1: startgeom = i+4
if outlines[i].find("ATOMIC ORBITAL ELECTRON POPULATIONS") > -1: endgeom = i-2; break
#if outlines[i].find("TOTAL CPU TIME") > -1:
# time=[0.0,0.0,0.0,float(line.split()[3])]
self.NATOMS = endgeom - startgeom
for i in range (startgeom,endgeom):
self.ATOMTYPES.append(outlines[i].split()[1])
self.CARTESIANS.append([float(outlines[i].split()[2]),float(outlines[i].split()[3]),float(outlines[i].split()[4])])
def getFREQS(self, outlines, format):
self.FREQS = []; self.NORMAL_MODES = []
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("Frequencies") > -1:
self.FREQS.append(float(outlines[i].split()[2]))
if len(outlines[i].split()) > 3: self.FREQS.append(float(outlines[i].split()[3]))
if len(outlines[i].split()) > 4: self.FREQS.append(float(outlines[i].split()[4]))
if outlines[i].find("Atom AN X Y Z") > -1:
for j in range(i+1, i+1+self.NATOMS): pass #print(outlines[j].split()[3:6])
if len(self.FREQS) > 0:
for i in range(0,len(outlines)):
if outlines[i].find("Zero-point correction") > -1: self.ZPE = float(outlines[i].split()[2])
if outlines[i].find("thermal Enthalpies") > -1: self.ENTHALPY = float(outlines[i].split()[6])
if outlines[i].find("thermal Free Energies") > -1: self.GIBBS = float(outlines[i].split()[7])
def getMULLIKEN(self, outlines, natoms, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("Mulliken charges:") > -1 or outlines[i].find("Mulliken charges and spin densities:") > -1:
self.MULLIKEN = []
for j in range(i+2,i+natoms+2):
self.MULLIKEN.append(float(outlines[j].split()[2]))
def getAPT(self, outlines, natoms, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("APT charges:") > -1:
self.APT = []
for j in range(i+2,i+natoms+2):
self.APT.append(float(outlines[j].split()[2]))
def getCPU(self, outlines, format):
days = 0
hours = 0
mins = 0
secs = 0
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("Job cpu time") > -1:
days = days + int(outlines[i].split()[3])
hours = hours + int(outlines[i].split()[5])
mins = mins + int(outlines[i].split()[7])
secs = secs + int(float(outlines[i].split()[9]))
self.CPU=[days,hours,mins,secs]
def getSPIN(self, outlines, format):
if format == "Gaussian":
for i in range(0,len(outlines)):
if outlines[i].find("<Sx>") > -1:
self.S2 = (float(outlines[i].split()[7]))
def getENERGY(self, outlines, format):
if format == "Gaussian":
uff = 0
am1 = 0
pm3 = 0
scf = 0
oniom = 0
for i in range(0,len(outlines)):
if outlines[i].find(" UFF") > -1: uff = i
if outlines[i] .find("AM1") > -1: am1 = i
if outlines[i].find("PM3") > -1: pm3 = i
if outlines[i].find("ONIOM") > -1: oniom = i
if outlines[i].find("SCF Done") > -1: scf = i
if outlines[i].find("(RB3LYP)") > -1 or outlines[i].find("(UB3LYP)") > -1: self.FUNCTIONAL = "B3LYP"
if outlines[i].find("(RB-P86)") > -1: self.FUNCTIONAL = "BP86"
if outlines[i].find("(RB2PLYP)") > -1: self.FUNCTIONAL = "B2PLYP"
if outlines[i].find("(RM06)") > -1: self.FUNCTIONAL = "M06"
if outlines[i].find("(RM062X)") > -1: self.FUNCTIONAL = "M06-2X"
if outlines[i].find("(RM06L)") > -1: self.FUNCTIONAL = "M06L"
if outlines[i].find("(RB97D)") > -1: self.FUNCTIONAL = "B97D"
calctype = [uff,am1,pm3,oniom,scf]
for i in range(0,len(outlines)):
if scf == max(calctype) and outlines[i].find("SCF Done") > -1 and outlines[i].find("Initial convergence to 1.0D-05 achieved")==-1: # Get energy from HF or DFT calculation
self.ENERGY = (float(outlines[i].split()[4]))
if oniom == max(calctype) and outlines[i].find("ONIOM: extrapolated energy") > -1: # Get energy from ONIOM calculation
self.ENERGY = (float(outlines[i].split()[4]))
if pm3 == max(calctype) or am1 == max(calctype) or uff == max(calctype):
if outlines[i].find("Energy= ") > -1 and outlines[i].find("Predicted")==-1 and outlines[i].find("Thermal")==-1: # Get energy from Semi-empirical or Molecular Mechanics calculation
self.ENERGY = (float(outlines[i].split()[1]))
if outlines[i].find("Total free energy in solution") > -1:
self.SOLVENERGY = (float(outlines[i+1].split()[7]))
if os.path.exists(file): outfile = open(file,"r")
outlines = outfile.readlines()
getFORMAT(self, outlines)
getJOBTYPE(self, outlines, self.FORMAT)
getTERMINATION(self, outlines,self.FORMAT)
getCHARGE(self, outlines, self.FORMAT)
getENERGY(self, outlines, self.FORMAT)
getSPIN(self, outlines, self.FORMAT)
getATOMTYPES(self, outlines, self.FORMAT)
getFREQS(self, outlines, self.FORMAT)
getCPU(self, outlines, self.FORMAT)
getMULLIKEN(self, outlines, self.NATOMS, self.FORMAT)
getAPT(self, outlines, self.NATOMS, self.FORMAT)
#print "\nSuccessfully read geometry output", file
#Rotate a molecule about its centre of mass
def rotateMol(mol):
# set up an array of new Cartesian coordinates
newcoord=[]
for i in range(0,len(mol.CARTESIANS)): newcoord.append(mol.CARTESIANS[i])
# create a random rotation axis
rot = [random.randint(0,180), random.randint(0,180), random.randint(0,180)]
mol_mass, m_x, m_y, m_z = 0.0, 0.0, 0.0, 0.0
print("Spinning molecule about its centre of mass by",rot)
# molecular mass
for atom, cartesian in zip(mol.ATOMTYPES, newcoord):
mol_mass += atomicmass[atomicnumber(atom)]
m_x += cartesian[0]*atomicmass[atomicnumber(atom)]
m_y += cartesian[1]*atomicmass[atomicnumber(atom)]
m_z += cartesian[2]*atomicmass[atomicnumber(atom)]
center_of_mass = [m_x/mol_mass, m_y/mol_mass, m_z/mol_mass]
print('Center of Mass', center_of_mass)
# define a rotation tensor
xvector=[center_of_mass[0]+1.0, center_of_mass[1], center_of_mass[2], rot[0]]
yvector=[center_of_mass[0], center_of_mass[1]+1.0, center_of_mass[2], rot[1]]
zvector=[center_of_mass[0], center_of_mass[1], center_of_mass[2]+1.0, rot[2]]
rotvector=[xvector,yvector,zvector]
# apply the rotation
for vector in rotvector:
magvector = math.sqrt(vector[0]*vector[0] + vector[1]*vector[1] + vector[2]*vector[2])
unitvector = [vector[0]/magvector, vector[1]/magvector, vector[2]/magvector]
theta = vector[3] / 180.0 * math.pi
for atom, coord in enumerate(newcoord):
dotproduct=unitvector[0]*((newcoord[atom][0])-(center_of_mass[0]))+unitvector[1]*((newcoord[atom][1])-(center_of_mass[1]))+unitvector[2]*((newcoord[atom][2])-(center_of_mass[2]))
centre=[(center_of_mass[0])+dotproduct*unitvector[0],(center_of_mass[1])+dotproduct*unitvector[1],(center_of_mass[2])+dotproduct*unitvector[2]]
v=[(newcoord[atom][0])-centre[0],(newcoord[atom][1])-centre[1],(newcoord[atom][2])-centre[2]]
d=math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2])
px=v[0]*math.cos(theta)+v[1]*math.sin(theta)*unitvector[2]-v[2]*math.sin(theta)*unitvector[1]
py=v[1]*math.cos(theta)+v[2]*math.sin(theta)*unitvector[0]-v[0]*math.sin(theta)*unitvector[2]
pz=v[2]*math.cos(theta)+v[0]*math.sin(theta)*unitvector[1]-v[1]*math.sin(theta)*unitvector[0]
newv=[px+centre[0],py+centre[1],pz+centre[2]]
newdist=math.sqrt(px*px+py*py+pz*pz)
newcoord[atom]=newv
return newcoord
class writeGinput:
############################################################################
# Gaussian Format #
############################################################################
def __init__(self, file, MolSpec, args):
if args.overwrite == False: newfile = os.path.splitext(file)[0]+'_'+args.append
elif args.overwrite == True: newfile = os.path.splitext(file)[0]
outfile = newfile+'.com'
chkfile = newfile+'.chk'
while len(chkfile.split('/')) > 1: chkfile = chkfile.split('/')[1]
print(" ", file, ">>", outfile)
fileout = open(outfile, "w")
fileout.write("%chk="+chkfile+"\n")
if hasattr(args, "mem"): fileout.write("%mem="+args.mem+"\n")
if hasattr(args, "nproc"): fileout.write("%nprocshared="+str(args.nproc)+"\n")
fileout.write("# "+args.route+"\n\n")
fileout.write(newfile+"\n\n")
if not hasattr(args, "charge") and not hasattr(args, "mult"):
fileout.write(str(MolSpec.CHARGE)+" "+str(MolSpec.MULT)+"\n")
else:
fileout.write(str(args.charge)+" "+str(args.mult)+"\n")
for i in range(0,MolSpec.NATOMS):
fileout.write(MolSpec.ATOMTYPES[i])
if args.invert == None: fileout.write(" "+str(Decimal(str((MolSpec.CARTESIANS[i][0])))))
else: fileout.write(" "+str(Decimal(str((-1.0 * MolSpec.CARTESIANS[i][0])))))
for j in range(1,3):
fileout.write(" "+str(Decimal(str((MolSpec.CARTESIANS[i][j])))))
fileout.write("\n")
fileout.write("\n")
if args.opt != None:
for option in args.opt: fileout.write(option+"\n")
fileout.write("\n")
def main():
# get command line inputs. Use -h to list all possible arguments and default values
parser = OptionParser(usage="Usage: %prog [options] <input1>.log <input2>.log ...")
parser.add_option("-n", dest="n_struct", action="store", help="Number of rotated structures to generate", default=1, type="int", metavar="NSTRUCT")
parser.add_option('--append', action="store", default="new", help='Append text to create new filenames')
parser.add_option('--route', action="store", default="", help='Route command line')
parser.add_option('--program', action="store", default='G16', help='Program to run calculations: [G16, Orca]')
parser.add_option('--nproc', action="store", default=24, help='Number of processors for calculations')
parser.add_option('--mem', action="store", default='96GB',help='Memory for calculations')
parser.add_option('--mult', action="store", help='Specify multiplicity')
parser.add_option('--charge', action="store", help='Specify charge')
parser.add_option('--invert', action="store", default=None, help='Mirror invert molecule')
parser.add_option('--overwrite', action="store_true", default=False, help='Overwrites existing input files')
parser.add_option('--opt', action="store", default=None, help='Optional section e.g. basis set specification')
(options, args) = parser.parse_args()
print(options.n_struct)
# Get the filenames from the command line prompt
files = []
if len(sys.argv) > 1:
for elem in sys.argv[1:]:
try:
if os.path.splitext(elem)[1] in [".out", ".log"]:
for file in glob(elem): files.append(file)
except IndexError: pass
# read in coordinates for each structure
for file in files:
for n in range(0, options.n_struct):
xyzdata = getoutData(file)
xyzdata.CARTESIANS = rotateMol(xyzdata)
if options.program.upper() == 'G16':
options.append = str(n+1); writeGinput(file, xyzdata, options)
else: print('WARNING:', options.program, 'is not supported ...' )
if __name__ == "__main__":
main()