|
|
import os |
|
|
import sys |
|
|
import importlib.util |
|
|
import numpy as np |
|
|
import pandas as pd |
|
|
import pytest |
|
|
|
|
|
NMSE_THRESHOLD = 3e-5 |
|
|
|
|
|
|
|
|
with open(os.path.join(os.path.dirname(__file__), './filtered_formula_py.txt')) as f: |
|
|
formula_py_list = [line.strip() for line in f if line.strip()] |
|
|
|
|
|
def dynamic_import_formula(formula_path): |
|
|
|
|
|
spec = importlib.util.spec_from_file_location('formula', formula_path) |
|
|
module = importlib.util.module_from_spec(spec) |
|
|
setattr(module, 'np', np) |
|
|
sys.modules['formula'] = module |
|
|
spec.loader.exec_module(module) |
|
|
|
|
|
func = None |
|
|
for name in dir(module): |
|
|
if not name.startswith('__') and callable(getattr(module, name)): |
|
|
func = getattr(module, name) |
|
|
break |
|
|
return func |
|
|
|
|
|
def find_all_csv_files(formula_path): |
|
|
|
|
|
base_dir = os.path.dirname(formula_path) |
|
|
csv_files = [] |
|
|
for fname in os.listdir(base_dir): |
|
|
if fname.endswith('.csv'): |
|
|
fpath = os.path.join(base_dir, fname) |
|
|
|
|
|
if os.path.getsize(fpath) > 0: |
|
|
csv_files.append(fpath) |
|
|
return csv_files |
|
|
|
|
|
def calc_nmse(y_true, y_pred): |
|
|
y_true = np.asarray(y_true) |
|
|
y_pred = np.asarray(y_pred) |
|
|
mse = np.mean((y_true - y_pred) ** 2) |
|
|
var = np.mean((y_true - np.mean(y_true)) ** 2) |
|
|
if var == 0: |
|
|
return np.inf if mse > 0 else 0 |
|
|
return mse / var |
|
|
|
|
|
@pytest.mark.parametrize('formula_path', formula_py_list) |
|
|
def test_formula(formula_path): |
|
|
func = dynamic_import_formula(formula_path) |
|
|
csv_files = find_all_csv_files(formula_path) |
|
|
assert csv_files, f'No csv files found for {formula_path}' |
|
|
for csv_file in csv_files: |
|
|
df = pd.read_csv(csv_file) |
|
|
if df.shape[1] < 2: |
|
|
continue |
|
|
target_col = df.columns[-1] |
|
|
input_cols = df.columns[:-1] |
|
|
|
|
|
df = df.iloc[:1000] |
|
|
y_true = df[target_col].values |
|
|
y_pred = [] |
|
|
for _, row in df.iterrows(): |
|
|
try: |
|
|
y_pred.append(func(*(row[col] for col in input_cols))) |
|
|
except Exception as e: |
|
|
pytest.fail(f'Error in {formula_path} {csv_file} row: {e}') |
|
|
nmse = calc_nmse(y_true, y_pred) |
|
|
assert nmse < NMSE_THRESHOLD, f'{formula_path} {csv_file} nmse={nmse} >= {NMSE_THRESHOLD}' |
|
|
|