"""Independent audit of the seven models (Section 2 of the audit brief).

The right-hand sides below are typed directly from Eqs. (m1)-(m7) of the manuscript with SymPy, NOT from
models.py.  They are compared with the matrices built by models.system(); structural properties are then
verified in EXACT rational arithmetic.  Also tests the HAM deformation equation independently.
Run:  python3 audit_models.py
"""
import itertools, random
import sympy as sp, mpmath as mp
from models import BASE, EXTRA, NAMES, params, system, initial, X0

mp.mp.dps = 60
ok = True
def check(name, cond, extra=''):
    global ok; ok &= bool(cond); print(('PASS ' if cond else 'FAIL ') + name + (' ' + extra if extra else ''))

# ---- Table 2 of the manuscript typed independently (decimal strings) ------------------------------------
TAB = {  # model -> parameter dict in the manuscript's notation
 'all': dict(mu='0.10', de='0.05'),
 'all6': dict(b4='0.20', ga='0.10'),
 '12457': dict(b1='0.68', b2='0.30'),
 '1_2_4_5_7': dict(b3='0.52', al='0.15'),
 2: dict(eps='0.20'), 3: dict(th='0.15', s1='0.30', s2='0.25', p12='0.08', p21='0.05', al1='0.35', al2='0.30'),
 4: dict(om='0.10', nu='0.08', rho='0.05'), 5: dict(eta='0.15', eps='0.10'),
 6: dict(b1='0.68', b2='0.50', s1='0.30', s2='0.25', s12='0.08', s21='0.06', p12='0.07', p21='0.05',
         d1='0.35', d2='0.30', g1='0.10', g2='0.12'),
 7: dict(psi='0.20', xi='0.50')}
CTRLS = dict(u1='0.70', u2='0.60', u3='0.50'); LAM = '0.5'
def table_params(k):
    d = dict(TAB['all']); d['Lam'] = LAM
    if k != 6: d.update(TAB['all6'])
    if k in (1, 2, 3, 4, 5, 7): d.update(TAB['12457'])
    if k in (1, 2, 4, 5, 7): d.update(TAB['1_2_4_5_7'])
    if k in TAB: d.update(TAB[k])
    d.update(CTRLS); return {a: sp.Rational(v) for a, v in d.items()}

