-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathotf_train.py
374 lines (319 loc) · 12.1 KB
/
otf_train.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
import time, os, shutil, glob, subprocess, sys, json
from copy import deepcopy
import pytest
import pkgutil, pyclbr
import importlib
import inspect
import numpy as np
from flare.learners.otf import OTF
from flare.md.fake import FakeDFT
from ase import units
import ase.calculators as ase_calculators
from ase.md.velocitydistribution import (
MaxwellBoltzmannDistribution,
Stationary,
ZeroRotation,
)
from ase import io
from ase.symbols import symbols2numbers
import yaml
def get_super_cell(atoms_config):
"""
Set up Supercell from ASE Atoms
"""
# parse parameters
atoms_file = atoms_config.get("file")
atoms_format = atoms_config.get("format", None)
atoms_index = atoms_config.get("index", -1)
replicate = atoms_config.get("replicate", [1, 1, 1])
jitter = atoms_config.get("jitter", 0)
if atoms_format is not None:
super_cell = io.read(atoms_file, format=atoms_format, index=atoms_index)
else:
super_cell = io.read(atoms_file)
super_cell *= replicate
# jitter positions to give nonzero force on first frame
super_cell.positions += (2 * np.random.rand(len(super_cell), 3) - 1) * jitter
return super_cell
def get_dft_calc(dft_config):
"""
Set up ASE DFT calculator
"""
dft_calc_name = dft_config.get("name", "LennardJones")
dft_calc_kwargs = dft_config.get("kwargs", {})
dft_calc_params = dft_config.get("params", {})
if dft_calc_name == "FakeDFT":
dft_calc = FakeDFT(**dft_calc_kwargs)
dft_calc.set(**dft_calc_params)
return dft_calc
# find the module including the ASE DFT calculator class by name
dft_module_name = ""
for importer, modname, ispkg in pkgutil.iter_modules(ase_calculators.__path__):
module_info = pyclbr.readmodule("ase.calculators." + modname)
if dft_calc_name in module_info:
dft_module_name = modname
break
# if the module is not found in the current folder, then search the sub-directory
if not dft_module_name:
for calc_dir in os.listdir(ase_calculators.__path__[0]):
dir_path = ase_calculators.__path__[0] + "/" + calc_dir
if os.path.isdir(dir_path):
for importer, modname, ispkg in pkgutil.iter_modules([dir_path]):
module_info = pyclbr.readmodule(
"ase.calculators." + calc_dir + "." + modname
)
if dft_calc_name in module_info:
dft_module_name = calc_dir + "." + modname
break
# import ASE DFT calculator module, and build a DFT calculator class object
dft_calc = None
dft_module = importlib.import_module("ase.calculators." + dft_module_name)
for name, obj in inspect.getmembers(dft_module, inspect.isclass):
if name == dft_calc_name:
dft_calc = obj(**dft_calc_kwargs)
dft_calc.set(**dft_calc_params)
return dft_calc
def get_flare_calc(flare_config):
"""
Set up ASE flare calculator
"""
gp_name = flare_config.get("gp")
if gp_name == "GaussianProcess":
return get_gp_calc(flare_config)
elif gp_name == "SGP_Wrapper":
return get_sgp_calc(flare_config)
else:
raise NotImplementedError(f"{gp_name} is not implemented")
def get_gp_calc(flare_config):
"""
Return a FLARE_Calculator with gp from GaussianProcess
"""
from flare.bffs.gp import GaussianProcess
from flare.bffs.mgp import MappedGaussianProcess
from flare.bffs.gp.calculator import FLARE_Calculator
from flare.utils.parameter_helper import ParameterHelper
gp_file = flare_config.get("file", None)
# Load GP from file
if gp_file is not None:
with open(gp_file, "r") as f:
gp_dct = json.loads(f.readline())
if gp_dct.get("class", None) == "FLARE_Calculator":
flare_calc = FLARE_Calculator.from_file(gp_file)
else:
gp, _ = GaussianProcess.from_file(gp_file)
flare_calc = FLARE_Calculator(gp)
return flare_calc
# Create gaussian process model
kernels = flare_config.get("kernels")
hyps = flare_config.get("hyps", "random")
opt_algorithm = flare_config.get("opt_algorithm", "BFGS")
max_iterations = flare_config.get("max_iterations", 20)
bounds = flare_config.get("bounds", None)
gp_parameters = flare_config.get("gp_parameters")
n_cpus = flare_config.get("n_cpus", 1)
use_mapping = flare_config.get("use_mapping", False)
# set up GP hyperparameters
pm = ParameterHelper(
kernels=kernels,
random=True,
parameters=gp_parameters,
)
hm = pm.as_dict()
if hyps == "random":
hyps = hm["hyps"]
gp_model = GaussianProcess(
kernels=kernels,
component="mc",
hyps=hyps,
cutoffs=hm["cutoffs"],
hyps_mask=None,
hyp_labels=hm["hyp_labels"],
opt_algorithm=opt_algorithm,
maxiter=max_iterations,
parallel=n_cpus > 1,
per_atom_par=flare_config.get("per_atom_par", True),
n_cpus=n_cpus,
n_sample=flare_config.get("n_sample", 100),
output=None,
name=flare_config.get("name", "default_gp"),
energy_noise=flare_config.get("energy_noise", 0.01),
)
# create mapped gaussian process
if use_mapping:
grid_params = flare_config.get("grid_params")
var_map = flare_config.get("var_map", "pca")
unique_species = flare_config.get("unique_species")
coded_unique_species = symbols2numbers(unique_species)
mgp_model = MappedGaussianProcess(
grid_params=grid_params,
unique_species=coded_unique_species,
n_cpus=n_cpus,
var_map=var_map,
)
else:
mgp_model = None
flare_calc = FLARE_Calculator(
gp_model=gp_model,
mgp_model=mgp_model,
par=n_cpus > 1,
use_mapping=use_mapping,
)
return flare_calc, kernels
def get_sgp_calc(flare_config):
"""
Return a SGP_Calculator with sgp from SparseGP
"""
from flare.bffs.sgp._C_flare import NormalizedDotProduct, SquaredExponential
from flare.bffs.sgp._C_flare import B2, B3, TwoBody, ThreeBody, FourBody
from flare.bffs.sgp import SGP_Wrapper
from flare.bffs.sgp.calculator import SGP_Calculator
sgp_file = flare_config.get("file", None)
# Load sparse GP from file
if sgp_file is not None:
with open(sgp_file, "r") as f:
gp_dct = json.loads(f.readline())
if gp_dct.get("class", None) == "SGP_Calculator":
flare_calc, kernels = SGP_Calculator.from_file(sgp_file)
else:
sgp, kernels = SGP_Wrapper.from_file(sgp_file)
flare_calc = SGP_Calculator(sgp)
return flare_calc, kernels
kernels = flare_config.get("kernels")
opt_algorithm = flare_config.get("opt_algorithm", "BFGS")
max_iterations = flare_config.get("max_iterations", 20)
bounds = flare_config.get("bounds", None)
use_mapping = flare_config.get("use_mapping", False)
# Define kernels.
kernels = []
for k in flare_config["kernels"]:
if k["name"] == "NormalizedDotProduct":
kernels.append(NormalizedDotProduct(k["sigma"], k["power"]))
elif k["name"] == "SquaredExponential":
kernels.append(SquaredExponential(k["sigma"], k["ls"]))
else:
raise NotImplementedError(f"{k['name']} kernel is not implemented")
# Define descriptor calculators.
n_species = len(flare_config["species"])
cutoff = flare_config["cutoff"]
descriptors = []
for d in flare_config["descriptors"]:
if d["name"] == "B2":
radial_hyps = [0.0, cutoff]
cutoff_hyps = []
descriptor_settings = [n_species, d["nmax"], d["lmax"]]
if "cutoff_matrix" in d: # multiple cutoffs
desc_calc = B2(
d["radial_basis"],
d["cutoff_function"],
radial_hyps,
cutoff_hyps,
descriptor_settings,
d["cutoff_matrix"],
)
else:
desc_calc = B2(
d["radial_basis"],
d["cutoff_function"],
radial_hyps,
cutoff_hyps,
descriptor_settings,
)
elif d["name"] == "B3":
radial_hyps = [0.0, cutoff]
cutoff_hyps = []
descriptor_settings = [n_species, d["nmax"], d["lmax"]]
desc_calc = B3(
d["radial_basis"],
d["cutoff_function"],
radial_hyps,
cutoff_hyps,
descriptor_settings,
)
elif d["name"] == "TwoBody":
desc_calc = TwoBody(cutoff, n_species, d["cutoff_function"], cutoff_hyps)
elif d["name"] == "ThreeBody":
desc_calc = ThreeBody(cutoff, n_species, d["cutoff_function"], cutoff_hyps)
elif d["name"] == "FourBody":
desc_calc = FourBody(cutoff, n_species, d["cutoff_function"], cutoff_hyps)
else:
raise NotImplementedError(f"{d['name']} descriptor is not supported")
descriptors.append(desc_calc)
# Define remaining parameters for the SGP wrapper.
species_map = {flare_config.get("species")[i]: i for i in range(n_species)}
sae_dct = flare_config.get("single_atom_energies", None)
if sae_dct is not None:
assert n_species == len(
sae_dct
), "'single_atom_energies' should be the same length as 'species'"
single_atom_energies = {i: sae_dct[i] for i in range(n_species)}
sgp = SGP_Wrapper(
kernels=kernels,
descriptor_calculators=descriptors,
cutoff=cutoff,
sigma_e=flare_config.get("energy_noise"),
sigma_f=flare_config.get("forces_noise"),
sigma_s=flare_config.get("stress_noise"),
species_map=species_map,
variance_type=flare_config.get("variance_type", "local"),
single_atom_energies=single_atom_energies,
energy_training=flare_config.get("energy_training", True),
force_training=flare_config.get("force_training", True),
stress_training=flare_config.get("stress_training", True),
max_iterations=max_iterations,
opt_method=opt_algorithm,
bounds=bounds,
)
flare_calc = SGP_Calculator(sgp, use_mapping)
return flare_calc, kernels
def fresh_start_otf(config):
"""
Set up MD and OTF training engine
"""
super_cell = get_super_cell(config["supercell"])
dft_calc = get_dft_calc(config["dft_calc"])
flare_calc, kernels = get_flare_calc(config["flare_calc"])
otf_config = config.get("otf")
# intialize velocity
# The "file" option uses the velocities read from the supercell file.
initial_velocity = otf_config.get("initial_velocity", "file")
if initial_velocity != "file":
# Otherwise, the initial_velocity is a number specifying the temperature
# to initialize the velocity with Boltzmann distribution
init_temp = float(initial_velocity)
MaxwellBoltzmannDistribution(super_cell, init_temp * units.kB)
Stationary(super_cell)
ZeroRotation(super_cell)
otf = OTF(
super_cell,
flare_calc=flare_calc,
dft_calc=dft_calc,
**otf_config,
)
otf.run()
def restart_otf(config):
"""
Set up MD and OTF training engine. Restart with checkpoint files
"""
otf_config = config.get("otf")
checkpoint = otf_config.get("checkpoint")
otf = OTF.from_checkpoint(checkpoint)
# allow modification of some parameters
for attr in [
"number_of_steps",
"rescale_steps",
"rescale_temps",
"write_model",
"freeze_hyps",
"store_dft_output",
]:
if attr in otf_config:
setattr(otf, attr, otf_config.get(attr))
otf.run()
def main():
with open(sys.argv[1], "r") as f:
config = yaml.safe_load(f)
mode = config.get("otf").get("mode", "fresh")
if mode == "fresh":
fresh_start_otf(config)
elif mode == "restart":
restart_otf(config)