#!/usr/bin/env python3
"""Independent checks for Foundations Poisson geometry and spectral examples.

Python 3 standard library only. Run:
    python3 check_geometry_spectral.py

Exact sparse polynomial arithmetic checks canonical angular momentum and
coordinate-dependent Jacobi examples. Other checks compare independent
constructions: matrix inversion vs spectral projectors; transfer matrices vs
finite-ring eigenvectors; variation of a functional vs its bulk derivative;
Jost ODE residuals vs finite differences; and bound-state norm quadrature.

The numerical checks specify grids and tolerances. They are finite checks of
the worked examples, not analytic PDE or inverse-scattering theorems.
"""
from fractions import Fraction as Q
import cmath
import math

NVAR = 6
ZERO = (0,) * NVAR
checks = 0


def check(condition, message):
    global checks
    if not condition:
        raise AssertionError(message)
    checks += 1


def poly(terms):
    return {k: Q(v) for k, v in terms.items() if v}


def constant(a):
    return poly({ZERO: a})


def var(i):
    p = list(ZERO)
    p[i] = 1
    return {tuple(p): Q(1)}


def add(*ps):
    out = {}
    for p in ps:
        for k, v in p.items():
            out[k] = out.get(k, Q(0)) + v
    return poly(out)


def scale(p, a):
    return poly({k: a * v for k, v in p.items()})


def mul(p, q):
    out = {}
    for a, x in p.items():
        for b, y in q.items():
            k = tuple(i+j for i, j in zip(a, b))
            out[k] = out.get(k, Q(0)) + x*y
    return poly(out)


def deriv(p, i):
    out = {}
    for a, x in p.items():
        if a[i]:
            b = list(a)
            b[i] -= 1
            out[tuple(b)] = x * a[i]
    return poly(out)


def bracket(f, g, tensor):
    return add(*(mul(mul(deriv(f, i), p), deriv(g, j))
                 for (i, j), p in tensor.items()))


def tensor_from_pairs(pairs):
    out = {}
    for i, j, p in pairs:
        out[i, j] = p
        out[j, i] = scale(p, -1)
    return out


x, y, z, px, py, pz = [var(i) for i in range(6)]
one = constant(1)
bad = tensor_from_pairs([(0, 1, one), (1, 2, y)])
jac = add(bracket(x, bracket(y, z, bad), bad),
          bracket(y, bracket(z, x, bad), bad),
          bracket(z, bracket(x, y, bad), bad))
check(jac == one, "Invalid variable bracket must have Jacobiator one")
fixed = tensor_from_pairs([(0, 1, one), (1, 2, x)])
casimir = add(z, scale(mul(x, x), Q(1, 2)))
check(all(bracket(casimir, v, fixed) == {} for v in (x, y, z)),
      "Repaired bracket Casimir")
canonical = tensor_from_pairs([(i, i+3, one) for i in range(3)])
L = [add(mul(y, pz), scale(mul(z, py), -1)),
     add(mul(z, px), scale(mul(x, pz), -1)),
     add(mul(x, py), scale(mul(y, px), -1))]
for i in range(3):
    check(bracket(L[i], L[(i+1) % 3], canonical) == L[(i+2) % 3],
          "Angular momentum component bracket")
spin = tensor_from_pairs([(0, 1, z), (1, 2, x), (2, 0, y)])
C = scale(add(mul(x, x), mul(y, y), mul(z, z)), Q(1, 2))
check(all(bracket(C, v, spin) == {} for v in (x, y, z)),
      "Spin Casimir against every coordinate")
print("Exact polynomial checks: invalid Jacobiator = 1; repaired Casimir;"
      " all 3 angular-momentum brackets; spin Casimir: PASS")

# Symplectic orientation: inverse map (phi,I) -> (q,p).
phi, action = 0.7, 1.3
r = math.sqrt(2*action)
det = (-r*math.sin(phi))*(-math.sin(phi)/r) - (
    math.cos(phi)/r)*(-r*math.cos(phi))
check(abs(det-1) < 1e-14, "Canonical polar orientation")
# Counterclockwise theta with p=+r sin(theta) has the opposite Jacobian.
ccw_det = (-r*math.sin(phi))*(math.sin(phi)/r) - (
    math.cos(phi)/r)*(r*math.cos(phi))
check(abs(ccw_det+1) < 1e-14, "Counterclockwise polar angle is not canonical")
print("Polar pullbacks: canonical det = +1; counterclockwise det = -1: PASS")


def integrate_periodic(f, n=512):
    return (2*math.pi/n)*sum(f(2*math.pi*j/n) for j in range(n))


def field_h(eps):
    def density(x):
        u = math.cos(x) + eps*(math.sin(2*x)+0.3*math.cos(x))
        ux = -math.sin(x) + eps*(2*math.cos(2*x)-0.3*math.sin(x))
        return 0.5*(2+math.sin(x))*ux*ux + 0.25*u**4
    return integrate_periodic(density)


