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.
venuspy/md.py ADDED
@@ -0,0 +1,492 @@
1
+ from ase.md.verlet import VelocityVerlet
2
+ from ase import units
3
+
4
+ import numpy as np
5
+ import os
6
+
7
+ # For rewinds with sGDML:
8
+ from ase.build import minimize_rotation_and_translation
9
+ from ase.io.trajectory import Trajectory
10
+
11
+
12
+ # Try importing sGDML
13
+ try:
14
+ import sgdml
15
+ from sgdml.train import GDMLTrain
16
+ from sgdml.predict import GDMLPredict
17
+ from sgdml.intf.ase_calc import SGDMLCalculator
18
+
19
+ from .calc.minisgdmlcalc import miniSGDMLCalculator
20
+
21
+ except ImportError:
22
+ print("WARNING: sGDML has not been loaded ... cannot do 'smoothedMD'")
23
+
24
+ ###################################################
25
+
26
+ # Define global constants up here in the correct
27
+ # units so that internally, everything uses:
28
+ # Energy: eV
29
+ # Distance: Angstrom
30
+ # Mass: Dalton
31
+
32
+ global r2threshold
33
+
34
+ r2threshold = 24.0*24.0
35
+
36
+ ###################################################
37
+
38
+
39
+ ########################################################################################
40
+
41
+ # A function to print the potential, kinetic and total energy
42
+ def printenergy(a,step,energyflag=""):
43
+ if ("ERROR" in energyflag):
44
+ epot = 0.0
45
+ ekin = a.get_kinetic_energy() / (units.kcal/units.mol)
46
+ print('@Epot = %.3f Ekin = %.3f (T=%3.0fK) '
47
+ 'Etot = %.3f kcal/mol Step = %8d %s' % (epot, ekin, ekin / (len(a) * 1.5 * 8.617281e-5), epot + ekin, step, energyflag))
48
+ else:
49
+ epot = a.get_potential_energy() / (units.kcal/units.mol)
50
+ ekin = a.get_kinetic_energy() / (units.kcal/units.mol)
51
+ print('@Epot = %.3f Ekin = %.3f (T=%3.0fK) '
52
+ 'Etot = %.3f kcal/mol Step = %8d %s' % (epot, ekin, ekin / (len(a) * 1.5 * 8.617281e-5), epot + ekin, step, energyflag))
53
+
54
+
55
+ # A function to see if any interatomic distance is > 20
56
+ def checkGeneralReactionProgress(a):
57
+ Natoms = len(a)
58
+ stop_flag = False
59
+ for i1 in range(1,Natoms):
60
+ for i2 in range(0,Natoms-1):
61
+
62
+ # Check the squared interatomic distances if any
63
+ # are greater than r2threshold (default is 20^2 = 400)
64
+ r = sum([(a.positions[i1][i] -
65
+ a.positions[i2][i])**2 for i in range(3)])
66
+ if (r > r2threshold):
67
+ stop_flag = True
68
+ break
69
+
70
+ return stop_flag
71
+
72
+ ########################################################################################
73
+
74
+ class regularMD():
75
+
76
+ def __init__(self,mol,trajfile,dt,Nprint=1):
77
+
78
+ self.mol = mol
79
+
80
+ # The timestep
81
+ self.dt = dt
82
+
83
+ # How often to print
84
+ self.Nprint = Nprint
85
+
86
+ # Get the output trajectory file ready
87
+ self.trajfile = trajfile
88
+
89
+ # Run MD with constant energy using the velocity verlet algorithm
90
+ self.dyn = VelocityVerlet(self.mol, self.dt * units.fs )
91
+
92
+ ########################################################################################
93
+
94
+ def production(self,Nsteps):
95
+
96
+ # Now run the dynamics
97
+ printenergy(self.mol,0)
98
+ traj = Trajectory(self.trajfile, mode="a", atoms=self.mol)
99
+ traj.write()
100
+
101
+ for i in range(Nsteps):
102
+ self.dyn.run(self.Nprint)
103
+ printenergy(self.mol,i+1)
104
+ traj.write()
105
+
106
+ stop_flag = checkGeneralReactionProgress(self.mol)
107
+ if (stop_flag): break
108
+
109
+
110
+ ########################################################################################
111
+
112
+ class pingpongMD():
113
+
114
+ def __init__(self,mol,trajfile,dt,Nprint=1,dEmax=1.0,Edriftmax=1.5,E0=None):
115
+
116
+ self.mol = mol
117
+
118
+ # The timestep
119
+ self.dt = dt
120
+
121
+ # How often to print
122
+ self.Nprint = Nprint
123
+
124
+ # The maximum change in total energy allowed for consecutive steps
125
+ self.dEmax = dEmax
126
+
127
+ # The maximum change in total energy allowed from start to end
128
+ self.Edriftmax = Edriftmax
129
+
130
+ # Set the initial total energy to follow the energy drift
131
+ if (E0 is not None):
132
+ self.E0 = E0
133
+ else:
134
+ self.E0 = 0.0
135
+
136
+ # A flag to keep track of when to "pong" (go in reverse)
137
+ self.reversal_countdown = 0
138
+
139
+ # Get the output trajectory file ready
140
+ self.trajfile = trajfile
141
+
142
+ # Run MD with constant energy using the velocity verlet algorithm
143
+ self.dyn = VelocityVerlet(self.mol, self.dt * units.fs )
144
+
145
+ ########################################################################################
146
+
147
+ def production(self,Nsteps):
148
+
149
+ # Now run the dynamics
150
+ printenergy(self.mol,0)
151
+ traj = Trajectory(self.trajfile, mode="a", atoms=self.mol)
152
+ traj.write()
153
+
154
+ for Nstep in range(Nsteps):
155
+ self.dyn.run(self.Nprint)
156
+ printenergy(self.mol,(Nstep+1)*self.Nprint)
157
+ traj.write()
158
+
159
+ epot = self.mol.get_potential_energy()
160
+ ekin = self.mol.get_kinetic_energy()
161
+ etot = (epot + ekin) / (units.kcal/units.mol)
162
+
163
+ # Set some variables up for initialization and to keep track
164
+ # of jumps/drifts in energy
165
+ if (Nstep > 0):
166
+ dE = np.abs(etot - prev_etot)
167
+ Edrift = np.abs(etot - E0)
168
+ else:
169
+ E0 = etot
170
+ dE = 0.0
171
+ Edrift = 0.0
172
+
173
+ prev_etot = etot
174
+
175
+ # Keep track of energy jumps and reverse if its too bad
176
+ if ((dE > self.dEmax) or (Edrift > self.Edriftmax)):
177
+ if (self.reversal_countdown == 0):
178
+ self.reversal_countdown = -11
179
+
180
+ # After the reversal flag is set (counter is negative),
181
+ # let the simulation go for 10 steps before reversing
182
+ if (self.reversal_countdown < 0):
183
+ self.reversal_countdown += 1
184
+ if (self.reversal_countdown == 0): break
185
+
186
+ stop_flag = checkGeneralReactionProgress(self.mol)
187
+ if (stop_flag): break
188
+
189
+ # Run MD with constant energy using the velocity verlet algorithm in REVERSE
190
+ self.reversedyn = VelocityVerlet(self.mol, -self.dt * units.fs )
191
+
192
+ printenergy(self.mol,Nsteps)
193
+ traj.write()
194
+
195
+ for Nstep in range(Nsteps,0,-1):
196
+ self.reversedyn.run(self.Nprint)
197
+ printenergy(self.mol,(Nstep-1)*self.Nprint)
198
+ traj.write()
199
+
200
+ stop_flag = checkGeneralReactionProgress(self.mol)
201
+ if (stop_flag): break
202
+
203
+
204
+ ########################################################################################
205
+
206
+ class smoothedMD():
207
+
208
+ def __init__(self,mol,trajfile,dt,Nprint=1,Nrewindsteps=4,dEmax=1.0,Edriftmax=1.5,E0=None,n_threads=None):
209
+
210
+ self.mol = mol
211
+ self.molsgdml = mol.copy()
212
+
213
+ # The timestep
214
+ self.dt = dt
215
+
216
+ # How often to print
217
+ self.Nprint = Nprint
218
+
219
+ # How many steps to use MLMD at a time
220
+ self.Nrewindsteps = Nrewindsteps
221
+
222
+ # The maximum change in total energy allowed for consecutive steps
223
+ self.dEmax = dEmax
224
+
225
+ # The maximum change in total energy allowed from start to end
226
+ self.Edriftmax = Edriftmax
227
+
228
+ # Set the initial total energy to follow the energy drift
229
+ if (E0 is not None):
230
+ self.E0 = E0
231
+ else:
232
+ self.E0 = 0.0
233
+
234
+ # Number of threads
235
+ self.n_threads = n_threads
236
+
237
+ # Get the output trajectory file ready
238
+ self.trajfile = trajfile
239
+
240
+ # Run MD with constant energy using the velocity verlet algorithm
241
+ self.dyn = VelocityVerlet(self.mol, self.dt * units.fs )
242
+
243
+ # When needed, run MLMD with constant energy using the velocity verlet algorithm
244
+ self.dynsgdml = VelocityVerlet(self.molsgdml, self.dt * units.fs)
245
+
246
+ ########################################################################################
247
+
248
+ def production(self,Nsteps):
249
+
250
+ # Get some stuff initialized
251
+ gdml_trajectory = []
252
+ trajectoryTrainingSet = []
253
+ temporaryTrainingSet = []
254
+ gdml_train = GDMLTrain()
255
+
256
+ currentstep = 0
257
+ Nrewind = 0
258
+ model = None
259
+ E0 = self.E0
260
+
261
+ # Now run the dynamics
262
+ printenergy(self.mol,currentstep,"AB INITIO")
263
+ traj = Trajectory(self.trajfile, mode="a", atoms=self.mol)
264
+ traj.write()
265
+
266
+ for Nstep in range(Nsteps):
267
+
268
+ # Try to use the ab initio method
269
+ energyflag = "AB INITIO"
270
+ newframeflag = True
271
+ try:
272
+ self.dyn.run(self.Nprint)
273
+ currentstep += self.Nprint
274
+
275
+ epot = self.mol.get_potential_energy()
276
+ ekin = self.mol.get_kinetic_energy()
277
+ etot = (epot + ekin) / (units.kcal/units.mol)
278
+
279
+ # Set some variables up for initialization and to keep track
280
+ # of jumps/drifts in energy
281
+ if (Nstep > 0):
282
+ dE = np.abs(etot - trajectoryTrainingSet[-1]['etot'])
283
+ Edrift = np.abs(etot - E0)
284
+ else:
285
+ E0 = etot
286
+ dE = 0.0
287
+ Edrift = 0.0
288
+
289
+ # Keep track of energy jumps and rewind accordingly
290
+ if ((dE > self.dEmax) or (Edrift > self.Edriftmax)):
291
+ energyflag += " ENERGY JUMP/DRIFT (%.1f/%.1f)" % (dE,Edrift)
292
+ Nrewind = self.Nrewindsteps
293
+
294
+ # Test whether or not this new frame is geometrically "new"
295
+ # compared to the training set
296
+ if (len(temporaryTrainingSet) > 0):
297
+ rmsds = []
298
+ tmpmol = self.mol.copy()
299
+ for oldframe in temporaryTrainingSet:
300
+ oldmol = oldframe["mol"]
301
+ minimize_rotation_and_translation(oldmol,tmpmol)
302
+ rmsds.append(np.std(oldmol.get_positions() - tmpmol.get_positions()))
303
+
304
+ # Usually for small molecules, consecutive frames differ by ~ 0.01 A
305
+ if (np.min(rmsds) < 0.01):
306
+
307
+ # If it's not new, then don't add it to the training set
308
+ # and do a little bit more MLMD
309
+ newframeflag = False
310
+ Nrewind = 2
311
+
312
+ # If it's not new, then we will be resetting the MLMD
313
+ else:
314
+ energyflag += " REWIND (%d)" % (1+len(gdml_trajectory))
315
+ gdml_trajectory = []
316
+
317
+ # If it's not new, then we will be resetting the MLMD
318
+ else:
319
+ energyflag += " REWIND (%d)" % (1+len(gdml_trajectory))
320
+ gdml_trajectory = []
321
+
322
+ else:
323
+
324
+ # If the ab initio is successful from a rewind, then throw out
325
+ # the old model to prepare for a new one later
326
+ if (Nrewind > 0):
327
+ model = None
328
+
329
+ # A successful a.i. calculation means we can finally go "forward"
330
+ # in time, including catching up on the ML frames we did earlier
331
+ for oldmol in gdml_trajectory:
332
+ traj.write(atoms=oldmol,calc=oldmol._calc,energy=oldmol._calc.results["energy"])
333
+ traj.write()
334
+ gdml_trajectory = []
335
+
336
+ Nrewind = 0
337
+ trajectoryTrainingSet.append({"mol":self.mol.copy(),"etot":etot,"energy":self.mol.calc.results['energy'],"forces":self.mol.calc.results['forces'],"step":currentstep})
338
+ Ntrain = len(trajectoryTrainingSet)
339
+
340
+ # # Temporary fix to ensure we have at least 10 GOOD frames
341
+ # # and then use the ab initio less often afterwards
342
+ # if (Ntrain > 9):
343
+ # self.mol.calc.restarts_max = 1
344
+ # self.mol._calc.restarts_max = 1
345
+
346
+ # Empty the trajectory training set out if it gets too large
347
+ if (Ntrain > 15):
348
+ del trajectoryTrainingSet[0]
349
+
350
+ # But prepare for failure (e.g. in the SCF convergence)
351
+ except:
352
+ energyflag += " ERROR"
353
+ Nrewind = self.Nrewindsteps
354
+ newframeflag = False
355
+
356
+ # currentstep -= self.Nprint # The last step was NOT successful
357
+ if (model is None):
358
+ energyflag += " REWIND (%d)" % (1)
359
+ currentstep += 1 # or + Nprint dependning on how many successful steps there were before the error
360
+
361
+ printenergy(self.mol,currentstep,energyflag)
362
+
363
+ # Rewind a step or two and do MLMD instead
364
+ if (Nrewind > 0):
365
+
366
+ # If we are using MLMD in response to an energy jump, and
367
+ # happen upon a new frame, add that new a.i. calculation
368
+ # to the training set
369
+ if (newframeflag):
370
+ model = None
371
+
372
+ # The a.i. calculation led to an energy jump so we won't
373
+ # use it in the trajectory, but add it to the training set
374
+ temporaryTrainingSet.append({"mol":self.mol.copy(),"etot":etot,"energy":self.mol.calc.results['energy'],"forces":self.mol.calc.results['forces'],"step":currentstep})
375
+
376
+ # Empty the temporary training set out if it gets too large
377
+ Ntrain = len(temporaryTrainingSet)
378
+ if (Ntrain > 15):
379
+ del temporaryTrainingSet[0]
380
+
381
+ # (Re)make the model with the training set
382
+ if (model is None):
383
+
384
+ # Go back to the last successful a.i. calculation and
385
+ # smooth it with ML (in case the problem was there)
386
+ lastmol = trajectoryTrainingSet[-1]["mol"]
387
+ q = lastmol.get_positions()
388
+ self.molsgdml.set_positions(q)
389
+ p = lastmol.get_momenta()
390
+ self.molsgdml.set_momenta(p)
391
+ v = lastmol.get_velocities()
392
+ self.molsgdml.set_velocities(v)
393
+ currentstep = trajectoryTrainingSet[-1]["step"]
394
+
395
+ # Because we are going back at least one step, we can
396
+ # go forward at least once more to catch up (may be even
397
+ # more if the last successful a.i. calculation was a
398
+ # number of steps back)
399
+ Nrewind += 1
400
+
401
+ # Set up the training set and model
402
+ c1 = 1.0 / (units.kcal/units.mol)
403
+
404
+ movingTrainingSet = trajectoryTrainingSet + temporaryTrainingSet
405
+ Ntrain = len(movingTrainingSet)
406
+
407
+ E = np.array([ x['energy']*c1 for x in movingTrainingSet])
408
+ F = np.array([ x['forces']*c1 for x in movingTrainingSet])
409
+ R = np.array([x['mol'].get_positions() for x in movingTrainingSet])
410
+ Z = np.array([x['mol'].get_atomic_numbers() for x in movingTrainingSet])
411
+ z = Z[0]
412
+
413
+ dataset = {'type': 'd', 'code_version': sgdml.__version__, 'name': np.str_('movingTrainingSet'), 'theory': np.str_('unknown'), 'R': R, 'z': z, 'F': F, 'E': E,}
414
+ dataset['F_min'], dataset['F_max'] = np.min(F.ravel()), np.max(F.ravel())
415
+ dataset['E_min'], dataset['E_max'] = np.min(E.ravel()), np.max(E.ravel())
416
+ dataset['r_unit'] = "Ang"; dataset['e_unit'] = "kcal/mol"
417
+
418
+ # Do a small scan of sigma values to fit the model over
419
+ sigs = [np.random.rand() * 7.5 for i in range(4)]
420
+ sigs.append(5.0)
421
+ sigs.reverse()
422
+
423
+ depots = []
424
+ models = []
425
+ for sig in sigs:
426
+ task = gdml_train.create_task(dataset,Ntrain,dataset,0,sig=sig,use_E_cstr=True)
427
+ # task = gdml_train.create_task(dataset,Ntrain,dataset,0,sig=sig)
428
+ model = gdml_train.train(task)
429
+
430
+ calcsgdml = miniSGDMLCalculator(model,n_threads=self.n_threads)
431
+ self.molsgdml.set_calculator(calcsgdml)
432
+ self.molsgdml.calc = calcsgdml
433
+ self.molsgdml._calc = calcsgdml
434
+
435
+ self.molsgdml.calc.results = {}
436
+ self.molsgdml._calc.results = {}
437
+
438
+ models.append(model)
439
+ depots.append(np.abs(self.molsgdml.get_potential_energy() - trajectoryTrainingSet[-1]["energy"]) / (units.kcal/units.mol))
440
+
441
+ print(" Retrained the sGDML model with Ntrain: %d and sigma: %.3f ... first point error: %.2f kcal/mol" % (Ntrain,sig,depots[-1]))
442
+
443
+ if (depots[-1] < 0.1): break
444
+
445
+ # Use the model that best fits the first point
446
+ model = models[np.argmin(depots)]
447
+
448
+ calcsgdml = miniSGDMLCalculator(model)
449
+ self.molsgdml.set_calculator(calcsgdml)
450
+ self.molsgdml.calc = calcsgdml
451
+ self.molsgdml._calc = calcsgdml
452
+
453
+ self.molsgdml.calc.results = {}
454
+ self.molsgdml._calc.results = {}
455
+
456
+ # Check to see how the ML agrees on the first point
457
+ printenergy(self.molsgdml,currentstep,"sGDML")
458
+
459
+ else:
460
+ self.molsgdml.calc.results = {}
461
+ self.molsgdml._calc.results = {}
462
+
463
+ # Note: is there a more elegant way to handle this case?
464
+ if ("JUMP" in energyflag):
465
+ currentstep -= self.Nprint
466
+
467
+ # Do the MLMD
468
+ for Nrewindstep in range(Nrewind):
469
+ self.dynsgdml.run(self.Nprint)
470
+ currentstep += self.Nprint
471
+ printenergy(self.molsgdml,currentstep,"sGDML")
472
+
473
+ gdml_trajectory.append(self.molsgdml.copy())
474
+ gdml_trajectory[-1]._calc = miniSGDMLCalculator(model)
475
+ gdml_trajectory[-1]._calc.results = {"energy":self.molsgdml._calc.results["energy"][0]}
476
+ gdml_trajectory[-1].calc = gdml_trajectory[-1]._calc
477
+
478
+
479
+ q = self.molsgdml.get_positions()
480
+ self.mol.set_positions(q)
481
+ p = self.molsgdml.get_momenta()
482
+ self.mol.set_momenta(p)
483
+ v = self.molsgdml.get_velocities()
484
+ self.mol.set_velocities(v)
485
+
486
+ self.mol.calc.results = {}
487
+ self.mol._calc.results = {}
488
+
489
+
490
+ stop_flag = checkGeneralReactionProgress(self.mol)
491
+ if (stop_flag): break
492
+