-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
199 lines (162 loc) · 5.97 KB
/
utils.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
from collections import defaultdict
import networkx as nx
import numpy as np
import torch
import torch.nn as nn
from matplotlib import pyplot as plt
def plotGraph(
graph: nx.Graph, nodeLabels=None, showLabel=True, nodeColors=None, edgeColors=None, fig_name=None
):
pos = nx.circular_layout(graph)
plt.figure()
if not nodeLabels:
nodeLabels = (
{node: node for node in graph.nodes}
if not showLabel
else {node: (node, graph.nodes[node]["label"]) for node in graph.nodes}
)
if not nodeColors:
nodeColors = "lime"
if not edgeColors:
edgeColors = "black"
nx.draw(
graph,
pos,
edge_color=edgeColors,
width=1,
linewidths=0.1,
node_size=500,
node_color=nodeColors,
alpha=0.9,
labels=nodeLabels,
)
# edgeLabels = {}
# for edge in graph.edges():
# edgeLabels[edge] = graph[edge[0]][edge[1]]["label"]
# nx.draw_networkx_edge_labels(graph, pos, edge_labels=edgeLabels, font_color='red')
plt.axis("off")
plt.savefig(fig_name, dpi=300)
def write_graphs(graphs, out_file_name):
with open(out_file_name, "w", encoding="utf-8") as f:
for i, g in enumerate(graphs):
f.write("t # %d\n" % i)
node_mapping = {}
for nid, nod in enumerate(g.nodes):
f.write("v %d %d\n" % (nid, g.nodes[nod]["label"]))
node_mapping[nod] = nid
for nod1, nod2 in g.edges:
nid1 = node_mapping[nod1]
nid2 = node_mapping[nod2]
f.write("e %d %d %d\n" %
(nid1, nid2, g.edges[(nod1, nod2)]["label"]))
def read_mapping(mapping_file, sg2g=False):
mapping = dict()
with open(mapping_file, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f.readlines()]
tmapping, graph_cnt = None, 0
for i, line in enumerate(lines):
cols = line.split(" ")
if cols[0] == "t":
if tmapping is not None:
mapping[graph_cnt] = tmapping
tmapping = None
if cols[-1] == "-1":
break
tmapping = defaultdict(lambda: -1)
graph_cnt = int(cols[2])
elif cols[0] == "v":
if sg2g:
tmapping[int(cols[1])] = int(cols[2])
else:
tmapping[int(cols[2])] = int(cols[1])
# adapt to input files that do not end with 't # -1'
if tmapping is not None:
mapping[graph_cnt] = tmapping
return mapping
def read_graphs(database_file_name):
graphs = dict()
max_size = 0
with open(database_file_name, "r", encoding="utf-8") as f:
lines = [line.strip() for line in f.readlines()]
tgraph, graph_cnt = None, 0
graph_size = 0
for i, line in enumerate(lines):
cols = line.split(" ")
if cols[0] == "t":
if tgraph is not None:
graphs[graph_cnt] = tgraph
if max_size < graph_size:
max_size = graph_size
graph_size = 0
tgraph = None
if cols[-1] == "-1":
break
tgraph = nx.Graph()
graph_cnt = int(cols[2])
elif cols[0] == "v":
tgraph.add_node(int(cols[1]), label=int(cols[2]))
graph_size += 1
elif cols[0] == "e":
tgraph.add_edge(int(cols[1]), int(cols[2]), label=int(cols[3]))
# adapt to input files that do not end with 't # -1'
if tgraph is not None:
graphs[graph_cnt] = tgraph
if max_size < graph_size:
max_size = graph_size
return graphs
def set_cuda_visible_device(ngpus):
import subprocess
empty = []
for i in range(8):
command = "nvidia-smi -i " + str(i) + ' | grep "No running" | wc -l'
output = subprocess.check_output(command, shell=True).decode("utf-8")
# print('nvidia-smi -i '+str(i)+' | grep "No running" | wc -l > empty_gpu_check')
if int(output) == 1:
empty.append(i)
if len(empty) < ngpus:
print("avaliable gpus are less than required")
exit(-1)
cmd = ""
for i in range(ngpus):
cmd += str(empty[i]) + ","
return cmd
def initialize_model(model, device, load_save_file=False, gpu=True):
if load_save_file:
if not gpu:
model.load_state_dict(
torch.load(load_save_file, map_location=torch.device("cpu"))
)
else:
model.load_state_dict(torch.load(load_save_file))
else:
for param in model.parameters():
if param.dim() == 1:
continue
nn.init.constant(param, 0)
else:
# nn.init.normal(param, 0.0, 0.15)
nn.init.xavier_normal_(param)
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
model = nn.DataParallel(model)
model.to(device)
return model
def onehot_encoding(x, max_x):
onehot_vector = [0] * max_x
onehot_vector[x - 1] = 1 # label start from 1
return onehot_vector
def one_of_k_encoding(x, allowable_set):
if x not in allowable_set:
raise Exception(
"input {0} not in allowable set{1}:".format(x, allowable_set))
# print list((map(lambda s: x == s, allowable_set)))
return list(map(lambda s: x == s, allowable_set))
def one_of_k_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return list(map(lambda s: x == s, allowable_set))
def node_feature(m, node_i, max_nodes):
node = m.nodes[node_i]
return onehot_encoding(node["label"], max_nodes)