-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
397 lines (359 loc) · 15.6 KB
/
solver.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
# below is the method using degree heuristic to let MST pick higher-degree nodes
import networkx as nx
from parse import read_input_file, write_output_file, read_output_file
import utils
from utils import is_valid_network, average_pairwise_distance, average_pairwise_distance_fast
import os
import sys
import matplotlib.pyplot as plt
import random
import numpy as np
import itertools
import time
def bruteforce(G):
list_of_trees = []
min_dist = 1000000
minT = nx.Graph()
# Remove degree 1 nodes and add their neighbors to minT
def traverse(T, G, G_copy):
nonlocal min_dist
nonlocal minT
if G_copy.number_of_edges() == 0:
return
for e in G_copy.edges():
u, v = e[0], e[1]
if e in T.edges():
continue
copy = T.copy()
temp = G_copy.copy()
T.add_node(u)
T.add_node(v)
T.add_edge(v, u, weight=G[v][u]['weight'])
temp.remove_edge(u, v)
if is_valid_network(G, T):
if average_pairwise_distance_fast(T) < min_dist:
min_dist = average_pairwise_distance_fast(T)
minT = T.copy()
traverse(T, G, temp)
elif not nx.is_dominating_set(G, T.nodes()) or not nx.is_connected(T):
traverse(T, G, temp)
T = copy.copy()
def findChain(G):
nonlocal confirmed
nonlocal T
nonlocal G_copy
changed = False
nodes = [n for n in G.nodes()]
for v in nodes:
if G.degree(v) == 1:
u = list(G.neighbors(v))[0]
confirmed.append(u)
T.add_node(u)
if u in confirmed and v in confirmed:
T.add_edge(u, v, weight=G[u][v]['weight'])
G_copy.remove_edge(u, v)
G.remove_node(v)
changed = True
if changed:
findChain(G)
def remove(copy, G_copy, k):
nonlocal min_dist
nonlocal minT
has_valid = False
for c in itertools.combinations(G_copy.edges(), k):
temp = copy.copy()
for e in c:
u, v = e[0], e[1]
if copy.degree(u) == 1:
copy.remove_node(u)
elif copy.degree(v) == 1:
copy.remove_node(v)
else:
copy.remove_edge(u, v)
if is_valid_network(G, copy):
has_valid = True
if average_pairwise_distance_fast(copy) < min_dist:
min_dist = average_pairwise_distance_fast(copy)
minT = copy.copy()
elif nx.is_dominating_set(G, copy.nodes()) and nx.is_connected(copy):
has_valid = True
copy = temp
if not has_valid:
return
remove(copy, G_copy, k + 1)
# if copy.number_of_nodes() == 1:
# if is_valid_network(G, copy):
# minT = copy
# return
# for e in G_copy.edges():
# if e not in copy.edges():
# continue
# u, v = e[0], e[1]
# if copy.degree(u) == 1:
# if u in confirmed:
# continue
# copy.remove_node(u)
# elif copy.degree(v) == 1:
# if v in confirmed:
# continue
# copy.remove_node(v)
# else:
# copy.remove_edge(u, v)
# if is_valid_network(G, copy):
# if average_pairwise_distance_fast(copy) < min_dist:
# min_dist = average_pairwise_distance_fast(copy)
# minT = copy.copy()
# remove(copy, G_copy)
# elif nx.is_dominating_set(G, copy.nodes) and nx.is_connected(copy):
# remove(copy, G_copy)
# if u not in copy.nodes():
# copy.add_node(u)
# elif v not in copy.nodes():
# copy.add_node(v)
# copy.add_edge(u, v, weight=G[u][v]['weight'])
# minT = min(list_of_trees, key=lambda t: average_pairwise_distance_fast(t))
confirmed = []
T = nx.Graph()
G_copy = G.copy()
findChain(G.copy())
if T.number_of_nodes() != 0 and is_valid_network(G, T):
min_dist = average_pairwise_distance_fast(T)
minT = T.copy()
else:
min_dist = average_pairwise_distance_fast(G)
minT = G.copy()
# for v in G.nodes():
# if G.degree(v) == 1:
# confirmed.append(list(G.neighbors(v))[0])
# remove(G.copy())
# T = nx.Graph()
remove(G.copy(), G_copy, 1)
return minT
def solve(G):
"""
Args:
G: networkx.Graph
Returns:
T: networkx.Graph
"""
def prune(g):
nonlocal min_T
copy = g.copy()
if g.number_of_edges() == 0:
min_T = g
return
e = random.choice(list(g.edges()))
if copy.degree(e[0]) == 1:
copy.remove_node(e[0])
elif copy.degree(e[1]) == 1:
copy.remove_node(e[1])
else:
copy.remove_edge(e[0], e[1])
if is_valid_network(G, copy):
# d = average_pairwise_distance_fast(copy)
# min_dist = average_pairwise_distance_fast(min_T)
# if d < min_dist:
# min_T = copy.copy()
prune(copy)
elif nx.is_connected(copy) and nx.is_dominating_set(G, copy):
prune(copy)
# Special case for one central node
for node in G.nodes():
if G.degree(node) == G.number_of_nodes() - 1 and not G.has_edge(node, node):
T = nx.Graph()
T.add_node(node)
return T
# added: weight <- weight - degree, to let MST choose higher-degree nodes
G_copy = G.copy()
for edge in G_copy.edges():
u, v = edge[0], edge[1]
G_copy[u][v]['weight'] /= (G_copy.degree(u) + G_copy.degree(v)) / 2
G_copy[u][v]['weight'] *= (nx.eccentricity(G, u) + nx.eccentricity(G, v)) / 2
G_copy[u][v]['weight'] /= np.exp(nx.edge_betweenness_centrality(G, k=8, weight='weight')[edge])
G_copy[u][v]['weight'] *= random.uniform(0.2, 3.8)
# T = nx.Graph()
# all_shortest_path_lengths = dict(nx.shortest_path_length(G, weight='weight'))
# all_shortest_paths = nx.shortest_path(G, weight='weight')
# average_shortest_path_lengths = {}
# for v in all_shortest_path_lengths.keys():
# average_shortest_path_lengths[v] = sum([all_shortest_path_lengths[v][u] for u in G.nodes()]) / (
# G.number_of_nodes() - 1)
# root = min(average_shortest_path_lengths, key=lambda x: average_shortest_path_lengths[x])
# T.add_node(root)
# G_copy = G.copy()
# G_copy.remove_node(root)
# while not is_valid_network(G, T):
# average_distances = {}
# corresponding_edge = {}
# for node in T.nodes():
# for adj in G.neighbors(node):
# if adj in T.nodes(): continue
# if adj not in average_distances.keys():
# average_distances[adj] = (sum(
# [all_shortest_path_lengths[adj][t] for t in T.nodes()]) / T.number_of_nodes() +
# G[node][adj]['weight'])
# corresponding_edge[adj] = (node, adj)
# else:
# temp = (sum(
# [all_shortest_path_lengths[adj][t] for t in T.nodes()]) / T.number_of_nodes() +
# G[node][adj]['weight'])
# if average_distances[adj] > temp:
# average_distances[adj] = temp
# corresponding_edge[adj] = (node, adj)
# next = min(average_distances.keys(), key=lambda x: average_distances[x])
# T.add_node(next)
# G_copy.remove_node(next)
# T.add_edge(corresponding_edge[next][0], corresponding_edge[next][1],
# weight=G[corresponding_edge[next][0]][corresponding_edge[next][1]]['weight'])
# min_T = T.copy()
T = nx.minimum_spanning_tree(G_copy)
for edge in T.edges.data():
u, v = edge[0], edge[1]
edge[2]['weight'] = G[u][v]['weight']
min_T = T.copy()
if T.number_of_nodes() == 1:
return T
elif T.number_of_nodes() == 2:
node = list(T.nodes)[0]
T.remove_node(node)
return T
else:
# for i in range(100):
# prune(T.copy())
# for v in G.nodes():
# if nx.eccentricity(G, v, all_shortest_path_lengths) / G.number_of_nodes() < dist:
# T.add_node(v)
# edge_list = [(u, v) for u in T.nodes() if G.has_edge(u, v)]
# r = random.randint(0, len(edge_list))
# edges_to_add = random.sample(edge_list, r)
# for e in edge_list:
# if G[e[0]][e[1]]['weight'] < dist:
# edges_to_add.append(e)
# for e in edges_to_add:
# T.add_edge(e[0], e[1], weight=G[e[0]][e[1]]['weight'])
# # Add some edges with lower weights
# all_shortest_path_lengths = dict(nx.shortest_path_length(G, weight='weight'))
# all_shortest_paths = nx.shortest_path(G, weight='weight')
# dist = average_pairwise_distance_fast(T)
# min_T = T.copy()
# for i in range(100):
# T = min_T.copy()
# edge_list = list(G.edges())
# random.shuffle(edge_list)
# for e in edge_list:
# if e in T.edges(): continue
# copy = T.copy()
# copy.add_edge(e[0], e[1], weight=G[e[0]][e[1]]['weight'])
# if is_valid_network(G, copy):
# if average_pairwise_distance_fast(T) > average_pairwise_distance_fast(copy):
# T = copy.copy()
# else: break
# if average_pairwise_distance_fast(T) < average_pairwise_distance_fast(min_T):
# min_T = T.copy()
def findChain(G):
nonlocal confirmed
nonlocal G_copy
changed = False
nodes = [n for n in G.nodes()]
for v in nodes:
if G.degree(v) == 1:
u = list(G.neighbors(v))[0]
confirmed.append(u)
if u in confirmed and v in confirmed:
T.add_edge(u, v, weight=G[u][v]['weight'])
G_copy.remove_edge(u, v)
G.remove_node(v)
changed = True
if changed:
findChain(G)
confirmed = []
G_copy = G.copy()
findChain(G.copy())
for i in range(100):
copy = min_T.copy()
while is_valid_network(G, copy):
if copy.number_of_edges() == 1:
if utils.average_pairwise_distance_fast(copy) < utils.average_pairwise_distance_fast(min_T):
min_T = copy.copy()
break
T = copy.copy()
edge = random.choices(list(T.edges()))[0]
if T.degree(edge[0]) == 1:
copy.remove_node(edge[0])
elif T.degree(edge[1]) == 1:
copy.remove_node(edge[1])
else:
copy.remove_edge(edge[0], edge[1])
if len(list(copy.nodes)) == 0:
return T
if is_valid_network(G, copy):
if utils.average_pairwise_distance_fast(copy) < utils.average_pairwise_distance_fast(min_T):
min_T = copy.copy()
# prune(T)
# added
# min_T.remove_edge(20, 21)
# min_T.add_edge(13, 17)
return min_T
# TODO: your code here!
# Here's an example of how to run your solver.
# Usage: python3 solver.py test.in
if __name__ == '__main__':
# input_folder_path = 'inputs'
# for input_file in os.listdir(input_folder_path):
# print(input_file)
# full_path = os.path.join(input_folder_path, input_file)
# G = read_input_file(full_path)
# # total = sum([1 for n in G.nodes() if G.degree(n) <= 2])
# # leaves = sum([1 for n in G.nodes() if G.degree(n) < 2])
# # if total >= 15 and G.number_of_nodes() <= 25 and leaves <= 12:
# # T = bruteforce(G)
# # else:
# Tree_list = []
# for i in range(10):
# Tree_list.append(solve(G))
# T = min(Tree_list, key= lambda t: average_pairwise_distance_fast(t))
# assert is_valid_network(G, T), "T is not a valid network of G."
# # Compare previous result with new result, update if improvement seen
# old = read_output_file('outputs/' + input_file[:-2] + 'out', G)
# dist_old = average_pairwise_distance_fast(old)
# dist_new = average_pairwise_distance_fast(T)
# print("Old Average pairwise distance: {}".format(dist_old))
# print("New Average pairwise distance: {}".format(dist_new))
# if dist_old > dist_new:
# write_output_file(T, 'outputs/' + input_file[:-2] + 'out')
file_list = "medium-242, medium-239, medium-238, medium-237, medium-233, medium-232, medium-230"
files = file_list.split(', ')
for file in files:
print(file)
path = 'inputs/' + file + '.in'
# path = 'inputs/small-4.in'
G = read_input_file(path)
Tree_list = []
timeout = time.time() + 60
while time.time() < timeout:
Tree_list.append(solve(G))
T = min(Tree_list, key=lambda t: average_pairwise_distance_fast(t))
# Added: if more than 15 nodes with degree <= 2
# total = sum([1 for n in G.nodes() if G.degree(n) <= 2])
# leaves = sum([1 for n in G.nodes() if G.degree(n) < 2])
# if total >= 15 and G.number_of_nodes() <= 25 and leaves <= 12:
# T = bruteforce(G)
# else:
# T = solve(G)
# fig = plt.figure(figsize=(20, 30))
# fig.add_subplot(211)
# pos = nx.circular_layout(G)
# labels = nx.get_edge_attributes(G, 'weight')
# nx.draw_networkx(G, pos=pos, node_color='yellow')
# nx.draw_networkx(G.edge_subgraph(T.edges()), pos=pos, node_color='red', edge_color='red')
# # nx.draw_networkx(T, pos=pos, node_color='blue')
# nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)
assert is_valid_network(G, T), "T is not a valid network of G."
# Compare previous result with new result, update if improvement seen
old = read_output_file('outputs/' + path[7:-2] + 'out', G)
dist_old = average_pairwise_distance_fast(old)
dist_new = average_pairwise_distance_fast(T)
print("Old Average pairwise distance: {}".format(dist_old))
print("New Average pairwise distance: {}".format(dist_new))
if dist_old > dist_new:
write_output_file(T, 'outputs/' + path[7:-2] + 'out')