MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / tabu_search

Function tabu_search

searches/tabu_search.py:188–250  ·  view source on GitHub ↗

Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in Python. :param first_solution: The solution for the first iteration of Tabu search using the redundant resolution strategy in a list. :param distance_of_first_solution: The total distance that

(
    first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
)

Source from the content-addressed store, hash-verified

186
187
188def tabu_search(
189 first_solution, distance_of_first_solution, dict_of_neighbours, iters, size
190):
191 """
192 Pure implementation of Tabu search algorithm for a Travelling Salesman Problem in
193 Python.
194
195 :param first_solution: The solution for the first iteration of Tabu search using
196 the redundant resolution strategy in a list.
197 :param distance_of_first_solution: The total distance that Travelling Salesman will
198 travel, if he follows the path in first_solution.
199 :param dict_of_neighbours: Dictionary with key each node and value a list of lists
200 with the neighbors of the node and the cost (distance) for each neighbor.
201 :param iters: The number of iterations that Tabu search will execute.
202 :param size: The size of Tabu List.
203 :return best_solution_ever: The solution with the lowest distance that occurred
204 during the execution of Tabu search.
205 :return best_cost: The total distance that Travelling Salesman will travel, if he
206 follows the path in best_solution ever.
207 """
208 count = 1
209 solution = first_solution
210 tabu_list = []
211 best_cost = distance_of_first_solution
212 best_solution_ever = solution
213
214 while count <= iters:
215 neighborhood = find_neighborhood(solution, dict_of_neighbours)
216 index_of_best_solution = 0
217 best_solution = neighborhood[index_of_best_solution]
218 best_cost_index = len(best_solution) - 1
219
220 found = False
221 while not found:
222 i = 0
223 while i < len(best_solution):
224 if best_solution[i] != solution[i]:
225 first_exchange_node = best_solution[i]
226 second_exchange_node = solution[i]
227 break
228 i = i + 1
229
230 if [first_exchange_node, second_exchange_node] not in tabu_list and [
231 second_exchange_node,
232 first_exchange_node,
233 ] not in tabu_list:
234 tabu_list.append([first_exchange_node, second_exchange_node])
235 found = True
236 solution = best_solution[:-1]
237 cost = neighborhood[index_of_best_solution][best_cost_index]
238 if cost < best_cost:
239 best_cost = cost
240 best_solution_ever = solution
241 else:
242 index_of_best_solution = index_of_best_solution + 1
243 best_solution = neighborhood[index_of_best_solution]
244
245 if len(tabu_list) >= size:

Callers 1

mainFunction · 0.85

Calls 3

find_neighborhoodFunction · 0.85
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected