This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
_dynamics.py
384 lines (334 loc) · 12.4 KB
/
_dynamics.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
"""
Dynamics calculations using M3GNet
"""
import contextlib
import io
import pickle
import sys
from typing import Optional, Union
import numpy as np
from ase import Atoms, units
from ase.calculators.calculator import Calculator, all_changes
from ase.constraints import ExpCellFilter
from ase.io import Trajectory
from ase.md.nptberendsen import NPTBerendsen, Inhomogeneous_NPTBerendsen
from ase.md.nvtberendsen import NVTBerendsen
from ase.optimize.bfgs import BFGS
from ase.optimize.bfgslinesearch import BFGSLineSearch
from ase.optimize.fire import FIRE
from ase.optimize.lbfgs import LBFGS, LBFGSLineSearch
from ase.optimize.mdmin import MDMin
from ase.optimize.optimize import Optimizer
from ase.optimize.sciopt import SciPyFminBFGS, SciPyFminCG
from pymatgen.core.structure import Molecule, Structure
from pymatgen.io.ase import AseAtomsAdaptor
from ._base import Potential
from ._m3gnet import M3GNet
OPTIMIZERS = {
"FIRE": FIRE,
"BFGS": BFGS,
"LBFGS": LBFGS,
"LBFGSLineSearch": LBFGSLineSearch,
"MDMin": MDMin,
"SciPyFminCG": SciPyFminCG,
"SciPyFminBFGS": SciPyFminBFGS,
"BFGSLineSearch": BFGSLineSearch,
}
class M3GNetCalculator(Calculator):
"""
M3GNet calculator based on ase Calculator
"""
implemented_properties = ["energy", "free_energy", "forces", "stress"]
def __init__(self, potential: Potential, compute_stress: bool = True, stress_weight: float = 1.0, **kwargs):
"""
Args:
potential (Potential): m3gnet.models.Potential
compute_stress (bool): whether to calculate the stress
stress_weight (float): the stress weight.
**kwargs:
"""
super().__init__(**kwargs)
self.potential = potential
self.compute_stress = compute_stress
self.stress_weight = stress_weight
def calculate(
self,
atoms: Optional[Atoms] = None,
properties: Optional[list] = None,
system_changes: Optional[list] = None,
):
"""
Args:
atoms (ase.Atoms): ase Atoms object
properties (list): list of properties to calculate
system_changes (list): monitor which properties of atoms were
changed for new calculation. If not, the previous calculation
results will be loaded.
Returns:
"""
properties = properties or ["energy"]
system_changes = system_changes or all_changes
super().calculate(atoms=atoms, properties=properties, system_changes=system_changes)
graph = self.potential.graph_converter(atoms)
graph_list = graph.as_tf().as_list()
results = self.potential.get_efs_tensor(graph_list, include_stresses=self.compute_stress)
self.results.update(
energy=results[0].numpy().ravel(),
free_energy=results[0].numpy().ravel(),
forces=results[1].numpy(),
)
if self.compute_stress:
self.results.update(stress=results[2].numpy()[0] * self.stress_weight)
class Relaxer:
"""
Relaxer is a class for structural relaxation
"""
def __init__(
self,
potential: Optional[Union[Potential, str]] = None,
optimizer: Union[Optimizer, str] = "FIRE",
relax_cell: bool = True,
stress_weight: float = 0.01,
):
"""
Args:
potential (Optional[Union[Potential, str]]): a potential,
a str path to a saved model or a short name for saved model
that comes with M3GNet distribution
optimizer (str or ase Optimizer): the optimization algorithm.
Defaults to "FIRE"
relax_cell (bool): whether to relax the lattice cell
stress_weight (float): the stress weight for relaxation
"""
if isinstance(potential, str):
potential = Potential(M3GNet.load(potential))
if potential is None:
potential = Potential(M3GNet.load())
if isinstance(optimizer, str):
optimizer_obj = OPTIMIZERS.get(optimizer, None)
elif optimizer is None:
raise ValueError("Optimizer cannot be None")
else:
optimizer_obj = optimizer
self.opt_class: Optimizer = optimizer_obj
self.calculator = M3GNetCalculator(potential=potential, stress_weight=stress_weight)
self.relax_cell = relax_cell
self.potential = potential
self.ase_adaptor = AseAtomsAdaptor()
def relax(
self,
atoms: Atoms,
fmax: float = 0.1,
steps: int = 500,
traj_file: str = None,
interval=1,
verbose=False,
**kwargs,
):
"""
Args:
atoms (Atoms): the atoms for relaxation
fmax (float): total force tolerance for relaxation convergence.
Here fmax is a sum of force and stress forces
steps (int): max number of steps for relaxation
traj_file (str): the trajectory file for saving
interval (int): the step interval for saving the trajectories
**kwargs:
Returns:
"""
if isinstance(atoms, (Structure, Molecule)):
atoms = self.ase_adaptor.get_atoms(atoms)
atoms.set_calculator(self.calculator)
stream = sys.stdout if verbose else io.StringIO()
with contextlib.redirect_stdout(stream):
obs = TrajectoryObserver(atoms)
if self.relax_cell:
atoms = ExpCellFilter(atoms)
optimizer = self.opt_class(atoms, **kwargs)
optimizer.attach(obs, interval=interval)
optimizer.run(fmax=fmax, steps=steps)
obs()
if traj_file is not None:
obs.save(traj_file)
if isinstance(atoms, ExpCellFilter):
atoms = atoms.atoms
return {
"final_structure": self.ase_adaptor.get_structure(atoms),
"trajectory": obs,
}
class TrajectoryObserver:
"""
Trajectory observer is a hook in the relaxation process that saves the
intermediate structures
"""
def __init__(self, atoms: Atoms):
"""
Args:
atoms (Atoms): the structure to observe
"""
self.atoms = atoms
self.energies: list[float] = []
self.forces: list[np.ndarray] = []
self.stresses: list[np.ndarray] = []
self.atom_positions: list[np.ndarray] = []
self.cells: list[np.ndarray] = []
def __call__(self):
"""
The logic for saving the properties of an Atoms during the relaxation
Returns:
"""
self.energies.append(self.compute_energy())
self.forces.append(self.atoms.get_forces())
self.stresses.append(self.atoms.get_stress())
self.atom_positions.append(self.atoms.get_positions())
self.cells.append(self.atoms.get_cell()[:])
def compute_energy(self) -> float:
"""
calculate the energy, here we just use the potential energy
Returns:
"""
energy = self.atoms.get_potential_energy()
return energy
def save(self, filename: str):
"""
Save the trajectory to file
Args:
filename (str): filename to save the trajectory
Returns:
"""
with open(filename, "wb") as f:
pickle.dump(
{
"energy": self.energies,
"forces": self.forces,
"stresses": self.stresses,
"atom_positions": self.atom_positions,
"cell": self.cells,
"atomic_number": self.atoms.get_atomic_numbers(),
},
f,
)
class MolecularDynamics:
"""
Molecular dynamics class
"""
def __init__(
self,
atoms: Atoms,
potential: Union[Potential, str] = "MP-2021.2.8-EFS",
ensemble: str = "nvt",
temperature: int = 300,
timestep: float = 1.0,
pressure: float = 1.01325 * units.bar,
taut: Optional[float] = None,
taup: Optional[float] = None,
compressibility_au: Optional[float] = None,
trajectory: Optional[Union[str, Trajectory]] = None,
logfile: Optional[str] = None,
loginterval: int = 1,
append_trajectory: bool = False,
):
"""
Args:
atoms (Atoms): atoms to run the MD
potential (Potential): potential for calculating the energy, force,
stress of the atoms
ensemble (str): choose from 'nvt' or 'npt'. NPT is not tested,
use with extra caution
temperature (float): temperature for MD simulation, in K
timestep (float): time step in fs
pressure (float): pressure in eV/A^3
taut (float): time constant for Berendsen temperature coupling
taup (float): time constant for pressure coupling
compressibility_au (float): compressibility of the material in A^3/eV
trajectory (str or Trajectory): Attach trajectory object
logfile (str): open this file for recording MD outputs
loginterval (int): write to log file every interval steps
append_trajectory (bool): Whether to append to prev trajectory
"""
if isinstance(potential, str):
potential = Potential(M3GNet.load(potential))
if isinstance(atoms, (Structure, Molecule)):
atoms = AseAtomsAdaptor().get_atoms(atoms)
self.atoms = atoms
self.atoms.set_calculator(M3GNetCalculator(potential=potential))
if taut is None:
taut = 100 * timestep * units.fs
if taup is None:
taup = 1000 * timestep * units.fs
if ensemble.lower() == "nvt":
self.dyn = NVTBerendsen(
self.atoms,
timestep * units.fs,
temperature_K=temperature,
taut=taut,
trajectory=trajectory,
logfile=logfile,
loginterval=loginterval,
append_trajectory=append_trajectory,
)
elif ensemble.lower() == "npt":
"""
NPT ensemble default to Inhomogeneous_NPTBerendsen thermo/barostat
This is a more flexible scheme that fixes three angles of the unit
cell but allows three lattice parameter to change independently.
"""
self.dyn = Inhomogeneous_NPTBerendsen(
self.atoms,
timestep * units.fs,
temperature_K=temperature,
pressure_au=pressure,
taut=taut,
taup=taup,
compressibility_au=compressibility_au,
trajectory=trajectory,
logfile=logfile,
loginterval=loginterval,
# append_trajectory=append_trajectory,
# this option is not supported in ASE at this point (I have sent merge request there)
)
elif ensemble.lower() == "npt_berendsen":
"""
This is a similar scheme to the Inhomogeneous_NPTBerendsen.
This is a less flexible scheme that fixes the shape of the
cell - three angles are fixed and the ratios between the three
lattice constants.
"""
self.dyn = NPTBerendsen(
self.atoms,
timestep * units.fs,
temperature_K=temperature,
pressure_au=pressure,
taut=taut,
taup=taup,
compressibility_au=compressibility_au,
trajectory=trajectory,
logfile=logfile,
loginterval=loginterval,
append_trajectory=append_trajectory,
)
else:
raise ValueError("Ensemble not supported")
self.trajectory = trajectory
self.logfile = logfile
self.loginterval = loginterval
self.timestep = timestep
def run(self, steps: int):
"""
Thin wrapper of ase MD run
Args:
steps (int): number of MD steps
Returns:
"""
self.dyn.run(steps)
def set_atoms(self, atoms: Atoms):
"""
Set new atoms to run MD
Args:
atoms (Atoms): new atoms for running MD
Returns:
"""
calculator = self.atoms.calc
self.atoms = atoms
self.dyn.atoms = atoms
self.dyn.atoms.set_calculator(calculator)