"""Checks of the remaining claims: positivity, two-sided decay, asymptotic direction,
Model 5 weighted norm, Model 5 growth for Theta>=1."""
import numpy as np
from scipy.linalg import expm
from models import *
from theory import theta5
import mpmath as mp
rng=np.random.default_rng(7); ok=True
def arrays(k,p):
    J,b=system(k,{a:mp.mpf(float(v)) for a,v in p.items()})[:2]; n=J.rows; return np.array([[float(J[i,j]) for j in range(n)] for i in range(n)]),np.array([float(b[i]) for i in range(n)])
def check(name,c):
    global ok
    if not c: ok=False; print("FAIL",name)
for k in range(1,8):
    for trial in range(60):
        p={a:float(v) for a,v in params(k).items()}
        if trial:
            for key in p:
                if key not in ('xi',): p[key]=p[key]*rng.uniform(.5,1.6)
        J,b=arrays(k,p); n=len(b)
        if k==5:
            th=theta5(p)[1]; s=max(np.linalg.eigvals(J[np.ix_(range(n),range(n))]).real)
        x0=rng.uniform(0,3,n); 
        zero=np.zeros(n); A=np.block([[J,b[:,None]],[np.zeros((1,n+1))]])
        y=(expm(A*0.5)@np.r_[zero,1])[:n]; check(f"pos{k}",(y>0).all())
        if k==5 and th>=1: continue
        xs=-np.linalg.solve(J,b); check(f"eq{k}",(xs>-1e-12).all())
        w=np.ones(n)@np.linalg.inv(-J) if k==5 else None
        for t in (0.3,2,10,40):
            y=expm(J*t)@(x0-xs)
            if k!=5:
                N=x0.sum()-p['Lam']/p['mu']; e=np.exp(-p['mu']*t)
                check(f"two{k}",abs(N)*e*(1-1e-9)-1e-12<=abs(y).sum()<=abs(x0-xs).sum()*e*(1+1e-9)+1e-12)
            else:
                check("w5",(w>0).all() and w@abs(y)<=np.exp(-t/w.max())*(w@abs(x0-xs))*(1+1e-9)+1e-12)
        if k!=5:
            ev,V=np.linalg.eig(J); i=np.argmin(abs(ev+p['mu'])); v=(V[:,i]/V[:,i].sum()).real
            o=np.delete(ev,i); check(f"gap{k}",o.real.max()<-p['mu']-1e-9)
            if k in (4,6): check(f"vpos{k}",(v>0).all())
            else: check(f"vL{k}",np.count_nonzero(abs(v)>1e-8)==1 and abs(v.max()-1)<1e-8)
# Model 5 above threshold
p={a:float(v) for a,v in params(5).items()}
for eta in (0.46,0.6,1.0):
    p['eta']=eta; J,b=arrays(5,p); A=np.block([[J,b[:,None]],[np.zeros((1,len(b)+1))]])
    N=[(expm(A*t)@np.r_[np.zeros(len(b)),1])[:-1].sum() for t in (50,200,800)]
    check("grow",theta5(p)[1]>1 and N[0]<N[1]<N[2] and N[2]>2*N[0])
print("ALL PASS" if ok else "SOME FAILED")
