-
Notifications
You must be signed in to change notification settings - Fork 2
/
graph.py
203 lines (177 loc) · 8.44 KB
/
graph.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
import numpy as np
import torch
from dgl.convert import graph as dgl_graph
from dgl.transform import to_bidirected
from fe_utils.sph_fea import dist_emb, angle_emb, torsion_emb, xyz_to_dat
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class GraphConstructor(object):
def __init__(self,
connect_method='CWC',
cutoff=5,
k=None,
strict=False,
gaussian_step=None,
num_spherical=None,
num_radial=None,
envelope_exponent=5):
self.connect_method = connect_method
self.cutoff = cutoff
self.k = k
self.strict = strict
self.gaussian_step = gaussian_step
if self.gaussian_step:
self.ge = GaussianExpansion(0, cutoff, step=gaussian_step)
self.use_sf = False
if num_spherical and num_radial:
self.sf = SphericalFeatures(num_spherical, num_radial, cutoff, envelope_exponent)
self.use_sf = True
def connect_graph(self, R):
if self.connect_method == 'CWC':
graph = self.connect_within_cutoff(R, self.cutoff, self.k, self.strict)
elif self.connect_method == 'PBC':
graph = self.periodic_boundary_condition(R, self.cutoff, self.k, self.strict)
elif self.connect_method == 'CGC':
graph = self.cgcnn_connect(R, self.cutoff, self.k)
else:
raise ValueError('Invalid graph connection method.')
return graph
def feature_assignment(self, graph, node_fea=None, edge_fea=None):
if node_fea:
for key, fea in node_fea.items():
graph.ndata[key] = fea.to(device)
if edge_fea:
for key, fea in edge_fea.items():
graph.edata[key] = fea.to(device)
if self.use_sf:
pos = graph.ndata['coords']
edge_index = graph.edges()
num_nodes = graph.num_nodes()
dist, angle, torsion, i, j, idx_kj, idx_ji = xyz_to_dat(pos, edge_index, num_nodes, use_torsion=True)
rbf, sbf, tbf = self.sf(dist, angle, torsion, idx_kj)
idx = torch.concat((idx_ji.reshape(1, -1), idx_kj.reshape(1, -1)))
sbf_sparse, tbf_sparse = map(lambda sf: torch.sparse_coo_tensor(idx, sf, (graph.num_edges(), graph.num_edges(), sf.size()[1])), (sbf, tbf))
graph.edata['rbf'], graph.edata['sbf'], graph.edata['tbf'] = rbf, sbf_sparse, tbf_sparse
return graph
def cgcnn_connect(self, cell, cutoff, k):
all_nbrs = cell.get_all_neighbors(cutoff, include_index=True)
all_nbrs = [sorted(nbrs, key=lambda x: x[1]) for nbrs in all_nbrs]
nbr_fea_idx, nbr_fea = [], []
for nbr in all_nbrs:
if len(nbr) < k:
print('not find enough neighbors to build graph. '
'If it happens frequently, consider increase '
'radius.')
nbr_fea_idx.append(list(map(lambda x: x[2], nbr)) +
[0] * (k - len(nbr)))
nbr_fea.append(list(map(lambda x: x[1], nbr)) +
[cutoff + 1.] * (k - len(nbr)))
else:
nbr_fea_idx.append(list(map(lambda x: x[2], nbr[:k])))
nbr_fea.append(list(map(lambda x: x[1], nbr[:k])))
nbr_fea_idx, nbr_fea = np.array(nbr_fea_idx), np.array(nbr_fea)
u = torch.tensor([[i] * len(nbr_fea_idx[i]) for i in range(len(nbr_fea_idx))], dtype=torch.long).flatten()
v = nbr_fea_idx.flatten()
graph = dgl_graph((u, v))
# graph = to_bidirected(graph)
graph = graph.to(device)
graph.ndata['nbr_fea_idx'] = torch.tensor(nbr_fea_idx, dtype=torch.long, device=device)
graph.ndata['image'] = torch.arange(len(cell), device=device)
graph.ndata['coords'] = torch.tensor(cell.cart_coords, dtype=torch.float64, device=device)
graph.ndata['dist'] = torch.tensor(nbr_fea, dtype=torch.float32, device=device)
if self.gaussian_step:
gaussian_dist = self.ge.expand(graph.ndata['dist'])
graph.ndata['gaussian_dist'] = gaussian_dist
return graph
def periodic_boundary_condition(self, cell, cutoff, k=None, strict=None):
cart_coords = []
image = []
index_dict = {}
for i in range(len(cell)):
cart_coords.append(cell[i].coords)
image.append(i)
index_dict[str(cell[i].species) + str(cell[i].coords)] = i
if cutoff == np.inf:
raise ValueError('Cutoff cannot be inf')
all_nbr = cell.get_all_neighbors(cutoff)
u, v = [], []
for i in range(len(all_nbr)):
nbrs = self.choose_k_nearest_PBC(all_nbr[i], k, strict) if k else all_nbr[i]
v += [i] * len(nbrs)
for nbr in nbrs:
if str(nbr._species) + str(nbr.coords) in index_dict:
u.append(index_dict[str(nbr._species) + str(nbr.coords)])
else:
cart_coords.append(nbr.coords)
image.append(nbr.index)
u.append(len(index_dict))
index_dict[str(nbr._species) + str(nbr.coords)] = u[-1]
graph = dgl_graph((u, v))
graph = to_bidirected(graph)
graph = graph.to(device)
graph.ndata['coords'] = torch.tensor(np.array(cart_coords), dtype=torch.float32, device=device)
graph.ndata['image'] = torch.tensor(image, dtype=torch.int64, device=device)
return graph
def choose_k_nearest_PBC(self, nbrs, k, strict):
if len(nbrs) > k:
if strict:
nbrs = sorted(nbrs, key=lambda x: x.nn_distance)[:k]
else:
dist = torch.tensor([nbr.nn_distance for nbr in nbrs], dtype=torch.float32)
threshold = dist[dist.argsort()[k - 1]]
nbrs = [nbrs[i] for i in torch.where(dist <= threshold)[0].tolist()]
return nbrs
def connect_within_cutoff(self, coords, cutoff, k=None, strict=None):
coords = torch.tensor(coords, dtype=torch.float32)
dist = torch.linalg.norm(coords[:, None, :] - coords[None, :, :], axis=-1)
adj = (dist <= cutoff).long() - torch.eye(len(coords))
if k is not None:
adj = self.choose_k_nearest_CWC(adj, dist, k, strict)
adj = adj + adj.T
adj = adj.bool().to_sparse()
u, v = adj.indices()
graph = dgl_graph((u, v))
graph = to_bidirected(graph)
graph = graph.to(device)
graph.ndata['coords'] = coords.to(device)
dist = dist[adj.indices()[0], adj.indices()[1]].flatten().to(device)
graph.edata['dist'] = dist
if self.gaussian_step:
gaussian_dist = self.ge.expand(dist)
graph.edata['gaussian_dist'] = gaussian_dist
return graph
def choose_k_nearest_CWC(self, adj, dist, k, strict):
for row in range(len(adj)):
if len(dist[row, :]) > k:
if strict:
adj[row, dist[row, :].argsort()[:k]] = 0
else:
threshold = dist[row, dist[row, :].argsort()[k - 1]]
adj[row, dist[row, :] > threshold] = 0
return adj
class GaussianExpansion(object):
def __init__(self,
dmin,
dmax,
step=0.2,
var=None):
assert dmin < dmax
assert dmax - dmin > step
assert dmax < np.inf
self.center = torch.arange(dmin, dmax + step, step, device=device)
self.var = step if var is None else var
def expand(self, dist):
return torch.exp(-(dist[..., None] - self.center) ** 2 / self.var ** 2)
class SphericalFeatures(torch.nn.Module):
def __init__(self, num_spherical=3, num_radial=6, cutoff=5, envelope_exponent=5):
super(SphericalFeatures, self).__init__()
self.dist_emb = dist_emb(num_radial, cutoff, envelope_exponent)
self.angle_emb = angle_emb(num_spherical, num_radial, cutoff, envelope_exponent)
self.torsion_emb = torsion_emb(num_spherical, num_radial, cutoff, envelope_exponent)
self.reset_parameters()
def reset_parameters(self):
self.dist_emb.reset_parameters()
def forward(self, dist, angle, torsion, idx_kj):
dist_emb = self.dist_emb(dist)
angle_emb = self.angle_emb(dist, angle, idx_kj)
torsion_emb = self.torsion_emb(dist, angle, torsion, idx_kj)
return dist_emb, angle_emb, torsion_emb