-
Notifications
You must be signed in to change notification settings - Fork 1
/
ant_colony.py
155 lines (137 loc) · 6.41 KB
/
ant_colony.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
import numpy as np
from copy import deepcopy
import matplotlib.pyplot as plt
from time import time
class VPR:
def __init__(self, n_trucks, dimension, capacity, demands, adj_matrix):
self.n_trucks = n_trucks
self.dimension = dimension
self.capacity = capacity
self.demands = demands
self.adj_matrix = adj_matrix
self.adj_matrix_sum = adj_matrix.sum()
self.final_cost = self.adj_matrix_sum
self.final_sol = None
self.epochs = None
self.n_ants = None
self.alpha = None
self.beta = None
self.rho = None
self.init_pheromone_value = None
self.pheromone_map = None
self.raw_prob_matrix = None
self.tabu = None
self.tabu_sum = None
self.capacity_left = None
def get_probality(self, raw_prob_list):
prob_list = raw_prob_list/raw_prob_list.sum()
return prob_list
def get_next_vertex(self, pos):
potential = deepcopy(self.tabu)
potential_sum = self.tabu_sum
while potential_sum < self.dimension:
raw_prob_list = deepcopy(self.raw_prob_matrix[pos]) * potential
next_vertex = np.random.choice(np.arange(0, self.dimension), p=self.get_probality(raw_prob_list))
if self.demands[next_vertex] <= self.capacity_left:
return next_vertex
potential[next_vertex] = 0
potential_sum += 1
return 0
def local_update(self, i, j):
self.pheromone_map[i, j] += self.rho * self.init_pheromone_value / self.adj_matrix[i, j]
self.pheromone_map[j, i] = self.pheromone_map[i, j]
self.raw_prob_matrix[i, j] = self.raw_prob_matrix[j, i] = (self.pheromone_map[i, j] ** self.alpha) * \
((1 / self.adj_matrix[i, j]) ** self.beta)
def global_update(self, best_solution, best_cost):
for one_path in best_solution:
for i in range(len(one_path)-1):
self.pheromone_map[one_path[i], one_path[i + 1]] += self.rho * self.capacity / best_cost
self.pheromone_map[one_path[i + 1], one_path[i]] = self.pheromone_map[one_path[i], one_path[i + 1]]
self.raw_prob_matrix[one_path[i], one_path[i + 1]] = \
self.raw_prob_matrix[one_path[i + 1], one_path[i]] = \
(self.pheromone_map[one_path[i], one_path[i + 1]] ** self.alpha) * \
((1 / self.adj_matrix[one_path[i], one_path[i + 1]]) ** self.beta)
def get_cost(self, solution):
current_cost = 0
for i in range(len(solution) - 1):
current_cost += self.adj_matrix[solution[i], solution[i + 1]]
return current_cost
def plot_function(self):
box = {'facecolor': 'white',
'edgecolor': 'black',
'boxstyle': 'round'}
plt.figure(figsize=(9.5, 6))
plt.text(self.epochs - 18, self.show_epoch[4] - 60,
f'cost={round(self.final_cost, 2)}, \n'
f'epochs={self.epochs}, \n'
f'n_ants={self.n_ants}, \n'
f'alpha={self.alpha}, \n'
f'beta={self.beta}, \n'
f'p={self.rho}, \n'
f'init_ph={self.init_pheromone_value}',
bbox=box, color='black', fontsize=12)
plt.plot(np.arange(self.epochs), self.show_cost, 'r')
plt.plot(np.arange(self.epochs), self.show_epoch, 'k')
plt.grid()
plt.title(f'Fitness function for A-n{self.dimension}-k{self.n_trucks}', fontsize=18)
plt.xlabel('epoch')
plt.ylabel('cost')
plt.show()
def compute(self, epochs=100, n_ants=50, alpha=1.5, beta=0.3, rho=0.95, init_pheromone=1000):
self.epochs = epochs
self.n_ants = n_ants
self.alpha = alpha
self.beta = beta
self.rho = rho
self.init_pheromone_value = init_pheromone
self.pheromone_map = np.full(shape=(self.dimension, self.dimension), fill_value=self.init_pheromone_value)
np.fill_diagonal(self.pheromone_map, 0)
np.fill_diagonal(self.adj_matrix, 0.1)
self.raw_prob_matrix = (self.pheromone_map ** self.alpha) * ((1 / self.adj_matrix) ** self.beta)
np.fill_diagonal(self.adj_matrix, 0)
self.show_epoch = []
self.show_cost = []
for epoch in range(self.epochs):
time_s = time()
best_solution = None
best_cost = self.adj_matrix_sum
for ant in range(self.n_ants):
current_state = 0
solutions = []
one_path_solution = [0]
self.capacity_left = self.capacity
self.tabu = np.ones(self.dimension)
self.tabu[0] = 0
self.tabu_sum = 1
while self.tabu_sum < self.dimension:
next_state = self.get_next_vertex(current_state)
if next_state == 0:
one_path_solution.append(0)
solutions.append(one_path_solution)
one_path_solution = [0]
current_state = 0
self.capacity_left = self.capacity
continue
one_path_solution.append(next_state)
self.capacity_left -= self.demands[next_state]
self.local_update(current_state, next_state)
current_state = next_state
self.tabu[current_state] = 0
self.tabu_sum += 1
one_path_solution.append(0)
solutions.append(one_path_solution)
cost = sum([self.get_cost(sol) for sol in solutions])
assert all(np.unique(np.hstack(solutions)) == np.arange(self.dimension))
if cost < best_cost:
best_cost = cost
best_solution = solutions
self.global_update(best_solution, best_cost)
self.show_epoch.append(best_cost)
if self.final_cost > best_cost:
self.final_cost = best_cost
self.final_sol = best_solution
self.show_cost.append(self.final_cost)
else:
self.show_cost.append(self.show_cost[-1])
# print(f'Epoch: {epoch} | time: {round(time() - time_s, 4)}| best cost: {best_cost}')
self.final_sol = [(np.array(x) + 1).tolist() for x in self.final_sol]