-
Notifications
You must be signed in to change notification settings - Fork 1
/
datasets.py
2228 lines (1899 loc) · 92.5 KB
/
datasets.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
from torch_geometric.datasets import OGB_MAG, DBLP
from torch_geometric.data import HeteroData
import torch_geometric
import torch
import os.path as osp
import copy
import itertools
import networkx as nx
import torch_geometric as pyg
from torch_geometric.datasets.graph_generator import BAGraph
from torch_geometric.data import Data, HeteroData
from torch_geometric.utils import from_networkx
from torch_geometric.utils import from_networkx
from torch_geometric.datasets import ExplainerDataset
from torch_geometric.datasets.graph_generator import BAGraph
from sklearn.model_selection import train_test_split
import random
from collections import Counter
from torch_geometric.datasets import DBLP
import torch_geometric.transforms as T
class PyGDataProcessor():
"""
A class, which stores the principles data of a dataset in PyG.
Especially: Training, validation, test data.
It transforms all input into one format (e.q. True/False as Training/Testinginstead of 0/1)
An object represents one (hdata) dataset.
"""
def __init__(self, data=HeteroData(), type_to_classify=None):
# Initialize an empty hdata object
self._data = data
self._type_to_classify = type_to_classify
# if _data has a type_to_classify, then we can use it as a type_to_classify
if hasattr(self._data, 'type_to_classify'):
self._type_to_classify = self._data.type_to_classify
else:
self._data.type_to_classify = str(self._type_to_classify)
def import_hdata(self, heterodata, type_to_classify=None):
"""
Gets as input a heterodata object and checks, if train, validation and test data are included.
And checks, if train, validation and test data are tensors with the indices of the nodes;
not tensors of boolean true/False values. If so, it calls _convert_format to
convert them to tensors with the indices of the nodes.
"""
self._data = heterodata
try:
self._type_to_classify = heterodata.type_to_classify
except Exception:
self._type_to_classify = type_to_classify
for split in ['train', 'val', 'test']:
split_key = f'{split}_mask'
if self._type_to_classify is not None:
if hasattr(heterodata, self._type_to_classify):
if hasattr(heterodata[self._type_to_classify], split_key):
self._data[self._type_to_classify][split_key] = getattr(
heterodata[self._type_to_classify], split_key)
self._convert_format_train_val_test()
else:
self.add_training_validation_test()
def add_training_validation_test(self, training_percent=40, validation_percent=30, test_percent=30):
# set the number of nodes of the to-be-classified type
self._type_to_classify = str(self._type_to_classify)
try:
number_of_nodes = self._data[self._type_to_classify].num_nodes
if hasattr(self._data[self._type_to_classify], 'num_nodes'):
number_of_nodes = self._data[self._type_to_classify].num_nodes
else:
number_of_nodes = self._data[self._type_to_classify].x.size()[
0]
self._data[self._type_to_classify].num_nodes = number_of_nodes
except Exception:
number_of_nodes = self._data[self._type_to_classify].size()
self._data[self._type_to_classify].num_nodes = number_of_nodes
assert isinstance(
number_of_nodes, int), ("The number of nodes is not an integer.", number_of_nodes)
idx = torch.arange(number_of_nodes)
if training_percent + validation_percent + test_percent != 100:
if training_percent + validation_percent + test_percent == 1:
training_percent = training_percent * 100
validation_percent = validation_percent * 100
test_percent = test_percent * 100
elif training_percent < 0 or validation_percent < 0 or test_percent < 0:
print(
"Error: Positive values were expected for training, validation and test sets")
training_percent = 40
validation_percent = 30
test_percent = 30
else:
print(
"Error: It was expected to make a fair split into training, validation and test sets")
training_percent = 40
validation_percent = 30
test_percent = 30
train_idx, valid_and_test_idx = train_test_split(
idx,
train_size=0.01*training_percent,
)
valid_idx, test_idx = train_test_split(
valid_and_test_idx,
train_size=0.01*(validation_percent /
(validation_percent+test_percent)),
)
self._data[self._type_to_classify].train_mask = torch.tensor(train_idx)
self._data[self._type_to_classify].val_mask = torch.tensor(valid_idx)
self._data[self._type_to_classify].test_mask = torch.tensor(test_idx)
self._convert_format_train_val_test() # convert the format of the masks
return self._data
def _convert_format_train_val_test(self):
# Helper method to convert data to required format (e.g., True/False to 1/0)
# Implement the conversion logic here
# First check, if the data is already in the right format
# then check, if each node is in some training, validation or test set
"""
This function converts the format of the training, validation and test data into tensors with the indices of the nodes.
"""
if hasattr(self._data[self._type_to_classify], 'num_nodes'):
total_nodes = self._data[self._type_to_classify].num_nodes
else:
total_nodes = self._data[self._type_to_classify].x.size()[0]
self._data[self._type_to_classify].num_nodes = total_nodes
print(total_nodes, self._data[self._type_to_classify])
for split in ['train', 'val', 'test']:
split_key = f'{split}_mask'
mask = getattr(self._data[self._type_to_classify], split_key)
if mask.dtype == torch.bool:
new_mask = list()
for ind in range(total_nodes):
if mask[ind]:
new_mask.append(ind)
new_mask = torch.tensor(new_mask)
self.data[self._type_to_classify][split_key] = new_mask
set_train = set(self._data[self._type_to_classify].train_mask.tolist())
set_val = set(self._data[self._type_to_classify].val_mask.tolist())
set_test = set(self._data[self._type_to_classify].test_mask.tolist())
intersection = set_train.intersection(set_val).intersection(set_test)
if intersection:
print("The training, validation and test data are not disjoint.")
self.add_training_validation_test()
# final test, if everything worked
set_train = set(self._data[self._type_to_classify].train_mask.tolist())
set_val = set(self._data[self._type_to_classify].val_mask.tolist())
set_test = set(self._data[self._type_to_classify].test_mask.tolist())
intersection = set_train.intersection(set_val).intersection(set_test)
assert intersection == set(), "The training, validation and test data are not disjoint."
# Getter and setter methods
# Getter method for 'data'
@property
def data(self):
return self._data
# Setter method for 'data'
@data.setter
def data(self, value):
self._data = value
self._convert_format_train_val_test()
@property
def type_to_classify(self):
"""
Getter for _type_to_classify.
Returns the current value of _type_to_classify.
"""
return self._type_to_classify
@type_to_classify.setter
def type_to_classify(self, value):
"""
Setter for _type_to_classify.
Sets the _type_to_classify to a new value.
Additional checks or validations can be added here if required.
"""
# Here you can add any validation or type checks if necessary
self._type_to_classify = value
# Similar getters and setters for validation and test data can be added
class GraphLibraryConverter():
"""
This class has all functions to convert graphs from one library to another.
Supported libraries: Networkx, PyG (heterogen and homogen), DGL
The constructor saves the library (for DGL-Fromat) and a (heterogeneous) graph as an attribute.
All methods are static.
"""
def __init__(self, library, graph):
self._library = library
self._graph = graph # in heterodata
@staticmethod
def networkx_to_homogen_pyg(graph):
# Assuming node features are numeric and stored in a 'feature' attribute
# If not, this part needs to be adjusted
node_features = [graph.nodes[node]['feature']
for node in graph.nodes()]
node_features_tensor = torch.tensor(node_features, dtype=torch.float)
# Extracting edge indices
edge_list = list(graph.edges())
edge_index = torch.tensor(
[[u, v] for u, v in edge_list], dtype=torch.long).t().contiguous()
# Creating PyG Data object
pyg_graph = Data(x=node_features_tensor, edge_index=edge_index)
return pyg_graph
@staticmethod
def homogen_pyg_to_heterogen_pyg(graph):
# Create a HeteroData object
hetero_graph = HeteroData()
# Assign a default node type and transfer node features
# Assuming node features are in 'x'
if 'x' in graph:
hetero_graph['node_type'].x = graph.x
# Assign a default edge type and transfer edge features and connections
# Assuming edge_index is present
if 'edge_index' in graph:
hetero_graph['node_type', 'edge_type',
'node_type'].edge_index = graph.edge_index
# Transfer edge features if present
for key, value in graph.items():
if key != 'x' and key != 'edge_index':
hetero_graph['node_type', 'edge_type',
'node_type'][key] = value
return hetero_graph
@staticmethod
def networkx_to_heterogen_pyg(graph, edge_type='to'):
# Implement conversion from Networkx graph to PyG graph
# Scenario: Each label is a node type
assert isinstance(
graph, nx.Graph), "The graph is not a networkx graph."
hetero_graph = HeteroData()
labels = []
for _, attr in graph.nodes(data=True):
# Replace 'label' with your attribute key
label = attr.get('label')
if label is not None:
labels.append(label)
# Step 1: count nodes of each label
dict_nodecount = {}
for label in labels:
dict_nodecount[label] = 0
for _, attr in graph.nodes(data=True):
if attr.get('label') == label:
dict_nodecount[label] += 1
# Step 2: create nodes
for nodetype in labels:
hetero_graph[str(nodetype)].x = torch.ones(
(dict_nodecount[nodetype], 1))
# Step 3: create edges
# 3.1: Create mapping old to new indices
def count_nodes_with_label_until_id(G, label, node_id): return sum(1 for n, d in itertools.takewhile(
lambda x: x[0] != node_id, G.nodes(data=True)) if d.get('label') == label)
dict_current_to_new_indices = dict()
# test, if all nodes have a label
for node_id, attr in graph.nodes(data=True):
assert attr.get('label') is not None, "Not all nodes have a label."
for node_id, attr in graph.nodes(data=True):
dict_current_to_new_indices[node_id] = count_nodes_with_label_until_id(
graph, attr.get('label'), node_id)
# 3.2: Create edges
# iterate over all edges of graph: nx.Graph and transfer them to hetero_graph with the dict_current_to_new_indices: list
for edge in graph.edges():
u, v = edge
# Replace 'label' with your attribute key
label1 = str(graph.nodes[u].get('label'))
label2 = str(graph.nodes[v].get('label'))
assert isinstance(u, int) and isinstance(
v, int), "The nodes are not integers."
u_new, v_new = dict_current_to_new_indices[u], dict_current_to_new_indices[v]
# update hetero_graph:
hetero_graph = GraphLibraryConverter.add_edge_to_hdata(
hetero_graph, label1, edge_type, label2, u_new, v_new)
# add number of nodes to hetero_graph
for nodetype in labels:
hetero_graph[str(nodetype)].num_nodes = dict_nodecount[nodetype]
for nodetype in labels:
assert isinstance(hetero_graph[str(
nodetype)].num_nodes, int), "num_nodes did not produce an integer"
# add number of num_node_types to hetero_graph
hetero_graph.num_node_types = len(labels)
# test if hetero_graph is bidirected:
hetero_graph = GraphLibraryConverter.make_hdata_bidirected(
hetero_graph)
# ---- test, if everything worked
# test, if all node types are strings
for nodetype in hetero_graph.node_types:
assert isinstance(nodetype, str), "The node types are not strings."
# test, if it is bidirected
# end tests
return hetero_graph, dict_current_to_new_indices
@staticmethod
def pyg_to_networkx(graph):
# Implement conversion from PyG graph to Networkx graph
pass
@staticmethod
def networkx_to_dgl(graph):
# Implement conversion from Networkx graph to DGL graph
pass
@staticmethod
def dgl_to_networkx(graph):
# Implement conversion from DGL graph to Networkx graph
pass
@staticmethod
def dict_to_heterodata(dict):
# dict must be of the form: {('node_type', 'edge_type', 'node_type'): (torch.tensor(), torch.tensor())}
pass
@staticmethod
def add_edge_to_hdata(hetero_graph, start_type, edge_type, end_type, start_id: int, end_id: int):
start_id_tensor = torch.tensor([start_id], dtype=torch.long)
end_id_tensor = torch.tensor([end_id], dtype=torch.long)
if (start_type, edge_type, end_type) in hetero_graph.edge_types:
list_ids_start, list_ids_end = [row.tolist()
for row in hetero_graph[(start_type, edge_type, end_type)].edge_index]
list_ids_start.append(start_id)
list_ids_end.append(end_id)
hetero_graph[(start_type, edge_type, end_type)].edge_index = torch.tensor(
[list_ids_start, list_ids_end])
elif (end_type, edge_type, start_type) in hetero_graph.edge_types:
list_ids_start, list_ids_end = [row.tolist()
for row in hetero_graph[(end_type, edge_type, start_type)].edge_index]
list_ids_start.append(end_id)
list_ids_end.append(start_id)
hetero_graph[(end_type, edge_type, start_type)].edge_index = torch.tensor(
[list_ids_start, list_ids_end])
else:
hetero_graph[start_type, edge_type, end_type].edge_index = (
start_id_tensor, end_id_tensor)
return hetero_graph
def make_hdata_bidirected(hetero_graph):
"""
This makes a heterogenous graph bidirected and checks on validity: Each edge should exist in 2 directions.
"""
for edge_type in hetero_graph.edge_types:
start_type, relation_type, end_type = edge_type
# Get the edge indices for this type
edge_indices = hetero_graph[start_type,
relation_type, end_type].edge_index
start_indices, end_indices = edge_indices[0], edge_indices[1]
# Iterate through the edges
for start_id, end_id in zip(start_indices, end_indices):
# Check if the reverse edge exists
if (end_type, relation_type, start_type) in hetero_graph.edge_types:
reverse_edge_index = hetero_graph[end_type,
relation_type, start_type].edge_index
if not any(end_id == reverse_edge_index[0][i] and start_id == reverse_edge_index[1][i] for i in range(len(reverse_edge_index[0]))):
# Add the reverse edge
# Assuming a function add_edge_to_hdata as defined previously
GraphLibraryConverter.add_edge_to_hdata(
hetero_graph, end_type, relation_type, start_type, end_id.item(), start_id.item())
else:
# Add the reverse edge
# Assuming a function add_edge_to_hdata as defined previously
GraphLibraryConverter.add_edge_to_hdata(
hetero_graph, end_type, relation_type, start_type, end_id.item(), start_id.item())
return hetero_graph
# class GenerateRandomHomogeneousGraph(): # Erbt von PyG-BAGraph, und anderen Graph Generators
"""
Erstellt über Parameter beliebige Random Graphs (BA, ...)
"""
# class GenerateRandomheterogeneousGraph(GenerateRandomHomogeneousGraph):
"""
Macht alles aus der Basisklasse GenerateRandomHomogeneousGraph für heterogene Graphen
"""
# class BAGraphGraphMotifDataset(): # Eventuell von GraphGeneration erben?: https://pytorch-geometric.readthedocs.io/en/latest/_modules/torch_geometric/datasets/graph_generator/base.html#GraphGenerator
"""
A class, which generates a Barabasi-Albert-Graph with a given number of nodes and edges.
Additionally, it can add motifs to the graph.
Object:
Methods:
- __init__: first calls the super class __init__ which initializes the dataset. This is an empty hdata object.
The input is a dictionary which encodes a motif, or some pre-defined motif (like house). Optional input is the number of motifs,
which should be added; the number of nodes of the initial BA graph or an optional start graph.
If no initial start graph is added, then a BA graph is created.
- add_motif: adds a motif to the graph. The input is a dictionary which encodes a motif, or some pre-defined motif
(like house).
- create_BAGraph: creates a Barabasi-Albert-Graph with a given number of nodes and edges. (using PyG)
"""
# class GenerateRandomGraph(): # Erbt von PyG-BAGraph, und anderen Graph Generators
class GenerateRandomGraph(): # getestet
"""
Erstellt über Parameter beliebige Random Graphs (BA, ...) in beliebigen Formaten
Methods:
- __init__: generates an empty object (networkx)
- create_BAGraph_nx: creates a Barabasi-Albert-Graph with a given number of nodes and edges. (using networkx)
- create_BAGraph_pyg: creates a Barabasi-Albert-Graph with a given number of nodes and edges. (using PyG)
"""
"""
Creates random graphs (BA, etc.) in various formats through parameters.
"""
def __init__(self):
"""
Generates an empty networkx object.
"""
self.graph_nx = nx.Graph()
@staticmethod
def create_BAGraph_nx(num_nodes, num_edges):
"""
Creates a Barabasi-Albert graph with a given number of nodes and edges using networkx.
"""
graph_nx = nx.barabasi_albert_graph(num_nodes, num_edges)
return graph_nx
@staticmethod
def create_BAGraph_pyg_homogen(num_nodes, num_edges):
"""
Return homogeneous pyg graph
Creates a Barabasi-Albert graph with a given number of nodes and edges using PyTorch Geometric (PyG).
"""
graph_generator = BAGraph(num_nodes, num_edges)
data = graph_generator()
return data
class GraphMotifAugmenter(): # getestet
"""
This class is designed to add motifs to a graph.
The input is:
- graph,
- a motif (given in homogeneous format),
- the number of times the motif should be added to the graph (num_motifs, default = 1)
Methods:
- __init__: initializes the class. Checks if the input graph is of the networkx format
and if not converts it (using the GraphConverter class).
There are some prededined motifs, like house, which can be added.
Everything happens in networkx
"""
house_motif = {
'labels': [1, 1, 2, 2, 3],
'edges': [(0, 1), (1, 2), (2, 3), (3, 4), (4, 2), (0, 3)],
}
def __init__(self, motif='house', num_motifs=0, orig_graph=None):
self.motif = motif
self.num_motifs = num_motifs
if orig_graph is not None:
self.orig_graph = orig_graph
else:
num_nodes = 400
num_edges = 3
graph = GenerateRandomGraph.create_BAGraph_nx(num_nodes, num_edges)
self.orig_graph = graph
self._graph = copy.deepcopy(self.orig_graph)
self._list_node_in_motif_or_not = [0]*self.orig_graph.number_of_nodes()
self._number_nodes_of_orig_graph = self.orig_graph.number_of_nodes()
for _ in range(num_motifs):
self.add_motif(motif, self._graph)
len_motif = 0
try:
len_motif = len(motif['labels'])
except Exception:
if motif == 'house':
len_motif = 5
if motif == 'house':
motif == GraphMotifAugmenter.house_motif
self._list_node_in_motif_or_not.extend([1]*len_motif)
@staticmethod
def add_motif(motif, graph): # getestet
"""
Adds a motif to the graph (self.graph).
Motifs are given by:
- a list of edges between nodes.
First, a random node from the motif is chosen
Second, a random node from the (possible already enhanced by motifs) BA Graph is chosen.
"""
if isinstance(graph, nx.Graph):
pass
else:
# TODO: convert to networkx
raise Exception("The graph is not a networkx graph.")
if graph is not None:
num_graph_nodes = graph.number_of_nodes()
elif hasattr(self, 'orig_graph'):
num_graph_nodes = self.orig_graph.number_of_nodes()
graph = self.orig_graph
else:
raise Exception(
"No graph was given and no BA graph was created yet or something else went wrong.")
if motif == 'house':
motif = GraphMotifAugmenter.house_motif
if isinstance(motif, dict):
# assetr tests, if the dictionary is correct
nodes_in_motif = max(max(pair) for pair in motif['edges'])+1
assert 'labels' in motif, "The motif does not have labels."
assert nodes_in_motif == len(
motif['labels']), "The highest node in the motif is not the last node."
# continue with the code
# select random node from bagraph and add an edge to the house motif
start_node = random.randint(0, nodes_in_graph) # in ba_graph
end_node = random.randint(
0, nodes_in_motif-1)+nodes_in_graph # in motif
# Add nodes to graph
assert 'labels' in motif, "The motif does not have labels."
for i, label in enumerate(motif['labels']):
graph.add_node(i+nodes_in_graph, label=label)
# Add edges
for u_motif, v_motif in motif['edges']:
u, v = u_motif + nodes_in_graph, v_motif + nodes_in_graph
graph.add_edge(u, v)
graph.add_edge(start_node, end_node)
# update the list, which nodes are in the motif and which are not
else:
raise Exception("This case is not implemented yet.")
return graph
# getter and setter methods
@property
def number_nodes_of_orig_graph(self):
"""
Getter for the number of nodes in the original graph.
Returns:
- int: The number of nodes in the original graph.
"""
return self._number_nodes_of_orig_graph
@property
def graph(self):
"""
Getter for the _graph attribute.
Returns:
- The graph object stored in the _graph attribute.
"""
return self._graph
class HeteroBAMotifDataset():
"""
Class, which makes a heterogenous graph out of a homogeneous graph with labels.
It makes the labels to node types and adds random node types to the graph.
All previous nodes without label get the lowest natural number (startint at 0) as a node type (called base-type), which is not used yet.
Input:
- The previous label, which now should be the node type to be classified.
- an instance of GraphMotifAugmenter
Output:
- a heterogenous graph in PyG format
Methods:
- __init__:
It converts the labels into node types.
Input: the node type, which should be classified; the graph, which should be converted.
- _convert_labels_to_node_types: converts the labels into node types.
- _add_random_types: randomly changes node types of the base-type to other available types.
Then it creates labels for each node of the type to be classified: 1 for nodes in a motif, 0 for nodes outside.
Nodes outside the motif are all nodes with id less than number_nodes_of_orig_graph.
"""
def __init__(self, graph: nx.Graph, type_to_classify=-1):
self._augmenter = GraphMotifAugmenter()
self._type_to_classify = type_to_classify
self._graph = graph
self._hdatagraph = HeteroData()
self._edge_index = 'to'
# resolve type_to_classify == -1:
labels = []
for _, attr in self._graph.nodes(data=True):
# Replace 'label' with your attribute key
label = attr.get('label')
if label is not None:
labels.append(label)
labels = list(set(labels))
if self._type_to_classify == -1:
self._type_to_classify = str(labels[-1])
# set base label
self._base_label = self._make_base_label(labels)
# save labels
labels.append(self._base_label)
self.labels = labels
# save type_to_classify into hdatagraph
self._hdatagraph.type_to_classify = self._type_to_classify
def _make_base_label(self, labels):
"""
Makes a base label, which is not used yet.
"""
# set base label
if 0 not in labels:
self._base_label = 0
else:
self._base_label = max(labels)+1
for node in self._graph.nodes(data=True):
node_id, attr = node
if 'label' not in attr or attr['label'] is None:
self._graph.nodes[node_id]['label'] = self._base_label
if node_id < self._augmenter.number_nodes_of_orig_graph:
self._graph.nodes[node_id]['label'] = self._base_label
return self._base_label
def _convert_labels_to_node_types(self, change_percent_labels=40):
"""
Converts the labels into node types and adds this to self._hdatagraph.
Steps:
0. All nodes in the original graph get the node label 0 (or the lowest natural number, which is not used yet);
this is the base-label. (in this function)
1. Get the list of all node labels
1.1. Get the list of all node types
1.2. Randomly change nodes of the base-label to other available labels
function: _add_random_types
2. For each label, create a new node type
3. Create a dictionary, st. for each node type:
3.1. For each node with this node type / label: get a new node-id, only based on this node-type
3.2. Add the node-id to the dictionary
Function: _convert_nxgraph_to_hdatagraph
4. For each old edge, make the new edge with the new node-ids (between corresponding node types);
use as edge_index: 'to'
Add to self._hdatagraph
Add Feature 1 to each node
function: _convert_nxgraph_to_hdatagraph (together with 3.)
This should now be finished and complete
5. Add training, validation, test sets to self._hdatagraph for the node_type self._type_to_classify (default=-1)
5.1.: Add labels to the nodes of the type to be classified: 1 for nodes in a motif, 0 for nodes outside.
Function: _add_training_validation_test_sets (from class ... )
"""
# Step 0
# in constructor
# Step 1
# 1.1
labels = self.labels
if self._base_label in labels:
labels.remove(self._base_label)
# 1.2
# changes self._graph
self._add_random_types(labels, self._base_label,
change_percent=change_percent_labels)
# Step 2-4
labels.append(self._base_label)
hdata_graph, dict_current_to_new_indices = GraphLibraryConverter.networkx_to_heterogen_pyg(
self._graph, edge_type=self._edge_index)
# Step 5.1:
# retrieve a label_list for nodes inside / outside the motif graph
if self._type_to_classify == -1:
# -1 is self._base_label, which is not classified
type_to_classify_str = str(labels[-2])
else:
type_to_classify_str = str(self._type_to_classify)
# tests
assert type_to_classify_str != str(
self._base_label), (type_to_classify_str, self._base_label)
node_types = hdata_graph.node_types
node_types_str = [str(node) for node in node_types]
assert type_to_classify_str in node_types_str, (
type_to_classify_str, hdata_graph)
# end tests
label_list = [0]*hdata_graph[type_to_classify_str].num_nodes
for node in self._graph.nodes(data=True):
node_id, attr = node
if str(attr['label']) == str(self._type_to_classify):
new_node_id = dict_current_to_new_indices[node_id]
label_list[new_node_id] = 1
hdata_graph[type_to_classify_str].y = torch.tensor(label_list)
hetero_data_pygdataprocessor = PyGDataProcessor(
hdata_graph, self._type_to_classify)
hetero_data_pygdataprocessor.add_training_validation_test(
training_percent=40, validation_percent=30, test_percent=30)
# return the correct object
return hetero_data_pygdataprocessor.data
def _add_random_types(self, labels, base_label=None, change_percent=40):
"""
Randomly changes node types of the base-type to other available types.
Then it creates labels for each node of the type to be classified: 1 for nodes in a motif, 0 for nodes outside.
Nodes outside the motif are all nodes with id less than number_nodes_of_orig_graph.
Steps:
1. Change labels of the base label to other labels by percentage change_percent; Stop if change_percent have been reached (iterate at random)
"""
if base_label is None:
base_label = self._base_label
# 1. Change labels of the base label to other labels
number_labels = len(labels)
nodes_with_data = list(self._graph.nodes(data=True))
# shuffle, st. the nodes with the base label are randomly distributed
random.shuffle(nodes_with_data)
changes_nodes = 0
num_nodes_total = self._augmenter.number_nodes_of_orig_graph
for node_id, data in nodes_with_data:
if data['label'] == base_label:
if random.random() < change_percent/100:
data['label'] = labels[random.randint(0, number_labels-1)]
changes_nodes += 1
if changes_nodes >= num_nodes_total*change_percent/100:
break
# getter and setter methods
@property
def augmenter(self):
"""
Getter for the _augmenter attribute.
Returns:
- The GraphMotifAugmenter object stored in the _augmenter attribute.
"""
return self._augmenter
@augmenter.setter
def augmenter(self, value):
"""
Setter for the _augmenter attribute.
Args:
- value: The new GraphMotifAugmenter object to set.
"""
# You can add any validation logic here if needed
self._augmenter = value
@property
def type_to_classify(self):
"""
Getter for the _type_to_classify attribute.
Returns:
- The type to classify.
"""
return self._type_to_classify
@type_to_classify.setter
def type_to_classify(self, value):
"""
Setter for the _type_to_classify attribute.
Args:
- value: The new type to classify.
"""
# You can add any validation logic here if needed
self._type_to_classify = value
@property
def edge_index(self):
"""
Getter for the _edge_index attribute.
Returns:
- The edge_index.
"""
return self._edge_index
@edge_index.setter
def edge_index(self, value):
"""
Setter for the _edge_index attribute.
Args:
- value: The new edge_index.
"""
# You can add any validation logic here if needed
self._edge_index = value
# class BAGraphCEMotifDataset(HeteroBAMotifDataset):
"""
Creates a Barabasi-Albert-Graph with a given number of nodes and edges.
Then it assigns the nodes random node types.
Then it creates some graphs from a CE
Additionally, it adds these graphs to the BA-graph
It uses fast-instance-checker to label the nodes afterwards.
Methods:
- __init__: Calls the constructor of the super class HeteroBAMotifDataset (output: non-empty hdata graph).
also callable with a CE, which will be transformed to self.ce. If so, it also calls check_graph_ce.
- add_CE: adds a CE to the graph. The parameters are the Class Expression
and the number of nodes, which should be added to the graph.
adds/ updates self.ce
- check_graph_ce: This labels all the nodes in the graph with satisfy the CE.
"""
class PyGDataProcessor():
"""
A class, which stores the principles data of a dataset in PyG.
Especially: Training, validation, test data.
It transforms all input into one format (e.q. True/False as Training/Testinginstead of 0/1)
An object represents one (hdata) dataset.
"""
def __init__(self, data=HeteroData(), type_to_classify=None):
# Initialize an empty hdata object
self._data = data
self._type_to_classify = type_to_classify
# if _data has a type_to_classify, then we can use it as a type_to_classify
if hasattr(self._data, 'type_to_classify'):
self._type_to_classify = self._data.type_to_classify
else:
self._data.type_to_classify = str(self._type_to_classify)
if self._data.type_to_classify == 'None':
self._type_to_classify = None
def import_hdata(self, heterodata, type_to_classify=None):
"""
Gets as input a heterodata object and checks, if train, validation and test data are included.
And checks, if train, validation and test data are tensors with the indices of the nodes;
not tensors of boolean true/False values. If so, it calls _convert_format to
convert them to tensors with the indices of the nodes.
"""
self._data = heterodata
try:
self._type_to_classify = heterodata.type_to_classify
except Exception:
self._type_to_classify = type_to_classify
for split in ['train', 'val', 'test']:
split_key = f'{split}_mask'
if self._type_to_classify is not None:
if hasattr(heterodata, self._type_to_classify):
if hasattr(heterodata[self._type_to_classify], split_key):
self._data[self._type_to_classify][split_key] = getattr(
heterodata[self._type_to_classify], split_key)
self._convert_format_train_val_test()
else:
self.add_training_validation_test()
def add_training_validation_test(self, training_percent=40, validation_percent=30, test_percent=30):
# set the number of nodes of the to-be-classified type
self._type_to_classify = str(self._type_to_classify)
try:
number_of_nodes = self._data[self._type_to_classify].num_nodes
if hasattr(self._data[self._type_to_classify], 'num_nodes'):
number_of_nodes = self._data[self._type_to_classify].num_nodes
else:
number_of_nodes = self._data[self._type_to_classify].x.size()[
0]
self._data[self._type_to_classify].num_nodes = number_of_nodes
except Exception:
number_of_nodes = self._data[self._type_to_classify].size()
self._data[self._type_to_classify].num_nodes = number_of_nodes
assert isinstance(
number_of_nodes, int), ("The number of nodes is not an integer.", number_of_nodes)
idx = torch.arange(number_of_nodes)
if training_percent + validation_percent + test_percent != 100:
if training_percent + validation_percent + test_percent == 1:
training_percent = training_percent * 100
validation_percent = validation_percent * 100
test_percent = test_percent * 100
elif training_percent < 0 or validation_percent < 0 or test_percent < 0:
print(
"Error: Positive values were expected for training, validation and test sets")
training_percent = 40
validation_percent = 30
test_percent = 30
else:
print(
"Error: It was expected to make a fair split into training, validation and test sets")
training_percent = 40
validation_percent = 30
test_percent = 30
try:
train_idx, valid_and_test_idx = train_test_split(
idx,
train_size=0.01*training_percent,
)
valid_idx, test_idx = train_test_split(
valid_and_test_idx,
train_size=validation_percent /
(validation_percent+test_percent),
)
self._data[self._type_to_classify].train_mask = train_idx.clone().detach()
self._data[self._type_to_classify].val_mask = valid_idx.clone().detach()
self._data[self._type_to_classify].test_mask = test_idx.clone().detach()
self._convert_format_train_val_test() # convert the format of the masks
except Exception:
print("Not possible to split the data into training, validation and test sets, probably not enough data")
return self._data
def _convert_format_train_val_test(self):
# Helper method to convert data to required format (e.g., True/False to 1/0)
# Implement the conversion logic here
# First check, if the data is already in the right format
# then check, if each node is in some training, validation or test set
"""
This function converts the format of the training, validation and test data into tensors with the indices of the nodes.
"""
if hasattr(self._data[self._type_to_classify], 'num_nodes'):
total_nodes = self._data[self._type_to_classify].num_nodes
else:
total_nodes = self._data[self._type_to_classify].x.size()[0]
self._data[self._type_to_classify].num_nodes = total_nodes
for split in ['train', 'val', 'test']:
split_key = f'{split}_mask'
mask = getattr(self._data[self._type_to_classify], split_key)
if mask.dtype == torch.bool:
new_mask = list()
for ind in range(total_nodes):
if mask[ind]:
new_mask.append(ind)
new_mask = torch.tensor(new_mask)
self.data[self._type_to_classify][split_key] = new_mask
set_train = set(self._data[self._type_to_classify].train_mask.tolist())
set_val = set(self._data[self._type_to_classify].val_mask.tolist())
set_test = set(self._data[self._type_to_classify].test_mask.tolist())
intersection = set_train.intersection(set_val).intersection(set_test)
if intersection:
print("The training, validation and test data are not disjoint.")
self.add_training_validation_test()
# final test, if everything worked
set_train = set(self._data[self._type_to_classify].train_mask.tolist())
set_val = set(self._data[self._type_to_classify].val_mask.tolist())
set_test = set(self._data[self._type_to_classify].test_mask.tolist())
intersection = set_train.intersection(set_val).intersection(set_test)
assert intersection == set(), "The training, validation and test data are not disjoint."
# Getter and setter methods
# Getter method for 'data'
@property
def data(self):
return self._data
# Setter method for 'data'
@data.setter