-
Notifications
You must be signed in to change notification settings - Fork 0
/
tsp.py
196 lines (141 loc) · 6.3 KB
/
tsp.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
# -*- coding: utf-8 -*-
"""tsp.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1l01IO8VL5nJsIGTy3eEHkjA6tD741abm
"""
!pip install networkx
import networkx as nx
import matplotlib.pyplot as plt
import time
import numpy as np
import pandas as pd
"""
---
## Função para plotar grafos no plano cartesiano
"""
def show_graph(graph):
pos = nx.get_node_attributes(graph, "pos")
fig, ax = plt.subplots()
for i in graph.nodes():
ax.annotate(i, (graph.nodes[i]['pos'][0], graph.nodes[i]['pos'][1]), fontsize=15)
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True)
nx.draw_networkx_edges(graph, pos, alpha=0.4, ax=ax)
nx.draw_networkx_nodes(graph, pos, node_size=100, cmap=plt.cm.Reds_r,)
plt.show()
"""
## Twice Around The Tree"""
def get_cost(graph, order):
cost = 0
for i in range(0, len(order) - 1):
cost += graph[order[i]][order[i+1]]['weight']
return cost + graph[order[0]][order[len(order) - 1]]['weight']
def twice_around_the_tree(graph):
mst = nx.minimum_spanning_tree(graph, weight = 'weight', algorithm="prim")
order = list(nx.dfs_preorder_nodes(mst, 0))
cost = get_cost(graph, order)
return cost
"""## Algoritmo de Christofides"""
def christofides(graph):
mst = nx.minimum_spanning_tree(graph, weight = 'weight', algorithm="prim") # Create a minimum spanning tree T of G.
i = graph.subgraph(nodes_odd_degree) # I is the induced subgraph given by the vertices from O
matching = nx.min_weight_matching(i, maxcardinality = True) # Find a minimum-weight perfect matching M in I
for e in matching:
weight = graph[e[0]][e[1]]['weight']
h = nx.MultiGraph(mst)
h.add_edges_from(matching) # Combine the edges of M and T to form a connected multigraph H in which each vertex has even degree.
order = list(nx.dfs_preorder_nodes(h, 0))
cost = get_cost(graph, order)
return cost
"""## Branch and Bound
"""
def bnb_recursive(graph, cbound, cweight, level, cpath, closest, visited, res):
if level == graph.number_of_nodes():
if cpath[level - 1] != cpath[0]:
cres = cweight + graph[cpath[level-1]][cpath[0]]['weight']
if cres < res: res = cres
return res
for v in graph.nodes():
if cpath[level-1] != v and visited[v] == False:
temp = cbound;
cweight += graph[cpath[level-1]][v]['weight'];
if level == 1: cbound -= ((closest[cpath[level-1]][0] + closest[v][0])/2)
else: cbound -= ((closest[cpath[level-1]][1] + closest[v][0])/2)
if (cbound + cweight) < res:
cpath[level], visited[v] = v, True
res = bnb_recursive(graph, cbound, cweight, level+1, cpath, closest, visited, res)
cweight -= graph[cpath[level-1]][v]['weight']
cbound = temp;
visited = [False for i in graph.nodes()]
for i in range(0,level): visited[cpath[i]] = True;
return res
def branch_and_bound(graph):
cbound, closest = 0, []
cpath, visited = [-1 for i in range(0, graph.number_of_nodes()+1)], [False for i in graph.nodes()]
visited[0], cpath[0] = True, 0
for v in graph.nodes():
min_weight_neighbors = sorted(graph[v].items(), key=lambda e: e[1]["weight"] if e[1]["weight"] != 0 else 1000000000)[:2]
closest.append([min_weight_neighbors[0][1]['weight'], min_weight_neighbors[1][1]['weight']])
cbound += (min_weight_neighbors[0][1]['weight']+ min_weight_neighbors[1][1]['weight'])/2
return bnb_recursive(graph, cbound, 0, 1, cpath, closest, visited, np.Inf)
"""## Gerador do grafo geométrico """
def distance(v1, v2, metric):
if metric == 'euclidean':
return ((v1[0] - v2[0])**2 + (v1[1] - v2[1])**2)**(1/2)
else:
return abs(v1[0] - v2[0]) + abs(v1[1] - v2[1])
def generate_graph(metric, amount_of_nodes):
graph = nx.soft_random_geometric_graph(n = amount_of_nodes, radius = 10, dim = 2, p_dist = lambda dist: 1, seed = 5)
for i in graph.nodes():
for j in graph.nodes():
if i != j:
dist = distance(graph.nodes[i]['pos'], graph.nodes[j]['pos'], metric)
graph.add_edge(i, j, weight = dist)
return graph
"""## Gerador de Instâncias"""
def instance_maker(algorithm):
df_cost, df_time = {}, {}
for i in range (4, 11):
graph_euclidean, graph_manhattan = generate_graph('euclidean', 2**i), generate_graph('manhattan', 2**i)
if algorithm == 'Twice Around The Tree':
init = time.time()
cost_e = twice_around_the_tree(graph_euclidean)
period_e = time.time() - init
init = time.time()
cost_m = twice_around_the_tree(graph_manhattan)
period_m = time.time() - init
elif algorithm == 'Christofides':
init = time.time()
cost_e = christofides(graph_euclidean)
period_e = time.time() - init
init = time.time()
cost_m = christofides(graph_manhattan)
period_m = time.time() - init
else:
if i >= 5:
df_cost[2**i], df_time[2**i] = ["NA", "NA"], ["NA", "NA"]
continue
else:
init = time.time()
cost_e = branch_and_bound(graph_euclidean)
period_e = time.time() - init
init = time.time()
cost_m = branch_and_bound(graph_manhattan)
period_m = time.time() - init
df_cost[2**i], df_time[2**i] = ["{:.5f}".format(cost_e), "{:.5f}".format(cost_m)], ["{:.5f}".format(period_e), "{:.5f}".format(period_m)]
print('\n', algorithm, 2**i, 'nodes:')
print('Euclidean distance:', cost_e)
print('Manhattan distance:', cost_m)
return df_cost, df_time
def main():
tat_cost, tat_time = instance_maker('Twice Around The Tree')
print('----------------------------------------------------------------------------------------')
ch_cost, ch_time = instance_maker('Christofides')
print('----------------------------------------------------------------------------------------')
bab_cost, bab_time = instance_maker('Branch and Bound')
print('----------------------------------------------------------------------------------------')
cost = pd.DataFrame({'Twice Around The Tree':tat_cost, 'Christofides':ch_cost, 'Branch and Bound':bab_cost})
time = pd.DataFrame({'Twice Around The Tree':tat_time, 'Christofides':ch_time, 'Branch and Bound':bab_time})
cost.to_csv("costs.csv")
time.to_csv("times.csv")
main()