-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathase_utils.py
More file actions
194 lines (171 loc) · 6.24 KB
/
ase_utils.py
File metadata and controls
194 lines (171 loc) · 6.24 KB
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
from pathlib import Path
import torch
from tqdm import tqdm
from torch_geometric.data import Data
import numpy as np
from ase import Atoms, units
from ase.calculators.calculator import Calculator
from ase.calculators.singlepoint import SinglePointCalculator as sp
from ase.md import MDLogger
from ase.md.velocitydistribution import MaxwellBoltzmannDistribution
from ase.io import Trajectory
from torch_geometric.data import Batch
def atoms_to_batch(atoms):
atomic_numbers = torch.Tensor(atoms.get_atomic_numbers())
positions = torch.Tensor(atoms.get_positions())
cell = torch.Tensor(np.array(atoms.get_cell())).view(1, 3, 3)
natoms = positions.shape[0]
return Data(
cell=cell,
pos=positions,
atomic_numbers=atomic_numbers,
natoms=natoms,
)
# Modified pbc
def data_to_atoms(data, pbc=[True, True, True]):
numbers = data.atomic_numbers
positions = data.pos
cell = data.cell.squeeze()
atoms = Atoms(numbers=numbers,
positions=positions.cpu().detach().numpy(),
cell=cell.cpu().detach().numpy(),
pbc=pbc)
return atoms
# Modified pbc
def batch_to_atoms(batch, pbc=[True, True, True]):
n_systems = batch.natoms.shape[0]
natoms = batch.natoms.tolist()
numbers = torch.split(batch.atomic_numbers, natoms)
forces = torch.split(batch.force, natoms)
positions = torch.split(batch.pos, natoms)
# tags = torch.split(batch.tags, natoms)
cells = batch.cell
if batch.y is not None:
energies = batch.y.tolist()
else:
energies = [None] * n_systems
atoms_objects = []
for idx in range(n_systems):
atoms = Atoms(
numbers=numbers[idx].tolist(),
positions=positions[idx].cpu().detach().numpy(),
cell=cells[idx].cpu().detach().numpy(),
pbc=pbc,
)
calc = sp(
atoms=atoms,
energy=energies[idx],
forces=forces[idx].cpu().detach().numpy(),
)
atoms.set_calculator(calc)
atoms_objects.append(atoms)
return atoms_objects
class MDCalculator(Calculator):
implemented_properties = ["energy", "forces"]
def __init__(self, model, normalizer, device):
"""
OCP-ASE Calculator. The default unit for energy is eV.
Args:
config_yml (str):
Path to yaml config or could be a dictionary.
checkpoint (str):
Path to trained checkpoint.
"""
super().__init__()
self.model = model
self.normalize = normalizer
self.device = device
def calculate(self, atoms, properties, system_changes):
Calculator.calculate(self, atoms, properties, system_changes)
data_object = atoms_to_batch(atoms)
batch = Batch.from_data_list([data_object]).to(self.device)
self.model.eval()
with torch.no_grad():
energy, forces = self.model(batch)
energy = self.normalize.denorm(energy)
self.results["energy"] = energy.item()
self.results["forces"] = forces.cpu().numpy()
class NeuralMDLogger(MDLogger):
def __init__(self,
*args,
start_time=0,
verbose=True,
**kwargs):
if start_time == 0:
header = True
else:
header = False
super().__init__(header=header, *args, **kwargs)
"""
Logger uses ps units.
"""
self.start_time = start_time
self.verbose = verbose
if verbose:
print(self.hdr)
self.natoms = self.atoms.get_number_of_atoms()
def __call__(self):
if self.start_time > 0 and self.dyn.get_time() == 0:
return
epot = self.atoms.get_potential_energy()
ekin = self.atoms.get_kinetic_energy()
temp = ekin / (1.5 * units.kB * self.natoms)
if self.peratom:
epot /= self.natoms
ekin /= self.natoms
if self.dyn is not None:
t = self.dyn.get_time() / (1000*units.fs) + self.start_time
dat = (t,)
else:
dat = ()
dat += (epot+ekin, epot, ekin, temp)
if self.stress:
dat += tuple(self.atoms.get_stress() / units.GPa)
self.logfile.write(self.fmt % dat)
self.logfile.flush()
if self.verbose:
print(self.fmt % dat)
class Simulator:
def __init__(self,
atoms,
integrator,
T_init,
start_time=0,
save_dir='./log',
restart=False,
save_frequency=100,
min_temp=0.1,
max_temp=100000):
self.atoms = atoms
self.integrator = integrator
self.save_dir = Path(save_dir)
self.min_temp = min_temp
self.max_temp = max_temp
self.natoms = self.atoms.get_number_of_atoms()
# intialize system momentum
if not restart:
assert (self.atoms.get_momenta() == 0).all()
MaxwellBoltzmannDistribution(self.atoms, T_init * units.kB)
# attach trajectory dump
self.traj = Trajectory(self.save_dir / 'atoms.traj', 'a', self.atoms)
self.integrator.attach(self.traj.write, interval=save_frequency)
# attach log file
self.integrator.attach(NeuralMDLogger(self.integrator, self.atoms,
self.save_dir / 'thermo.log',
start_time=start_time, mode='a'),
interval=save_frequency)
def run(self, steps):
early_stop = False
step = 0
for step in tqdm(range(steps)):
self.integrator.run(1)
ekin = self.atoms.get_kinetic_energy()
temp = ekin / (1.5 * units.kB * self.natoms)
if temp < self.min_temp or temp > self.max_temp:
print(f'Temprature {temp:.2f} is out of range: \
[{self.min_temp:.2f}, {self.max_temp:.2f}]. \
Early stopping the simulation.')
early_stop = True
break
self.traj.close()
return early_stop, (step+1)