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
| import os import random import math import time import matplotlib.pyplot as plt class GeneticAlgTSP(): def initial_population(self, amount, length, elite): population = [] if elite != []: elite = self.mutate(elite) population.append(elite) while len(population) != amount: individual = random.sample(range(length), length) if individual not in population: population.append(individual) return population
def initial_cities(self, filename): cities = [] diskpath = os.path.dirname(__file__) filepath = diskpath + '//TSP数据库//'+ filename with open(filepath, 'r') as file: lines = file.readlines() for line in lines: if line.startswith("EOF"): break data = line.split() if len(data) == 3 and data[0].isdigit(): x = float(data[1]) y = float(data[2]) cities.append((x, y)) return cities
def __init__(self, filename, elite): self.cities = self.initial_cities(filename) self.population = self.initial_population(10, len(self.cities), elite)
def random2point(self, size): point1 = random.randint(1, size - 1) point2 = random.randint(1, size - 1) while point1 == point2: point2 = random.randint(1, size - 1) return min(point1, point2), max(point1, point2)
def euclidean_distance(self, city1, city2): x1, y1 = city1 x2, y2 = city2 distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) return distance
def fitness(self, individual): amount = len(individual) distance = 0 for i in range(amount): city1 = self.cities[individual[i]] city2 = self.cities[individual[(i + 1) % amount]] distance += self.euclidean_distance(city1, city2) return int(distance)
def tournament_select(self, population): group1 = random.sample(population, 8) parent1 = min(group1, key=self.fitness) group2 = random.sample(population, 8) if parent1 in group2: group2.remove(parent1) parent2 = min(group2, key=self.fitness) return parent1, parent2
def crossover(self, parent1, parent2): size = len(parent1) child1, child2 = [None] * size, [None] * size point1, point2 = self.random2point(size) child1[point1:point2 + 1] = parent2[point1:point2 + 1] child2[point1:point2 + 1] = parent1[point1:point2 + 1] mapping1 = {parent2[i]: parent1[i] for i in range(point1, point2 + 1)} mapping2 = {parent1[i]: parent2[i] for i in range(point1, point2 + 1)} for i in range(size): if i < point1 or i > point2: element1 = parent1[i] while element1 in mapping1: element1 = mapping1[element1] child1[i] = element1
element2 = parent2[i] while element2 in mapping2: element2 = mapping2[element2] child2[i] = element2 return child1, child2
def mutate(self, individual): size = len(individual) point1, point2 = self.random2point(size) mutate_individual = individual[:point1] + individual[point1:point2 + 1][::-1] + individual[point2 + 1:] return mutate_individual
def GA(self, max_iterations, max_populations, mutate_rate): iteration = 0 while iteration != max_iterations: size = len(self.population) parent1, parent2 = self.tournament_select(self.population) child1, child2 = self.crossover(parent1, parent2) self.population = sorted(self.population, key=self.fitness) if size == max_populations: self.population[size - 1], self.population[size - 2] = child1, child2 elif size <= 18: self.population.append(child1) self.population.append(child2) self.population = sorted(self.population, key=self.fitness) rate = mutate_rate for i in range(len(self.population)): if random.random() < mutate_rate: self.population[i] = self.mutate(self.population[i]) rate += 0.01 iteration += 1 self.population = sorted(self.population, key=self.fitness) return self.fitness(self.population[0]), self.population[0]
def plot_path(points, path): plt.cla() x_values = [point[0] for point in points] y_values = [point[1] for point in points] plt.scatter(x_values, y_values, color='blue', s=15) for i in range(len(path) - 1): point1 = points[path[i]] point2 = points[path[i + 1]] plt.plot([point1[0], point2[0]], [point1[1], point2[1]], color='red', linewidth=0.1) point1 = points[path[-1]] point2 = points[path[0]] plt.plot([point1[0], point2[0]], [point1[1], point2[1]], color='red', linewidth=0.1) plt.title('Visualization of Path') plt.xlabel('X') plt.ylabel('Y') plt.legend(['points', 'path'], loc='upper right') plt.draw() plt.pause(0.2)
def EA(filename): max_iterations = 10000 max_generations = 100 max_populations = 20 max_blocktime = 15 mutate_rate = 0.08
generation = 0 best_distance = float('inf') best_path = []
blocktime = 0 while generation != max_generations: solve = GeneticAlgTSP(filename, best_path) distance, path = solve.GA(max_iterations, max_populations, mutate_rate) if distance < best_distance or blocktime == max_blocktime: if distance < best_distance: best_distance = distance best_path = path print("第", generation + 1, "次路径长度:", best_distance) plot_path(solve.cities, best_path) blocktime = 0 generation += 1 continue blocktime += 1 return best_distance, best_path
filename = '//' + 'rw1621'+ '.tsp' best_distance,best_path = EA(filename) print("最佳路线:",best_path) print("最短距离",best_distance)
|