1
|
|
|
|
2
|
|
|
|
3
|
|
|
import ctypes as ct |
4
|
|
|
|
5
|
|
|
from pyclustering.core.definitions import PATH_DLL_CCORE_WIN64 |
6
|
|
|
|
7
|
|
|
from pyclustering.core.definitions import ant_colony_TSP_cities |
8
|
|
|
from pyclustering.core.definitions import ant_colony_TSP_params |
9
|
|
|
from pyclustering.core.definitions import ant_colony_TSP_result |
10
|
|
|
|
11
|
|
|
import collections |
12
|
|
|
|
13
|
|
|
def ant_colony_TSP_run(cities, params): |
|
|
|
|
14
|
|
|
|
15
|
|
|
dimension = len(cities[0]) |
16
|
|
|
|
17
|
|
|
cities_coord = ant_colony_TSP_cities() |
18
|
|
|
cities_coord.size = ct.c_uint(len(cities) * dimension) |
19
|
|
|
cities_coord.dimension = ct.c_uint(dimension) |
20
|
|
|
|
21
|
|
|
cities_coord.data = (ct.c_double * cities_coord.size)(); |
22
|
|
|
for i in range(0, cities_coord.size): |
|
|
|
|
23
|
|
|
cities_coord.data[i] =cities[i // dimension][i % dimension] |
24
|
|
|
|
25
|
|
|
cities_coord = ct.pointer(cities_coord); |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
algorithm_params = ant_colony_TSP_params() |
29
|
|
|
algorithm_params.q = ct.c_double(params.q) |
30
|
|
|
algorithm_params.ro = ct.c_double(params.ro) |
31
|
|
|
algorithm_params.alpha = ct.c_double(params.alpha) |
32
|
|
|
algorithm_params.beta = ct.c_double(params.beta) |
33
|
|
|
algorithm_params.gamma = ct.c_double(params.gamma) |
34
|
|
|
algorithm_params.qinitial_pheramone = ct.c_double(params.qinitial_pheramone) |
35
|
|
|
algorithm_params.iterations = ct.c_uint(params.iterations) |
36
|
|
|
algorithm_params.count_ants_in_iteration = ct.c_uint(params.count_ants_in_iteration) |
37
|
|
|
|
38
|
|
|
algorithm_params = ct.pointer(algorithm_params) |
39
|
|
|
|
40
|
|
|
|
41
|
|
|
ccore = ct.cdll.LoadLibrary(PATH_DLL_CCORE_WIN64) |
42
|
|
|
result = ccore.ant_colony_TSP(cities_coord, algorithm_params) |
43
|
|
|
|
44
|
|
|
result = ct.cast(result, ct.POINTER(ant_colony_TSP_result))[0] |
45
|
|
|
#result = result[0] |
46
|
|
|
|
47
|
|
|
return result |
48
|
|
|
|
49
|
|
|
|
50
|
|
|
|
51
|
|
|
cities = [[0.0, 0.0], [0.0, 1.0], [0.0, 2.0], [1.0, 0.0], [1.0, 1.0], [1.0, 2.0]] |
52
|
|
|
|
53
|
|
|
params = collections.namedtuple('Params', 'q ro alpha beta gamma qinitial_pheramone iterations count_ants_in_iteration') |
54
|
|
|
params.q = 1.5; |
55
|
|
|
params.ro = 0.7 |
56
|
|
|
params.alpha = 1.0 |
57
|
|
|
params.beta = 1.0 |
58
|
|
|
params.gamma = 2.0 |
59
|
|
|
params.qinitial_pheramone = 0.1 |
60
|
|
|
params.iterations = 50 |
61
|
|
|
params.count_ants_in_iteration = 10 |
62
|
|
|
|
63
|
|
|
res = ant_colony_TSP_run(cities, params) |
64
|
|
|
|
65
|
|
|
print ("Result :") |
66
|
|
|
print (res.size) |
67
|
|
|
print (res.path_length) |
68
|
|
|
for i in range(res.size): |
69
|
|
|
print (res.cities_num[i]) |
70
|
|
|
|
71
|
|
|
|
It is generally a bad practice to shadow variables from the outer-scope. In most cases, this is done unintentionally and might lead to unexpected behavior: