#!/usr/bin/env python3
"""Independent checks for Foundations limits/evidence articles.

Run: python3 check_limits_evidence.py
Requires Python 3, NumPy and SymPy. No network, randomness, input files or writes.
Numeric norms are float64 maximum absolute or Euclidean norms as labeled.
Symbolic tests use exact arithmetic. These verify stated examples, not general
integrability or convergence theorems. Negative controls must fail the intended
scientific check, while the script itself succeeds when it detects them.
"""

import itertools
import json
import math

import numpy as np
import sympy as sp


def maxabs(x):
    return float(np.max(np.abs(x)))


def weyl_checks():
    x, hbar = sp.symbols("x hbar", real=True)

    def word_apply(word, f):
        for letter in reversed(word):
            f = x * f if letter == "Q" else -sp.I * hbar * sp.diff(f, x)
        return sp.expand(f)

    def W(m, n, f):
        words = set(itertools.permutations("Q" * m + "P" * n))
        return sp.expand(sum(word_apply(w, f) for w in words) / len(words))

    tests = [sp.Integer(1), x, x**2 + 3*x, x**5 - x**3 + 2]
    negative = []
    for f in tests:
        cubic = (W(3, 0, W(0, 3, f))-W(0, 3, W(3, 0, f)))/(sp.I*hbar)
        mixed = (W(2, 1, W(1, 2, f))-W(1, 2, W(2, 1, f)))/(sp.I*hbar)
        assert sp.simplify(cubic - 9*W(2, 2, f) + sp.Rational(3, 2)*hbar**2*f) == 0
        assert sp.simplify(mixed - 3*W(2, 2, f) - hbar**2*f/2) == 0
        assert sp.simplify(mixed/3 - cubic/9 - hbar**2*f/3) == 0
        negative.append(sp.simplify(cubic - 9*W(2, 2, f)) != 0)
    assert all(negative)
    d = 8
    a = np.diag(np.sqrt(np.arange(1, d)), 1)
    canonical = np.eye(d)
    corrected = canonical.copy()
    corrected[-1, -1] -= d
    residual = maxabs(a @ a.T - a.T @ a - corrected)
    assert residual < 1e-14
    assert maxabs(a @ a.T - a.T @ a - canonical) > 7.9
    return {"symbolic_test_functions": len(tests), "cubic_and_mixed_residuals": 0,
            "missing_cubic_correction_detected": True,
            "truncated_commutator_max_error": residual}


def bracket_checks():
    q1, p1, q2, p2 = z = sp.symbols("q1 p1 q2 p2", real=True)

    def pb(f, g):
        return sp.expand(sum(sp.diff(f, q)*sp.diff(g, p)-sp.diff(f, p)*sp.diff(g, q)
                             for q, p in [(q1, p1), (q2, p2)]))

    e1, e2 = (q1*q1+p1*p1)/2, (q2*q2+p2*p2)/2
    c, ell = q1*q2+p1*p2, q1*p2-q2*p1
    assert pb(c, e1+e2) == pb(ell, e1+e2) == 0
    assert pb(e1, c) == ell and pb(e2, c) == -ell
    assert sp.expand(pb(c, ell)-2*(e1-e2)) == 0
    jac = sp.Matrix([e1, e2, c]).jacobian(z)
    assert sp.expand(jac[:, [0, 1, 3]].det()+p2*ell) == 0
    witness = dict(zip(z, [1, 0, 0, 1]))
    assert jac.subs(witness).rank() == 3
    assert pb(e1, c).subs(witness) == 1
    misleading = dict(zip(z, [1, 0, 2, 0]))
    assert pb(e1, c).subs(misleading) == 0
    assert jac.subs(misleading).rank() == 2
    goodjac = sp.Matrix([e1, e2]).jacobian(z)
    minors2 = sum(goodjac[:, list(cols)].det()**2 for cols in itertools.combinations(range(4), 2))
    assert sp.expand(minors2 - 4*e1*e2) == 0
    assert sp.expand(c*c+ell*ell-4*e1*e2) == 0
    return {"symbolic_bracket_and_minor_residuals": 0,
            "witness_rank": 3, "witness_nonzero_bracket": 1,
            "misleading_L_zero_sample_rank": 2}


