Update pheromones on the route and update the best route >>> >>> pheromone_update(pheromone=[[1.0, 1.0], [1.0, 1.0]], ... cities={0: [0,0], 1: [2,2]}, pheromone_evaporation=0.7, ... ants_route=[[0, 1, 0]], q=10, best_path=[], ...
(
pheromone: list[list[float]],
cities: dict[int, list[int]],
pheromone_evaporation: float,
ants_route: list[list[int]],
q: float, # Pheromone system parameters Q, which is a constant
best_path: list[int],
best_distance: float,
)
| 113 | |
| 114 | |
| 115 | def pheromone_update( |
| 116 | pheromone: list[list[float]], |
| 117 | cities: dict[int, list[int]], |
| 118 | pheromone_evaporation: float, |
| 119 | ants_route: list[list[int]], |
| 120 | q: float, # Pheromone system parameters Q, which is a constant |
| 121 | best_path: list[int], |
| 122 | best_distance: float, |
| 123 | ) -> tuple[list[list[float]], list[int], float]: |
| 124 | """ |
| 125 | Update pheromones on the route and update the best route |
| 126 | >>> |
| 127 | >>> pheromone_update(pheromone=[[1.0, 1.0], [1.0, 1.0]], |
| 128 | ... cities={0: [0,0], 1: [2,2]}, pheromone_evaporation=0.7, |
| 129 | ... ants_route=[[0, 1, 0]], q=10, best_path=[], |
| 130 | ... best_distance=float("inf")) |
| 131 | ([[0.7, 4.235533905932737], [4.235533905932737, 0.7]], [0, 1, 0], 5.656854249492381) |
| 132 | >>> pheromone_update(pheromone=[], |
| 133 | ... cities={0: [0,0], 1: [2,2]}, pheromone_evaporation=0.7, |
| 134 | ... ants_route=[[0, 1, 0]], q=10, best_path=[], |
| 135 | ... best_distance=float("inf")) |
| 136 | Traceback (most recent call last): |
| 137 | ... |
| 138 | IndexError: list index out of range |
| 139 | >>> pheromone_update(pheromone=[[1.0, 1.0], [1.0, 1.0]], |
| 140 | ... cities={}, pheromone_evaporation=0.7, |
| 141 | ... ants_route=[[0, 1, 0]], q=10, best_path=[], |
| 142 | ... best_distance=float("inf")) |
| 143 | Traceback (most recent call last): |
| 144 | ... |
| 145 | KeyError: 0 |
| 146 | """ |
| 147 | for a in range(len(cities)): # Update the volatilization of pheromone on all routes |
| 148 | for b in range(len(cities)): |
| 149 | pheromone[a][b] *= pheromone_evaporation |
| 150 | for ant_route in ants_route: |
| 151 | total_distance = 0.0 |
| 152 | for i in range(len(ant_route) - 1): # Calculate total distance |
| 153 | total_distance += distance(cities[ant_route[i]], cities[ant_route[i + 1]]) |
| 154 | delta_pheromone = q / total_distance |
| 155 | for i in range(len(ant_route) - 1): # Update pheromones |
| 156 | pheromone[ant_route[i]][ant_route[i + 1]] += delta_pheromone |
| 157 | pheromone[ant_route[i + 1]][ant_route[i]] = pheromone[ant_route[i]][ |
| 158 | ant_route[i + 1] |
| 159 | ] |
| 160 | |
| 161 | if total_distance < best_distance: |
| 162 | best_path = ant_route |
| 163 | best_distance = total_distance |
| 164 | |
| 165 | return pheromone, best_path, best_distance |
| 166 | |
| 167 | |
| 168 | def city_select( |