-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathga.py
256 lines (215 loc) · 9.16 KB
/
ga.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
from brainfuck_me import *
import math
import random
from numba import vectorize
mean_fitness_list = list()
max_fitness_list = list()
def evaluate_fitness(code_string, input = None):
# Determine fitness of a population member
# First, sanitize the code string. That is, make sure openign and closing brackets match
end = len(code_string)
while 1:
try:
prepare_code(code_string)
break
except:
end -= 1
if end == -2:
break
code_string = code_string[:end]
# print("Evaluating: ", code_string)
# Call to interpreter
evaluate_code(read(code_string)) # This takes input from 'input.txt' stores the result in 'output.txt'
result = open('output.txt', 'r').read()
# if len(result) > 0:
# print('Result: ', result)
fitness = 0
desired_result = open('desired.txt', 'r').read()
# Compute fitness (Here, the aim is to print a known string so the fitness fucction is based on the goal.)
for i in range(min(len(result), len(desired_result))):
fitness += 256 - math.fabs(ord(result[i]) - ord(desired_result[i]))
# print('Fitness: ', fitness)
if fitness == 256*len(desired_result):
print("Perfect code: ", code_string)
plot_stats()
import sys
sys.exit(0)
return fitness
class pop_member:
def __init__(self, length = random.randint(2,100), code = ''):
self.seq = ['+', '-', '.', ',', '[', ']', '>', '<']
self.length = length
if code == '':
self.code = ''.join([random.choice(self.seq) for i in range(self.length)])
else:
self.code = code
self.fitness = 0
def mutate(self, prob): # Mutate strlen and str with prob = mutation rate
temp_code = list(self.code)
for i in range(self.length):
if prob > random.random():
d = random.random()
if d <= 0.25: # Replacement mutation
temp_code[i] = random.choice(self.seq)
elif d <= 0.5: # insertion mutation
shiftBit = temp_code[i]
temp_code[i] = random.choice(self.seq)
up = random.random() >= 0.5
if up: # last bit is lost
j = i + 1
while j < self.length:
nextShiftBit = temp_code[j]
temp_code[j] = shiftBit
shiftBit = nextShiftBit
j += 1
else: # first bit is lost
j = i - 1
while j >= 0:
nextShiftBit = temp_code[j]
temp_code[j] = shiftBit
shiftBit = nextShiftBit
j -= 1
elif d <= 0.75: # Deletion mutation
up = random.random() >= 0.5
if up:
j = i
while j > 0:
temp_code[j] = temp_code[j - 1]
j -= 1
temp_code[0] = random.choice(self.seq)
else:
j = i
while j < self.length - 1:
temp_code[j] = temp_code[j + 1]
j += 1
temp_code[-1] = random.choice(self.seq)
else: # Rotation mutation
up = random.random() >= 0.5
if up:
shiftBit = temp_code[0]
for j in range(self.length):
if j > 0:
temp = temp_code[j]
temp_code[j] = shiftBit
shiftBit = temp
else:
temp_code[j] = temp_code[-1]
else:
shiftBit = temp_code[-1]
j = self.length - 1
while j >= 0:
if j < self.length - 1:
temp = temp_code[j]
temp_code[j] = shiftBit
shiftBit = temp
else:
temp_code[j] = temp_code[0]
j -= 1
self.code = ''.join(temp_code)
def crossover(self, mom, dad): # Single point crossover
self.length = 0
self.code = ''
x = random.randint(0,len(mom) - 1)
y = random.randint(0,len(dad) - 1)
child1 = dad[:y] + mom[x:]
child2 = mom[:x] + dad[y:]
self.length = len(child1)
self.code = child1
return pop_member(len(child2), child2)
class Life:
def __init__(self):
# Parameters for the genetic algorithm
self.pop_size = 1000
self.crossover_rate = 0.8
self.num_gens = 5000
self.mutation_rate = 0.05 # * (1 - (self.num_gens/5000))
self.elitism = True
self.population = [None] * self.pop_size
self.mating_pool = list()
def random_population(self):
# initial population (initialized all with length between 2 and 10)
for i in range(self.pop_size):
self.population[i] = pop_member()
def select(self): # Roulette wheel selection
self.mating_pool = list()
fitnesses = [self.population[i].fitness for i in range(self.pop_size)]
# print(fitnesses)
max_fitness = max(fitnesses)
mean_fitness = sum(fitnesses) / len(fitnesses)
if max_fitness == 0: max_fitness = 1
print("max fitness = ", max_fitness)
print("mean fitness = ", mean_fitness)
mean_fitness_list.append(mean_fitness)
max_fitness_list.append(max_fitness)
for i in range(self.pop_size):
fitness_normal = fitnesses[i] / max_fitness; # Normalize fitness between 0 and 1
n = int(fitness_normal * 100); # Arbitrary multiplier
for j in range(n):
self.mating_pool.append(self.population[i]); # Based on fitness, probability of selection will be higher for higher fitness because that organism's genes will get added to the mating pool more number of times
# print(len(self.mating_pool))
def mate(self):
# Randomly select 2 individuals from the mating pool
size = self.pop_size
new_population = [None] * size
if self.elitism:
self.population.sort(key = lambda x : x.fitness)
new_population[0] = self.population[-1]
new_population[1] = self.population[-2]
i = 2
while i < size:
mom_genome = self.mating_pool[random.randint(0, len(self.mating_pool) - 1)]
dad_genome = self.mating_pool[random.randint(0, len(self.mating_pool) - 1)]
if random.random() < self.crossover_rate:
child_genome1 = pop_member()
child_genome2 = pop_member()
child_genome2 = child_genome1.crossover(mom_genome.code, dad_genome.code) # Mating
else:
child_genome1 = mom_genome
child_genome2 = dad_genome
child_genome1.mutate(self.mutation_rate) # Mutation
child_genome2.mutate(self.mutation_rate)
new_population[i] = child_genome1 # Add the child to the next generation population
new_population[i + 1] = child_genome2
i += 2
for i in range(self.pop_size):
self.population[i] = new_population[i]
def plot_stats():
import matplotlib.pyplot as plt
import numpy as np
l = len(mean_fitness_list)
x = np.linspace(0, l-1, l)
plt.plot(x, [256*len(open('desired.txt', 'r').read())]*l)
plt.plot(x, mean_fitness_list)
plt.plot(x, max_fitness_list)
plt.show()
def main():
print("Initializing ...")
life = Life()
# life.evaluate_fitness('++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++[++++++++[++++.+++++++++++++++++++++++++++++.+++++[++..<>+++.>+++++++++++++++++++++++++++++<>++++-.[,.,.,.,.]].].][.,]-,-]][+.--+><<..>[+>[+.<+,]><<>]<><<.>.,--<>[<>-,,,><.>.<-,][-[-,-[.-[-+')
# life.evaluate_fitness('')
life.random_population()
best_fitness = 0
best_code = ''
gen = 0
# for gen in range(life.num_gens):
while 1:# life.num_gens > 0:
print('Gen: ', gen)
gen += 1
life.num_gens -= 1
for i in range(life.pop_size):
# print('code: ', life.population[i][0])
life.population[i].fitness = evaluate_fitness(life.population[i].code)
if life.population[i].fitness > best_fitness:
best_fitness = life.population[i].fitness
best_code = life.population[i].code
print("So far best: ", best_code)
# print('fitness: ', life.fitness[i])
# print('--------------------------------------------')
life.select()
life.mate()
print('----------------------------------------')
plot_stats()
if __name__ == '__main__':
# import cProfile
# cProfile.run('main()')
main()