# ---- right-hand sides typed from the manuscript -----------------------------------------------------------
def rhs(k, s, P, u1, u2, u3):
    """s: dict name->symbol.  Returns dict name->expression, from Eqs. (m1)-(m7)."""
    p = P; mu, de, La = p['mu'], p['de'], p['Lam']
    g, b = p['b1'] * u1, p.get('b3', 0) * u2
    b4, ga = p['b4'] if k != 6 else None, p['ga'] if k != 6 else None
    if k == 7: b4 = p['b4'] + p['psi'] * u3; ga = p['ga'] * (1 - p['xi'] * u3)
    S = s; d = {}
    if k == 1 or k == 7:
        d['U'] = La + de*S['R'] - (g+mu)*S['U'];            d['E'] = g*S['U'] - (p['b2']+mu)*S['E']
        d['A'] = p['b2']*S['E'] - (b+p['al']+mu)*S['A'];    d['C'] = (b+p['al'])*S['A'] - (b4+ga+mu)*S['C']
        d['L'] = b4*S['C'] - mu*S['L'];                     d['R'] = ga*S['C'] - (de+mu)*S['R']
    if k == 2:
        d['U'] = La + de*S['R'] - (g+mu)*S['U'];            d['E'] = g*S['U'] - (p['b2']+mu)*S['E']
        d['I1'] = p['b2']*S['E'] - (p['eps']+p['al']+mu)*S['I1']; d['I2'] = p['eps']*S['I1'] - (b+mu)*S['I2']
        d['C'] = p['al']*S['I1'] + b*S['I2'] - (b4+ga+mu)*S['C']; d['L'] = b4*S['C'] - mu*S['L']
        d['R'] = ga*S['C'] - (de+mu)*S['R']
    if k == 3:
        d['U'] = La + de*S['R'] - (g+p['th']+mu)*S['U']
        d['E1'] = g*S['U'] + p['p21']*S['E2'] - (p['s1']+p['p12']+mu)*S['E1']
        d['E2'] = p['th']*S['U'] + p['p12']*S['E1'] - (p['s2']+p['p21']+mu)*S['E2']
        d['A1'] = p['s1']*S['E1'] - (p['al1']+mu)*S['A1'];  d['A2'] = p['s2']*S['E2'] - (p['al2']+mu)*S['A2']
        d['C'] = p['al1']*S['A1'] + p['al2']*S['A2'] - (b4+ga+mu)*S['C']
        d['L'] = b4*S['C'] - mu*S['L'];                     d['R'] = ga*S['C'] - (de+mu)*S['R']
    if k == 4:
        d['U'] = La + de*S['R'] + p['rho']*S['W'] - (g+mu)*S['U'];  d['E'] = g*S['U'] - (p['b2']+mu)*S['E']
        d['A'] = p['b2']*S['E'] - (b+p['al']+mu)*S['A'];    d['C'] = (b+p['al'])*S['A'] - (b4+ga+mu)*S['C']
        d['L'] = b4*S['C'] + p['nu']*S['W'] - (p['om']+mu)*S['L']; d['W'] = p['om']*S['L'] - (p['nu']+p['rho']+mu)*S['W']
        d['R'] = ga*S['C'] - (de+mu)*S['R']
    if k == 5:
        d['U'] = La + de*S['R'] - (g+mu)*S['U'];            d['E'] = g*S['U'] + p['eta']*S['A'] - (p['b2']+mu)*S['E']
        d['A'] = p['b2']*S['E'] - (p['eps']+p['al']+mu)*S['A']; d['F'] = p['eps']*S['A'] - (b+mu)*S['F']
        d['C'] = p['al']*S['A'] + b*S['F'] - (b4+ga+mu)*S['C']; d['L'] = b4*S['C'] - mu*S['L']
        d['R'] = ga*S['C'] - (de+mu)*S['R']
    if k == 6:
        g1, g2 = p['b1']*u1, p['b2']*u2
        d['U'] = La + de*S['R'] - (g1+g2+mu)*S['U']
        for i, j in ((1, 2), (2, 1)):
            d['A%d' % i] = (g1 if i == 1 else g2)*S['U'] + p['s%d%d' % (j, i)]*S['A%d' % j] - (p['s%d' % i] + p['s%d%d' % (i, j)] + mu)*S['A%d' % i]
            d['E%d' % i] = p['s%d' % i]*S['A%d' % i] + p['p%d%d' % (j, i)]*S['E%d' % j] - (p['d%d' % i] + p['p%d%d' % (i, j)] + mu)*S['E%d' % i]
            d['C%d' % i] = p['d%d' % i]*S['E%d' % i] - (p['g%d' % i] + mu)*S['C%d' % i]
        d['R'] = p['g1']*S['C1'] + p['g2']*S['C2'] - (de+mu)*S['R']
    return d

def build(k, P, u):
    nm = NAMES[k]; s = {n: sp.Symbol(n) for n in nm}
    d = rhs(k, s, P, *u); f = sp.Matrix([d[n] for n in nm]); x = sp.Matrix([s[n] for n in nm])
    J = f.jacobian(x); b = f.subs({s[n]: 0 for n in nm}); return J, b

