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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
| from itertools import permutations import random import math from timeit import default_timer as timer from datetime import timedelta from typing import List, Tuple, Union, Callable import numpy as np from pulp import LpMaximize, LpMinimize, LpProblem, LpStatus, lpSum, LpVariable, LpBinary, LpInteger, lpDot from pulp import GLPK
from genetic_algorithm import TSPGeneticAlgorithmSolver
def idx_2d_to_1d(i: int, j: int, width: int) -> int:
return (i - 1) * width + (j - 1)
def assemble_tsp_solution(non_zero_idx: List[Tuple[int, int]]) -> List[int]:
n = len(non_zero_idx) tsp_solution = [1]
src_tgt_map = {} for idx in non_zero_idx: src_tgt_map[idx[0]] = idx[1]
src = 1 while len(tsp_solution) < n: tgt = src_tgt_map[src] tsp_solution.append(tgt) src = tgt if len(tsp_solution) == n: assert src_tgt_map[src] == 1
return tsp_solution
def verify_symmetric_tsp_solution_equality(tsp_solution_1: List[int], tsp_solution_2: List[int]) -> bool:
return (tsp_solution_1[:1] + tsp_solution_1[:0:-1] ) == tsp_solution_2 or tsp_solution_1 == tsp_solution_2
def tsp_brute_force_solver( distance_matrix: np.ndarray) -> Tuple[List[int], float]:
assert distance_matrix.ndim == 2 assert distance_matrix.shape[0] == distance_matrix.shape[1]
n = distance_matrix.shape[0]
perms = permutations(range(2, n + 1))
tsp_solution = None optimal_cost = float("inf")
for perm in perms: perm = [1] + list(perm) cost = 0 for i in range(n): j = (i + 1) % n cost += distance_matrix[perm[i] - 1][perm[j] - 1] if cost < optimal_cost: optimal_cost = cost tsp_solution = perm
return tsp_solution, optimal_cost
def tsp_mtz_integer_linear_programming_solver( distance_matrix: np.ndarray) -> Tuple[List[int], float]:
assert distance_matrix.ndim == 2 assert distance_matrix.shape[0] == distance_matrix.shape[1]
n = distance_matrix.shape[0]
distance_list = distance_matrix.flatten().tolist()
model = LpProblem(name="TSP-Problem", sense=LpMinimize)
x_variables = [] for i in range(n): for j in range(n): x_variables.append(LpVariable(name=f"x_{i+1}_{j+1}", cat=LpBinary)) u_variables = [1] + [ LpVariable(name=f"u_{i+2}", lowBound=1, upBound=n - 1, cat=LpInteger) for i in range(n - 1) ]
model += lpDot(x_variables, distance_list)
for j in range(1, n + 1): sum_exp = 0 for i in range(1, n + 1): if i != j: idx_id = idx_2d_to_1d(i=i, j=j, width=n) sum_exp += x_variables[idx_id] model += sum_exp == 1
for i in range(1, n + 1): sum_exp = 0 for j in range(1, n + 1): if j != i: idx_id = idx_2d_to_1d(i=i, j=j, width=n) sum_exp += x_variables[idx_id] model += sum_exp == 1
for i in range(2, n + 1): for j in range(2, n + 1): if i != j: idx_id = idx_2d_to_1d(i=j, j=i, width=n) model += u_variables[i - 1] - u_variables[ j - 1] + n * x_variables[idx_id] <= n - 1
status = model.solve(solver=GLPK(msg=False))
assert status == True, "Linear programming solver did not solve the problem successfully."
non_zero_idx = [] for variable in model.variables(): if variable.name.startswith("x_") and variable.value() == 1: _, i, j = variable.name.split("_") i = int(i) j = int(j) non_zero_idx.append((i, j)) assert len(non_zero_idx) == n
tsp_solution = assemble_tsp_solution(non_zero_idx=non_zero_idx)
optimal_cost = model.objective.value()
return tsp_solution, optimal_cost
def tsp_genetic_algorithm_approximate_solver( distance_matrix: np.ndarray) -> Tuple[List[int], float]: def is_convergent(cost_history: List[float], minimum_history_size: int):
if len(cost_history) < minimum_history_size:
return False
else: val = cost_history[0] for i in range(1, len(cost_history)): if cost_history[i] != val: return False
return True
population_size = 500 parent_pool_size = 100 child_pool_size = 2000 mutation_rate = 2.5e-1 minimum_cross_over_size = 3 maximum_cross_over_size = 8 minimum_convergence_iterations = 200
tsp_ga_solver = TSPGeneticAlgorithmSolver( population_size=population_size, parent_pool_size=parent_pool_size, child_pool_size=child_pool_size, distance_matrix=distance_matrix, mutation_rate=mutation_rate, minimum_cross_over_size=minimum_cross_over_size, maximum_cross_over_size=maximum_cross_over_size)
best_tsp_solution = None cost_history = []
while not is_convergent( cost_history=cost_history, minimum_history_size=minimum_convergence_iterations): tsp_ga_solver.evolve_population() best_tsp_solution = tsp_ga_solver.get_top_k_individuals(k=1)[0] best_cost = tsp_ga_solver.compute_travelling_distance( individual=best_tsp_solution) cost_history.append(best_cost) cost_history = cost_history[-minimum_convergence_iterations:]
tsp_solution = best_tsp_solution optimal_cost = best_cost
return tsp_solution, optimal_cost
def create_random_symmetric_distance_matrix(n: int) -> np.ndarray: def euclidean_distance(node_1: Tuple[float, float], node_2: Tuple[float, float]) -> float:
return math.sqrt((node_1[0] - node_2[0])**2 + (node_1[1] - node_2[1])**2)
nodes = [(random.uniform(0, 1), random.uniform(0, 1)) for _ in range(n)]
distance_matrix = np.zeros((n, n)) for i in range(n): for j in range(n): distance = euclidean_distance(nodes[i], nodes[j]) distance_matrix[i][j] = distance distance_matrix[j][i] = distance
return distance_matrix
def main():
random_seed = 1 n = 25
random.seed(random_seed)
distance_matrix = create_random_symmetric_distance_matrix(n=n) print("-" * 75) print("Distance Matrix (Symmetric):") print(distance_matrix)
start = timer() tsp_mtz_integer_linear_programming_solution, tsp_mtz_integer_linear_programming_optimal_cost = tsp_mtz_integer_linear_programming_solver( distance_matrix=distance_matrix) end = timer() print("-" * 75) print( f"Integer Linear Programming Solver Time Elapsed: {timedelta(seconds=end-start)}" ) print("Integer Linear Programming Solver Solution:") print(tsp_mtz_integer_linear_programming_solution, tsp_mtz_integer_linear_programming_optimal_cost)
start = timer() tsp_genetic_algorithm_approximate_solution, tsp_genetic_algorithm_approximate_optimal_cost = tsp_genetic_algorithm_approximate_solver( distance_matrix=distance_matrix) end = timer() print("-" * 75) print( f"Genetic Algorithm Approximate Solver Time Elapsed: {timedelta(seconds=end-start)}" ) print("Genetic Algorithm Approximate Solver Solution:") print(tsp_genetic_algorithm_approximate_solution, tsp_genetic_algorithm_approximate_optimal_cost)
if __name__ == "__main__":
main()
|