Пример #1
0
def findMST(G):    
    F = returnTree(G)
    #now we check if F is a tree (there are no cycles)
    #TO ADD: also check if every node except the root node has exactly one edge entering! 
    if is_tree(F):
        return F
    else:
        C = find_cycle(F)
        G_prime = contract_graph(G,C)
        T_prime = findMST(G_prime)
        #if is_tree(T_prime):
        T = extract_graph(T_prime,G_prime,C)
        return T
Пример #2
0
    test_graph.node[terminal]['weight'] = 0
    mapping[terminal] = "t"+str(terminal)


for node in list(test_graph.nodes):
    if node not in terminals:
        mapping[node] = "S"+str(node)

terminals = ["t"+str(x) for x in terminals]

test_graph = nx.relabel_nodes(test_graph,mapping)
plt.figure()
nx.draw(test_graph,with_labels=True)
#plt.show()
print('The terminals are '+str(terminals))
weights = nx.get_node_attributes(test_graph,'weight')
steiner_tree,steiner_cost = nwst.approximate_steiner(test_graph,terminals,weights)
plt.figure()
nx.draw(steiner_tree,with_labels=True)
plt.show()

if t.is_tree(steiner_tree):
    print("Is a tree")
print(steiner_cost)
write_dot(steiner_tree,"steiner.dot")
print("Testing through ILP")
exact_solver = ilp.NWSTLPSolver(test_graph,terminals)
exact_solver.formulate_problem()
optimal_cost = exact_solver.solve_ilp()
print("Approximation ratio is "+str(steiner_cost/optimal_cost)+" which is within the bound "+str(2*math.log(len(terminals))))