-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrammar.py
More file actions
62 lines (52 loc) · 1.8 KB
/
Copy pathgrammar.py
File metadata and controls
62 lines (52 loc) · 1.8 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
# Grammar Lib
class Grammar:
# Initial grammar
op = ['+', '-', '/', '*']
#exp = [['exp', 'op', 'exp'], ['sin(', 'exp', ')'], ['cos(', 'exp', ')'], ['sqrt(', 'exp', ')'], 'var']
exp = [['exp', 'op', 'exp'], ['sqrt(', 'exp', ')'], ['log(', 'exp', ')'], ['exp(', 'exp', ')'], 'const', 'var']
expWeight = [40, 5, 5, 10, 40]
var = []
# def __init__(self, numVariables):
# for i in range(numVariables):
# self.var.append("x" + str(i))
# print(self.var)
def symbolReplacement(self, expression, symbol, position):
if not isinstance(symbol, list):
expression[position] = symbol
else:
expression[position] = symbol[0]
k = 1
for element in symbol[1:]:
expression.insert(position + k, element)
k = k + 1
def setVariables(self, variables):
self.var = variables
def cromossomeToExpression(self, C):
cromossome = C.getList()
expression = ['exp']
i = 0
i_max = 50
k = 0
while(i < len(expression)):
if(expression[i] == 'exp' or expression[i] == 'var' or expression[i] == 'op' or expression[i] == 'digit'):
if(expression[i] == 'exp'):
if(i < i_max):
newSymbol = self.exp[cromossome[k] % len(self.exp)]
else:
newSymbol = self.exp[-1]
elif(expression[i] == 'op'):
newSymbol = self.op[cromossome[k] % len(self.op)]
elif(expression[i] == 'var'):
newSymbol = "v['" + self.var[cromossome[k] % len(self.var)] + "']"
elif(expression[i] == 'const'):
newSymbol = str(cromossome[k])
self.symbolReplacement(expression, newSymbol, i)
k = k + 1
k = k % len(cromossome)
else:
i = i + 1
if(i == i_max):
expression = "NaN"
else:
expression = "".join(expression)
return expression