"""Extend the published grid with exact named powers, without changing the solver.

Requires the dependencies listed by model_sweep.py. Put that solver and
sweep.csv beside this script, or in a data/ subdirectory. Run with Python 3.
Writes grid.json and GRID_CHECKS.json beside this script.
"""
from pathlib import Path
import csv
import hashlib
import json
import math
import sys

HERE = Path(__file__).parent
INPUT = HERE/'data' if (HERE/'data/model_sweep.py').is_file() else HERE
assert hashlib.sha256((INPUT/'model_sweep.py').read_bytes()).hexdigest() == 'a0b3fadc99fbd9b64cac8450b6b98914ad6d8101c36a541605b64d4b853929cc'
assert hashlib.sha256((INPUT/'sweep.csv').read_bytes()).hexdigest() == '9a083b4a2eb737245c26f5c4f3c0678478d76fa15c950ef3ee4e61b9ffb23d69'
sys.path.insert(0,str(INPUT))
import model_sweep as m
rows = []
for r in csv.DictReader((INPUT/'sweep.csv').open()):
    rows.append({'n':float(r['n']), 'q':int(r['Q']), 'a':float(r['a']),
                 'ch':[float(r['ch_'+w]) for w in ['0.24','0.5','1.2']],
                 'r12':float(r['R12']), 'r13':float(r['R13']), 'grid':True})
widths = [0.24,0.5,1.2]
capacities = [200,350,500,750,1000,1500,2000]
named = [
    [2.10732997,'Solution pH 6 refit'],[2.02,'Solution pH 6 published power'],
    [1.76394234,'Solution pH 7 refit'],[1.11636664,'Solution pH 8 refit'],
    [0.46932662,'Solution pH 9 refit'],[0.41315569,'Solution pH 10 refit']]
ch = [m.chamber_sched(w) for w in widths]
de = m.delousing_sched()
calibration_errors = []
for n,label in named:
    for q in capacities:
        a = m.calibrate(n,q)
        v = [m.run(a,n,q,1.,*s) for s in ch]
        d = m.run(a,n,q,1.,*de)
        assert all(math.isfinite(x) and x >= 0 for x in [a,*v,d])
        residual = abs(m.run(a,n,q,1.,m.np.array([24.75,1704.]),m.np.array([1.,0.]))-m.LAB_TARGET)
        calibration_errors.append(residual)
        assert residual < 0.05, (n,q,residual)
        rows.append({'n':n,'q':q,'a':round(a,8),'ch':[round(x,2) for x in v],
                     'r12':round(.85*d,2),'r13':round(.90*d,2),'grid':False})
    print(label, 'complete', flush=True)
assert len(rows)==175 and len({(r['n'],r['q']) for r in rows})==175
opening=next(r for r in rows if r['n']==2.10732997 and r['q']==500)
assert opening['ch'][0]==8.18 and round(opening['r12'])==2884 and round(opening['r13'])==3053
data={'version':1,'method':'Published fixed-step solver, 0.01-hour step; each power and capacity recalibrated to the same laboratory endpoint.',
      'solver_sha256':'a0b3fadc99fbd9b64cac8450b6b98914ad6d8101c36a541605b64d4b853929cc',
      'sweep_sha256':'9a083b4a2eb737245c26f5c4f3c0678478d76fa15c950ef3ee4e61b9ffb23d69',
      'widths_minutes':[14.4,30,72],'capacities':capacities,'named_powers':named,
      'assays':{'initial_r3':6.7,'r12':2900,'r13':3000,'r3_retest':'Below detection; effective detection limit not established here.'},
      'rows':rows}
(HERE/'grid.json').write_text(json.dumps(data,separators=(',',':'))+'\n')
(HERE/'GRID_CHECKS.json').write_text(json.dumps({'rows':175,'retained_published_rows':133,'new_exact_power_rows':42,'max_calibration_residual_mg_kg':max(calibration_errors),'opening':opening,'grid_sha256':hashlib.sha256((HERE/'grid.json').read_bytes()).hexdigest(),'status':'PASS'},indent=2)+'\n')
print('PASS',len(rows),'rows; max calibration error',max(calibration_errors),flush=True)
