-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbatch.py
327 lines (263 loc) · 12.7 KB
/
batch.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
import torch
from torch_geometric.data import Data
class BatchMasking(Data):
"""A plain old python object modeling a batch of graphs as one big
(disconnected) graph. With :class:`torch_geometric.data.Data` being the
base class, all its methods can also be used here.
In addition, single graphs can be reconstructed via the assignment vector
:obj:`batch`, which maps each node to its respective graph identifier."""
def __init__(self, batch=None, **kwargs):
super(BatchMasking, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
"""Constructs a batch object from a python list holding
:class:`torch_geometric.data.Data` objects.
The assignment vector :obj:`batch` is created on the fly."""
keys = [set(data.keys) for data in data_list]
keys = list(set.union(*keys)-set('num_nodes'))
assert 'batch' not in keys
batch = BatchMasking()
for key in keys:
batch[key] = []
batch.batch = []
cumsum_node = 0
cumsum_edge = 0
for i, data in enumerate(data_list):
num_nodes = data.num_nodes
batch.batch.append(torch.full((num_nodes,), i, dtype=torch.long))
for key in data.keys:
item = data[key]
if key in ['edge_index', 'masked_atom_indices']:
item = item + cumsum_node
elif key == 'connected_edge_indices':
item = item + cumsum_edge
batch[key].append(item)
cumsum_node += num_nodes
cumsum_edge += data.edge_index.shape[1]
for key in keys:
try:
batch[key] = torch.cat(batch[key], dim=data_list[0].__cat_dim__(key, batch[key][0]))
except:
pass
batch.batch = torch.cat(batch.batch, dim=-1)
return batch.contiguous()
def cumsum(self, key, item):
"""If :obj:`True`, the attribute :obj:`key` with content :obj:`item`
should be added up cumulatively before concatenated together.
.. note::
This method is for internal use only, and should only be overridden
if the batch concatenation process is corrupted for a specific data
attribute."""
return key in ['edge_index', 'face',
'masked_atom_indices',
'connected_edge_indices']
@property
def num_graphs(self):
"""Returns the number of graphs in the batch."""
return self.batch[-1].item() + 1
class BatchAE(Data):
"""A plain old python object modeling a batch of graphs as one big
(disconnected) graph. With :class:`torch_geometric.data.Data` being the
base class, all its methods can also be used here.
In addition, single graphs can be reconstructed via the assignment vector
:obj:`batch`, which maps each node to its respective graph identifier. """
def __init__(self, batch=None, **kwargs):
super(BatchAE, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
"""Constructs a batch object from a python list holding
:class:`torch_geometric.data.Data` objects.
The assignment vector :obj:`batch` is created on the fly."""
keys = [set(data.keys) for data in data_list]
keys = list(set.union(*keys))
assert 'batch' not in keys
batch = BatchAE()
for key in keys:
batch[key] = []
batch.batch = []
cumsum_node = 0
for i, data in enumerate(data_list):
num_nodes = data.num_nodes
batch.batch.append(torch.full((num_nodes,), i, dtype=torch.long))
for key in data.keys:
item = data[key]
if key in ['edge_index', 'negative_edge_index']:
item = item + cumsum_node
batch[key].append(item)
cumsum_node += num_nodes
for key in keys:
batch[key] = torch.cat(
batch[key], dim=batch.__cat_dim__(key))
batch.batch = torch.cat(batch.batch, dim=-1)
return batch.contiguous()
@property
def num_graphs(self):
'''Returns the number of graphs in the batch.'''
return self.batch[-1].item() + 1
def __cat_dim__(self, key):
return -1 if key in ['edge_index', 'negative_edge_index'] else 0
class BatchSubstructContext(Data):
"""A plain old python object modeling a batch of graphs as one big
(disconnected) graph. With :class:`torch_geometric.data.Data` being the
base class, all its methods can also be used here.
In addition, single graphs can be reconstructed via the assignment vector
:obj:`batch`, which maps each node to its respective graph identifier. """
''' Specialized batching for substructure context pair! '''
def __init__(self, batch=None, **kwargs):
super(BatchSubstructContext, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
"""Constructs a batch object from a python list holding
:class:`torch_geometric.data.Data` objects.
The assignment vector :obj:`batch` is created on the fly."""
batch = BatchSubstructContext()
keys = [
'center_substruct_idx', 'edge_attr_substruct',
'edge_index_substruct', 'x_substruct', 'overlap_context_substruct_idx',
'edge_attr_context', 'edge_index_context', 'x_context'
]
for key in keys:
batch[key] = []
batch.batch = []
batch.batch_overlapped_context = []
batch.overlapped_context_size = []
cumsum_main = 0
cumsum_substruct = 0
cumsum_context = 0
i = 0
for data in data_list:
if hasattr(data, 'x_context'):
num_nodes = data.num_nodes
num_nodes_substruct = len(data.x_substruct)
num_nodes_context = len(data.x_context)
batch.batch.append(torch.full((num_nodes,), i, dtype=torch.long))
batch.batch_overlapped_context.append(
torch.full((len(data.overlap_context_substruct_idx),), i, dtype=torch.long))
batch.overlapped_context_size.append(len(data.overlap_context_substruct_idx))
# batching for the substructure graph
for key in ['center_substruct_idx', 'edge_attr_substruct',
'edge_index_substruct', 'x_substruct']:
item = data[key]
item = item + cumsum_substruct if batch.cumsum(key, item) else item
batch[key].append(item)
# batching for the context graph
for key in ['overlap_context_substruct_idx', 'edge_attr_context',
'edge_index_context', 'x_context']:
item = data[key]
item = item + cumsum_context if batch.cumsum(key, item) else item
batch[key].append(item)
cumsum_main += num_nodes
cumsum_substruct += num_nodes_substruct
cumsum_context += num_nodes_context
i += 1
for key in keys:
batch[key] = torch.cat(batch[key], dim=batch.__cat_dim__(key))
batch.batch = torch.cat(batch.batch, dim=-1)
batch.batch_overlapped_context = torch.cat(batch.batch_overlapped_context, dim=-1)
batch.overlapped_context_size = torch.LongTensor(batch.overlapped_context_size)
return batch.contiguous()
def __cat_dim__(self, key):
return -1 if key in ['edge_index', 'edge_index_substruct', 'edge_index_context'] else 0
def cumsum(self, key, item):
"""If :obj:`True`, the attribute :obj:`key` with content :obj:`item`
should be added up cumulatively before concatenated together.
.. note::
This method is for internal use only, and should only be overridden
if the batch concatenation process is corrupted for a specific data
attribute. """
return key in ['edge_index', 'edge_index_substruct',
'edge_index_context',
'overlap_context_substruct_idx',
'center_substruct_idx']
@property
def num_graphs(self):
"""Returns the number of graphs in the batch."""
return self.batch[-1].item() + 1
class BatchSubstructContext3D(Data):
"""A plain old python object modeling a batch of graphs as one big
(disconnected) graph. With :class:`torch_geometric.data.Data` being the
base class, all its methods can also be used here.
In addition, single graphs can be reconstructed via the assignment vector
:obj:`batch`, which maps each node to its respective graph identifier. """
''' Specialized batching for substructure context pair! '''
def __init__(self, batch=None, **kwargs):
super(BatchSubstructContext, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
"""Constructs a batch object from a python list holding
:class:`torch_geometric.data.Data` objects.
The assignment vector :obj:`batch` is created on the fly."""
batch = BatchSubstructContext()
keys = [
'center_substruct_idx', 'edge_attr_substruct',
'edge_index_substruct', 'x_substruct', 'overlap_context_substruct_idx',
'edge_attr_context', 'edge_index_context', 'x_context',
'positions', 'x', 'edge_attr', 'edge_index'
]
for key in keys:
batch[key] = []
batch.batch = []
batch.batch_overlapped_context = []
batch.overlapped_context_size = []
cumsum_main = 0
cumsum_substruct = 0
cumsum_context = 0
i = 0
for data in data_list:
if hasattr(data, 'x_context'):
num_nodes = data.num_nodes
num_nodes_substruct = len(data.x_substruct)
num_nodes_context = len(data.x_context)
batch.batch.append(torch.full((num_nodes,), i, dtype=torch.long))
batch.batch_overlapped_context.append(
torch.full((len(data.overlap_context_substruct_idx),), i, dtype=torch.long))
batch.overlapped_context_size.append(len(data.overlap_context_substruct_idx))
# batching for the main graph
for key in ['x', 'edge_attr', 'edge_index', 'positions']:
item = data[key]
if key in ['edge_index']:
item = item + cumsum_main
batch[key].append(item)
# batching for the substructure graph
for key in ['center_substruct_idx', 'edge_attr_substruct',
'edge_index_substruct', 'x_substruct']:
item = data[key]
item = item + cumsum_substruct if batch.cumsum(key, item) else item
batch[key].append(item)
# batching for the context graph
for key in ['overlap_context_substruct_idx', 'edge_attr_context',
'edge_index_context', 'x_context']:
item = data[key]
item = item + cumsum_context if batch.cumsum(key, item) else item
batch[key].append(item)
cumsum_main += num_nodes
cumsum_substruct += num_nodes_substruct
cumsum_context += num_nodes_context
i += 1
for key in keys:
batch[key] = torch.cat(batch[key], dim=batch.__cat_dim__(key))
batch.batch = torch.cat(batch.batch, dim=-1)
batch.batch_overlapped_context = torch.cat(batch.batch_overlapped_context, dim=-1)
batch.overlapped_context_size = torch.LongTensor(batch.overlapped_context_size)
return batch.contiguous()
def __cat_dim__(self, key):
return -1 if key in ['edge_index', 'edge_index_substruct', 'edge_index_context'] else 0
def cumsum(self, key, item):
"""If :obj:`True`, the attribute :obj:`key` with content :obj:`item`
should be added up cumulatively before concatenated together.
.. note::
This method is for internal use only, and should only be overridden
if the batch concatenation process is corrupted for a specific data
attribute. """
return key in ['edge_index', 'edge_index_substruct',
'edge_index_context',
'overlap_context_substruct_idx',
'center_substruct_idx']
@property
def num_graphs(self):
"""Returns the number of graphs in the batch."""
return self.batch[-1].item() + 1