forked from trevlovett/Python-Ant-Colony-TSP-Solver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anttsp.py
57 lines (47 loc) · 1.67 KB
/
anttsp.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
from antcolony import AntColony
from antgraph import AntGraph
import pickle
import sys
import traceback
#default
num_nodes = 10
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1]:
num_nodes = int(sys.argv[1])
if num_nodes <= 10:
num_ants = 20
num_iterations = 12
num_repetitions = 1
else:
num_ants = 28
num_iterations = 20
num_repetitions = 1
stuff = pickle.load(open("citiesAndDistances.pickled", "r"))
cities = stuff[0]
cost_mat = stuff[1]
if num_nodes < len(cost_mat):
cost_mat = cost_mat[0:num_nodes]
for i in range(0, num_nodes):
cost_mat[i] = cost_mat[i][0:num_nodes]
print cost_mat
try:
graph = AntGraph(num_nodes, cost_mat)
best_path_vec = None
best_path_cost = sys.maxint
for i in range(0, num_repetitions):
graph.reset_tau()
ant_colony = AntColony(graph, num_ants, num_iterations)
ant_colony.start()
if ant_colony.best_path_cost < best_path_cost:
best_path_vec = ant_colony.best_path_vec
best_path_cost = ant_colony.best_path_cost
print "\n------------------------------------------------------------"
print " Results "
print "------------------------------------------------------------"
print "\nBest path = %s" % (best_path_vec,)
for node in best_path_vec:
print cities[node] + " ",
print "\nBest path cost = %s\n" % (best_path_cost,)
except Exception, e:
print "exception: " + str(e)
traceback.print_exc()