"""Model 5: population interpretation, boundedness threshold and the conservative variant 5c.
Run: python3 model5_study.py   (writes ../results/model5.json, ../figures/fig_model5.pdf, ../tables/model5_*.tex)"""
import json, numpy as np, mpmath as mp
import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
from models import *; from theory import theta5, equilibrium; from models_alt import *
import fastham as fh
mp.mp.dps = 40
ok = True
def check(name, c, extra=''):
    global ok; ok &= bool(c); print(('PASS ' if c else 'FAIL ') + name, extra)
out = {}
p = params(5); Rw, Th, _ = theta5(p)
J5, b5 = system(5, p); J5c, b5c = system_5c(p); nm = NAMES[5]; n = len(nm)
check('Model 5: Theta_w = loop gain eta b2/(dE dA) = 0.321, Theta = 0.355', abs(Rw - mp.mpf('0.3214')) < 1e-3 and abs(Th - mp.mpf('0.3548')) < 1e-3, '(%s, %s)' % (mp.nstr(Rw, 5), mp.nstr(Th, 5)))
eta_c = mp.findroot(lambda e: theta5({**p, 'eta': e})[1] - 1, 0.45)
check('eta_c = 0.451 (manuscript Remark 4.x)', abs(eta_c - mp.mpf('0.451')) < 1e-3, mp.nstr(eta_c, 8))
# closed form of eta_c from Theorem 4.4:  eta_c = dE dA / b2 * (1 - (Theta - Theta_w))
dE = p['b2'] + p['mu']; dA = p['eps'] + p['al'] + p['mu']; eta_cf = dE * dA / p['b2'] * (1 - (Th - Rw))
check('eta_c closed form of Theorem 4.4 equals root of Theta = 1', abs(eta_c - eta_cf) < mp.mpf(10) ** -30, mp.nstr(eta_cf, 8))
# equilibrium total versus eta (original model) and conservative variant
etas = [mp.mpf(e) for e in ('0', '0.05', '0.10', '0.15', '0.25', '0.35', '0.40', '0.44', '0.45')]
rows = []; Nstar = []
for e in etas:
    q = {**p, 'eta': e}; Jq, bq = system(5, q); xs = mp.lu_solve(Jq, -bq); Nq = sum(xs)
    Jc, bc = system_5c(q); xc = mp.lu_solve(Jc, -bc)
    rows.append((float(e), float(theta5(q)[1]), float(Nq), float(sum(xc)), float(xs[nm.index('C')]), float(xc[nm.index('C')]), float(xs[nm.index('L')]), float(xc[nm.index('L')])))
    Nstar.append(float(Nq))
out['eta_scan'] = dict(header=['eta', 'Theta', 'N*_5', 'N*_5c', 'C*_5', 'C*_5c', 'L*_5', 'L*_5c'], rows=rows)
check('5c: equilibrium total equals Lam/mu for every eta', all(abs(r[3] - 5) < 1e-12 for r in rows))
check('5: N*(eta=0) = Lam/mu and N* increases to infinity as eta -> eta_c', abs(rows[0][2] - 5) < 1e-12 and all(rows[i][2] < rows[i + 1][2] for i in range(len(rows) - 1)))
# exact structural properties of 5c
cs = [sum(J5c[i, j] for i in range(n)) for j in range(n)]
check('5c: all column sums equal -mu', max(abs(c + p['mu']) for c in cs) < mp.mpf(10) ** -35)
check('5c: Metzler', all(J5c[i, j] >= 0 for i in range(n) for j in range(n) if i != j))
ev = np.linalg.eigvals(np.array(J5c.tolist(), float)); ev5 = np.linalg.eigvals(np.array(J5.tolist(), float))
check('5c: spectral abscissa = -mu (Theorem 4.? applies, no threshold)', abs(ev.real.max() + 0.1) < 1e-9, 'abscissa %.10f' % ev.real.max())
check('5 : spectral abscissa = -mu at eta = 0.15 < eta_c', abs(ev5.real.max() + 0.1) < 1e-9)
# trajectories: week-10 state for 5 and 5c, constant controls
ts = [mp.mpf(j) / 4 for j in range(41)]
x0 = initial(5); res = {}
for tag, (J, b) in (('5', (J5, b5)), ('5c', (J5c, b5c))):
    xs = mp.lu_solve(J, -b); X = [xs + mp.expm(J * t) * (x0 - xs) for t in ts]; res[tag] = (X, xs)
def st(X, name): return float(X[-1][nm.index(name)])
rows = []
for tag in ('5', '5c'):
    X, xs = res[tag]; conv = lambda v: float(v[nm.index('C')])
    peak = max(range(41), key=lambda s: conv(X[s]))
    rows.append([tag, st(X, 'U'), st(X, 'C'), float(ts[peak]), st(X, 'L'), st(X, 'R'), float(sum(X[-1])), float(sum(xs))])
