-
Notifications
You must be signed in to change notification settings - Fork 1
/
fitness.py
59 lines (50 loc) · 2.15 KB
/
fitness.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
from antlr4 import *
from antlr.GPMiniLexer import GPMiniLexer
from antlr.GPMiniListener import GPMiniListener
from antlr.GPMiniParser import GPMiniParser
from antlr.MyGPMiniVisitor import MyGPMiniVisitor
from gpParser import GpParser
import math
import timeit
class Fitness():
def __init__(self, heuristic, config):
self.heuristic = heuristic
self.config = config
self.input = []
self.output = []
self.prepare_data()
def prepare_data(self):
file = open('data/'+self.config.data, 'r')
data = file.read().split('\n')
for line in data:
line = line.split(':')
self.input.append(line[0].split())
self.output.append(line[1].split())
def fitness_function(self, indiv, best_fitness = None):
fitness = 0
output_generated = []
#parse
gpParser = GpParser(indiv)
result = gpParser.parse()
# result = 'var1 = -34;var4 = -53;var2 = input;var3 = -76;var4 = ((not false) >= true);output var2;var5 = input;if ((not ((not false) > (not false)))){output var4;}var6 = (-76 // var5);'
# interpreter
input_stream = InputStream(result)
lexer = GPMiniLexer(input_stream)
stream = CommonTokenStream(lexer)
parser = GPMiniParser(stream)
tree = parser.program()
len_input = len(self.input)
for i in range(len_input):
visitor = MyGPMiniVisitor(self.config.max_interpreter_steps, self.input[i])
tab = visitor.visitProgram(tree)
output_generated = tab[0]
# fitness += tab[1]
if 'ERROR' in output_generated:
fitness -= math.inf
elif output_generated == []:
fitness -= math.inf
else:
# fitness += self.heuristic.rate(self.config.heuristic, self.input[i], self.output[i], output_generated)
fitness += self.heuristic.rate(self.config.heuristic, self.input[i], self.output[i], output_generated, best_fitness, len_input)
# print(f"output_generated = {output_generated} \nfitness = {fitness}\n")
return fitness