# ---------------------------------------------------------------------------------------------------------
print('== 1. Table of parameters in the manuscript vs models.py')
for k in range(1, 8):
    P = table_params(k); Q = params(k)
    same = all(abs(mp.mpf(sp.N(P[a], 50)) - Q[a]) < mp.mpf(10) ** -50 for a in P if a in Q)
    miss = [a for a in P if a not in Q and a not in ('u3', 'psi', 'xi')] 
    check('Model %d parameter values: Table 2 == models.py' % k, same, 'extra keys %s' % miss if miss else '')
    ini = initial(k); tot = sum(ini)
    check('Model %d initial total N(0)=11.5, U(0)=10' % k, abs(tot - mp.mpf('11.5')) < 1e-50 and ini[0] == 10)

print('== 2. Equations (m1)-(m7) typed from the manuscript == models.system() at constant controls')
for k in range(1, 8):
    P = table_params(k); u = (P['u1'], P['u2'], P['u3']); J, b = build(k, P, u)
    Jc, bc = system(k)
    n = J.shape[0]; dmax = max(abs(mp.mpf(sp.N(J[i, j], 60)) - Jc[i, j]) for i in range(n) for j in range(n))
    dmax = max(dmax, max(abs(mp.mpf(sp.N(b[i], 60)) - bc[i]) for i in range(n)))
    check('Model %d matrix J and forcing b agree with Python (max diff %s)' % (k, mp.nstr(dmax, 2)), dmax < mp.mpf(10) ** -50)

print('== 3. Exact (rational) structural properties for random admissible controls')
random.seed(11)
for k in range(1, 8):
    P = table_params(k); n = len(NAMES[k]); good_m = good_c = True
    Jsym = None
    for t in range(40):
        u = tuple(sp.Rational(random.randint(0, 100), 100) for _ in range(3))
        J, b = build(k, P, u)
        good_m &= all(J[i, j] >= 0 for i in range(n) for j in range(n) if i != j)      # Metzler
        cs = [sum(J[i, j] for i in range(n)) for j in range(n)]
        if k != 5: good_c &= all(c == -P['mu'] for c in cs)
        else:      good_c &= all(c == -P['mu'] + (P['eta'] if NAMES[5][j] == 'A' else 0) for j, c in enumerate(cs))
    check('Model %d is Metzler and column sums are %s for 40 random u in [0,1]^3 (exact)' % (k, '-mu' if k != 5 else '-mu+eta e_A'), good_m and good_c)
    # affine structure in u: J(u) = J0 + sum u_i J^i  (exact)
    Z = (0, 0, 0); J0, _ = build(k, P, Z); Ji = [build(k, P, tuple(1 if a == i else 0 for a in range(3)))[0] - J0 for i in range(3)]
    u = (sp.Rational(3, 10), sp.Rational(7, 10), sp.Rational(1, 5)); Jt, _ = build(k, P, u)
    check('Model %d J(u) = J^0 + sum u_i J^i exactly' % k, sp.simplify(Jt - (J0 + sum((u[i] * Ji[i] for i in range(3)), sp.zeros(n, n)))) == sp.zeros(n, n))
    lam = [max(sum(abs(Ji[a][i, j]) for i in range(n)) for j in range(n)) for a in range(3)]
    print('     lambda_i = ||J^i||_1 =', [str(sp.nsimplify(l)) for l in lam])

print('== 4. Manuscript constants lambda_i of Proposition (Lipschitz)')
P = table_params(1); lam1 = [max(sum(abs(M[i, j]) for i in range(6)) for j in range(6)) for M in
        [build(1, P, tuple(1 if a == i else 0 for a in range(3)))[0] - build(1, P, (0, 0, 0))[0] for i in range(3)]]
check('Model 1: lambda_1 = 2 beta_1, lambda_2 = 2 beta_3, lambda_3 = 0', (lam1[0], lam1[1], lam1[2]) == (2*P['b1'], 2*P['b3'], 0))
P = table_params(7); lam7 = max(sum(abs(M[i, j]) for i in range(6)) for j in range(6) for M in
        [build(7, P, (0, 0, 1))[0] - build(7, P, (0, 0, 0))[0]])