variation_exact = integrate_periodic(
    lambda x: (2*math.cos(x)+2*math.sin(x)*math.cos(x)+math.cos(x)**3)
    * (math.sin(2*x)+0.3*math.cos(x)))
eps = 1e-5
variation_fd = (field_h(eps)-field_h(-eps))/(2*eps)
check(abs(variation_exact-1.825*math.pi) < 1e-12, "Variation closed integral")
check(abs(variation_fd-variation_exact) < 2e-8, "Functional variation finite difference")
wrong_variation = integrate_periodic(
    lambda x: ((2+math.sin(x))*math.cos(x)+math.cos(x)**3)
    * (math.sin(2*x)+0.3*math.cos(x)))
check(abs(variation_exact-wrong_variation-math.pi/2) < 1e-12,
      "Negative control: omitting coefficient derivative")
naive_self = integrate_periodic(
    lambda x: (1+math.cos(x))*(2+math.sin(x))*(-math.sin(x)))
corrected_self = naive_self + integrate_periodic(
    lambda x: 0.5*math.cos(x)*(1+math.cos(x))**2)
check(abs(naive_self+math.pi) < 1e-12, "Naive a*d/dx self bracket is -pi")
check(abs(corrected_self) < 1e-12, "Corrected variable operator skewness")
print(f"Field variation: analytic={variation_exact:.12f}, "
      f"central difference error={abs(variation_fd-variation_exact):.3e}"
      f" (epsilon={eps:g}, 512-point periodic quadrature)")
print(f"Variable-operator negative control={naive_self:.12f}; "
      f"corrected self bracket={corrected_self:.3e}")

# Robin state checks compare bulk integral, boundary contribution, energy norm.
kappa, ell = 0.8, 1.7
norm2 = (1-math.exp(-2*kappa*ell))/(2*kappa)
kinetic = kappa*kappa*norm2
boundary = -kappa+kappa*math.exp(-2*kappa*ell)
check(abs(kinetic+boundary+kappa*kappa*norm2) < 1e-14,
      "Negative Robin eigenvalue quadratic form")
# Free interval T12 at k=0 is ell, not zero.
check(ell != 0, "Zero free Dirichlet mode rejected")
print(f"Robin quadratic form={kinetic+boundary:.12f}; "
      f"(-kappa^2)*norm^2={-kappa*kappa*norm2:.12f}: PASS")

# Resolvent inversion compared with independently normalized eigenvectors.
sqrt2 = math.sqrt(2)
lam = [1-sqrt2, 1+sqrt2]
weights = [1/(1+t*t) for t in lam]
for z0 in [0.3+0.8j, -3+0.2j, 2.3+1.5j]:
    m_inverse = (2-z0)/(z0*z0-2*z0-1)
    m_spectral = sum(w/(t-z0) for t, w in zip(lam, weights))
    check(abs(m_inverse-m_spectral) < 2e-14, "Two-site resolvent/projectors")
    check(m_inverse.imag > 0, "Herglotz sign")
for power, moment in enumerate([1, 0, 1, 2]):
    check(abs(sum(w*t**power for t, w in zip(lam, weights))-moment) < 1e-13,
          "Two-site spectral moments")
# Direct Green kernel derivatives at x=y.
k, ell, y0 = 0.7, 1.6, 0.61
left_derivative = math.cos(k*y0)*math.sin(k*(ell-y0))/math.sin(k*ell)
right_derivative = -math.sin(k*y0)*math.cos(k*(ell-y0))/math.sin(k*ell)
check(abs(right_derivative-left_derivative+1) < 1e-14,
      "Dirichlet Green kernel derivative jump")
print("Resolvent: direct inverse vs normalized eigenvectors, four moments,"
      " upper-half-plane sign; Green derivative jump=-1: PASS")


def matmul(a, b):
    return [[sum(a[i][k]*b[k][j] for k in range(len(b)))
             for j in range(len(b[0]))] for i in range(len(a))]


def subtract(a, b):
    return [[x-y for x, y in zip(ar, br)] for ar, br in zip(a, b)]


def maxnorm(a):
    return max(abs(x) for row in a for x in row)


# Shear matrix Lax check with genuinely nonzero lambda and t.
ll, tt = 0.4+0.3j, 0.8
B = [[0, 1], [0, 0]]
L = [[ll+tt, 1-2*ll*tt-tt*tt], [1, -ll-tt]]
commutator = subtract(matmul(B, L), matmul(L, B))
Ldot = [[1, -2*(ll+tt)], [0, -1]]
check(maxnorm(subtract(commutator, Ldot)) < 1e-14, "Shear Lax equation")
check(maxnorm(subtract(matmul(L, L), [[ll*ll+1, 0], [0, ll*ll+1]])) < 1e-14,
      "Shear characteristic relation")
check(maxnorm(Ldot) > 1, "Negative control omitting time matrix")
print("Shear Lax equation and squared-matrix identity: PASS")

