-
Notifications
You must be signed in to change notification settings - Fork 74
/
symbolic_utils.py
252 lines (219 loc) · 7.71 KB
/
symbolic_utils.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
import pdb
import pandas as pd
from yaml import load, Loader
import sympy
# from sympy import *
from sympy import Symbol, simplify, factor, Float, preorder_traversal, Integer
from sympy.parsing.sympy_parser import parse_expr
from read_file import read_file
import re
import ast
###############################################################################
# fn definitions from the algorithms, written in sympy operators
def sub(x,y):
return sympy.Add(x,-y)
# def division(x,y):
# print('division')
# if isinstance(y, sympy.Float):
# if abs(y) < 0.00001:
# return x
# # result = sympy.Mod(x,1e-6+abs(y))
# # if y < 0:
# # result = -result
# # return result
# return sympy.Mul(x,1/y)
#TODO: handle protected division
def div(x,y):
return sympy.Mul(x,1/y)
def square(x):
return sympy.Pow(x,2)
def cube(x):
return sympy.Pow(x,3)
def quart(x):
return sympy.Pow(x,4)
def PLOG(x, base=None):
if isinstance(x, sympy.Float):
if x < 0:
x = sympy.Abs(x)
if base:
return sympy.log(x,base)
else:
return sympy.log(x)
def PLOG10(x):
return PLOG(x,10)
def PSQRT(x):
if isinstance(x, sympy.Float):
if x < 0:
return sympy.sqrt(sympy.Abs(x))
return sympy.sqrt(x)
###############################################################################
def complexity(expr):
c=0
for arg in preorder_traversal(expr):
c += 1
return c
def round_floats(ex1):
ex2 = ex1
for a in preorder_traversal(ex1):
if isinstance(a, Float):
if abs(a) < 0.0001:
ex2 = ex2.subs(a,Integer(0))
else:
ex2 = ex2.subs(a, Float(round(a, 3),3))
return ex2
################################################################################
# currently the MRGP model is put together incorrectly. this set of functions
# corrects the MRGP model form so that it can be fed to sympy and simplified.
################################################################################
def add_commas(model):
return ''.join([m + ',' if not m.endswith('(') else m
for m in model.split()])[:-1]
def decompose_mrgp_model(model_str):
"""split mrgp model into its betas and model parts"""
new_model=[]
# get betas
betas = [float(b[0]) for b in re.findall(
r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\*',
model_str)]
print('betas:',betas)
# get form
submodel = re.sub(pattern=r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\*',
repl=r'',
string=model_str)
return betas, submodel #new_model
def print_model(node):
if hasattr(node, 'func'):
model_str = node.func.id + '('
elif hasattr(node, 'id'):
# model_str = node.id
return node.id
else:
pdb.set_trace()
if hasattr(node, 'args'):
i = 0
for arg in node.args:
model_str += print_model(arg)
i += 1
if i < len(node.args):
model_str += ','
model_str += ')'
# print('print_model::',model_str)
return model_str
def add_betas(node, betas):
beta = betas[0]
betas.pop(0)
if float(beta) > 0:
model_str = str(beta) + '*' + print_model(node)
i = 1
else:
# print('filtering fn w beta=',beta)
model_str = ''
i = 0
if hasattr(node, 'args'):
for arg in node.args:
submodel = add_betas(arg, betas)
if submodel != '':
model_str += '+' if i != 0 else ''
model_str += submodel
i += 1
# print('add_betas::',model_str)
return model_str
################################################################################
def clean_pred_model(model_str, dataset, est_name):
mrgp = 'MRGP' in est_name
model_str = model_str.strip()
if mrgp:
model_str = model_str.replace('+','add')
model_str = add_commas(model_str)
betas, model_str = decompose_mrgp_model(model_str)
X, labels, features = read_file(dataset)
local_dict = {k:Symbol(k) for k in features}
new_model_str = model_str
# rename features
for i,f in enumerate(features):
print('replacing feature',i,'with',f)
if any([n in est_name.lower() for n in ['mrgp','operon','dsr']]):
i = i + 1
new_model_str = new_model_str.replace('x'+str(i),f)
new_model_str = new_model_str.replace('x_'+str(i),f)
new_model_str = new_model_str.replace('X_'+str(i),f)
new_model_str = new_model_str.replace('X'+str(i),f)
new_model_str = new_model_str.replace('x[:,{}]'.format(i),f)
new_model_str = new_model_str.replace('x[{}]'.format(i),f)
# operators
new_model_str = new_model_str.replace('^','**')
#GP-GOMEA
new_model_str = new_model_str.replace('p/','/')
new_model_str = new_model_str.replace('plog','PLOG')
new_model_str = new_model_str.replace('aq','/')
# MRGP
new_model_str = new_model_str.replace('mylog','PLOG')
# ITEA
new_model_str = new_model_str.replace('sqrtAbs','PSQRT')
# new_model_str = re.sub(pattern=r'sqrtAbs\((.*?)\)',
# repl=r'sqrt(abs(\1))',
# string=new_model_str
# )
new_model_str = new_model_str.replace('np.','')
# ellyn & FEAT
new_model_str = new_model_str.replace('|','')
new_model_str = new_model_str.replace('log','PLOG')
new_model_str = new_model_str.replace('sqrt','PSQRT')
# AIFeynman
new_model_str = new_model_str.replace('pi','3.1415926535')
local_dict.update({
'add':sympy.Add,
'mul':sympy.Mul,
'max':sympy.Max,
'min':sympy.Min,
'sub':sub,
'div':div,
'square':square,
'cube':cube,
'quart':quart,
'PLOG':PLOG,
'PLOG10':PLOG,
'PSQRT':PSQRT
})
# BSR
# get rid of square brackets
new_model_str = new_model_str.replace('[','').replace(']','')
print('parsing',new_model_str)
if mrgp:
mrgp_ast = ast.parse(new_model_str, "","eval")
new_model_str = add_betas(mrgp_ast.body,betas)
assert(len(betas)==0)
print(local_dict)
model_sym = parse_expr(new_model_str, local_dict = local_dict)
print('round_floats')
model_sym = round_floats(model_sym)
print('rounded:',model_sym)
print('simplify...')
model_sym = simplify(model_sym, ratio=1)
print('simplified:',model_sym)
return model_sym
def get_sym_model(dataset, return_str=True):
"""return sympy model from dataset metadata"""
metadata = load(
open('/'.join(dataset.split('/')[:-1])+'/metadata.yaml','r'),
Loader=Loader
)
df = pd.read_csv(dataset,sep='\t')
features = [c for c in df.columns if c != 'target']
# print('features:',df.columns)
description = metadata['description'].split('\n')
model_str = [ms for ms in description if '=' in ms][0].split('=')[-1]
model_str = model_str.replace('pi','3.1415926535')
if return_str:
return model_str
# pdb.set_trace()
# handle feynman problem constants
# print('model:',model_str)
model_sym = parse_expr(model_str,
local_dict = {k:Symbol(k) for k in features})
model_sym = round_floats(model_sym)
# print('sym model:',model_sym)
return model_sym
def rewrite_AIFeynman_model_size(model_str):
"""AIFeynman complexity was incorrect prior to version , update it here"""
return complexity(parse_expr(model_str))