def lattice_checks():
    rows = []
    for n in [32, 64, 128, 256]:
        a = 2*np.pi/n
        x = a*np.arange(n)
        u = np.sin(x) + .3*np.cos(2*x)
        ux = np.cos(x)-.6*np.sin(2*x)
        uxx = -np.sin(x)-1.2*np.cos(2*x)
        tau = 2+.4*np.cos(x)
        correct = tau*uxx-.4*np.sin(x)*ux
        tp = 2+.4*np.cos(x+a/2)
        tm = 2+.4*np.cos(x-a/2)
        discrete = (tp*(np.roll(u, -1)-u)-tm*(u-np.roll(u, 1)))/a**2
        rows.append({"N": n, "flux_max_error": maxabs(discrete-correct),
                     "missing_tension_derivative_error": maxabs(discrete-tau*uxx)})
    ratios = [rows[i]["flux_max_error"]/rows[i+1]["flux_max_error"] for i in range(3)]
    assert min(ratios) > 3.8
    assert rows[-1]["missing_tension_derivative_error"] > .3
    return {"periodic_length": 2*math.pi, "rows": rows, "refinement_ratios": ratios}


def covariance_checks():
    beta, mass, stiffness, omega = 1.3, .7, 1.2, .8
    pinned_errors, unpinned_errors = [], []
    for n in [7, 12, 31]:
        shift = np.roll(np.eye(n), 1, axis=1)
        lap = 2*np.eye(n)-shift-shift.T
        theta = 2*np.pi*np.arange(n)/n
        w2 = omega**2 + 4*stiffness/mass*np.sin(theta/2)**2
        direct = np.linalg.inv(mass*omega**2*np.eye(n)+stiffness*lap)/beta
        fourier = np.array([np.mean(np.cos(theta*r)/w2)/(beta*mass) for r in range(n)])
        pinned_errors.append(maxabs(direct[0]-fourier))
        assert abs(np.sum(direct)/n**2 - 1/(beta*mass*n*omega**2)) < 2e-14
        restricted = np.linalg.pinv(stiffness*lap, rcond=1e-12)/beta
        diffvar = np.diag(restricted)+restricted[0, 0]-2*restricted[0]
        r = np.arange(n)
        expected = r*(1-r/n)/(beta*stiffness)
        unpinned_errors.append(maxabs(diffvar-expected))
        assert abs(restricted[0, 0]-(n*n-1)/(12*beta*stiffness*n)) < 5e-13
        assert np.linalg.eigvalsh(stiffness*lap)[0] < 1e-13
        assert np.linalg.matrix_rank(lap, tol=1e-10) == n-1
    limit = 1/(beta*mass*omega*np.sqrt(omega**2+4*stiffness/mass))
    refinements = []
    for n in [8, 16, 32, 64]:
        theta = 2*np.pi*np.arange(n)/n
        value = np.mean(1/(omega**2+4*stiffness/mass*np.sin(theta/2)**2))/(beta*mass)
        refinements.append({"N": n, "C0": float(value), "integral_error": abs(float(value)-limit)})
    assert max(pinned_errors) < 2e-13 and max(unpinned_errors) < 1e-11
    assert refinements[-1]["integral_error"] < 1e-14
    return {"pinned_matrix_fourier_max_error": max(pinned_errors),
            "constrained_unpinned_max_error": max(unpinned_errors),
            "zero_mode_detected": True, "C0_limit": float(limit), "refinements": refinements}


def limit_checks():
    k, c = 1., 1.4
    fixed_t, s = 2., math.pi
    rows = []
    for n in [32, 64, 128, 256]:
        a = 2*np.pi/n
        wa = 2*c/a*np.sin(k*a/2)
        delta = c*k-wa
        t_scaled = 24*s/(c*k**3*a*a)
        fixed_error = abs(np.exp(-1j*wa*fixed_t)-np.exp(-1j*c*k*fixed_t))
        scaled_error = 2*abs(np.sin(delta*t_scaled/2))
        bound = c*k**3*a*a*fixed_t/24
        assert fixed_error <= bound*(1+1e-12)
        rows.append({"N": n, "fixed_time_error": float(fixed_error),
                     "scaled_time": t_scaled, "scaled_time_error": float(scaled_error)})
    assert rows[-1]["scaled_time_error"] > 1.99999999
    # Same beta*gap gives the same polarization along different joint paths.
    pol = [math.tanh((2*n)*(.3/n)/2) for n in [10, 100, 1000]]
    assert max(pol)-min(pol) < 1e-15
    # Search a window around the first beating-envelope maximum; do not assume
    # the fast factor equals one at a single predetermined time.
    beating = []
    for eps in [.1, .05, .025]:
        wp, wm = math.sqrt(1+eps), math.sqrt(1-eps)
        center = math.pi/(wp-wm)
        ts = np.linspace(center-math.pi, center+math.pi, 20001)
        q2 = (np.cos(wp*ts)-np.cos(wm*ts))/2
        beating.append({"epsilon": eps, "window_center": center, "max_abs_q2": maxabs(q2)})
    assert min(x["max_abs_q2"] for x in beating) > .99
    return {"dispersion_phase": rows, "fixed_beta_gap_polarization": pol[0], "beating": beating}


