-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn_queens_valorado.py
272 lines (219 loc) · 8.05 KB
/
n_queens_valorado.py
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
272
import configparser
import matplotlib.pyplot as plt
import numpy as np
import math
import random
from functools import reduce
parser = configparser.ConfigParser()
parser.read("n_queens_valorado.cfg")
def binaryRandom(size):
return np.random.randint(0, 2, size, dtype="uint8")
def integerPermutation(low, high):
return np.random.permutation(range(math.floor(low), math.floor(high + 1)))
def integerRandom(size, low, high):
return np.random.randint(math.floor(low), math.floor(high + 1), size)
def realRandom(size, low, high):
return np.random.uniform(low, high, size)
def genIndividuo(key):
dim = int(parser.get("config", "DIM"))
low = int(parser.get("config", "LOW"))
high = int(parser.get("config", "HIGH"))
generator = {
"BIN": binaryRandom(dim),
"INT_PERM": integerPermutation(low, high),
"INT": integerRandom(dim, low, high),
"REAL": realRandom(dim, low, high),
}
return generator[key]
def show_table(chromosome, profit_array, maxFitValue) -> str:
size = len(chromosome)
board = np.full((size, size), "-")
for index, item in enumerate(chromosome):
board[index][item - 1] = "x"
out = ""
for row in board:
out += "|"
for tile in row:
out += tile
out += " |\n"
col, profit = 0, 0
for i in range(len(chromosome) - 1):
profit += profit_array[(i + 1) * (chromosome[i] - 1)]
for j in range(i + 1, len(chromosome)):
col += 2 * (abs(chromosome[i] - chromosome[j]) == abs(i - j))
out += f"\ncollisions: {col}\n"
out += "profit: %f/%f\n" % (profit, maxFitValue)
return out
def pmx(parent1, parent2):
size = min(len(parent1), len(parent2))
# inicia com 0 dois arrays do mesmo tamanho
p1, p2 = [0] * size, [0] * size
for i in range(size):
p1[parent1[i] - 1] = i
p2[parent2[i] - 1] = i
splitPoint1 = np.random.randint(0, size)
splitPoint2 = np.random.randint(0, size - 1)
## ponto 1 precisa ser o menor
if splitPoint2 >= splitPoint1:
# evita que o ponto 1 seja igual ao 2
splitPoint2 += 1
else:
# inverte os pontos
splitPoint1, splitPoint2 = splitPoint2, splitPoint1
for i in range(splitPoint1, splitPoint2):
parent1Sol = parent1[i]
parent2Sol = parent2[i]
parent1[i], parent1[p1[parent2Sol - 1]] = parent2Sol, parent1Sol
parent2[i], parent2[p2[parent1Sol - 1]] = parent1Sol, parent2Sol
p1[parent1Sol - 1], p1[parent2Sol - 1] = p1[parent2Sol - 1], p1[parent1Sol - 1]
p2[parent1Sol - 1], p2[parent2Sol - 1] = p2[parent2Sol - 1], p2[parent1Sol - 1]
return (parent1, parent2)
def getPopulation():
popMax = int(parser.get("config", "POP"))
key = parser.get("config", "COD")
pop = []
## gera pop
for i in range(popMax):
result = genIndividuo(key)
fitnessVal = None
pop.append(result)
return pop
def fitness(individo, values, maxFitValue):
dim = len(individo)
fit = dim * (dim - 1)
maxFit = fit * 0.5 + maxFitValue * 0.5
value: float = 0
for i in range(len(individo) - 1):
value += values[(i + 1) * (individo[i] - 1)]
for j in range(i + 1, len(individo)):
fit -= 2 * (abs(individo[i] - individo[j]) == abs(i - j))
return individo, (fit * 0.5 + value * 0.5) / maxFit
def plotChart(result, media):
plt.plot(result, label="Melhor")
plt.plot(media, label="Média")
plt.legend()
plt.show()
def elitismo(population):
best = population[0]
for i in range(len(population)):
if (population[i][1] > best[1]):
best = population[i]
return best[0].copy(),best[1]
def crossover(population, pc):
change = np.random.rand(len(population))
for i in range(0, len(change) - 1, 2):
if change[i] <= pc:
population[i], population[i + 1] = pmx(
population[i], population[i + 1]
)
return population
def stochasticTournament(population, k: int = 2, kp: int = 1):
def fight(subpop):
lucky_number = random.random()
if kp >= lucky_number:
return subpop[1][0]
return subpop[0][0]
weights = [1 for i in population]
sortPop = sorted(
random.choices(population, k=k, weights=weights), key=lambda x: x[1]
)[0 :: k - 1]
newPop = [
fight(sortPop)
for i in population
]
return newPop
def fitnessProportionateSelection(population):
selected = []
removed_fitness = None
sum_fit = float(sum([c[1] for c in population]))
for _ in range(len(population)):
lucky_number = random.random()
prev_probability = 0.0
if removed_fitness is not None:
population[index] = (population[index][0],removed_fitness)
sum_fit += removed_fitness
removed_fitness = None
for i, c in enumerate(population):
if (prev_probability + (c[1] / sum_fit)) >= lucky_number:
selected.append(c[0])
sum_fit -= c[1]
removed_fitness = c[1]
index = i
c = (c[0],0)
break
prev_probability += c[1] / sum_fit
return selected
def swap(chromosome):
point_1 = np.random.randint(len(chromosome))
point_2 = np.random.randint(len(chromosome))
while point_1 == point_2:
point_2 = np.random.randint(len(chromosome))
chromosome[point_1], chromosome[point_2] = chromosome[point_2], chromosome[point_1]
return chromosome
def select(population):
return stochasticTournament(population)
def mutate(population):
def willMutate(individual):
rnd = np.random.rand()
return (
swap(individual)
if rnd <= float(parser.get("config", "PM"))
else individual
)
return list(map(willMutate, population))
if __name__ == "__main__":
gen = int(parser.get("config", "GEN"))
run = int(parser.get("config", "RUN"))
pc = float(parser.get("config", "PC"))
el = bool(int(parser.get("config", "EL")))
dim = int(parser.get("config", "DIM"))
valueArray = np.array(list(map(float, range(1, dim ** 2 + 1))))
operacao, nextOp = math.sqrt, math.log10
for i in range(len(valueArray)):
valueArray[i] = operacao(valueArray[i])
if not (i + 1) % dim:
nextOp, operacao = operacao, nextOp
continue
maxFitValue = sum(sorted(valueArray)[-1 : -dim - 1 : -1])
bestOfAll = []
mediaAll = []
bestSolution = ([], 0)
for r in range(run):
bestOfGen = []
media = []
pop = getPopulation()
for j in range(gen):
popFit = [fitness(i, valueArray, maxFitValue) for i in pop]
avg = reduce(lambda a, b: a + b[1], popFit, 0) / len(popFit)
media.append(avg)
# print(popFit)
elite = elitismo(popFit)
if elite[1] > bestSolution[1]:
bestSolution = elite
bestOfGen.append(elite[1])
selected = select(popFit)
cross = crossover(selected, pc)
pop = mutate(cross)
if el:
# adiciona o melhor de volta a populacao
pop.pop()
pop.append(elite[0])
# print(pop)
# print(selected)
mediaAll.append(media)
bestOfAll.append(bestOfGen)
avgAll = []
avgAllBest = []
for j in range(gen):
avv = 0
for r in mediaAll:
avv += r[j]
md = avv / len(mediaAll)
avgAll.append(md)
avv2 = 0
for r in bestOfAll:
avv2 += r[j]
avgAllBest.append(avv2 / len(bestOfAll))
print("Melhor solucao: ", bestSolution)
# print(show_table(bestSolution[0], profit_array, maxFitValue))
plotChart(avgAllBest, avgAll)