-
Notifications
You must be signed in to change notification settings - Fork 7
/
operationGenerationTests.py
345 lines (290 loc) · 13.3 KB
/
operationGenerationTests.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import unittest
import datetime
import genetic
import random
class Node:
Value = None
Left = None
Right = None
def __init__(self, value, left=None, right=None):
self.Value = value
self.Left = left
self.Right = right
def isFunction(self):
return self.Left is not None
def __str__(self):
result = self.Value
if self.isFunction():
result += "([" + str(self.Left) + "]"
if self.Right is not None:
result += ",[" + str(self.Right) + "]"
result += ")"
return result + " "
class Operation:
Func = None
HasLeft = None
HasRight = None
def __init__(self, func, hasLeft, hasRight):
self.Func = func
self.HasLeft = hasLeft
self.HasRight = hasRight
def getUsedIndexes(candidate):
used = {0: [0]}
if candidate[0].isFunction():
for i in reversed(range(len(candidate))):
element = candidate[i]
iUsed = [i]
if element.isFunction():
leftIndex = element.Left
rightIndex = element.Right
if i < leftIndex < len(candidate):
iUsed.extend(used[leftIndex])
if rightIndex is not None:
if i < rightIndex < len(candidate):
iUsed.extend(used[rightIndex])
used[i] = iUsed
return set(used[0])
def getFitness(candidate, geneset, rules):
usedIndexes = getUsedIndexes(candidate)
localCopy = candidate[:]
notUsed = list(set(range(len(candidate))) - usedIndexes)
for i in notUsed:
localCopy[i] = None
fitness = 0
for rule in rules:
if getFitnessForRule(localCopy, rule[0], rule[1], geneset) == rule[2]:
fitness += 1
if fitness == len(rules):
fitness = 1000 - len(usedIndexes)
return fitness
def getFitnessForRule(candidate, a, b, geneset):
if candidate[0].isFunction():
localCopy = candidate[:]
for i in reversed(range(len(localCopy))):
element = localCopy[i]
if element is None:
continue
if element.isFunction():
leftIndex = element.Left
rightIndex = element.Right
left = None
if i < leftIndex < len(localCopy):
left = localCopy[leftIndex].Value
right = None
if rightIndex is not None:
if i < rightIndex < len(localCopy):
right = localCopy[rightIndex].Value
value = element.Value
if isinstance(element.Value, str):
gene = geneset[element.Value]
value = gene.Func(left if left is not None else 0,
right if right is not None else 0)
localCopy[i] = Node(value)
else:
localCopy[i] = Node(geneset[element.Value].Func(a, b))
result = localCopy[0].Value
else:
result = geneset[candidate[0].Value].Func(a, b)
return result
def displayDot(candidate, startTime):
result = createDot(candidate.Genes)
timeDiff = datetime.datetime.now() - startTime
print("%s\nfitness: %i\t%s\t%s" % (";".join(result), candidate.Fitness, str(timeDiff), candidate.Strategy))
def createDot(genes):
dotCommands = []
added = [False for i in range(0, len(genes))]
stack = [0]
haveZeroNode = False
while len(stack) > 0:
index = stack.pop()
if added[index]:
continue
added[index] = True
element = genes[index]
if not element.isFunction():
dotCommands.append(str(index) + " [label=\"" + str(element.Value) + "\"]")
else:
dotCommands.append(str(index) + " [label=\"" + element.Value + "\"]")
leftIndex = element.Left
if index < leftIndex < len(genes):
stack.append(leftIndex)
dotCommands.append(str(leftIndex) + " -> " + str(index))
else:
if not haveZeroNode:
dotCommands.append("zero [label=\"0\"]")
haveZeroNode = True
dotCommands.append("zero -> " + str(index))
rightIndex = element.Right
if rightIndex is not None:
if index < rightIndex < len(genes):
stack.append(rightIndex)
dotCommands.append(str(rightIndex) + " -> " + str(index))
else:
if not haveZeroNode:
dotCommands.append("zero [label=\"0\"]")
haveZeroNode = True
dotCommands.append("zero -> " + str(index))
return dotCommands
def displayRaw(candidate, startTime):
timeDiff = datetime.datetime.now() - startTime
print("%s\t%i\t%s" %
((' '.join(map(str, [str(item) for item in candidate.Genes]))),
candidate.Fitness,
str(timeDiff)))
def mutate(childGenes, fnCreateGene):
childIndexesUsed = list(getUsedIndexes(childGenes))
index = childIndexesUsed[random.randint(0, len(childIndexesUsed) - 1)]
childGenes[index] = fnCreateGene(index, len(childGenes))
def crossover(child, parent):
usedParentIndexes = list(sorted(getUsedIndexes(parent)))
usedChildIndexes = list(getUsedIndexes(child))
if len(usedParentIndexes) == 1 and len(usedChildIndexes) == 1:
# node 0 has no child nodes, just copy it
child[0] = parent[0]
return
while True:
parentIndex = usedParentIndexes[random.randint(0, len(usedParentIndexes) - 1)]
childIndex = usedChildIndexes[random.randint(0, len(usedChildIndexes) - 1)]
if parentIndex != 0 or childIndex != 0:
# don't copy the root to the root
break
unusedChildIndexes = list(sorted(set(range(childIndex, len(child))) - set(usedChildIndexes)))
unusedChildIndexes.insert(0, childIndex)
mappedIndexes = {}
nextIndex = 0
for pIndex in usedParentIndexes:
if pIndex < parentIndex:
continue
if len(unusedChildIndexes) > nextIndex:
mappedIndexes[pIndex] = unusedChildIndexes[nextIndex]
else:
mappedIndexes[pIndex] = len(child) + nextIndex - len(unusedChildIndexes)
nextIndex += 1
for parentIndex in mappedIndexes.keys():
node = parent[parentIndex]
childIndex = mappedIndexes[parentIndex]
childNode = Node(node.Value, node.Left, node.Right)
if childIndex < len(child):
child[childIndex] = childNode
else:
child.append(childNode)
left = node.Left
if left is not None:
childNode.Left = mappedIndexes[left] if left in mappedIndexes else 0
right = node.Right
if right is not None:
childNode.Right = mappedIndexes[right] if right in mappedIndexes else 0
def createGene(index, length, geneset):
keys = list(geneset.keys())
key = keys[random.randint(0, len(keys) - 1)]
op = geneset[key]
left = random.randint(index, length - 1) if op.HasLeft else None
right = random.randint(index, length - 1) if op.HasRight else None
return Node(key, left, right)
class OperationGenerationTests(unittest.TestCase):
geneset = None
@classmethod
def setUpClass(cls):
cls.geneset = {'A': Operation(lambda a, b: a, False, False),
'B': Operation(lambda a, b: b, False, False),
'AND': Operation(lambda a, b: a & b, True, True),
'NOT': Operation(lambda a, b: a == 0, True, False)}
def test_generate_OR(self):
minNodes = 6 # not( and( not(a), not(b)))
rules = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]
maxNodes = 20
optimalValue = 1000 - minNodes
startTime = datetime.datetime.now()
fnDisplay = lambda candidate: displayDot(candidate, startTime)
fnGetFitness = lambda candidate: getFitness(candidate, self.geneset, rules)
fnCreateGene = lambda index, length: createGene(index, length, self.geneset)
fnMutate = lambda child: mutate(child, fnCreateGene)
best = genetic.getBest(fnGetFitness, fnDisplay, minNodes, optimalValue, createGene=fnCreateGene,
maxLen=maxNodes, customMutate=fnMutate, customCrossover=crossover)
self.assertTrue(best.Fitness >= optimalValue)
def test_generate_XOR(self):
minNodes = 9 # and( not( and(a, b)), not( and( not(a), not(b))))
rules = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
maxNodes = 50
optimalValue = 1000 - minNodes
startTime = datetime.datetime.now()
fnDisplay = lambda candidate: displayDot(candidate, startTime)
fnGetFitness = lambda candidate: getFitness(candidate, self.geneset, rules)
fnCreateGene = lambda index, length: createGene(index, length, self.geneset)
fnMutate = lambda child: mutate(child, fnCreateGene)
best = genetic.getBest(fnGetFitness, fnDisplay, minNodes, optimalValue, createGene=fnCreateGene,
maxLen=maxNodes, customMutate=fnMutate, customCrossover=crossover)
self.assertTrue(best.Fitness >= optimalValue)
def test_generate_XOR_with_addition(self):
minNodes = 5 # and( 1, +(a, b))
geneset = {'A': Operation(lambda a, b: a, False, False),
'B': Operation(lambda a, b: b, False, False),
'AND': Operation(lambda a, b: a & b, True, True),
'NOT': Operation(lambda a, b: a == 0, True, False),
'+': Operation(lambda a, b: a + b, True, True),
'1': Operation(lambda a, b: 1, False, False)}
rules = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
maxNodes = 50
optimalValue = 1000 - minNodes
startTime = datetime.datetime.now()
fnDisplay = lambda candidate: displayDot(candidate, startTime)
fnGetFitness = lambda candidate: getFitness(candidate, geneset, rules)
fnCreateGene = lambda index, length: createGene(index, length, geneset)
fnMutate = lambda child: mutate(child, fnCreateGene)
best = genetic.getBest(fnGetFitness, fnDisplay, minNodes, optimalValue, createGene=fnCreateGene,
maxLen=maxNodes, customMutate=fnMutate, customCrossover=crossover)
self.assertTrue(best.Fitness >= optimalValue)
def test_getFitness_given_base_node_is_A_and_1_matching_rule_should_return_1(self):
rules = [[0, 0, 0], [0, 1, 1]]
genes = [Node('A')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1)
def test_getFitness_given_base_node_is_B_and_1st_2_rules_match_should_return_2(self):
rules = [[0, 0, 0], [0, 1, 1], [1, 0, 1]]
genes = [Node('B')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 2)
def test_getFitness_given_base_node_is_NOT_with_Left_node_out_of_bounds_and_1st_rule_matches_should_return_1(self):
rules = [[1, 1, 1], [0, 0, 0]]
genes = [Node('NOT', 100, 0)]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1)
def test_getFitness_given_base_node_is_NOT_with_Left_node_A_and_2nd_rule_matches_should_return_1(self):
rules = [[0, 0, 0], [1, 1, 1]]
genes = [Node('NOT', 100, 0)]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1)
def test_getFitness_given_base_node_is_AND_with_both_nodes_out_of_bounds_and_0_matching_rules_should_return_0(self):
rules = [[1, 0, 1]]
genes = [Node('AND', 100, 100)]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 0)
def test_getFitness_given_all_rules_pass_and_1_gene_should_return_1000_minus_1(self):
rules = [[0, 0, 0]]
genes = [Node('AND', 100, 100)]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1000 - len(genes))
def test_getFitness_given_all_rules_pass_and_2_genes_but_only_1_used_should_return_1000_minus_1(self):
rules = [[0, 0, 0]]
genes = [Node('AND', 100, 100), Node('B')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1000 - 1)
def test_getFitness_given_all_rules_pass_and_3_genes_but_only_2_used_should_return_1000_minus_2(self):
rules = [[0, 0, 0]]
genes = [Node('AND', 2, 100), Node('AND', 2, 2), Node('B')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1000 - 2)
def test_getFitness_given_all_rules_pass_with_NOT_2_NOT_1_NOT_2_B_A_should_return_1000_minus_2(self):
rules = [[0, 0, 0]]
genes = [Node('NOT', 2), Node('NOT', 1), Node('NOT', 2), Node('B'), Node('A')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1000 - 2)
def test_getFitness_given_rules_and_genes_for_XOR_should_get_1000_minus_9(self):
rules = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]]
# and( not( and(a, b)), not( and( not(a), not(b))))
genes = [Node('AND', 1, 2), Node('NOT', 3), Node('NOT', 4), Node('AND', 5, 6), Node('AND', 7, 8),
Node('NOT', 7), Node('NOT', 8), Node('A'), Node('B')]
result = getFitness(genes, self.geneset, rules)
self.assertEqual(result, 1000 - 9)
if __name__ == '__main__':
unittest.main()