Pure implementation of generating the first solution for the Tabu search to start, with the redundant resolution strategy. That means that we start from the starting node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node (let's assume is node 'c'), then
(path, dict_of_neighbours)
| 72 | |
| 73 | |
| 74 | def generate_first_solution(path, dict_of_neighbours): |
| 75 | """ |
| 76 | Pure implementation of generating the first solution for the Tabu search to start, |
| 77 | with the redundant resolution strategy. That means that we start from the starting |
| 78 | node (e.g. node 'a'), then we go to the city nearest (lowest distance) to this node |
| 79 | (let's assume is node 'c'), then we go to the nearest city of the node 'c', etc. |
| 80 | till we have visited all cities and return to the starting node. |
| 81 | |
| 82 | :param path: The path to the .txt file that includes the graph (e.g.tabudata2.txt) |
| 83 | :param dict_of_neighbours: Dictionary with key each node and value a list of lists |
| 84 | with the neighbors of the node and the cost (distance) for each neighbor. |
| 85 | :return first_solution: The solution for the first iteration of Tabu search using |
| 86 | the redundant resolution strategy in a list. |
| 87 | :return distance_of_first_solution: The total distance that Travelling Salesman |
| 88 | will travel, if he follows the path in first_solution. |
| 89 | """ |
| 90 | |
| 91 | with open(path) as f: |
| 92 | start_node = f.read(1) |
| 93 | end_node = start_node |
| 94 | |
| 95 | first_solution = [] |
| 96 | |
| 97 | visiting = start_node |
| 98 | |
| 99 | distance_of_first_solution = 0 |
| 100 | while visiting not in first_solution: |
| 101 | minim = 10000 |
| 102 | for k in dict_of_neighbours[visiting]: |
| 103 | if int(k[1]) < int(minim) and k[0] not in first_solution: |
| 104 | minim = k[1] |
| 105 | best_node = k[0] |
| 106 | |
| 107 | first_solution.append(visiting) |
| 108 | distance_of_first_solution = distance_of_first_solution + int(minim) |
| 109 | visiting = best_node |
| 110 | |
| 111 | first_solution.append(end_node) |
| 112 | |
| 113 | position = 0 |
| 114 | for k in dict_of_neighbours[first_solution[-2]]: |
| 115 | if k[0] == start_node: |
| 116 | break |
| 117 | position += 1 |
| 118 | |
| 119 | distance_of_first_solution = ( |
| 120 | distance_of_first_solution |
| 121 | + int(dict_of_neighbours[first_solution[-2]][position][1]) |
| 122 | - 10000 |
| 123 | ) |
| 124 | return first_solution, distance_of_first_solution |
| 125 | |
| 126 | |
| 127 | def find_neighborhood(solution, dict_of_neighbours): |