-
Notifications
You must be signed in to change notification settings - Fork 5
/
greedy.py
76 lines (58 loc) · 2.26 KB
/
greedy.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
# Placeholder for the naive greedy heuristic planned in the initial proposal
import networkx as nx
def check_terminals_connected(tree,terminals):
num_terminals = len(terminals)
for i in range(0,num_terminals):
for j in range(i+1,num_terminals):
try:
paths = list(nx.all_simple_paths(tree,terminals[i],terminals[j]))
if paths is None or len(paths)==0:
return False
except:
return False
return True
def approximate_steiner(graph,terminals):
steiner_tree = nx.Graph()
for terminal in terminals:
steiner_tree.add_node(terminal)
nodes = list(graph.nodes)
weights = nx.get_node_attributes(graph,'weight')
steiner_nodes = list()
for node in nodes:
if node not in terminals:
n = dict()
n['node'] = node
n['weight'] = weights[node]
steiner_nodes.append(n)
num_terminals = len(terminals)
# Add edges between terminals if any
for i in range(0,num_terminals):
for j in range(i+1,num_terminals):
if graph.has_edge(terminals[i],terminals[j]):
steiner_tree.add_edge(terminals[i],terminals[j])
if check_terminals_connected(steiner_tree,terminals):
return steiner_tree
# Sort non-terminal nodes by weight
steiner_nodes.sort(key=lambda x:x['weight'])
for steiner_node in steiner_nodes:
current_nodes = list(steiner_tree.nodes)
steiner_tree.add_node(steiner_node['node'])
# Add any edges between the selected node and existing nodes
for current_node in current_nodes:
if graph.has_edge(steiner_node['node'],current_node):
steiner_tree.add_edge(steiner_node['node'],current_node)
if check_terminals_connected(steiner_tree,terminals):
break
# Remove cycles if any
while True:
try:
cycle = nx.find_cycle(steiner_tree)
edge = cycle[0]
steiner_tree.remove_edge(edge[0],edge[1])
except:
break
steiner_cost = 0
weights = nx.get_node_attributes(graph,'weight')
for node in list(steiner_tree.nodes):
steiner_cost = steiner_cost + weights[node]
return steiner_tree, steiner_cost