"""Reproduce all six Cell Response Evidence Explorer folds.
GPL-3.0-or-later. Requires only the Python standard library.
Run: python3 reproduce.py [path/to/data/vinclozolin.csv]
"""
import csv, json, math, statistics, sys
from pathlib import Path

path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).parent / 'data/vinclozolin.csv'
data = [dict(day=r['exper'], conc=float(r['conc']), y=float(r['effect'])) for r in csv.DictReader(path.open())]
results = []
for day in sorted({r['day'] for r in data}):
    train = [r for r in data if r['day'] != day]
    test = [r for r in data if r['day'] == day]
    group = {c: statistics.mean(r['y'] for r in train if r['conc'] == c) for c in {r['conc'] for r in train}}
    constant = statistics.mean(r['y'] for r in train)
    def score(predictions):
        errors = [p-r['y'] for p, r in zip(predictions, test)]
        ss = sum((r['y']-statistics.mean(x['y'] for x in test))**2 for r in test)
        return dict(mae=statistics.mean(abs(e) for e in errors), rmse=math.sqrt(statistics.mean(e*e for e in errors)), r2=1-sum(e*e for e in errors)/ss if ss else None)
    results.append(dict(holdout=day, trainN=len(train), testN=len(test), dose=score([group[r['conc']] for r in test]), global_mean=score([constant]*len(test))))
print(json.dumps(results, indent=2))
