#!/usr/bin/env python3
"""Independent finite-matrix and quadrature checks for Foundations chapters 5–6.

Run: python3 check_algebra_complex.py
Dependencies: NumPy, SymPy, mpmath. No files are modified.
Matrix residuals use the Frobenius norm unless explicitly called operator norm.
Quadratures are recomputed at 35 and 50 decimal digits. These checks verify the
displayed examples; they do not prove functional-analytic or asymptotic theorems.
"""

import cmath
import itertools
import math

import mpmath as mp
import numpy as np
import sympy as sp


def near(name, actual, expected, tol=2e-12):
    error = np.linalg.norm(np.asarray(actual) - np.asarray(expected))
    assert error < tol, (name, error)
    print(f"{name}: residual {error:.3e}")


def swap(n, first, second, graded=False):
    out = np.zeros((2**n, 2**n), dtype=complex)
    for state in itertools.product(range(2), repeat=n):
        moved = list(state)
        moved[first], moved[second] = moved[second], moved[first]
        source = sum(v << (n-j-1) for j, v in enumerate(state))
        target = sum(v << (n-j-1) for j, v in enumerate(moved))
        # Only the adjacent two-factor graded swap is used below.
        out[target, source] = (-1)**(state[first]*state[second]) if graded else 1
    return out


def ptrace_first(a, dim, rest):
    return np.trace(a.reshape(dim, rest, dim, rest), axis1=0, axis2=2)


def commutant_dimension(generators):
    n = len(generators[0])
    system = np.vstack([
        np.kron(np.eye(n), a) - np.kron(a.T, np.eye(n))
        for a in generators
    ])
    singular = np.linalg.svd(system, compute_uv=False)
    return n*n - int(np.count_nonzero(singular > 1e-11))


def matrices():
    eye = np.eye(2)
    x = np.array([[0, 1], [1, 0]], dtype=complex)
    y = np.array([[0, -1j], [1j, 0]])
    z = np.diag([1, -1])
    spin = [x/2, y/2, z/2]
    dims = [commutant_dimension(spin),
            commutant_dimension([np.kron(eye, s) for s in spin])]
    assert dims == [1, 4]
    print(f"single spin / repeated spin commutant dimensions: {dims}")
    near("invariant multiplicity commutator",
         np.kron(x, eye) @ np.kron(z, eye) - np.kron(z, eye) @ np.kron(x, eye),
         -2j*np.kron(y, eye))
    p = swap(2, 0, 1)
    p12, p13, p23 = (swap(3, a, b) for a, b in [(0, 1), (0, 2), (1, 2)])
    near("three-leg braid", p12@p23@p12, p13)
    near("three-leg partial trace", ptrace_first(p12@p13, 2, 4), p)
    a = np.array([[1, 2j], [3, 4]])
    b = np.array([[0, 2], [-1j, 5]])
    near("swap trace order BA", ptrace_first(np.kron(a, b)@p, 2, 2), b@a)
    defect = ptrace_first(np.kron(eye, x)@np.kron(eye, z)
                         - np.kron(eye, z)@np.kron(eye, x), 2, 2)
    near("partial trace cyclicity defect", defect, -4j*y)
    assert np.linalg.norm(defect) > 5
    c = np.array([[0, 1], [0, 0]], dtype=complex)
    c1, c2 = np.kron(c, eye), np.kron(z, c)
    near("fermion anticommutator", c1@c2+c2@c1, np.zeros((4, 4)))
    near("fermion canonical anticommutator", c2@c2.conj().T+c2.conj().T@c2, np.eye(4))
    pg = swap(2, 0, 1, graded=True)
    near("fermionic swap action", pg@c1@pg, c2)
    near("ordinary trace of graded swap", ptrace_first(pg, 2, 2), z)
    near("supertrace of graded swap", ptrace_first(np.kron(z, eye)@pg, 2, 2), eye)
    near("odd tensor square", np.linalg.matrix_power(np.kron(x@z, x), 2), -np.eye(4))
    wrong = np.kron(eye, c)
    print(f"missing parity string negative control: anticommutator norm {np.linalg.norm(c1@wrong+wrong@c1):.3f}")
    assert np.linalg.norm(c1@wrong+wrong@c1) > 1


def continuation():
    for winding in [-1, 1, 2]:
        angles = np.linspace(0, 2*math.pi*winding, 401)
        points = np.exp(1j*angles)
        increments = [cmath.log(b/a) for a, b in zip(points[:-1], points[1:])]
        log_return = sum(increments)
        root_return = math.prod(cmath.exp(d/2) for d in increments)
        near(f"log continuation winding {winding}", log_return, 2j*math.pi*winding)
        near(f"root continuation winding {winding}", root_return, (-1)**winding)
    n = sp.Matrix([[0, 1], [0, 0]])
    monodromy = sp.eye(2)+2*sp.pi*sp.I*n
    assert monodromy**3 == sp.eye(2)+6*sp.pi*sp.I*n
    print("logarithmic monodromy cube: exact symbolic equality")


def contour(n):
    theta = 2*np.pi*np.arange(n)/n
    s = np.exp(1j*theta)
    integral = 2*np.pi*np.mean(1j*s/((s-.5)*(s-2)))
    errors = [abs(integral+4j*np.pi/3)]
    for point in [.3+.2j, 1.7+.2j]:
        value = np.mean((s+2/s)*s/(s-point))
        expected = point if abs(point) < 1 else -2/point
        errors.append(abs(value-expected))
    return max(errors)


