#!/usr/bin/env python3
"""
S-I-C-T reconstruction: replication & validation suite (v1.0, 2026-11-26)
Roth Complexity Lab — open for independent testing.

Every theorem, corollary, counterexample and numeric figure value in
"What Survives: A Validated Mathematical Reconstruction of the S-I-C-T
Framework" (Preprint v2.0, Nov 2026) is checked here,
either exactly (closed form) or by randomized falsification attempts.
A single FAIL line means a claim did not survive.

Run:  python3 sict_validation.py            (seed fixed for reproducibility)
Needs: Python >= 3.10, NumPy, SciPy.  Expected last line: "41 checks, 41 passed, 0 failed"
Report results, failures or counterexamples to miklosroth@rothcomplexity.org
(subject: "S-I-C-T TEST - replication").
"""
import numpy as np
from numpy.linalg import eigvals, eigvalsh

rng = np.random.default_rng(20261126)
N = 200_000
results = []

def check(name, ok, detail=""):
    results.append((name, bool(ok), detail))
    print(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f"  — {detail}" if detail else ""))

def r(p, q):
    return (p - q) / (p + q)

# ---------------------------------------------------------------- T1 / Cor 1
a = rng.normal(size=N); b = rng.normal(size=N)
W = np.minimum(a, b); V = a + b
check("T1  W>=0  <=>  a>=0 and b>=0", np.all((W >= 0) == ((a >= 0) & (b >= 0))))
check("Cor1 W>=0 => V>=0", np.all(V[W >= 0] >= 0))
mask = (V >= 0) & (W < 0)
check("Cor1 converse fails (masking region M non-empty)", mask.mean() > 0,
      f"share of N(0,1)^2 draws in M = {mask.mean():.3f} (theory 0.25)")
S, I, C, T = 0.9, 0.2, 0.3, 0.8
check("Counterexample S=.9,I=.2,C=.3,T=.8 gives V=0.2, W=-0.5",
      np.isclose(S + C - I - T, 0.2) and np.isclose(min(S - I, C - T), -0.5))
check("Widget values a=.65,b=-.35 -> V=.30, W=-.35",
      np.isclose(0.65 - 0.35, 0.30) and np.isclose(min(0.65, -0.35), -0.35))

# ---------------------------------------------------------------- T2
check("T2  min(a,b) = (V-|a-b|)/2", np.allclose(W, (V - np.abs(a - b)) / 2))
check("T2' W>=0 <=> V>=|a-b|", np.all((W >= 0) == (V >= np.abs(a - b))))

# ---------------------------------------------------------------- T3 / T4
S, I, C, T = (rng.exponential(size=N) for _ in range(4))
rS, rC = r(S, I), r(C, T); WN = np.minimum(rS, rC)
check("T3  W_N in [-1,1]", np.all((WN >= -1) & (WN <= 1)))
check("T3  W_N>=0 <=> S>=I and C>=T", np.all((WN >= 0) == ((S >= I) & (C >= T))))
al, be = rng.lognormal(0, 2, N), rng.lognormal(0, 2, N)
check("T4  pairwise scale invariance", np.allclose(np.minimum(r(al*S, al*I), r(be*C, be*T)), WN))
g = [rng.lognormal(0, 1, N) for _ in range(4)]
WN_ind = np.minimum(r(g[0]*S, g[1]*I), r(g[2]*C, g[3]*T))
check("T4  limit: NOT invariant under independent per-coordinate rescaling",
      np.mean(np.sign(WN_ind) != np.sign(WN)) > 0.01,
      f"sign flips in {np.mean(np.sign(WN_ind) != np.sign(WN)):.1%} of draws")

# ---------------------------------------------------------------- 4.1 tanh identity / rank equivalence
L = np.minimum(np.log(S / I), np.log(C / T))
check("Eq18 r = tanh(log(p/q)/2)", np.allclose(rS, np.tanh(np.log(S / I) / 2)))
check("Eq18 W_N = tanh(L/2)", np.allclose(WN, np.tanh(L / 2)))
rho_star = np.maximum(I / S, T / C)
check("NEW W_N = (1-rho*)/(1+rho*), rho* = max(I/S, T/C)",
      np.allclose(WN, (1 - rho_star) / (1 + rho_star)))