check('Model 7: lambda_3 = 2 max(psi, gamma xi)', lam7 == 2 * max(P['psi'], P['ga'] * P['xi']))
P = table_params(6); lam6 = [max(sum(abs(M[i, j]) for i in range(8)) for j in range(8)) for M in
        [build(6, P, tuple(1 if a == i else 0 for a in range(3)))[0] - build(6, P, (0, 0, 0))[0] for i in range(2)]]
check('Model 6: lambda_1 = 2 beta_1, lambda_2 = 2 beta_2', (lam6[0], lam6[1]) == (2*P['b1'], 2*P['b2']))

print('== 5. HAM deformation equation, tested independently of series.py / tv.py')
from series import Model
def x_terms_const(m, h, M):
    """x_m(t) as polynomial coefficient lists from the recurrence x_m = (1+h) x_{m-1} - h V x_{m-1}, x_1 = -h int(J x0 + b)"""
    n = m.n; Jr = m.J; h = mp.mpf(h)
    v = Jr * m.x0 + m.b
    prev = [[mp.mpf(0)] + [-h * v[i]] for i in range(n)]          # x_1 = -h v t
    out = [prev]
    for _ in range(2, M + 1):
        new = []
        for i in range(n):
            deg = len(prev[0])
            c = [mp.mpf(0)] * (deg + 1)
            for d in range(deg):
                c[d] += (1 + h) * prev[i][d]
            for j in range(n):
                if Jr[i, j] != 0:
                    for d in range(deg): c[d + 1] += -h * Jr[i, j] * prev[j][d] / (d + 1)
            new.append(c)
        prev = new; out.append(prev)
    return out
def poly(c, t): return mp.polyval(c[::-1], t)
for k in (1, 3, 5, 6):
    m = Model(k); h = mp.mpf('-0.8'); q = mp.mpf('0.3'); M = 60; t = mp.mpf(6)
    xt = x_terms_const(m, h, M)
    vq = [m.x0[i] + mp.fsum(q ** (mm + 1) * poly(xt[mm][i], t) for mm in range(M)) for i in range(m.n)]
    kap = -h * q / (1 - (1 + h) * q); xs = mp.lu_solve(m.J, -m.b); Xk = xs + mp.expm(kap * m.J * t) * (m.x0 - xs)
    d1 = max(abs(vq[i] - Xk[i]) for i in range(m.n))
    check('Model %d: sum q^m x_m(t) equals the solution of v_t = kappa(q)(Jv+f)  (diff %s)' % (k, mp.nstr(d1, 2)), d1 < mp.mpf(10) ** -35)
    # (1-q) d/dt[v-x0] - q h N[v] = 0 with v = X(t; kappa(q)): evaluate numerically
    dv = mp.matrix([mp.diff(lambda tt, i=i: (xs + mp.expm(kap * m.J * tt) * (m.x0 - xs))[i], t) for i in range(m.n)])
    Nv = dv - m.J * Xk - m.b; res = (1 - q) * dv - q * h * Nv
    check('Model %d: X(t;kappa(q)) satisfies the zeroth-order deformation equation (res %s)' % (k, mp.nstr(max(abs(r) for r in res), 2)), max(abs(r) for r in res) < mp.mpf(10) ** -30)
    # HPM special case: x_m = Picard increment t^m J^{m-1} v / m!
    x1 = x_terms_const(m, -1, 5); v = m.J * m.x0 + m.b; Jk = v; dd = 0
    for mm in range(1, 6):
        pic = [Jk[i] * mp.mpf(6) ** mm / mp.factorial(mm) for i in range(m.n)]; Jk = m.J * Jk
        dd = max(dd, max(abs(poly(x1[mm - 1][i], mp.mpf(6)) - pic[i]) for i in range(m.n)))
    check('Model %d: HPM (h=-1) terms equal the Picard increments / Taylor terms (diff %s)' % (k, mp.nstr(dd, 2)), dd < mp.mpf(10) ** -40)
print('ALL PASS' if ok else 'SOME CHECKS FAILED')