def analytic_checks(dps):
    mp.mp.dps = dps
    overlap = mp.quad(lambda t: mp.exp(mp.j*mp.pi*t), [0, 1])
    assert abs(overlap-2j/mp.pi) < mp.mpf(10)**(-dps+4)
    c = abs(overlap)
    projection_defect = c*mp.sqrt(1-c*c)
    # Continuum Fourier overlap determines the exact two-projection witness.
    print(f"dps={dps}: momentum spectral-projection commutator operator norm {mp.nstr(projection_defect, 16)}")
    elliptic_errors = []
    modular_errors = []
    for m in map(mp.mpf, ['0.2', '0.5', '0.8']):
        a = 2*mp.quad(lambda l: 1/mp.sqrt(l*(1-l)*(m-l)), [0, m/2, m])
        b = 2j*mp.quad(lambda l: 1/mp.sqrt(l*(1-l)*(l-m)), [m, (m+1)/2, 1])
        aa = 4*mp.quad(lambda t: 1/mp.sqrt(1-m*mp.sin(t)**2), [0, mp.pi/2])
        bb = 4j*mp.quad(lambda t: 1/mp.sqrt(1-(1-m)*mp.sin(t)**2), [0, mp.pi/2])
        elliptic_errors += [abs(a-aa), abs(b-bb)]
        tau = bb/aa
        transformed = tau/(1+tau)
        modular_errors.append(abs(mp.im(transformed)-mp.im(tau)/abs(1+tau)**2))
    assert max(elliptic_errors) < mp.mpf(10)**(-dps/2+2)
    print(f"dps={dps}: endpoint vs smooth elliptic quadrature max error {mp.nstr(max(elliptic_errors), 8)}")
    assert max(modular_errors) < mp.mpf(10)**(-dps+4)
    airy_errors = []
    ray = mp.exp(mp.j*mp.pi/3)
    for eta in map(mp.mpf, [-2, 0, 1, 3]):
        # DLMF 9.5.4 on its two decaying rays, independent of mp.airyai.
        integral = mp.quad(lambda r: mp.im(ray*mp.exp(-r**3/3+eta*r*ray)),
                           [0, 1, 2, 4, mp.inf])/mp.pi
        airy_errors.append(abs(integral-mp.airyai(-eta)))
    assert max(airy_errors) < mp.mpf(10)**(-dps+8)
    print(f"dps={dps}: decaying-contour vs Airy function max error {mp.nstr(max(airy_errors), 8)}")
    return max(elliptic_errors), max(airy_errors)


def asymptotic_checks():
    mp.mp.dps = 50
    for t in [20, 40, 80, 160]:
        t = mp.mpf(t)
        exact = mp.sqrt(mp.pi)/mp.sqrt(1-1j*t/2)
        leading = mp.sqrt(2*mp.pi/t)*mp.exp(mp.j*mp.pi/4)
        relative = exact/leading
        e1 = t*abs(relative-1)
        e2 = t*t*abs(relative-1+1j/t)
        print(f"Gaussian T={int(t)}: scaled errors {mp.nstr(e1, 10)}, {mp.nstr(e2, 10)}")
    assert abs(e1-1) < mp.mpf('.001')
    assert abs(e2-mp.mpf('1.5')) < mp.mpf('.001')
    # Fixed eta=1 means s=T^(-2/3): compare envelope-scaled errors,
    # which do not improve with T along this path.
    eta = mp.mpf(1)
    exact_scaled = 2*mp.pi*mp.airyai(-eta)
    separate_scaled = 2*mp.sqrt(mp.pi)*eta**(-mp.mpf(1)/4)*mp.cos(2*eta**mp.mpf('1.5')/3-mp.pi/4)
    defect = abs(exact_scaled-separate_scaled)
    print(f"coalescing-saddle negative control, eta=1 scaled absolute error: {mp.nstr(defect, 12)}")
    assert defect > mp.mpf('.1')


def divisors():
    z, s, m = sp.symbols('z s m', positive=True)
    # Regular coordinates lambda=z^2 at p0 and lambda=s^-2 at infinity.
    omega_zero = 2/sp.sqrt((z*z-1)*(z*z-m))
    omega_infinity = -2/sp.sqrt((1-s*s)*(1-m*s*s))
    assert sp.limit(omega_zero, z, 0) == 2/sp.sqrt(m)
    assert sp.limit(omega_infinity, s, 0) == -2
    assert sp.diff(s**-2, s) == -2/s**3
    print("elliptic divisor orders: lambda=(2,-2), mu=(1,1,1,-3), d lambda/mu has order 0 at all four marked points")


if __name__ == '__main__':
    matrices()
    continuation()
    for n in [64, 128]:
        error = contour(n)
        assert error < 2e-12
        print(f"N={n}: residue and Cauchy-transform trapezoidal max error {error:.3e}")
    low = analytic_checks(35)
    high = analytic_checks(50)
    assert high[0] < low[0]
    divisors()
    asymptotic_checks()
    print("PASS: all finite examples and numerical refinement checks")