def auroc(score, y):
    """Mann-Whitney AUROC (higher score = more likely y=1); ties averaged."""
    from scipy.stats import rankdata
    rk = rankdata(score); n1 = y.sum(); n0 = len(y) - n1
    return (rk[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)

y = (rng.random(N) < 1 / (1 + np.exp(-3 * (rho_star - 1)))).astype(int)
A_WN, A_L, A_rho = auroc(-WN, y), auroc(-L, y), auroc(rho_star, y)
check("NEW AUROC(-W_N) = AUROC(-L) = AUROC(rho*) exactly",
      np.isclose(A_WN, A_L) and np.isclose(A_WN, A_rho), f"AUROC = {A_WN:.6f} for all three")

# ---------------------------------------------------------------- T5
p, q = rng.exponential(size=N), rng.exponential(size=N); h = 1e-6
dp = (r(p + h, q) - r(p - h, q)) / (2 * h); dq = (r(p, q + h) - r(p, q - h)) / (2 * h)
check("T5  dr/dp = 2q/(p+q)^2 >= 0", np.allclose(dp, 2 * q / (p + q) ** 2, rtol=1e-4) and np.all(dp >= 0))
check("T5  dr/dq = -2p/(p+q)^2 <= 0", np.allclose(dq, -2 * p / (p + q) ** 2, rtol=1e-4) and np.all(dq <= 0))

# ---------------------------------------------------------------- T6 + new error propagation
eS, eC = rng.uniform(0, .3, N), rng.uniform(0, .3, N)
rSh = rS + rng.uniform(-1, 1, N) * eS; rCh = rC + rng.uniform(-1, 1, N) * eC
check("T6  |W_N^ - W_N| <= max(eS,eC)",
      np.all(np.abs(np.minimum(rSh, rCh) - WN) <= np.maximum(eS, eC) + 1e-12))
eta = 0.05
ph = p + rng.uniform(-eta, eta, N); qh = q + rng.uniform(-eta, eta, N)
ok = (ph + qh) > 0
bound = 2 * eta / (ph + qh)
check("NEW absolute raw error eta  =>  |r^ - r| <= 2 eta/(p^+q^)  (observable bound)",
      np.all(np.abs(r(ph, qh) - r(p, q))[ok] <= bound[ok] + 1e-12))
er = 0.10
ph = p * (1 + rng.uniform(-er, er, N)); qh = q * (1 + rng.uniform(-er, er, N))
check("NEW relative raw error e  =>  |r^ - r| <= -log(1-e)  (scale-free bound)",
      np.all(np.abs(r(ph, qh) - r(p, q)) <= -np.log(1 - er) + 1e-12), f"bound = {-np.log(1-er):.4f} for e=10%")

# ---------------------------------------------------------------- T7 signed distance (l_inf)
z = rng.uniform(-1, 1, (N, 2)); inK = np.all(z >= 0, axis=1)
d_in = np.min(z, axis=1)                                   # dist to complement
d_out = np.max(np.maximum(-z, 0), axis=1)                  # dist to K
signed = np.where(inK, d_in, -d_out)
check("T7  W_N = signed l_inf distance to K=[0,inf)^2", np.allclose(signed, np.min(z, axis=1)))
# brute-force check on a subsample: projection onto K in l_inf and distance to K^c
zs = z[:2000]; best = []
for v in zs:
    if np.all(v >= 0):
        best.append(min(v))      # move the smaller coordinate just below 0
    else:
        proj = np.maximum(v, 0); best.append(-np.max(np.abs(v - proj)))
check("T7  brute-force projection agrees", np.allclose(best, np.min(zs, axis=1)))

# ---------------------------------------------------------------- T8 soft-min
for tau in [0.01, 0.15, 1.0]:
    Wt = -tau * np.log(np.exp(-rS / tau) + np.exp(-rC / tau))
    check(f"T8  WN - tau log2 <= W_tau < WN  (tau={tau})",
          np.all(Wt <= WN + 1e-12) and np.all(Wt >= WN - tau * np.log(2) - 1e-12))
check("Fig2 tau*log2 at tau=0.15 = 0.1040", np.isclose(0.15 * np.log(2), 0.1040, atol=5e-5),
      f"{0.15*np.log(2):.5f}")

# ---------------------------------------------------------------- T10 Routh–Hurwitz (2x2)
M = 50_000
k1, k2 = rng.uniform(.1, 3, M), rng.uniform(.1, 3, M)
aa, bb = rng.normal(0, 1, M), rng.normal(0, 1, M)
u, v = rng.normal(0, 1.5, M), rng.normal(0, 1.5, M)
J = np.stack([np.stack([-k1 * aa, u], -1), np.stack([v, -k2 * bb], -1)], -2)
maxre = np.max(eigvals(J).real, axis=1)
hur = maxre < 0
rh = (k1 * aa + k2 * bb > 0) & (k1 * k2 * aa * bb - u * v > 0)
check("T10 Hurwitz <=> tr<0 and det>0", np.all(hur == rh))

# ---------------------------------------------------------------- Cor 2 (Gershgorin) & T11 (Lyapunov)
Wraw = np.minimum(aa, bb); rho = np.maximum(np.abs(u), np.abs(v)); kmin = np.minimum(k1, k2)
g_cond = Wraw > rho / kmin
check("Cor2 W > rho/k_min  =>  Hurwitz", np.all(hur[g_cond]), f"{g_cond.sum()} cases satisfied the condition")
m = np.minimum(k1 * aa, k2 * bb); lam = np.abs(u + v) / 2      # lambda_max of sym. part of [[0,u],[v,0]]
l_cond = m - lam > 0
check("T11 (constant B) m - lambda_max(B_s) > 0  =>  Hurwitz", np.all(hur[l_cond]))
check("NEW Cor2 condition implies Lyapunov condition (Lyapunov is sharper)",
      np.all(l_cond[g_cond]) and (l_cond & ~g_cond).sum() > 0,
      f"{(l_cond & ~g_cond).sum()} systems certified by Lyapunov but not by Gershgorin")

# T11 time-varying: simulate and check the exponential envelope
def simulate(delta_target=0.2, Tend=20.0, dt=1e-3):
    t = 0.0; yv = np.array([1.0, -0.7]); ok = True; y0 = np.linalg.norm(yv)
    while t < Tend:
        a_t, b_t = 1.0 + 0.5 * np.sin(t), 1.2 + 0.4 * np.cos(1.3 * t)
        Bt = np.array([[0.0, 0.6 * np.sin(2 * t)], [-0.3 + 0.2 * np.cos(t), 0.0]])
        Bs = (Bt + Bt.T) / 2
        mt = min(a_t, b_t); margin = mt - eigvalsh(Bs).max()
        ok &= margin >= delta_target
        A = -np.diag([a_t, b_t]) + Bt
        k1_ = A @ yv; k2_ = A @ (yv + dt / 2 * k1_); k3_ = A @ (yv + dt / 2 * k2_); k4_ = A @ (yv + dt * k3_)
        yv = yv + dt / 6 * (k1_ + 2 * k2_ + 2 * k3_ + k4_); t += dt
        if np.linalg.norm(yv) > np.exp(-delta_target * t) * y0 * (1 + 1e-6):
            return False, ok
    return True, ok
env_ok, cond_ok = simulate()
check("T11 time-varying: ||y(t)|| <= e^{-delta t}||y(0)|| on a simulated system", env_ok and cond_ok)

# ---------------------------------------------------------------- 11.1 / 11.2 counterexamples
ev1 = np.sort(eigvals(np.array([[-1, 2], [2, -1]])).real)
check("11.1 W=+1 but spec = {-3, 1} (unstable)", np.allclose(ev1, [-3, 1]))
J2 = np.array([[0.2, -1], [1, -1]]); ev2 = eigvals(J2)
check("11.2 W=-0.2 but tr=-0.8, det=0.8, Re(lambda)=-0.4 (stable)",
      np.isclose(np.trace(J2), -0.8) and np.isclose(np.linalg.det(J2), 0.8) and np.allclose(ev2.real, -0.4),
      f"eigenvalues {ev2[0]:.2f}, {ev2[1]:.2f}")

# ---------------------------------------------------------------- Sec. 12 bipartite
ok_poly, ok_sym = True, True
for _ in range(2000):
    B, Cm = rng.normal(size=(2, 2)), rng.normal(size=(2, 2))
    A = np.block([[np.zeros((2, 2)), B], [Cm, np.zeros((2, 2))]])
    P, Q = np.trace(B @ Cm), np.linalg.det(B @ Cm)
    lam_ = eigvals(A)
    rts = np.roots([1, 0, -P, 0, Q])
    ok_poly &= (np.abs(lam_**4 - P * lam_**2 + Q).max() < 1e-8) and \
               (max(min(abs(rts - l)) for l in lam_) < 1e-5)   # match roots by distance, not by sort order
    ok_sym &= np.max(lam_.real) >= -1e-9
check("Sec12 p(q)=q^4 - tr(BC) q^2 + det(BC) for 2x2 blocks", ok_poly)
check("Sec12 undamped bipartite system never asymptotically stable", ok_sym)
B3, C3 = rng.normal(size=(3, 3)), rng.normal(size=(3, 3))
A3 = np.block([[np.zeros((3, 3)), B3], [C3, np.zeros((3, 3))]])
check("Sec12 general n: char. poly = det(q^2 I - BC) (n=3 test)",
      np.allclose(np.sort_complex(eigvals(A3) ** 2), np.sort_complex(np.repeat(eigvals(B3 @ C3), 2)), atol=1e-6))

# ---------------------------------------------------------------- Sec. 13 OU
kap, sig, Dl = 0.40, 0.2, 1.0
check("Fig5 OU: 1/kappa=2.50, Var=0.050, rho1=0.670",
      np.isclose(1 / kap, 2.5) and np.isclose(sig**2 / (2 * kap), 0.05) and np.isclose(np.exp(-kap * Dl), 0.670, atol=5e-4),
      f"rho1 = {np.exp(-kap*Dl):.4f}")
# Monte Carlo check of stationary variance and lag-1 autocorrelation (exact discretisation)
n = 400_000; x = np.empty(n); x[0] = 0.0
phi = np.exp(-kap * Dl); s = sig * np.sqrt((1 - phi**2) / (2 * kap))
eps = rng.normal(size=n)
for i in range(1, n):
    x[i] = phi * x[i - 1] + s * eps[i]
x = x[1000:]
check("Sec13 OU Monte Carlo matches Var and lag-1 autocorrelation",
      abs(x.var() - 0.05) < 0.002 and abs(np.corrcoef(x[:-1], x[1:])[0, 1] - phi) < 0.01,
      f"Var^={x.var():.4f}, rho1^={np.corrcoef(x[:-1], x[1:])[0,1]:.4f}")

# ---------------------------------------------------------------- Sec. 14.3 queueing
def mm1_mean_queue(lam, mu, horizon=20_000.0):
    """Gillespie simulation of an M/M/1 queue; returns time-average number in system."""
    t, nq, area = 0.0, 0, 0.0
    while t < horizon:
        rate = lam + (mu if nq > 0 else 0.0)
        dt = rng.exponential(1 / rate); area += nq * dt; t += dt
        nq += 1 if rng.random() < lam / rate else -1
    return area / t
lam, mu = 0.8, 1.0
Lq = mm1_mean_queue(lam, mu)
check("Sec14.3 stable M/M/1 (I<S): mean number = rho/(1-rho) = 4", abs(Lq - 4.0) < 0.6, f"simulated {Lq:.2f}")
Lq_over = mm1_mean_queue(1.1, 1.0, horizon=5000.0)
check("Sec14.3 overloaded M/M/1 (I>S): queue grows without bound", Lq_over > 100, f"time-avg {Lq_over:.0f} after t=5000")

# ---------------------------------------------------------------- Sec. 15.1 information
# Discrete example: I(Y;g(F)) <= I(Y;F)
def mi(xd, yd):
    xs, xi = np.unique(xd, return_inverse=True); ys, yi = np.unique(yd, return_inverse=True)
    joint = np.zeros((len(xs), len(ys))); np.add.at(joint, (xi, yi), 1); joint /= joint.sum()
    px, py = joint.sum(1, keepdims=True), joint.sum(0, keepdims=True)
    nz = joint > 0
    return float((joint[nz] * np.log(joint[nz] / (px @ py)[nz])).sum())
Fd = rng.integers(0, 4, (N, 4)); Wd = np.minimum(Fd[:, 0] - Fd[:, 1], Fd[:, 2] - Fd[:, 3])
Yd = ((Fd[:, 0] - Fd[:, 1] + 0.5 * (Fd[:, 2] - Fd[:, 3]) + rng.normal(0, 1, N)) < 0).astype(int)
Fkey = Fd @ np.array([64, 16, 4, 1])
check("Sec15.1 data-processing inequality I(Y;W) <= I(Y;F)", mi(Wd, Yd) <= mi(Fkey, Yd) + 1e-12,
      f"I(Y;W)={mi(Wd,Yd):.4f} nats, I(Y;F)={mi(Fkey,Yd):.4f} nats")

# ---------------------------------------------------------------- summary
n_fail = sum(not ok for _, ok, _ in results)
print(f"\n{len(results)} checks, {len(results)-n_fail} passed, {n_fail} failed")