out['week10'] = dict(header=['model', 'U(10)', 'C(10)', 'peak wk', 'L(10)', 'R(10)', 'N(10)', 'N*'], rows=rows)
for r in rows: print('   ', r)
# HAM / HPM accuracy for 5c, constant controls and time-varying controls
ts_ld = np.linspace(0, 10, 201).astype(fh.LD)
J, b, xx = fh.to_ld(J5c), np.array([fh.LD(mp.nstr(v, 28)) for v in b5c], dtype=fh.LD), fh.to_ld(x0.T)[0] if False else np.array([fh.LD(mp.nstr(v, 28)) for v in x0], dtype=fh.LD)
T = fh.picard_terms(J, b, xx, ts_ld, 40); R = fh.reference_const(J, b, xx, ts_ld)
e5c = {}
for M in (10, 15, 20, 25):
    e5c[M] = (float(fh.err_const(J, b, xx, ts_ld, M, -0.8, T, R).max()), float(fh.err_const(J, b, xx, ts_ld, M, -1.0, T, R).max()))
out['err_5c_const'] = e5c; print('    5c constant controls, (HAM -0.8, HPM):', e5c)
# certified bounds for 5c (constant and time-varying)
from certify import certify
from fractions import Fraction as Fr
out['cert_5c'] = {d: certify('5c', Fr('-4/5'), 20, d) for d in ('const', 'tv')}
out['cert_5'] = {d: certify(5, Fr('-4/5'), 20, d) for d in ('const', 'tv')}
print('    certified (M=20, h=-0.8): 5c', out['cert_5c'], '\n                              5 ', out['cert_5'])
# time-varying controls: boundedness of Model 5 under the tv data (Theta(u+) < 1) and balance law of 5c
ctrl = dict(u1=(0.9, -0.04), u2=(0.3, 0.05), u3=(0.2, 0.06), Lam=(0.5, 0.02))
J0, J1, b0, b1, xt = fh.tv_mats(5, ctrl)
Jc0 = J0.copy(); Jc1 = J1.copy(); iA = nm.index('A'); Jc0[iA, iA] -= fh.LD('0.15')
tt = np.linspace(0, 10, 11).astype(fh.LD)
ref5 = fh.reference_tv(J0, J1, b0, b1, xt, tt); ref5c = fh.reference_tv(Jc0, Jc1, b0, b1, xt, tt)
Nexact = lambda t: 11.5 * np.exp(-0.1 * t) + 0.5 * (1 - np.exp(-0.1 * t)) / 0.1 + 0.02 * (t / 0.1 - (1 - np.exp(-0.1 * t)) / 0.01)
check('5c under time-varying data: N(t) equals the control-independent balance law', max(abs(float(ref5c[i].sum()) - Nexact(float(tt[i]))) for i in range(11)) < 1e-9)
out['tv_N'] = dict(t=[float(t) for t in tt], N5=[float(r.sum()) for r in ref5], N5c=[float(r.sum()) for r in ref5c], balance=[float(Nexact(float(t))) for t in tt])
print('    tv N(10): Model 5 %.4f, 5c %.4f, balance law %.4f' % (out['tv_N']['N5'][-1], out['tv_N']['N5c'][-1], out['tv_N']['balance'][-1]))
json.dump(out, open('../results/model5.json', 'w'), indent=1)
# ---- figure
plt.rcParams.update({'font.family': 'serif', 'font.size': 9, 'mathtext.fontset': 'cm'})
fig, ax = plt.subplots(1, 2, figsize=(8.4, 3.2))
eg = np.linspace(0, float(eta_c) * 0.995, 200); Ns = []
for e in eg:
    q = {**p, 'eta': mp.mpf(e)}; Jq, bq = system(5, q); Ns.append(float(sum(mp.lu_solve(Jq, -bq))))
ax[0].plot(eg, Ns, color='#1F3A68', label=r'Model 5: $N^*(\eta)$'); ax[0].axhline(5, color='#D35400', ls='--', label=r'variant 5c: $N^*=\Lambda/\mu$')
ax[0].axvline(float(eta_c), color='0.5', lw=0.8, ls=':'); ax[0].axvline(0.1, color='0.5', lw=0.8, ls='-.'); ax[0].set_ylim(0, 60)
ax[0].text(float(eta_c) - 0.005, 40, r'$\eta_c$', ha='right', fontsize=9); ax[0].text(0.105, 40, r'$\mu$', fontsize=9)
ax[0].set_xlabel(r'recruitment rate $\eta$'); ax[0].set_ylabel('equilibrium audience'); ax[0].legend(fontsize=7, loc='upper left'); ax[0].grid(alpha=.25)
tf = [float(t) for t in ts]
N5 = [float(sum(x)) for x in res['5'][0]]; N5c = [float(sum(x)) for x in res['5c'][0]]
ax[1].plot(tf, N5, color='#1F3A68', label='Model 5'); ax[1].plot(tf, N5c, color='#D35400', ls='--', label='variant 5c (= Models 1-4, 6, 7)')
ax[1].axhline(5, color='0.5', lw=0.8, ls=':'); ax[1].axhline(float(res['5'][1].sum()) if hasattr(res['5'][1], 'sum') else float(sum(res['5'][1])), color='0.5', lw=0.8, ls=':')
ax[1].set_xlabel('time (weeks)'); ax[1].set_ylabel('total audience $N(t)$'); ax[1].legend(fontsize=7); ax[1].grid(alpha=.25)
fig.tight_layout(); fig.savefig('../figures/fig_model5.pdf')
print('ALL PASS' if ok else 'SOME CHECKS FAILED')
