"""Validation of certify.py and production of the certification tables (constant and time-varying data).
Run: python3 cert_validate.py   (writes ../results/certified_*.json)"""
import json, time, random
from fractions import Fraction as Fr
import mpmath as mp
from certify import *
from series import Model, weights
from tv import TV
mp.mp.dps = 50
H = {'-4/5': -0.8, '-1': -1.0}
out = {'const': {}, 'tv': {}}
random.seed(5)
print('== self-test: majorant >= exact ||Res(t)||_1 at 400 random points; sampled vs certified supremum')
for data in ('const', 'tv'):
    for k in range(1, 8):
        for hs in H:
            M = 20; h = Fr(hs)
            res = (residual_const(k, h, M)[0] if data == 'const' else residual_tv(k, h, M)[0])
            mu = exact_params(k)['mu']; m = -mu if k != 5 else exact_params(5)['eta'] - mu
            C = Certifier(res, 10); C.refine(m, 0.02, 400); supU, BT, Bmax = C.bound(m)
            viol = 0
            for _ in range(120):
                s = Fr(random.randint(0, 10 ** 6), 10 ** 6)
                val = C.point_value(s)
                for lev, idx, U in C.leaves:
                    if Fr(idx, 2 ** lev) <= s <= Fr(idx + 1, 2 ** lev):
                        if val > U: viol += 1
            samp = sampled_sup(res, 10, 81 if data == 'const' else 101)
            fine = max(float(C.point_value(Fr(j, 200))) for j in range(201))
            out[data]['%d,%s' % (k, hs)] = dict(violations=viol, sampled=samp, fine201=fine, cert_sup=supU, bound_T=BT, bound_sup=Bmax, m=float(m), leaves=len(C.leaves))
            print(data, k, hs, 'viol=%d' % viol, 'sampled=%.3e fine=%.3e certified_sup<=%.3e  B(T)<=%.3e' % (samp, fine, supU, BT), flush=True)
assert all(v['violations'] == 0 for d in out.values() for v in d.values())
json.dump(out, open('../results/certified_residuals.json', 'w'), indent=1)

print('== certified bound vs true error (1-norm), M = 20')
def true_const(k, h, M=20, npts=401):
    m = Model(k); w = weights(h, M); worst = mp.mpf(0)
    for j in range(npts):
        t = mp.mpf(10) * j / (npts - 1); x = m.exact(t); ph = m.phi(t, w)
        worst = max(worst, mp.fsum(abs(a - b) for a, b in zip(ph, x)))
    return float(worst)
def true_tv(k, h, M=20, npts=201):
    m = TV(k); c = m.exact_series(160); w = weights(h, M); worst = mp.mpf(0)
    for j in range(npts):
        t = mp.mpf(10) * j / (npts - 1); x = [mp.polyval([c[d][i] for d in range(len(c) - 1, -1, -1)], t) for i in range(m.n)]
        ph = m.phi(t, w); worst = max(worst, mp.fsum(abs(a - b) for a, b in zip(ph, x)))
    return float(worst)
for data in ('const', 'tv'):
    for k in range(1, 8):
        for hs, h in H.items():
            tr = true_const(k, h) if data == 'const' else true_tv(k, h)
            e = out[data]['%d,%s' % (k, hs)]; e['true_1norm_sup'] = tr
            assert e['bound_sup'] >= tr, (data, k, hs, e['bound_sup'], tr)
            print(data, k, hs, 'true=%.3e  certified bound=%.3e  ratio=%.2f' % (tr, e['bound_sup'], e['bound_sup'] / tr), flush=True)
json.dump(out, open('../results/certified_residuals.json', 'w'), indent=1)
print('ALL CERTIFICATES CONSISTENT WITH THE TRUE ERROR')
