abfml 2025.2.20__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.
- abfml/__init__.py +0 -0
- abfml/calculate.py +66 -0
- abfml/data/__init__.py +4 -0
- abfml/data/dataset.py +71 -0
- abfml/data/read_data.py +205 -0
- abfml/entrypoints/__init__.py +0 -0
- abfml/entrypoints/check.py +122 -0
- abfml/entrypoints/main_command.py +16 -0
- abfml/entrypoints/main_parser.py +194 -0
- abfml/entrypoints/train.py +304 -0
- abfml/entrypoints/valid.py +174 -0
- abfml/logger/__init__.py +3 -0
- abfml/logger/loggers.py +105 -0
- abfml/loss/__init__.py +2 -0
- abfml/loss/losser.py +17 -0
- abfml/main.py +19 -0
- abfml/model/__init__.py +0 -0
- abfml/model/field_model_bp.py +579 -0
- abfml/model/field_model_dp.py +382 -0
- abfml/model/field_model_nep.py +249 -0
- abfml/model/math_fun.py +170 -0
- abfml/model/method.py +144 -0
- abfml/model/network.py +192 -0
- abfml/model/normal.py +138 -0
- abfml/optimizer/__init__.py +0 -0
- abfml/optimizer/learn_rate.py +35 -0
- abfml/optimizer/optim_init.py +16 -0
- abfml/param/__init__.py +0 -0
- abfml/param/param.py +699 -0
- abfml/train/__init__.py +0 -0
- abfml/train/trainer.py +160 -0
- abfml/utils/plot_loss.py +21 -0
- abfml-2025.2.20.dist-info/LICENSE +674 -0
- abfml-2025.2.20.dist-info/METADATA +812 -0
- abfml-2025.2.20.dist-info/RECORD +38 -0
- abfml-2025.2.20.dist-info/WHEEL +5 -0
- abfml-2025.2.20.dist-info/entry_points.txt +2 -0
- abfml-2025.2.20.dist-info/top_level.txt +1 -0
abfml/__init__.py
ADDED
|
File without changes
|
abfml/calculate.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import ase
|
|
2
|
+
import torch
|
|
3
|
+
import numpy as np
|
|
4
|
+
from typing import List
|
|
5
|
+
from ase.calculators.calculator import Calculator, all_changes, PropertyNotImplementedError
|
|
6
|
+
from abfml.data.read_data import ReadData
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ABFML(Calculator):
|
|
10
|
+
implemented_properties = ['energy', 'energies', 'forces', 'stress', 'stresses']
|
|
11
|
+
|
|
12
|
+
def __init__(self, model: str = None, dtype: str = 'float64', model_class = None, **kwargs) -> None:
|
|
13
|
+
Calculator.__init__(self, **kwargs)
|
|
14
|
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
15
|
+
if model is not None:
|
|
16
|
+
try:
|
|
17
|
+
self.model = torch.jit.load(model)
|
|
18
|
+
except RuntimeError:
|
|
19
|
+
try:
|
|
20
|
+
self.model = torch.load(model)
|
|
21
|
+
except Exception as e:
|
|
22
|
+
raise RuntimeError(f"Failed to load model using both jit and torch.load: {e}")
|
|
23
|
+
elif model_class is not None:
|
|
24
|
+
self.model = model_class
|
|
25
|
+
else:
|
|
26
|
+
raise RuntimeError('Please give the model file')
|
|
27
|
+
|
|
28
|
+
if dtype == "float32":
|
|
29
|
+
self.dtype = torch.float32
|
|
30
|
+
else:
|
|
31
|
+
self.dtype = torch.float64
|
|
32
|
+
|
|
33
|
+
self.model.to(self.dtype).to(device=self.device)
|
|
34
|
+
self.model.eval()
|
|
35
|
+
|
|
36
|
+
def calculate(self,
|
|
37
|
+
atoms: ase.Atoms = None,
|
|
38
|
+
properties: List[str] = None,
|
|
39
|
+
system_changes: List[str] = all_changes) -> None:
|
|
40
|
+
|
|
41
|
+
type_map = self.model.type_map
|
|
42
|
+
cutoff = self.model.cutoff
|
|
43
|
+
neighbor = self.model.neighbor
|
|
44
|
+
information_tulp = ReadData.calculate_neighbor(atom=atoms, cutoff=cutoff, neighbor=neighbor, type_map=type_map)
|
|
45
|
+
element_type, Zi, Nij, Zij, Rij = information_tulp
|
|
46
|
+
predict_tulp = self.model(torch.tensor(element_type),
|
|
47
|
+
torch.tensor(Zi).to(device=self.device),
|
|
48
|
+
torch.tensor(Nij).to(device=self.device),
|
|
49
|
+
torch.tensor(Zij).to(device=self.device),
|
|
50
|
+
torch.tensor(Rij).to(self.dtype).to(device=self.device), 0)
|
|
51
|
+
self.results["energy"] = predict_tulp[0].detach().numpy().item()
|
|
52
|
+
self.results["energies"] = predict_tulp[1].detach().numpy().reshape(-1)
|
|
53
|
+
self.results["forces"] = predict_tulp[2].detach().numpy().reshape(-1, 3)
|
|
54
|
+
if "stress" in properties:
|
|
55
|
+
stress = predict_tulp[3].detach().numpy().reshape(3, 3)
|
|
56
|
+
if any(atoms.get_pbc()):
|
|
57
|
+
stress = -0.5 * (stress * stress.T) / atoms.get_volume()
|
|
58
|
+
self.results["stress"] = stress
|
|
59
|
+
|
|
60
|
+
if "stresses" in properties:
|
|
61
|
+
stresses = predict_tulp[4].detach().numpy().reshape(-1, 3, 3)
|
|
62
|
+
if any(atoms.get_pbc()):
|
|
63
|
+
self.results["stresses"] = -1.0 * stresses / atoms.get_volume()
|
|
64
|
+
else:
|
|
65
|
+
raise PropertyNotImplementedError
|
|
66
|
+
|
abfml/data/__init__.py
ADDED
abfml/data/dataset.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch.utils.data import Dataset
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ABFMLDataset(Dataset):
|
|
6
|
+
def __init__(self,
|
|
7
|
+
n_frames: int,
|
|
8
|
+
n_atoms: int,
|
|
9
|
+
element_type: torch.Tensor,
|
|
10
|
+
Zi: torch.Tensor,
|
|
11
|
+
Nij: torch.Tensor,
|
|
12
|
+
Zij: torch.Tensor,
|
|
13
|
+
Rij: torch.Tensor,
|
|
14
|
+
energy: torch.Tensor = None,
|
|
15
|
+
atomic_energy: torch.Tensor = None,
|
|
16
|
+
force: torch.Tensor = None,
|
|
17
|
+
virial: torch.Tensor = None,
|
|
18
|
+
):
|
|
19
|
+
super(ABFMLDataset, self).__init__()
|
|
20
|
+
self.n_frames = n_frames
|
|
21
|
+
self.n_atoms = n_atoms
|
|
22
|
+
|
|
23
|
+
physics_name = ["energy", "atomic_energy", "force", "virial"]
|
|
24
|
+
physics_var = [energy, atomic_energy, force, virial]
|
|
25
|
+
physics_shape = [(n_frames, 1), (n_frames, n_atoms, 1), (n_frames, n_atoms, 3), (n_frames, 9)]
|
|
26
|
+
for tensor_p, shape_p, name_p in zip(physics_var, physics_shape, physics_name):
|
|
27
|
+
if tensor_p is not None:
|
|
28
|
+
if not isinstance(tensor_p, torch.Tensor):
|
|
29
|
+
raise TypeError(f"If {name_p} is required, then the type of a should be torch.Tensor, "
|
|
30
|
+
f"but its type is {type(tensor_p)}")
|
|
31
|
+
if tensor_p.shape != shape_p:
|
|
32
|
+
raise ValueError(f"Expected shape of {name_p} is {shape_p},"
|
|
33
|
+
f"but the shape you get is {tensor_p.shape}")
|
|
34
|
+
self.atomic_energy = atomic_energy
|
|
35
|
+
self.energy = energy
|
|
36
|
+
self.force = force
|
|
37
|
+
self.virial = virial
|
|
38
|
+
|
|
39
|
+
neighbor_name = ["Zi", "Nij", "Zij", "Rij"]
|
|
40
|
+
neighbor_var = [Zi, Nij, Zij, Rij]
|
|
41
|
+
neighbor_shape = [(n_frames, n_atoms), (n_frames, n_atoms, Nij.shape[-1]),
|
|
42
|
+
(n_frames, n_atoms, Nij.shape[-1]), (n_frames, n_atoms, Nij.shape[-1], 4)]
|
|
43
|
+
for tensor_n, shape_n, name_n in zip(neighbor_var, neighbor_shape, neighbor_name):
|
|
44
|
+
if not isinstance(tensor_n, torch.Tensor):
|
|
45
|
+
raise TypeError(f"The type of {name_n} should to be torch.Tensor, but its {type(tensor_n)}")
|
|
46
|
+
if tensor_n.shape != shape_n:
|
|
47
|
+
raise ValueError(f"Expected shape of {name_n} is {shape_n}, but the shape you get is {tensor_n.shape}")
|
|
48
|
+
self.element_type = element_type
|
|
49
|
+
self.Zi = Zi
|
|
50
|
+
self.Nij = Nij
|
|
51
|
+
self.Zij = Zij
|
|
52
|
+
self.Rij = Rij
|
|
53
|
+
|
|
54
|
+
def __len__(self):
|
|
55
|
+
return self.n_frames
|
|
56
|
+
|
|
57
|
+
def __getitem__(self, index):
|
|
58
|
+
mlff_dict = {
|
|
59
|
+
'n_atoms': self.n_atoms,
|
|
60
|
+
'element_type': self.element_type,
|
|
61
|
+
'Zi': self.Zi[index],
|
|
62
|
+
'Nij': self.Nij[index],
|
|
63
|
+
'Zij': self.Zij[index],
|
|
64
|
+
'Rij': self.Rij[index],
|
|
65
|
+
}
|
|
66
|
+
optional_name = ["energy", "atomic_energy", "force", "virial"]
|
|
67
|
+
optional_val = [self.energy, self.atomic_energy, self.force, self.virial]
|
|
68
|
+
for tensor, name in zip(optional_val, optional_name):
|
|
69
|
+
if tensor is not None:
|
|
70
|
+
mlff_dict[name] = tensor[index]
|
|
71
|
+
return mlff_dict
|
abfml/data/read_data.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import numpy as np
|
|
3
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
4
|
+
from functools import partial
|
|
5
|
+
from ase import Atoms, io
|
|
6
|
+
from ase.neighborlist import NeighborList
|
|
7
|
+
from typing import List, Optional, Union
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from abfml.data.dataset import ABFMLDataset
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class DataClass:
|
|
14
|
+
def __init__(self, filename: str, file_format: Optional[str]):
|
|
15
|
+
self.filename: str = filename
|
|
16
|
+
if file_format == "pwmat-config":
|
|
17
|
+
image_list = []
|
|
18
|
+
elif file_format == "pwmat-movement":
|
|
19
|
+
image_list = []
|
|
20
|
+
else:
|
|
21
|
+
image_list = io.read(filename, format=file_format, index=':')
|
|
22
|
+
self.image_list: List[Atoms] = image_list
|
|
23
|
+
self.include_element: set = set()
|
|
24
|
+
include_atoms_number = []
|
|
25
|
+
for atom_information in image_list:
|
|
26
|
+
self.include_element = self.include_element.union(set(atom_information.get_chemical_symbols()))
|
|
27
|
+
include_atoms_number.append(len(atom_information))
|
|
28
|
+
self.include_atoms_number: set = set(include_atoms_number)
|
|
29
|
+
self.n_frames: int = len(self.image_list)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ReadData:
|
|
33
|
+
def __init__(self, filename: Union[str, List[str]], cutoff: float, neighbor: List[int],
|
|
34
|
+
type_map: Optional[List[int]], file_format: Optional[str]):
|
|
35
|
+
self.cutoff = cutoff
|
|
36
|
+
self.neighbor = neighbor
|
|
37
|
+
self.filename = filename
|
|
38
|
+
self.type_map = type_map
|
|
39
|
+
self.image_list: list[Atoms] = []
|
|
40
|
+
if isinstance(filename, str):
|
|
41
|
+
filename = [filename]
|
|
42
|
+
self.data_information: List[dict] = []
|
|
43
|
+
for file in filename:
|
|
44
|
+
data_information = DataClass(file, file_format)
|
|
45
|
+
self.data_information.append({'file_name': data_information.filename,
|
|
46
|
+
'n_frames': data_information.n_frames,
|
|
47
|
+
'include_element': data_information.include_element,
|
|
48
|
+
'include_atoms_number': data_information.include_atoms_number})
|
|
49
|
+
self.image_list = self.image_list + data_information.image_list
|
|
50
|
+
self.n_frames: int = len(self.image_list)
|
|
51
|
+
self.unique_image = {}
|
|
52
|
+
for i, image in enumerate(self.image_list):
|
|
53
|
+
image_tuple = tuple(image.get_atomic_numbers())
|
|
54
|
+
if image_tuple in self.unique_image:
|
|
55
|
+
self.unique_image[image_tuple].append(i)
|
|
56
|
+
else:
|
|
57
|
+
self.unique_image[image_tuple] = [i]
|
|
58
|
+
|
|
59
|
+
def get_mlffdata(self):
|
|
60
|
+
dataset = []
|
|
61
|
+
for same_image_index in self.unique_image.values():
|
|
62
|
+
n_frames: int = len(same_image_index)
|
|
63
|
+
n_atoms: int = len(self.image_list[same_image_index[0]])
|
|
64
|
+
n_elements: int = len(set(self.image_list[same_image_index[0]].get_atomic_numbers()))
|
|
65
|
+
if isinstance(self.neighbor, int):
|
|
66
|
+
max_neighbor: int = self.neighbor
|
|
67
|
+
elif isinstance(self.neighbor, list):
|
|
68
|
+
if len(self.neighbor) == len(self.type_map):
|
|
69
|
+
max_neighbor = sum(self.neighbor[self.type_map.index(atomic_numbers)]
|
|
70
|
+
for atomic_numbers in set(self.image_list[same_image_index[0]].get_atomic_numbers()))
|
|
71
|
+
|
|
72
|
+
else:
|
|
73
|
+
raise Exception('neighbor and type_map must have the same length')
|
|
74
|
+
else:
|
|
75
|
+
raise ValueError(f'Expected a member of List[int] and int but instead found type {type(self.neighbor)}')
|
|
76
|
+
|
|
77
|
+
Zi = torch.empty(n_frames, n_atoms, dtype=torch.int)
|
|
78
|
+
Nij = torch.empty(n_frames, n_atoms, max_neighbor, dtype=torch.int)
|
|
79
|
+
Zij = torch.empty(n_frames, n_atoms, max_neighbor, dtype=torch.int)
|
|
80
|
+
Rij = torch.zeros(n_frames, n_atoms, max_neighbor, 4, dtype=torch.float64)
|
|
81
|
+
element_type = torch.zeros(n_frames, n_elements, dtype=torch.int)
|
|
82
|
+
energy = torch.zeros(n_frames, 1, dtype=torch.float64)
|
|
83
|
+
atomic_energy = torch.zeros(n_frames, n_atoms, 1, dtype=torch.float64)
|
|
84
|
+
force = torch.zeros(n_frames, n_atoms, 3, dtype=torch.float64)
|
|
85
|
+
virial = torch.zeros(n_frames, 9, dtype=torch.float64)
|
|
86
|
+
for i, image_index in enumerate(same_image_index):
|
|
87
|
+
atom_ase = self.image_list[image_index]
|
|
88
|
+
neighbor_information = ReadData.calculate_neighbor(atom=atom_ase,
|
|
89
|
+
cutoff=self.cutoff,
|
|
90
|
+
neighbor=self.neighbor,
|
|
91
|
+
type_map=self.type_map)
|
|
92
|
+
element_type = torch.tensor(neighbor_information[0])
|
|
93
|
+
Zi[i] = torch.tensor(neighbor_information[1])
|
|
94
|
+
Nij[i] = torch.tensor(neighbor_information[2])
|
|
95
|
+
Zij[i] = torch.tensor(neighbor_information[3])
|
|
96
|
+
Rij[i] = torch.tensor(neighbor_information[4])
|
|
97
|
+
try:
|
|
98
|
+
energy[i] = torch.tensor(atom_ase.get_potential_energy())
|
|
99
|
+
except (RuntimeError, AttributeError):
|
|
100
|
+
energy = None
|
|
101
|
+
try:
|
|
102
|
+
atomic_energy[i] = torch.tensor(atom_ase.atomic_energy)
|
|
103
|
+
except (RuntimeError, AttributeError):
|
|
104
|
+
atomic_energy = None
|
|
105
|
+
try:
|
|
106
|
+
force[i] = torch.tensor(atom_ase.get_forces(apply_constraint=False))
|
|
107
|
+
except (RuntimeError, AttributeError):
|
|
108
|
+
force = None
|
|
109
|
+
try:
|
|
110
|
+
# ASE calculated in units of eV/A^3, virial: eV
|
|
111
|
+
virial[i] = torch.tensor(-1.0 * atom_ase.get_stress(voigt=False).reshape(9) * atom_ase.get_volume())
|
|
112
|
+
except (RuntimeError, AttributeError):
|
|
113
|
+
virial = None
|
|
114
|
+
dataset.append(ABFMLDataset(n_frames=n_frames,
|
|
115
|
+
n_atoms=n_atoms,
|
|
116
|
+
element_type=element_type,
|
|
117
|
+
Zi=Zi,
|
|
118
|
+
Nij=Nij,
|
|
119
|
+
Zij=Zij,
|
|
120
|
+
Rij=Rij,
|
|
121
|
+
energy=energy,
|
|
122
|
+
atomic_energy=atomic_energy,
|
|
123
|
+
force=force,
|
|
124
|
+
virial=virial))
|
|
125
|
+
return dataset
|
|
126
|
+
|
|
127
|
+
@staticmethod
|
|
128
|
+
def calculate_neighbor(atom: Atoms, cutoff: float, neighbor: Union[List[int], int], type_map: Optional[List[int]]):
|
|
129
|
+
nl = NeighborList([cutoff / 2] * len(atom), skin=0, self_interaction=False, bothways=True, sorted=False)
|
|
130
|
+
nl.update(atom)
|
|
131
|
+
atoms_num = len(atom)
|
|
132
|
+
Zi = atom.numbers
|
|
133
|
+
element_type = np.sort(np.unique(Zi))
|
|
134
|
+
if isinstance(neighbor, int) or type_map is None:
|
|
135
|
+
max_neighbor: int = neighbor
|
|
136
|
+
Rij = np.zeros(shape=(1, atoms_num, max_neighbor, 4), dtype=np.float64)
|
|
137
|
+
Nij = np.full(shape=(1, atoms_num, max_neighbor), fill_value=-1, dtype=np.int32)
|
|
138
|
+
Zij = np.full(shape=(1, atoms_num, max_neighbor), fill_value=-1, dtype=np.int32)
|
|
139
|
+
for i in range(atoms_num):
|
|
140
|
+
indices_neighbor, offsets = nl.get_neighbors(i)
|
|
141
|
+
j_xyz = atom.positions[indices_neighbor] + np.dot(offsets, atom.get_cell())
|
|
142
|
+
ij_xyz = j_xyz - atom.positions[i]
|
|
143
|
+
rij = np.sqrt(np.sum(ij_xyz ** 2, axis=1))
|
|
144
|
+
if indices_neighbor.shape[0] <= max_neighbor:
|
|
145
|
+
end_index = indices_neighbor.shape[0]
|
|
146
|
+
else:
|
|
147
|
+
indices_rij = np.argsort(rij, axis=-1)
|
|
148
|
+
for j in range(3):
|
|
149
|
+
ij_xyz[..., j] = np.take_along_axis(ij_xyz[..., j], indices=indices_rij, axis=-1)
|
|
150
|
+
rij = np.take_along_axis(rij, indices=indices_rij, axis=-1)
|
|
151
|
+
indices_neighbor = np.take_along_axis(indices_neighbor, indices=indices_rij, axis=-1)
|
|
152
|
+
end_index = max_neighbor
|
|
153
|
+
Rij[:, i, :end_index, 1:] = ij_xyz[:end_index, :]
|
|
154
|
+
Rij[:, i, :end_index, 0] = rij[:end_index]
|
|
155
|
+
Nij[:, i, :end_index] = indices_neighbor[:end_index]
|
|
156
|
+
mask = (Nij != -1)
|
|
157
|
+
Zij[mask] = Zi[Nij[mask]]
|
|
158
|
+
|
|
159
|
+
elif len(type_map) == len(neighbor):
|
|
160
|
+
atom_map = type_map
|
|
161
|
+
neighbor_map = neighbor
|
|
162
|
+
Zi = atom.numbers
|
|
163
|
+
max_neighbor = sum(neighbor_map[atom_map.index(atomic_numbers)] for atomic_numbers in element_type)
|
|
164
|
+
width_map = [0]
|
|
165
|
+
Zi_unique = list(element_type)
|
|
166
|
+
for ii in Zi_unique:
|
|
167
|
+
width_map.append(neighbor_map[atom_map.index(ii)]+width_map[-1])
|
|
168
|
+
Rij = np.zeros(shape=(1, atoms_num, max_neighbor, 4), dtype=np.float64)
|
|
169
|
+
Nij = np.full(shape=(1, atoms_num, max_neighbor), fill_value=-1, dtype=np.int32)
|
|
170
|
+
Zij = np.full(shape=(1, atoms_num, max_neighbor), fill_value=-1, dtype=np.int32)
|
|
171
|
+
for i in range(atoms_num):
|
|
172
|
+
indices_neighbor, offsets = nl.get_neighbors(i)
|
|
173
|
+
j_xyz = atom.positions[indices_neighbor] + np.dot(offsets, atom.get_cell())
|
|
174
|
+
ij_xyz = j_xyz - atom.positions[i]
|
|
175
|
+
rij = np.sqrt(np.sum(ij_xyz ** 2, axis=1))
|
|
176
|
+
Zij_i = Zi[indices_neighbor]
|
|
177
|
+
|
|
178
|
+
for atomic_numbers in Zi_unique:
|
|
179
|
+
mask = (Zij_i == atomic_numbers)
|
|
180
|
+
width = Zij_i[mask].shape[0]
|
|
181
|
+
start_index = width_map[Zi_unique.index(atomic_numbers)]
|
|
182
|
+
width_i = neighbor_map[Zi_unique.index(atomic_numbers)]
|
|
183
|
+
if width <= width_i:
|
|
184
|
+
end_index = start_index + width
|
|
185
|
+
else:
|
|
186
|
+
indices_rij = np.argsort(rij[mask], axis=-1)
|
|
187
|
+
for j in range(3):
|
|
188
|
+
ij_xyz[..., j][mask] = np.take_along_axis(ij_xyz[..., j][mask],
|
|
189
|
+
indices=indices_rij,
|
|
190
|
+
axis=-1)
|
|
191
|
+
rij[mask] = np.take_along_axis(rij[mask], indices=indices_rij, axis=-1)
|
|
192
|
+
indices_neighbor[mask] = np.take_along_axis(indices_neighbor[mask],
|
|
193
|
+
indices=indices_rij,
|
|
194
|
+
axis=-1)
|
|
195
|
+
end_index = start_index + width_i
|
|
196
|
+
Zij[:, i, start_index:end_index] = Zij_i[mask][:width_i]
|
|
197
|
+
Nij[:, i, start_index:end_index] = indices_neighbor[mask][:width_i]
|
|
198
|
+
Rij[:, i, start_index:end_index, 0] = rij[mask][:width_i]
|
|
199
|
+
Rij[:, i, start_index:end_index, 1:] = ij_xyz[mask][:width_i, :]
|
|
200
|
+
else:
|
|
201
|
+
raise Exception('neighbor[0] and neighbor[1] should have the same length '
|
|
202
|
+
'or neighbor[1] have only one element. Maybe you should read the manual!')
|
|
203
|
+
Zi = Zi[np.newaxis,...]
|
|
204
|
+
return element_type, Zi, Nij, Zij, Rij
|
|
205
|
+
|
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import sys
|
|
3
|
+
import importlib.util
|
|
4
|
+
import numpy as np
|
|
5
|
+
from ase import Atoms
|
|
6
|
+
from ase.data import chemical_symbols
|
|
7
|
+
from ase.build import bulk
|
|
8
|
+
from typing import Optional
|
|
9
|
+
from torch.utils.data import ConcatDataset
|
|
10
|
+
from abfml.param.param import Param
|
|
11
|
+
from abfml.logger.loggers import Logger, log_logo
|
|
12
|
+
from abfml.data.read_data import ReadData
|
|
13
|
+
from abfml.calculate import ABFML
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def check_mlff(
|
|
17
|
+
*,
|
|
18
|
+
model_name: Optional[str] = None,
|
|
19
|
+
input: Optional[str] = None,
|
|
20
|
+
dtype: str = "float32",
|
|
21
|
+
**kwargs):
|
|
22
|
+
logger = Logger("check.log").logger
|
|
23
|
+
log_logo(logger=logger)
|
|
24
|
+
|
|
25
|
+
if input is not None:
|
|
26
|
+
with open(input, 'r') as file:
|
|
27
|
+
input_json = json.load(file)
|
|
28
|
+
param_class = Param(input_dict=input_json)
|
|
29
|
+
field_model_name = param_class.user_defined.field_name
|
|
30
|
+
model_path = param_class.user_defined.model_path
|
|
31
|
+
spec = importlib.util.spec_from_file_location(field_model_name, model_path)
|
|
32
|
+
module = importlib.util.module_from_spec(spec)
|
|
33
|
+
sys.modules[field_model_name] = module
|
|
34
|
+
spec.loader.exec_module(module)
|
|
35
|
+
|
|
36
|
+
field_model = getattr(module, field_model_name)
|
|
37
|
+
if param_class.user_defined.normal_name is not None:
|
|
38
|
+
logger.info(f"| Information: Since you defined Normal, we'll read the train_file as the dataset for Normal")
|
|
39
|
+
train_dataclass = ReadData(filename=param_class.DataSet.train_file,
|
|
40
|
+
cutoff=param_class.GlobalSet.cutoff,
|
|
41
|
+
neighbor=param_class.GlobalSet.neighbor,
|
|
42
|
+
type_map=param_class.GlobalSet.type_map,
|
|
43
|
+
file_format=param_class.DataSet.file_format)
|
|
44
|
+
train_data = ConcatDataset(train_dataclass.get_mlffdata())
|
|
45
|
+
normal_class = getattr(module, param_class.user_defined.normal_name)
|
|
46
|
+
normal_model = normal_class(normal_data=train_data, param_class=param_class, normal_rate="auto")
|
|
47
|
+
normal_data = normal_model.normal_data
|
|
48
|
+
else:
|
|
49
|
+
normal_data = None
|
|
50
|
+
model = field_model(type_map=param_class.GlobalSet.type_map,
|
|
51
|
+
cutoff=param_class.GlobalSet.cutoff,
|
|
52
|
+
neighbor=param_class.GlobalSet.neighbor,
|
|
53
|
+
config=param_class.user_defined.config,
|
|
54
|
+
normal=normal_data)
|
|
55
|
+
calculator = ABFML(model_class=model,dtype=dtype)
|
|
56
|
+
|
|
57
|
+
elif model_name is not None:
|
|
58
|
+
calculator = ABFML(model=model_name,dtype=dtype)
|
|
59
|
+
|
|
60
|
+
else:
|
|
61
|
+
raise RuntimeError("model_name and input are None?")
|
|
62
|
+
|
|
63
|
+
atomic_number = calculator.model.type_map[0]
|
|
64
|
+
element_symbol = chemical_symbols[atomic_number]
|
|
65
|
+
|
|
66
|
+
logger.info(f"+----------------------------------- rotate symmetry check ------------------------------------+")
|
|
67
|
+
position = np.array([[15.0, 15.0, 15.0],[13.0, 15.0, 15.0],[15.0, 15.0, 13.0]])
|
|
68
|
+
cluster = Atoms(element_symbol+'3', position)
|
|
69
|
+
cluster.calc = calculator
|
|
70
|
+
energy = [cluster.get_potential_energy()]
|
|
71
|
+
force = [cluster.get_forces()]
|
|
72
|
+
cluster.rotate(45, 'z', center='COP')
|
|
73
|
+
energy.append(cluster.get_potential_energy())
|
|
74
|
+
force.append(cluster.get_forces())
|
|
75
|
+
dF = (np.linalg.norm(force[1], axis=1) - np.linalg.norm(force[0], axis=1)).sum().item()
|
|
76
|
+
logger.info(f" cluster-> energy: {energy[0]:>.6f}, force-sum: {force[0].sum().item():>.6f}")
|
|
77
|
+
logger.info(f"rotate cluster-> energy: {energy[1]:>.6f}, force-sum: {force[1].sum().item():>.6f}")
|
|
78
|
+
logger.info(f" difference-> energy: {energy[1]-energy[0]:>.6f}, force: {dF:>.6f}")
|
|
79
|
+
logger.info(f"Information: The magnitude of the energy/and the combined force remains the same after the")
|
|
80
|
+
logger.info(f" structure is rotated. Isolated system combined force should be 0.")
|
|
81
|
+
logger.warning(f"Part “difference” should be 0. But if it is less than 1e-5, ")
|
|
82
|
+
logger.warning(f"it may be a precision issue, otherwise check the model rotation conservation")
|
|
83
|
+
logger.info(f"+----------------------------------------------------------------------------------------------+")
|
|
84
|
+
|
|
85
|
+
logger.info(f"+-------------------------------------- periodicity check -------------------------------------+")
|
|
86
|
+
cluster = bulk('Cu', 'fcc', a=3.62, cubic=True)
|
|
87
|
+
cluster.calc = calculator
|
|
88
|
+
energy = [cluster.get_potential_energy()]
|
|
89
|
+
force = [cluster.get_forces()]
|
|
90
|
+
cluster = cluster * (3, 3, 3)
|
|
91
|
+
cluster.calc = calculator
|
|
92
|
+
energy.append(cluster.get_potential_energy())
|
|
93
|
+
force.append(cluster.get_forces())
|
|
94
|
+
dE = energy[1] - energy[0] * 27
|
|
95
|
+
dF = np.abs(force[1][:4] - force[0]).sum().item()
|
|
96
|
+
logger.info(f" bulk-> energy: {energy[0]:>.6f}, force: {force[0].sum().item():>.6f}")
|
|
97
|
+
logger.info(f" 3*3*3 bulk-> energy: {energy[1]:>.6f}, force: {force[1].sum().item():>.6f}")
|
|
98
|
+
logger.info(f" difference-> E[1]-E[0]*27: {dE:>.6f}, dF: {dF:>.6f}")
|
|
99
|
+
logger.info(f"Information: The energy of the expanded cell of a periodic structure is proportional to the number")
|
|
100
|
+
logger.info(f" of times it is expanded and the force on the corresponding atoms is unchanged.")
|
|
101
|
+
logger.warning(f"If the difference is less than 1e-5 it may be an accuracy problem,")
|
|
102
|
+
logger.warning(f"otherwise the energy and force relationship should be checked.")
|
|
103
|
+
logger.info(f"+----------------------------------------------------------------------------------------------+")
|
|
104
|
+
|
|
105
|
+
logger.info(f"+------------------------------------- energy-force check -------------------------------------+")
|
|
106
|
+
cluster = Atoms(element_symbol + '3', position)
|
|
107
|
+
cluster.calc = calculator
|
|
108
|
+
energy = [cluster.get_potential_energy()]
|
|
109
|
+
force = [cluster.get_forces()[0]]
|
|
110
|
+
cluster.positions[0] = [15.0, 15.0, 15.002]
|
|
111
|
+
energy.append(cluster.get_potential_energy())
|
|
112
|
+
force.append(cluster.get_forces()[0])
|
|
113
|
+
Fdx = -1 * (force[0][2] + force[1][2]) / 2 * 0.002
|
|
114
|
+
dE = energy[1] - energy[0]
|
|
115
|
+
logger.info(f" cluster-> energy: {energy[0]:>.6f}, force: {force[0][2].item():>.6f}")
|
|
116
|
+
logger.info(f" perturbation-> energy: {energy[1]:>.6f}, force: {force[1][2].item():>.6f}")
|
|
117
|
+
logger.info(f" -> dE: {dE:>.6f}, F * dx: {Fdx:>.6f}, difference: {dE - Fdx:>.6f}")
|
|
118
|
+
logger.info(f"Information: Force and energy should satisfy F=-dE/dx, dE=F*dx for perturbation.")
|
|
119
|
+
logger.warning(f"if the difference is less than 1e-5 it may be an accuracy problem,")
|
|
120
|
+
logger.warning(f"otherwise the energy and force relationship should be checked.")
|
|
121
|
+
logger.info(f"+----------------------------------------------------------------------------------------------+")
|
|
122
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
from typing import List, Optional, Union
|
|
3
|
+
from abfml.entrypoints.train import train_mlff
|
|
4
|
+
from abfml.entrypoints.valid import valid_mlff
|
|
5
|
+
from abfml.entrypoints.check import check_mlff
|
|
6
|
+
|
|
7
|
+
def main_command(args: Optional[Union[List[str], argparse.Namespace]] = None):
|
|
8
|
+
dict_args = vars(args)
|
|
9
|
+
if args.command == "train":
|
|
10
|
+
train_mlff(**dict_args)
|
|
11
|
+
elif args.command == "valid":
|
|
12
|
+
valid_mlff(**dict_args)
|
|
13
|
+
elif args.command == "check":
|
|
14
|
+
check_mlff(**dict_args)
|
|
15
|
+
else:
|
|
16
|
+
raise Exception(f"undefined command")
|