-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathmace_utils.py
258 lines (226 loc) · 7.92 KB
/
mace_utils.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
###########################################################################################
# Utilities
# Authors: Ilyes Batatia, Gregor Simm and David Kovacs
# This program is distributed under the MIT License (see MIT.md)
###########################################################################################
import logging
from typing import List, Optional, Tuple
import numpy as np
import torch
import torch.nn
import torch.utils.data
from scipy.constants import c, e
def _broadcast(src: torch.Tensor, other: torch.Tensor, dim: int):
if dim < 0:
dim = other.dim() + dim
if src.dim() == 1:
for _ in range(0, dim):
src = src.unsqueeze(0)
for _ in range(src.dim(), other.dim()):
src = src.unsqueeze(-1)
src = src.expand_as(other)
return src
@torch.jit.script
def scatter_sum(
src: torch.Tensor,
index: torch.Tensor,
dim: int = -1,
out: Optional[torch.Tensor] = None,
dim_size: Optional[int] = None,
reduce: str = "sum",
) -> torch.Tensor:
assert reduce == "sum" # for now, TODO
index = _broadcast(index, src, dim)
if out is None:
size = list(src.size())
if dim_size is not None:
size[dim] = dim_size
elif index.numel() == 0:
size[dim] = 0
else:
size[dim] = int(index.max()) + 1
out = torch.zeros(size, dtype=src.dtype, device=src.device)
return out.scatter_add_(dim, index, src)
else:
return out.scatter_add_(dim, index, src)
def to_numpy(t: torch.Tensor) -> np.ndarray:
return t.cpu().detach().numpy()
def compute_forces(
energy: torch.Tensor, positions: torch.Tensor, training: bool = True
) -> torch.Tensor:
grad_outputs: List[Optional[torch.Tensor]] = [torch.ones_like(energy)]
gradient = torch.autograd.grad(
outputs=[energy], # [n_graphs, ]
inputs=[positions], # [n_nodes, 3]
grad_outputs=grad_outputs,
retain_graph=training, # Make sure the graph is not destroyed during training
create_graph=training, # Create graph for second derivative
allow_unused=True, # For complete dissociation turn to true
)[
0
] # [n_nodes, 3]
if gradient is None:
return torch.zeros_like(positions)
return -1 * gradient
def compute_forces_virials(
energy: torch.Tensor,
positions: torch.Tensor,
displacement: torch.Tensor,
cell: torch.Tensor,
training: bool = True,
compute_stress: bool = False,
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[torch.Tensor]]:
grad_outputs: List[Optional[torch.Tensor]] = [torch.ones_like(energy)]
forces, virials = torch.autograd.grad(
outputs=[energy], # [n_graphs, ]
inputs=[positions, displacement], # [n_nodes, 3]
grad_outputs=grad_outputs,
retain_graph=training, # Make sure the graph is not destroyed during training
create_graph=training, # Create graph for second derivative
allow_unused=True,
)
stress = torch.zeros_like(displacement)
if compute_stress and virials is not None:
cell = cell.view(-1, 3, 3)
volume = torch.einsum(
"zi,zi->z",
cell[:, 0, :],
torch.cross(cell[:, 1, :], cell[:, 2, :], dim=1),
).unsqueeze(-1)
stress = virials / volume.view(-1, 1, 1)
if forces is None:
forces = torch.zeros_like(positions)
if virials is None:
virials = torch.zeros((1, 3, 3))
return -1 * forces, -1 * virials, stress
def get_symmetric_displacement(
positions: torch.Tensor,
unit_shifts: torch.Tensor,
cell: Optional[torch.Tensor],
edge_index: torch.Tensor,
num_graphs: int,
batch: torch.Tensor,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if cell is None:
cell = torch.zeros(
num_graphs * 3,
3,
dtype=positions.dtype,
device=positions.device,
)
sender = edge_index[0]
displacement = torch.zeros(
(num_graphs, 3, 3),
dtype=positions.dtype,
device=positions.device,
)
displacement.requires_grad_(True)
symmetric_displacement = 0.5 * (
displacement + displacement.transpose(-1, -2)
) # From https://github.com/mir-group/nequip
positions = positions + torch.einsum(
"be,bec->bc", positions, symmetric_displacement[batch]
)
cell = cell.view(-1, 3, 3)
cell = cell + torch.matmul(cell, symmetric_displacement)
shifts = torch.einsum(
"be,bec->bc",
unit_shifts,
cell[batch[sender]],
)
return positions, shifts, displacement
def get_outputs(
energy: torch.Tensor,
positions: torch.Tensor,
displacement: Optional[torch.Tensor],
cell: torch.Tensor,
training: bool = False,
compute_force: bool = True,
compute_virials: bool = True,
compute_stress: bool = True,
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]:
if (compute_virials or compute_stress) and displacement is not None:
# forces come for free
forces, virials, stress = compute_forces_virials(
energy=energy,
positions=positions,
displacement=displacement,
cell=cell,
compute_stress=compute_stress,
training=training,
)
elif compute_force:
forces, virials, stress = (
compute_forces(energy=energy, positions=positions, training=training),
None,
None,
)
else:
forces, virials, stress = (None, None, None)
return forces, virials, stress
def get_edge_vectors_and_lengths(
positions: torch.Tensor, # [n_nodes, 3]
edge_index: torch.Tensor, # [2, n_edges]
shifts: torch.Tensor, # [n_edges, 3]
normalize: bool = False,
eps: float = 1e-9,
) -> Tuple[torch.Tensor, torch.Tensor]:
sender = edge_index[0]
receiver = edge_index[1]
vectors = positions[receiver] - positions[sender] + shifts # [n_edges, 3]
lengths = torch.linalg.norm(vectors, dim=-1, keepdim=True) # [n_edges, 1]
if normalize:
vectors_normed = vectors / (lengths + eps)
return vectors_normed, lengths
return vectors, lengths
def _check_non_zero(std):
if std == 0.0:
logging.warning(
"Standard deviation of the scaling is zero, Changing to no scaling"
)
std = 1.0
return std
def extract_invariant(x: torch.Tensor, num_layers: int, num_features: int, l_max: int):
out = []
for i in range(num_layers - 1):
out.append(
x[
:,
i
* (l_max + 1) ** 2
* num_features : (i * (l_max + 1) ** 2 + 1)
* num_features,
]
)
out.append(x[:, -num_features:])
return torch.cat(out, dim=-1)
def compute_avg_num_neighbors(data_loader: torch.utils.data.DataLoader) -> float:
num_neighbors = []
for batch in data_loader:
_, receivers = batch.edge_index
_, counts = torch.unique(receivers, return_counts=True)
num_neighbors.append(counts)
avg_num_neighbors = torch.mean(
torch.cat(num_neighbors, dim=0).type(torch.get_default_dtype())
)
return to_numpy(avg_num_neighbors).item()
def compute_rms_dipoles(
data_loader: torch.utils.data.DataLoader,
) -> Tuple[float, float]:
dipoles_list = []
for batch in data_loader:
dipoles_list.append(batch.dipole) # {[n_graphs,3], }
dipoles = torch.cat(dipoles_list, dim=0) # {[total_n_graphs,3], }
rms = to_numpy(torch.sqrt(torch.mean(torch.square(dipoles)))).item()
rms = _check_non_zero(rms)
return rms
def compute_fixed_charge_dipole(
charges: torch.Tensor,
positions: torch.Tensor,
batch: torch.Tensor,
num_graphs: int,
) -> torch.Tensor:
mu = positions * charges.unsqueeze(-1) / (1e-11 / c / e) # [N_atoms,3]
return scatter_sum(
src=mu, index=batch.unsqueeze(-1), dim=0, dim_size=num_graphs
) # [N_graphs,3]