-
Notifications
You must be signed in to change notification settings - Fork 2
/
demoga.html
269 lines (227 loc) · 10.3 KB
/
demoga.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<!-- <div id="editor">function foo(items) {
var x = "All this is syntax highlighted";
return x;
}</div> -->
<div id="editor">
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<!-- <div id="editor">function foo(items) {
var x = "All this is syntax highlighted";
return x;
}</div> -->
<div id="editor">
# GENETIC ALGORITHM
from tkinter import *
from tkinter.ttk import *
import time
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.animation import FuncAnimation
#import matplotlib.animation as animation
import numpy
import string
import matplotlib.pyplot as plt
import matplotlib.animation
#import matplotlib
import random
numpy.random.seed(1)
N = 25
_nodes = [(random.uniform(-400, 400), random.uniform(-400, 400)) for _ in range(0, 25)]
xx = [i[0] for i in _nodes]
yy = [i[1] for i in _nodes]
# Generation of labels and random coordinates for N cities
CITY_LABELS = list(range(N))
#CITY_COORD = numpy.random.randint(0, 200, (N, 2))
#CITY_COORD=numpy.array([(random.uniform(-400, 400), random.uniform(-400, 400)) for _ in range(0, 25)])
CITY_COORD=numpy.array(_nodes)
CITY_DICT = {label: coord for (label, coord) in zip(CITY_LABELS, CITY_COORD)}
# Population initialization function
def init(pop_size):
def random_permutation():
population = list()
for _ in range(pop_size):
# Each individual is a random permutation of the set of cities
individual = list(numpy.random.permutation(CITY_LABELS))
population.append(individual)
return population
return random_permutation()
#fitness function
# Calculates the fitness of all individuals in the population
def fit(population):
fitness = list()
for individual in population:
distance = 0
for i, city in enumerate(individual):
s = CITY_DICT[individual[i-1]]
t = CITY_DICT[individual[i]]
distance += numpy.linalg.norm(s-t)
fitness.append(1/distance)
return fitness
# Selection function
def selection(population, fitness, n):
def roulette():
# Obtaining the indices for each individual in the population
idx = numpy.arange(0, len(population))
# Calculation of selection probabilities based on individuals' aptitude
probabilities = fitness/numpy.sum(fitness)
# Choice of parent indexes
parents_idx = numpy.random.choice(idx, size=n, p=probabilities)
# Choice of parents based on selected indexes
parents = numpy.take(population, parents_idx, axis=0)
parents = [(parents[i], parents[i+1])
for i in range(0, len(parents)-1, 2)]
return parents
return roulette()
# Crossover function
def crossover(parents, crossover_rate=0.9):
def ordered():
children = list()
# Iteration by all pairs of parents
for pair in parents:
if numpy.random.random() < crossover_rate:
for (parent1, parent2) in [(pair[0], pair[1]), (pair[1], pair[0])]:
# Cut segment definition
points = numpy.random.randint(0, len(parent1), 2)
start = min(points)
end = max(points)
segment1 = [x for x in parent1[start:end]]
segment2 = [x for x in parent2[end:] if x not in segment1]
segment3 = [x for x in parent2[:end] if x not in segment1]
child = segment3 + segment1 + segment2
children.append(child)
else:
# If the crossing does not occur, the parents remain in the next generation
children.append(pair[0])
children.append(pair[1])
return children
return ordered()
#mutation function
def mutation(children, mutation_rate=0.05):
def swap():
# Mutação pode ocorrer em qualquer dos filhos
for i, child in enumerate(children):
if numpy.random.random() < mutation_rate:
[a, b] = numpy.random.randint(0, len(child), 2)
children[i][a], children[i][b] = children[i][b], children[i][a]
return children
return swap()
# Stop criterion function
def stop():
return False
# Elitism function
def elitism(population, fitness, n):
# Select n most suitable individuals
return [e[0] for e in sorted(zip(population, fitness),
key=lambda x:x[1], reverse=True)[:n]]
def base_algorithm(pop_size, max_generations, elite_size=0):
population = init(pop_size)
yield 0, population, fit(population)
for g in range(max_generations):
fitness = fit(population)
elite = elitism(population, fitness, elite_size)
parents = selection(population, fitness, pop_size - elite_size)
children = crossover(parents)
children = mutation(children)
population = elite + children
yield g+1, population, fit(population)
#if stop():
#break
def ga():
run = base_algorithm(pop_size=100, max_generations=300, elite_size=10)
#fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(15, 10))
fig = plt.figure(figsize=(12, 8))
gs = fig.add_gridspec(2, 3, wspace=0.45, hspace=0.35)
ax3 = fig.add_subplot(gs[0, 0])
ax3.set_xlabel('x (kms)')
ax3.set_ylabel('y (kms)')
ax3.set_title('Cities', fontweight='bold', pad=10)
ax3.set_xlim([-400, 410])
ax3.set_ylim([-400, 410])
ax3.scatter(CITY_COORD[:, 0],CITY_COORD[:, 1], c='r', edgecolors='black', alpha=0.85)
#ax3.scatter(CITY_COORD[:, 0],CITY_COORD[:, 1], color='black', alpha=0.85)
x = []
y_min = []
y_mean = []
ax0 = fig.add_subplot(gs[1, 0])
#ax0.set_title('Best path distance in every generation', fontweight='bold', pad=10)
#ax0.set_ylim(0, 3000)
#ax0.set_xlim(0, 200)
ax1 = fig.add_subplot(gs[:, 1:])
#ax1.set_xlabel('x (kms)')
#ax1.set_ylabel('y (kms)')
#title = ax1.set_title('Best Path Distance', fontweight='bold', fontsize=13, pad=10)
def animate(args):
ax0.clear()
ax1.clear()
ax0.set_title('Best path distance in every generation', fontweight='bold', pad=10)
ax0.set_xlabel('Generations')
ax0.set_ylabel('Distance (kms)')
g, population, fitness = args
x.append(g)
dist = [1/f for f in fitness]
y_min.append(numpy.min(dist))
y_mean.append(numpy.mean(dist))
ax0.plot(x, y_min, color='blue', alpha=0.7, label='Fittest individual')
#ax0.plot(x, y_mean, color='blue', alpha=0.7, label='Média da população')
ax0.legend(loc='upper right')
#ax1.set_title('Fittest individual')
ax1.set_title(f"Best Path Cost : {numpy.min(dist)} kms")
ax1.set_xlabel('x (kms)')
ax1.set_ylabel('y (kms)')
ax1.set_xlim([-400, 410])
ax1.set_ylim([-400, 410])
ax1.scatter(CITY_COORD[:, 0],
CITY_COORD[:, 1], c='r', edgecolors='black', alpha=0.85)
solution = max(zip(population, fitness), key=lambda x: x[1])[0]
P = numpy.array([CITY_DICT[s]
for s in solution] + [CITY_DICT[solution[0]]])
ax1.plot(P[:, 0], P[:, 1], '--',c='black', alpha=0.85)
return
try:
#anim = matplotlib.animation.FuncAnimation(
anim =FuncAnimation(
fig, animate, frames=run, interval=50, repeat=False)
anim.save(f'xyz.gif', writer='')
#plt.tight_layout(pad=3.5)
#plt.show()
except AttributeError:
pass
</div>
<script src="ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/twilight");
editor.session.setMode("ace/mode/javascript");
</script>
</body>
</html>