def spectral_statistics_checks():
    bins = np.linspace(0, 2, 21)
    gaps = []
    for delta in (np.arange(200)+.5)/100:
        left = 2*np.arange(-30, 31)
        levels = np.sort(np.concatenate([left, left+delta]))
        interior = levels[(levels > -40) & (levels < 40)]
        gaps.extend(np.diff(interior))
    counts, _ = np.histogram(gaps, bins=bins)
    probs = counts/counts.sum()
    err = maxabs(probs-np.diff(bins)/2)
    # Finite-window imbalance of one alternating gap is permitted and reported.
    assert err < 2e-4
    fixed_levels = np.sort(np.concatenate([2*np.arange(100), 2*np.arange(100)+.4]))
    fixed_gaps = np.diff(fixed_levels)
    ratios = np.minimum(fixed_gaps[1:], fixed_gaps[:-1])/np.maximum(fixed_gaps[1:], fixed_gaps[:-1])
    assert maxabs(ratios-.25) < 5e-14
    # Deterministic Gauss quadrature independently integrates the Poisson ratio law.
    nodes, weights = np.polynomial.legendre.leggauss(48)
    r, w = (nodes+1)/2, weights/2
    norm, mean = float(np.sum(w*2/(1+r)**2)), float(np.sum(w*2*r/(1+r)**2))
    assert abs(norm-1) < 1e-14
    assert abs(mean-(2*math.log(2)-1)) < 1e-14
    return {"phase_realizations": 200, "retained_gaps": len(gaps),
            "uniform_bin_probability_max_error": err,
            "single_phase_ratio": float(np.mean(ratios)),
            "poisson_ratio_normalization": norm, "poisson_ratio_mean": mean}


def midpoint_checks():
    a = np.array([[0., 1.], [-1., 0.]])
    rows = []
    for h in [.2, .1, .05]:
        steps = round(10/h)
        m = np.linalg.solve(np.eye(2)-h*a/2, np.eye(2)+h*a/2)
        z = [np.array([1., 0.])]
        for _ in range(steps):
            z.append(m @ z[-1])
        z = np.array(z)
        drift = maxabs(np.sum(z*z, axis=1)-1)
        discrete = (z[1:]-z[:-1])/h - (z[1:]+z[:-1]) @ a.T/2
        cd = (z[2:]-z[:-2])/(2*h) - z[1:-1] @ a.T
        cdnorm = np.linalg.norm(cd, axis=1)
        freq = 2*math.atan(h/2)/h
        expected_cd = h*h/(4+h*h)
        exact = np.array([math.cos(10), -math.sin(10)])
        endpoint = float(np.linalg.norm(z[-1]-exact))
        assert drift < 2e-13 and maxabs(discrete) < 2e-14
        assert maxabs(cdnorm-expected_cd) < 2e-14
        assert abs(endpoint-2*abs(math.sin((freq-1)*5))) < 2e-13
        wrong_m = np.linalg.solve(np.eye(2)+h*a/2, np.eye(2)-h*a/2)
        wrong_z = [np.array([1., 0.])]
        for _ in range(steps):
            wrong_z.append(wrong_m @ wrong_z[-1])
        wrong_z = np.array(wrong_z)
        wrong_energy_drift = maxabs(np.sum(wrong_z**2, axis=1)-1)
        wrong_cd = (wrong_z[2:]-wrong_z[:-2])/(2*h)-wrong_z[1:-1] @ a.T
        wrong_cd_norm = float(np.mean(np.linalg.norm(wrong_cd, axis=1)))
        assert wrong_energy_drift < 2e-13 and wrong_cd_norm > 1.99
        rows.append({"h": h, "energy_drift": drift,
                     "discrete_residual_max": maxabs(discrete),
                     "centered_residual": float(np.mean(cdnorm)),
                     "frequency_error": 1-freq, "endpoint_error": endpoint,
                     "wrong_sign_continuous_residual": 1+freq,
                     "wrong_sign_centered_residual": wrong_cd_norm,
                     "wrong_sign_energy_drift": wrong_energy_drift})
    assert min(r["wrong_sign_continuous_residual"] for r in rows) > 1.99
    return {"omega": 1., "T": 10., "rows": rows}


