Choose the next city for ants >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={0: [0, 0]}, ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0) ({1: [2, 2]}, {}) >>> city_select(pheromone=[], current_city={0: [0,0]}, ... unvisited_c
(
pheromone: list[list[float]],
current_city: dict[int, list[int]],
unvisited_cities: dict[int, list[int]],
alpha: float,
beta: float,
)
| 166 | |
| 167 | |
| 168 | def city_select( |
| 169 | pheromone: list[list[float]], |
| 170 | current_city: dict[int, list[int]], |
| 171 | unvisited_cities: dict[int, list[int]], |
| 172 | alpha: float, |
| 173 | beta: float, |
| 174 | ) -> tuple[dict[int, list[int]], dict[int, list[int]]]: |
| 175 | """ |
| 176 | Choose the next city for ants |
| 177 | >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={0: [0, 0]}, |
| 178 | ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0) |
| 179 | ({1: [2, 2]}, {}) |
| 180 | >>> city_select(pheromone=[], current_city={0: [0,0]}, |
| 181 | ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0) |
| 182 | Traceback (most recent call last): |
| 183 | ... |
| 184 | IndexError: list index out of range |
| 185 | >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={}, |
| 186 | ... unvisited_cities={1: [2, 2]}, alpha=1.0, beta=5.0) |
| 187 | Traceback (most recent call last): |
| 188 | ... |
| 189 | StopIteration |
| 190 | >>> city_select(pheromone=[[1.0, 1.0], [1.0, 1.0]], current_city={0: [0, 0]}, |
| 191 | ... unvisited_cities={}, alpha=1.0, beta=5.0) |
| 192 | Traceback (most recent call last): |
| 193 | ... |
| 194 | IndexError: list index out of range |
| 195 | """ |
| 196 | probabilities = [] |
| 197 | for city, value in unvisited_cities.items(): |
| 198 | city_distance = distance(value, next(iter(current_city.values()))) |
| 199 | probability = (pheromone[city][next(iter(current_city.keys()))] ** alpha) * ( |
| 200 | (1 / city_distance) ** beta |
| 201 | ) |
| 202 | probabilities.append(probability) |
| 203 | |
| 204 | chosen_city_i = random.choices( |
| 205 | list(unvisited_cities.keys()), weights=probabilities |
| 206 | )[0] |
| 207 | chosen_city = {chosen_city_i: unvisited_cities[chosen_city_i]} |
| 208 | del unvisited_cities[next(iter(chosen_city.keys()))] |
| 209 | return chosen_city, unvisited_cities |
| 210 | |
| 211 | |
| 212 | if __name__ == "__main__": |