forked from tea-lang-org/tea-lang
/
evaluate.py
420 lines (345 loc) · 19.2 KB
/
evaluate.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
from tea.ast import ( Node, Variable, Literal,
Equal, NotEqual, LessThan,
LessThanEqual, GreaterThan, GreaterThanEqual,
Relate
)
from tea.runtimeDataStructures.dataset import Dataset
from tea.runtimeDataStructures.varData import VarData
from tea.runtimeDataStructures.bivariateData import BivariateData
from tea.runtimeDataStructures.multivariateData import MultivariateData
from tea.runtimeDataStructures.resultData import ResultData
from tea.helpers.evaluateHelperMethods import determine_study_type, assign_roles, add_paired_property, execute_test, correct_multiple_comparison
from tea.z3_solver.solver import synthesize_tests
import attr
from typing import Any
from types import SimpleNamespace # allows for dot notation access for dictionaries
from typing import Dict
from scipy import stats # Stats library used
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np # Use some stats from numpy instead
import pandas as pd
# TODO: Pass participant_id as part of experimental design, not load_data
def evaluate(dataset: Dataset, expr: Node, assumptions: Dict[str, str], design: Dict[str, str]=None):
if isinstance(expr, Variable):
# dataframe = dataset[expr.name] # I don't know if we want this. We may want to just store query (in metadata?) and
# then use query to get raw data later....(for user, not interpreter?)
metadata = dataset.get_variable_data(expr.name) # (dtype, categories)
# if expr.name == 'strategy':
# import pdb; pdb.set_trace()
metadata['var_name'] = expr.name
metadata['query'] = ''
return VarData(metadata)
elif isinstance(expr, Literal):
data = pd.Series([expr.value] * len(dataset.data), index=dataset.data.index) # Series filled with literal value
# metadata = None # metadata=None means literal
metadata = dict() # metadata=None means literal
metadata['var_name'] = '' # because not a var in the dataset
metadata['query'] = ''
metadata['value'] = expr.value
return VarData(data, metadata)
elif isinstance(expr, Equal):
lhs = evaluate(dataset, expr.lhs)
rhs = evaluate(dataset, expr.rhs)
assert isinstance(lhs, VarData)
assert isinstance(rhs, VarData)
dataframe = lhs.dataframe[lhs.dataframe == rhs.dataframe]
metadata = lhs.metadata
if (isinstance(expr.rhs, Literal)):
metadata['query'] = f" == \'{rhs.metadata['value']}\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" == {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, NotEqual):
rhs = evaluate(dataset, expr.rhs)
lhs = evaluate(dataset, expr.lhs)
assert isinstance(rhs, VarData)
assert isinstance(lhs, VarData)
dataframe = lhs.dataframe[lhs.dataframe != rhs.dataframe]
metadata = lhs.metadata
if (isinstance(expr.rhs, Literal)):
metadata['query'] = " != \'\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" != {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, LessThan):
lhs = evaluate(dataset, expr.lhs)
rhs = evaluate(dataset, expr.rhs)
assert isinstance(lhs, VarData)
assert isinstance(rhs, VarData)
dataframe = None
metadata = rhs.metadata
if (not lhs.metadata):
raise ValueError('Malformed Relation. Filter on Variables must have variable as rhs')
elif (lhs.metadata['dtype'] is DataType.NOMINAL):
raise ValueError('Cannot compare nominal values with Less Than')
elif (lhs.metadata['dtype'] is DataType.ORDINAL):
# TODO May want to add a case should RHS and LHS both be variables
# assert (rhs.metadata is None)
comparison = rhs.dataframe.iloc[0]
if (isinstance(comparison, str)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] < categories[comparison]]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
elif (np.issubdtype(comparison, np.integer)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] < comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise ValueError(f"Cannot compare ORDINAL variables to {type(rhs.dataframe.iloc[0])}")
elif (lhs.metadata['dtype'] is DataType.INTERVAL or lhs.metadata['dtype'] is DataType.RATIO):
comparison = rhs.dataframe.iloc[0]
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if x < comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise Exception(f"Invalid Less Than Operation:{lhs} < {rhs}")
if (isinstance(expr.rhs, Literal)):
metadata['query'] = " < \'\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" < {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, LessThanEqual):
lhs = evaluate(dataset, expr.lhs)
rhs = evaluate(dataset, expr.rhs)
assert isinstance(lhs, VarData)
assert isinstance(rhs, VarData)
dataframe = None
metadata = rhs.metadata
if (not lhs.metadata):
raise ValueError('Malformed Relation. Filter on Variables must have variable as rhs')
elif (lhs.metadata['dtype'] is DataType.NOMINAL):
raise ValueError('Cannot compare nominal values with Less Than')
elif (lhs.metadata['dtype'] is DataType.ORDINAL):
# TODO May want to add a case should RHS and LHS both be variables
# assert (rhs.metadata is None)
comparison = rhs.dataframe.iloc[0]
if (isinstance(comparison, str)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] <= categories[comparison]]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
elif (np.issubdtype(comparison, np.integer)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] <= comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise ValueError(f"Cannot compare ORDINAL variables to {type(rhs.dataframe.iloc[0])}")
elif (lhs.metadata['dtype'] is DataType.INTERVAL or lhs.metadata['dtype'] is DataType.RATIO):
comparison = rhs.dataframe.iloc[0]
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if x <= comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise Exception(f"Invalid Less Than Equal Operation:{lhs} <= {rhs}")
if (isinstance(expr.rhs, Literal)):
metadata['query'] = " <= \'\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" <= {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, GreaterThan):
lhs = evaluate(dataset, expr.lhs)
rhs = evaluate(dataset, expr.rhs)
assert isinstance(lhs, VarData)
assert isinstance(rhs, VarData)
dataframe = None
metadata = rhs.metadata
if (not lhs.metadata):
raise ValueError('Malformed Relation. Filter on Variables must have variable as rhs')
elif (lhs.metadata['dtype'] is DataType.NOMINAL):
raise ValueError('Cannot compare nominal values with Greater Than')
elif (lhs.metadata['dtype'] is DataType.ORDINAL):
# TODO May want to add a case should RHS and LHS both be variables
# assert (rhs.metadata is None)
comparison = rhs.dataframe.iloc[0]
if (isinstance(comparison, str)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] > categories[comparison]]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
elif (np.issubdtype(comparison, np.integer)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] > comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise ValueError(f"Cannot compare ORDINAL variables to {type(rhs.dataframe.iloc[0])}")
elif (lhs.metadata['dtype'] is DataType.INTERVAL or lhs.metadata['dtype'] is DataType.RATIO):
comparison = rhs.dataframe.iloc[0]
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if x > comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise Exception(f"Invalid Greater Than Operation:{lhs} > {rhs}")
if (isinstance(expr.rhs, Literal)):
metadata['query'] = " > \'\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" > {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, GreaterThanEqual):
lhs = evaluate(dataset, expr.lhs)
rhs = evaluate(dataset, expr.rhs)
assert isinstance(lhs, VarData)
assert isinstance(rhs, VarData)
dataframe = None
metadata = rhs.metadata
if (not lhs.metadata):
raise ValueError('Malformed Relation. Filter on Variables must have variable as rhs')
elif (lhs.metadata['dtype'] is DataType.NOMINAL):
raise ValueError('Cannot compare nominal values with Greater Than Equal')
elif (lhs.metadata['dtype'] is DataType.ORDINAL):
# TODO May want to add a case should RHS and LHS both be variables
# assert (rhs.metadata is None)
comparison = rhs.dataframe.iloc[0]
if (isinstance(comparison, str)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] >= categories[comparison]]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
elif (np.issubdtype(comparison, np.integer)):
categories = lhs.metadata['categories'] # OrderedDict
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if categories[x] >= comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise ValueError(f"Cannot compare ORDINAL variables to {type(rhs.dataframe.iloc[0])}")
elif (lhs.metadata['dtype'] is DataType.INTERVAL or lhs.metadata['dtype'] is DataType.RATIO):
comparison = rhs.dataframe.iloc[0]
# Get raw Pandas Series indices for desired data
ids = [i for i,x in enumerate(lhs.dataframe) if x >= comparison]
# Get Pandas Series set indices for desired data
p_ids = [lhs.dataframe.index.values[i] for i in ids]
# Create new Pandas Series with only the desired data, using set indices
dataframe = pd.Series(lhs.dataframe, p_ids)
dataframe.index.name = dataset.pid_col_name
else:
raise Exception(f"Invalid Greater Than Equal Operation:{lhs} >= {rhs}")
if (isinstance(expr.rhs, Literal)):
metadata['query'] = " >= \'\'" # override lhs metadata for query
elif (isinstance(expr.rhs, Variable)):
metadata['query'] = f" >= {rhs.metadata['var_name']}"
else:
raise ValueError(f"Not implemented for {rhs}")
return VarData(metadata)
elif isinstance(expr, Relate):
vars = []
for v in expr.vars:
eval_v = evaluate(dataset, v, design)
if not eval_v:
raise ValueError("The variables you are referencing are not defined as variables in your list of variables.")
assert isinstance(eval_v, VarData)
vars.append(eval_v)
# What kind of study are we analyzing?
study_type = determine_study_type(vars, design)
# Assign roles to variables we are analyzing
vars = assign_roles(vars, study_type, design)
combined_data = None
# Do we have a Bivariate analysis?
if len(vars) == 2:
combined_data = BivariateData(vars, study_type, alpha=float(assumptions['alpha']))
else: # Do we have a Multivariate analysis?
combined_data = MultivariateData(vars, study_type, alpha=float(assumptions['alpha']))
# Add paired property
add_paired_property(dataset, combined_data, study_type, design) # check sample sizes are identical
tests = synthesize_tests(dataset, assumptions, combined_data)
""""
# verify_properties(properties_and_tests)
# get_tests
# execute_tests
# interpret_tests_results
# print(tests)
for test in tests:
print("\nValid test: %s" % test.name)
print("Properties:")
properties = test.properties()
for prop in properties:
property_identifier = ""
if prop.scope == "test":
property_identifier = test.name + ": " + prop.name
else:
for var_indices in test.properties_for_vars[prop]:
for var_index in var_indices:
property_identifier += f"variable {test.test_vars[var_index].name} "
property_identifier += ": %s" % prop.name
print(property_identifier)
"""
# Execute and store results from each valid test
results = {}
if len(tests) == 0:
tests.append('bootstrap') # Default to bootstrap
for test in tests:
test_result = execute_test(dataset, design, expr.predictions, combined_data, test)
results[test] = test_result
res_data = ResultData(results)
# TODO: use a handle here to more generally/modularly support corrections, need a more generic data structure for this!
if expr.predictions:
preds = expr.predictions
# There are multiple comparisons
# if len(preds > 1):
# FOR DEBUGGING:
if len(preds) >= 1:
correct_multiple_comparison(res_data, len(preds))
return res_data
elif isinstance(expr, Mean):
var = evaluate(dataset, expr.var)
assert isinstance(var, VarData)
# bs.bootstrap(var.dataframe, stat_func=
# bs_stats.mean)
raise Exception('Not implemented Mean')