def perturbation_checks():
    q1, p1, q2, p2 = z = sp.symbols("q1 p1 q2 p2", real=True)
    w1, w2, eps = sp.symbols("w1 w2 eps", positive=True)

    def pb(f, g):
        return sp.expand(sum(sp.diff(f,q)*sp.diff(g,p)-sp.diff(f,p)*sp.diff(g,q)
                             for q,p in [(q1,p1),(q2,p2)]))

    e1, e2 = (p1**2+w1**2*q1**2)/2, (p2**2+w2**2*q2**2)/2
    h0, v = e1+e2, q1*q2
    correction = (w1**2*q1*q2+p1*p2)/(w1**2-w2**2)
    assert sp.simplify(pb(correction,h0)+pb(e1,v)) == 0
    drift = pb(e1+eps*correction,h0+eps*v)
    expected = -eps**2*(p1*q1+p2*q2)/(w1**2-w2**2)
    assert sp.simplify(drift-expected) == 0
    bad = w1**2*q1*q2+p1*p2
    assert sp.simplify(pb(bad,h0)+pb(e1,v)) != 0
    assert pb(e1,q1**2*q2**2) == -2*p1*q1*q2**2
    rows = []
    # Actual perturbed trajectories from independent normal-mode diagonalization.
    a1, a2 = 1.3, .8
    q0, p0 = np.array([.6,-.4]), np.array([.2,.5])
    for epsilon in [.04,.02,.01]:
        K = np.array([[a1*a1,epsilon],[epsilon,a2*a2]])
        lam, R = np.linalg.eigh(K)
        om = np.sqrt(lam)
        Q0, P0 = R.T @ q0, R.T @ p0
        t = np.linspace(0,20,2001)
        Q = np.cos(t[:,None]*om)*Q0 + np.sin(t[:,None]*om)*P0/om
        P = -np.sin(t[:,None]*om)*Q0*om + np.cos(t[:,None]*om)*P0
        q, p = Q @ R.T, P @ R.T
        qdot, pdot = p, -q @ K.T
        e1dot = p[:,0]*pdot[:,0]+a1*a1*q[:,0]*qdot[:,0]
        c1dot = (a1*a1*(qdot[:,0]*q[:,1]+q[:,0]*qdot[:,1])
                 +pdot[:,0]*p[:,1]+p[:,0]*pdot[:,1])/(a1*a1-a2*a2)
        actual = e1dot+epsilon*c1dot
        theoretical = -epsilon**2*np.sum(p*q,axis=1)/(a1*a1-a2*a2)
        residual = maxabs(actual-theoretical)
        assert residual < 1e-15
        rows.append({"epsilon":epsilon,"derivative_identity_max_error":residual,
                     "max_corrected_drift_rate":maxabs(actual),
                     "drift_rate_over_epsilon_squared":maxabs(actual)/epsilon**2})
    # Deterministic grid on a positive-energy domain for the quartic bound.
    ratios=[]
    epsilon=.12
    for zz in itertools.product([-.9,-.3,.2,.8],repeat=4):
        a,b,c,d=zz
        energy=(b*b+a1*a1*a*a+d*d+a2*a2*c*c)/2+epsilon*a*a*c*c
        rate=abs(-2*epsilon*b*a*c*c)
        bound=4*epsilon*energy**2/(a1*a2*a2)
        ratios.append(rate/bound)
    assert max(ratios) <= 1
    return {"symbolic_residuals":0,"wrong_denominator_detected":True,
            "normal_mode_checks":rows,"quartic_bound_max_fraction":max(ratios)}


if __name__ == "__main__":
    report = {"weyl":weyl_checks(), "rank_and_brackets":bracket_checks(),
              "variable_tension":lattice_checks(), "covariances":covariance_checks(),
              "nonuniform_limits":limit_checks(), "spectral_statistics":spectral_statistics_checks(),
              "midpoint":midpoint_checks(), "perturbed_charges":perturbation_checks()}
    print(json.dumps({"status":"all checks passed", "numpy":np.__version__,
                      "sympy":sp.__version__, "checks":report}, indent=2))
