"""Builds the LaTeX tables of the new Section 9.4 from ../results/*.json.  Run after cert_validate.py, sensitivity.py, model5_study.py."""
import json, numpy as np
C = json.load(open('../results/certified_residuals.json')); S = json.load(open('../results/sensitivity.json')); M5 = json.load(open('../results/model5.json'))
def sci(v):
    v = float(v)
    if v == 0: return '$0$'
    e = int(np.floor(np.log10(abs(v)))); a = v / 10 ** e
    if round(a, 1) >= 10: a /= 10; e += 1
    return ('$%.2g$' % v) if -2 <= e <= 1 else r'$%.1f\times10^{%d}$' % (a, e)
def w(name, body): open('../tables/%s.tex' % name, 'w').write(body)
# certified table
rows = []
for dt in ('const', 'tv'):
    for k in range(1, 8):
        e = C[dt]['%d,-4/5' % k]; h = C[dt]['%d,-1' % k]
        rows.append('%s%d & %s & %s & %s & %s & %.2f & %.2f\\\\' % ('' if dt == 'const' else 'tv ', k, sci(e['sampled']), sci(e['cert_sup']), sci(e['bound_sup']), sci(e['true_1norm_sup']), e['bound_sup'] / e['true_1norm_sup'], h['bound_sup'] / h['true_1norm_sup']))
    if dt == 'const': rows.append('\\midrule')
w('cert', '\\begin{tabular}{lrrrrrr}\n\\toprule\nModel & sampled $\\sup\\|\\mathrm{Res}\\|_1$ & certified $\\sup$ & certified bound & true error & ratio ($\\hbar{=}{-}0.8$) & ratio (HPM)\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
# elasticity
names = [('Lam', r'$\Lambda$'), ('mu', r'$\mu$'), ('b1', r'$\beta_1$'), ('b2', r'$\beta_2$'), ('b3', r'$\beta_3$'), ('al', r'$\alpha$'), ('b4', r'$\beta_4$'), ('ga', r'$\gamma$'), ('de', r'$\delta$'), ('u1', r'$\bar u_1$'), ('u2', r'$\bar u_2$')]
rows = []
for key, lab in names:
    cells = []
    for k in range(1, 8):
        v = S['elasticity_B10'][str(k)].get(key); cells.append('--' if v is None else '%.2f' % v)
    rows.append(lab + ' & ' + ' & '.join(cells) + '\\\\')
w('elast', '\\begin{tabular}{lccccccc}\n\\toprule\n & M1 & M2 & M3 & M4 & M5 & M6 & M7\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
# ranges +-50%
rows = []
for k in range(1, 8):
    r = S['ranges_pm50'][str(k)]
    rows.append('%d & %.2f & %d--%d & %d--%d & %s--%s & %s--%s\\\\' % (k, 10 * r['base']['K'], r['M_ham'][0], r['M_ham'][1], r['M_hpm'][0], r['M_hpm'][1], sci(r['E_ham'][0]), sci(r['E_ham'][1]), sci(r['E_hpm'][0]), sci(r['E_hpm'][1])))
w('pm50', '\\begin{tabular}{lccccc}\n\\toprule\nModel & $KT$ (baseline) & order$_{\\rm HAM}$ & order$_{\\rm HPM}$ & $E_{20}$ HAM & $E_{20}$ HPM\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
# initial conditions
rows = []
for k in range(1, 8):
    r = S['initial'][str(k)]
    rows.append('%d & %s--%s & %s & %s & %s\\\\' % (k, sci(r['dir_E_ham'][0]), sci(r['dir_E_ham'][2]), sci(r['A']['ham']), sci(r['A']['hpm']), sci(r['ratio_min'])))
w('ic', '\\begin{tabular}{lcccc}\n\\toprule\nModel & $E_{20}$ (HAM), 150 random $\\mathbf x_0$ & $A_{20}$ (HAM) & $A_{20}$ (HPM) & min HPM/HAM error\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
# campaigns
rows = []
for k in range(1, 8):
    c = S['campaign'][str(k)]
    rows.append('%d & %.3f & %.3f & %.3f & %s & %s\\\\' % (k, c[0]['B10'], c[5]['B10'], c[10]['B10'], sci(max(r['N10'] for r in c) - min(r['N10'] for r in c)), sci(max(r['err_ham'] for r in c))))
w('camp', '\\begin{tabular}{lccccc}\n\\toprule\nModel & $B(10)$, $D{=}0$ & $D{=}5$ & $D{=}10$ & spread of $N(10)$ over $D$ & max two-stage HAM error\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
# model 5 vs 5c
rows = ['%.2f & %.3f & %.2f & %.2f\\\\' % (r[0], r[1], r[2], r[3]) for r in M5['eta_scan']['rows'] if r[0] in (0.0, 0.1, 0.15, 0.35, 0.45)]
w('m5scan', '\\begin{tabular}{cccc}\n\\toprule\n$\\eta$ & $\\Theta$ & $N^*$ (Model 5) & $N^*$ (variant 5c)\\\\\n\\midrule\n' + '\n'.join(rows) + '\n\\bottomrule\n\\end{tabular}\n')
r5, r5c = M5['week10']['rows']
w('m5week', '\\begin{tabular}{lcccccc}\n\\toprule\n & $U(10)$ & $C(10)$ & $L(10)$ & $R(10)$ & $N(10)$ & $N^*$\\\\\n\\midrule\nModel 5 & %.3f & %.3f & %.3f & %.3f & %.3f & %.3f\\\\\nVariant 5c & %.3f & %.3f & %.3f & %.3f & %.3f & %.3f\\\\\n\\bottomrule\n\\end{tabular}\n' % (r5[1], r5[2], r5[4], r5[5], r5[6], r5[7], r5c[1], r5c[2], r5c[4], r5c[5], r5c[6], r5c[7]))
print(open('../tables/cert.tex').read()); print(open('../tables/pm50.tex').read()); print(open('../tables/ic.tex').read()); print(open('../tables/camp.tex').read()); print(open('../tables/m5week.tex').read()); print(open('../tables/m5scan.tex').read()); print(open('../tables/elast.tex').read())
print('ratio ranges: ham const', min(C['const'][k]['bound_sup']/C['const'][k]['true_1norm_sup'] for k in C['const'] if k.endswith('-4/5')))
