-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpopulation.py
More file actions
213 lines (143 loc) · 4.38 KB
/
population.py
File metadata and controls
213 lines (143 loc) · 4.38 KB
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
# This script creates a randomly generated population
# 9/20/2017
# Daniel Couturier
import random;
import math;
import numpy as np;
# create a "word" container
class word(object):
"""docstring for word"""
def __init__(self, emptyArray=[]):
super(word, self).__init__()
self.letters = emptyArray
def printPop(pop):
pop0 = pop[0];
pop1 = pop[1];
for x in range (0, len(pop)):
for a in range (0, len(pop[x].letters)):
print (pop0.letters[a])
print ("\n")
def createWord(object, target):
# create one array of random numbers
w = word([]);
for i in range (0,len(target)):
num = random.randrange(0,5)
w.letters.append(num)
return w;
def createPopulation(numWords, target):
population = [];
for i in range (0, numWords):
w = createWord(0, target);
population.append(w);
return population;
def scoreWord(word, target):
# score fitness of a word
score = 0;
for i in range(0, len(word.letters)):
if word.letters[i] == target[i]:
score = score + 1;
# this is to make the better words stick out more
score = score * score;
return float(score);
def calculateScores(pop, target):
#find fitness of each word in the population
scores = [];
for i in range(0, len(pop)):
wordIndex = pop[i];
score = scoreWord(wordIndex, target)
scores.append(score)
return scores;
def calculateNormalizeScores(scores):
# normalize scores
scoresSum = sum(scores)
# create an array or normalized scores
normScores = [];
for i in range(0, len(scores)):
normScore = float(scores[i] / scoresSum)
normScores.append(normScore)
return normScores
def selectParent(normScores):
# select an index from the population of words based on it's probability from normalized score
# this number is always between 0 and 1
dart = random.random();
index = 0;
while (dart > 0):
dart = dart - normScores[index];
index = index + 1;
index = index - 1;
return index;
def createChild(indexA, indexB, pop, target, mutationRate):
#create child from parents
parentA = pop[indexA]
parentB = pop[indexB]
child = createWord(0, target);
for i in range(0, len(parentA.letters)):
dart = random.random();
if (dart < 0.5):
child.letters[i] = parentA.letters[i]
else:
child.letters[i] = parentB.letters[i]
#mutate here
rand = random.random();
if(rand < mutationRate):
newNum = random.randrange(0,10)
child.letters[i] = newNum
return child;
def createChildren(normScores, pop, target, mutationRate):
#create children for entire next population
for i in range (0, len(pop)):
#select parents a & b randomly "from a bag"
indexA = selectParent(normScores);
indexB = selectParent(normScores);
#create child from given parents
child = createChild(indexA, indexB, pop, target, mutationRate)
#replace child into population
pop[i] = child
return pop;
def getMaxScore(scores, pop, generation):
# get top scorer
maxScore = 0;
maxScoreIndex = 0;
for i in range(0, len(scores)):
currScore = scores[i];
if(currScore > maxScore):
maxScore = currScore;
maxScoreIndex = i;
print ("Generation:", generation, ", max score: ", maxScore)
return maxScore
def setup(target):
# population is an array of words
pop = createPopulation(200, target);
# score the initial population
# calculate scores for each word
scores = calculateScores(pop, target);
# normalize word scores
normScores = calculateNormalizeScores(scores);
# print high score
maxScore = getMaxScore(scores, pop, 0);
return [pop, scores, normScores, maxScore]
# ==================================================
def main():
# target word is "01234"
target = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8];
mutationRate = 0.01;
[pop, scores, normScores, maxScore] = setup(target)
generation = 0;
targetWord = word(0);
targetWord.letters = target;
targetScore = scoreWord(targetWord, target)
print (targetScore);
while (maxScore < targetScore):
generation = generation + 1;
# ===== CROSS BREEDING ===================================
#create children for entire next population
pop = createChildren(normScores, pop, target, mutationRate);
# ==== SCORING ==========================================
# calculate scores for each word
scores = calculateScores(pop, target);
# normalize word scores
normScores = calculateNormalizeScores(scores);
# print high score
maxScore = getMaxScore(scores, pop, generation);
# ====================
main();