-
Notifications
You must be signed in to change notification settings - Fork 117
/
data.py
executable file
·1392 lines (1169 loc) · 52.3 KB
/
data.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import torchvision as tv
import torch.nn as nn
from torch.autograd import Variable
import matplotlib.pyplot as plt
from random import shuffle
import networkx as nx
import pickle as pkl
import scipy.sparse as sp
import logging
import random
import shutil
import os
import time
from model import *
from utils import *
# load ENZYMES and PROTEIN and DD dataset
def Graph_load_batch(min_num_nodes = 20, max_num_nodes = 1000, name = 'ENZYMES',node_attributes = True,graph_labels=True):
'''
load many graphs, e.g. enzymes
:return: a list of graphs
'''
print('Loading graph dataset: '+str(name))
G = nx.Graph()
# load data
path = 'dataset/'+name+'/'
data_adj = np.loadtxt(path+name+'_A.txt', delimiter=',').astype(int)
if node_attributes:
data_node_att = np.loadtxt(path+name+'_node_attributes.txt', delimiter=',')
data_node_label = np.loadtxt(path+name+'_node_labels.txt', delimiter=',').astype(int)
data_graph_indicator = np.loadtxt(path+name+'_graph_indicator.txt', delimiter=',').astype(int)
if graph_labels:
data_graph_labels = np.loadtxt(path+name+'_graph_labels.txt', delimiter=',').astype(int)
data_tuple = list(map(tuple, data_adj))
# print(len(data_tuple))
# print(data_tuple[0])
# add edges
G.add_edges_from(data_tuple)
# add node attributes
for i in range(data_node_label.shape[0]):
if node_attributes:
G.add_node(i+1, feature = data_node_att[i])
G.add_node(i+1, label = data_node_label[i])
G.remove_nodes_from(list(nx.isolates(G)))
# print(G.number_of_nodes())
# print(G.number_of_edges())
# split into graphs
graph_num = data_graph_indicator.max()
node_list = np.arange(data_graph_indicator.shape[0])+1
graphs = []
max_nodes = 0
for i in range(graph_num):
# find the nodes for each graph
nodes = node_list[data_graph_indicator==i+1]
G_sub = G.subgraph(nodes)
if graph_labels:
G_sub.graph['label'] = data_graph_labels[i]
# print('nodes', G_sub.number_of_nodes())
# print('edges', G_sub.number_of_edges())
# print('label', G_sub.graph)
if G_sub.number_of_nodes()>=min_num_nodes and G_sub.number_of_nodes()<=max_num_nodes:
graphs.append(G_sub)
if G_sub.number_of_nodes() > max_nodes:
max_nodes = G_sub.number_of_nodes()
# print(G_sub.number_of_nodes(), 'i', i)
# print('Graph dataset name: {}, total graph num: {}'.format(name, len(graphs)))
# logging.warning('Graphs loaded, total num: {}'.format(len(graphs)))
print('Loaded')
return graphs
def test_graph_load_DD():
graphs, max_num_nodes = Graph_load_batch(min_num_nodes=10,name='DD',node_attributes=False,graph_labels=True)
shuffle(graphs)
plt.switch_backend('agg')
plt.hist([len(graphs[i]) for i in range(len(graphs))], bins=100)
plt.savefig('figures/test.png')
plt.close()
row = 4
col = 4
draw_graph_list(graphs[0:row*col], row=row,col=col, fname='figures/test')
print('max num nodes',max_num_nodes)
def parse_index_file(filename):
index = []
for line in open(filename):
index.append(int(line.strip()))
return index
# load cora, citeseer and pubmed dataset
def Graph_load(dataset = 'cora'):
'''
Load a single graph dataset
:param dataset: dataset name
:return:
'''
names = ['x', 'tx', 'allx', 'graph']
objects = []
for i in range(len(names)):
load = pkl.load(open("dataset/ind.{}.{}".format(dataset, names[i]), 'rb'), encoding='latin1')
# print('loaded')
objects.append(load)
# print(load)
x, tx, allx, graph = tuple(objects)
test_idx_reorder = parse_index_file("dataset/ind.{}.test.index".format(dataset))
test_idx_range = np.sort(test_idx_reorder)
if dataset == 'citeseer':
# Fix citeseer dataset (there are some isolated nodes in the graph)
# Find isolated nodes, add them as zero-vecs into the right position
test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1)
tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
tx_extended[test_idx_range - min(test_idx_range), :] = tx
tx = tx_extended
features = sp.vstack((allx, tx)).tolil()
features[test_idx_reorder, :] = features[test_idx_range, :]
G = nx.from_dict_of_lists(graph)
adj = nx.adjacency_matrix(G)
return adj, features, G
######### code test ########
# adj, features,G = Graph_load()
# print(adj)
# print(G.number_of_nodes(), G.number_of_edges())
# _,_,G = Graph_load(dataset='citeseer')
# G = max(nx.connected_component_subgraphs(G), key=len)
# G = nx.convert_node_labels_to_integers(G)
#
# count = 0
# max_node = 0
# for i in range(G.number_of_nodes()):
# G_ego = nx.ego_graph(G, i, radius=3)
# # draw_graph(G_ego,prefix='test'+str(i))
# m = G_ego.number_of_nodes()
# if m>max_node:
# max_node = m
# if m>=50:
# print(i, G_ego.number_of_nodes(), G_ego.number_of_edges())
# count += 1
# print('count', count)
# print('max_node', max_node)
def bfs_seq(G, start_id):
'''
get a bfs node sequence
:param G:
:param start_id:
:return:
'''
dictionary = dict(nx.bfs_successors(G, start_id))
start = [start_id]
output = [start_id]
while len(start) > 0:
next = []
while len(start) > 0:
current = start.pop(0)
neighbor = dictionary.get(current)
if neighbor is not None:
#### a wrong example, should not permute here!
# shuffle(neighbor)
next = next + neighbor
output = output + next
start = next
return output
def encode_adj(adj, max_prev_node=10, is_full = False):
'''
:param adj: n*n, rows means time step, while columns are input dimension
:param max_degree: we want to keep row number, but truncate column numbers
:return:
'''
if is_full:
max_prev_node = adj.shape[0]-1
# pick up lower tri
adj = np.tril(adj, k=-1)
n = adj.shape[0]
adj = adj[1:n, 0:n-1]
# use max_prev_node to truncate
# note: now adj is a (n-1)*(n-1) matrix
adj_output = np.zeros((adj.shape[0], max_prev_node))
for i in range(adj.shape[0]):
input_start = max(0, i - max_prev_node + 1)
input_end = i + 1
output_start = max_prev_node + input_start - input_end
output_end = max_prev_node
adj_output[i, output_start:output_end] = adj[i, input_start:input_end]
adj_output[i,:] = adj_output[i,:][::-1] # reverse order
return adj_output
def decode_adj(adj_output):
'''
recover to adj from adj_output
note: here adj_output have shape (n-1)*m
'''
max_prev_node = adj_output.shape[1]
adj = np.zeros((adj_output.shape[0], adj_output.shape[0]))
for i in range(adj_output.shape[0]):
input_start = max(0, i - max_prev_node + 1)
input_end = i + 1
output_start = max_prev_node + max(0, i - max_prev_node + 1) - (i + 1)
output_end = max_prev_node
adj[i, input_start:input_end] = adj_output[i,::-1][output_start:output_end] # reverse order
adj_full = np.zeros((adj_output.shape[0]+1, adj_output.shape[0]+1))
n = adj_full.shape[0]
adj_full[1:n, 0:n-1] = np.tril(adj, 0)
adj_full = adj_full + adj_full.T
return adj_full
def encode_adj_flexible(adj):
'''
return a flexible length of output
note that here there is no loss when encoding/decoding an adj matrix
:param adj: adj matrix
:return:
'''
# pick up lower tri
adj = np.tril(adj, k=-1)
n = adj.shape[0]
adj = adj[1:n, 0:n-1]
adj_output = []
input_start = 0
for i in range(adj.shape[0]):
input_end = i + 1
adj_slice = adj[i, input_start:input_end]
adj_output.append(adj_slice)
non_zero = np.nonzero(adj_slice)[0]
input_start = input_end-len(adj_slice)+np.amin(non_zero)
return adj_output
def decode_adj_flexible(adj_output):
'''
return a flexible length of output
note that here there is no loss when encoding/decoding an adj matrix
:param adj: adj matrix
:return:
'''
adj = np.zeros((len(adj_output), len(adj_output)))
for i in range(len(adj_output)):
output_start = i+1-len(adj_output[i])
output_end = i+1
adj[i, output_start:output_end] = adj_output[i]
adj_full = np.zeros((len(adj_output)+1, len(adj_output)+1))
n = adj_full.shape[0]
adj_full[1:n, 0:n-1] = np.tril(adj, 0)
adj_full = adj_full + adj_full.T
return adj_full
def test_encode_decode_adj():
######## code test ###########
G = nx.ladder_graph(5)
G = nx.grid_2d_graph(20,20)
G = nx.ladder_graph(200)
G = nx.karate_club_graph()
G = nx.connected_caveman_graph(2,3)
print(G.number_of_nodes())
adj = np.asarray(nx.to_numpy_matrix(G))
G = nx.from_numpy_matrix(adj)
#
start_idx = np.random.randint(adj.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj = adj[np.ix_(x_idx, x_idx)]
print('adj\n',adj)
adj_output = encode_adj(adj,max_prev_node=5)
print('adj_output\n',adj_output)
adj_recover = decode_adj(adj_output,max_prev_node=5)
print('adj_recover\n',adj_recover)
print('error\n',np.amin(adj_recover-adj),np.amax(adj_recover-adj))
adj_output = encode_adj_flexible(adj)
for i in range(len(adj_output)):
print(len(adj_output[i]))
adj_recover = decode_adj_flexible(adj_output)
print(adj_recover)
print(np.amin(adj_recover-adj),np.amax(adj_recover-adj))
def encode_adj_full(adj):
'''
return a n-1*n-1*2 tensor, the first dimension is an adj matrix, the second show if each entry is valid
:param adj: adj matrix
:return:
'''
# pick up lower tri
adj = np.tril(adj, k=-1)
n = adj.shape[0]
adj = adj[1:n, 0:n-1]
adj_output = np.zeros((adj.shape[0],adj.shape[1],2))
adj_len = np.zeros(adj.shape[0])
for i in range(adj.shape[0]):
non_zero = np.nonzero(adj[i,:])[0]
input_start = np.amin(non_zero)
input_end = i + 1
adj_slice = adj[i, input_start:input_end]
# write adj
adj_output[i,0:adj_slice.shape[0],0] = adj_slice[::-1] # put in reverse order
# write stop token (if token is 0, stop)
adj_output[i,0:adj_slice.shape[0],1] = 1 # put in reverse order
# write sequence length
adj_len[i] = adj_slice.shape[0]
return adj_output,adj_len
def decode_adj_full(adj_output):
'''
return an adj according to adj_output
:param
:return:
'''
# pick up lower tri
adj = np.zeros((adj_output.shape[0]+1,adj_output.shape[1]+1))
for i in range(adj_output.shape[0]):
non_zero = np.nonzero(adj_output[i,:,1])[0] # get valid sequence
input_end = np.amax(non_zero)
adj_slice = adj_output[i, 0:input_end+1, 0] # get adj slice
# write adj
output_end = i+1
output_start = i+1-input_end-1
adj[i+1,output_start:output_end] = adj_slice[::-1] # put in reverse order
adj = adj + adj.T
return adj
def test_encode_decode_adj_full():
########### code test #############
# G = nx.ladder_graph(10)
G = nx.karate_club_graph()
# get bfs adj
adj = np.asarray(nx.to_numpy_matrix(G))
G = nx.from_numpy_matrix(adj)
start_idx = np.random.randint(adj.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj = adj[np.ix_(x_idx, x_idx)]
adj_output, adj_len = encode_adj_full(adj)
print('adj\n',adj)
print('adj_output[0]\n',adj_output[:,:,0])
print('adj_output[1]\n',adj_output[:,:,1])
# print('adj_len\n',adj_len)
adj_recover = decode_adj_full(adj_output)
print('adj_recover\n', adj_recover)
print('error\n',adj_recover-adj)
print('error_sum\n',np.amax(adj_recover-adj), np.amin(adj_recover-adj))
########## use pytorch dataloader
class Graph_sequence_sampler_pytorch(torch.utils.data.Dataset):
def __init__(self, G_list, max_num_node=None, max_prev_node=None, iteration=20000):
self.adj_all = []
self.len_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.len_all.append(G.number_of_nodes())
if max_num_node is None:
self.n = max(self.len_all)
else:
self.n = max_num_node
if max_prev_node is None:
print('calculating max previous node, total iteration: {}'.format(iteration))
self.max_prev_node = max(self.calc_max_prev_node(iter=iteration))
print('max previous node: {}'.format(self.max_prev_node))
else:
self.max_prev_node = max_prev_node
# self.max_prev_node = max_prev_node
# # sort Graph in descending order
# len_batch_order = np.argsort(np.array(self.len_all))[::-1]
# self.len_all = [self.len_all[i] for i in len_batch_order]
# self.adj_all = [self.adj_all[i] for i in len_batch_order]
def __len__(self):
return len(self.adj_all)
def __getitem__(self, idx):
adj_copy = self.adj_all[idx].copy()
x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
x_batch[0,:] = 1 # the first input token is all ones
y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
# generate input x, y pairs
len_batch = adj_copy.shape[0]
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[0:adj_encoded.shape[0], :] = adj_encoded
x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded
return {'x':x_batch,'y':y_batch, 'len':len_batch}
def calc_max_prev_node(self, iter=20000,topk=10):
max_prev_node = []
for i in range(iter):
if i % (iter / 5) == 0:
print('iter {} times'.format(i))
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
# print('Graph size', adj_copy.shape[0])
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
# encode adj
adj_encoded = encode_adj_flexible(adj_copy.copy())
max_encoded_len = max([len(adj_encoded[i]) for i in range(len(adj_encoded))])
max_prev_node.append(max_encoded_len)
max_prev_node = sorted(max_prev_node)[-1*topk:]
return max_prev_node
########## use pytorch dataloader
class Graph_sequence_sampler_pytorch_nobfs(torch.utils.data.Dataset):
def __init__(self, G_list, max_num_node=None):
self.adj_all = []
self.len_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.len_all.append(G.number_of_nodes())
if max_num_node is None:
self.n = max(self.len_all)
else:
self.n = max_num_node
def __len__(self):
return len(self.adj_all)
def __getitem__(self, idx):
adj_copy = self.adj_all[idx].copy()
x_batch = np.zeros((self.n, self.n-1)) # here zeros are padded for small graph
x_batch[0,:] = 1 # the first input token is all ones
y_batch = np.zeros((self.n, self.n-1)) # here zeros are padded for small graph
# generate input x, y pairs
len_batch = adj_copy.shape[0]
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.n-1)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[0:adj_encoded.shape[0], :] = adj_encoded
x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded
return {'x':x_batch,'y':y_batch, 'len':len_batch}
# dataset = Graph_sequence_sampler_pytorch_nobfs(graphs)
# print(dataset[1]['x'])
# print(dataset[1]['y'])
# print(dataset[1]['len'])
########## use pytorch dataloader
class Graph_sequence_sampler_pytorch_canonical(torch.utils.data.Dataset):
def __init__(self, G_list, max_num_node=None, max_prev_node=None, iteration=20000):
self.adj_all = []
self.len_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.len_all.append(G.number_of_nodes())
if max_num_node is None:
self.n = max(self.len_all)
else:
self.n = max_num_node
if max_prev_node is None:
# print('calculating max previous node, total iteration: {}'.format(iteration))
# self.max_prev_node = max(self.calc_max_prev_node(iter=iteration))
# print('max previous node: {}'.format(self.max_prev_node))
self.max_prev_node = self.n-1
else:
self.max_prev_node = max_prev_node
# self.max_prev_node = max_prev_node
# # sort Graph in descending order
# len_batch_order = np.argsort(np.array(self.len_all))[::-1]
# self.len_all = [self.len_all[i] for i in len_batch_order]
# self.adj_all = [self.adj_all[i] for i in len_batch_order]
def __len__(self):
return len(self.adj_all)
def __getitem__(self, idx):
adj_copy = self.adj_all[idx].copy()
x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
x_batch[0,:] = 1 # the first input token is all ones
y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
# generate input x, y pairs
len_batch = adj_copy.shape[0]
# adj_copy_matrix = np.asmatrix(adj_copy)
# G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
# start_idx = G.number_of_nodes()-1
# x_idx = np.array(bfs_seq(G, start_idx))
# adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[0:adj_encoded.shape[0], :] = adj_encoded
x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded
return {'x':x_batch,'y':y_batch, 'len':len_batch}
def calc_max_prev_node(self, iter=20000,topk=10):
max_prev_node = []
for i in range(iter):
if i % (iter / 5) == 0:
print('iter {} times'.format(i))
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
# print('Graph size', adj_copy.shape[0])
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
# encode adj
adj_encoded = encode_adj_flexible(adj_copy.copy())
max_encoded_len = max([len(adj_encoded[i]) for i in range(len(adj_encoded))])
max_prev_node.append(max_encoded_len)
max_prev_node = sorted(max_prev_node)[-1*topk:]
return max_prev_node
########## use pytorch dataloader
class Graph_sequence_sampler_pytorch_nll(torch.utils.data.Dataset):
def __init__(self, G_list, max_num_node=None, max_prev_node=None, iteration=20000):
self.adj_all = []
self.len_all = []
for G in G_list:
adj = np.asarray(nx.to_numpy_matrix(G))
adj_temp = self.calc_adj(adj)
self.adj_all.extend(adj_temp)
self.len_all.append(G.number_of_nodes())
if max_num_node is None:
self.n = max(self.len_all)
else:
self.n = max_num_node
if max_prev_node is None:
# print('calculating max previous node, total iteration: {}'.format(iteration))
# self.max_prev_node = max(self.calc_max_prev_node(iter=iteration))
# print('max previous node: {}'.format(self.max_prev_node))
self.max_prev_node = self.n-1
else:
self.max_prev_node = max_prev_node
# self.max_prev_node = max_prev_node
# # sort Graph in descending order
# len_batch_order = np.argsort(np.array(self.len_all))[::-1]
# self.len_all = [self.len_all[i] for i in len_batch_order]
# self.adj_all = [self.adj_all[i] for i in len_batch_order]
def __len__(self):
return len(self.adj_all)
def __getitem__(self, idx):
adj_copy = self.adj_all[idx].copy()
x_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
x_batch[0,:] = 1 # the first input token is all ones
y_batch = np.zeros((self.n, self.max_prev_node)) # here zeros are padded for small graph
# generate input x, y pairs
len_batch = adj_copy.shape[0]
# adj_copy_matrix = np.asmatrix(adj_copy)
# G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
# start_idx = G.number_of_nodes()-1
# x_idx = np.array(bfs_seq(G, start_idx))
# adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy, max_prev_node=self.max_prev_node)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[0:adj_encoded.shape[0], :] = adj_encoded
x_batch[1:adj_encoded.shape[0] + 1, :] = adj_encoded
return {'x':x_batch,'y':y_batch, 'len':len_batch}
def calc_adj(self,adj):
max_iter = 10000
adj_all = [adj]
adj_all_len = 1
i_old = 0
for i in range(max_iter):
adj_copy = adj.copy()
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
add_flag = True
for adj_exist in adj_all:
if np.array_equal(adj_exist, adj_copy):
add_flag = False
break
if add_flag:
adj_all.append(adj_copy)
adj_all_len += 1
if adj_all_len % 10 ==0:
print('adj found:',adj_all_len,'iter used',i)
return adj_all
# graphs = [nx.barabasi_albert_graph(20,3)]
# graphs = [nx.grid_2d_graph(4,4)]
# dataset = Graph_sequence_sampler_pytorch_nll(graphs)
############## below are codes not used in current version
############## they are based on pytorch default data loader, we should consider reimplement them in current datasets, since they are more efficient
# normal version
class Graph_sequence_sampler_truncate():
'''
the output will truncate according to the max_prev_node
'''
def __init__(self, G_list, max_node_num=25, batch_size=4, max_prev_node = 25):
self.batch_size = batch_size
self.n = max_node_num
self.max_prev_node = max_prev_node
self.adj_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
def sample(self):
# batch, length, feature
x_batch = np.zeros((self.batch_size, self.n, self.max_prev_node)) # here zeros are padded for small graph
y_batch = np.zeros((self.batch_size, self.n, self.max_prev_node)) # here zeros are padded for small graph
len_batch = np.zeros(self.batch_size)
# generate input x, y pairs
for i in range(self.batch_size):
# first sample and get a permuted adj
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
len_batch[i] = adj_copy.shape[0]
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node)
# get x and y and adj
# for small graph the rest are zero padded
y_batch[i, 0:adj_encoded.shape[0], :] = adj_encoded
x_batch[i, 1:adj_encoded.shape[0]+1, :] = adj_encoded
# sort in descending order
len_batch_order = np.argsort(len_batch)[::-1]
len_batch = len_batch[len_batch_order]
x_batch = x_batch[len_batch_order,:,:]
y_batch = y_batch[len_batch_order,:,:]
return torch.from_numpy(x_batch).float(), torch.from_numpy(y_batch).float(), len_batch.astype('int').tolist()
def calc_max_prev_node(self,iter):
max_prev_node = []
for i in range(iter):
if i%(iter/10)==0:
print(i)
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
# print('Graph size', adj_copy.shape[0])
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
time1 = time.time()
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
# encode adj
adj_encoded = encode_adj_flexible(adj_copy.copy())
max_encoded_len = max([len(adj_encoded[i]) for i in range(len(adj_encoded))])
max_prev_node.append(max_encoded_len)
max_prev_node = sorted(max_prev_node)[-100:]
return max_prev_node
# graphs, max_num_nodes = Graph_load_batch(min_num_nodes=6, name='DD',node_attributes=False)
# dataset = Graph_sequence_sampler_truncate([nx.karate_club_graph()])
# max_prev_nodes = dataset.calc_max_prev_node(iter=10000)
# print(max_prev_nodes)
# x,y,len = dataset.sample()
# print('x',x)
# print('y',y)
# print(len)
# only output y_batch (which is needed in batch version of new model)
class Graph_sequence_sampler_fast():
def __init__(self, G_list, max_node_num=25, batch_size=4, max_prev_node = 25):
self.batch_size = batch_size
self.G_list = G_list
self.n = max_node_num
self.max_prev_node = max_prev_node
self.adj_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
def sample(self):
# batch, length, feature
y_batch = np.zeros((self.batch_size, self.n, self.max_prev_node)) # here zeros are padded for small graph
# generate input x, y pairs
for i in range(self.batch_size):
# first sample and get a permuted adj
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
# print('graph size',adj_copy.shape[0])
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
# get the feature for the permuted G
# dict = nx.bfs_successors(G, start_idx)
# print('dict', dict, 'node num', self.G.number_of_nodes())
# print('x idx', x_idx, 'len', len(x_idx))
# print('adj')
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_copy.shape[0]):
# print(adj_copy[print_i].astype(int))
# adj_before = adj_copy.copy()
# encode adj
adj_encoded = encode_adj(adj_copy.copy(), max_prev_node=self.max_prev_node)
# print('adj encoded')
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_copy.shape[0]):
# print(adj_copy[print_i].astype(int))
# decode adj
# print('adj recover error')
# adj_decode = decode_adj(adj_encoded.copy(), max_prev_node=self.max_prev_node)
# adj_err = adj_decode-adj_copy
# print(np.sum(adj_err))
# if np.sum(adj_err)!=0:
# print(adj_err)
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_err.shape[0]):
# print(adj_err[print_i].astype(int))
# get x and y and adj
# for small graph the rest are zero padded
y_batch[i, 0:adj_encoded.shape[0], :] = adj_encoded
# np.set_printoptions(linewidth=200,precision=3)
# print('y\n')
# for print_i in range(self.y_batch[i,:,:].shape[0]):
# print(self.y_batch[i,:,:][print_i].astype(int))
# print('x\n')
# for print_i in range(self.x_batch[i, :, :].shape[0]):
# print(self.x_batch[i, :, :][print_i].astype(int))
# print('adj\n')
# for print_i in range(self.adj_batch[i, :, :].shape[0]):
# print(self.adj_batch[i, :, :][print_i].astype(int))
# print('adj_norm\n')
# for print_i in range(self.adj_norm_batch[i, :, :].shape[0]):
# print(self.adj_norm_batch[i, :, :][print_i].astype(float))
# print('feature\n')
# for print_i in range(self.feature_batch[i, :, :].shape[0]):
# print(self.feature_batch[i, :, :][print_i].astype(float))
# print('x_batch\n',self.x_batch)
# print('y_batch\n',self.y_batch)
return torch.from_numpy(y_batch).float()
# graphs, max_num_nodes = Graph_load_batch(min_num_nodes=6, name='PROTEINS_full')
# print(max_num_nodes)
# G = nx.ladder_graph(100)
# # G1 = nx.karate_club_graph()
# # G2 = nx.connected_caveman_graph(4,5)
# G_list = [G]
# dataset = Graph_sequence_sampler_fast(graphs, batch_size=128, max_node_num=max_num_nodes, max_prev_node=30)
# for i in range(5):
# time0 = time.time()
# y = dataset.sample()
# time1 = time.time()
# print(i,'time', time1 - time0)
# output size is flexible (using list to represent), batch size is 1
class Graph_sequence_sampler_flexible():
def __init__(self, G_list):
self.G_list = G_list
self.adj_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.y_batch = []
def sample(self):
# generate input x, y pairs
# first sample and get a permuted adj
adj_idx = np.random.randint(len(self.adj_all))
adj_copy = self.adj_all[adj_idx].copy()
# print('graph size',adj_copy.shape[0])
x_idx = np.random.permutation(adj_copy.shape[0])
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
adj_copy_matrix = np.asmatrix(adj_copy)
G = nx.from_numpy_matrix(adj_copy_matrix)
# then do bfs in the permuted G
start_idx = np.random.randint(adj_copy.shape[0])
x_idx = np.array(bfs_seq(G, start_idx))
adj_copy = adj_copy[np.ix_(x_idx, x_idx)]
# get the feature for the permuted G
# dict = nx.bfs_successors(G, start_idx)
# print('dict', dict, 'node num', self.G.number_of_nodes())
# print('x idx', x_idx, 'len', len(x_idx))
# print('adj')
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_copy.shape[0]):
# print(adj_copy[print_i].astype(int))
# adj_before = adj_copy.copy()
# encode adj
adj_encoded = encode_adj_flexible(adj_copy.copy())
# print('adj encoded')
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_copy.shape[0]):
# print(adj_copy[print_i].astype(int))
# decode adj
# print('adj recover error')
# adj_decode = decode_adj(adj_encoded.copy(), max_prev_node=self.max_prev_node)
# adj_err = adj_decode-adj_copy
# print(np.sum(adj_err))
# if np.sum(adj_err)!=0:
# print(adj_err)
# np.set_printoptions(linewidth=200)
# for print_i in range(adj_err.shape[0]):
# print(adj_err[print_i].astype(int))
# get x and y and adj
# for small graph the rest are zero padded
self.y_batch=adj_encoded
# np.set_printoptions(linewidth=200,precision=3)
# print('y\n')
# for print_i in range(self.y_batch[i,:,:].shape[0]):
# print(self.y_batch[i,:,:][print_i].astype(int))
# print('x\n')
# for print_i in range(self.x_batch[i, :, :].shape[0]):
# print(self.x_batch[i, :, :][print_i].astype(int))
# print('adj\n')
# for print_i in range(self.adj_batch[i, :, :].shape[0]):
# print(self.adj_batch[i, :, :][print_i].astype(int))
# print('adj_norm\n')
# for print_i in range(self.adj_norm_batch[i, :, :].shape[0]):
# print(self.adj_norm_batch[i, :, :][print_i].astype(float))
# print('feature\n')
# for print_i in range(self.feature_batch[i, :, :].shape[0]):
# print(self.feature_batch[i, :, :][print_i].astype(float))
return self.y_batch,adj_copy
# G = nx.ladder_graph(5)
# # G = nx.grid_2d_graph(20,20)
# # G = nx.ladder_graph(200)
# graphs = [G]
#
# graphs, max_num_nodes = Graph_load_batch(min_num_nodes=6, name='ENZYMES')
# sampler = Graph_sequence_sampler_flexible(graphs)
#
# y_max_all = []
# for i in range(10000):
# y_raw,adj_copy = sampler.sample()
# y_max = max(len(y_raw[i]) for i in range(len(y_raw)))
# y_max_all.append(y_max)
# # print('max bfs node',y_max)
# print('max', max(y_max_all))
# print(y[1])
# print(Variable(torch.FloatTensor(y[1])).cuda(CUDA))
########### potential use: an encoder along with the GraphRNN decoder
# preprocess the adjacency matrix
def preprocess(A):
# Get size of the adjacency matrix
size = len(A)
# Get the degrees for each node
degrees = np.sum(A, axis=1)+1
# Create diagonal matrix D from the degrees of the nodes
D = np.diag(np.power(degrees, -0.5).flatten())
# Cholesky decomposition of D
# D = np.linalg.cholesky(D)
# Inverse of the Cholesky decomposition of D
# D = np.linalg.inv(D)
# Create an identity matrix of size x size
I = np.eye(size)
# Create A hat
A_hat = A + I
# Return A_hat
A_normal = np.dot(np.dot(D,A_hat),D)
return A_normal
# truncate the output seqence to save representation, and allowing for infinite generation
# now having a list of graphs
class Graph_sequence_sampler_bfs_permute_truncate_multigraph():
def __init__(self, G_list, max_node_num=25, batch_size=4, max_prev_node = 25, feature = None):
self.batch_size = batch_size
self.G_list = G_list
self.n = max_node_num
self.max_prev_node = max_prev_node
self.adj_all = []
for G in G_list:
self.adj_all.append(np.asarray(nx.to_numpy_matrix(G)))
self.has_feature = feature
def sample(self):
# batch, length, feature
# self.x_batch = np.ones((self.batch_size, self.n - 1, self.max_prev_node))