# Period-two transfer discriminant, independently checked against a finite ring.
m, cells, beta = 0.8, 5, 0.7
ring_residual = 0.0
for j in range(cells):
    theta = (2*math.pi*j+beta)/cells
    for sign in [-1, 1]:
        energy = sign*math.sqrt(m*m+2+2*math.cos(theta))
        transfer = matmul([[energy+m, -1], [1, 0]],
                          [[energy-m, -1], [1, 0]])
        check(abs(transfer[0][0]+transfer[1][1]-2*math.cos(theta)) < 2e-14,
              "Period-two discriminant")
        amp = (energy-m)/(1+cmath.exp(-1j*theta))
        def wave(n):
            cell, parity = divmod(n, 2)
            return cmath.exp(1j*cell*theta)*(1 if parity == 0 else amp)
        norm = math.sqrt(sum(abs(wave(n))**2 for n in range(2*cells)))
        for n in range(2*cells):
            lhs = wave(n+1)+wave(n-1)+(-1)**n*m*wave(n)
            ring_residual = max(ring_residual, abs(lhs-energy*wave(n))/norm)
        check(abs(wave(2*cells)-cmath.exp(1j*beta)*wave(0)) < 1e-13,
              "Finite ring total twist")
check(ring_residual < 1e-13, "Finite-ring eigenvector residual")
check(abs(math.sqrt(m*m)-abs(m)) < 1e-14, "Band inner endpoints")
print(f"Floquet: transfer vs all 10 twisted-ring eigenvectors, "
      f"N={cells}, m={m}, beta={beta}; max normalized residual={ring_residual:.3e}")

# A chosen end-site energy selects one decaying multiplier of the gapped bulk.
rho = (math.sqrt(5) - 3) / 2
odd_amplitude = 1 + rho
state = [amplitude * rho**j for j in range(40) for amplitude in (1, odd_amplitude)]
end_potential = -odd_amplitude
check(abs(end_potential * state[0] + state[1]) < 1e-14, "Gap-state boundary equation")
check(abs(state[0] + state[1]) > 1, "Bulk end potential rejects gap state")
for i in range(1, len(state)-1):
    check(abs(state[i-1] + (-1)**i * state[i] + state[i+1]) < 1e-14,
          "Gap-state bulk recurrence")
tail = sum(x*x for x in state[8:]) / sum(x*x for x in state)
check(abs(tail - rho**8) < 1e-16, "Four-cell right-tail probability")
print(f"Half-line gap state: end potential {end_potential:.9f}, four-cell tail {tail:.9f}")

# Reflectionless Jost check: ODE residual evaluated via independent finite differences.
kappa, center, k = 0.9, 0.4, 0.7
def potential(x):
    return -2*kappa*kappa/math.cosh(kappa*(x-center))**2


def jost(x):
    return cmath.exp(1j*k*x)*(k+1j*kappa*math.tanh(kappa*(x-center)))/(k+1j*kappa)


grid = [-5+10*j/200 for j in range(201)]
residuals = []
for h in [0.02, 0.01, 0.005]:
    residual = max(abs(-(jost(x+h)-2*jost(x)+jost(x-h))/(h*h)
                       +(potential(x)-k*k)*jost(x)) for x in grid)
    residuals.append(residual)
check(residuals[-1] < 2e-5, "Jost finite-difference ODE residual")
check(3.8 < residuals[0]/residuals[1] < 4.2
      and 3.8 < residuals[1]/residuals[2] < 4.2,
      "Jost residual second-order refinement")
transmission = (k+1j*kappa)/(k-1j*kappa)
check(abs(abs(transmission)**2-1) < 1e-14, "Reflectionless flux")


def simpson(f, a, b, n=4000):
    assert n % 2 == 0
    h = (b-a)/n
    return (h/3)*(f(a)+f(b)+4*sum(f(a+h*j) for j in range(1, n, 2))
                  +2*sum(f(a+h*j) for j in range(2, n, 2)))


def bound_jost(x):
    return 0.5*math.exp(-kappa*center)/math.cosh(kappa*(x-center))


extent = 14/kappa
numerical_norm = simpson(lambda x: bound_jost(x)**2, center-extent, center+extent)
exact_norm = math.exp(-2*kappa*center)/(2*kappa)
relative_norm_error = abs(numerical_norm/exact_norm-1)
check(relative_norm_error < 2e-11, "Jost bound-state normalization")
norming_c = 1/exact_norm
check(abs(math.log(norming_c/(2*kappa))/(2*kappa)-center) < 1e-14,
      "Location reconstructed from squared norming coefficient")
print("Jost ODE max residuals on 201 points in [-5,5], h=.02,.01,.005:",
      ", ".join(f"{x:.6e}" for x in residuals))
print(f"Bound-state norm: Simpson 4000 panels, |x-x0|<=14/kappa;"
      f" relative error={relative_norm_error:.3e}; position reconstruction: PASS")
print(f"ALL {checks} CHECKS PASSED")
