-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgraph_constructor.py
More file actions
172 lines (148 loc) · 7.29 KB
/
graph_constructor.py
File metadata and controls
172 lines (148 loc) · 7.29 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
# taken from https://github.com/Open-Catalyst-Project/ocp
import numpy as np
import torch
from torch_geometric.data import Data
try:
from pymatgen.io.ase import AseAtomsAdaptor
except Exception:
pass
class AtomsToGraphs:
"""A class to help convert periodic atomic structures to graphs.
The AtomsToGraphs class takes in periodic atomic structures in form of ASE atoms objects and converts
them into graph representations for use in PyTorch. The primary purpose of this class is to determine the
nearest neighbors within some radius around each individual atom, taking into account PBC, and set the
pair index and distance between atom pairs appropriately. Lastly, atomic properties and the graph information
are put into a PyTorch geometric data object for use with PyTorch.
Args:
max_neigh (int): Maximum number of neighbors to consider.
radius (int or float): Cutoff radius in Angstroms to search for neighbors.
r_energy (bool): Return the energy with other properties. Default is False, so the energy will not be returned.
r_forces (bool): Return the forces with other properties. Default is False, so the forces will not be returned.
r_distances (bool): Return the distances with other properties.
Default is False, so the distances will not be returned.
r_edges (bool): Return interatomic edges with other properties. Default is True, so edges will be returned.
r_fixed (bool): Return a binary vector with flags for fixed (1) vs free (0) atoms.
Default is True, so the fixed indices will be returned.
r_pbc (bool): Return the periodic boundary conditions with other properties.
Default is False, so the periodic boundary conditions will not be returned.
Attributes:
max_neigh (int): Maximum number of neighbors to consider.
radius (int or float): Cutoff radius in Angstoms to search for neighbors.
r_energy (bool): Return the energy with other properties. Default is False, so the energy will not be returned.
r_forces (bool): Return the forces with other properties. Default is False, so the forces will not be returned.
r_distances (bool): Return the distances with other properties.
Default is False, so the distances will not be returned.
r_edges (bool): Return interatomic edges with other properties. Default is True, so edges will be returned.
r_fixed (bool): Return a binary vector with flags for fixed (1) vs free (0) atoms.
Default is True, so the fixed indices will be returned.
r_pbc (bool): Return the periodic boundary conditions with other properties.
Default is False, so the periodic boundary conditions will not be returned.
"""
def __init__(
self,
max_neigh=200,
radius=6,
r_energy=False,
r_forces=False,
r_distances=False,
r_edges=True,
r_fixed=True,
r_pbc=False,
):
self.max_neigh = max_neigh
self.radius = radius
self.r_energy = r_energy
self.r_forces = r_forces
self.r_distances = r_distances
self.r_fixed = r_fixed
self.r_edges = r_edges
self.r_pbc = r_pbc
def _get_neighbors_pymatgen(self, atoms):
"""Preforms nearest neighbor search and returns edge index, distances,
and cell offsets"""
struct = AseAtomsAdaptor.get_structure(atoms)
_c_index, _n_index, _offsets, n_distance = struct.get_neighbor_list(
r=self.radius, numerical_tol=0, exclude_self=True
)
_nonmax_idx = []
for i in range(len(atoms)):
idx_i = (_c_index == i).nonzero()[0]
# sort neighbors by distance, remove edges larger than max_neighbors
idx_sorted = np.argsort(n_distance[idx_i])[: self.max_neigh]
_nonmax_idx.append(idx_i[idx_sorted])
_nonmax_idx = np.concatenate(_nonmax_idx)
_c_index = _c_index[_nonmax_idx]
_n_index = _n_index[_nonmax_idx]
n_distance = n_distance[_nonmax_idx]
_offsets = _offsets[_nonmax_idx]
return _c_index, _n_index, n_distance, _offsets
def _reshape_features(self, c_index, n_index, n_distance, offsets):
"""Stack center and neighbor index and reshapes distances,
takes in np.arrays and returns torch tensors"""
edge_index = torch.LongTensor(np.vstack((n_index, c_index)))
edge_distances = torch.FloatTensor(n_distance)
cell_offsets = torch.LongTensor(offsets)
# remove distances smaller than a tolerance ~ 0. The small tolerance is
# needed to correct for pymatgen's neighbor_list returning self atoms
# in a few edge cases.
nonzero = torch.where(edge_distances >= 1e-8)[0]
edge_index = edge_index[:, nonzero]
edge_distances = edge_distances[nonzero]
cell_offsets = cell_offsets[nonzero]
return edge_index, edge_distances, cell_offsets
def convert(
self,
atoms,
):
"""Convert a single atomic stucture to a graph.
Args:
atoms (ase.atoms.Atoms): An ASE atoms object.
Returns:
data (torch_geometric.data.Data): A torch geometic data object with positions, atomic_numbers, tags,
and optionally, energy, forces, distances, edges, and periodic boundary conditions.
Optional properties can included by setting r_property=True when constructing the class.
"""
# set the atomic numbers, positions, and cell
atomic_numbers = torch.Tensor(atoms.get_atomic_numbers())
positions = torch.Tensor(atoms.get_positions())
cell = torch.Tensor(atoms.get_cell()).view(1, 3, 3)
natoms = positions.shape[0]
# initialized to torch.zeros(natoms) if tags missing.
# https://wiki.fysik.dtu.dk/ase/_modules/ase/atoms.html#Atoms.get_tags
tags = torch.Tensor(atoms.get_tags())
# put the minimum data in torch geometric data object
data = Data(
cell=cell,
pos=positions,
atomic_numbers=atomic_numbers,
natoms=natoms,
tags=tags,
)
# optionally include other properties
if self.r_edges:
# run internal functions to get padded indices and distances
split_idx_dist = self._get_neighbors_pymatgen(atoms)
edge_index, edge_distances, cell_offsets = self._reshape_features(
*split_idx_dist
)
data.edge_index = edge_index
data.cell_offsets = cell_offsets
if self.r_energy:
energy = atoms.get_potential_energy(apply_constraint=False)
data.y = energy
if self.r_forces:
forces = torch.Tensor(atoms.get_forces(apply_constraint=False))
data.force = forces
if self.r_distances and self.r_edges:
data.distances = edge_distances
if self.r_fixed:
fixed_idx = torch.zeros(natoms)
if hasattr(atoms, "constraints"):
from ase.constraints import FixAtoms
for constraint in atoms.constraints:
if isinstance(constraint, FixAtoms):
fixed_idx[constraint.index] = 1
data.fixed = fixed_idx
if self.r_pbc:
data.pbc = torch.tensor(atoms.pbc)
return data