venuspython 1.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1435 @@
1
+ from ase import units
2
+
3
+ #from scipy.optimize import minimize, root
4
+ from scipy.interpolate import interp1d
5
+ from ase.optimize import QuasiNewton, LBFGS
6
+ from ase.vibrations import Vibrations
7
+ import random
8
+
9
+ import numpy as np
10
+
11
+ ########################################################################################
12
+
13
+ class initialSampling:
14
+
15
+ # Some conversion constants
16
+ kB = 8.617281e-5 # eV
17
+ freq2energy = 1.000 # cm^-1
18
+ rotConstant2energy = 0.00209008 # eV
19
+
20
+ # Distance to separate the centers of mass of
21
+ # the two molecules so that hey have little
22
+ # to no interactions (in Angstrom)
23
+ dSEPARATED = 200.0 # 200.0
24
+
25
+ # A larger number of points will make the
26
+ # semiclassical sampling converge smoother
27
+ NorderPolynomial = 50 # 100
28
+
29
+ # Threshold for error in rovibrational energy
30
+ # (in quanta) for the semiclassical sampling
31
+ Nvib_error_threshold = 1.0e-1 # 1.0e-5
32
+
33
+ # If "debug" is true, then more information
34
+ # is printed out during the sampling
35
+ debug=True
36
+
37
+ def __init__(self,mol,atomsInFirstGroup,optimize=False,optimization_file="optimization.traj",
38
+ samplingMethodA="thermal",vibrationalSampleA=298,rotationalSampleA=298,
39
+ samplingMethodB="thermal",vibrationalSampleB=298,rotationalSampleB=298):
40
+
41
+ self.mol = mol
42
+ self.optimize = optimize
43
+ self.optimization_file = optimization_file
44
+
45
+ self.samplingMethodA = samplingMethodA
46
+ self.vibrationalSampleA = vibrationalSampleA
47
+ self.rotationalSampleA = rotationalSampleA
48
+ self.samplingMethodB = samplingMethodB
49
+ self.vibrationalSampleB = vibrationalSampleB
50
+ self.rotationalSampleB = rotationalSampleB
51
+
52
+ self.Natoms = len(self.mol)
53
+ self.atomsInFirstGroup = atomsInFirstGroup
54
+ self.atomsInSecondGroup = []
55
+ for i in range(self.Natoms):
56
+ if (i not in atomsInFirstGroup): self.atomsInSecondGroup.append(i)
57
+
58
+ ##########################################################################################################
59
+
60
+ # First, basic functions are defined below:
61
+
62
+ # Get the kinetic energy of the molecule
63
+ def getKineticEnergy(self,m,p):
64
+ KE = 0.0
65
+ for i in range(len(m)):
66
+ KE += np.inner(p[i],p[i])/m[i]
67
+
68
+ return 0.5e0 * KE
69
+
70
+ # Separate the two molecules
71
+ def separateMolecules(self):
72
+ masses = self.mol.get_masses()
73
+ q = self.mol.get_positions()
74
+ if (len(self.atomsInFirstGroup) > 0):
75
+ mass1 = sum([masses[i] for i in self.atomsInFirstGroup])
76
+ r1 = sum([masses[i]*q[i] for i in self.atomsInFirstGroup]) / mass1
77
+ else:
78
+ r1 = np.array([0.0, 0.0, 0.0])
79
+ if (len(self.atomsInSecondGroup) > 0):
80
+ mass2 = sum([masses[i] for i in self.atomsInSecondGroup])
81
+ r2 = sum([masses[i]*q[i] for i in self.atomsInSecondGroup]) / mass2
82
+ else:
83
+ r2 = np.array([0.0, 0.0, 0.0])
84
+
85
+ for i in range(self.Natoms):
86
+ if i in self.atomsInFirstGroup:
87
+ q[i] -= r1
88
+ # q[i][0] += self.dSEPARATED
89
+ q[i][0] += 2*self.dSEPARATED # Temporary fix to make parsing NWChem output easier
90
+ else:
91
+ q[i] -= r2
92
+ # q[i][0] -= self.dSEPARATED
93
+ q[i][0] -= 0.0 # Temporary fix to make parsing NWChem output easier
94
+
95
+ self.mol.set_positions(q)
96
+
97
+ # Get the center-of-mass of the molecule
98
+ def getCenterOfMass(self,m,q):
99
+ qCM = np.zeros((3))
100
+ for i in range(len(m)):
101
+ qCM += m[i]*q[i]
102
+
103
+ return qCM / sum(m)
104
+
105
+ # Place the center-of-mass of the molecule at the origin
106
+ def centerMolecule(self,reactantIndexes):
107
+ masses = self.mol.get_masses()
108
+ q = self.mol.get_positions()
109
+ r = self.getCenterOfMass(masses[reactantIndexes],q[reactantIndexes])
110
+ for i in range(self.Natoms):
111
+ if i in reactantIndexes:
112
+ q[i] -= r
113
+
114
+ self.mol.set_positions(q)
115
+
116
+ # Rotate the molecule's coordinates by a rotationa matrix
117
+ def rotateMolecule(self,reactantIndexes,rotationMatrix):
118
+ q = self.mol.get_positions()
119
+ p = self.mol.get_momenta()
120
+ for i in reactantIndexes:
121
+ q[i] = np.dot(rotationMatrix.transpose(),q[i])
122
+ p[i] = np.dot(rotationMatrix.transpose(),p[i])
123
+
124
+ self.mol.set_positions(q)
125
+ self.mol.set_momenta(p)
126
+
127
+ # Rotate a set of normal modes or velocities by a rotation matrix
128
+ def rotateNormalModes(self,nmodes,rotationMatrix):
129
+ newmodes = np.copy(nmodes)
130
+ for i in range(len(nmodes)):
131
+ nmode = nmodes[i]
132
+ for Natom in range(len(nmode)):
133
+ newmodes[i][Natom] = np.dot(rotationMatrix.transpose(),nmode[Natom])
134
+
135
+ return newmodes
136
+
137
+ # Calculate the moment of inertia tensor from the
138
+ # mass, m, and coordinates, q
139
+ def getMomentOfInertia(self,m,q):
140
+ I = np.zeros((3,3))
141
+ for i in range(len(m)):
142
+ qi = q[i]
143
+ I += m[i] * (np.diag(np.tile(np.inner(qi,qi),3)) - np.outer(qi,qi))
144
+
145
+ return I
146
+
147
+ # Do an SVD to get the principal axes of a 3x3 matrix
148
+ def getPrincipalAxes(self,I):
149
+ U, S, VH = np.linalg.svd(I)
150
+
151
+ return S, U
152
+
153
+ # Choose a random rotation in 3D space
154
+ def chooseRandomSpatialRotation(self):
155
+
156
+ # First, get a random unit vector for the x-axis
157
+ while True:
158
+ u = np.array([random.random(), random.random(), random.random()])
159
+ u -= 0.5e0
160
+ u2 = sum(u**2)
161
+ if (u2 > 1.0e-4):
162
+ u = u / np.sqrt(u2)
163
+ break
164
+
165
+ # Second, get a random unit vector for the y-axis
166
+ # orthogonal to the already-chosen x-axis
167
+ while True:
168
+ v = np.array([random.random(), random.random(), random.random()])
169
+ v -= 0.5e0
170
+ v = np.cross(u,v)
171
+ v2 = sum(v**2)
172
+ if (v2 > 1.0e-4):
173
+ v = v / np.sqrt(v2)
174
+ break
175
+
176
+ # Third, define the z-axis to be the unit vector
177
+ # orthogonal to both the x- and y-axis, with the
178
+ # sign chosen randomly
179
+ w = np.cross(u,v)
180
+ if (random.random() > 0.5e0):
181
+ w = -w
182
+
183
+ # Three orthogonal unit vectors are one way to
184
+ # construct a random rotation matrix
185
+ return np.array([u, v, w])
186
+
187
+ # Choose a random axis to spin the molecules, and also
188
+ # consider the principal axes if the molecule is linear
189
+ # Output the axis as a normed vector or "unit"
190
+ def chooseRandomUnitAngularVelocity(self,Nlinear,principalAxes):
191
+ if (Nlinear):
192
+ u = 2 * np.pi * random.random()
193
+ a = principalAxes[0] * np.sin(u) + principalAxes[1] * np.cos(u)
194
+ else:
195
+ x = random.random()
196
+ y = random.random()
197
+ z = random.random()
198
+ a = np.array([x,y,z])
199
+ return a / np.norm(a)
200
+
201
+ # Calculate angular speed given the unit angular velocity,
202
+ # moment of inertia tensor, and the required amount of
203
+ # rotational energy
204
+ def getAngularSpeed(self,unitOmega,I,RE):
205
+ REunit = np.inner(unitOmega,np.dot(I,unitOmega))
206
+ return np.sqrt(2*RE/REunit)
207
+
208
+ # Calculate the angular momentum from the (relative)
209
+ # positions and momenta
210
+ def getAngularMomentum(self,q,p):
211
+ L = np.zeros((3))
212
+ for i in range(len(q)):
213
+ L += np.cross(q[i],p[i])
214
+
215
+ return L
216
+
217
+ # Assuming the system is rigid, return the linear momenta
218
+ # which correspond to the given input angular velocity
219
+ def getMomentaFromAngularVelocity(self,m,q,omega):
220
+ p = np.zeros(np.shape(q))
221
+ for i in range(len(m)):
222
+ p[i] = m[i]*np.cross(omega,q[i])
223
+
224
+ return p
225
+
226
+ # Calculate the rotational energy and angular velocity,
227
+ # omega, of the system
228
+ def getErotAndOmegaFromL(self,m,q,L):
229
+ I = self.getMomentOfInertia(m,q)
230
+
231
+ # The singular value decomposition will be able to
232
+ # ignore essentially-zero components of the moment
233
+ # of inertia tensor (e.g., for linear molecules) and
234
+ # allow the inverse to be taken easily
235
+ U, S, VH = np.linalg.svd(I)
236
+ Sinv = np.diag(S)
237
+ for i in range(3):
238
+ if (Sinv[i,i] > 1.0e-12):
239
+ Sinv[i,i] = 1.0e0 / Sinv[i,i]
240
+ else:
241
+ Sinv[i,i] = 0.0e0
242
+
243
+ omega = np.dot(VH.transpose() @ Sinv @ U.transpose(), L)
244
+ Erot = 0.5e0*np.dot(omega,L)
245
+
246
+ return Erot, omega
247
+
248
+ # Calculate the rotational energy and angular velocity,
249
+ # omega, of the system
250
+ def getErotAndOmegaFromP(self,m,q,p):
251
+ L = self.getAngularMomentum(q,p)
252
+ Erot, omega = self.getErotAndOmegaFromL(m,q,L)
253
+
254
+ return Erot, omega
255
+
256
+ ##########################################################################################################
257
+
258
+ # Calculate Gauss-Legendre x-values and weights (x,w(x))
259
+ def gaussLegendre(self,xLEFT,xRIGHT,n,xx=None):
260
+
261
+ # First, get the roots of the Gauss-Legendre
262
+ # polynomial, if they were not given
263
+ m = int((n+1)/2)
264
+ if (xx == None):
265
+ xx = np.zeros((m))
266
+ df = np.zeros((m))
267
+ for i in range(m):
268
+ j = i + 1
269
+ xx[i] = np.cos(np.pi*(j - 0.25e0)/(n+0.50e0))
270
+
271
+ # Find the root with the
272
+ # Newton-Raphson formula
273
+ f = 1.0e0
274
+ while (abs(f) > 1.0e-13):
275
+ f, df[i] = self.legendrePolynomial(xx[i],n)
276
+ xx[i] = xx[i] - f / df[i]
277
+
278
+ # Finally, get the points (x,w(x)) at
279
+ # which the polynomial is evaluated
280
+
281
+ x = np.zeros((n))
282
+ w = np.zeros((n))
283
+
284
+ xm = 0.5e0 * (xRIGHT + xLEFT)
285
+ xl = 0.5e0 * (xRIGHT - xLEFT)
286
+ for i in range(m):
287
+ x[i] = xm - xl * xx[i]
288
+ x[(n-1)-i] = xm + xl * xx[i]
289
+ w[i] = (xl / ((1.0e0 - xx[i]*xx[i]) * df[i] * df[i]) ) / 0.5e0
290
+ w[(n-1)-i] = w[i]
291
+
292
+ return x, w
293
+
294
+ # Calculate the legendre polynomial of
295
+ # order n at x, and its derivative
296
+ def legendrePolynomial(self,x,n):
297
+ p2 = x
298
+ pl = 1.5e0 * x * x - 0.5e0
299
+ for k in range(2,n):
300
+ p1 = p2
301
+ p2 = pl
302
+ pl = float((2*k+1) * p2 * x - k * p1) / (k+1)
303
+
304
+ dpl = n * (x * pl - p2) / (x * x - 1.0e0)
305
+
306
+ return pl, dpl
307
+
308
+ ##########################################################################################################
309
+
310
+ # Took this from: XXXXXXX
311
+ def beyer_swinehart(self, freq, egrain, emax, count='dos', interp=False):
312
+ """Beyer-Swinehart state count
313
+
314
+ Args:
315
+ freq (array): array of frequencies
316
+ egrain (int): energy grain (same unit as freq)
317
+ emax (int): maximum energy (same unit as freq)
318
+ count (str, optional): Count type - dos or sos. Defaults to 'dos'.
319
+ interp (bool, optional): Interpolate to make smoother. Defaults to False.
320
+
321
+ Returns:
322
+ array: density or sum of states
323
+ """
324
+
325
+ # Initialize values for counting (reduce to integers divided by egrain)
326
+ emax = int(round(emax/egrain))
327
+ freq = abs(np.array(freq)) # make all values positive
328
+ if type(freq) == np.float64: # to deal with only one provided frequency value
329
+ freq = [freq]
330
+ # For high egrain values, should use a multiplier for correcting the initial SOS array
331
+ ini_multiplier = egrain//freq[0]
332
+ if ini_multiplier == 0:
333
+ ini_multiplier = 1
334
+ # Set up frequencies
335
+ freq = [1 if f<egrain else int(round(f/egrain)) for f in freq]
336
+ # Set up DOS or SOS count
337
+ if count == 'dos':
338
+ bs = np.zeros(emax)
339
+ bs[0] = 1
340
+ elif count == 'sos':
341
+ bs = np.ones(emax) * ini_multiplier
342
+ # ns = np.zeros((len(freq),emax))
343
+ # Count the states
344
+ for i in range(0,len(freq)):
345
+ for j in range(freq[i],emax):
346
+ bs[j] += bs[j-freq[i]]
347
+ # ns[i][j] += bs[j-freq[i]]
348
+ # Interpolate if toggled
349
+ if interp:
350
+ bs[bs < 1] = 0
351
+ idx = np.nonzero(bs)
352
+ x = np.arange(len(bs))
353
+ interp = interp1d(x[idx],bs[idx],fill_value='extrapolate')
354
+ bs = interp(x)
355
+ # Divide DOS by egrain to get DOS per 1 energy unit
356
+ if count == 'dos':
357
+ bs[1:] /= egrain
358
+ # return bs, ns
359
+ return bs
360
+
361
+ ##########################################################################################################
362
+
363
+ # Find out the "turning points" or the bond
364
+ # lengths which are accessible with this
365
+ # vibrational and rotational energy
366
+ def getRovibrationalRange(self,reactantIndexes,E,angularMomentum,V0):
367
+
368
+ # Initialize some information about the diatom
369
+ L2 = angularMomentum**2
370
+ m = self.mol.get_masses()[reactantIndexes]
371
+ mu = m[0] * m[1] / (m[0] + m[1])
372
+ qBOTH = self.mol.get_positions()
373
+ q = qBOTH[reactantIndexes]
374
+ bondLength = np.sqrt(sum((q[1]-q[0])**2))
375
+
376
+ # If the bond length at the energy minimum is too
377
+ # large, print this warning
378
+ if (bondLength > 6):
379
+ raise ValueError("In FINLNJ: bondLength > 6 for diatom sampling")
380
+
381
+ # Position the diatom so that the bond is along
382
+ # the z-axis; place the atoms so that (assuming
383
+ # the two reactants started separate) the two
384
+ # reactants stay separate
385
+ qCM = self.getCenterOfMass(m,q)
386
+ q[0] = qCM
387
+ q[0][2] -= 0.5e0 * bondLength
388
+ q[1] = qCM
389
+ q[1][2] += 0.5e0 * bondLength
390
+
391
+ # Calculate the energy; only do this when the two
392
+ # reactants are separate
393
+ qBOTH[reactantIndexes] = q
394
+ self.mol.set_positions(qBOTH)
395
+ V = self.mol.get_potential_energy()
396
+
397
+ # Calculate Veff, the rotational + vibrational
398
+ # energy
399
+ Erot0 = L2 / (2 * mu * (bondLength**2))
400
+ Veff = (V - V0) + Erot0
401
+
402
+ if (self.debug):
403
+ print("In FINLNJ: V-V0 = ", (V-V0), "E(not V-V0) = ", Erot0)
404
+ print("In FINLNJ: Veff = ", Veff, " E = ", E)
405
+
406
+ # If the energy is ALREADY above that required
407
+ # for the system, then print this warning
408
+ if (Veff > E):
409
+ # raise ValueError("In FINLNJ: Veff > E for diatom sampling")
410
+
411
+ # temporary addition:
412
+ Nvib = -0.5e0
413
+ return Nvib, bondLength, bondLength
414
+
415
+ # If there are no problems, go on ahead with
416
+ # integrating the energy
417
+
418
+ # First, define the boundaries of the integral
419
+ # as the bond lengths which just are just
420
+ # barely going over the required energy E
421
+
422
+ # Find the upper bound
423
+ q[1][2] = q[0][2] + bondLength
424
+ while True:
425
+
426
+ # Increment the bond by values of 0.001 A
427
+ q[1][2] += 0.001e0
428
+
429
+ # Evaluate the new energy and Veff
430
+ qBOTH[reactantIndexes] = q
431
+ self.mol.set_positions(qBOTH)
432
+ V = self.mol.get_potential_energy()
433
+
434
+ newBondLength = q[1][2] - q[0][2]
435
+ Veff = (V - V0) + L2 / (2 * mu * (newBondLength**2))
436
+
437
+ # Eventually, the potential energy should
438
+ # rise enough to get above the threshold
439
+ if (Veff >= E or newBondLength > 50):
440
+ break
441
+
442
+ rMAX = newBondLength
443
+ if (self.debug): print("In FINLNJ: rMAX(A) = ", rMAX)
444
+
445
+ # Find the lower bound
446
+ q[1][2] = q[0][2] + bondLength
447
+ while True:
448
+
449
+ # Decrement the bond by values of 0.001 A
450
+ q[1][2] -= 0.001e0
451
+
452
+ # Evaluate the new energy and Veff
453
+ qBOTH[reactantIndexes] = q
454
+ self.mol.set_positions(qBOTH)
455
+ V = self.mol.get_potential_energy()
456
+
457
+ # Eventually, the potential energy should
458
+ # rise enough to get above the threshold
459
+ newBondLength = q[1][2] - q[0][2]
460
+ Veff = (V - V0) + L2 / (2 * mu * (newBondLength**2))
461
+
462
+ if (Veff >= E):
463
+ break
464
+
465
+ rMIN = newBondLength
466
+ if (self.debug): print("In FINLNJ: rMIN(A) = ", rMIN)
467
+
468
+ # Prepare the bond lengths for which to
469
+ # integrate the energy over
470
+
471
+ # r, w = GLPAR(rMIN,rMAX,NorderPolynomial)
472
+ r, w = self.gaussLegendre(rMIN,rMAX,self.NorderPolynomial)
473
+
474
+ # Next, take the integral by evaluating the
475
+ # energy on these points
476
+ Asum = 0.0e0
477
+ for j in range(self.NorderPolynomial):
478
+ newBondLength = r[j]
479
+
480
+ q[1][2] = q[0][2] + newBondLength
481
+ qBOTH[reactantIndexes] = q
482
+ self.mol.set_positions(qBOTH)
483
+ V = self.mol.get_potential_energy()
484
+
485
+ Veff = (V - V0) + L2 / (2 * mu * (newBondLength**2))
486
+
487
+ # If some of the points are above the
488
+ # integral (should only be the endpoints)
489
+ # don't add them into the integral
490
+ if (E > Veff):
491
+ Asum += w[j] * np.sqrt(E-Veff)
492
+ else:
493
+ if (self.debug): print("In FINLNJ: see point with E<Veff (r(A),E(kcal/mol),Veff(kcal/mol)) = ", (newBondLength, E, Veff))
494
+
495
+ if (self.debug): print("In FINLNJ: Integral = ", Asum)
496
+
497
+ # Return the molecule to its minimum
498
+ # energy configuration for now
499
+ q[1][2] = q[0][2] + bondLength
500
+ qBOTH[reactantIndexes] = q
501
+ self.mol.set_positions(qBOTH)
502
+
503
+ # The "expected" vibrational quantum number
504
+ # corresponding to this energy can then be
505
+ # computed to see if it agrees with the
506
+ # value requested
507
+ Nvib = np.sqrt(8.0e0 * mu) * Asum / (2*np.pi* np.sqrt(2*self.rotConstant2energy))
508
+ Nvib = Nvib - 0.5e0
509
+
510
+ return Nvib, rMIN, rMAX
511
+
512
+ # Sample a diatomic molecule's acceptable range
513
+ # of bond lengths for the specified quantum numbers
514
+ def getDiatomBondLengthRangeWithEBK(self,reactantIndexes,Nrot0,Nvib0,Evib0,V0):
515
+
516
+ # Initialize some information about the diatom
517
+ m = self.mol.get_masses()[reactantIndexes]
518
+ mu = m[0] * m[1] / (m[0] + m[1])
519
+ q = self.mol.get_positions()[reactantIndexes]
520
+ bondLength = np.sqrt(sum((q[1]-q[0])**2))
521
+
522
+ hnu = Evib0 / (Nvib0 + 0.5e0)
523
+ AM0 = (np.sqrt(2 * self.rotConstant2energy)) * np.sqrt(float(Nrot0*(Nrot0+1)))
524
+
525
+ if (self.debug):
526
+ print("AM from EBK:", AM0)
527
+ print("R0: ", bondLength, "I=mu*R0^2: ", mu*(bondLength**2), "Erot: ", (AM0**2)/(2*mu*(bondLength**2)))
528
+
529
+ # Only accept the range of bond lengths
530
+ # found by the algorithm "FINLNJ" if its
531
+ # expected vibrational quantum number
532
+ # agrees with the requested one
533
+ Ntries = 0
534
+ Erovib = Evib0
535
+ Nvib_error = 1.0e0
536
+ while (abs(Nvib_error) > self.Nvib_error_threshold):
537
+ Nvib, rMIN, rMAX = self.getRovibrationalRange(reactantIndexes,Erovib,AM0,V0)
538
+ Nvib_error = Nvib0 - Nvib
539
+ Erovib = Erovib + Nvib_error * hnu
540
+
541
+ if (self.debug): print("Nvib0:",Nvib0, "Nvib:",Nvib, "Nvib_error:",Nvib_error)
542
+
543
+ Ntries += 1
544
+ if (Ntries > 200):
545
+ raise ValueError("In getDiatomBondLengthRangeWithEBK: Ntries for diatom sampling above 200")
546
+
547
+ # Make sure not to include the turning points themselves
548
+ # in the subsequent distance scans
549
+ rMIN += 0.001e0
550
+ rMAX -= 0.001e0
551
+
552
+ pTEST = np.sqrt(2 * mu * Erovib * 0.0001e0)
553
+
554
+ return rMIN, rMAX, AM0, Erovib, pTEST
555
+
556
+ def chooseQPforDiatom(self,reactantIndexes,Nrot,Nvib,freq):
557
+
558
+ qBOTH = self.mol.get_positions()
559
+ m = self.mol.get_masses()[reactantIndexes]
560
+ mu = m[0] * m[1] / (m[0] + m[1])
561
+ q = qBOTH[reactantIndexes]
562
+ qCM = self.getCenterOfMass(m,q)
563
+
564
+ if (self.debug): print("Nvib:", [Nvib])
565
+
566
+ # Get the energy at this optimized structure;
567
+ # this MUST be a energy minimum for this program
568
+ # to work smoothly
569
+ self.separateMolecules()
570
+ V0 = self.mol.get_potential_energy()
571
+ if (self.debug): print("V0:",V0)
572
+
573
+ # Get the "turning points" or the bounds for
574
+ # the bond length
575
+ Evib = freq * (Nvib + 0.5e0)
576
+ rMIN, rMAX, AM, Erovib, pTEST = self.getDiatomBondLengthRangeWithEBK(reactantIndexes,Nrot,Nvib,Evib,V0)
577
+
578
+ if (self.debug):
579
+ print("Evib: ", Evib, "Erovib: ", Erovib)
580
+ print("Rmin: ", rMIN, "Rmax: ", rMAX)
581
+
582
+ ErotR2 = (AM**2) / (2*mu)
583
+
584
+ # Try out a lot of different positions for the
585
+ # atoms in space; stop when the energy is
586
+ # nearly correct
587
+ while True:
588
+ u = random.random()
589
+ r = rMIN + (rMAX - rMIN) * u
590
+
591
+ q[0] = qCM
592
+ q[0][2] -= 0.5e0 * r
593
+ q[1] = qCM
594
+ q[1][2] += 0.5e0 * r
595
+
596
+ qBOTH[reactantIndexes] = q
597
+ self.mol.set_positions(qBOTH)
598
+ V = self.mol.get_potential_energy()
599
+
600
+ Vdiff = (V - V0)
601
+ Ediff = Erovib - ((ErotR2 / (r**2)) + Vdiff)
602
+
603
+ # This case should occur very rarely if at all...
604
+ # make sure to set Rmin and Rmax correctly to avoid this
605
+ # (so that the MC sampling is correct)
606
+ if (Ediff <= 0.0e0):
607
+ if (self.debug): print("initQP diatom iteration.... ACCEPTED for (r,Ediff) = ", (r,Ediff))
608
+ Ediff = 0.0e0
609
+ PR = 0.0e0
610
+ break
611
+
612
+ else:
613
+ PR = np.sqrt(2.0e0*mu*Ediff)
614
+ Pkinetic = pTEST/PR
615
+
616
+ u = random.random()
617
+ if (Pkinetic < u):
618
+ if (self.debug): print("initQP diatom iteration.... REJECTED for (Kvib>0) (r,Ediff,Pkin) = ", (r,Ediff,Pkinetic))
619
+ continue
620
+
621
+ if (self.debug): print("initQP diatom iteration.... ACCEPTED for (Kvib>0) (r,Ediff,Pkin) = ", (r,Ediff,Pkinetic))
622
+ break
623
+
624
+ # Determine whether to spin clockwise or anticlockwise
625
+ u = random.random()
626
+ if (u < 0.5e0):
627
+ PR = -PR
628
+
629
+ # Now, give the diatom momenta
630
+ pBOTH = self.mol.get_momenta()
631
+ p = pBOTH[reactantIndexes]
632
+ p = np.zeros(p.shape)
633
+
634
+ # First, give it vibrational momenta
635
+ vrel = PR / mu
636
+ vel1 = vrel * m[1] / (m[0] + m[1])
637
+ vel2 = vel1 - vrel
638
+ p[0][2] = m[0] * vel1
639
+ p[1][2] = m[1] * vel2
640
+
641
+ # Second, get a random rotation axis
642
+ u = 2*np.pi * random.random()
643
+ L = np.zeros((3))
644
+ L[0] = AM*np.sin(u)
645
+ L[1] = AM*np.cos(u)
646
+ Ixy = mu * r * r
647
+
648
+ # Third, give it rotational momenta
649
+ q = np.zeros(np.shape(q))
650
+ q[0][2] -= r * m[1] / (m[0] + m[1])
651
+ q[1][2] += r * m[0] / (m[0] + m[1])
652
+ omega = np.zeros((3))
653
+ omega[0] = -L[0] / Ixy
654
+ omega[1] = -L[1] / Ixy
655
+ p += self.getMomentaFromAngularVelocity(m,q,omega)
656
+
657
+ if (self.debug):
658
+ print("initQP Evib and potEvib: ", Evib, Vdiff)
659
+ print("initQP Erot and omega: ", self.getErotAndOmegaFromP(m,q,p))
660
+
661
+ # Set these positions and momenta
662
+ qBOTH[reactantIndexes] = q
663
+ self.mol.set_positions(qBOTH)
664
+
665
+ pBOTH[reactantIndexes] = p
666
+ self.mol.set_momenta(pBOTH)
667
+
668
+ # Finally, separate the molecules again
669
+ self.separateMolecules()
670
+
671
+ return
672
+
673
+ ##########################################################################################################
674
+
675
+ # Choose a total angular momentum from a thermal
676
+ # distribution, similar to that in: (Bunker,1973)
677
+ def chooseAngularMomentumFromSymmetricTopThermalDistribution(self,linear,axesMasses,T):
678
+
679
+ Erot = 0.0e0
680
+ L = np.zeros((3))
681
+
682
+ if (not linear):
683
+
684
+ # Look at the difference between the "axesMasses" or the
685
+ # moment of inertia principal components to see which
686
+ # axes are favored to be "spun on" as Lz
687
+ dI12 = axesMasses[0]-axesMasses[1]
688
+ dI23 = axesMasses[1]-axesMasses[2]
689
+ if (dI12 <= dI23):
690
+ zAxis=2
691
+ else:
692
+ zAxis=0
693
+
694
+ # Define a maximum L (idk why this value in particular)
695
+ LzMAX = np.sqrt(20.0e0*axesMasses[zAxis]*self.kB*T)
696
+
697
+ # Do rejection sampling to determine Lz
698
+ while True:
699
+ u = random.random()
700
+ L[zAxis] = u * LzMAX
701
+ probL = np.exp(-(L[zAxis]**2)/(2*axesMasses[zAxis]*self.kB*T))
702
+ u = random.random()
703
+ if (u <= probL): break
704
+
705
+ # Finally, flip a coin to determine the sign of Lz
706
+ u = random.random()
707
+ if (u > 0.5e0): L[zAxis] = -L[zAxis]
708
+
709
+ # Calculate the Erot contribution from this
710
+ Erot = (L[zAxis]**2)/axesMasses[zAxis]
711
+
712
+ # Determine sampling for the non-z axes
713
+
714
+ # Here, the z-axis is the first spatial dimension
715
+ if (linear or (zAxis==0)):
716
+
717
+ # Use the inverse CDF to determine Lxy
718
+ u = random.random()
719
+ Ixy = np.sqrt(axesMasses[1]*axesMasses[2])
720
+ Lxyz = np.sqrt(L[0]**2 - 2*Ixy*self.kB*T*np.log(1.0e0-u))
721
+ Lxy = np.sqrt(Lxyz**2 - L[0]**2)
722
+
723
+ # Determine a random phase for the x-y partitioning
724
+ # of the Lxy component of the angular momentum
725
+ u = 2 * np.pi * random.random()
726
+ L[1] = Lxy*np.sin(u)
727
+ L[2] = Lxy*np.cos(u)
728
+
729
+ # Calculate the Erot contribution from this
730
+ Erot = 0.5e0*(Erot + ((L[1]**2)/axesMasses[1]) + ((L[2]**2)/axesMasses[2]))
731
+
732
+ # Here, the z-axis is the third spatial dimension
733
+ else:
734
+
735
+ # Use the inverse CDF to determine Lxy
736
+ u = random.random()
737
+ Ixy = np.sqrt(axesMasses[0]*axesMasses[1])
738
+ Lxyz = np.sqrt(L[2]**2 - 2*Ixy*self.kB*T*np.log(1.0e0-u))
739
+ Lxy = np.sqrt(Lxyz**2 - L[2]**2)
740
+
741
+ # Determine a random phase for the x-y partitioning
742
+ # of the Lxy component of the angular momentum
743
+ u = 2 * np.pi * random.random()
744
+ L[0] = Lxy*np.sin(u)
745
+ L[1] = Lxy*np.cos(u)
746
+
747
+ # Calculate the Erot contribution from this
748
+ Erot = 0.5e0*(Erot + ((L[0]**2)/axesMasses[0]) + ((L[1]**2)/axesMasses[1]))
749
+
750
+ if (self.debug): print("AM from thermal:", np.sqrt(sum(L**2)))
751
+
752
+ return Erot, L
753
+
754
+ # Choose vibrational quantum numbers from a thermal
755
+ # distribution
756
+ def chooseVibrationalQuantaFromThermalDistribution(self,freqs,T):
757
+
758
+ vibNums = []
759
+ for freq in freqs:
760
+ u = random.random()
761
+ n = np.floor(-np.log(u)*T*self.kB/freq)
762
+ vibNums.append(n)
763
+
764
+ return np.array(vibNums)
765
+
766
+ # Calculate the vibrational energy contribution of each
767
+ # normal mode, and then compute the amplitude of that
768
+ # mode's harmonic-oscillator-like spatial displacement
769
+ def getVibrationalEnergiesAndAmplitudes(self,freqs,vibNums):
770
+
771
+ Nmodes = len(freqs)
772
+ Evibs = []
773
+ amplitudes = []
774
+ for i in range(Nmodes):
775
+ Evib = (0.5+vibNums[i])*freqs[i]
776
+ Evibs.append(Evib)
777
+ amplitudes.append(np.sqrt(2*Evib)/freqs[i])
778
+
779
+ return np.array(Evibs), np.array(amplitudes)
780
+
781
+ # After choosing an angular momentum, the frequencies,
782
+ # normal modes, and vibrational quanta, choose a set
783
+ # of initial coordinates
784
+ def chooseQPgivenNandLandNormalModes(self,reactantIndexes,vibNums,L0,freqs,nmodes):
785
+
786
+ massesBOTH = self.mol.get_masses()
787
+ qBOTH = self.mol.get_positions()
788
+ pBOTH = self.mol.get_momenta()
789
+
790
+ q0 = qBOTH[reactantIndexes]
791
+ masses = massesBOTH[reactantIndexes]
792
+ qCM = self.getCenterOfMass(masses,q0)
793
+
794
+ if (self.debug): print("reactant indexes:", reactantIndexes)
795
+
796
+ # Get the energy at this optimized structure;
797
+ # this MUST be a energy minimum for this program
798
+ # to work smoothly
799
+ self.separateMolecules()
800
+ E0 = self.mol.get_potential_energy()
801
+ self.centerMolecule(reactantIndexes)
802
+ if (self.debug): print("E0:",E0)
803
+
804
+ # Now, get the corresponding vibrational and
805
+ # rotational energies
806
+ Evibs, amplitudes = self.getVibrationalEnergiesAndAmplitudes(freqs,vibNums)
807
+ Evib0 = sum(Evibs)
808
+ Erot0, omega0 = self.getErotAndOmegaFromL(masses,q0-qCM,L0)
809
+
810
+ Eint0 = Evib0 + Erot0
811
+ if (self.debug): print("Evib0,Erot0,Eint0:",Evib0,Erot0,Eint0)
812
+
813
+ Nmodes = len(freqs)
814
+ Natoms = len(reactantIndexes)
815
+ NpureKinetic=0
816
+
817
+ dq = np.zeros((Nmodes))
818
+ dp = np.zeros((Nmodes))
819
+ while True:
820
+
821
+ # Fill up some normal modes with purely
822
+ # kinetic energy
823
+ for i in range(NpureKinetic):
824
+ dq[i] = 0.0e0
825
+ dp[i] = -freqs[i]*amplitudes[i]
826
+
827
+ # Fill up the other normal modes with a mix
828
+ # of kinetic and potential energy
829
+ for i in range(NpureKinetic,Nmodes):
830
+ u = 2 * np.pi * random.random()
831
+ dq[i] = amplitudes[i]*np.cos(u) / (8065.5401*1.8836518e-3)
832
+ dp[i] = -freqs[i]*amplitudes[i]*np.sin(u)
833
+
834
+ # Modify the original optimized structure
835
+ # with the perturbations
836
+ q = np.copy(q0)
837
+ p = np.zeros(np.shape(q))
838
+ for i in range(Nmodes):
839
+ q += nmodes[i] * dq[i]
840
+ p += nmodes[i] * dp[i]
841
+
842
+ for i in range(Natoms):
843
+ p[i] = p[i] * masses[i]
844
+
845
+ qCM = self.getCenterOfMass(masses,q)
846
+
847
+ # Calculate the new (probably different)
848
+ # angular momentum
849
+ L = self.getAngularMomentum(q-qCM,p)
850
+
851
+ # Comput the "difference" in angular
852
+ # momentum and velocity
853
+ Ldiff = L - L0
854
+ Erot, omega = self.getErotAndOmegaFromL(masses,q-qCM,Ldiff)
855
+
856
+ # Use this angular momentum difference to
857
+ # adjust linear momenta for an accurate
858
+ # angular momentum and rotational energy
859
+ pdiff = self.getMomentaFromAngularVelocity(masses,q-qCM,omega)
860
+ p -= pdiff
861
+
862
+ # Compute the new total potential and kinetic
863
+ # energies of the system
864
+
865
+ qBOTH[reactantIndexes] = q
866
+ self.mol.set_positions(qBOTH)
867
+ KE = self.getKineticEnergy(masses,p)
868
+
869
+ self.separateMolecules()
870
+ E = self.mol.get_potential_energy() + KE
871
+ self.centerMolecule(reactantIndexes)
872
+
873
+ # The internal energy of the molecule of interest
874
+ # will be the difference between the total energy
875
+ # and the reference energy from earlier (when it
876
+ # is at the local minimum)
877
+ Eint = E - E0
878
+
879
+ # See how close this internal energy is to the
880
+ # required amount
881
+ fitnessOfEint = abs(Eint0-Eint)/Eint0
882
+
883
+ qCM = self.getCenterOfMass(masses,q)
884
+ L = self.getAngularMomentum(q-qCM,p)
885
+ Erot, omega = self.getErotAndOmegaFromL(masses,q-qCM,L)
886
+
887
+ if (self.debug):
888
+ print("KErot: ", Erot, " KEvib: ", KE-Erot)
889
+ print(NpureKinetic,fitnessOfEint,Eint0,Eint)
890
+
891
+ # First, if all of the internal energy is rotational,
892
+ # then do not attempt any scaling and just exit
893
+ if (Evib0 < 1.0e-4*Eint0): break
894
+
895
+ # If the internal energy is not that close, then just
896
+ # convert one of the normal modes to being purely
897
+ # kinetic
898
+ if (fitnessOfEint >= 0.1e0 and NpureKinetic < Nmodes):
899
+ NpureKinetic += 1
900
+ continue
901
+
902
+ # If the internal energy is close to that required,
903
+ # try scaling it
904
+ Nscale = 0
905
+ #while (Nscale < 1000 and fitnessOfEint >= 0.001e0):
906
+ while (Nscale < 50 and fitnessOfEint >= 0.001e0):
907
+ scalingFactor = np.sqrt(Eint0/Eint)
908
+ p = p * scalingFactor
909
+ q = q0 + (q - q0) * scalingFactor
910
+
911
+ qCM = self.getCenterOfMass(masses,q)
912
+
913
+ L = self.getAngularMomentum(q-qCM,p)
914
+
915
+ Ldiff = L - L0
916
+ Erot, omega = self.getErotAndOmegaFromL(masses,q-qCM,Ldiff)
917
+
918
+ pdiff = self.getMomentaFromAngularVelocity(masses,q-qCM,omega)
919
+ p -= pdiff
920
+
921
+ qBOTH[reactantIndexes] = q
922
+ self.mol.set_positions(qBOTH)
923
+ KE = self.getKineticEnergy(masses,p)
924
+
925
+ self.separateMolecules()
926
+ E = self.mol.get_potential_energy() + KE
927
+ self.centerMolecule(reactantIndexes)
928
+
929
+ Eint = E - E0
930
+
931
+ fitnessOfEint = abs(Eint0-Eint)/Eint0
932
+
933
+ qCM = self.getCenterOfMass(masses,q)
934
+ L = self.getAngularMomentum(q-qCM,p)
935
+ Erot, omega = self.getErotAndOmegaFromL(masses,q-qCM,L)
936
+
937
+ if (self.debug):
938
+ print("Erot:",Erot)
939
+ print(fitnessOfEint,Eint0,Eint)
940
+ print(q)
941
+
942
+ if (fitnessOfEint >= 0.1e0 and NpureKinetic < Nmodes):
943
+ NpureKinetic += 1
944
+ break
945
+
946
+ Nscale += 1
947
+
948
+ if (fitnessOfEint < 0.001e0): break
949
+
950
+ pBOTH[reactantIndexes] = p
951
+ self.mol.set_momenta(pBOTH)
952
+
953
+
954
+ # Make a function that will set up the two molecules' internal positions
955
+ # and momenta including their rotational and vibrational energies
956
+ def sampleRelativeQP(self):
957
+
958
+ # If the molecules are not aleady optimized, then they
959
+ # can be done here at the start
960
+ if (self.optimize):
961
+
962
+ # Move the two groups FAR from one another
963
+ self.separateMolecules()
964
+
965
+ # Optimize the two molecules with ASE
966
+ # optimizer = QuasiNewton(
967
+ # self.mol,maxstep=0.0100, # original NWChemEx value = 0.0250,
968
+ optimizer = LBFGS(
969
+ self.mol, # original NWChemEx value = 0.0250,
970
+ trajectory=self.optimization_file,
971
+ )
972
+
973
+ # The convergence threshold is in the default units (eV and Ang)
974
+ # optimizer.run(1.0e-3, 10000) # original value = 5.0e-3
975
+ # optimizer.run(4.0e-3, 10000)
976
+ optimizer.run(1.0e-2, 10000)
977
+ # optimizer.run(1.8e-2, 10000)
978
+ # optimizer.run(1.0e-2, 10000)
979
+
980
+ ###############################################################################
981
+
982
+ Nreactant = 0
983
+ reactantGroups = [self.atomsInFirstGroup, self.atomsInSecondGroup]
984
+ samplingMethod = [self.samplingMethodA, self.samplingMethodB]
985
+ rotationSampling = [self.rotationalSampleA, self.rotationalSampleB]
986
+ vibrationSampling = [self.vibrationalSampleA, self.vibrationalSampleB]
987
+ for reactantIndexes in reactantGroups:
988
+
989
+ Nreactant += 1
990
+ if (self.debug):
991
+ print("##############################################################")
992
+ print("Initializing reactant group ", Nreactant)
993
+ print(" with atomic indexes:", reactantIndexes)
994
+
995
+ if (len(reactantIndexes) == 0):
996
+ print("No atoms in reactant group ", Nreactant)
997
+ print("Must be unimolecular! Skipping sampling for this group...")
998
+ continue
999
+
1000
+ # You must center the molecule first before calculating
1001
+ # its moment of inertia tensor
1002
+ self.centerMolecule(reactantIndexes)
1003
+ relativeQ0 = self.mol.get_positions()
1004
+ masses = self.mol.get_masses()
1005
+
1006
+ I = self.getMomentOfInertia(masses[reactantIndexes],relativeQ0[reactantIndexes])
1007
+ axesMasses, axesVectors = self.getPrincipalAxes(I)
1008
+ axesMasses = np.array([axesMasses[2], axesMasses[1], axesMasses[0]] ) # Switch axes so that they are in INCREASING order instead
1009
+ # axesVectors = np.array([axesVectors[2],axesVectors[1],axesVectors[0]]) # Switch axes so that they are in INCREASING order instead
1010
+ Ix,Iy,Iz = np.copy(axesVectors[:,2]), np.copy(axesVectors[:,1]), np.copy(axesVectors[:,0])
1011
+ axesVectors[:,0], axesVectors[:,1], axesVectors[:,2] = Ix, Iy, Iz # Switch axes so that they are in INCREASING order instead
1012
+
1013
+ if (self.debug):
1014
+ print("I:", I)
1015
+ print("axesMasses ... axesVectors")
1016
+ for i in range(3):
1017
+ print(axesMasses[i]," ... ",axesVectors[i])
1018
+
1019
+ # Determine whether the molecules is linear by looking at the smallest principal axis
1020
+ # if (axesMasses[0] < axesMasses[1]*1.0e-12):
1021
+ # if (axesMasses[0] < axesMasses[1]*1.0e-8): # As of now, this seems to be a reasonable threshold (haven't tested large linear molecules, though)
1022
+ # if (axesMasses[0] < axesMasses[1]*1.0e-6): # As of now, this seems to be a reasonable threshold (up to the HCCH molecule) (haven't tested large linear molecules, though)
1023
+ if (axesMasses[0] < axesMasses[1]*1.0e-5): # As of now, this seems to be a reasonable threshold (up to the CCC molecule) (haven't tested large linear molecules, though)
1024
+ linear = True
1025
+ else:
1026
+ linear = False
1027
+
1028
+ if (self.debug): print("Reactant is linear?", linear)
1029
+
1030
+ # For accurate energy (and force) calculations, the
1031
+ # two molecules must be first separated
1032
+ self.separateMolecules()
1033
+
1034
+ # Create the vibration instance for the first group of atoms
1035
+ vibFirstGroup = Vibrations(self.mol,indices=reactantIndexes,name=".vib",delta=0.01,nfree=2)
1036
+ vibFirstGroup.clean() # Cleaning is necessary otherwise it will just use results from old runs
1037
+ vibFirstGroup.run()
1038
+ vibFirstGroup.summary()
1039
+ vibFirstGroupData = vibFirstGroup.get_vibrations()
1040
+ Es, modes = vibFirstGroupData.get_energies_and_modes(all_atoms=False)
1041
+
1042
+ if (linear):
1043
+ nonzeroEs = np.real(Es[5:]) * self.freq2energy
1044
+ nonzeroModes = modes[5:]
1045
+ else:
1046
+ nonzeroEs = np.real(Es[6:]) * self.freq2energy
1047
+ nonzeroModes = modes[6:]
1048
+
1049
+ if (any(nonzeroEs < 0)):
1050
+ print("WARNING: one of the 'nonzero' modes has a negative frequency...")
1051
+ print(" for initial sampling, will convert to a positive number")
1052
+ nonzeroEs = np.abs(nonzeroEs)
1053
+
1054
+ if (any(nonzeroEs <= 0.001*self.freq2energy)):
1055
+ print("WARNING: one of the 'nonzero' modes has a close to zero frequency...")
1056
+ print(" for initial sampling, will convert to a small nonzero number (0.001 cm-1)")
1057
+ nonzeroEs[nonzeroEs <= 0.001*self.freq2energy] = 0.001 * self.freq2energy
1058
+
1059
+ ###############################################################################################
1060
+
1061
+ Natoms = len(reactantIndexes)
1062
+
1063
+ q = self.mol.get_positions()[reactantIndexes]
1064
+
1065
+ if (self.debug):
1066
+ print("Reactant, before selection:")
1067
+ for qi in q:
1068
+ print(qi)
1069
+
1070
+ # Monoatomics need no sampling
1071
+ if (Natoms == 1):
1072
+
1073
+ pass
1074
+
1075
+ # If this is a diatom and we are doing the
1076
+ # semiclassical QM sampling, set the quantum
1077
+ # numbers and enter here
1078
+ elif (Natoms == 2 and samplingMethod[Nreactant-1] == "semiclassical"):
1079
+
1080
+ # Change these later to be changed via input file
1081
+ Nrot = rotationSampling[Nreactant-1]
1082
+ Nvib = vibrationSampling[Nreactant-1]
1083
+
1084
+ if (self.debug):
1085
+ print("Semiclassical QM sampling")
1086
+ print("Nrot: ", Nrot)
1087
+ print("Nvib: ", Nvib)
1088
+
1089
+ freq = nonzeroEs[0]
1090
+ self.chooseQPforDiatom(reactantIndexes,Nrot,Nvib,freq)
1091
+
1092
+ # In all other cases, we will be doing a thermal
1093
+ # sampling, so enter the temperatures of interest
1094
+ # here
1095
+ elif (samplingMethod[Nreactant-1] == "thermal"):
1096
+
1097
+ # Change these later to be changed via input file
1098
+ Trot = rotationSampling[Nreactant-1]
1099
+ Tvib = vibrationSampling[Nreactant-1]
1100
+
1101
+ if (self.debug):
1102
+ print("Thermal sampling")
1103
+ print("Trot: ", Trot)
1104
+ print("Tvib: ", Tvib)
1105
+
1106
+ # You must center the molecule first before calculating
1107
+ # any angular-velocity-related property
1108
+ self.centerMolecule(reactantIndexes)
1109
+
1110
+ # Choose the angular momentum vector assuming the molecule
1111
+ # is oriented in the principal axes coordinates
1112
+ self.rotateMolecule(reactantIndexes,axesVectors)
1113
+ modes = self.rotateNormalModes(modes,axesVectors)
1114
+ nonzeroModes = self.rotateNormalModes(nonzeroModes,axesVectors)
1115
+ Erot, L = self.chooseAngularMomentumFromSymmetricTopThermalDistribution(linear,axesMasses,Trot)
1116
+ vibNums = self.chooseVibrationalQuantaFromThermalDistribution(nonzeroEs,Tvib)
1117
+
1118
+ if (self.debug):
1119
+ print("kBTrot:",self.kB*Trot)
1120
+ print("kBTvib:",self.kB*Tvib)
1121
+ print("nonzeroFreqs:",nonzeroEs)
1122
+ print("nonzeroModes:",nonzeroModes)
1123
+ print("Erot:",Erot)
1124
+ print("Evib:",sum([float((x+0.5)*y) for x,y in zip (vibNums,nonzeroEs)]))
1125
+ print("L:", L)
1126
+ print("Nvibs:",[float(x) for x in vibNums])
1127
+ print("Evibs:",[float((x+0.5)*y) for x,y in zip (vibNums,nonzeroEs)])
1128
+
1129
+ self.chooseQPgivenNandLandNormalModes(reactantIndexes,vibNums,L,nonzeroEs,nonzeroModes)
1130
+
1131
+ q = self.mol.get_positions()[reactantIndexes]
1132
+ p = self.mol.get_momenta()[reactantIndexes]
1133
+ ErotTEST, omegaTEST = self.getErotAndOmegaFromP(masses[reactantIndexes],q,p)
1134
+
1135
+ if (self.debug):
1136
+ print("Erot:",ErotTEST)
1137
+ print("omega:", omegaTEST)
1138
+
1139
+ # Enter in the desired Erot and Evib, and this will produce QP
1140
+ elif (samplingMethod[Nreactant-1] == "microcanonical"):
1141
+
1142
+ # Change these later to be changed via input file
1143
+ Erot = rotationSampling[Nreactant-1] * (units.kcal/units.mol)
1144
+ Evib = vibrationSampling[Nreactant-1] * (units.kcal/units.mol)
1145
+
1146
+ if (self.debug):
1147
+ print("Microcanonical sampling")
1148
+ print("Erot: ", Erot)
1149
+ print("Evib: ", Evib)
1150
+
1151
+ # You must center the molecule first before calculating
1152
+ # any angular-velocity-related property
1153
+ self.centerMolecule(reactantIndexes)
1154
+
1155
+ # Choose the angular momentum vector assuming the molecule
1156
+ # is oriented in the principal axes coordinates
1157
+ self.rotateMolecule(reactantIndexes,axesVectors)
1158
+ modes = self.rotateNormalModes(modes,axesVectors)
1159
+ nonzeroModes = self.rotateNormalModes(nonzeroModes,axesVectors)
1160
+ Erot0, L = self.chooseAngularMomentumFromSymmetricTopThermalDistribution(linear,axesMasses,300.0)
1161
+ L = L * np.sqrt(Erot/Erot0)
1162
+
1163
+ Nnonzeromodes = len(nonzeroEs)
1164
+ Evibs = []
1165
+ Evib0 = Evib * 1.0e0
1166
+ ZPEs, amplitudes = self.getVibrationalEnergiesAndAmplitudes(nonzeroEs,[0 for nonzeroE in nonzeroEs])
1167
+
1168
+ # Approximate microcanonical sampling method (NOT the orthant sampling)
1169
+ for i in range(1,Nnonzeromodes):
1170
+ Evibs.append(Evib0 * ((1.0e0 - random.random() ** (1.0e0/(Nnonzeromodes-i)) )))
1171
+ Evib0 -= Evibs[-1]
1172
+ Evibs.append(Evib0)
1173
+
1174
+ vibNums = []
1175
+ for i in range(Nnonzeromodes):
1176
+ vibNums.append((Evibs[i]/nonzeroEs[i]) - 0.50e0)
1177
+
1178
+ if (self.debug):
1179
+ print("nonzeroFreqs:",nonzeroEs)
1180
+ print("nonzeroModes:",nonzeroModes)
1181
+ print("Erot:",Erot)
1182
+ print("Evib:",sum(Evibs))
1183
+ print("L:", L)
1184
+ print("Nvibs:",[float(x) for x in vibNums])
1185
+ print("Evibs:",[float((x+0.5)*y) for x,y in zip (vibNums,nonzeroEs)])
1186
+
1187
+ self.chooseQPgivenNandLandNormalModes(reactantIndexes,vibNums,L,nonzeroEs,nonzeroModes)
1188
+
1189
+ q = self.mol.get_positions()[reactantIndexes]
1190
+ p = self.mol.get_momenta()[reactantIndexes]
1191
+ ErotTEST, omegaTEST = self.getErotAndOmegaFromP(masses[reactantIndexes],q,p)
1192
+
1193
+ if (self.debug):
1194
+ print("Erot:",ErotTEST)
1195
+ print("omega:", omegaTEST)
1196
+
1197
+ # NEW!
1198
+ # Enter in the desired Erot and Evib, and this will produce QP
1199
+ elif (samplingMethod[Nreactant-1] == "microcanonical-wigner"):
1200
+
1201
+ # Change these later to be changed via input file
1202
+ Erot = rotationSampling[Nreactant-1] * (units.kcal/units.mol)
1203
+ Evib = vibrationSampling[Nreactant-1] * (units.kcal/units.mol)
1204
+
1205
+ if (self.debug):
1206
+ print("Microcanonical sampling with Wigner rejection")
1207
+ print("Erot: ", Erot)
1208
+ print("Evib: ", Evib)
1209
+
1210
+ # You must center the molecule first before calculating
1211
+ # any angular-velocity-related property
1212
+ self.centerMolecule(reactantIndexes)
1213
+
1214
+ # Choose the angular momentum vector assuming the molecule
1215
+ # is oriented in the principal axes coordinates
1216
+ self.rotateMolecule(reactantIndexes,axesVectors)
1217
+ modes = self.rotateNormalModes(modes,axesVectors)
1218
+ nonzeroModes = self.rotateNormalModes(nonzeroModes,axesVectors)
1219
+ Erot0, L = self.chooseAngularMomentumFromSymmetricTopThermalDistribution(linear,axesMasses,300.0)
1220
+ L = L * np.sqrt(Erot/Erot0)
1221
+
1222
+ Nnonzeromodes = len(nonzeroEs)
1223
+ ZPEs, amplitudes = self.getVibrationalEnergiesAndAmplitudes(nonzeroEs,[0 for nonzeroE in nonzeroEs])
1224
+
1225
+ Pwigner_max = np.exp(-2*Evib/nonzeroEs[-1]) # The largest frequency determines the maximum probability
1226
+ while True:
1227
+
1228
+ # Approximate microcanonical sampling method (NOT the orthant sampling)
1229
+ Evibs = []
1230
+ Evib0 = Evib * 1.0e0
1231
+ for i in range(1,Nnonzeromodes):
1232
+ Evibs.append(Evib0 * ((1.0e0 - random.random() ** (1.0e0/(Nnonzeromodes-i)) )))
1233
+ Evib0 -= Evibs[-1]
1234
+ Evibs.append(Evib0)
1235
+
1236
+ vibNums = []
1237
+ for i in range(Nnonzeromodes):
1238
+ vibNums.append((Evibs[i]/nonzeroEs[i]) - 0.50e0)
1239
+
1240
+ Pwigner = np.exp(-2*sum([x+0.5e0 for x in vibNums]))
1241
+ Prand = random.random()*Pwigner_max
1242
+
1243
+ if (self.debug):
1244
+ print("Wigner rejection: ", Pwigner, ">=", Prand, "?")
1245
+
1246
+ if (Pwigner >= Prand): break # Von Neumann rejection
1247
+
1248
+ if (self.debug):
1249
+ print("nonzeroFreqs:",nonzeroEs)
1250
+ print("nonzeroModes:",nonzeroModes)
1251
+ print("Erot:",Erot)
1252
+ print("Evib:",sum(Evibs))
1253
+ print("L:", L)
1254
+ print("Nvibs:",[float(x) for x in vibNums])
1255
+ print("Evibs:",[float((x+0.5)*y) for x,y in zip (vibNums,nonzeroEs)])
1256
+
1257
+ self.chooseQPgivenNandLandNormalModes(reactantIndexes,vibNums,L,nonzeroEs,nonzeroModes)
1258
+
1259
+ q = self.mol.get_positions()[reactantIndexes]
1260
+ p = self.mol.get_momenta()[reactantIndexes]
1261
+ ErotTEST, omegaTEST = self.getErotAndOmegaFromP(masses[reactantIndexes],q,p)
1262
+
1263
+ if (self.debug):
1264
+ print("Erot:",ErotTEST)
1265
+ print("omega:", omegaTEST)
1266
+
1267
+ # NEW!
1268
+ # Enter in the desired Erot and Evib, and this will produce QP
1269
+ elif (samplingMethod[Nreactant-1] == "microcanonical-quantum"):
1270
+
1271
+ # Change these later to be changed via input file
1272
+ Erot = rotationSampling[Nreactant-1] * (units.kcal/units.mol)
1273
+ Evib = vibrationSampling[Nreactant-1] * (units.kcal/units.mol)
1274
+
1275
+ if (self.debug):
1276
+ print("Microcanonical sampling with Wigner rejection")
1277
+ print("Erot: ", Erot)
1278
+ print("Evib: ", Evib)
1279
+
1280
+ # You must center the molecule first before calculating
1281
+ # any angular-velocity-related property
1282
+ self.centerMolecule(reactantIndexes)
1283
+
1284
+ # Choose the angular momentum vector assuming the molecule
1285
+ # is oriented in the principal axes coordinates
1286
+ self.rotateMolecule(reactantIndexes,axesVectors)
1287
+ modes = self.rotateNormalModes(modes,axesVectors)
1288
+ nonzeroModes = self.rotateNormalModes(nonzeroModes,axesVectors)
1289
+ Erot0, L = self.chooseAngularMomentumFromSymmetricTopThermalDistribution(linear,axesMasses,300.0)
1290
+ L = L * np.sqrt(Erot/Erot0)
1291
+
1292
+ Nnonzeromodes = len(nonzeroEs)
1293
+ ZPEs, amplitudes = self.getVibrationalEnergiesAndAmplitudes(nonzeroEs,[0 for nonzeroE in nonzeroEs])
1294
+
1295
+ tmp_nonzeroEs = list(nonzeroEs)
1296
+ tmp_indices = list(range(Nnonzeromodes))
1297
+ dEgrain = 0.025 # min(0.01,Evib*1.1*5.0e-3)
1298
+ DOSs = []
1299
+ next_indices = []
1300
+ for i in range(Nnonzeromodes-1):
1301
+ tmp_nonzeroEs.pop()
1302
+ next_index = tmp_indices.pop()
1303
+ next_indices.append(next_index)
1304
+ states = self.beyer_swinehart(tmp_nonzeroEs, dEgrain, Evib*1.1, count='dos', interp=False)
1305
+ DOSs.append(states)
1306
+
1307
+ if (DOSs[0][round((Evib - 0.5e0*sum(nonzeroEs)) // dEgrain)] == 0):
1308
+ raise ValueError("Quantum microcanonical ensemble does not a vibrational state with exactly {:.3f} kcal/mol energy".format(Evib/(units.kcal/units.mol)))
1309
+
1310
+ while True:
1311
+
1312
+ # Approximate microcanonical sampling method (NOT the orthant sampling)
1313
+ Evibs = []
1314
+ Evib0 = Evib * 1.0e0 - 0.5e0*sum(nonzeroEs) # Take out the ZPE
1315
+ for next_index,dos in zip(next_indices,DOSs):
1316
+ while True:
1317
+ Evib_chosen = round(random.random() * Evib0 / nonzeroEs[next_index]) * nonzeroEs[next_index]
1318
+ Pquantum = dos[int((Evib0-Evib_chosen) // dEgrain)] / dos[int((Evib0) // dEgrain)]
1319
+ Prand = random.random()
1320
+ if (self.debug): print("MicrocanonicalQuantum rejection: ", Pquantum, ">=", Prand, "? for mode", next_index, "Evib_left:", Evib0-Evib_chosen)
1321
+ if (Pquantum > Prand): break
1322
+ Evibs.insert(0,Evib_chosen)
1323
+ Evib0 -= Evibs[0]
1324
+ if (next_index == 2): break
1325
+
1326
+ candidateEvib12s = []
1327
+ for n1 in range(1+int(Evib0//nonzeroEs[0])):
1328
+ Evib1 = n1 * nonzeroEs[0]
1329
+ for n2 in range(1+int(Evib0//nonzeroEs[1])):
1330
+ Evib2 = n2 * nonzeroEs[1]
1331
+ if (np.abs(Evib1+Evib2-Evib0) < dEgrain):
1332
+ candidateEvib12s.append([Evib1,Evib2])
1333
+
1334
+ if (len(candidateEvib12s) == 0):
1335
+ if (self.debug): print("Warning: inconsistency in microcanonical-quantum sampling ... will try to resample...")
1336
+ continue
1337
+ tmpEvibs = random.choice(candidateEvib12s) + Evibs
1338
+ Evibs = [float(x + 0.5e0*y) for x,y in zip(tmpEvibs,nonzeroEs)]
1339
+
1340
+ vibNums = []
1341
+ for i in range(Nnonzeromodes):
1342
+ vibNums.append((Evibs[i]/nonzeroEs[i]) - 0.50e0)
1343
+
1344
+ break
1345
+
1346
+
1347
+
1348
+ if (self.debug):
1349
+ print("nonzeroFreqs:",nonzeroEs)
1350
+ print("nonzeroModes:",nonzeroModes)
1351
+ print("Erot:",Erot)
1352
+ print("Evib:",sum(Evibs))
1353
+ print("L:", L)
1354
+ print("Nvibs:",[float(x) for x in vibNums])
1355
+ print("Evibs:",[float((x+0.5)*y) for x,y in zip (vibNums,nonzeroEs)])
1356
+
1357
+ self.chooseQPgivenNandLandNormalModes(reactantIndexes,vibNums,L,nonzeroEs,nonzeroModes)
1358
+
1359
+ q = self.mol.get_positions()[reactantIndexes]
1360
+ p = self.mol.get_momenta()[reactantIndexes]
1361
+ ErotTEST, omegaTEST = self.getErotAndOmegaFromP(masses[reactantIndexes],q,p)
1362
+
1363
+ if (self.debug):
1364
+ print("Erot:",ErotTEST)
1365
+ print("omega:", omegaTEST)
1366
+
1367
+
1368
+ else:
1369
+
1370
+ raise ValueError("Incorrect sampling method chosen: ", samplingMethod[Nreactant-1])
1371
+
1372
+ q = self.mol.get_positions()[reactantIndexes]
1373
+ if (self.debug):
1374
+ print("Reactant, after selection:")
1375
+ for qi in q:
1376
+ print(qi)
1377
+
1378
+ # After choosing relative positions, rotate the
1379
+ # molecule randomly in 3D space
1380
+ axesVectors = self.chooseRandomSpatialRotation()
1381
+ self.centerMolecule(reactantIndexes)
1382
+ self.rotateMolecule(reactantIndexes,axesVectors)
1383
+ self.separateMolecules()
1384
+
1385
+ # After sampling the relative coordinates and momenta of
1386
+ # each molecule, the relative position and speed of the
1387
+ # two molecules with respect to each other can be set
1388
+ # Collision energy in kcal/mol
1389
+ # Center-of-mass distance (dCM) and
1390
+ # impact parameter (b) in Anstrom
1391
+ def sampleAbsoluteQP(self,collisionEnergy,dCM=10.0,b=0.0):
1392
+
1393
+ # Get the masses of each group of atoms
1394
+ masses=self.mol.get_masses()
1395
+ totalMass = sum(masses)
1396
+ massA = sum([masses[i] for i in self.atomsInFirstGroup])
1397
+ massB = totalMass - massA
1398
+
1399
+ self.centerMolecule(self.atomsInFirstGroup)
1400
+ self.centerMolecule(self.atomsInSecondGroup)
1401
+
1402
+ # Construct the vector between the two
1403
+ # molecules' centers of mass
1404
+ dPARALLEL = np.sqrt(dCM**2 - b**2)
1405
+ rPARALLEL = np.array([1.0, 0.0, 0.0])
1406
+ rREL = np.array([dPARALLEL, b, 0.0])
1407
+
1408
+ # First, prepare the impact parameter with this vector
1409
+ # orthogonal to the centers of mass vector
1410
+ q = self.mol.get_positions()
1411
+ for i in self.atomsInFirstGroup:
1412
+ q[i] += rREL
1413
+
1414
+ # Second, prepare the center of mass velocities given the
1415
+ # collision energy
1416
+ reducedmass = massA*massB/(totalMass)
1417
+ speedREL = np.sqrt(2*(collisionEnergy*(units.kcal/units.mol))/reducedmass)
1418
+ vA = -(massB/totalMass)*(speedREL)*rPARALLEL
1419
+ vB = (massA/totalMass)*(speedREL)*rPARALLEL
1420
+
1421
+ v = self.mol.get_velocities()
1422
+ p = self.mol.get_momenta()
1423
+ for i in range(self.Natoms):
1424
+ if i in self.atomsInFirstGroup:
1425
+ v[i] += vA
1426
+ else:
1427
+ v[i] += vB
1428
+
1429
+ p[i] = v[i] * masses[i]
1430
+
1431
+ # Set the new positions and velocities
1432
+ self.mol.set_positions(q)
1433
+ self.mol.set_velocities(v)
1434
+ self.mol.set_momenta(p)
1435
+