forked from ppoffice/ant-colony-tsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
33 lines (27 loc) · 920 Bytes
/
main.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
import math
from aco import ACO, Graph
from plot import plot
def distance(city1: dict, city2: dict):
return math.sqrt((city1['x'] - city2['x']) ** 2 + (city1['y'] - city2['y']) ** 2)
def main():
cities = []
points = []
with open('./data/chn31.txt') as f:
for line in f.readlines():
city = line.split(' ')
cities.append(dict(index=int(city[0]), x=int(city[1]), y=int(city[2])))
points.append((int(city[1]), int(city[2])))
cost_matrix = []
rank = len(cities)
for i in range(rank):
row = []
for j in range(rank):
row.append(distance(cities[i], cities[j]))
cost_matrix.append(row)
aco = ACO(10, 100, 1.0, 10.0, 0.5, 10, 2)
graph = Graph(cost_matrix, rank)
path, cost = aco.solve(graph)
print('cost: {}, path: {}'.format(cost, path))
plot(points, path)
if __name__ == '__main__':
main()