-
Notifications
You must be signed in to change notification settings - Fork 11
/
GCN.py
459 lines (354 loc) · 15.2 KB
/
GCN.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import os
import torch
import torch_geometric
import gzip
import pickle
import numpy as np
import time
class GNNPolicy(torch.nn.Module):
def __init__(self):
super().__init__()
emb_size = 64
cons_nfeats = 4
edge_nfeats = 1
var_nfeats = 6
# CONSTRAINT EMBEDDING
self.cons_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(cons_nfeats),
torch.nn.Linear(cons_nfeats, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
)
# EDGE EMBEDDING
self.edge_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(edge_nfeats),
)
# VARIABLE EMBEDDING
self.var_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(var_nfeats),
torch.nn.Linear(var_nfeats, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
)
self.conv_v_to_c = BipartiteGraphConvolution()
self.conv_c_to_v = BipartiteGraphConvolution()
self.conv_v_to_c2 = BipartiteGraphConvolution()
self.conv_c_to_v2 = BipartiteGraphConvolution()
self.output_module = torch.nn.Sequential(
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, 1, bias=False),
)
def forward(
self, constraint_features, edge_indices, edge_features, variable_features
):
reversed_edge_indices = torch.stack([edge_indices[1], edge_indices[0]], dim=0)
# First step: linear embedding layers to a common dimension (64)
constraint_features = self.cons_embedding(constraint_features)
edge_features = self.edge_embedding(edge_features)
variable_features = self.var_embedding(variable_features)
# Two half convolutions
constraint_features = self.conv_v_to_c(
variable_features, reversed_edge_indices, edge_features, constraint_features
)
variable_features = self.conv_c_to_v(
constraint_features, edge_indices, edge_features, variable_features
)
constraint_features = self.conv_v_to_c2(
variable_features, reversed_edge_indices, edge_features, constraint_features
)
variable_features = self.conv_c_to_v2(
constraint_features, edge_indices, edge_features, variable_features
)
# A final MLP on the variable features
output = self.output_module(variable_features).squeeze(-1)
return output
class BipartiteGraphConvolution(torch_geometric.nn.MessagePassing):
"""
The bipartite graph convolution is already provided by pytorch geometric and we merely need
to provide the exact form of the messages being passed.
"""
def __init__(self):
super().__init__("add")
emb_size = 64
self.feature_module_left = torch.nn.Sequential(
torch.nn.Linear(emb_size, emb_size)
)
self.feature_module_edge = torch.nn.Sequential(
torch.nn.Linear(1, emb_size, bias=False)
)
self.feature_module_right = torch.nn.Sequential(
torch.nn.Linear(emb_size, emb_size, bias=False)
)
self.feature_module_final = torch.nn.Sequential(
torch.nn.LayerNorm(emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
)
self.post_conv_module = torch.nn.Sequential(torch.nn.LayerNorm(emb_size))
# output_layers
self.output_module = torch.nn.Sequential(
torch.nn.Linear(2 * emb_size, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
)
def forward(self, left_features, edge_indices, edge_features, right_features):
"""
This method sends the messages, computed in the message method.
"""
output = self.propagate(
edge_indices,
size=(left_features.shape[0], right_features.shape[0]),
node_features=(left_features, right_features),
edge_features=edge_features,
)
b=torch.cat([self.post_conv_module(output), right_features], dim=-1)
a=self.output_module(
torch.cat([self.post_conv_module(output), right_features], dim=-1)
)
return self.output_module(
torch.cat([self.post_conv_module(output), right_features], dim=-1)
)
def message(self, node_features_i, node_features_j, edge_features):
#node_features_i,the node to be aggregated
#node_features_j,the neighbors of the node i
# print("node_features_i:",node_features_i.shape)
# print("node_features_j",node_features_j.shape)
# print("edge_features:",edge_features.shape)
output = self.feature_module_final(
self.feature_module_left(node_features_i)
+ self.feature_module_edge(edge_features)
+ self.feature_module_right(node_features_j)
)
return output
class GraphDataset(torch_geometric.data.Dataset):
"""
This class encodes a collection of graphs, as well as a method to load such graphs from the disk.
It can be used in turn by the data loaders provided by pytorch geometric.
"""
def __init__(self, sample_files):
super().__init__(root=None, transform=None, pre_transform=None)
self.sample_files = sample_files
def len(self):
return len(self.sample_files)
def process_sample(self,filepath):
BGFilepath, solFilePath = filepath
with open(BGFilepath, "rb") as f:
bgData = pickle.load(f)
with open(solFilePath, "rb") as f:
solData = pickle.load(f)
BG = bgData
varNames = solData['var_names']
sols = solData['sols'][:50]#[0:300]
objs = solData['objs'][:50]#[0:300]
sols=np.round(sols,0)
return BG,sols,objs,varNames
def get(self, index):
"""
This method loads a node bipartite graph observation as saved on the disk during data collection.
"""
# nbp, sols, objs, varInds, varNames = self.process_sample(self.sample_files[index])
BG, sols, objs, varNames = self.process_sample(self.sample_files[index])
A, v_map, v_nodes, c_nodes, b_vars=BG
constraint_features = c_nodes
edge_indices = A._indices()
variable_features = v_nodes
edge_features =A._values().unsqueeze(1)
edge_features=torch.ones(edge_features.shape)
constraint_features[np.isnan(constraint_features)] = 1
graph = BipartiteNodeData(
torch.FloatTensor(constraint_features),
torch.LongTensor(edge_indices),
torch.FloatTensor(edge_features),
torch.FloatTensor(variable_features),
)
# We must tell pytorch geometric how many nodes there are, for indexing purposes
graph.num_nodes = constraint_features.shape[0] + variable_features.shape[0]
graph.solutions = torch.FloatTensor(sols).reshape(-1)
graph.objVals = torch.FloatTensor(objs)
graph.nsols = sols.shape[0]
graph.ntvars = variable_features.shape[0]
graph.varNames = varNames
varname_dict={}
varname_map=[]
i=0
for iter in varNames:
varname_dict[iter]=i
i+=1
for iter in v_map:
varname_map.append(varname_dict[iter])
varname_map=torch.tensor(varname_map)
graph.varInds = [[varname_map],[b_vars]]
return graph
class BipartiteNodeData(torch_geometric.data.Data):
"""
This class encode a node bipartite graph observation as returned by the `ecole.observation.NodeBipartite`
observation function in a format understood by the pytorch geometric data handlers.
"""
def __init__(
self,
constraint_features,
edge_indices,
edge_features,
variable_features,
):
super().__init__()
self.constraint_features = constraint_features
self.edge_index = edge_indices
self.edge_attr = edge_features
self.variable_features = variable_features
def __inc__(self, key, value, store, *args, **kwargs):
"""
We overload the pytorch geometric method that tells how to increment indices when concatenating graphs
for those entries (edge index, candidates) for which this is not obvious.
"""
if key == "edge_index":
return torch.tensor(
[[self.constraint_features.size(0)], [self.variable_features.size(0)]]
)
elif key == "candidates":
return self.variable_features.size(0)
else:
return super().__inc__(key, value, *args, **kwargs)
class GNNPolicy_position(torch.nn.Module):
def __init__(self):
super().__init__()
emb_size = 64
cons_nfeats = 4
edge_nfeats = 1
var_nfeats = 18
# CONSTRAINT EMBEDDING
self.cons_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(cons_nfeats),
torch.nn.Linear(cons_nfeats, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
)
# EDGE EMBEDDING
self.edge_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(edge_nfeats),
)
# VARIABLE EMBEDDING
self.var_embedding = torch.nn.Sequential(
torch.nn.LayerNorm(var_nfeats),
torch.nn.Linear(var_nfeats, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
)
self.conv_v_to_c = BipartiteGraphConvolution()
self.conv_c_to_v = BipartiteGraphConvolution()
self.conv_v_to_c2 = BipartiteGraphConvolution()
self.conv_c_to_v2 = BipartiteGraphConvolution()
self.output_module = torch.nn.Sequential(
torch.nn.Linear(emb_size, emb_size),
torch.nn.ReLU(),
torch.nn.Linear(emb_size, 1, bias=False),
)
def forward(
self, constraint_features, edge_indices, edge_features, variable_features
):
reversed_edge_indices = torch.stack([edge_indices[1], edge_indices[0]], dim=0)
# First step: linear embedding layers to a common dimension (64)
constraint_features = self.cons_embedding(constraint_features)
edge_features = self.edge_embedding(edge_features)
variable_features = self.var_embedding(variable_features)
# Two half convolutions
constraint_features = self.conv_v_to_c(
variable_features, reversed_edge_indices, edge_features, constraint_features
)
variable_features = self.conv_c_to_v(
constraint_features, edge_indices, edge_features, variable_features
)
constraint_features = self.conv_v_to_c2(
variable_features, reversed_edge_indices, edge_features, constraint_features
)
variable_features = self.conv_c_to_v2(
constraint_features, edge_indices, edge_features, variable_features
)
# A final MLP on the variable features
output = self.output_module(variable_features).squeeze(-1)
return output
class GraphDataset_position(torch_geometric.data.Dataset):
"""
This class encodes a collection of graphs, as well as a method to load such graphs from the disk.
It can be used in turn by the data loaders provided by pytorch geometric.
"""
def __init__(self, sample_files):
super().__init__(root=None, transform=None, pre_transform=None)
self.sample_files = sample_files
def len(self):
return len(self.sample_files)
def process_sample(self,filepath):
BGFilepath, solFilePath = filepath
with open(BGFilepath, "rb") as f:
bgData = pickle.load(f)
with open(solFilePath, "rb") as f:
solData = pickle.load(f)
BG = bgData
varNames = solData['var_names']
sols = solData['sols'][:50]#[0:300]
objs = solData['objs'][:50]#[0:300]
sols=np.round(sols,0)
return BG,sols,objs,varNames
def get(self, index):
"""
This method loads a node bipartite graph observation as saved on the disk during data collection.
"""
# nbp, sols, objs, varInds, varNames = self.process_sample(self.sample_files[index])
BG, sols, objs, varNames = self.process_sample(self.sample_files[index])
A, v_map, v_nodes, c_nodes, b_vars=BG
constraint_features = c_nodes
edge_indices = A._indices()
variable_features = v_nodes
edge_features =A._values().unsqueeze(1)
edge_features=torch.ones(edge_features.shape)
lens = variable_features.shape[0]
feature_widh = 12 # max length 4095
position = torch.arange(0, lens, 1)
position_feature = torch.zeros(lens, feature_widh)
for i in range(len(position_feature)):
binary = str(bin(position[i]).replace('0b', ''))
for j in range(len(binary)):
position_feature[i][j] = int(binary[-(j + 1)])
v = torch.concat([variable_features, position_feature], dim=1)
variable_features = v
graph = BipartiteNodeData(
torch.FloatTensor(constraint_features),
torch.LongTensor(edge_indices),
torch.FloatTensor(edge_features),
torch.FloatTensor(variable_features),
)
# We must tell pytorch geometric how many nodes there are, for indexing purposes
graph.num_nodes = constraint_features.shape[0] + variable_features.shape[0]
graph.solutions = torch.FloatTensor(sols).reshape(-1)
graph.objVals = torch.FloatTensor(objs)
graph.nsols = sols.shape[0]
graph.ntvars = variable_features.shape[0]
graph.varNames = varNames
varname_dict={}
varname_map=[]
i=0
for iter in varNames:
varname_dict[iter]=i
i+=1
for iter in v_map:
varname_map.append(varname_dict[iter])
varname_map=torch.tensor(varname_map)
graph.varInds = [[varname_map],[b_vars]]
return graph
def postion_get(variable_features):
lens = variable_features.shape[0]
feature_widh = 12 # max length 4095
position = torch.arange(0, lens, 1)
position_feature = torch.zeros(lens, feature_widh)
for i in range(len(position_feature)):
binary = str(bin(position[i]).replace('0b', ''))
for j in range(len(binary)):
position_feature[i][j] = int(binary[-(j + 1)])
variable_features = torch.FloatTensor(variable_features.cpu())
v = torch.concat([variable_features, position_feature], dim=1).to(DEVICE)
return v