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
|
import numpy as np import json from math import radians, cos, sin, asin, sqrt
""" @param: CITIES the longitude and the latitude of cities N_CITIES the number of cities CROSS_RATE the rate of cross MUTATE_RATE the rate of mutate POP_SIZE the size of population N_GENERATIONS the number of generations """
CITIES = np.array([[116.4, 39.9], [117.2, 39.12], [114.52, 38.05], [112.55, 37.87], [111.73, 40.83], [123.43, 41.8], [125.32, 43.9], [126.53, 45.8], [121.47, 31.23], [118.78, 32.07], [120.15, 30.28], [117.25, 31.83], [119.3, 26.08], [115.85, 28.68], [116.98, 36.67], [113.62, 34.75], [114.3, 30.6], [112.93, 28.23], [113.27, 23.13], [108.37, 22.82], [108.37, 22.82], [106.55, 29.57], [104.07, 30.67], [106.63, 26.65], [102.72, 25.05], [91.13, 29.65], [108.93, 34.27], [103.82, 36.07], [101.78, 36.62], [106.28, 38.47], [87.62, 43.82], [121.52, 25.03], [114.17, 22.28], [113.55, 22.19]]) N_CITIES = CITIES.shape[0] CROSS_RATE = 0.1 MUTATE_RATE = 0.02 POP_SIZE = 1000 N_GENERATIONS = 500
""" Calculate the great circle distance between two points on the earth (specified in decimal degrees) @param: lon1 Longitude of the first point lat1 Latitude of the first point lon2 Longitude of the second point lat2 Latitude of the second point """
def haversine(lon1, lat1, lon2, lat2): lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2 c = 2 * asin(sqrt(a)) r = 6378.137 return c * r
class GA(object): def __init__(self, DNA_size, cross_rate, mutation_rate, pop_size, ): self.DNA_size = DNA_size self.cross_rate = cross_rate self.mutate_rate = mutation_rate self.pop_size = pop_size
self.pop = np.vstack([np.random.permutation(DNA_size) for _ in range(pop_size)])
def translateDNA(self, DNA, city_position): line_x = np.empty_like(DNA, dtype=np.float64) line_y = np.empty_like(DNA, dtype=np.float64)
for i, d in enumerate(DNA):
city_coord = city_position[d] line_x[i, :] = city_coord[:, 0] line_y[i, :] = city_coord[:, 1] return line_x, line_y
def get_fitness(self, line_x, line_y): total_distance = np.zeros((line_x.shape[0],), dtype=np.float64) for i in range(line_x.shape[0]): for j in range(line_x.shape[1]-1): total_distance[i] += haversine(line_x[i][j], line_y[i][j], line_x[i][j+1], line_y[i][j+1]) total_distance[i] += haversine(line_x[i][0], line_y[i][0], line_x[i][line_x.shape[1]-1], line_y[i][line_x.shape[1]-1])
fitness = np.exp(self.DNA_size * 20000 / total_distance)
return fitness, total_distance
def select(self, fitness): idx = np.random.choice(np.arange( self.pop_size), size=self.pop_size, replace=True, p=fitness / fitness.sum()) return self.pop[idx]
def crossover(self, parent, pop): if np.random.rand() < self.cross_rate: i_ = np.random.randint(0, self.pop_size, size=1) cross_points = np.random.randint( 0, 2, self.DNA_size).astype(np.bool) keep_city = parent[~cross_points] swap_city = pop[i_, np.in1d( pop[i_].ravel(), keep_city, invert=True)] parent[:] = np.concatenate((keep_city, swap_city)) return parent
def mutate(self, child): for point in range(self.DNA_size): if np.random.rand() < self.mutate_rate: swap_point = np.random.randint(0, self.DNA_size) swapA, swapB = child[point], child[swap_point] child[point], child[swap_point] = swapB, swapA return child
def evolve(self, fitness): pop = self.select(fitness) pop_copy = pop.copy() for parent in pop: child = self.crossover(parent, pop_copy) child = self.mutate(child) parent[:] = child self.pop = pop
if __name__ == "__main__": ga = GA(DNA_size=N_CITIES, cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE, pop_size=POP_SIZE)
path_list = [] for generation in range(N_GENERATIONS): lx, ly = ga.translateDNA(ga.pop, CITIES) fitness, total_distance = ga.get_fitness(lx, ly) ga.evolve(fitness) best_idx = np.argmax(fitness) print('Gen:', generation, '| total distance: %.4f' % total_distance[best_idx],)
path_x = np.array(list(lx[best_idx]) + [lx[best_idx][0]]) path_y = np.array(list(ly[best_idx]) + [ly[best_idx][0]]) path = np.stack((path_x, path_y)) path = path.transpose(1, 0) path_list.append(path.tolist())
f = open('data.json', 'w') f.write(json.dumps(path_list)) f.close()
|